hash
stringlengths
40
40
date
stringdate
2022-11-17 13:04:47
2025-03-21 17:04:41
author
stringclasses
141 values
commit_message
stringlengths
22
166
is_merge
bool
1 class
git_diff
stringlengths
238
9.63M
type
stringclasses
17 values
masked_commit_message
stringlengths
6
143
9bf16b1a0787f9badb4a6decd38e3e5d69a3ea51
2024-04-22 05:33:20
github-actions
chore(version): 2024.04.22.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 089e3dfe43e..c5b2e7da631 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,23 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.04.22.0 + +### Features + +- **payment_methods:** Client secret implementation in payment method… ([#4134](https://github.com/juspay/hyperswitch/pull/4134)) ([`4330781`](https://github.com/juspay/hyperswitch/commit/43307815e0200caf2e9517ec1374d09696356fbc)) +- **router:** [BOA/CYBS] add avs_response and cvv validation result in the response ([#4376](https://github.com/juspay/hyperswitch/pull/4376)) ([`e458e49`](https://github.com/juspay/hyperswitch/commit/e458e4907e39961f386900f21382c9ace3b7c392)) + +### Bug Fixes + +- **connectors:** Mask fields for webhook_resource_object ([#4400](https://github.com/juspay/hyperswitch/pull/4400)) ([`110bf22`](https://github.com/juspay/hyperswitch/commit/110bf22511cf4994c7325fb105fee60f910c1210)) +- **core:** Fix 3DS mandates, for the connector _mandate_details to be stored in the payment_methods table ([#4323](https://github.com/juspay/hyperswitch/pull/4323)) ([`f4e5784`](https://github.com/juspay/hyperswitch/commit/f4e5784f6ce57b4a205c164889242bfa1bc1fde2)) +- **user:** Add onboarding_survey enum in dashboard metadata type ([#4353](https://github.com/juspay/hyperswitch/pull/4353)) ([`f6fccaf`](https://github.com/juspay/hyperswitch/commit/f6fccafb3d43ce4b2865cf4b3cba7ad8a9619e5b)) + +**Full Changelog:** [`2024.04.19.0...2024.04.22.0`](https://github.com/juspay/hyperswitch/compare/2024.04.19.0...2024.04.22.0) + +- - - + ## 2024.04.19.0 ### Features
chore
2024.04.22.0
6b7ada1a34450ea3a7fc019375ba462a14ddd6ab
2023-11-29 20:35:33
Sakil Mostak
fix(core): Error message on Refund update for `Not Implemented` Case (#3011)
false
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 33435bb0ad9..c43c00b7259 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -211,7 +211,10 @@ pub async fn trigger_refund_to_gateway( errors::ConnectorError::NotImplemented(message) => { Some(storage::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::Failure), - refund_error_message: Some(message.to_string()), + refund_error_message: Some( + errors::ConnectorError::NotImplemented(message.to_owned()) + .to_string(), + ), refund_error_code: Some("NOT_IMPLEMENTED".to_string()), updated_by: storage_scheme.to_string(), })
fix
Error message on Refund update for `Not Implemented` Case (#3011)
d17d2fe075bee35c3449bfb7db356df83f49a045
2024-12-05 20:11:40
Sanchith Hegde
chore: enable `clippy::trivially_copy_pass_by_ref` lint and address it (#6724)
false
diff --git a/Cargo.toml b/Cargo.toml index 38d895d767a..dc60c64f667 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,6 +35,7 @@ panicking_unwrap = "warn" print_stderr = "warn" print_stdout = "warn" todo = "warn" +trivially_copy_pass_by_ref = "warn" unimplemented = "warn" unnecessary_self_imports = "warn" unreachable = "warn" diff --git a/crates/analytics/src/api_event/core.rs b/crates/analytics/src/api_event/core.rs index 305de7e69c8..425d1476a47 100644 --- a/crates/analytics/src/api_event/core.rs +++ b/crates/analytics/src/api_event/core.rs @@ -118,7 +118,7 @@ pub async fn get_api_event_metrics( &req.group_by_names.clone(), &merchant_id_scoped, &req.filters, - &req.time_series.map(|t| t.granularity), + req.time_series.map(|t| t.granularity), &req.time_range, ) .await diff --git a/crates/analytics/src/api_event/metrics.rs b/crates/analytics/src/api_event/metrics.rs index ac29ec15169..ad49f5d0ccd 100644 --- a/crates/analytics/src/api_event/metrics.rs +++ b/crates/analytics/src/api_event/metrics.rs @@ -45,7 +45,7 @@ where dimensions: &[ApiEventDimensions], merchant_id: &common_utils::id_type::MerchantId, filters: &ApiEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>>; @@ -66,7 +66,7 @@ where dimensions: &[ApiEventDimensions], merchant_id: &common_utils::id_type::MerchantId, filters: &ApiEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { diff --git a/crates/analytics/src/api_event/metrics/api_count.rs b/crates/analytics/src/api_event/metrics/api_count.rs index f00c01bbf38..85f6cac01ce 100644 --- a/crates/analytics/src/api_event/metrics/api_count.rs +++ b/crates/analytics/src/api_event/metrics/api_count.rs @@ -32,7 +32,7 @@ where _dimensions: &[ApiEventDimensions], merchant_id: &common_utils::id_type::MerchantId, filters: &ApiEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { @@ -62,7 +62,7 @@ where alias: Some("end_bucket"), }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/api_event/metrics/latency.rs b/crates/analytics/src/api_event/metrics/latency.rs index 5d71da2a0aa..03c1a226e44 100644 --- a/crates/analytics/src/api_event/metrics/latency.rs +++ b/crates/analytics/src/api_event/metrics/latency.rs @@ -35,7 +35,7 @@ where _dimensions: &[ApiEventDimensions], merchant_id: &common_utils::id_type::MerchantId, filters: &ApiEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { @@ -67,7 +67,7 @@ where alias: Some("end_bucket"), }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/api_event/metrics/status_code_count.rs b/crates/analytics/src/api_event/metrics/status_code_count.rs index b4fff367b62..f67d3d73e59 100644 --- a/crates/analytics/src/api_event/metrics/status_code_count.rs +++ b/crates/analytics/src/api_event/metrics/status_code_count.rs @@ -32,7 +32,7 @@ where _dimensions: &[ApiEventDimensions], merchant_id: &common_utils::id_type::MerchantId, filters: &ApiEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { @@ -68,7 +68,7 @@ where alias: Some("end_bucket"), }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs index 250dc07fee7..3fd134bc498 100644 --- a/crates/analytics/src/auth_events/core.rs +++ b/crates/analytics/src/auth_events/core.rs @@ -38,7 +38,7 @@ pub async fn get_metrics( &metric_type, &merchant_id_scoped, &publishable_key_scoped, - &req.time_series.map(|t| t.granularity), + req.time_series.map(|t| t.granularity), &req.time_range, ) .await diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs index da5bf6309fe..4a1fbd0e147 100644 --- a/crates/analytics/src/auth_events/metrics.rs +++ b/crates/analytics/src/auth_events/metrics.rs @@ -46,7 +46,7 @@ where &self, merchant_id: &common_utils::id_type::MerchantId, publishable_key: &str, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>>; @@ -66,7 +66,7 @@ where &self, merchant_id: &common_utils::id_type::MerchantId, publishable_key: &str, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs index 4fee15e2afd..5faeefec686 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs @@ -31,7 +31,7 @@ where &self, _merchant_id: &common_utils::id_type::MerchantId, publishable_key: &str, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { @@ -45,7 +45,7 @@ where }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs index 06de7a694fc..663473c2d89 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs @@ -31,7 +31,7 @@ where &self, _merchant_id: &common_utils::id_type::MerchantId, publishable_key: &str, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { @@ -45,7 +45,7 @@ where }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs index 2f744f15e90..15cd86e5cc8 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs @@ -31,7 +31,7 @@ where &self, merchant_id: &common_utils::id_type::MerchantId, _publishable_key: &str, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { @@ -45,7 +45,7 @@ where }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs index 551810d8e5a..61b10e6fb9e 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs @@ -31,7 +31,7 @@ where &self, _merchant_id: &common_utils::id_type::MerchantId, publishable_key: &str, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { @@ -45,7 +45,7 @@ where }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs index c6c7d1cda08..c5bf7bf81ce 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs @@ -31,7 +31,7 @@ where &self, merchant_id: &common_utils::id_type::MerchantId, _publishable_key: &str, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { @@ -45,7 +45,7 @@ where }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs index 69b4eeba4a6..c08cc511e16 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs @@ -31,7 +31,7 @@ where &self, _merchant_id: &common_utils::id_type::MerchantId, publishable_key: &str, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { @@ -45,7 +45,7 @@ where }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs index 6ea26a90979..b310567c9db 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs @@ -31,7 +31,7 @@ where &self, merchant_id: &common_utils::id_type::MerchantId, _publishable_key: &str, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { @@ -45,7 +45,7 @@ where }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; diff --git a/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs b/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs index ca67400a9b2..4ce10c9aad3 100644 --- a/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs +++ b/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs @@ -31,7 +31,7 @@ where &self, _merchant_id: &common_utils::id_type::MerchantId, publishable_key: &str, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { @@ -45,7 +45,7 @@ where }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; diff --git a/crates/analytics/src/disputes/core.rs b/crates/analytics/src/disputes/core.rs index 85d1a62a1d9..f4235518b2d 100644 --- a/crates/analytics/src/disputes/core.rs +++ b/crates/analytics/src/disputes/core.rs @@ -54,7 +54,7 @@ pub async fn get_metrics( &req.group_by_names.clone(), &auth_scoped, &req.filters, - &req.time_series.map(|t| t.granularity), + req.time_series.map(|t| t.granularity), &req.time_range, ) .await diff --git a/crates/analytics/src/disputes/metrics.rs b/crates/analytics/src/disputes/metrics.rs index ad7ed81aaee..6514e5fcbe0 100644 --- a/crates/analytics/src/disputes/metrics.rs +++ b/crates/analytics/src/disputes/metrics.rs @@ -52,7 +52,7 @@ where dimensions: &[DisputeDimensions], auth: &AuthInfo, filters: &DisputeFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>; @@ -73,7 +73,7 @@ where dimensions: &[DisputeDimensions], auth: &AuthInfo, filters: &DisputeFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> { diff --git a/crates/analytics/src/disputes/metrics/dispute_status_metric.rs b/crates/analytics/src/disputes/metrics/dispute_status_metric.rs index bbce460e475..ce962e284f6 100644 --- a/crates/analytics/src/disputes/metrics/dispute_status_metric.rs +++ b/crates/analytics/src/disputes/metrics/dispute_status_metric.rs @@ -32,7 +32,7 @@ where dimensions: &[DisputeDimensions], auth: &AuthInfo, filters: &DisputeFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> @@ -80,7 +80,7 @@ where .add_group_by_clause("dispute_status") .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; 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 index c5c0b91a173..9a7b0535819 100644 --- a/crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs +++ b/crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs @@ -32,7 +32,7 @@ where dimensions: &[DisputeDimensions], auth: &AuthInfo, filters: &DisputeFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> @@ -80,7 +80,7 @@ where .add_group_by_clause("dispute_status") .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; 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 index 0767bdaf85d..5c5eceb0619 100644 --- a/crates/analytics/src/disputes/metrics/sessionized_metrics/total_amount_disputed.rs +++ b/crates/analytics/src/disputes/metrics/sessionized_metrics/total_amount_disputed.rs @@ -32,7 +32,7 @@ where dimensions: &[DisputeDimensions], auth: &AuthInfo, filters: &DisputeFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> @@ -78,7 +78,7 @@ where query_builder.add_group_by_clause(dim).switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; 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 index f4f4d860862..d6308b09f33 100644 --- 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 @@ -32,7 +32,7 @@ where dimensions: &[DisputeDimensions], auth: &AuthInfo, filters: &DisputeFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> @@ -78,7 +78,7 @@ where query_builder.add_group_by_clause(dim).switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; diff --git a/crates/analytics/src/disputes/metrics/total_amount_disputed.rs b/crates/analytics/src/disputes/metrics/total_amount_disputed.rs index 5b9d0f54622..68c7fa6d166 100644 --- a/crates/analytics/src/disputes/metrics/total_amount_disputed.rs +++ b/crates/analytics/src/disputes/metrics/total_amount_disputed.rs @@ -32,7 +32,7 @@ where dimensions: &[DisputeDimensions], auth: &AuthInfo, filters: &DisputeFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> @@ -77,7 +77,7 @@ where query_builder.add_group_by_clause(dim).switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; diff --git a/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs b/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs index e13f3a0f530..d14d4982701 100644 --- a/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs +++ b/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs @@ -32,7 +32,7 @@ where dimensions: &[DisputeDimensions], auth: &AuthInfo, filters: &DisputeFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> @@ -77,7 +77,7 @@ where query_builder.add_group_by_clause(dim).switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; diff --git a/crates/analytics/src/frm/core.rs b/crates/analytics/src/frm/core.rs index d2b79ad2773..6f120913a7a 100644 --- a/crates/analytics/src/frm/core.rs +++ b/crates/analytics/src/frm/core.rs @@ -47,7 +47,7 @@ pub async fn get_metrics( &req.group_by_names.clone(), &merchant_id_scoped, &req.filters, - &req.time_series.map(|t| t.granularity), + req.time_series.map(|t| t.granularity), &req.time_range, ) .await diff --git a/crates/analytics/src/frm/metrics.rs b/crates/analytics/src/frm/metrics.rs index 7f5b4ea32be..b3780dfd3cb 100644 --- a/crates/analytics/src/frm/metrics.rs +++ b/crates/analytics/src/frm/metrics.rs @@ -44,7 +44,7 @@ where dimensions: &[FrmDimensions], merchant_id: &common_utils::id_type::MerchantId, filters: &FrmFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>>; @@ -65,7 +65,7 @@ where dimensions: &[FrmDimensions], merchant_id: &common_utils::id_type::MerchantId, filters: &FrmFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>> { diff --git a/crates/analytics/src/frm/metrics/frm_blocked_rate.rs b/crates/analytics/src/frm/metrics/frm_blocked_rate.rs index 7154478c026..00903cdcaef 100644 --- a/crates/analytics/src/frm/metrics/frm_blocked_rate.rs +++ b/crates/analytics/src/frm/metrics/frm_blocked_rate.rs @@ -29,7 +29,7 @@ where dimensions: &[FrmDimensions], merchant_id: &common_utils::id_type::MerchantId, filters: &FrmFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>> @@ -76,7 +76,7 @@ where query_builder.add_group_by_clause(dim).switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; diff --git a/crates/analytics/src/frm/metrics/frm_triggered_attempts.rs b/crates/analytics/src/frm/metrics/frm_triggered_attempts.rs index 168a256ffa6..dd487cdc93f 100644 --- a/crates/analytics/src/frm/metrics/frm_triggered_attempts.rs +++ b/crates/analytics/src/frm/metrics/frm_triggered_attempts.rs @@ -30,7 +30,7 @@ where dimensions: &[FrmDimensions], merchant_id: &common_utils::id_type::MerchantId, filters: &FrmFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>> { @@ -77,7 +77,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 13fdefe864d..6d694caadf5 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -116,7 +116,7 @@ impl AnalyticsProvider { dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { // Metrics to get the fetch time for each payment metric @@ -220,7 +220,7 @@ impl AnalyticsProvider { dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>> { // Metrics to get the fetch time for each payment metric @@ -330,7 +330,7 @@ impl AnalyticsProvider { dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> { @@ -435,7 +435,7 @@ impl AnalyticsProvider { dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { // Metrics to get the fetch time for each refund metric @@ -645,7 +645,7 @@ impl AnalyticsProvider { dimensions: &[FrmDimensions], merchant_id: &common_utils::id_type::MerchantId, filters: &FrmFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>> { // Metrics to get the fetch time for each refund metric @@ -745,7 +745,7 @@ impl AnalyticsProvider { dimensions: &[DisputeDimensions], auth: &AuthInfo, filters: &DisputeFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> { // Metrics to get the fetch time for each refund metric @@ -845,7 +845,7 @@ impl AnalyticsProvider { dimensions: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { match self { @@ -910,7 +910,7 @@ impl AnalyticsProvider { metric: &AuthEventMetrics, merchant_id: &common_utils::id_type::MerchantId, publishable_key: &str, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { match self { @@ -941,7 +941,7 @@ impl AnalyticsProvider { dimensions: &[ApiEventDimensions], merchant_id: &common_utils::id_type::MerchantId, filters: &ApiEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { match self { diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs index 246a0f4e8bb..e85340e49d2 100644 --- a/crates/analytics/src/opensearch.rs +++ b/crates/analytics/src/opensearch.rs @@ -497,7 +497,7 @@ impl OpenSearchQueryBuilder { Ok(()) } - pub fn get_status_field(&self, index: &SearchIndex) -> &str { + pub fn get_status_field(&self, index: SearchIndex) -> &str { match index { SearchIndex::Refunds | SearchIndex::SessionizerRefunds => "refund_status.keyword", SearchIndex::Disputes | SearchIndex::SessionizerDisputes => "dispute_status.keyword", @@ -544,7 +544,7 @@ impl OpenSearchQueryBuilder { mut payload: Value, case_insensitive_filters: &[&(String, Vec<String>)], auth_array: Vec<Value>, - index: &SearchIndex, + index: SearchIndex, ) -> Value { let mut must_array = case_insensitive_filters .iter() @@ -728,7 +728,7 @@ impl OpenSearchQueryBuilder { payload, &case_insensitive_filters, should_array.clone(), - index, + *index, ); payload }) diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs index 0b66dfda58c..80cfc563071 100644 --- a/crates/analytics/src/payment_intents/core.rs +++ b/crates/analytics/src/payment_intents/core.rs @@ -98,7 +98,7 @@ pub async fn get_metrics( &req.group_by_names.clone(), &auth_scoped, &req.filters, - &req.time_series.map(|t| t.granularity), + req.time_series.map(|t| t.granularity), &req.time_range, ) .await diff --git a/crates/analytics/src/payment_intents/metrics.rs b/crates/analytics/src/payment_intents/metrics.rs index ee3d4773e24..c063b3a7c04 100644 --- a/crates/analytics/src/payment_intents/metrics.rs +++ b/crates/analytics/src/payment_intents/metrics.rs @@ -66,7 +66,7 @@ where dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>; @@ -87,7 +87,7 @@ where dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> 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..424901ca7e4 100644 --- a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs +++ b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs @@ -35,7 +35,7 @@ where dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> @@ -82,7 +82,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") 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 696dd6a584b..d913bfe9a34 100644 --- a/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs @@ -36,7 +36,7 @@ where dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> @@ -103,7 +103,7 @@ where .attach_printable("Error grouping by currency") .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") 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 4bb9dc36b07..dda3e37d39a 100644 --- a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs +++ b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs @@ -35,7 +35,7 @@ where dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> @@ -86,7 +86,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") 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..3f0f3bc3bc8 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 @@ -35,7 +35,7 @@ where dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> @@ -82,7 +82,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") 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 0f13ff39af7..11b630a55cc 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 @@ -36,7 +36,7 @@ where dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> @@ -105,7 +105,7 @@ where .add_group_by_clause("currency") .attach_printable("Error grouping by currency") .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") 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 437b22aac71..dbb6d33e907 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 @@ -35,7 +35,7 @@ where dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> @@ -94,7 +94,7 @@ where .add_group_by_clause("first_attempt") .attach_printable("Error grouping by first_attempt") .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") 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 9716c7ce4de..178d9c1d816 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 @@ -35,7 +35,7 @@ where dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> @@ -95,7 +95,7 @@ where .attach_printable("Error grouping by first_attempt") .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") 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 c6d7c59f240..40e41253d77 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 @@ -41,7 +41,7 @@ where dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> @@ -107,7 +107,7 @@ where .add_group_by_clause("currency") .attach_printable("Error grouping by currency") .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") 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..84f6d31dfc6 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 @@ -41,7 +41,7 @@ where dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> @@ -92,7 +92,7 @@ where .attach_printable("Error grouping by dimensions") .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") 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..8cc4e75b3ba 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 @@ -38,7 +38,7 @@ where dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> @@ -87,7 +87,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding 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 f8acb2e6e9a..d51cb4cdf73 100644 --- a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs @@ -41,7 +41,7 @@ where dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> @@ -99,7 +99,7 @@ where .add_group_by_clause("currency") .attach_printable("Error grouping by currency") .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") 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..524b3ff2939 100644 --- a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs @@ -41,7 +41,7 @@ where dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> @@ -92,7 +92,7 @@ where .attach_printable("Error grouping by dimensions") .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") 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..8eb561d38d5 100644 --- a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs @@ -38,7 +38,7 @@ where dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> @@ -87,7 +87,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/payments/core.rs b/crates/analytics/src/payments/core.rs index 01a3b1abc15..c6f0276c47f 100644 --- a/crates/analytics/src/payments/core.rs +++ b/crates/analytics/src/payments/core.rs @@ -78,7 +78,7 @@ pub async fn get_metrics( &req.group_by_names.clone(), &auth_scoped, &req.filters, - &req.time_series.map(|t| t.granularity), + req.time_series.map(|t| t.granularity), &req.time_range, ) .await @@ -106,7 +106,7 @@ pub async fn get_metrics( &req.group_by_names.clone(), &auth_scoped, &req.filters, - &req.time_series.map(|t| t.granularity), + req.time_series.map(|t| t.granularity), &req.time_range, ) .await diff --git a/crates/analytics/src/payments/distribution.rs b/crates/analytics/src/payments/distribution.rs index 055572a0805..86a2f06c5f5 100644 --- a/crates/analytics/src/payments/distribution.rs +++ b/crates/analytics/src/payments/distribution.rs @@ -57,7 +57,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>>; @@ -79,7 +79,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>> { diff --git a/crates/analytics/src/payments/distribution/payment_error_message.rs b/crates/analytics/src/payments/distribution/payment_error_message.rs index de5cb3ae5e8..0a92cfbe470 100644 --- a/crates/analytics/src/payments/distribution/payment_error_message.rs +++ b/crates/analytics/src/payments/distribution/payment_error_message.rs @@ -35,7 +35,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>> { @@ -89,7 +89,7 @@ where .attach_printable("Error grouping by distribution_for") .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/payments/metrics.rs b/crates/analytics/src/payments/metrics.rs index 23b133ad035..71d2e57d7fa 100644 --- a/crates/analytics/src/payments/metrics.rs +++ b/crates/analytics/src/payments/metrics.rs @@ -68,7 +68,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>>; @@ -89,7 +89,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { diff --git a/crates/analytics/src/payments/metrics/avg_ticket_size.rs b/crates/analytics/src/payments/metrics/avg_ticket_size.rs index fc2f44cada2..10f350e30ce 100644 --- a/crates/analytics/src/payments/metrics/avg_ticket_size.rs +++ b/crates/analytics/src/payments/metrics/avg_ticket_size.rs @@ -34,7 +34,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { @@ -85,7 +85,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/payments/metrics/connector_success_rate.rs b/crates/analytics/src/payments/metrics/connector_success_rate.rs index 36783eda72a..9e6bf31fbfb 100644 --- a/crates/analytics/src/payments/metrics/connector_success_rate.rs +++ b/crates/analytics/src/payments/metrics/connector_success_rate.rs @@ -36,7 +36,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { @@ -87,7 +87,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/payments/metrics/payment_count.rs b/crates/analytics/src/payments/metrics/payment_count.rs index bd0b52d7cf8..297aef4fec5 100644 --- a/crates/analytics/src/payments/metrics/payment_count.rs +++ b/crates/analytics/src/payments/metrics/payment_count.rs @@ -33,7 +33,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { @@ -78,7 +78,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/payments/metrics/payment_processed_amount.rs b/crates/analytics/src/payments/metrics/payment_processed_amount.rs index fa54c173041..95846924665 100644 --- a/crates/analytics/src/payments/metrics/payment_processed_amount.rs +++ b/crates/analytics/src/payments/metrics/payment_processed_amount.rs @@ -34,7 +34,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { @@ -85,7 +85,7 @@ where .attach_printable("Error grouping by currency") .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/payments/metrics/payment_success_count.rs b/crates/analytics/src/payments/metrics/payment_success_count.rs index ea926761c13..843e2858977 100644 --- a/crates/analytics/src/payments/metrics/payment_success_count.rs +++ b/crates/analytics/src/payments/metrics/payment_success_count.rs @@ -34,7 +34,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { @@ -79,7 +79,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/payments/metrics/retries_count.rs b/crates/analytics/src/payments/metrics/retries_count.rs index 9695e1fe18b..ced845651cf 100644 --- a/crates/analytics/src/payments/metrics/retries_count.rs +++ b/crates/analytics/src/payments/metrics/retries_count.rs @@ -39,7 +39,7 @@ where _dimensions: &[PaymentDimensions], auth: &AuthInfo, _filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { @@ -82,7 +82,7 @@ where .attach_printable("Error filtering time range") .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/avg_ticket_size.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/avg_ticket_size.rs index b7f13667917..e29c19bda88 100644 --- a/crates/analytics/src/payments/metrics/sessionized_metrics/avg_ticket_size.rs +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/avg_ticket_size.rs @@ -34,7 +34,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { @@ -86,7 +86,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/connector_success_rate.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/connector_success_rate.rs index 66006c15a2a..d8ee7fcb473 100644 --- a/crates/analytics/src/payments/metrics/sessionized_metrics/connector_success_rate.rs +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/connector_success_rate.rs @@ -36,7 +36,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { @@ -88,7 +88,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") 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 c472c12795f..d6944d8d0bd 100644 --- a/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs @@ -37,7 +37,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { @@ -136,7 +136,7 @@ where .attach_printable("Error grouping by first_attempt") .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut outer_query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/payment_count.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_count.rs index 29d083dd232..98735b9383a 100644 --- a/crates/analytics/src/payments/metrics/sessionized_metrics/payment_count.rs +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_count.rs @@ -33,7 +33,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { @@ -79,7 +79,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") 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 a315b2fc4c8..453f988d229 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 @@ -34,7 +34,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { @@ -103,7 +103,7 @@ where .attach_printable("Error grouping by currency") .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/payment_success_count.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_success_count.rs index b307b77d5da..14391588b48 100644 --- a/crates/analytics/src/payments/metrics/sessionized_metrics/payment_success_count.rs +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_success_count.rs @@ -34,7 +34,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { @@ -80,7 +80,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/payments_distribution.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/payments_distribution.rs index e0987dd0d22..5c6a8c6adec 100644 --- a/crates/analytics/src/payments/metrics/sessionized_metrics/payments_distribution.rs +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/payments_distribution.rs @@ -33,7 +33,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { @@ -89,7 +89,7 @@ where .add_group_by_clause("first_attempt") .attach_printable("Error grouping by first_attempt") .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/retries_count.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/retries_count.rs index b79489744cc..7d81c48274b 100644 --- a/crates/analytics/src/payments/metrics/sessionized_metrics/retries_count.rs +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/retries_count.rs @@ -39,7 +39,7 @@ where _dimensions: &[PaymentDimensions], auth: &AuthInfo, _filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { @@ -82,7 +82,7 @@ where .attach_printable("Error filtering time range") .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/success_rate.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/success_rate.rs index 30e7471d608..f20308ed3b1 100644 --- a/crates/analytics/src/payments/metrics/sessionized_metrics/success_rate.rs +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/success_rate.rs @@ -33,7 +33,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { @@ -82,7 +82,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/payments/metrics/success_rate.rs b/crates/analytics/src/payments/metrics/success_rate.rs index e756115a67d..6698fe8ce65 100644 --- a/crates/analytics/src/payments/metrics/success_rate.rs +++ b/crates/analytics/src/payments/metrics/success_rate.rs @@ -33,7 +33,7 @@ where dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { @@ -81,7 +81,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index cbb0cf6737c..f449ba2f9b5 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -379,7 +379,7 @@ impl Default for Filter { impl<T: AnalyticsDataSource> ToSql<T> for Filter { fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(match self { - Self::Plain(l, op, r) => filter_type_to_sql(l, op, r), + Self::Plain(l, op, r) => filter_type_to_sql(l, *op, r), Self::NestedFilter(operator, filters) => { format!( "( {} )", @@ -536,7 +536,7 @@ pub enum FilterTypes { IsNotNull, } -pub fn filter_type_to_sql(l: &String, op: &FilterTypes, r: &String) -> String { +pub fn filter_type_to_sql(l: &str, op: FilterTypes, r: &str) -> String { match op { FilterTypes::EqualBool => format!("{l} = {r}"), FilterTypes::Equal => format!("{l} = '{r}'"), @@ -743,7 +743,7 @@ where Ok(()) } - pub fn add_granularity_in_mins(&mut self, granularity: &Granularity) -> QueryResult<()> { + pub fn add_granularity_in_mins(&mut self, granularity: Granularity) -> QueryResult<()> { let interval = match granularity { Granularity::OneMin => "1", Granularity::FiveMin => "5", @@ -814,7 +814,7 @@ where pub fn get_filter_type_clause(&self) -> Option<String> { self.having.as_ref().map(|vec| { vec.iter() - .map(|(l, op, r)| filter_type_to_sql(l, op, r)) + .map(|(l, op, r)| filter_type_to_sql(l, *op, r)) .collect::<Vec<String>>() .join(" AND ") }) diff --git a/crates/analytics/src/refunds/core.rs b/crates/analytics/src/refunds/core.rs index 205600b9259..ca72c9003a6 100644 --- a/crates/analytics/src/refunds/core.rs +++ b/crates/analytics/src/refunds/core.rs @@ -73,7 +73,7 @@ pub async fn get_metrics( &req.group_by_names.clone(), &auth_scoped, &req.filters, - &req.time_series.map(|t| t.granularity), + req.time_series.map(|t| t.granularity), &req.time_range, ) .await diff --git a/crates/analytics/src/refunds/metrics.rs b/crates/analytics/src/refunds/metrics.rs index 57e6511d92c..13990e8c2e6 100644 --- a/crates/analytics/src/refunds/metrics.rs +++ b/crates/analytics/src/refunds/metrics.rs @@ -58,7 +58,7 @@ where dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>>; @@ -79,7 +79,7 @@ where dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { diff --git a/crates/analytics/src/refunds/metrics/refund_count.rs b/crates/analytics/src/refunds/metrics/refund_count.rs index 7079993094d..ae21f166a29 100644 --- a/crates/analytics/src/refunds/metrics/refund_count.rs +++ b/crates/analytics/src/refunds/metrics/refund_count.rs @@ -33,7 +33,7 @@ where dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { @@ -78,7 +78,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") diff --git a/crates/analytics/src/refunds/metrics/refund_processed_amount.rs b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs index 3890b8be6e9..9b8c4f313d0 100644 --- a/crates/analytics/src/refunds/metrics/refund_processed_amount.rs +++ b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs @@ -33,7 +33,7 @@ where dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> @@ -80,7 +80,7 @@ where } query_builder.add_group_by_clause("currency").switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; diff --git a/crates/analytics/src/refunds/metrics/refund_success_count.rs b/crates/analytics/src/refunds/metrics/refund_success_count.rs index 4c3f600b05c..1eb198687a0 100644 --- a/crates/analytics/src/refunds/metrics/refund_success_count.rs +++ b/crates/analytics/src/refunds/metrics/refund_success_count.rs @@ -34,7 +34,7 @@ where dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> @@ -76,7 +76,7 @@ where query_builder.add_group_by_clause(dim).switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; diff --git a/crates/analytics/src/refunds/metrics/refund_success_rate.rs b/crates/analytics/src/refunds/metrics/refund_success_rate.rs index 8ed144999a7..c0a8d27db6f 100644 --- a/crates/analytics/src/refunds/metrics/refund_success_rate.rs +++ b/crates/analytics/src/refunds/metrics/refund_success_rate.rs @@ -32,7 +32,7 @@ where dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> @@ -77,7 +77,7 @@ where query_builder.add_group_by_clause(dim).switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; 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 20989daca7d..c7114e5ddc9 100644 --- a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs +++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs @@ -33,7 +33,7 @@ where dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { @@ -79,7 +79,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") 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 index 72e32907efb..c6579005fac 100644 --- a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_error_message.rs +++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_error_message.rs @@ -37,7 +37,7 @@ where dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { @@ -127,7 +127,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut outer_query_builder) .attach_printable("Error adding granularity") 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 93880824ef9..b376b7c1286 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 @@ -33,7 +33,7 @@ where dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> @@ -88,7 +88,7 @@ where query_builder.add_group_by_clause("currency").switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs index 0df28901e8f..f7a2e11676f 100644 --- a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs +++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs @@ -36,7 +36,7 @@ where dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { @@ -119,7 +119,7 @@ where .switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut outer_query_builder) .attach_printable("Error adding granularity") 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 c0bb139c46f..ce9c8f4b397 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 @@ -34,7 +34,7 @@ where dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> @@ -76,7 +76,7 @@ where query_builder.add_group_by_clause(dim).switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; 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 e2348d51ad7..b04698c28d0 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 @@ -32,7 +32,7 @@ where dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> @@ -77,7 +77,7 @@ where query_builder.add_group_by_clause(dim).switch()?; } - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; diff --git a/crates/analytics/src/sdk_events/core.rs b/crates/analytics/src/sdk_events/core.rs index 3eca479818b..c8ea156674a 100644 --- a/crates/analytics/src/sdk_events/core.rs +++ b/crates/analytics/src/sdk_events/core.rs @@ -65,7 +65,7 @@ pub async fn get_metrics( &req.group_by_names.clone(), &publishable_key_scoped, &req.filters, - &req.time_series.map(|t| t.granularity), + req.time_series.map(|t| t.granularity), &req.time_range, ) .await diff --git a/crates/analytics/src/sdk_events/metrics.rs b/crates/analytics/src/sdk_events/metrics.rs index 7d5ad0c53d4..3c587925a2f 100644 --- a/crates/analytics/src/sdk_events/metrics.rs +++ b/crates/analytics/src/sdk_events/metrics.rs @@ -56,7 +56,7 @@ where dimensions: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>>; @@ -77,7 +77,7 @@ where dimensions: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { diff --git a/crates/analytics/src/sdk_events/metrics/average_payment_time.rs b/crates/analytics/src/sdk_events/metrics/average_payment_time.rs index c7f6bca988c..1b3ce566827 100644 --- a/crates/analytics/src/sdk_events/metrics/average_payment_time.rs +++ b/crates/analytics/src/sdk_events/metrics/average_payment_time.rs @@ -34,7 +34,7 @@ where dimensions: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { @@ -54,7 +54,7 @@ where }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; diff --git a/crates/analytics/src/sdk_events/metrics/load_time.rs b/crates/analytics/src/sdk_events/metrics/load_time.rs index 73cc693c506..6c6ce21a75e 100644 --- a/crates/analytics/src/sdk_events/metrics/load_time.rs +++ b/crates/analytics/src/sdk_events/metrics/load_time.rs @@ -34,7 +34,7 @@ where dimensions: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { @@ -54,7 +54,7 @@ where }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; diff --git a/crates/analytics/src/sdk_events/metrics/payment_attempts.rs b/crates/analytics/src/sdk_events/metrics/payment_attempts.rs index 4d949d9fb82..a7bb717102f 100644 --- a/crates/analytics/src/sdk_events/metrics/payment_attempts.rs +++ b/crates/analytics/src/sdk_events/metrics/payment_attempts.rs @@ -34,7 +34,7 @@ where dimensions: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { @@ -53,7 +53,7 @@ where }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; diff --git a/crates/analytics/src/sdk_events/metrics/payment_data_filled_count.rs b/crates/analytics/src/sdk_events/metrics/payment_data_filled_count.rs index 37eb967b385..0488907f9a7 100644 --- a/crates/analytics/src/sdk_events/metrics/payment_data_filled_count.rs +++ b/crates/analytics/src/sdk_events/metrics/payment_data_filled_count.rs @@ -34,7 +34,7 @@ where dimensions: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { @@ -53,7 +53,7 @@ where }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; diff --git a/crates/analytics/src/sdk_events/metrics/payment_method_selected_count.rs b/crates/analytics/src/sdk_events/metrics/payment_method_selected_count.rs index d524d0021cf..9599caa1e7b 100644 --- a/crates/analytics/src/sdk_events/metrics/payment_method_selected_count.rs +++ b/crates/analytics/src/sdk_events/metrics/payment_method_selected_count.rs @@ -34,7 +34,7 @@ where dimensions: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { @@ -53,7 +53,7 @@ where }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; diff --git a/crates/analytics/src/sdk_events/metrics/payment_methods_call_count.rs b/crates/analytics/src/sdk_events/metrics/payment_methods_call_count.rs index 081c4968c53..77e6f389930 100644 --- a/crates/analytics/src/sdk_events/metrics/payment_methods_call_count.rs +++ b/crates/analytics/src/sdk_events/metrics/payment_methods_call_count.rs @@ -34,7 +34,7 @@ where dimensions: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { @@ -53,7 +53,7 @@ where }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; diff --git a/crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs b/crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs index 92308acac69..25c81eacd80 100644 --- a/crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs +++ b/crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs @@ -34,7 +34,7 @@ where dimensions: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { @@ -53,7 +53,7 @@ where }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; diff --git a/crates/analytics/src/sdk_events/metrics/sdk_rendered_count.rs b/crates/analytics/src/sdk_events/metrics/sdk_rendered_count.rs index 6f03008e0c1..e972abbd8e3 100644 --- a/crates/analytics/src/sdk_events/metrics/sdk_rendered_count.rs +++ b/crates/analytics/src/sdk_events/metrics/sdk_rendered_count.rs @@ -34,7 +34,7 @@ where dimensions: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, - granularity: &Option<Granularity>, + granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { @@ -53,7 +53,7 @@ where }) .switch()?; - if let Some(granularity) = granularity.as_ref() { + if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; diff --git a/crates/api_models/src/connector_enums.rs b/crates/api_models/src/connector_enums.rs index 4931b8dbd92..294666f35f8 100644 --- a/crates/api_models/src/connector_enums.rs +++ b/crates/api_models/src/connector_enums.rs @@ -139,7 +139,7 @@ pub enum Connector { impl Connector { #[cfg(feature = "payouts")] - pub fn supports_instant_payout(&self, payout_method: Option<PayoutType>) -> bool { + pub fn supports_instant_payout(self, payout_method: Option<PayoutType>) -> bool { matches!( (self, payout_method), (Self::Paypal, Some(PayoutType::Wallet)) @@ -148,26 +148,26 @@ impl Connector { ) } #[cfg(feature = "payouts")] - pub fn supports_create_recipient(&self, payout_method: Option<PayoutType>) -> bool { + pub fn supports_create_recipient(self, payout_method: Option<PayoutType>) -> bool { matches!((self, payout_method), (_, Some(PayoutType::Bank))) } #[cfg(feature = "payouts")] - pub fn supports_payout_eligibility(&self, payout_method: Option<PayoutType>) -> bool { + pub fn supports_payout_eligibility(self, payout_method: Option<PayoutType>) -> bool { matches!((self, payout_method), (_, Some(PayoutType::Card))) } #[cfg(feature = "payouts")] - pub fn is_payout_quote_call_required(&self) -> bool { + pub fn is_payout_quote_call_required(self) -> bool { matches!(self, Self::Wise) } #[cfg(feature = "payouts")] - pub fn supports_access_token_for_payout(&self, payout_method: Option<PayoutType>) -> bool { + pub fn supports_access_token_for_payout(self, payout_method: Option<PayoutType>) -> bool { matches!((self, payout_method), (Self::Paypal, _)) } #[cfg(feature = "payouts")] - pub fn supports_vendor_disburse_account_create_for_payout(&self) -> bool { + pub fn supports_vendor_disburse_account_create_for_payout(self) -> bool { matches!(self, Self::Stripe) } - pub fn supports_access_token(&self, payment_method: PaymentMethod) -> bool { + pub fn supports_access_token(self, payment_method: PaymentMethod) -> bool { matches!( (self, payment_method), (Self::Airwallex, _) @@ -181,13 +181,13 @@ impl Connector { | (Self::Itaubank, _) ) } - pub fn supports_file_storage_module(&self) -> bool { + pub fn supports_file_storage_module(self) -> bool { matches!(self, Self::Stripe | Self::Checkout) } - pub fn requires_defend_dispute(&self) -> bool { + pub fn requires_defend_dispute(self) -> bool { matches!(self, Self::Checkout) } - pub fn is_separate_authentication_supported(&self) -> bool { + pub fn is_separate_authentication_supported(self) -> bool { match self { #[cfg(feature = "dummy_connector")] Self::DummyConnector1 @@ -281,15 +281,15 @@ impl Connector { Self::Checkout | Self::Nmi | Self::Cybersource => true, } } - pub fn is_pre_processing_required_before_authorize(&self) -> bool { + pub fn is_pre_processing_required_before_authorize(self) -> bool { matches!(self, Self::Airwallex) } - pub fn should_acknowledge_webhook_for_resource_not_found_errors(&self) -> bool { + pub fn should_acknowledge_webhook_for_resource_not_found_errors(self) -> bool { matches!(self, Self::Adyenplatform) } #[cfg(feature = "dummy_connector")] pub fn validate_dummy_connector_enabled( - &self, + self, is_dummy_connector_enabled: bool, ) -> errors::CustomResult<(), errors::ValidationError> { if !is_dummy_connector_enabled diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 701e8793786..1e05e7ec883 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -599,13 +599,13 @@ pub enum Currency { impl Currency { /// Convert the amount to its base denomination based on Currency and return String - pub fn to_currency_base_unit(&self, amount: i64) -> Result<String, TryFromIntError> { + pub fn to_currency_base_unit(self, amount: i64) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; Ok(format!("{amount_f64:.2}")) } /// Convert the amount to its base denomination based on Currency and return f64 - pub fn to_currency_base_unit_asf64(&self, amount: i64) -> Result<f64, TryFromIntError> { + pub fn to_currency_base_unit_asf64(self, amount: i64) -> Result<f64, TryFromIntError> { let amount_f64: f64 = u32::try_from(amount)?.into(); let amount = if self.is_zero_decimal_currency() { amount_f64 @@ -618,7 +618,7 @@ impl Currency { } ///Convert the higher decimal amount to its base absolute units - pub fn to_currency_lower_unit(&self, amount: String) -> Result<String, ParseFloatError> { + pub fn to_currency_lower_unit(self, amount: String) -> Result<String, ParseFloatError> { let amount_f64 = amount.parse::<f64>()?; let amount_string = if self.is_zero_decimal_currency() { amount_f64 @@ -634,7 +634,7 @@ impl Currency { /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ pub fn to_currency_base_unit_with_zero_decimal_check( - &self, + self, amount: i64, ) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; @@ -645,8 +645,8 @@ impl Currency { } } - pub fn iso_4217(&self) -> &'static str { - match *self { + pub fn iso_4217(self) -> &'static str { + match self { Self::AED => "784", Self::AFN => "971", Self::ALL => "008", @@ -1301,7 +1301,7 @@ pub enum IntentStatus { impl IntentStatus { /// Indicates whether the syncing with the connector should be allowed or not - pub fn should_force_sync_with_connector(&self) -> bool { + pub fn should_force_sync_with_connector(self) -> bool { match self { // Confirm has not happened yet Self::RequiresConfirmation @@ -2495,7 +2495,7 @@ pub enum ClientPlatform { } impl PaymentSource { - pub fn is_for_internal_use_only(&self) -> bool { + pub fn is_for_internal_use_only(self) -> bool { match self { Self::Dashboard | Self::Sdk | Self::MerchantServer | Self::Postman => false, Self::Webhook | Self::ExternalAuthenticator => true, @@ -2590,7 +2590,7 @@ pub enum AuthenticationConnectors { } impl AuthenticationConnectors { - pub fn is_separate_version_call_required(&self) -> bool { + pub fn is_separate_version_call_required(self) -> bool { match self { Self::Threedsecureio | Self::Netcetera => false, Self::Gpayments => true, @@ -2624,15 +2624,15 @@ pub enum AuthenticationStatus { } impl AuthenticationStatus { - pub fn is_terminal_status(&self) -> bool { + pub fn is_terminal_status(self) -> bool { match self { Self::Started | Self::Pending => false, Self::Success | Self::Failed => true, } } - pub fn is_failed(&self) -> bool { - self == &Self::Failed + pub fn is_failed(self) -> bool { + self == Self::Failed } } diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index ddf55d29371..7611ae127ee 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -522,7 +522,7 @@ impl Country { CountryAlpha2::ZW => Self::Zimbabwe, } } - pub const fn to_alpha2(&self) -> CountryAlpha2 { + pub const fn to_alpha2(self) -> CountryAlpha2 { match self { Self::Afghanistan => CountryAlpha2::AF, Self::AlandIslands => CountryAlpha2::AX, @@ -1028,7 +1028,7 @@ impl Country { CountryAlpha3::ZWE => Self::Zimbabwe, } } - pub const fn to_alpha3(&self) -> CountryAlpha3 { + pub const fn to_alpha3(self) -> CountryAlpha3 { match self { Self::Afghanistan => CountryAlpha3::AFG, Self::AlandIslands => CountryAlpha3::ALA, @@ -1535,7 +1535,7 @@ impl Country { _ => Err(NumericCountryCodeParseError), } } - pub const fn to_numeric(&self) -> u32 { + pub const fn to_numeric(self) -> u32 { match self { Self::Afghanistan => 4, Self::AlandIslands => 248, @@ -1905,6 +1905,8 @@ mod custom_serde { use super::*; + // `serde::Serialize` implementation needs the function to accept `&Country` + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn serialize<S>(code: &Country, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, @@ -1937,6 +1939,8 @@ mod custom_serde { use super::*; + // `serde::Serialize` implementation needs the function to accept `&Country` + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn serialize<S>(code: &Country, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, @@ -1969,6 +1973,8 @@ mod custom_serde { use super::*; + // `serde::Serialize` implementation needs the function to accept `&Country` + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn serialize<S>(code: &Country, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs index a8085564145..e0aa77ce707 100644 --- a/crates/common_utils/src/id_type.rs +++ b/crates/common_utils/src/id_type.rs @@ -47,7 +47,7 @@ use thiserror::Error; use crate::{fp_utils::when, generate_id_with_default_len}; #[inline] -fn is_valid_id_character(input_char: &char) -> bool { +fn is_valid_id_character(input_char: char) -> bool { input_char.is_ascii_alphanumeric() || matches!(input_char, '_' | '-') } @@ -57,7 +57,7 @@ fn get_invalid_input_character(input_string: Cow<'static, str>) -> Option<char> input_string .trim() .chars() - .find(|char| !is_valid_id_character(char)) + .find(|&char| !is_valid_id_character(char)) } #[derive(Debug, PartialEq, Hash, Serialize, Clone, Eq)] diff --git a/crates/common_utils/src/id_type/global_id.rs b/crates/common_utils/src/id_type/global_id.rs index a54df758587..d783912459e 100644 --- a/crates/common_utils/src/id_type/global_id.rs +++ b/crates/common_utils/src/id_type/global_id.rs @@ -29,7 +29,7 @@ pub(crate) enum GlobalEntity { } impl GlobalEntity { - fn prefix(&self) -> &'static str { + fn prefix(self) -> &'static str { match self { Self::Customer => "cus", Self::Payment => "pay", diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 6c4b090fff2..0d39841fe09 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -375,7 +375,7 @@ pub struct MinorUnit(i64); impl MinorUnit { /// gets amount as i64 value will be removed in future - pub fn get_amount_as_i64(&self) -> i64 { + pub fn get_amount_as_i64(self) -> i64 { self.0 } diff --git a/crates/hyperswitch_connectors/src/connectors/cashtocode.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs index b5363cdf5db..b4e066ebd99 100644 --- a/crates/hyperswitch_connectors/src/connectors/cashtocode.rs +++ b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs @@ -64,7 +64,7 @@ impl api::RefundExecute for Cashtocode {} impl api::RefundSync for Cashtocode {} fn get_b64_auth_cashtocode( - payment_method_type: &Option<enums::PaymentMethodType>, + payment_method_type: Option<enums::PaymentMethodType>, auth_type: &transformers::CashtocodeAuth, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { fn construct_basic_auth( @@ -204,7 +204,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData &req.request.currency, ))?; - let mut api_key = get_b64_auth_cashtocode(&req.request.payment_method_type, &auth_type)?; + let mut api_key = get_b64_auth_cashtocode(req.request.payment_method_type, &auth_type)?; header.append(&mut api_key); Ok(header) diff --git a/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs index 2a282414f4b..7a70d97a102 100644 --- a/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs @@ -203,7 +203,7 @@ pub struct CashtocodePaymentsSyncResponse { } fn get_redirect_form_data( - payment_method_type: &enums::PaymentMethodType, + payment_method_type: enums::PaymentMethodType, response_data: CashtocodePaymentsResponseData, ) -> CustomResult<RedirectForm, errors::ConnectorError> { match payment_method_type { @@ -260,7 +260,6 @@ impl<F> .data .request .payment_method_type - .as_ref() .ok_or(errors::ConnectorError::MissingPaymentMethodType)?; let redirection_data = get_redirect_form_data(payment_method_type, response_data)?; ( diff --git a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs index 74c8d1edb38..83f861dfdb3 100644 --- a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs @@ -1,4 +1,4 @@ -use common_enums::enums::{self, AuthenticationType, Currency}; +use common_enums::enums::{self, AuthenticationType}; use common_utils::pii::IpAddress; use hyperswitch_domain_models::{ payment_method_data::{Card, PaymentMethodData}, @@ -148,7 +148,7 @@ impl TryFrom<&PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest { item.request.amount, item.request.currency, )?, - currency_code: Currency::iso_4217(&item.request.currency).to_string(), + currency_code: item.request.currency.iso_4217().to_string(), three_d_secure, source, order_identifier: item.connector_request_reference_id.clone(), diff --git a/crates/hyperswitch_connectors/src/connectors/rapyd.rs b/crates/hyperswitch_connectors/src/connectors/rapyd.rs index c94cd09e275..f909de4dccd 100644 --- a/crates/hyperswitch_connectors/src/connectors/rapyd.rs +++ b/crates/hyperswitch_connectors/src/connectors/rapyd.rs @@ -69,7 +69,7 @@ impl Rapyd { http_method: &str, url_path: &str, body: &str, - timestamp: &i64, + timestamp: i64, salt: &str, ) -> CustomResult<String, errors::ConnectorError> { let rapyd::RapydAuthType { @@ -230,7 +230,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData let body = types::PaymentsAuthorizeType::get_request_body(self, req, connectors)?; let req_body = body.get_inner_value().expose(); let signature = - self.generate_signature(&auth, "post", "/v1/payments", &req_body, &timestamp, &salt)?; + self.generate_signature(&auth, "post", "/v1/payments", &req_body, timestamp, &salt)?; let headers = vec![ ("access_key".to_string(), auth.access_key.into_masked()), ("salt".to_string(), salt.into_masked()), @@ -342,7 +342,7 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Ra let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?; let url_path = format!("/v1/payments/{}", req.request.connector_transaction_id); let signature = - self.generate_signature(&auth, "delete", &url_path, "", &timestamp, &salt)?; + self.generate_signature(&auth, "delete", &url_path, "", timestamp, &salt)?; let headers = vec![ ("access_key".to_string(), auth.access_key.into_masked()), @@ -438,7 +438,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Rap .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)? ); - let signature = self.generate_signature(&auth, "get", &url_path, "", &timestamp, &salt)?; + let signature = self.generate_signature(&auth, "get", &url_path, "", timestamp, &salt)?; let headers = vec![ ("access_key".to_string(), auth.access_key.into_masked()), @@ -535,7 +535,7 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo let body = types::PaymentsCaptureType::get_request_body(self, req, connectors)?; let req_body = body.get_inner_value().expose(); let signature = - self.generate_signature(&auth, "post", &url_path, &req_body, &timestamp, &salt)?; + self.generate_signature(&auth, "post", &url_path, &req_body, timestamp, &salt)?; let headers = vec![ ("access_key".to_string(), auth.access_key.into_masked()), ("salt".to_string(), salt.into_masked()), @@ -664,7 +664,7 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Rapyd { let req_body = body.get_inner_value().expose(); let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?; let signature = - self.generate_signature(&auth, "post", "/v1/refunds", &req_body, &timestamp, &salt)?; + self.generate_signature(&auth, "post", "/v1/refunds", &req_body, timestamp, &salt)?; let headers = vec![ ("access_key".to_string(), auth.access_key.into_masked()), ("salt".to_string(), salt.into_masked()), diff --git a/crates/hyperswitch_connectors/src/connectors/worldline.rs b/crates/hyperswitch_connectors/src/connectors/worldline.rs index 0cbd4660da2..b68a1e7a652 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldline.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldline.rs @@ -62,7 +62,7 @@ impl Worldline { pub fn generate_authorization_token( &self, auth: worldline::WorldlineAuthType, - http_method: &Method, + http_method: Method, content_type: &str, date: &str, endpoint: &str, @@ -113,7 +113,7 @@ where let date = Self::get_current_date_time()?; let content_type = Self::get_content_type(self); let signed_data: String = - self.generate_authorization_token(auth, &http_method, content_type, &date, &endpoint)?; + self.generate_authorization_token(auth, http_method, content_type, &date, &endpoint)?; Ok(vec![ (headers::DATE.to_string(), date.into()), diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index e35c4672308..c65ec864d32 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -515,13 +515,13 @@ fn compile_graph_for_countries_and_currencies( fn compile_config_graph( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, config: &kgraph_types::CountryCurrencyFilter, - connector: &api_enums::RoutableConnectors, + connector: api_enums::RoutableConnectors, ) -> Result<cgraph::NodeId, KgraphError> { let mut agg_node_id: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); let mut pmt_enabled: Vec<dir::DirValue> = Vec::new(); if let Some(pmt) = config .connector_configs - .get(connector) + .get(&connector) .or(config.default_configs.as_ref()) .map(|inner| inner.0.clone()) { @@ -635,7 +635,7 @@ fn compile_merchant_connector_graph( let config_info = "Config for respective PaymentMethodType for the connector"; - let config_enabled_agg_id = compile_config_graph(builder, config, &connector)?; + let config_enabled_agg_id = compile_config_graph(builder, config, connector)?; let domain_level_node_id = builder .make_all_aggregator( diff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rs index 5b6dd81501b..212a1257425 100644 --- a/crates/router/src/bin/router.rs +++ b/crates/router/src/bin/router.rs @@ -35,7 +35,7 @@ async fn main() -> ApplicationResult<()> { // Spawn a thread for collecting metrics at fixed intervals metrics::bg_metrics_collector::spawn_metrics_collector( - &conf.log.telemetry.bg_metrics_collection_interval_in_secs, + conf.log.telemetry.bg_metrics_collection_interval_in_secs, ); #[allow(clippy::expect_used)] diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 83ad0d3a182..16cab2fda47 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1738,7 +1738,7 @@ fn get_additional_data(item: &types::PaymentsAuthorizeRouterData) -> Option<Addi }) } -fn get_channel_type(pm_type: &Option<storage_enums::PaymentMethodType>) -> Option<Channel> { +fn get_channel_type(pm_type: Option<storage_enums::PaymentMethodType>) -> Option<Channel> { pm_type.as_ref().and_then(|pmt| match pmt { storage_enums::PaymentMethodType::GoPay | storage_enums::PaymentMethodType::Vipps => { Some(Channel::Web) @@ -3139,7 +3139,7 @@ impl let additional_data = get_additional_data(item.router_data); let payment_method = AdyenPaymentMethod::try_from((wallet_data, item.router_data))?; let shopper_interaction = AdyenShopperInteraction::from(item.router_data); - let channel = get_channel_type(&item.router_data.request.payment_method_type); + let channel = get_channel_type(item.router_data.request.payment_method_type); let (recurring_processing_model, store_payment_method, shopper_reference) = get_recurring_processing_model(item.router_data)?; let return_url = item.router_data.request.get_router_return_url()?; diff --git a/crates/router/src/connector/paybox/transformers.rs b/crates/router/src/connector/paybox/transformers.rs index 4e237223fa8..80e3e0ef075 100644 --- a/crates/router/src/connector/paybox/transformers.rs +++ b/crates/router/src/connector/paybox/transformers.rs @@ -189,8 +189,7 @@ impl TryFrom<&PayboxRouterData<&types::PaymentsCaptureRouterData>> for PayboxCap let auth_data: PayboxAuthType = PayboxAuthType::try_from(&item.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - let currency = diesel_models::enums::Currency::iso_4217(&item.router_data.request.currency) - .to_string(); + let currency = item.router_data.request.currency.iso_4217().to_string(); let paybox_meta_data: PayboxMeta = utils::to_connector_meta(item.router_data.request.connector_meta.clone())?; let format_time = common_utils::date_time::format_date( @@ -387,9 +386,7 @@ impl TryFrom<&PayboxRouterData<&types::PaymentsAuthorizeRouterData>> for PayboxP item.router_data.request.capture_method, item.router_data.request.is_mandate_payment(), )?; - let currency = - diesel_models::enums::Currency::iso_4217(&item.router_data.request.currency) - .to_string(); + let currency = item.router_data.request.currency.iso_4217().to_string(); let expiration_date = req_card.get_card_expiry_month_year_2_digit_with_delimiter("".to_owned())?; let format_time = common_utils::date_time::format_date( @@ -892,8 +889,7 @@ impl<F> TryFrom<&PayboxRouterData<&types::RefundsRouterData<F>>> for PayboxRefun let auth_data: PayboxAuthType = PayboxAuthType::try_from(&item.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - let currency = diesel_models::enums::Currency::iso_4217(&item.router_data.request.currency) - .to_string(); + let currency = item.router_data.request.currency.iso_4217().to_string(); let format_time = common_utils::date_time::format_date( common_utils::date_time::now(), DateFormat::DDMMYYYYHHmmss, @@ -1090,9 +1086,7 @@ impl TryFrom<&PayboxRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for item.router_data.request.capture_method, item.router_data.request.is_mandate_payment(), )?; - let currency = - diesel_models::enums::Currency::iso_4217(&item.router_data.request.currency) - .to_string(); + let currency = item.router_data.request.currency.iso_4217().to_string(); let expiration_date = req_card.get_card_expiry_month_year_2_digit_with_delimiter("".to_owned())?; let format_time = common_utils::date_time::format_date( @@ -1207,8 +1201,7 @@ impl Some(enums::CaptureMethod::Manual) => Ok(MANDATE_AUTH_ONLY.to_string()), _ => Err(errors::ConnectorError::CaptureMethodNotSupported), }?; - let currency = diesel_models::enums::Currency::iso_4217(&item.router_data.request.currency) - .to_string(); + let currency = item.router_data.request.currency.iso_4217().to_string(); let format_time = common_utils::date_time::format_date( common_utils::date_time::now(), DateFormat::DDMMYYYYHHmmss, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 6e2ed220721..b026b1e32fe 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -2723,7 +2723,6 @@ pub async fn create_connector( let key_manager_state = &(&state).into(); #[cfg(feature = "dummy_connector")] req.connector_name - .clone() .validate_dummy_connector_enabled(state.conf.dummy_connector.enabled) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector name".to_string(), diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index 3555eb1193e..bc66461e819 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -182,7 +182,7 @@ pub async fn form_payment_link_data( let payment_link_status = check_payment_link_status(session_expiry); let is_terminal_state = check_payment_link_invalid_conditions( - &payment_intent.status, + payment_intent.status, &[ storage_enums::IntentStatus::Cancelled, storage_enums::IntentStatus::Failed, @@ -668,10 +668,10 @@ fn capitalize_first_char(s: &str) -> String { } fn check_payment_link_invalid_conditions( - intent_status: &storage_enums::IntentStatus, + intent_status: storage_enums::IntentStatus, not_allowed_statuses: &[storage_enums::IntentStatus], ) -> bool { - not_allowed_statuses.contains(intent_status) + not_allowed_statuses.contains(&intent_status) } #[cfg(feature = "v2")] diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index a7c4a4c4ade..53ec0129896 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -433,7 +433,7 @@ pub async fn render_pm_collect_link( fn generate_task_id_for_payment_method_status_update_workflow( key_id: &str, - runner: &storage::ProcessTrackerRunner, + runner: storage::ProcessTrackerRunner, task: &str, ) -> String { format!("{runner}_{task}_{key_id}") @@ -467,7 +467,7 @@ pub async fn add_payment_method_status_update_task( let process_tracker_id = generate_task_id_for_payment_method_status_update_workflow( payment_method.get_id().as_str(), - &runner, + runner, task, ); let process_tracker_entry = storage::ProcessTrackerNew::new( diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index ad612ed6f3b..68b1790880d 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3328,7 +3328,7 @@ pub async fn list_payment_methods( None }; - helpers::infer_payment_type(&amount, mandate_type.as_ref()) + helpers::infer_payment_type(amount, mandate_type.as_ref()) }); let all_mcas = db @@ -3838,7 +3838,7 @@ pub async fn list_payment_methods( .extend(required_fields_final.non_mandate.clone()); } required_fields_hs = should_collect_shipping_or_billing_details_from_wallet_connector( - &payment_method, + payment_method, element.payment_experience.as_ref(), business_profile.as_ref(), required_fields_hs.clone(), @@ -4269,7 +4269,7 @@ pub async fn list_payment_methods( } fn should_collect_shipping_or_billing_details_from_wallet_connector( - payment_method: &api_enums::PaymentMethod, + payment_method: api_enums::PaymentMethod, payment_experience_optional: Option<&api_enums::PaymentExperience>, business_profile: Option<&Profile>, mut required_fields_hs: HashMap<String, RequiredFieldInfo>, @@ -4553,7 +4553,7 @@ pub async fn filter_payment_methods( let filter_pm_based_on_allowed_types = filter_pm_based_on_allowed_types( allowed_payment_method_types.as_ref(), - &payment_method_object.payment_method_type, + payment_method_object.payment_method_type, ); if payment_attempt @@ -4596,7 +4596,7 @@ pub async fn filter_payment_methods( let filter_pm_card_network_based = filter_pm_card_network_based( payment_method_object.card_networks.as_ref(), req.card_networks.as_ref(), - &payment_method_object.payment_method_type, + payment_method_object.payment_method_type, ); let saved_payment_methods_filter = req @@ -4696,7 +4696,7 @@ fn filter_installment_based( fn filter_pm_card_network_based( pm_card_networks: Option<&Vec<api_enums::CardNetwork>>, request_card_networks: Option<&Vec<api_enums::CardNetwork>>, - pm_type: &api_enums::PaymentMethodType, + pm_type: api_enums::PaymentMethodType, ) -> bool { match pm_type { api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => { @@ -4714,9 +4714,9 @@ fn filter_pm_card_network_based( fn filter_pm_based_on_allowed_types( allowed_types: Option<&Vec<api_enums::PaymentMethodType>>, - payment_method_type: &api_enums::PaymentMethodType, + payment_method_type: api_enums::PaymentMethodType, ) -> bool { - allowed_types.map_or(true, |pm| pm.contains(payment_method_type)) + allowed_types.map_or(true, |pm| pm.contains(&payment_method_type)) } fn filter_recurring_based( diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rs index 604e8c70626..816807fe014 100644 --- a/crates/router/src/core/payment_methods/utils.rs +++ b/crates/router/src/core/payment_methods/utils.rs @@ -96,7 +96,7 @@ fn compile_pm_graph( domain_id, supported_payment_methods_for_update_mandate, pmt.clone(), - &pm_enabled.payment_method, + pm_enabled.payment_method, ); if let Ok(Some(connector_eligible_for_update_mandates_node)) = res { agg_or_nodes_for_mandate_filters.push(( @@ -200,7 +200,7 @@ fn compile_pm_graph( .or_else(|| config.0.get("default")) .map(|inner| { if let Ok(Some(capture_method_filter)) = - construct_capture_method_node(builder, inner, &pmt.payment_method_type) + construct_capture_method_node(builder, inner, pmt.payment_method_type) { agg_nodes.push(( capture_method_filter, @@ -214,7 +214,7 @@ fn compile_pm_graph( if let Ok(Some(country_node)) = compile_accepted_countries_for_mca( builder, domain_id, - &pmt.payment_method_type, + pmt.payment_method_type, pmt.accepted_countries, config, connector.clone(), @@ -230,7 +230,7 @@ fn compile_pm_graph( if let Ok(Some(currency_node)) = compile_accepted_currency_for_mca( builder, domain_id, - &pmt.payment_method_type, + pmt.payment_method_type, pmt.accepted_currencies, config, connector.clone(), @@ -274,7 +274,7 @@ fn construct_supported_connectors_for_update_mandate_node( domain_id: cgraph::DomainId, supported_payment_methods_for_update_mandate: &settings::SupportedPaymentMethodsForMandate, pmt: RequestPaymentMethodTypes, - payment_method: &enums::PaymentMethod, + payment_method: enums::PaymentMethod, ) -> Result<Option<cgraph::NodeId>, KgraphError> { let card_value_node = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)), @@ -296,9 +296,9 @@ fn construct_supported_connectors_for_update_mandate_node( if let Some(supported_pm_for_mandates) = supported_payment_methods_for_update_mandate .0 - .get(payment_method) + .get(&payment_method) { - if payment_method == &enums::PaymentMethod::Card { + if payment_method == enums::PaymentMethod::Card { if let Some(credit_connector_list) = supported_pm_for_mandates .0 .get(&api_enums::PaymentMethodType::Credit) @@ -498,12 +498,12 @@ fn construct_supported_connectors_for_mandate_node( fn construct_capture_method_node( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, payment_method_filters: &settings::PaymentMethodFilters, - payment_method_type: &api_enums::PaymentMethodType, + payment_method_type: api_enums::PaymentMethodType, ) -> Result<Option<cgraph::NodeId>, KgraphError> { if !payment_method_filters .0 .get(&settings::PaymentMethodFilterKey::PaymentMethodType( - *payment_method_type, + payment_method_type, )) .and_then(|v| v.not_available_flows) .and_then(|v| v.capture_method) @@ -542,7 +542,7 @@ fn construct_capture_method_node( fn compile_accepted_countries_for_mca( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, domain_id: cgraph::DomainId, - payment_method_type: &enums::PaymentMethodType, + payment_method_type: enums::PaymentMethodType, pm_countries: Option<admin::AcceptedCountries>, config: &settings::ConnectorFilters, connector: String, @@ -608,7 +608,7 @@ fn compile_accepted_countries_for_mca( derived_config .0 .get(&settings::PaymentMethodFilterKey::PaymentMethodType( - *payment_method_type, + payment_method_type, )) { if let Some(config_countries) = value.country.as_ref() { @@ -636,7 +636,7 @@ fn compile_accepted_countries_for_mca( default_derived_config .0 .get(&settings::PaymentMethodFilterKey::PaymentMethodType( - *payment_method_type, + payment_method_type, )) { if let Some(config_countries) = value.country.as_ref() { @@ -673,7 +673,7 @@ fn compile_accepted_countries_for_mca( fn compile_accepted_currency_for_mca( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, domain_id: cgraph::DomainId, - payment_method_type: &enums::PaymentMethodType, + payment_method_type: enums::PaymentMethodType, pm_currency: Option<admin::AcceptedCurrencies>, config: &settings::ConnectorFilters, connector: String, @@ -730,7 +730,7 @@ fn compile_accepted_currency_for_mca( derived_config .0 .get(&settings::PaymentMethodFilterKey::PaymentMethodType( - *payment_method_type, + payment_method_type, )) { if let Some(config_currencies) = value.currency.as_ref() { @@ -760,7 +760,7 @@ fn compile_accepted_currency_for_mca( default_derived_config .0 .get(&settings::PaymentMethodFilterKey::PaymentMethodType( - *payment_method_type, + payment_method_type, )) { if let Some(config_currencies) = value.currency.as_ref() { diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 7a24f2a30a2..e4f72c717f6 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1379,7 +1379,7 @@ pub async fn add_delete_tokenized_data_task( lookup_key: lookup_key.to_owned(), pm, }; - let schedule_time = get_delete_tokenize_schedule_time(db, &pm, 0) + let schedule_time = get_delete_tokenize_schedule_time(db, pm, 0) .await .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to obtain initial process tracker schedule time")?; @@ -1434,8 +1434,7 @@ pub async fn start_tokenize_data_workflow( } Err(err) => { logger::error!("Err: Deleting Card From Locker : {:?}", err); - retry_delete_tokenize(db, &delete_tokenize_data.pm, tokenize_tracker.to_owned()) - .await?; + retry_delete_tokenize(db, delete_tokenize_data.pm, tokenize_tracker.to_owned()).await?; metrics::RETRIED_DELETE_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]); } } @@ -1444,7 +1443,7 @@ pub async fn start_tokenize_data_workflow( pub async fn get_delete_tokenize_schedule_time( db: &dyn db::StorageInterface, - pm: &enums::PaymentMethod, + pm: enums::PaymentMethod, retry_count: i32, ) -> Option<time::PrimitiveDateTime> { let redis_mapping = db::get_and_deserialize_key( @@ -1467,7 +1466,7 @@ pub async fn get_delete_tokenize_schedule_time( pub async fn retry_delete_tokenize( db: &dyn db::StorageInterface, - pm: &enums::PaymentMethod, + pm: enums::PaymentMethod, pt: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let schedule_time = get_delete_tokenize_schedule_time(db, pm, pt.retry_count).await; diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index c088fa3fce2..99b0a635400 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3281,8 +3281,8 @@ where payment_data.set_surcharge_details(session_surcharge_details.as_ref().and_then( |session_surcharge_details| { session_surcharge_details.fetch_surcharge_details( - &session_connector_data.payment_method_type.into(), - &session_connector_data.payment_method_type, + session_connector_data.payment_method_type.into(), + session_connector_data.payment_method_type, None, ) }, @@ -3736,8 +3736,8 @@ where fn is_payment_method_tokenization_enabled_for_connector( state: &SessionState, connector_name: &str, - payment_method: &storage::enums::PaymentMethod, - payment_method_type: &Option<storage::enums::PaymentMethodType>, + payment_method: storage::enums::PaymentMethod, + payment_method_type: Option<storage::enums::PaymentMethodType>, apple_pay_flow: &Option<domain::ApplePayFlow>, ) -> RouterResult<bool> { let connector_tokenization_filter = state.conf.tokenization.0.get(connector_name); @@ -3747,7 +3747,7 @@ fn is_payment_method_tokenization_enabled_for_connector( connector_filter .payment_method .clone() - .contains(payment_method) + .contains(&payment_method) && is_payment_method_type_allowed_for_connector( payment_method_type, connector_filter.payment_method_type.clone(), @@ -3762,7 +3762,7 @@ fn is_payment_method_tokenization_enabled_for_connector( } fn is_apple_pay_pre_decrypt_type_connector_tokenization( - payment_method_type: &Option<storage::enums::PaymentMethodType>, + payment_method_type: Option<storage::enums::PaymentMethodType>, apple_pay_flow: &Option<domain::ApplePayFlow>, apple_pay_pre_decrypt_flow_filter: Option<ApplePayPreDecryptFlow>, ) -> bool { @@ -3780,7 +3780,7 @@ fn is_apple_pay_pre_decrypt_type_connector_tokenization( fn decide_apple_pay_flow( state: &SessionState, - payment_method_type: &Option<enums::PaymentMethodType>, + payment_method_type: Option<enums::PaymentMethodType>, merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>, ) -> Option<domain::ApplePayFlow> { payment_method_type.and_then(|pmt| match pmt { @@ -3872,10 +3872,10 @@ fn check_apple_pay_metadata( } fn is_payment_method_type_allowed_for_connector( - current_pm_type: &Option<storage::enums::PaymentMethodType>, + current_pm_type: Option<storage::enums::PaymentMethodType>, pm_type_filter: Option<PaymentMethodTypeTokenFilter>, ) -> bool { - match (*current_pm_type).zip(pm_type_filter) { + match (current_pm_type).zip(pm_type_filter) { Some((pm_type, type_filter)) => match type_filter { PaymentMethodTypeTokenFilter::AllAccepted => true, PaymentMethodTypeTokenFilter::EnableOnly(enabled) => enabled.contains(&pm_type), @@ -3888,7 +3888,7 @@ fn is_payment_method_type_allowed_for_connector( async fn decide_payment_method_tokenize_action( state: &SessionState, connector_name: &str, - payment_method: &storage::enums::PaymentMethod, + payment_method: storage::enums::PaymentMethod, pm_parent_token: Option<&str>, is_connector_tokenization_enabled: bool, apple_pay_flow: Option<domain::ApplePayFlow>, @@ -4041,11 +4041,11 @@ where TokenizationAction::SkipConnectorTokenization, ), Some(connector) if is_operation_confirm(&operation) => { - let payment_method = &payment_data + let payment_method = payment_data .get_payment_attempt() .payment_method .get_required_value("payment_method")?; - let payment_method_type = &payment_data.get_payment_attempt().payment_method_type; + let payment_method_type = payment_data.get_payment_attempt().payment_method_type; let apple_pay_flow = decide_apple_pay_flow(state, payment_method_type, Some(merchant_connector_account)); @@ -4072,7 +4072,7 @@ where payment_data.get_token(), is_connector_tokenization_enabled, apple_pay_flow, - *payment_method_type, + payment_method_type, ) .await?; @@ -6268,7 +6268,7 @@ pub async fn payment_external_authentication( })? } helpers::validate_payment_status_against_allowed_statuses( - &payment_intent.status, + payment_intent.status, &[storage_enums::IntentStatus::RequiresCustomerAction], "authenticate", )?; diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 265046f42d9..71049a56241 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -162,7 +162,7 @@ fn is_dynamic_fields_required( required_fields: &settings::RequiredFields, payment_method: enums::PaymentMethod, payment_method_type: enums::PaymentMethodType, - connector: &types::Connector, + connector: types::Connector, required_field_type: Vec<enums::FieldType>, ) -> bool { required_fields @@ -170,7 +170,7 @@ fn is_dynamic_fields_required( .get(&payment_method) .and_then(|pm_type| pm_type.0.get(&payment_method_type)) .and_then(|required_fields_for_connector| { - required_fields_for_connector.fields.get(connector) + required_fields_for_connector.fields.get(&connector) }) .map(|required_fields_final| { required_fields_final @@ -371,7 +371,7 @@ async fn create_applepay_session_token( &state.conf.required_fields, enums::PaymentMethod::Wallet, enums::PaymentMethodType::ApplePay, - &connector.connector_name, + connector.connector_name, billing_variants, ) .then_some(payment_types::ApplePayBillingContactFields(vec![ @@ -399,7 +399,7 @@ async fn create_applepay_session_token( &state.conf.required_fields, enums::PaymentMethod::Wallet, enums::PaymentMethodType::ApplePay, - &connector.connector_name, + connector.connector_name, shipping_variants, ) .then_some(payment_types::ApplePayShippingContactFields(vec![ @@ -839,7 +839,7 @@ fn create_gpay_session_token( &state.conf.required_fields, enums::PaymentMethod::Wallet, enums::PaymentMethodType::GooglePay, - &connector.connector_name, + connector.connector_name, billing_variants, ) } else { @@ -901,7 +901,7 @@ fn create_gpay_session_token( &state.conf.required_fields, enums::PaymentMethod::Wallet, enums::PaymentMethodType::GooglePay, - &connector.connector_name, + connector.connector_name, shipping_variants, ) } else { diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 1be4f4eb7c8..6d40593060d 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1052,7 +1052,7 @@ pub fn validate_card_expiry( } pub fn infer_payment_type( - amount: &api::Amount, + amount: api::Amount, mandate_type: Option<&api::MandateTransactionType>, ) -> api_enums::PaymentType { match mandate_type { @@ -2833,7 +2833,7 @@ pub fn validate_payment_method_type_against_payment_method( } } -pub fn check_force_psync_precondition(status: &storage_enums::AttemptStatus) -> bool { +pub fn check_force_psync_precondition(status: storage_enums::AttemptStatus) -> bool { !matches!( status, storage_enums::AttemptStatus::Charged @@ -3257,11 +3257,11 @@ pub fn authenticate_client_secret( } pub(crate) fn validate_payment_status_against_allowed_statuses( - intent_status: &storage_enums::IntentStatus, + intent_status: storage_enums::IntentStatus, allowed_statuses: &[storage_enums::IntentStatus], action: &'static str, ) -> Result<(), errors::ApiErrorResponse> { - fp_utils::when(!allowed_statuses.contains(intent_status), || { + fp_utils::when(!allowed_statuses.contains(&intent_status), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: format!( "You cannot {action} this payment because it has status {intent_status}", @@ -3271,11 +3271,11 @@ pub(crate) fn validate_payment_status_against_allowed_statuses( } pub(crate) fn validate_payment_status_against_not_allowed_statuses( - intent_status: &storage_enums::IntentStatus, + intent_status: storage_enums::IntentStatus, not_allowed_statuses: &[storage_enums::IntentStatus], action: &'static str, ) -> Result<(), errors::ApiErrorResponse> { - fp_utils::when(not_allowed_statuses.contains(intent_status), || { + fp_utils::when(not_allowed_statuses.contains(&intent_status), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: format!( "You cannot {action} this payment because it has status {intent_status}", diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index 2bc18122b22..97832a08184 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -70,7 +70,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; helpers::validate_payment_status_against_not_allowed_statuses( - &payment_intent.status, + payment_intent.status, &[IntentStatus::Failed, IntentStatus::Succeeded], "approve", )?; diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 8d7361cd257..ef6570abf8c 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -68,7 +68,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; helpers::validate_payment_status_against_not_allowed_statuses( - &payment_intent.status, + payment_intent.status, &[ enums::IntentStatus::Failed, enums::IntentStatus::Succeeded, diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 8c003f54adf..b296d6c3052 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -76,7 +76,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?; helpers::validate_payment_status_against_not_allowed_statuses( - &payment_intent.status, + payment_intent.status, &[ storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Succeeded, diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 4b4091b1c3a..5a73371c212 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -115,7 +115,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .contains(&header_payload.payment_confirm_source) { helpers::validate_payment_status_against_not_allowed_statuses( - &payment_intent.status, + payment_intent.status, &[ storage_enums::IntentStatus::Cancelled, storage_enums::IntentStatus::Succeeded, @@ -127,7 +127,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa )?; } else { helpers::validate_payment_status_against_not_allowed_statuses( - &payment_intent.status, + payment_intent.status, &[ storage_enums::IntentStatus::Cancelled, storage_enums::IntentStatus::Succeeded, diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 23531d2342d..c747c7d984a 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -64,7 +64,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for P .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; helpers::validate_payment_status_against_not_allowed_statuses( - &payment_intent.status, + payment_intent.status, &[ enums::IntentStatus::Cancelled, enums::IntentStatus::Failed, diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 1bc11854ad0..ebc663aaf39 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -68,7 +68,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; helpers::validate_payment_status_against_not_allowed_statuses( - &payment_intent.status, + payment_intent.status, &[ storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Succeeded, diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index cad5dcfbd67..edcb0282bdd 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -66,7 +66,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; helpers::validate_payment_status_against_not_allowed_statuses( - &payment_intent.status, + payment_intent.status, &[ storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Succeeded, diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index a3a826ccd0e..ab3a70aa1bb 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -480,7 +480,7 @@ async fn get_tracker_for_sync< payment_method_info, force_sync: Some( request.force_sync - && (helpers::check_force_psync_precondition(&payment_attempt.status) + && (helpers::check_force_psync_precondition(payment_attempt.status) || contains_encoded_data), ), payment_attempt, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 98491cab1db..61a52e7dfb5 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -102,7 +102,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa )?; helpers::validate_payment_status_against_allowed_statuses( - &payment_intent.status, + payment_intent.status, &[ storage_enums::IntentStatus::RequiresPaymentMethod, storage_enums::IntentStatus::RequiresConfirmation, diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs index 1ddaf0b6abf..1b7acc796ec 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -77,7 +77,7 @@ impl<F: Send + Clone> .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; helpers::validate_payment_status_against_allowed_statuses( - &payment_intent.status, + payment_intent.status, &[enums::IntentStatus::RequiresCapture], "increment authorization", )?; diff --git a/crates/router/src/core/payments/operations/tax_calculation.rs b/crates/router/src/core/payments/operations/tax_calculation.rs index c615e2eb174..712dff35c7a 100644 --- a/crates/router/src/core/payments/operations/tax_calculation.rs +++ b/crates/router/src/core/payments/operations/tax_calculation.rs @@ -78,7 +78,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsDynamicTaxCalcu .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; helpers::validate_payment_status_against_not_allowed_statuses( - &payment_intent.status, + payment_intent.status, &[ storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Succeeded, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index fe70c3b7108..fb8962117c1 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -751,7 +751,7 @@ where let apple_pay_flow = payments::decide_apple_pay_flow( state, - &payment_data.payment_attempt.payment_method_type, + payment_data.payment_attempt.payment_method_type, Some(merchant_connector_account), ); diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs index 223db5b9f90..61ebffe6b83 100644 --- a/crates/router/src/core/payout_link.rs +++ b/crates/router/src/core/payout_link.rs @@ -388,7 +388,7 @@ pub async fn filter_payout_methods( let currency_country_filter = check_currency_country_filters( payout_filter, request_payout_method_type, - &payout.destination_currency, + payout.destination_currency, address .as_ref() .and_then(|address| address.country) @@ -447,7 +447,7 @@ pub async fn filter_payout_methods( pub fn check_currency_country_filters( payout_method_filter: Option<&PaymentMethodFilters>, request_payout_method_type: &api_models::payment_methods::RequestPaymentMethodTypes, - currency: &common_enums::Currency, + currency: common_enums::Currency, country: Option<&common_enums::CountryAlpha2>, ) -> errors::RouterResult<Option<bool>> { if matches!( @@ -476,7 +476,7 @@ pub fn check_currency_country_filters( currency_country_filter .currency .as_ref() - .map(|currency_hash_set| currency_hash_set.contains(currency)) + .map(|currency_hash_set| currency_hash_set.contains(&currency)) }); Ok(currency_filter.or(country_filter)) } diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index d239638c0c6..94946b7e0e0 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -383,7 +383,7 @@ pub async fn payouts_confirm_core( let status = payout_attempt.status; helpers::validate_payout_status_against_not_allowed_statuses( - &status, + status, &[ storage_enums::PayoutStatus::Cancelled, storage_enums::PayoutStatus::Success, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 49b18e53a0c..5becf01597c 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -1010,11 +1010,11 @@ pub fn is_payout_initiated(status: api_enums::PayoutStatus) -> bool { } pub(crate) fn validate_payout_status_against_not_allowed_statuses( - payout_status: &api_enums::PayoutStatus, + payout_status: api_enums::PayoutStatus, not_allowed_statuses: &[api_enums::PayoutStatus], action: &'static str, ) -> Result<(), errors::ApiErrorResponse> { - fp_utils::when(not_allowed_statuses.contains(payout_status), || { + fp_utils::when(not_allowed_statuses.contains(&payout_status), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: format!( "You cannot {action} this payout because it has status {payout_status}", diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index f7a89396397..cdd8b518f35 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -99,7 +99,7 @@ impl RoutingAlgorithmUpdate { request: &routing_types::RoutingConfigRequest, merchant_id: &common_utils::id_type::MerchantId, profile_id: common_utils::id_type::ProfileId, - transaction_type: &enums::TransactionType, + transaction_type: enums::TransactionType, ) -> Self { let algorithm_id = common_utils::generate_routing_id_of_default_length(); let timestamp = common_utils::date_time::now(); @@ -113,7 +113,7 @@ impl RoutingAlgorithmUpdate { algorithm_data: serde_json::json!(request.algorithm), created_at: timestamp, modified_at: timestamp, - algorithm_for: transaction_type.to_owned(), + algorithm_for: transaction_type, }; Self(algo) } @@ -170,7 +170,7 @@ pub async fn create_routing_algorithm_under_profile( key_store: domain::MerchantKeyStore, authentication_profile_id: Option<common_utils::id_type::ProfileId>, request: routing_types::RoutingConfigRequest, - transaction_type: &enums::TransactionType, + transaction_type: enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(&metrics::CONTEXT, 1, &[]); let db = &*state.store; @@ -240,7 +240,7 @@ pub async fn create_routing_algorithm_under_profile( key_store: domain::MerchantKeyStore, authentication_profile_id: Option<common_utils::id_type::ProfileId>, request: routing_types::RoutingConfigRequest, - transaction_type: &enums::TransactionType, + transaction_type: enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(&metrics::CONTEXT, 1, &[]); let db = state.store.as_ref(); diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 196db63ff1b..6a5e3bd0264 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -725,7 +725,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( )?; let payment_status_attribute = - get_desired_payment_status_for_success_routing_metrics(&payment_attempt.status); + get_desired_payment_status_for_success_routing_metrics(payment_attempt.status); let first_success_based_connector_label = &success_based_connectors .labels_with_score @@ -746,7 +746,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( ))?; let outcome = get_success_based_metrics_outcome_for_payment( - &payment_status_attribute, + payment_status_attribute, payment_connector.to_string(), first_success_based_connector.to_string(), ); @@ -843,7 +843,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( #[cfg(all(feature = "v1", feature = "dynamic_routing"))] fn get_desired_payment_status_for_success_routing_metrics( - attempt_status: &common_enums::AttemptStatus, + attempt_status: common_enums::AttemptStatus, ) -> common_enums::AttemptStatus { match attempt_status { common_enums::AttemptStatus::Charged @@ -879,7 +879,7 @@ fn get_desired_payment_status_for_success_routing_metrics( #[cfg(all(feature = "v1", feature = "dynamic_routing"))] fn get_success_based_metrics_outcome_for_payment( - payment_status_attribute: &common_enums::AttemptStatus, + payment_status_attribute: common_enums::AttemptStatus, payment_connector: String, first_success_based_connector: String, ) -> common_enums::SuccessBasedRoutingConclusiveState { diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 4f77b219044..e4ac902f7ba 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -2403,7 +2403,7 @@ pub async fn terminate_auth_select( // Skip SSO if continue with password(TOTP) if next_flow.get_flow() == domain::UserFlow::SPTFlow(domain::SPTFlow::SSO) - && !utils::user::is_sso_auth_type(&user_authentication_method.auth_type) + && !utils::user::is_sso_auth_type(user_authentication_method.auth_type) { next_flow = next_flow.skip(user_from_db, &state).await?; } diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index 32ad135a7d6..a64b0f39dc0 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -46,11 +46,11 @@ pub async fn get_multiple_metadata( for key in metadata_keys { let data = metadata.iter().find(|ele| ele.data_key == key); let resp; - if data.is_none() && utils::is_backfill_required(&key) { + if data.is_none() && utils::is_backfill_required(key) { let backfill_data = backfill_metadata(&state, &user, &key).await?; - resp = into_response(backfill_data.as_ref(), &key)?; + resp = into_response(backfill_data.as_ref(), key)?; } else { - resp = into_response(data, &key)?; + resp = into_response(data, key)?; } response.push(resp); } @@ -148,7 +148,7 @@ fn parse_get_request(data_enum: api::GetMetaDataRequest) -> DBEnum { fn into_response( data: Option<&DashboardMetadata>, - data_type: &DBEnum, + data_type: DBEnum, ) -> UserResult<api::GetMetaDataResponse> { match data_type { DBEnum::ProductionAgreement => Ok(api::GetMetaDataResponse::ProductionAgreement( diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index cfd36629134..62f1425d4d3 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -553,8 +553,8 @@ mod tests { // Dispute Stage can move linearly from PreDispute -> Dispute -> PreArbitration pub fn validate_dispute_stage( - prev_dispute_stage: &DisputeStage, - dispute_stage: &DisputeStage, + prev_dispute_stage: DisputeStage, + dispute_stage: DisputeStage, ) -> bool { match prev_dispute_stage { DisputeStage::PreDispute => true, @@ -596,7 +596,7 @@ pub fn validate_dispute_stage_and_dispute_status( dispute_stage: DisputeStage, dispute_status: DisputeStatus, ) -> CustomResult<(), errors::WebhooksFlowError> { - let dispute_stage_validation = validate_dispute_stage(&prev_dispute_stage, &dispute_stage); + let dispute_stage_validation = validate_dispute_stage(prev_dispute_stage, dispute_stage); let dispute_status_validation = if dispute_stage == prev_dispute_stage { validate_dispute_status(prev_dispute_status, dispute_status) } else { diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index b1e1127787c..be24084bcc0 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -728,7 +728,7 @@ impl Routing { .app_data(web::Data::new(state.clone())) .service( web::resource("").route(web::post().to(|state, req, payload| { - routing::routing_create_config(state, req, payload, &TransactionType::Payment) + routing::routing_create_config(state, req, payload, TransactionType::Payment) })), ) .service( @@ -770,7 +770,7 @@ impl Routing { state, req, payload, - &TransactionType::Payment, + TransactionType::Payment, ) })), ) @@ -850,7 +850,7 @@ impl Routing { state, req, payload, - &TransactionType::Payout, + TransactionType::Payout, ) })), ) diff --git a/crates/router/src/routes/metrics/bg_metrics_collector.rs b/crates/router/src/routes/metrics/bg_metrics_collector.rs index 52d7777f5aa..f3ba7076e53 100644 --- a/crates/router/src/routes/metrics/bg_metrics_collector.rs +++ b/crates/router/src/routes/metrics/bg_metrics_collector.rs @@ -2,7 +2,7 @@ use storage_impl::redis::cache; const DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS: u16 = 15; -pub fn spawn_metrics_collector(metrics_collection_interval_in_secs: &Option<u16>) { +pub fn spawn_metrics_collector(metrics_collection_interval_in_secs: Option<u16>) { let metrics_collection_interval = metrics_collection_interval_in_secs .unwrap_or(DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS); diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index a9f0bc3a26d..19b96a9dc84 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -21,7 +21,7 @@ pub async fn routing_create_config( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<routing_types::RoutingConfigRequest>, - transaction_type: &enums::TransactionType, + transaction_type: enums::TransactionType, ) -> impl Responder { let flow = Flow::RoutingCreateConfig; Box::pin(oss_api::server_wrap( @@ -62,7 +62,7 @@ pub async fn routing_create_config( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<routing_types::RoutingConfigRequest>, - transaction_type: &enums::TransactionType, + transaction_type: enums::TransactionType, ) -> impl Responder { let flow = Flow::RoutingCreateConfig; Box::pin(oss_api::server_wrap( diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 58253684a27..f465719949a 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -1680,7 +1680,7 @@ where )?; let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.permission, &role_info)?; + authorization::check_permission(self.permission, &role_info)?; Ok(( (), @@ -1713,7 +1713,7 @@ where )?; let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.permission, &role_info)?; + authorization::check_permission(self.permission, &role_info)?; Ok(( UserFromToken { @@ -1753,7 +1753,7 @@ where )?; let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.permission, &role_info)?; + authorization::check_permission(self.permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -1816,7 +1816,7 @@ where )?; let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_permission(self.required_permission, &role_info)?; // Check if token has access to Organization that has been requested in the route if payload.org_id != self.organization_id { @@ -1861,7 +1861,7 @@ where )?; let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_permission(self.required_permission, &role_info)?; let merchant_id_from_header = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; @@ -1900,7 +1900,7 @@ where &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_permission(self.required_permission, &role_info)?; let merchant_id_from_header = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; @@ -1970,7 +1970,7 @@ where .get_required_value(headers::X_PROFILE_ID)?; let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_permission(self.required_permission, &role_info)?; let merchant_id_from_header = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; @@ -2047,7 +2047,7 @@ where } let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_permission(self.required_permission, &role_info)?; let merchant_id_from_header = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; @@ -2116,7 +2116,7 @@ where )?; let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_permission(self.required_permission, &role_info)?; // Check if token has access to MerchantId that has been requested through query param if payload.merchant_id != self.merchant_id { @@ -2157,7 +2157,7 @@ where } let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_permission(self.required_permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -2221,7 +2221,7 @@ where } let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_permission(self.required_permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -2292,7 +2292,7 @@ where } let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_permission(self.required_permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -2366,7 +2366,7 @@ where } let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_permission(self.required_permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -2433,7 +2433,7 @@ where )?; let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_permission(self.required_permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -2498,7 +2498,7 @@ where .get_required_value(headers::X_PROFILE_ID)?; let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_permission(self.required_permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -2598,7 +2598,7 @@ where )?; let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.permission, &role_info)?; + authorization::check_permission(self.permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -2662,7 +2662,7 @@ where .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?; let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.permission, &role_info)?; + authorization::check_permission(self.permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -2735,7 +2735,7 @@ where )?; let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.permission, &role_info)?; + authorization::check_permission(self.permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -3184,7 +3184,7 @@ where &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.permission, &role_info)?; + authorization::check_permission(self.permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -3255,7 +3255,7 @@ where &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; - authorization::check_permission(&self.permission, &role_info)?; + authorization::check_permission(self.permission, &role_info)?; let user = UserFromToken { user_id: payload.user_id.clone(), diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index 8f48ef068ce..e0feaa5e817 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -100,7 +100,7 @@ where } pub fn check_permission( - required_permission: &permissions::Permission, + required_permission: permissions::Permission, role_info: &roles::RoleInfo, ) -> RouterResult<()> { role_info diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs index 7ca8442c1ce..8c45210e4b5 100644 --- a/crates/router/src/services/authorization/permission_groups.rs +++ b/crates/router/src/services/authorization/permission_groups.rs @@ -137,13 +137,13 @@ impl ParentGroupExt for ParentGroup { .resources() .iter() .filter(|res| res.entities().iter().any(|entity| entity <= &entity_type)) - .map(|res| permissions::get_resource_name(res, &entity_type)) + .map(|res| permissions::get_resource_name(*res, entity_type)) .collect::<Vec<_>>() .join(", "); Some(( parent, - format!("{} {}", permissions::get_scope_name(&scopes), resources), + format!("{} {}", permissions::get_scope_name(scopes), resources), )) }) .collect() diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs index 6f612007425..b9872b371e0 100644 --- a/crates/router/src/services/authorization/permissions.rs +++ b/crates/router/src/services/authorization/permissions.rs @@ -98,7 +98,7 @@ generate_permissions! { ] } -pub fn get_resource_name(resource: &Resource, entity_type: &EntityType) -> &'static str { +pub fn get_resource_name(resource: Resource, entity_type: EntityType) -> &'static str { match (resource, entity_type) { (Resource::Payment, _) => "Payments", (Resource::Refund, _) => "Refunds", @@ -128,7 +128,7 @@ pub fn get_resource_name(resource: &Resource, entity_type: &EntityType) -> &'sta } } -pub fn get_scope_name(scope: &PermissionScope) -> &'static str { +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.rs b/crates/router/src/services/authorization/roles.rs index f6c4f4b9ef2..a6c5cee1c4e 100644 --- a/crates/router/src/services/authorization/roles.rs +++ b/crates/router/src/services/authorization/roles.rs @@ -76,7 +76,7 @@ impl RoleInfo { .collect() } - pub fn check_permission_exists(&self, required_permission: &Permission) -> bool { + pub fn check_permission_exists(&self, required_permission: Permission) -> bool { required_permission.entity_type() <= self.entity_type && self.get_permission_groups().iter().any(|group| { required_permission.scope() <= group.scope() diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 975b219a26c..763d408d174 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -248,15 +248,15 @@ pub enum SessionSurchargeDetails { impl SessionSurchargeDetails { pub fn fetch_surcharge_details( &self, - payment_method: &enums::PaymentMethod, - payment_method_type: &enums::PaymentMethodType, + payment_method: enums::PaymentMethod, + payment_method_type: enums::PaymentMethodType, card_network: Option<&enums::CardNetwork>, ) -> Option<payments_types::SurchargeDetails> { match self { Self::Calculated(surcharge_metadata) => surcharge_metadata .get_surcharge_details(payments_types::SurchargeKey::PaymentMethodData( - *payment_method, - *payment_method_type, + payment_method, + payment_method_type, card_network.cloned(), )) .cloned(), diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 281b95255c8..e2c25141808 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -273,7 +273,7 @@ pub fn get_oidc_sso_redirect_url(state: &SessionState, provider: &str) -> String format!("{}/redirect/oidc/{}", state.conf.user.base_url, provider) } -pub fn is_sso_auth_type(auth_type: &UserAuthType) -> bool { +pub fn is_sso_auth_type(auth_type: UserAuthType) -> bool { match auth_type { UserAuthType::OpenIdConnect => true, UserAuthType::Password | UserAuthType::MagicLink => false, diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs index 3abdfdd3abe..39a76844be1 100644 --- a/crates/router/src/utils/user/dashboard_metadata.rs +++ b/crates/router/src/utils/user/dashboard_metadata.rs @@ -233,7 +233,7 @@ pub fn is_update_required(metadata: &UserResult<DashboardMetadata>) -> bool { } } -pub fn is_backfill_required(metadata_key: &DBEnum) -> bool { +pub fn is_backfill_required(metadata_key: DBEnum) -> bool { matches!( metadata_key, DBEnum::StripeConnected | DBEnum::PaypalConnected diff --git a/crates/router/tests/connectors/payeezy.rs b/crates/router/tests/connectors/payeezy.rs index 49f7085bda4..a91f5b0fedd 100644 --- a/crates/router/tests/connectors/payeezy.rs +++ b/crates/router/tests/connectors/payeezy.rs @@ -71,7 +71,7 @@ impl PayeezyTest { ..Default::default() }) } - fn get_request_interval(&self) -> u64 { + fn get_request_interval(self) -> u64 { 20 } } diff --git a/crates/router_derive/src/macros/to_encryptable.rs b/crates/router_derive/src/macros/to_encryptable.rs index 561c3a72371..60895c50a8f 100644 --- a/crates/router_derive/src/macros/to_encryptable.rs +++ b/crates/router_derive/src/macros/to_encryptable.rs @@ -124,7 +124,7 @@ enum StructType { 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> { + fn generate_struct_fields(self, fields: &[(Field, Ident)]) -> Vec<proc_macro2::TokenStream> { fields .iter() .map(|(field, inner_ty)| { @@ -162,7 +162,7 @@ impl StructType { /// Generates the ToEncryptable trait implementation fn generate_impls( - &self, + self, gen1: proc_macro2::TokenStream, gen2: proc_macro2::TokenStream, gen3: proc_macro2::TokenStream, @@ -177,7 +177,7 @@ impl StructType { let field_ident = &field.ident; let field_ident_string = field_ident.as_ref().map(|s| s.to_string()); - if is_option || *self == Self::Updated { + 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) } @@ -191,7 +191,7 @@ impl StructType { let field_ident = &field.ident; let field_ident_string = field_ident.as_ref().map(|s| s.to_string()); - if is_option || *self == Self::Updated { + if is_option || self == Self::Updated { quote! { #field_ident: map.remove(#field_ident_string) } } else { quote! { diff --git a/crates/router_env/src/logger/config.rs b/crates/router_env/src/logger/config.rs index 746c8ee9580..431fb5a6368 100644 --- a/crates/router_env/src/logger/config.rs +++ b/crates/router_env/src/logger/config.rs @@ -47,7 +47,7 @@ pub struct Level(pub(super) tracing::Level); impl Level { /// Returns the most verbose [`tracing::Level`] - pub fn into_level(&self) -> tracing::Level { + pub fn into_level(self) -> tracing::Level { self.0 } } diff --git a/crates/router_env/src/logger/formatter.rs b/crates/router_env/src/logger/formatter.rs index 5c3341026c2..bbcf1e23061 100644 --- a/crates/router_env/src/logger/formatter.rs +++ b/crates/router_env/src/logger/formatter.rs @@ -330,7 +330,7 @@ where /// Serialize event into a buffer of bytes using parent span. pub fn event_serialize<S>( &self, - span: &Option<&SpanRef<'_, S>>, + span: Option<&SpanRef<'_, S>>, event: &Event<'_>, ) -> std::io::Result<Vec<u8>> where @@ -347,7 +347,7 @@ where let name = span.map_or("?", SpanRef::name); Self::event_message(span, event, &mut storage); - self.common_serialize(&mut map_serializer, event.metadata(), *span, &storage, name)?; + self.common_serialize(&mut map_serializer, event.metadata(), span, &storage, name)?; map_serializer.end()?; Ok(buffer) @@ -366,11 +366,8 @@ where /// Format message of an event. /// /// Examples: "[FN_WITHOUT_COLON - EVENT] Message" - fn event_message<S>( - span: &Option<&SpanRef<'_, S>>, - event: &Event<'_>, - storage: &mut Storage<'_>, - ) where + fn event_message<S>(span: Option<&SpanRef<'_, S>>, event: &Event<'_>, storage: &mut Storage<'_>) + where S: Subscriber + for<'a> LookupSpan<'a>, { // Get value of kept "message" or "target" if does not exist. @@ -397,7 +394,7 @@ where // Event could have no span. let span = ctx.lookup_current(); - let result: std::io::Result<Vec<u8>> = self.event_serialize(&span.as_ref(), event); + let result: std::io::Result<Vec<u8>> = self.event_serialize(span.as_ref(), event); if let Ok(formatted) = result { let _ = self.flush(formatted); } diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs index 8c2424d5017..e4b636ac5f1 100644 --- a/crates/scheduler/src/utils.rs +++ b/crates/scheduler/src/utils.rs @@ -321,10 +321,10 @@ pub fn get_schedule_time( pub fn get_pm_schedule_time( mapping: process_data::PaymentMethodsPTMapping, - pm: &enums::PaymentMethod, + pm: enums::PaymentMethod, retry_count: i32, ) -> Option<i32> { - let mapping = match mapping.custom_pm_mapping.get(pm) { + let mapping = match mapping.custom_pm_mapping.get(&pm) { Some(map) => map.clone(), None => mapping.default_mapping, }; diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index 5954f4791a5..9b306ec8b07 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -280,7 +280,7 @@ pub trait DataModelExt { } pub(crate) fn diesel_error_to_data_error( - diesel_error: &diesel_models::errors::DatabaseError, + diesel_error: diesel_models::errors::DatabaseError, ) -> StorageError { match diesel_error { diesel_models::errors::DatabaseError::DatabaseConnectionError => { @@ -293,7 +293,7 @@ pub(crate) fn diesel_error_to_data_error( entity: "entity ", key: None, }, - _ => StorageError::DatabaseError(error_stack::report!(*diesel_error)), + _ => StorageError::DatabaseError(error_stack::report!(diesel_error)), } } diff --git a/crates/storage_impl/src/lookup.rs b/crates/storage_impl/src/lookup.rs index eec85e267b9..2f8a743a81a 100644 --- a/crates/storage_impl/src/lookup.rs +++ b/crates/storage_impl/src/lookup.rs @@ -44,7 +44,7 @@ impl<T: DatabaseStore> ReverseLookupInterface for RouterStore<T> { .await .change_context(errors::StorageError::DatabaseConnectionError)?; new.insert(&conn).await.map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } @@ -58,7 +58,7 @@ impl<T: DatabaseStore> ReverseLookupInterface for RouterStore<T> { DieselReverseLookup::find_by_lookup_id(id, &conn) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 4eedfd5005e..06c7fefe85f 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -60,7 +60,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .insert(&conn) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) @@ -83,7 +83,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .insert(&conn) .await .map_err(|error| { - let new_error = diesel_error_to_data_error(error.current_context()); + let new_error = diesel_error_to_data_error(*error.current_context()); error.change_context(new_error) })? .convert( @@ -108,7 +108,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .update_with_attempt_id(&conn, payment_attempt.to_storage_model()) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) @@ -135,7 +135,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { ) .await .map_err(|error| { - let new_error = diesel_error_to_data_error(error.current_context()); + let new_error = diesel_error_to_data_error(*error.current_context()); error.change_context(new_error) })? .convert( @@ -165,7 +165,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { ) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) @@ -187,7 +187,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { ) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) @@ -209,7 +209,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { ) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) @@ -231,7 +231,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { ) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) @@ -255,7 +255,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { ) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })? .convert( @@ -286,7 +286,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { ) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) @@ -313,7 +313,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { DieselPaymentAttempt::get_filters_for_payments(&conn, intents.as_slice(), merchant_id) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map( @@ -352,7 +352,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { ) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) @@ -370,7 +370,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { DieselPaymentAttempt::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(|a| { @@ -393,7 +393,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { DieselPaymentAttempt::find_by_merchant_id_attempt_id(&conn, merchant_id, attempt_id) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) @@ -413,7 +413,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { DieselPaymentAttempt::find_by_id(&conn, attempt_id) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })? .convert( @@ -464,7 +464,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { ) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index 15f1aa24370..ebf75a58b2c 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -297,7 +297,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { DieselPaymentIntent::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }; @@ -358,7 +358,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { let diesel_payment_intent = DieselPaymentIntent::find_by_global_id(&conn, id) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; @@ -481,7 +481,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { .insert(&conn) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; @@ -515,7 +515,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { .update(&conn, diesel_payment_intent_update) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; @@ -550,7 +550,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { .update(&conn, diesel_payment_intent_update) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; @@ -579,7 +579,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { DieselPaymentIntent::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .async_and_then(|diesel_payment_intent| async { @@ -608,7 +608,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { let diesel_payment_intent = DieselPaymentIntent::find_by_global_id(&conn, id) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rs index 3ac66a2c301..caefa4eeda8 100644 --- a/crates/storage_impl/src/payouts/payout_attempt.rs +++ b/crates/storage_impl/src/payouts/payout_attempt.rs @@ -395,7 +395,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> { .insert(&conn) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PayoutAttempt::from_storage_model) @@ -415,7 +415,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> { .update_with_attempt_id(&conn, payout.to_storage_model()) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PayoutAttempt::from_storage_model) @@ -437,7 +437,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> { .await .map(PayoutAttempt::from_storage_model) .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } @@ -458,7 +458,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> { .await .map(PayoutAttempt::from_storage_model) .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } @@ -479,7 +479,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> { DieselPayoutAttempt::get_filters_for_payouts(&conn, payouts.as_slice(), merchant_id) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map( diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs index 2f6540732fd..0c69b2f2412 100644 --- a/crates/storage_impl/src/payouts/payouts.rs +++ b/crates/storage_impl/src/payouts/payouts.rs @@ -235,7 +235,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> { DieselPayouts::find_by_merchant_id_payout_id(&conn, merchant_id, payout_id) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }; @@ -283,7 +283,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> { DieselPayouts::find_optional_by_merchant_id_payout_id(&conn, merchant_id, payout_id) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }; @@ -423,7 +423,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> { .insert(&conn) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(Payouts::from_storage_model) @@ -443,7 +443,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> { .update(&conn, payout.to_storage_model()) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(Payouts::from_storage_model) @@ -461,7 +461,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> { .await .map(Payouts::from_storage_model) .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } @@ -478,7 +478,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> { .await .map(|x| x.map(Payouts::from_storage_model)) .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } @@ -814,7 +814,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> { ) .await .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); + let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }
chore
enable `clippy::trivially_copy_pass_by_ref` lint and address it (#6724)
897e264ad9e26df9877a18eef26a24e05de78528
2024-03-08 19:16:35
Hrithikesh
feat(core): add core functions for external authentication (#3969)
false
diff --git a/crates/cards/src/validate.rs b/crates/cards/src/validate.rs index ffe96fc13da..14d4c6e4c12 100644 --- a/crates/cards/src/validate.rs +++ b/crates/cards/src/validate.rs @@ -52,7 +52,15 @@ impl FromStr for CardNumber { fn from_str(s: &str) -> Result<Self, Self::Err> { // Valid test cards for threedsecureio - let valid_test_cards = ["4000100511112003", "6000100611111203", "3000100811111072"]; + let valid_test_cards = match router_env::which() { + router_env::Env::Development | router_env::Env::Sandbox => vec![ + "4000100511112003", + "6000100611111203", + "3000100811111072", + "9000100111111111", + ], + router_env::Env::Production => vec![], + }; if luhn::valid(s) || valid_test_cards.contains(&s) { let cc_no_whitespace: String = s.split_whitespace().collect(); Ok(Self(StrongSecret::from_str(&cc_no_whitespace)?)) diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs index c395ae3df92..b839fcc9b63 100644 --- a/crates/diesel_models/src/query.rs +++ b/crates/diesel_models/src/query.rs @@ -6,6 +6,7 @@ mod capture; pub mod cards_info; pub mod configs; +pub mod authentication; pub mod authorization; pub mod blocklist; pub mod blocklist_fingerprint; diff --git a/crates/router/src/core/authentication.rs b/crates/router/src/core/authentication.rs index cd408564ea0..27c71ffb088 100644 --- a/crates/router/src/core/authentication.rs +++ b/crates/router/src/core/authentication.rs @@ -1 +1,226 @@ +pub(crate) mod utils; + +pub mod transformers; pub mod types; + +use api_models::payments; +use common_enums::Currency; +use common_utils::{errors::CustomResult, ext_traits::ValueExt}; +use error_stack::ResultExt; +use masking::PeekInterface; + +use super::errors; +use crate::{ + core::{errors::ApiErrorResponse, payments as payments_core}, + routes::AppState, + types::{self as core_types, api, authentication::AuthenticationResponseData, storage}, + utils::OptionExt, +}; + +#[allow(clippy::too_many_arguments)] +pub async fn perform_authentication( + state: &AppState, + authentication_connector: String, + payment_method_data: payments::PaymentMethodData, + payment_method: common_enums::PaymentMethod, + billing_address: api_models::payments::Address, + shipping_address: Option<api_models::payments::Address>, + browser_details: Option<core_types::BrowserInformation>, + business_profile: core_types::storage::BusinessProfile, + merchant_connector_account: payments_core::helpers::MerchantConnectorAccountType, + amount: Option<i64>, + currency: Option<Currency>, + message_category: api::authentication::MessageCategory, + device_channel: payments::DeviceChannel, + authentication_data: (types::AuthenticationData, storage::Authentication), + return_url: Option<String>, + sdk_information: Option<payments::SdkInformation>, + threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator, + email: Option<common_utils::pii::Email>, +) -> CustomResult<core_types::api::authentication::AuthenticationResponse, ApiErrorResponse> { + let router_data = transformers::construct_authentication_router_data( + authentication_connector.clone(), + payment_method_data, + payment_method, + billing_address, + shipping_address, + browser_details, + amount, + currency, + message_category, + device_channel, + business_profile, + merchant_connector_account, + authentication_data.clone(), + return_url, + sdk_information, + threeds_method_comp_ind, + email, + )?; + let response = + utils::do_auth_connector_call(state, authentication_connector.clone(), router_data).await?; + let (_authentication, _authentication_data) = + utils::update_trackers(state, response.clone(), authentication_data.1, None, None).await?; + let authentication_response = + response + .response + .map_err(|err| ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: authentication_connector, + status_code: err.status_code, + reason: err.reason, + })?; + match authentication_response { + AuthenticationResponseData::AuthNResponse { + authn_flow_type, + trans_status, + .. + } => Ok(match authn_flow_type { + core_types::authentication::AuthNFlowType::Challenge(challenge_params) => { + core_types::api::AuthenticationResponse { + trans_status, + acs_url: challenge_params.acs_url, + challenge_request: challenge_params.challenge_request, + acs_reference_number: challenge_params.acs_reference_number, + acs_trans_id: challenge_params.acs_trans_id, + three_dsserver_trans_id: challenge_params.three_dsserver_trans_id, + acs_signed_content: challenge_params.acs_signed_content, + } + } + core_types::authentication::AuthNFlowType::Frictionless => { + core_types::api::AuthenticationResponse { + trans_status, + acs_url: None, + challenge_request: None, + acs_reference_number: None, + acs_trans_id: None, + three_dsserver_trans_id: None, + acs_signed_content: None, + } + } + }), + _ => Err(errors::ApiErrorResponse::InternalServerError.into()) + .attach_printable("unexpected response in authentication flow")?, + } +} + +pub async fn perform_post_authentication<F: Clone + Send>( + state: &AppState, + authentication_connector: String, + business_profile: core_types::storage::BusinessProfile, + merchant_connector_account: payments_core::helpers::MerchantConnectorAccountType, + authentication_flow_input: types::PostAuthenthenticationFlowInput<'_, F>, +) -> CustomResult<(), ApiErrorResponse> { + match authentication_flow_input { + types::PostAuthenthenticationFlowInput::PaymentAuthNFlow { + payment_data, + authentication_data: (authentication, authentication_data), + should_continue_confirm_transaction, + } => { + // let (auth, authentication_data) = authentication; + let updated_authentication = + if !authentication.authentication_status.is_terminal_status() { + let router_data = transformers::construct_post_authentication_router_data( + authentication_connector.clone(), + business_profile, + merchant_connector_account, + authentication_data, + )?; + let router_data = + utils::do_auth_connector_call(state, authentication_connector, router_data) + .await?; + let (updated_authentication, updated_authentication_data) = + utils::update_trackers( + state, + router_data, + authentication, + payment_data.token.clone(), + None, + ) + .await?; + payment_data.authentication = Some(( + updated_authentication.clone(), + updated_authentication_data.unwrap_or_default(), + )); + updated_authentication + } else { + authentication + }; + //If authentication is not successful, skip the payment connector flows and mark the payment as failure + if !(updated_authentication.authentication_status + == api_models::enums::AuthenticationStatus::Success) + { + *should_continue_confirm_transaction = false; + } + } + types::PostAuthenthenticationFlowInput::PaymentMethodAuthNFlow { other_fields: _ } => { + // todo!("Payment method post authN operation"); + } + } + Ok(()) +} + +pub async fn perform_pre_authentication<F: Clone + Send>( + state: &AppState, + authentication_connector_name: String, + authentication_flow_input: types::PreAuthenthenticationFlowInput<'_, F>, + business_profile: &core_types::storage::BusinessProfile, + three_ds_connector_account: payments_core::helpers::MerchantConnectorAccountType, + payment_connector_account: payments_core::helpers::MerchantConnectorAccountType, +) -> CustomResult<(), ApiErrorResponse> { + let authentication = utils::create_new_authentication( + state, + business_profile.merchant_id.clone(), + authentication_connector_name.clone(), + ) + .await?; + match authentication_flow_input { + types::PreAuthenthenticationFlowInput::PaymentAuthNFlow { + payment_data, + should_continue_confirm_transaction, + card_number, + } => { + let router_data = transformers::construct_pre_authentication_router_data( + authentication_connector_name.clone(), + card_number, + &three_ds_connector_account, + business_profile.merchant_id.clone(), + )?; + let router_data = + utils::do_auth_connector_call(state, authentication_connector_name, router_data) + .await?; + let acquirer_details: types::AcquirerDetails = payment_connector_account + .get_metadata() + .get_required_value("merchant_connector_account.metadata")? + .peek() + .clone() + .parse_value("AcquirerDetails") + .change_context(ApiErrorResponse::PreconditionFailed { message: "acquirer_bin and acquirer_merchant_id not found in Payment Connector's Metadata".to_string()})?; + + let (authentication, authentication_data) = utils::update_trackers( + state, + router_data, + authentication, + payment_data.token.clone(), + Some(acquirer_details), + ) + .await?; + if authentication_data + .as_ref() + .is_some_and(|authentication_data| authentication_data.is_separate_authn_required()) + { + *should_continue_confirm_transaction = false; + } + payment_data.authentication = + Some((authentication, authentication_data.unwrap_or_default())); + } + types::PreAuthenthenticationFlowInput::PaymentMethodAuthNFlow { + card_number: _, + other_fields: _, + } => { + // todo!("Payment method authN operation"); + } + }; + Ok(()) +} diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs new file mode 100644 index 00000000000..99f468b4677 --- /dev/null +++ b/crates/router/src/core/authentication/transformers.rs @@ -0,0 +1,189 @@ +use std::marker::PhantomData; + +use api_models::payments; +use common_enums::PaymentMethod; +use common_utils::ext_traits::ValueExt; +use error_stack::ResultExt; + +use crate::{ + core::{ + errors::{self, RouterResult}, + payments::helpers as payments_helpers, + }, + types::{self, storage, transformers::ForeignFrom}, + utils::ext_traits::OptionExt, +}; + +const IRRELEVANT_PAYMENT_ID_IN_AUTHENTICATION_FLOW: &str = + "irrelevant_payment_id_in_AUTHENTICATION_flow"; +const IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW: &str = + "irrelevant_attempt_id_in_AUTHENTICATION_flow"; +const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW: &str = + "irrelevant_connector_request_reference_id_in_AUTHENTICATION_flow"; + +#[allow(clippy::too_many_arguments)] +pub fn construct_authentication_router_data( + authentication_connector: String, + payment_method_data: payments::PaymentMethodData, + payment_method: PaymentMethod, + billing_address: api_models::payments::Address, + shipping_address: Option<api_models::payments::Address>, + browser_details: Option<types::BrowserInformation>, + amount: Option<i64>, + currency: Option<common_enums::Currency>, + message_category: types::api::authentication::MessageCategory, + device_channel: payments::DeviceChannel, + business_profile: storage::BusinessProfile, + merchant_connector_account: payments_helpers::MerchantConnectorAccountType, + authentication_data: (super::types::AuthenticationData, storage::Authentication), + return_url: Option<String>, + sdk_information: Option<api_models::payments::SdkInformation>, + threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator, + email: Option<common_utils::pii::Email>, +) -> RouterResult<types::authentication::ConnectorAuthenticationRouterData> { + let authentication_details: api_models::admin::AuthenticationConnectorDetails = + business_profile + .authentication_connector_details + .clone() + .get_required_value("authentication_details") + .attach_printable("authentication_details not configured by the merchant")? + .parse_value("AuthenticationDetails") + .change_context(errors::ApiErrorResponse::UnprocessableEntity { + message: "Invalid data format found for authentication_details".into(), + }) + .attach_printable("Error while parsing authentication_details from merchant_account")?; + let router_request = types::authentication::ConnectorAuthenticationRequestData { + payment_method_data, + billing_address, + shipping_address, + browser_details, + amount, + currency, + message_category, + device_channel, + authentication_data, + return_url, + sdk_information, + email, + three_ds_requestor_url: authentication_details.three_ds_requestor_url, + threeds_method_comp_ind, + }; + construct_router_data( + authentication_connector, + payment_method, + business_profile.merchant_id.clone(), + types::PaymentAddress::default(), + router_request, + &merchant_connector_account, + ) +} + +pub fn construct_post_authentication_router_data( + authentication_connector: String, + business_profile: storage::BusinessProfile, + merchant_connector_account: payments_helpers::MerchantConnectorAccountType, + authentication_data: super::types::AuthenticationData, +) -> RouterResult<types::authentication::ConnectorPostAuthenticationRouterData> { + let router_request = types::authentication::ConnectorPostAuthenticationRequestData { + authentication_data, + }; + construct_router_data( + authentication_connector, + PaymentMethod::default(), + business_profile.merchant_id.clone(), + types::PaymentAddress::default(), + router_request, + &merchant_connector_account, + ) +} + +pub fn construct_pre_authentication_router_data( + authentication_connector: String, + card_holder_account_number: cards::CardNumber, + merchant_connector_account: &payments_helpers::MerchantConnectorAccountType, + merchant_id: String, +) -> RouterResult<types::authentication::PreAuthNRouterData> { + let router_request = types::authentication::PreAuthNRequestData { + card_holder_account_number, + }; + construct_router_data( + authentication_connector, + PaymentMethod::default(), + merchant_id, + types::PaymentAddress::default(), + router_request, + merchant_connector_account, + ) +} + +pub fn construct_router_data<F: Clone, Req, Res>( + authentication_connector_name: String, + payment_method: PaymentMethod, + merchant_id: String, + address: types::PaymentAddress, + request_data: Req, + merchant_connector_account: &payments_helpers::MerchantConnectorAccountType, +) -> RouterResult<types::RouterData<F, Req, Res>> { + let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); + let auth_type: types::ConnectorAuthType = merchant_connector_account + .get_connector_account_details() + .parse_value("ConnectorAuthType") + .change_context(errors::ApiErrorResponse::InternalServerError)?; + Ok(types::RouterData { + flow: PhantomData, + merchant_id, + customer_id: None, + connector_customer: None, + connector: authentication_connector_name, + payment_id: IRRELEVANT_PAYMENT_ID_IN_AUTHENTICATION_FLOW.to_owned(), + attempt_id: IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW.to_owned(), + status: common_enums::AttemptStatus::default(), + payment_method, + connector_auth_type: auth_type, + description: None, + return_url: None, + address, + auth_type: common_enums::AuthenticationType::NoThreeDs, + connector_meta_data: merchant_connector_account.get_metadata(), + amount_captured: None, + access_token: None, + session_token: None, + reference_id: None, + payment_method_token: None, + recurring_mandate_payment_data: None, + preprocessing_id: None, + payment_method_balance: None, + connector_api_version: None, + request: request_data, + response: Err(types::ErrorResponse::default()), + payment_method_id: None, + connector_request_reference_id: + IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW.to_owned(), + #[cfg(feature = "payouts")] + payout_method_data: None, + #[cfg(feature = "payouts")] + quote_id: None, + test_mode, + connector_http_status_code: None, + external_latency: None, + apple_pay_flow: None, + frm_metadata: None, + dispute_id: None, + refund_id: None, + }) +} + +impl ForeignFrom<payments::TransactionStatus> for common_enums::AuthenticationStatus { + fn foreign_from(trans_status: payments::TransactionStatus) -> Self { + match trans_status { + api_models::payments::TransactionStatus::Success => Self::Success, + api_models::payments::TransactionStatus::Failure + | api_models::payments::TransactionStatus::Rejected + | api_models::payments::TransactionStatus::VerificationNotPerformed + | api_models::payments::TransactionStatus::NotVerified => Self::Failed, + api_models::payments::TransactionStatus::ChallengeRequired + | api_models::payments::TransactionStatus::ChallengeRequiredDecoupledAuthentication + | api_models::payments::TransactionStatus::InformationOnly => Self::Pending, + } + } +} diff --git a/crates/router/src/core/authentication/types.rs b/crates/router/src/core/authentication/types.rs index c6816bacf8d..b7c61c14d4d 100644 --- a/crates/router/src/core/authentication/types.rs +++ b/crates/router/src/core/authentication/types.rs @@ -53,7 +53,6 @@ pub struct ThreeDsMethodData { pub three_ds_method_data: String, pub three_ds_method_url: Option<String>, } - #[derive(Clone, Default, Debug, Serialize, Deserialize)] pub struct AcquirerDetails { pub acquirer_bin: String, diff --git a/crates/router/src/core/authentication/utils.rs b/crates/router/src/core/authentication/utils.rs new file mode 100644 index 00000000000..059b0950bad --- /dev/null +++ b/crates/router/src/core/authentication/utils.rs @@ -0,0 +1,250 @@ +use common_enums::DecoupledAuthenticationType; +use common_utils::ext_traits::{Encode, ValueExt}; +use error_stack::ResultExt; + +use super::types::{AuthenticationData, ThreeDsMethodData}; +use crate::{ + consts, + core::{ + errors::{ApiErrorResponse, ConnectorErrorExt, StorageErrorExt}, + payments, + }, + errors::RouterResult, + routes::AppState, + services::{self, execute_connector_processing_step}, + types::{ + api, + authentication::{AuthNFlowType, AuthenticationResponseData}, + storage, + transformers::ForeignFrom, + RouterData, + }, + utils::OptionExt, +}; + +pub async fn update_trackers<F: Clone, Req>( + state: &AppState, + router_data: RouterData<F, Req, AuthenticationResponseData>, + authentication: storage::Authentication, + token: Option<String>, + acquirer_details: Option<super::types::AcquirerDetails>, +) -> RouterResult<(storage::Authentication, Option<AuthenticationData>)> { + let authentication_data_option = authentication + .authentication_data + .as_ref() + .map(|authentication_data| { + authentication_data + .to_owned() + .parse_value::<AuthenticationData>("AuthenticationData") + .change_context(ApiErrorResponse::InternalServerError) + }) + .transpose()?; + + let (authentication_update, updated_authentication_data) = match router_data.response { + Ok(response) => match response { + AuthenticationResponseData::PreAuthNResponse { + threeds_server_transaction_id, + maximum_supported_3ds_version, + connector_authentication_id, + three_ds_method_data, + three_ds_method_url, + message_version, + connector_metadata, + } => { + let three_ds_method_data = ThreeDsMethodData { + three_ds_method_data, + three_ds_method_data_submission: three_ds_method_url.is_some(), + three_ds_method_url, + }; + let authentication_data = AuthenticationData { + maximum_supported_version: maximum_supported_3ds_version, + threeds_server_transaction_id, + three_ds_method_data, + message_version, + acquirer_details, + ..Default::default() + }; + ( + storage::AuthenticationUpdate::AuthenticationDataUpdate { + authentication_data: Some( + Encode::encode_to_value(&authentication_data) + .change_context(ApiErrorResponse::InternalServerError)?, + ), + connector_authentication_id: Some(connector_authentication_id), + payment_method_id: token.map(|token| format!("eph_{}", token)), + authentication_type: None, + authentication_status: Some(common_enums::AuthenticationStatus::Started), + authentication_lifecycle_status: None, + connector_metadata, + }, + Some(authentication_data), + ) + } + AuthenticationResponseData::AuthNResponse { + authn_flow_type, + authentication_value: cavv, + trans_status, + } => { + let authentication_data = authentication_data_option + .get_required_value("authentication_data") + .attach_printable( + "AuthenticationData is required to make Authentication call", + )?; + let authentication_data = AuthenticationData { + authn_flow_type: Some(authn_flow_type.clone()), + cavv, + trans_status: trans_status.clone(), + ..authentication_data + }; + ( + storage::AuthenticationUpdate::AuthenticationDataUpdate { + authentication_data: Some( + Encode::encode_to_value(&authentication_data) + .change_context(ApiErrorResponse::InternalServerError)?, + ), + connector_authentication_id: None, + payment_method_id: None, + authentication_type: Some(match authn_flow_type { + AuthNFlowType::Challenge { .. } => { + DecoupledAuthenticationType::Challenge + } + AuthNFlowType::Frictionless => { + DecoupledAuthenticationType::Frictionless + } + }), + authentication_status: Some( + common_enums::AuthenticationStatus::foreign_from(trans_status), + ), + authentication_lifecycle_status: None, + connector_metadata: None, + }, + Some(authentication_data), + ) + } + AuthenticationResponseData::PostAuthNResponse { + trans_status, + authentication_value, + eci, + } => { + let authentication_data = authentication_data_option + .get_required_value("authentication_data") + .attach_printable( + "AuthenticationData is required to make Post Authentication call", + )?; + let authentication_data = AuthenticationData { + cavv: authentication_value, + eci, + trans_status: trans_status.clone(), + ..authentication_data + }; + ( + storage::AuthenticationUpdate::AuthenticationDataUpdate { + authentication_data: Some( + Encode::encode_to_value(&authentication_data) + .change_context(ApiErrorResponse::InternalServerError)?, + ), + connector_authentication_id: None, + payment_method_id: None, + authentication_type: None, + authentication_status: Some( + common_enums::AuthenticationStatus::foreign_from(trans_status), + ), + authentication_lifecycle_status: None, + connector_metadata: None, + }, + Some(authentication_data), + ) + } + }, + Err(error) => ( + storage::AuthenticationUpdate::ErrorUpdate { + connector_authentication_id: error.connector_transaction_id, + authentication_status: common_enums::AuthenticationStatus::Failed, + error_message: Some(error.message), + error_code: Some(error.code), + }, + authentication_data_option, + ), + }; + let authentication_result = state + .store + .update_authentication_by_merchant_id_authentication_id( + authentication, + authentication_update, + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Error while updating authentication"); + authentication_result.map(|authentication| (authentication, updated_authentication_data)) +} + +impl ForeignFrom<common_enums::AuthenticationStatus> for common_enums::AttemptStatus { + fn foreign_from(from: common_enums::AuthenticationStatus) -> Self { + match from { + common_enums::AuthenticationStatus::Started + | common_enums::AuthenticationStatus::Pending => Self::AuthenticationPending, + common_enums::AuthenticationStatus::Success => Self::AuthenticationSuccessful, + common_enums::AuthenticationStatus::Failed => Self::AuthenticationFailed, + } + } +} + +pub async fn create_new_authentication( + state: &AppState, + merchant_id: String, + authentication_connector: String, +) -> RouterResult<storage::Authentication> { + let authentication_id = + common_utils::generate_id_with_default_len(consts::AUTHENTICATION_ID_PREFIX); + let new_authorization = storage::AuthenticationNew { + authentication_id: authentication_id.clone(), + merchant_id, + authentication_connector, + connector_authentication_id: None, + authentication_data: None, + payment_method_id: "".into(), + authentication_type: None, + authentication_status: common_enums::AuthenticationStatus::Started, + authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus::Unused, + error_message: None, + error_code: None, + connector_metadata: None, + }; + state + .store + .insert_authentication(new_authorization) + .await + .to_duplicate_response(ApiErrorResponse::GenericDuplicateError { + message: format!( + "Authentication with authentication_id {} already exists", + authentication_id + ), + }) +} + +pub async fn do_auth_connector_call<F, Req, Res>( + state: &AppState, + authentication_connector_name: String, + router_data: RouterData<F, Req, Res>, +) -> RouterResult<RouterData<F, Req, Res>> +where + Req: std::fmt::Debug + Clone + 'static, + Res: std::fmt::Debug + Clone + 'static, + F: std::fmt::Debug + Clone + 'static, + dyn api::Connector + Sync: services::api::ConnectorIntegration<F, Req, Res>, +{ + let connector_data = + api::AuthenticationConnectorData::get_connector_by_name(&authentication_connector_name)?; + let connector_integration: services::BoxedConnectorIntegration<'_, F, Req, Res> = + connector_data.connector.get_connector_integration(); + let router_data = execute_connector_processing_step( + state, + connector_integration, + &router_data, + payments::CallConnectorAction::Trigger, + None, + ) + .await + .to_payment_failed_response()?; + Ok(router_data) +} diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 002502e9d9d..9b06e657f2a 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -41,7 +41,8 @@ use self::{ routing::{self as self_routing, SessionFlowRoutingInput}, }; use super::{ - errors::StorageErrorExt, payment_methods::surcharge_decision_configs, routing::TransactionData, + authentication::types::AuthenticationData, errors::StorageErrorExt, + payment_methods::surcharge_decision_configs, routing::TransactionData, }; #[cfg(feature = "frm")] use crate::core::fraud_check as frm_core; @@ -2073,6 +2074,7 @@ where pub payment_link_data: Option<api_models::payments::PaymentLinkResponse>, pub incremental_authorization_details: Option<IncrementalAuthorizationDetails>, pub authorizations: Vec<diesel_models::authorization::Authorization>, + pub authentication: Option<(storage::Authentication, AuthenticationData)>, pub frm_metadata: Option<serde_json::Value>, } diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index a38c7bbdd3c..3068e7f238e 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -177,6 +177,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> incremental_authorization_details: None, authorizations: vec![], frm_metadata: None, + authentication: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 1b09e9abce5..aa995d8f7a0 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -185,6 +185,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> incremental_authorization_details: None, authorizations: vec![], frm_metadata: None, + authentication: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index 4a488a07eb3..f5fd9eb60aa 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -229,6 +229,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> incremental_authorization_details: None, authorizations: vec![], frm_metadata: None, + authentication: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 395f8e59dbc..e26228011c2 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -277,6 +277,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], + authentication: None, frm_metadata: None, }; diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 529565c71e8..72c8131b802 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -576,6 +576,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> incremental_authorization_details: None, authorizations: vec![], frm_metadata: request.frm_metadata.clone(), + authentication: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 5ec8bfaf550..d75cecd7e64 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -417,6 +417,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> payment_link_data, incremental_authorization_details: None, authorizations: vec![], + authentication: None, frm_metadata: request.frm_metadata.clone(), }; diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index a1416ea1908..2b28195a15c 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -172,6 +172,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], + authentication: None, frm_metadata: None, }; diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index ed3eda8832b..64712881bff 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -197,6 +197,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], + authentication: None, frm_metadata: None, }; diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 650fef7e1bf..f90a57f5f69 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -175,6 +175,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], + authentication: None, frm_metadata: None, }; diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 70f04ed364d..4cfad8e55a3 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -448,6 +448,7 @@ async fn get_tracker_for_sync< frm_message: frm_response.ok(), incremental_authorization_details: None, authorizations, + authentication: None, frm_metadata: None, }; diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 81efdbabc4c..a669dc32cbc 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -413,6 +413,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], + authentication: None, frm_metadata: request.frm_metadata.clone(), }; diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs index 96cbf9fb9db..76efc7bccaf 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -152,6 +152,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> authorization_id: None, }), authorizations: vec![], + authentication: None, frm_metadata: None, }; diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index d385d94a5de..a6e15be0c09 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -1,5 +1,6 @@ pub mod address; pub mod api_keys; +pub mod authentication; pub mod authorization; pub mod blocklist; pub mod blocklist_fingerprint; @@ -113,6 +114,7 @@ pub trait StorageInterface: + user::sample_data::BatchSampleDataInterface + health_check::HealthCheckDbInterface + role::RoleInterface + + authentication::AuthenticationInterface + 'static { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 8ba977befcc..4509da8f0ff 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -33,6 +33,7 @@ use crate::{ db::{ address::AddressInterface, api_keys::ApiKeyInterface, + authentication::AuthenticationInterface, authorization::AuthorizationInterface, business_profile::BusinessProfileInterface, capture::CaptureInterface, @@ -2347,6 +2348,41 @@ impl AuthorizationInterface for KafkaStore { } } +#[async_trait::async_trait] +impl AuthenticationInterface for KafkaStore { + async fn insert_authentication( + &self, + authentication: storage::AuthenticationNew, + ) -> CustomResult<storage::Authentication, errors::StorageError> { + self.diesel_store + .insert_authentication(authentication) + .await + } + + async fn find_authentication_by_merchant_id_authentication_id( + &self, + merchant_id: String, + authentication_id: String, + ) -> CustomResult<storage::Authentication, errors::StorageError> { + self.diesel_store + .find_authentication_by_merchant_id_authentication_id(merchant_id, authentication_id) + .await + } + + async fn update_authentication_by_merchant_id_authentication_id( + &self, + previous_state: storage::Authentication, + authentication_update: storage::AuthenticationUpdate, + ) -> CustomResult<storage::Authentication, errors::StorageError> { + self.diesel_store + .update_authentication_by_merchant_id_authentication_id( + previous_state, + authentication_update, + ) + .await + } +} + #[async_trait::async_trait] impl HealthCheckDbInterface for KafkaStore { async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> { diff --git a/crates/router/src/types/api/authentication.rs b/crates/router/src/types/api/authentication.rs index 4c662c08fac..ab00872fe85 100644 --- a/crates/router/src/types/api/authentication.rs +++ b/crates/router/src/types/api/authentication.rs @@ -1,6 +1,11 @@ +use std::str::FromStr; + use api_models::enums; +use common_utils::errors::CustomResult; +use error_stack::{IntoReport, ResultExt}; use super::BoxedConnector; +use crate::core::errors; #[derive(Debug, Clone)] pub struct PreAuthentication; @@ -82,3 +87,32 @@ pub struct AuthenticationConnectorData { pub connector: BoxedConnector, pub connector_name: enums::AuthenticationConnectors, } + +impl AuthenticationConnectorData { + pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> { + let connector_name = enums::AuthenticationConnectors::from_str(name) + .into_report() + .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) + .attach_printable_lazy(|| format!("unable to parse connector: {name}"))?; + let connector = Self::convert_connector(connector_name)?; + Ok(Self { + connector, + connector_name, + }) + } + + fn convert_connector( + connector_name: enums::AuthenticationConnectors, + ) -> CustomResult<BoxedConnector, errors::ApiErrorResponse> { + match connector_name { + enums::AuthenticationConnectors::Threedsecureio => { + Err(errors::ApiErrorResponse::NotImplemented { + message: errors::NotImplementedMessage::Reason( + "external 3ds authentication is not fully implemented".to_string(), + ), + } + .into()) + } + } + } +} diff --git a/crates/router/src/types/authentication.rs b/crates/router/src/types/authentication.rs index dfce745e791..93eb5f37ffb 100644 --- a/crates/router/src/types/authentication.rs +++ b/crates/router/src/types/authentication.rs @@ -22,7 +22,7 @@ pub enum AuthenticationResponseData { }, AuthNResponse { authn_flow_type: AuthNFlowType, - cavv: Option<String>, + authentication_value: Option<String>, trans_status: api_models::payments::TransactionStatus, }, PostAuthNResponse { @@ -51,7 +51,8 @@ pub enum AuthNFlowType { #[derive(Clone, Default, Debug)] pub struct PreAuthNRequestData { // card number - pub card_holder_account_number: CardNumber, + #[allow(dead_code)] + pub(crate) card_holder_account_number: CardNumber, } #[derive(Clone, Debug)] diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs index a1518cea431..023f30db325 100644 --- a/crates/storage_impl/src/mock_db.rs +++ b/crates/storage_impl/src/mock_db.rs @@ -45,6 +45,7 @@ pub struct MockDb { pub user_roles: Arc<Mutex<Vec<store::user_role::UserRole>>>, pub authorizations: Arc<Mutex<Vec<store::authorization::Authorization>>>, pub dashboard_metadata: Arc<Mutex<Vec<store::user::dashboard_metadata::DashboardMetadata>>>, + pub authentications: Arc<Mutex<Vec<store::authentication::Authentication>>>, pub roles: Arc<Mutex<Vec<store::role::Role>>>, } @@ -83,6 +84,7 @@ impl MockDb { user_roles: Default::default(), authorizations: Default::default(), dashboard_metadata: Default::default(), + authentications: Default::default(), roles: Default::default(), }) }
feat
add core functions for external authentication (#3969)
49892b261ef9bd0a54b8e4568d40463fca26862b
2024-08-06 15:05:40
Narayan Bhat
refactor(merchant_account_v2): recreate id and remove deprecated fields from merchant account (#5493)
false
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 040df7d84f0..a3e67c1d1c8 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -7059,7 +7059,7 @@ }, "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.", + "description": "Metadata is useful for storing additional, unstructured information on an object.", "nullable": true }, "routing_algorithm": { @@ -7221,7 +7221,7 @@ }, "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.", + "description": "Metadata is useful for storing additional, unstructured information on an object.", "nullable": true }, "routing_algorithm": { @@ -11757,7 +11757,7 @@ }, "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.", + "description": "Metadata is useful for storing additional, unstructured information on an object.", "nullable": true }, "publishable_key": { @@ -11889,7 +11889,7 @@ }, "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.", + "description": "Metadata is useful for storing additional, unstructured information on an object.", "nullable": true }, "test_mode": { @@ -11999,7 +11999,7 @@ }, "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.", + "description": "Metadata is useful for storing additional, unstructured information on an object.", "nullable": true } } @@ -12118,7 +12118,7 @@ }, "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.", + "description": "Metadata is useful for storing additional, unstructured information on an object.", "nullable": true }, "test_mode": { @@ -12285,7 +12285,7 @@ }, "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.", + "description": "Metadata is useful for storing additional, unstructured information on an object.", "nullable": true }, "test_mode": { @@ -12436,7 +12436,7 @@ }, "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.", + "description": "Metadata is useful for storing additional, unstructured information on an object.", "nullable": true }, "test_mode": { diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index c80a188534f..c6a6fe17222 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -260,6 +260,11 @@ pub struct MerchantAccountMetadata { #[serde(flatten)] pub data: Option<pii::SecretSerdeValue>, } + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MerchantAccountUpdate { @@ -310,7 +315,7 @@ pub struct MerchantAccountUpdate { #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, - /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, @@ -339,6 +344,110 @@ pub struct MerchantAccountUpdate { pub pm_collect_link_config: Option<BusinessCollectLinkConfig>, } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] +impl MerchantAccountUpdate { + pub fn get_primary_details_as_value( + &self, + ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { + self.primary_business_details + .as_ref() + .map(|primary_business_details| primary_business_details.encode_to_value()) + .transpose() + } + + pub fn get_pm_link_config_as_value( + &self, + ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { + self.pm_collect_link_config + .as_ref() + .map(|pm_collect_link_config| pm_collect_link_config.encode_to_value()) + .transpose() + } + + pub fn get_merchant_details_as_secret( + &self, + ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { + self.merchant_details + .as_ref() + .map(|merchant_details| merchant_details.encode_to_value().map(Secret::new)) + .transpose() + } + + pub fn get_metadata_as_secret( + &self, + ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { + self.metadata + .as_ref() + .map(|metadata| metadata.encode_to_value().map(Secret::new)) + .transpose() + } + + pub fn get_webhook_details_as_value( + &self, + ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { + self.webhook_details + .as_ref() + .map(|webhook_details| webhook_details.encode_to_value()) + .transpose() + } + + pub fn parse_routing_algorithm(&self) -> CustomResult<(), errors::ParsingError> { + match self.routing_algorithm { + Some(ref routing_algorithm) => { + let _: routing::RoutingAlgorithm = + routing_algorithm.clone().parse_value("RoutingAlgorithm")?; + Ok(()) + } + None => Ok(()), + } + } + + // Get the enable payment response hash as a boolean, where the default value is true + pub fn get_enable_payment_response_hash(&self) -> bool { + self.enable_payment_response_hash.unwrap_or(true) + } +} + +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] +#[serde(deny_unknown_fields)] +pub struct MerchantAccountUpdate { + /// Name of the Merchant Account + #[schema(example = "NewAge Retailer")] + pub merchant_name: Option<String>, + + /// Details about the merchant + pub merchant_details: Option<MerchantDetails>, + + /// Metadata is useful for storing additional, unstructured information on an object. + #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] + pub metadata: Option<pii::SecretSerdeValue>, +} + +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +impl MerchantAccountUpdate { + pub fn get_merchant_details_as_secret( + &self, + ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { + self.merchant_details + .as_ref() + .map(|merchant_details| merchant_details.encode_to_value().map(Secret::new)) + .transpose() + } + + pub fn get_metadata_as_secret( + &self, + ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { + self.metadata + .as_ref() + .map(|metadata| metadata.encode_to_value().map(Secret::new)) + .transpose() + } +} + #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "merchant_account_v2") @@ -462,9 +571,6 @@ pub struct MerchantAccountResponse { #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub organization_id: id_type::OrganizationId, - /// A boolean value to indicate if the merchant has recon service is enabled or not, by default value is false - pub is_recon_enabled: bool, - /// Used to indicate the status of the recon module for a merchant account #[schema(value_type = ReconStatus, example = "not_requested")] pub recon_status: api_enums::ReconStatus, @@ -636,7 +742,7 @@ pub struct MerchantConnectorCreate { }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, - /// 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. + /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, @@ -766,7 +872,7 @@ pub struct MerchantConnectorCreate { }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, - /// 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. + /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, @@ -1001,7 +1107,7 @@ pub struct MerchantConnectorResponse { }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, - /// 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. + /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, @@ -1108,7 +1214,7 @@ pub struct MerchantConnectorResponse { }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, - /// 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. + /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, @@ -1220,7 +1326,7 @@ pub struct MerchantConnectorListResponse { ]))] pub payment_methods_enabled: Option<Vec<PaymentMethodsEnabled>>, - /// 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. + /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, @@ -1329,7 +1435,7 @@ pub struct MerchantConnectorListResponse { ]))] pub payment_methods_enabled: Option<Vec<PaymentMethodsEnabled>>, - /// 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. + /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, @@ -1424,7 +1530,7 @@ pub struct MerchantConnectorUpdate { }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, - /// 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. + /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, @@ -1722,7 +1828,7 @@ pub struct MerchantConnectorDetails { /// Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: pii::SecretSerdeValue, - /// 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. + /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, } @@ -1752,7 +1858,7 @@ pub struct BusinessProfileCreate { /// Webhook related details pub webhook_details: Option<WebhookDetails>, - /// 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. + /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, @@ -1845,7 +1951,7 @@ pub struct BusinessProfileResponse { #[schema(value_type = Option<WebhookDetails>)] pub webhook_details: Option<pii::SecretSerdeValue>, - /// 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. + /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, @@ -1933,7 +2039,7 @@ pub struct BusinessProfileUpdate { /// Webhook related details pub webhook_details: Option<WebhookDetails>, - /// 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. + /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, diff --git a/crates/api_models/src/conditional_configs.rs b/crates/api_models/src/conditional_configs.rs index 46bad3e9e86..555e7bd955f 100644 --- a/crates/api_models/src/conditional_configs.rs +++ b/crates/api_models/src/conditional_configs.rs @@ -97,6 +97,7 @@ pub struct DecisionManagerRequest { pub name: Option<String>, pub program: Option<Program<ConditionalConfigs>>, } + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum DecisionManager { diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rs index 3aa4088f3b0..907162da7c2 100644 --- a/crates/diesel_models/src/merchant_account.rs +++ b/crates/diesel_models/src/merchant_account.rs @@ -146,32 +146,18 @@ impl From<MerchantAccountSetter> for MerchantAccount { )] #[diesel(table_name = merchant_account, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct MerchantAccount { - pub return_url: Option<String>, - pub enable_payment_response_hash: bool, - pub payment_response_hash_key: Option<String>, - pub redirect_to_merchant_with_http_post: bool, pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, - pub webhook_details: Option<serde_json::Value>, - pub sub_merchants_enabled: Option<bool>, - pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, - pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, - pub primary_business_details: serde_json::Value, - pub intent_fulfillment_time: Option<i64>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, - pub is_recon_enabled: bool, - pub default_profile: Option<String>, pub recon_status: storage_enums::ReconStatus, - pub payment_link_config: Option<serde_json::Value>, - pub pm_collect_link_config: Option<serde_json::Value>, pub id: common_utils::id_type::MerchantId, } @@ -180,32 +166,18 @@ impl From<MerchantAccountSetter> for MerchantAccount { fn from(item: MerchantAccountSetter) -> Self { Self { id: item.id, - return_url: item.return_url, - enable_payment_response_hash: item.enable_payment_response_hash, - payment_response_hash_key: item.payment_response_hash_key, - redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, merchant_name: item.merchant_name, merchant_details: item.merchant_details, - webhook_details: item.webhook_details, - sub_merchants_enabled: item.sub_merchants_enabled, - parent_merchant_id: item.parent_merchant_id, publishable_key: item.publishable_key, storage_scheme: item.storage_scheme, - locker_id: item.locker_id, metadata: item.metadata, - routing_algorithm: item.routing_algorithm, - primary_business_details: item.primary_business_details, - intent_fulfillment_time: item.intent_fulfillment_time, created_at: item.created_at, modified_at: item.modified_at, frm_routing_algorithm: item.frm_routing_algorithm, + routing_algorithm: item.routing_algorithm, payout_routing_algorithm: item.payout_routing_algorithm, organization_id: item.organization_id, - is_recon_enabled: item.is_recon_enabled, - default_profile: item.default_profile, recon_status: item.recon_status, - payment_link_config: item.payment_link_config, - pm_collect_link_config: item.pm_collect_link_config, } } } @@ -213,32 +185,18 @@ impl From<MerchantAccountSetter> for MerchantAccount { #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] pub struct MerchantAccountSetter { pub id: common_utils::id_type::MerchantId, - pub return_url: Option<String>, - pub enable_payment_response_hash: bool, - pub payment_response_hash_key: Option<String>, - pub redirect_to_merchant_with_http_post: bool, pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, - pub webhook_details: Option<serde_json::Value>, - pub sub_merchants_enabled: Option<bool>, - pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, - pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, - pub primary_business_details: serde_json::Value, - pub intent_fulfillment_time: Option<i64>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, - pub is_recon_enabled: bool, - pub default_profile: Option<String>, pub recon_status: storage_enums::ReconStatus, - pub payment_link_config: Option<serde_json::Value>, - pub pm_collect_link_config: Option<serde_json::Value>, } impl MerchantAccount { @@ -298,33 +256,40 @@ pub struct MerchantAccountNew { pub struct MerchantAccountNew { pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, - pub return_url: Option<String>, - pub webhook_details: Option<serde_json::Value>, - pub sub_merchants_enabled: Option<bool>, - pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, - pub enable_payment_response_hash: Option<bool>, - pub payment_response_hash_key: Option<String>, - pub redirect_to_merchant_with_http_post: Option<bool>, pub publishable_key: Option<String>, - pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, - pub primary_business_details: serde_json::Value, - pub intent_fulfillment_time: Option<i64>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, - pub is_recon_enabled: bool, - pub default_profile: Option<String>, pub recon_status: storage_enums::ReconStatus, - pub payment_link_config: Option<serde_json::Value>, - pub pm_collect_link_config: Option<serde_json::Value>, pub id: common_utils::id_type::MerchantId, } -#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] +#[diesel(table_name = merchant_account)] +pub struct MerchantAccountUpdateInternal { + pub merchant_name: Option<Encryption>, + pub merchant_details: Option<Encryption>, + pub publishable_key: Option<String>, + pub storage_scheme: Option<storage_enums::MerchantStorageScheme>, + pub metadata: Option<pii::SecretSerdeValue>, + pub routing_algorithm: Option<serde_json::Value>, + pub modified_at: time::PrimitiveDateTime, + pub frm_routing_algorithm: Option<serde_json::Value>, + pub payout_routing_algorithm: Option<serde_json::Value>, + pub organization_id: Option<common_utils::id_type::OrganizationId>, + pub recon_status: Option<storage_enums::ReconStatus>, +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] +#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] pub struct MerchantAccountUpdateInternal { pub merchant_name: Option<Encryption>, @@ -342,12 +307,12 @@ pub struct MerchantAccountUpdateInternal { pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: Option<serde_json::Value>, - pub modified_at: Option<time::PrimitiveDateTime>, + pub modified_at: time::PrimitiveDateTime, pub intent_fulfillment_time: Option<i64>, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: Option<common_utils::id_type::OrganizationId>, - pub is_recon_enabled: bool, + pub is_recon_enabled: Option<bool>, pub default_profile: Option<Option<String>>, pub recon_status: Option<storage_enums::ReconStatus>, pub payment_link_config: Option<serde_json::Value>, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 23f9dff31ea..91c02b69034 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -639,39 +639,20 @@ diesel::table! { use crate::enums::diesel_exports::*; merchant_account (id) { - #[max_length = 255] - return_url -> Nullable<Varchar>, - enable_payment_response_hash -> Bool, - #[max_length = 255] - payment_response_hash_key -> Nullable<Varchar>, - redirect_to_merchant_with_http_post -> Bool, merchant_name -> Nullable<Bytea>, merchant_details -> Nullable<Bytea>, - webhook_details -> Nullable<Json>, - sub_merchants_enabled -> Nullable<Bool>, - #[max_length = 64] - parent_merchant_id -> Nullable<Varchar>, #[max_length = 128] publishable_key -> Nullable<Varchar>, storage_scheme -> MerchantStorageScheme, - #[max_length = 64] - locker_id -> Nullable<Varchar>, metadata -> Nullable<Jsonb>, routing_algorithm -> Nullable<Json>, - primary_business_details -> Json, - intent_fulfillment_time -> Nullable<Int8>, created_at -> Timestamp, modified_at -> Timestamp, frm_routing_algorithm -> Nullable<Jsonb>, payout_routing_algorithm -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, - is_recon_enabled -> Bool, - #[max_length = 64] - default_profile -> Nullable<Varchar>, recon_status -> ReconStatus, - payment_link_config -> Nullable<Jsonb>, - pm_collect_link_config -> Nullable<Jsonb>, #[max_length = 64] id -> Varchar, } diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs index ce11cd566c6..2452e5091fd 100644 --- a/crates/hyperswitch_domain_models/src/merchant_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_account.rs @@ -130,65 +130,52 @@ impl From<MerchantAccountSetter> for MerchantAccount { /// Set the private fields of merchant account pub struct MerchantAccountSetter { pub id: common_utils::id_type::MerchantId, - pub return_url: Option<String>, - pub enable_payment_response_hash: bool, - pub payment_response_hash_key: Option<String>, - pub redirect_to_merchant_with_http_post: bool, pub merchant_name: OptionalEncryptableName, pub merchant_details: OptionalEncryptableValue, - pub webhook_details: Option<serde_json::Value>, - pub sub_merchants_enabled: Option<bool>, - pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub publishable_key: String, pub storage_scheme: MerchantStorageScheme, - pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, - pub primary_business_details: serde_json::Value, pub frm_routing_algorithm: Option<serde_json::Value>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, - pub intent_fulfillment_time: Option<i64>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, - pub is_recon_enabled: bool, - pub default_profile: Option<String>, pub recon_status: diesel_models::enums::ReconStatus, - pub payment_link_config: Option<serde_json::Value>, - pub pm_collect_link_config: Option<serde_json::Value>, } #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] impl From<MerchantAccountSetter> for MerchantAccount { fn from(item: MerchantAccountSetter) -> Self { + let MerchantAccountSetter { + id, + merchant_name, + merchant_details, + publishable_key, + storage_scheme, + metadata, + routing_algorithm, + frm_routing_algorithm, + created_at, + modified_at, + payout_routing_algorithm, + organization_id, + recon_status, + } = item; Self { - id: item.id, - return_url: item.return_url, - enable_payment_response_hash: item.enable_payment_response_hash, - payment_response_hash_key: item.payment_response_hash_key, - redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, - merchant_name: item.merchant_name, - merchant_details: item.merchant_details, - webhook_details: item.webhook_details, - sub_merchants_enabled: item.sub_merchants_enabled, - parent_merchant_id: item.parent_merchant_id, - publishable_key: item.publishable_key, - storage_scheme: item.storage_scheme, - locker_id: item.locker_id, - metadata: item.metadata, - routing_algorithm: item.routing_algorithm, - primary_business_details: item.primary_business_details, - frm_routing_algorithm: item.frm_routing_algorithm, - created_at: item.created_at, - modified_at: item.modified_at, - intent_fulfillment_time: item.intent_fulfillment_time, - payout_routing_algorithm: item.payout_routing_algorithm, - organization_id: item.organization_id, - is_recon_enabled: item.is_recon_enabled, - default_profile: item.default_profile, - recon_status: item.recon_status, - payment_link_config: item.payment_link_config, - pm_collect_link_config: item.pm_collect_link_config, + id, + merchant_name, + merchant_details, + publishable_key, + storage_scheme, + metadata, + routing_algorithm, + frm_routing_algorithm, + created_at, + modified_at, + payout_routing_algorithm, + organization_id, + recon_status, } } } @@ -197,32 +184,18 @@ impl From<MerchantAccountSetter> for MerchantAccount { #[derive(Clone, Debug, serde::Serialize)] pub struct MerchantAccount { id: common_utils::id_type::MerchantId, - pub return_url: Option<String>, - pub enable_payment_response_hash: bool, - pub payment_response_hash_key: Option<String>, - pub redirect_to_merchant_with_http_post: bool, pub merchant_name: OptionalEncryptableName, pub merchant_details: OptionalEncryptableValue, - pub webhook_details: Option<serde_json::Value>, - pub sub_merchants_enabled: Option<bool>, - pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub publishable_key: String, pub storage_scheme: MerchantStorageScheme, - pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, - pub primary_business_details: serde_json::Value, pub frm_routing_algorithm: Option<serde_json::Value>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, - pub intent_fulfillment_time: Option<i64>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, - pub is_recon_enabled: bool, - pub default_profile: Option<String>, pub recon_status: diesel_models::enums::ReconStatus, - pub payment_link_config: Option<serde_json::Value>, - pub pm_collect_link_config: Option<serde_json::Value>, } impl MerchantAccount { @@ -242,6 +215,10 @@ impl MerchantAccount { } } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] #[allow(clippy::large_enum_variant)] #[derive(Debug)] pub enum MerchantAccountUpdate { @@ -277,6 +254,33 @@ pub enum MerchantAccountUpdate { ModifiedAtUpdate, } +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +#[allow(clippy::large_enum_variant)] +#[derive(Debug)] +pub enum MerchantAccountUpdate { + Update { + merchant_name: OptionalEncryptableName, + merchant_details: OptionalEncryptableValue, + publishable_key: Option<String>, + metadata: Option<pii::SecretSerdeValue>, + routing_algorithm: Option<serde_json::Value>, + frm_routing_algorithm: Option<serde_json::Value>, + payout_routing_algorithm: Option<serde_json::Value>, + }, + StorageSchemeUpdate { + storage_scheme: MerchantStorageScheme, + }, + ReconUpdate { + recon_status: diesel_models::enums::ReconStatus, + }, + ModifiedAtUpdate, +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] + impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { fn from(merchant_account_update: MerchantAccountUpdate) -> Self { let now = date_time::now(); @@ -285,8 +289,8 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { MerchantAccountUpdate::Update { merchant_name, merchant_details, - return_url, webhook_details, + return_url, routing_algorithm, sub_merchants_enabled, parent_merchant_id, @@ -307,11 +311,11 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { merchant_name: merchant_name.map(Encryption::from), merchant_details: merchant_details.map(Encryption::from), frm_routing_algorithm, - return_url, webhook_details, routing_algorithm, sub_merchants_enabled, parent_merchant_id, + return_url, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, @@ -319,32 +323,194 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { locker_id, metadata, primary_business_details, - modified_at: Some(now), + modified_at: now, intent_fulfillment_time, payout_routing_algorithm, default_profile, payment_link_config, pm_collect_link_config, - ..Default::default() + storage_scheme: None, + organization_id: None, + is_recon_enabled: None, + recon_status: None, }, MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self { storage_scheme: Some(storage_scheme), - modified_at: Some(now), - ..Default::default() + modified_at: now, + merchant_name: None, + merchant_details: None, + return_url: None, + webhook_details: None, + sub_merchants_enabled: None, + parent_merchant_id: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + publishable_key: None, + locker_id: None, + metadata: None, + routing_algorithm: None, + primary_business_details: None, + intent_fulfillment_time: None, + frm_routing_algorithm: None, + payout_routing_algorithm: None, + organization_id: None, + is_recon_enabled: None, + default_profile: None, + recon_status: None, + payment_link_config: None, + pm_collect_link_config: None, }, MerchantAccountUpdate::ReconUpdate { recon_status } => Self { recon_status: Some(recon_status), - modified_at: Some(now), - ..Default::default() + modified_at: now, + merchant_name: None, + merchant_details: None, + return_url: None, + webhook_details: None, + sub_merchants_enabled: None, + parent_merchant_id: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + publishable_key: None, + storage_scheme: None, + locker_id: None, + metadata: None, + routing_algorithm: None, + primary_business_details: None, + intent_fulfillment_time: None, + frm_routing_algorithm: None, + payout_routing_algorithm: None, + organization_id: None, + is_recon_enabled: None, + default_profile: None, + payment_link_config: None, + pm_collect_link_config: None, }, MerchantAccountUpdate::UnsetDefaultProfile => Self { default_profile: Some(None), - modified_at: Some(now), - ..Default::default() + modified_at: now, + merchant_name: None, + merchant_details: None, + return_url: None, + webhook_details: None, + sub_merchants_enabled: None, + parent_merchant_id: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + publishable_key: None, + storage_scheme: None, + locker_id: None, + metadata: None, + routing_algorithm: None, + primary_business_details: None, + intent_fulfillment_time: None, + frm_routing_algorithm: None, + payout_routing_algorithm: None, + organization_id: None, + is_recon_enabled: None, + recon_status: None, + payment_link_config: None, + pm_collect_link_config: None, + }, + MerchantAccountUpdate::ModifiedAtUpdate => Self { + modified_at: now, + merchant_name: None, + merchant_details: None, + return_url: None, + webhook_details: None, + sub_merchants_enabled: None, + parent_merchant_id: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + publishable_key: None, + storage_scheme: None, + locker_id: None, + metadata: None, + routing_algorithm: None, + primary_business_details: None, + intent_fulfillment_time: None, + frm_routing_algorithm: None, + payout_routing_algorithm: None, + organization_id: None, + is_recon_enabled: None, + default_profile: None, + recon_status: None, + payment_link_config: None, + pm_collect_link_config: None, + }, + } + } +} + +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { + fn from(merchant_account_update: MerchantAccountUpdate) -> Self { + let now = date_time::now(); + + match merchant_account_update { + MerchantAccountUpdate::Update { + merchant_name, + merchant_details, + routing_algorithm, + publishable_key, + metadata, + frm_routing_algorithm, + payout_routing_algorithm, + } => Self { + merchant_name: merchant_name.map(Encryption::from), + merchant_details: merchant_details.map(Encryption::from), + frm_routing_algorithm, + routing_algorithm, + publishable_key, + metadata, + modified_at: now, + payout_routing_algorithm, + storage_scheme: None, + organization_id: None, + recon_status: None, + }, + MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self { + storage_scheme: Some(storage_scheme), + modified_at: now, + merchant_name: None, + merchant_details: None, + publishable_key: None, + metadata: None, + routing_algorithm: None, + frm_routing_algorithm: None, + payout_routing_algorithm: None, + organization_id: None, + recon_status: None, + }, + MerchantAccountUpdate::ReconUpdate { recon_status } => Self { + recon_status: Some(recon_status), + modified_at: now, + merchant_name: None, + merchant_details: None, + publishable_key: None, + storage_scheme: None, + metadata: None, + routing_algorithm: None, + frm_routing_algorithm: None, + payout_routing_algorithm: None, + organization_id: None, }, MerchantAccountUpdate::ModifiedAtUpdate => Self { - modified_at: Some(date_time::now()), - ..Default::default() + modified_at: now, + merchant_name: None, + merchant_details: None, + publishable_key: None, + storage_scheme: None, + metadata: None, + routing_algorithm: None, + frm_routing_algorithm: None, + payout_routing_algorithm: None, + organization_id: None, + recon_status: None, }, } } @@ -360,32 +526,18 @@ impl super::behaviour::Conversion for MerchantAccount { let setter = diesel_models::merchant_account::MerchantAccountSetter { id, - return_url: self.return_url, - enable_payment_response_hash: self.enable_payment_response_hash, - payment_response_hash_key: self.payment_response_hash_key, - redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, merchant_name: self.merchant_name.map(|name| name.into()), merchant_details: self.merchant_details.map(|details| details.into()), - webhook_details: self.webhook_details, - sub_merchants_enabled: self.sub_merchants_enabled, - parent_merchant_id: self.parent_merchant_id, publishable_key: Some(self.publishable_key), storage_scheme: self.storage_scheme, - locker_id: self.locker_id, metadata: self.metadata, routing_algorithm: self.routing_algorithm, - primary_business_details: self.primary_business_details, created_at: self.created_at, modified_at: self.modified_at, - intent_fulfillment_time: self.intent_fulfillment_time, frm_routing_algorithm: self.frm_routing_algorithm, payout_routing_algorithm: self.payout_routing_algorithm, organization_id: self.organization_id, - is_recon_enabled: self.is_recon_enabled, - default_profile: self.default_profile, recon_status: self.recon_status, - payment_link_config: self.payment_link_config, - pm_collect_link_config: self.pm_collect_link_config, }; Ok(diesel_models::MerchantAccount::from(setter)) @@ -410,10 +562,6 @@ impl super::behaviour::Conversion for MerchantAccount { async { Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { id, - return_url: item.return_url, - enable_payment_response_hash: item.enable_payment_response_hash, - payment_response_hash_key: item.payment_response_hash_key, - redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, merchant_name: item .merchant_name .async_lift(|inner| { @@ -426,26 +574,16 @@ impl super::behaviour::Conversion for MerchantAccount { decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek()) }) .await?, - webhook_details: item.webhook_details, - sub_merchants_enabled: item.sub_merchants_enabled, - parent_merchant_id: item.parent_merchant_id, publishable_key, storage_scheme: item.storage_scheme, - locker_id: item.locker_id, metadata: item.metadata, routing_algorithm: item.routing_algorithm, frm_routing_algorithm: item.frm_routing_algorithm, - primary_business_details: item.primary_business_details, created_at: item.created_at, modified_at: item.modified_at, - intent_fulfillment_time: item.intent_fulfillment_time, payout_routing_algorithm: item.payout_routing_algorithm, organization_id: item.organization_id, - is_recon_enabled: item.is_recon_enabled, - default_profile: item.default_profile, recon_status: item.recon_status, - payment_link_config: item.payment_link_config, - pm_collect_link_config: item.pm_collect_link_config, }) } .await @@ -460,29 +598,15 @@ impl super::behaviour::Conversion for MerchantAccount { id: self.id, merchant_name: self.merchant_name.map(Encryption::from), merchant_details: self.merchant_details.map(Encryption::from), - return_url: self.return_url, - webhook_details: self.webhook_details, - sub_merchants_enabled: self.sub_merchants_enabled, - parent_merchant_id: self.parent_merchant_id, - enable_payment_response_hash: Some(self.enable_payment_response_hash), - payment_response_hash_key: self.payment_response_hash_key, - redirect_to_merchant_with_http_post: Some(self.redirect_to_merchant_with_http_post), publishable_key: Some(self.publishable_key), - locker_id: self.locker_id, metadata: self.metadata, routing_algorithm: self.routing_algorithm, - primary_business_details: self.primary_business_details, created_at: now, modified_at: now, - intent_fulfillment_time: self.intent_fulfillment_time, frm_routing_algorithm: self.frm_routing_algorithm, payout_routing_algorithm: self.payout_routing_algorithm, organization_id: self.organization_id, - is_recon_enabled: self.is_recon_enabled, - default_profile: self.default_profile, recon_status: self.recon_status, - payment_link_config: self.payment_link_config, - pm_collect_link_config: self.pm_collect_link_config, }) } } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 925fd3c61ed..b8e9d7c4f14 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -7,7 +7,7 @@ use api_models::{ use base64::Engine; use common_utils::{ date_time, - ext_traits::{AsyncExt, ConfigExt, Encode, ValueExt}, + ext_traits::{AsyncExt, Encode, ValueExt}, id_type, pii, types::keymanager::{self as km_types, KeyManagerState}, }; @@ -15,7 +15,6 @@ use diesel_models::configs; #[cfg(all(any(feature = "v1", feature = "v2"), feature = "olap"))] use diesel_models::organization::OrganizationBridge; use error_stack::{report, FutureExt, ResultExt}; -use futures::future::try_join_all; use masking::{ExposeInterface, PeekInterface, Secret}; use pm_auth::{connector::plaid::transformers::PlaidAuthType, types as pm_auth_types}; use regex::Regex; @@ -230,7 +229,7 @@ pub async fn create_merchant_account( }; let domain_merchant_account = req - .create_domain_model_from_request(&state, key_store.clone()) + .create_domain_model_from_request(&state, key_store.clone(), &merchant_id) .await?; let key_manager_state = &(&state).into(); db.insert_merchant_key_store( @@ -264,6 +263,7 @@ trait MerchantAccountCreateBridge { self, state: &SessionState, key: domain::MerchantKeyStore, + identifier: &id_type::MerchantId, ) -> RouterResult<domain::MerchantAccount>; } @@ -278,6 +278,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { self, state: &SessionState, key_store: domain::MerchantKeyStore, + identifier: &id_type::MerchantId, ) -> RouterResult<domain::MerchantAccount> { let db = &*state.store; let publishable_key = create_merchant_publishable_key(); @@ -341,7 +342,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { let merchant_account = async { Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( domain::MerchantAccountSetter { - merchant_id: self.merchant_id, + merchant_id: identifier.clone(), merchant_name: self .merchant_name .async_lift(|inner| { @@ -618,6 +619,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { self, state: &SessionState, key_store: domain::MerchantKeyStore, + identifier: &id_type::MerchantId, ) -> RouterResult<domain::MerchantAccount> { let publishable_key = create_merchant_publishable_key(); let db = &*state.store; @@ -634,18 +636,12 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { }, )?; - let primary_business_details = self.get_primary_details_as_value().change_context( - errors::ApiErrorResponse::InvalidDataValue { - field_name: "primary_business_details", - }, - )?; - let organization = CreateOrValidateOrganization::new(self.organization_id.clone()) .create_or_validate(db) .await?; let key = key_store.key.into_inner(); - let id = self.get_merchant_reference_id().to_owned(); + let id = identifier.to_owned(); let key_manager_state = state.into(); let identifier = km_types::Identifier::Merchant(id.clone()); @@ -673,33 +669,19 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { ) }) .await?, - return_url: None, - webhook_details: None, routing_algorithm: Some(serde_json::json!({ "algorithm_id": null, "timestamp": 0 })), - sub_merchants_enabled: None, - parent_merchant_id: None, - enable_payment_response_hash: true, - payment_response_hash_key: None, - redirect_to_merchant_with_http_post: true, publishable_key, - locker_id: None, metadata, storage_scheme: MerchantStorageScheme::PostgresOnly, - primary_business_details, created_at: date_time::now(), modified_at: date_time::now(), - intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, organization_id: organization.get_organization_id(), - is_recon_enabled: false, - default_profile: None, recon_status: diesel_models::enums::ReconStatus::NotRequested, - payment_link_config: None, - pm_collect_link_config: None, }), ) } @@ -762,7 +744,10 @@ pub async fn get_merchant_account( )) } -#[cfg(any(feature = "v1", feature = "v2"))] +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] /// For backwards compatibility, whenever new business labels are passed in /// primary_business_details, create a business profile pub async fn create_business_profile_from_business_labels( @@ -832,74 +817,222 @@ pub async fn create_business_profile_from_business_labels( Ok(()) } -/// For backwards compatibility -/// If any of the fields of merchant account are updated, then update these fields in business profiles -pub async fn update_business_profile_cascade( - state: SessionState, - merchant_account_update: api::MerchantAccountUpdate, - merchant_id: id_type::MerchantId, -) -> RouterResult<()> { - if merchant_account_update.return_url.is_some() - || merchant_account_update.webhook_details.is_some() - || merchant_account_update - .enable_payment_response_hash - .is_some() - || merchant_account_update - .redirect_to_merchant_with_http_post - .is_some() - { - // Update these fields in all the business profiles - let business_profiles = state - .store - .list_business_profile_by_merchant_id(&merchant_id) - .await - .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound { - id: merchant_id.get_string_repr().to_owned(), - })?; +#[cfg(any(feature = "v1", feature = "v2", feature = "olap"))] +#[async_trait::async_trait] +trait MerchantAccountUpdateBridge { + async fn get_update_merchant_object( + self, + state: &SessionState, + merchant_id: &id_type::MerchantId, + key_store: &domain::MerchantKeyStore, + ) -> RouterResult<storage::MerchantAccountUpdate>; +} - let business_profile_update = admin_types::BusinessProfileUpdate { - profile_name: None, - return_url: merchant_account_update.return_url, - enable_payment_response_hash: merchant_account_update.enable_payment_response_hash, - payment_response_hash_key: merchant_account_update.payment_response_hash_key, - redirect_to_merchant_with_http_post: merchant_account_update - .redirect_to_merchant_with_http_post, - webhook_details: merchant_account_update.webhook_details, - metadata: None, - routing_algorithm: None, +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] +#[async_trait::async_trait] +impl MerchantAccountUpdateBridge for api::MerchantAccountUpdate { + async fn get_update_merchant_object( + self, + state: &SessionState, + merchant_id: &id_type::MerchantId, + key_store: &domain::MerchantKeyStore, + ) -> RouterResult<storage::MerchantAccountUpdate> { + use common_utils::ext_traits::ConfigExt; + + let key_manager_state = &state.into(); + let key = key_store.key.get_inner().peek(); + + let db = state.store.as_ref(); + + let primary_business_details = self.get_primary_details_as_value().change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "primary_business_details", + }, + )?; + + let pm_collect_link_config = self.get_pm_link_config_as_value().change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "pm_collect_link_config", + }, + )?; + + let merchant_details = self.get_merchant_details_as_secret().change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "merchant_details", + }, + )?; + + self.parse_routing_algorithm().change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "routing_algorithm", + }, + )?; + + let webhook_details = self.get_webhook_details_as_value().change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "webhook_details", + }, + )?; + + let parent_merchant_id = get_parent_merchant( + state, + self.sub_merchants_enabled, + self.parent_merchant_id.as_ref(), + key_store, + ) + .await?; + + // This supports changing the business profile by passing in the profile_id + let business_profile_id_update = if let Some(ref profile_id) = self.default_profile { + if !profile_id.is_empty_after_trim() { + // Validate whether profile_id passed in request is valid and is linked to the merchant + core_utils::validate_and_get_business_profile( + state.store.as_ref(), + Some(profile_id), + merchant_id, + ) + .await? + .map(|business_profile| Some(business_profile.profile_id)) + } else { + // If empty, Update profile_id to None in the database + Some(None) + } + } else { + None + }; + + #[cfg(any(feature = "v1", feature = "v2"))] + // In order to support backwards compatibility, if a business_labels are passed in the update + // call, then create new business_profiles with the profile_name as business_label + self.primary_business_details + .clone() + .async_map(|primary_business_details| async { + let _ = create_business_profile_from_business_labels( + state, + db, + key_store, + merchant_id, + primary_business_details, + ) + .await; + }) + .await; + + let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone()); + Ok(storage::MerchantAccountUpdate::Update { + merchant_name: self + .merchant_name + .map(Secret::new) + .async_lift(|inner| { + domain_types::encrypt_optional( + key_manager_state, + inner, + identifier.clone(), + key, + ) + }) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt merchant name")?, + merchant_details: merchant_details + .async_lift(|inner| { + domain_types::encrypt_optional( + key_manager_state, + inner, + km_types::Identifier::Merchant(key_store.merchant_id.clone()), + key, + ) + }) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt merchant details")?, + return_url: self.return_url.map(|a| a.to_string()), + webhook_details, + sub_merchants_enabled: self.sub_merchants_enabled, + parent_merchant_id, + enable_payment_response_hash: self.enable_payment_response_hash, + payment_response_hash_key: self.payment_response_hash_key, + redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, + locker_id: self.locker_id, + metadata: self.metadata, + publishable_key: None, + primary_business_details, + frm_routing_algorithm: self.frm_routing_algorithm, intent_fulfillment_time: None, - frm_routing_algorithm: None, #[cfg(feature = "payouts")] + payout_routing_algorithm: self.payout_routing_algorithm, + #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, - applepay_verified_domains: None, + default_profile: business_profile_id_update, payment_link_config: None, - session_expiry: None, - authentication_connector_details: None, - payout_link_config: None, - extended_card_info_config: None, - use_billing_as_payment_method_billing: None, - collect_shipping_details_from_wallet_connector: None, - collect_billing_details_from_wallet_connector: None, - is_connector_agnostic_mit_enabled: None, - outgoing_webhook_custom_http_headers: None, - }; + pm_collect_link_config, + routing_algorithm: self.routing_algorithm, + }) + } +} - let update_futures = business_profiles.iter().map(|business_profile| async { - let profile_id = &business_profile.profile_id; +#[cfg(all(any(feature = "v1", feature = "v2"), feature = "merchant_account_v2",))] +#[async_trait::async_trait] +impl MerchantAccountUpdateBridge for api::MerchantAccountUpdate { + async fn get_update_merchant_object( + self, + state: &SessionState, + _merchant_id: &id_type::MerchantId, + key_store: &domain::MerchantKeyStore, + ) -> RouterResult<storage::MerchantAccountUpdate> { + let key_manager_state = &state.into(); + let key = key_store.key.get_inner().peek(); - update_business_profile( - state.clone(), - profile_id, - &merchant_id, - business_profile_update.clone(), - ) - .await - }); + let merchant_details = self.get_merchant_details_as_secret().change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "merchant_details", + }, + )?; - try_join_all(update_futures).await?; - } + let metadata = self.get_metadata_as_secret().change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "metadata", + }, + )?; - Ok(()) + let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone()); + Ok(storage::MerchantAccountUpdate::Update { + merchant_name: self + .merchant_name + .map(Secret::new) + .async_lift(|inner| { + domain_types::encrypt_optional( + key_manager_state, + inner, + identifier.clone(), + key, + ) + }) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt merchant name")?, + merchant_details: merchant_details + .async_lift(|inner| { + domain_types::encrypt_optional( + key_manager_state, + inner, + km_types::Identifier::Merchant(key_store.merchant_id.clone()), + key, + ) + }) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt merchant details")?, + metadata, + publishable_key: None, + frm_routing_algorithm: None, + payout_routing_algorithm: None, + routing_algorithm: None, + }) + } } pub async fn merchant_account_update( @@ -913,169 +1046,27 @@ pub async fn merchant_account_update( let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, - &req.merchant_id, + merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; - if &req.merchant_id != merchant_id { - Err(report!(errors::ValidationError::IncorrectValueProvided { - field_name: "parent_merchant_id" - }) - .attach_printable( - "If `sub_merchants_enabled` is true, then `parent_merchant_id` is mandatory", - ) - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "parent_merchant_id", - }))?; - } - - if let Some(ref routing_algorithm) = req.routing_algorithm { - let _: api_models::routing::RoutingAlgorithm = routing_algorithm - .clone() - .parse_value("RoutingAlgorithm") - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "routing_algorithm", - }) - .attach_printable("Invalid routing algorithm given")?; - } - - let primary_business_details = req - .primary_business_details - .as_ref() - .map(|primary_business_details| { - primary_business_details.encode_to_value().change_context( - errors::ApiErrorResponse::InvalidDataValue { - field_name: "primary_business_details", - }, - ) - }) - .transpose()?; - - let pm_collect_link_config = req - .pm_collect_link_config - .as_ref() - .map(|c| { - c.encode_to_value() - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "pm_collect_link_config", - }) - }) - .transpose()?; - - #[cfg(any(feature = "v1", feature = "v2"))] - // In order to support backwards compatibility, if a business_labels are passed in the update - // call, then create new business_profiles with the profile_name as business_label - req.primary_business_details - .clone() - .async_map(|primary_business_details| async { - let _ = create_business_profile_from_business_labels( - &state, - db, - &key_store, - merchant_id, - primary_business_details, - ) - .await; - }) - .await; - - let key = key_store.key.get_inner().peek(); - - let business_profile_id_update = if let Some(ref profile_id) = req.default_profile { - if !profile_id.is_empty_after_trim() { - // Validate whether profile_id passed in request is valid and is linked to the merchant - core_utils::validate_and_get_business_profile(db, Some(profile_id), merchant_id) - .await? - .map(|business_profile| Some(business_profile.profile_id)) - } else { - // If empty, Update profile_id to None in the database - Some(None) - } - } else { - None - }; - - // Update the business profile, This is for backwards compatibility - update_business_profile_cascade(state.clone(), req.clone(), merchant_id.to_owned()).await?; - - let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone()); - let updated_merchant_account = storage::MerchantAccountUpdate::Update { - merchant_name: req - .merchant_name - .map(Secret::new) - .async_lift(|inner| { - domain_types::encrypt_optional(key_manager_state, inner, identifier.clone(), key) - }) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt merchant name")?, - - merchant_details: req - .merchant_details - .as_ref() - .map(Encode::encode_to_value) - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to convert merchant_details to a value")? - .map(Secret::new) - .async_lift(|inner| { - domain_types::encrypt_optional(key_manager_state, inner, identifier.clone(), key) - }) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt merchant details")?, - - return_url: req.return_url.map(|a| a.to_string()), - - webhook_details: req - .webhook_details - .as_ref() - .map(Encode::encode_to_value) - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError)?, - - routing_algorithm: req.routing_algorithm, - sub_merchants_enabled: req.sub_merchants_enabled, - - parent_merchant_id: get_parent_merchant( - &state, - req.sub_merchants_enabled, - req.parent_merchant_id.as_ref(), - &key_store, - ) - .await?, - enable_payment_response_hash: req.enable_payment_response_hash, - payment_response_hash_key: req.payment_response_hash_key, - redirect_to_merchant_with_http_post: req.redirect_to_merchant_with_http_post, - locker_id: req.locker_id, - metadata: req.metadata, - publishable_key: None, - primary_business_details, - frm_routing_algorithm: req.frm_routing_algorithm, - intent_fulfillment_time: None, - #[cfg(feature = "payouts")] - payout_routing_algorithm: req.payout_routing_algorithm, - #[cfg(not(feature = "payouts"))] - payout_routing_algorithm: None, - default_profile: business_profile_id_update, - payment_link_config: None, - pm_collect_link_config, - }; + let merchant_account_storage_object = req + .get_update_merchant_object(&state, merchant_id, &key_store) + .await + .attach_printable("Failed to create merchant account update object")?; let response = db .update_specific_fields_in_merchant( key_manager_state, merchant_id, - updated_merchant_account, + merchant_account_storage_object, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; - // If there are any new business labels generated, create business profile - Ok(service_api::ApplicationResponse::Json( api::MerchantAccountResponse::foreign_try_from(response) .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1153,6 +1144,10 @@ pub async fn merchant_account_delete( Ok(service_api::ApplicationResponse::Json(response)) } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] async fn get_parent_merchant( state: &SessionState, sub_merchants_enabled: Option<bool>, @@ -1181,6 +1176,10 @@ async fn get_parent_merchant( }) } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] async fn validate_merchant_id( state: &SessionState, merchant_id: &id_type::MerchantId, @@ -2207,7 +2206,8 @@ trait MerchantConnectorAccountCreateBridge { #[cfg(all( feature = "v2", feature = "merchant_connector_account_v2", - feature = "olap" + feature = "olap", + feature = "merchant_account_v2" ))] #[async_trait::async_trait] impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { @@ -2359,7 +2359,8 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { #[cfg(all( any(feature = "v1", feature = "v2", feature = "olap"), - not(feature = "merchant_connector_account_v2") + not(feature = "merchant_connector_account_v2"), + not(feature = "merchant_account_v2") ))] #[async_trait::async_trait] impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { @@ -2580,7 +2581,7 @@ pub async fn create_payment_connector( #[cfg(all( any(feature = "v1", feature = "v2"), - not(feature = "merchant_connector_account_v2") + not(feature = "merchant_account_v2") ))] helpers::validate_business_details( req.business_country, @@ -3157,9 +3158,19 @@ pub async fn create_and_insert_business_profile( merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<storage::business_profile::BusinessProfile> { + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") + ))] let business_profile_new = admin::create_business_profile(state, merchant_account, request, key_store).await?; + #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] + let business_profile_new = { + let _ = merchant_account; + admin::create_business_profile(state, request, key_store).await? + }; + let profile_name = business_profile_new.profile_name.clone(); state @@ -3174,6 +3185,10 @@ pub async fn create_and_insert_business_profile( .attach_printable("Failed to insert Business profile because of duplication error") } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] pub async fn create_business_profile( state: SessionState, request: api::BusinessProfileCreate, @@ -3239,6 +3254,15 @@ pub async fn create_business_profile( )) } +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +pub async fn create_business_profile( + _state: SessionState, + _request: api::BusinessProfileCreate, + _merchant_id: &id_type::MerchantId, +) -> RouterResponse<api_models::admin::BusinessProfileResponse> { + todo!() +} + pub async fn list_business_profile( state: SessionState, merchant_id: id_type::MerchantId, diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs index df3a5a2ca2f..64fadd0e33d 100644 --- a/crates/router/src/core/fraud_check.rs +++ b/crates/router/src/core/fraud_check.rs @@ -2,6 +2,7 @@ use std::fmt::Debug; use api_models::{admin::FrmConfigs, enums as api_enums}; use common_enums::CaptureMethod; +use common_utils::ext_traits::OptionExt; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface}; use router_env::{ @@ -21,7 +22,6 @@ use crate::{ core::{ errors::{self, RouterResult}, payments::{self, flows::ConstructFlowSpecificData, operations::BoxedOperation}, - utils as core_utils, }, db::StorageInterface, routes::{app::ReqState, SessionState}, @@ -145,16 +145,14 @@ where }) .attach_printable("Data field not found in frm_routing_algorithm")?; - let profile_id = core_utils::get_profile_id_from_business_details( - payment_data.payment_intent.business_country, - payment_data.payment_intent.business_label.as_ref(), - merchant_account, - payment_data.payment_intent.profile_id.as_ref(), - db, - false, - ) - .await - .attach_printable("Could not find profile id from business details")?; + let profile_id = payment_data + .payment_intent + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("profile_id is not set in payment_intent")? + .clone(); #[cfg(all( any(feature = "v1", feature = "v2"), diff --git a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs index a16dc2b16e1..c99636581c3 100644 --- a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs +++ b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs @@ -1,4 +1,4 @@ -use common_utils::ext_traits::ValueExt; +use common_utils::ext_traits::{OptionExt, ValueExt}; use error_stack::ResultExt; use router_env::tracing::{self, instrument}; @@ -26,17 +26,13 @@ pub async fn construct_fulfillment_router_data<'a>( connector: String, fulfillment_request: FrmFulfillmentRequest, ) -> RouterResult<FrmFulfillmentRouterData> { - let profile_id = core_utils::get_profile_id_from_business_details( - payment_intent.business_country, - payment_intent.business_label.as_ref(), - merchant_account, - payment_intent.profile_id.as_ref(), - &*state.store, - false, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("profile_id is not set in payment_intent")?; + let profile_id = payment_intent + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("profile_id is not set in payment_intent")? + .clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index b919541adef..17745517b67 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2335,16 +2335,12 @@ pub async fn list_payment_methods( let profile_id = payment_intent .as_ref() .async_map(|payment_intent| async { - crate::core::utils::get_profile_id_from_business_details( - payment_intent.business_country, - payment_intent.business_label.as_ref(), - &merchant_account, - payment_intent.profile_id.as_ref(), - db, - false, - ) - .await - .attach_printable("Could not find profile id from business details") + payment_intent + .profile_id + .clone() + .get_required_value("profile_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("profile_id is not set in payment_intent") }) .await .transpose()?; @@ -2667,7 +2663,7 @@ pub async fn list_payment_methods( for inner_config in config.enabled_payment_methods.iter() { let is_active_mca = all_mcas .iter() - .any(|mca| mca.merchant_connector_id == inner_config.mca_id); + .any(|mca| mca.get_id() == inner_config.mca_id); if inner_config.payment_method_type == *payment_method_type && is_active_mca { @@ -3738,16 +3734,12 @@ pub async fn list_customer_payment_method( let profile_id = payment_intent .as_ref() .async_map(|payment_intent| async { - core_utils::get_profile_id_from_business_details( - payment_intent.business_country, - payment_intent.business_label.as_ref(), - &merchant_account, - payment_intent.profile_id.as_ref(), - db, - false, - ) - .await - .attach_printable("Could not find profile id from business details") + payment_intent + .profile_id + .clone() + .get_required_value("profile_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("profile_id is not set in payment_intent") }) .await .transpose()?; diff --git a/crates/router/src/core/payment_methods/validator.rs b/crates/router/src/core/payment_methods/validator.rs index c45f6df837d..d9ec794151c 100644 --- a/crates/router/src/core/payment_methods/validator.rs +++ b/crates/router/src/core/payment_methods/validator.rs @@ -1,5 +1,5 @@ use api_models::{admin, payment_methods::PaymentMethodCollectLinkRequest}; -use common_utils::{ext_traits::ValueExt, link_utils}; +use common_utils::link_utils; use diesel_models::generic_link::PaymentMethodCollectLinkData; use error_stack::ResultExt; use masking::Secret; @@ -62,18 +62,28 @@ pub async fn validate_request_and_initiate_payment_method_collect_link( // Fetch all configs let default_config = &state.conf.generic_link.payment_method_collect; + + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") + ))] let merchant_config = merchant_account .pm_collect_link_config .as_ref() .map(|config| { - config - .clone() - .parse_value::<admin::BusinessCollectLinkConfig>("BusinessCollectLinkConfig") + common_utils::ext_traits::ValueExt::parse_value::<admin::BusinessCollectLinkConfig>( + config.clone(), + "BusinessCollectLinkConfig", + ) }) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "pm_collect_link_config in merchant_account", })?; + + #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] + let merchant_config = Option::<admin::BusinessCollectLinkConfig>::None; + let merchant_ui_config = merchant_config.as_ref().map(|c| c.config.ui_config.clone()); let ui_config = req .ui_config diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 78d0d8fd79d..8d7266c499e 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1967,16 +1967,14 @@ where { connector_label } else { - let profile_id = utils::get_profile_id_from_business_details( - payment_data.payment_intent.business_country, - payment_data.payment_intent.business_label.as_ref(), - merchant_account, - payment_data.payment_intent.profile_id.as_ref(), - &*state.store, - false, - ) - .await - .attach_printable("Could not find profile id from business details")?; + let profile_id = payment_data + .payment_intent + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("profile_id is not set in payment_intent")? + .clone(); format!("{connector_name}_{profile_id}") }; @@ -2243,22 +2241,19 @@ pub async fn construct_profile_id_and_get_mca<'a, F>( connector_name: &str, merchant_connector_id: Option<&String>, key_store: &domain::MerchantKeyStore, - should_validate: bool, + _should_validate: bool, ) -> RouterResult<helpers::MerchantConnectorAccountType> where F: Clone, { - let profile_id = utils::get_profile_id_from_business_details( - payment_data.payment_intent.business_country, - payment_data.payment_intent.business_label.as_ref(), - merchant_account, - payment_data.payment_intent.profile_id.as_ref(), - &*state.store, - should_validate, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("profile_id is not set in payment_intent")?; + let profile_id = payment_data + .payment_intent + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("profile_id is not set in payment_intent")? + .clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 53fc1e1938c..9f661a8b0c5 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2942,6 +2942,10 @@ pub async fn verify_payment_intent_time_and_client_secret( .transpose() } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] /// Check whether the business details are configured in the merchant account pub fn validate_business_details( business_country: Option<api_enums::CountryAlpha2>, @@ -2974,41 +2978,6 @@ pub fn validate_business_details( Ok(()) } -/// Do lazy parsing of primary business details -/// If both country and label are passed, no need to parse business details from merchant_account -/// If any one is missing, get it from merchant_account -/// If there is more than one label or country configured in merchant account, then -/// passing business details for payment is mandatory to avoid ambiguity -pub fn get_business_details( - business_country: Option<api_enums::CountryAlpha2>, - business_label: Option<&String>, - merchant_account: &domain::MerchantAccount, -) -> RouterResult<(api_enums::CountryAlpha2, String)> { - let primary_business_details = merchant_account - .primary_business_details - .clone() - .parse_value::<Vec<api_models::admin::PrimaryBusinessDetails>>("PrimaryBusinessDetails") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to parse primary business details")?; - - match business_country.zip(business_label) { - Some((business_country, business_label)) => { - Ok((business_country.to_owned(), business_label.to_owned())) - } - _ => match primary_business_details.first() { - Some(business_details) if primary_business_details.len() == 1 => Ok(( - business_country.unwrap_or_else(|| business_details.country.to_owned()), - business_label - .map(ToString::to_string) - .unwrap_or_else(|| business_details.business.to_owned()), - )), - _ => Err(report!(errors::ApiErrorResponse::MissingRequiredField { - field_name: "business_country, business_label" - })), - }, - } -} - #[inline] pub(crate) fn get_payment_id_from_client_secret(cs: &str) -> RouterResult<String> { let (payment_id, _) = cs diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 1723084d0f1..94eddff25d4 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -80,6 +80,10 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") + ))] helpers::validate_business_details( request.business_country, request.business_label.as_ref(), @@ -87,6 +91,10 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa )?; // If profile id is not passed, get it from the business_country and business_label + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") + ))] let profile_id = core_utils::get_profile_id_from_business_details( request.business_country, request.business_label.as_ref(), @@ -97,6 +105,15 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa ) .await?; + // Profile id will be mandatory in v2 in the request / headers + #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] + let profile_id = request + .profile_id + .clone() + .get_required_value("profile_id") + .attach_printable("Profile id is a mandatory parameter")?; + + // TODO: eliminate a redundant db call to fetch the business profile // Validate whether profile_id passed in request is valid and is linked to the merchant let business_profile = if let Some(business_profile) = core_utils::validate_and_get_business_profile(db, Some(&profile_id), merchant_id) diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 5e384021e54..f061fc2f07b 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -368,16 +368,12 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Database error when querying for merchant connector accounts")?; - let profile_id = crate::core::utils::get_profile_id_from_business_details( - payment_intent.business_country, - payment_intent.business_label.as_ref(), - merchant_account, - payment_intent.profile_id.as_ref(), - &*state.store, - false, - ) - .await - .attach_printable("Could not find profile id from business details")?; + let profile_id = payment_intent + .profile_id + .clone() + .get_required_value("profile_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("profile_id is not set in payment_intent")?; let filtered_connector_accounts = helpers::filter_mca_based_on_business_profile(all_connector_accounts, Some(profile_id)); diff --git a/crates/router/src/core/payouts/validator.rs b/crates/router/src/core/payouts/validator.rs index f9a2939eb08..8dbdc73cea4 100644 --- a/crates/router/src/core/payouts/validator.rs +++ b/crates/router/src/core/payouts/validator.rs @@ -118,7 +118,10 @@ pub async fn validate_create_request( None => None, }; - // Profile ID + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") + ))] let profile_id = core_utils::get_profile_id_from_business_details( req.business_country, req.business_label.as_ref(), @@ -129,6 +132,16 @@ pub async fn validate_create_request( ) .await?; + #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] + // Profile id will be mandatory in v2 in the request / headers + let profile_id = req + .profile_id + .clone() + .ok_or(errors::ApiErrorResponse::MissingRequiredField { + field_name: "profile_id", + }) + .attach_printable("Profile id is a mandatory parameter")?; + Ok((payout_id, payout_method_data, profile_id)) } diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index f550c7e501f..6444f6bc457 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -119,6 +119,10 @@ pub async fn update_merchant_routing_dictionary( /// This will help make one of all configured algorithms to be in active state for a particular /// merchant +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] pub async fn update_merchant_active_algorithm_ref( state: &SessionState, key_store: &domain::MerchantKeyStore, @@ -152,6 +156,7 @@ pub async fn update_merchant_active_algorithm_ref( payment_link_config: None, pm_collect_link_config: None, }; + let db = &*state.store; db.update_specific_fields_in_merchant( &state.into(), @@ -170,7 +175,19 @@ pub async fn update_merchant_active_algorithm_ref( Ok(()) } -// TODO: Move it to business_profile + +#[cfg(all(any(feature = "v1", feature = "v2"), feature = "merchant_account_v2"))] +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +pub async fn update_merchant_active_algorithm_ref( + _state: &SessionState, + _key_store: &domain::MerchantKeyStore, + _config_key: cache::CacheKind<'_>, + _algorithm_id: routing_types::RoutingAlgorithmRef, +) -> RouterResult<()> { + // TODO: handle updating the active routing algorithm for v2 in merchant account + Ok(()) +} + pub async fn update_business_profile_active_algorithm_ref( db: &dyn StorageInterface, current_business_profile: BusinessProfile, diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index f25e13161aa..1500721cc7b 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -229,24 +229,19 @@ pub async fn construct_refund_router_data<'a, F>( creds_identifier: Option<String>, charges: Option<types::ChargeRefunds>, ) -> RouterResult<types::RefundsRouterData<F>> { - let profile_id = get_profile_id_from_business_details( - payment_intent.business_country, - payment_intent.business_label.as_ref(), - merchant_account, - payment_intent.profile_id.as_ref(), - &*state.store, - false, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("profile_id is not set in payment_intent")?; + let profile_id = payment_intent + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("profile_id is not set in payment_intent")?; let merchant_connector_account = helpers::get_merchant_connector_account( state, merchant_account.get_id(), creds_identifier, key_store, - &profile_id, + profile_id, connector_id, payment_attempt.merchant_connector_id.as_ref(), ) @@ -524,17 +519,13 @@ pub async fn construct_accept_dispute_router_data<'a>( key_store: &domain::MerchantKeyStore, dispute: &storage::Dispute, ) -> RouterResult<types::AcceptDisputeRouterData> { - let profile_id = get_profile_id_from_business_details( - payment_intent.business_country, - payment_intent.business_label.as_ref(), - merchant_account, - payment_intent.profile_id.as_ref(), - &*state.store, - false, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("profile_id is not set in payment_intent")?; + let profile_id = payment_intent + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("profile_id is not set in payment_intent")? + .clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, @@ -623,17 +614,13 @@ pub async fn construct_submit_evidence_router_data<'a>( submit_evidence_request_data: types::SubmitEvidenceRequestData, ) -> RouterResult<types::SubmitEvidenceRouterData> { let connector_id = &dispute.connector; - let profile_id = get_profile_id_from_business_details( - payment_intent.business_country, - payment_intent.business_label.as_ref(), - merchant_account, - payment_intent.profile_id.as_ref(), - &*state.store, - false, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("profile_id is not set in payment_intent")?; + let profile_id = payment_intent + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("profile_id is not set in payment_intent")? + .clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, @@ -720,17 +707,13 @@ pub async fn construct_upload_file_router_data<'a>( connector_id: &str, file_key: String, ) -> RouterResult<types::UploadFileRouterData> { - let profile_id = get_profile_id_from_business_details( - payment_intent.business_country, - payment_intent.business_label.as_ref(), - merchant_account, - payment_intent.profile_id.as_ref(), - &*state.store, - false, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("profile_id is not set in payment_intent")?; + let profile_id = payment_intent + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("profile_id is not set in payment_intent")? + .clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, @@ -821,17 +804,13 @@ pub async fn construct_defend_dispute_router_data<'a>( ) -> RouterResult<types::DefendDisputeRouterData> { let _db = &*state.store; let connector_id = &dispute.connector; - let profile_id = get_profile_id_from_business_details( - payment_intent.business_country, - payment_intent.business_label.as_ref(), - merchant_account, - payment_intent.profile_id.as_ref(), - &*state.store, - false, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("profile_id is not set in payment_intent")?; + let profile_id = payment_intent + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("profile_id is not set in payment_intent")? + .clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, @@ -1090,6 +1069,10 @@ pub fn get_connector_label( }) } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] /// If profile_id is not passed, use default profile if available, or /// If business_details (business_country and business_label) are passed, get the business_profile /// or return a `MissingRequiredField` error diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index 2e43d469815..5a828ebb0cd 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -580,6 +580,10 @@ async fn publish_and_redact_merchant_account_cache( .as_ref() .map(|publishable_key| CacheKind::Accounts(publishable_key.into())); + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") + ))] let cgraph_key = merchant_account.default_profile.as_ref().map(|profile_id| { CacheKind::CGraph( format!( @@ -591,6 +595,10 @@ async fn publish_and_redact_merchant_account_cache( ) }); + // TODO: we will not have default profile in v2 + #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] + let cgraph_key = None; + let mut cache_keys = vec![CacheKind::Accounts( merchant_account.get_id().get_string_repr().into(), )]; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 0b42c71944e..045a455ebbf 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1097,6 +1097,11 @@ impl MerchantAccount { web::scope("/v2/accounts") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(merchant_account_create))) + .service( + web::resource("/{id}") + .route(web::get().to(retrieve_merchant_account)) + .route(web::post().to(update_merchant_account)), + ) } } diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index acbca54f4b1..683bbd895ca 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -11,19 +11,16 @@ pub use api_models::{ }, organization::{OrganizationId, OrganizationRequest, OrganizationResponse}, }; -use common_utils::{ - ext_traits::{AsyncExt, Encode, ValueExt}, - types::keymanager::Identifier, -}; +use common_utils::{ext_traits::ValueExt, types::keymanager::Identifier}; use diesel_models::organization::OrganizationBridge; -use error_stack::{report, ResultExt}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ merchant_key_store::MerchantKeyStore, type_encryption::decrypt_optional, }; use masking::{ExposeInterface, PeekInterface, Secret}; use crate::{ - core::{errors, payment_methods::cards::create_encrypted_data}, + core::errors, routes::SessionState, types::{domain, storage, transformers::ForeignTryFrom, ForeignFrom}, }; @@ -106,7 +103,6 @@ impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse { publishable_key: item.publishable_key, metadata: item.metadata, organization_id: item.organization_id, - is_recon_enabled: item.is_recon_enabled, recon_status: item.recon_status, }) } @@ -179,7 +175,23 @@ pub async fn business_profile_response( }) } -#[cfg(any(feature = "v1", feature = "v2"))] +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] + +pub async fn create_business_profile( + _state: &SessionState, + _request: BusinessProfileCreate, + _key_store: &MerchantKeyStore, +) -> Result< + storage::business_profile::BusinessProfileNew, + error_stack::Report<errors::ApiErrorResponse>, +> { + todo!() +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] pub async fn create_business_profile( state: &SessionState, merchant_account: domain::MerchantAccount, @@ -189,6 +201,10 @@ pub async fn create_business_profile( storage::business_profile::BusinessProfileNew, error_stack::Report<errors::ApiErrorResponse>, > { + use common_utils::ext_traits::{AsyncExt, Encode}; + + use crate::core; + // Generate a unique profile id let profile_id = common_utils::generate_id_with_default_len("pro"); let merchant_id = merchant_account.get_id().to_owned(); @@ -224,7 +240,9 @@ pub async fn create_business_profile( .transpose()?; let outgoing_webhook_custom_http_headers = request .outgoing_webhook_custom_http_headers - .async_map(|headers| create_encrypted_data(state, key_store, headers)) + .async_map(|headers| { + core::payment_methods::cards::create_encrypted_data(state, key_store, headers) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -239,9 +257,11 @@ pub async fn create_business_profile( field_name: "payout_link_config", }, ), - Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { - message: e.to_string() - })), + Err(e) => Err(error_stack::report!( + errors::ApiErrorResponse::InvalidRequestData { + message: e.to_string() + } + )), }) .transpose()?; diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index 1e8761d1375..6fad1e2195d 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -51,7 +51,7 @@ use crate::{ core::{ authentication::types::ExternalThreeDSConnectorMetadata, errors::{self, CustomResult, RouterResult, StorageErrorExt}, - utils, webhooks as webhooks_core, + webhooks as webhooks_core, }, logger, routes::{metrics, SessionState}, @@ -441,20 +441,14 @@ pub async fn get_mca_from_payment_intent( } } None => { - let profile_id = match payment_intent.profile_id { - Some(profile_id) => profile_id, - None => utils::get_profile_id_from_business_details( - payment_intent.business_country, - payment_intent.business_label.as_ref(), - merchant_account, - payment_intent.profile_id.as_ref(), - db, - false, - ) - .await + let profile_id = payment_intent + .profile_id + .as_ref() + .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("profile_id is not set in payment_intent")?, - }; + .attach_printable("profile_id is not set in payment_intent")? + .clone(); + #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "merchant_connector_account_v2") @@ -579,7 +573,17 @@ pub async fn get_mca_from_object_reference_id( key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; - match merchant_account.default_profile.as_ref() { + + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") + ))] + let default_profile_id = merchant_account.default_profile.as_ref(); + + #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] + let default_profile_id = Option::<&String>::None; + + match default_profile_id { Some(profile_id) => { #[cfg(all( any(feature = "v1", feature = "v2"), @@ -601,8 +605,8 @@ pub async fn get_mca_from_object_reference_id( } #[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))] { - let _ = db; - let _ = profile_id; + let _db = db; + let _profile_id = profile_id; todo!() } } diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index 86607234d4e..303f02acc69 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -43,25 +43,44 @@ pub async fn generate_sample_data( .await .change_context::<SampleDataError>(SampleDataError::DataDoesNotExist)?; - let merchant_parsed_details: Vec<api_models::admin::PrimaryBusinessDetails> = - serde_json::from_value(merchant_from_db.primary_business_details.clone()) - .change_context(SampleDataError::InternalServerError) - .attach_printable("Error while parsing primary business details")?; - - let business_country_default = merchant_parsed_details.first().map(|x| x.country); - - let business_label_default = merchant_parsed_details.first().map(|x| x.business.clone()); - - let profile_id = match crate::core::utils::get_profile_id_from_business_details( - business_country_default, - business_label_default.as_ref(), - &merchant_from_db, - req.profile_id.as_ref(), - &*state.store, - false, - ) - .await - { + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") + ))] + let (profile_id_result, business_country_default, business_label_default) = { + let merchant_parsed_details: Vec<api_models::admin::PrimaryBusinessDetails> = + serde_json::from_value(merchant_from_db.primary_business_details.clone()) + .change_context(SampleDataError::InternalServerError) + .attach_printable("Error while parsing primary business details")?; + + let business_country_default = merchant_parsed_details.first().map(|x| x.country); + + let business_label_default = merchant_parsed_details.first().map(|x| x.business.clone()); + + let profile_id = crate::core::utils::get_profile_id_from_business_details( + business_country_default, + business_label_default.as_ref(), + &merchant_from_db, + req.profile_id.as_ref(), + &*state.store, + false, + ) + .await; + (profile_id, business_country_default, business_label_default) + }; + + #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] + let (profile_id_result, business_country_default, business_label_default) = { + let profile_id = req + .profile_id.clone() + .ok_or(hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse::MissingRequiredField { + field_name: "profile_id", + }); + + (profile_id, None, None) + }; + + let profile_id = match profile_id_result { Ok(id) => id.clone(), Err(error) => { router_env::logger::error!( diff --git a/justfile b/justfile index 1823c1ec19e..00a6187f41c 100644 --- a/justfile +++ b/justfile @@ -55,12 +55,12 @@ check_v2 *FLAGS: jq -r ' [ ( .workspace_members | sort ) as $package_ids # Store workspace crate package IDs in `package_ids` array | .packages[] | select( IN(.id; $package_ids[]) ) | .features | keys[] ] | unique # Select all unique features from all workspace crates - | del( .[] | select( any( . ; . == ("v1", "merchant_account_v2", "payment_v2","routing_v2") ) ) ) # Exclude some features from features list + | del( .[] | select( any( . ; . == ("v1") ) ) ) # Exclude some features from features list | join(",") # Construct a comma-separated string of features for passing to `cargo` ')" set -x - cargo clippy {{ check_flags }} --features "${FEATURES}" {{ FLAGS }} + cargo check {{ check_flags }} --features "${FEATURES}" {{ FLAGS }} set +x check *FLAGS: @@ -76,7 +76,7 @@ check *FLAGS: ')" set -x - cargo clippy {{ check_flags }} --features "${FEATURES}" {{ FLAGS }} + cargo check {{ check_flags }} --features "${FEATURES}" {{ FLAGS }} set +x alias cl := clippy diff --git a/v2_migrations/2024-07-26-065428_remove_deprecated_field_from_merchant_account/down.sql b/v2_migrations/2024-07-26-065428_remove_deprecated_field_from_merchant_account/down.sql new file mode 100644 index 00000000000..60e6c17b08b --- /dev/null +++ b/v2_migrations/2024-07-26-065428_remove_deprecated_field_from_merchant_account/down.sql @@ -0,0 +1,46 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE merchant_account +ADD COLUMN return_url VARCHAR(255); + +ALTER TABLE merchant_account +ADD COLUMN enable_payment_response_hash BOOLEAN DEFAULT FALSE; + +ALTER TABLE merchant_account +ADD COLUMN payment_response_hash_key VARCHAR(255); + +ALTER TABLE merchant_account +ADD COLUMN redirect_to_merchant_with_http_post BOOLEAN DEFAULT FALSE; + +ALTER TABLE merchant_account +ADD COLUMN sub_merchants_enabled BOOLEAN DEFAULT FALSE; + +ALTER TABLE merchant_account +ADD COLUMN parent_merchant_id VARCHAR(64); + +-- The default value is for temporary purpose only +ALTER TABLE merchant_account +ADD COLUMN primary_business_details JSON NOT NULL DEFAULT '[{"country": "US", "business": "default"}]'; + +ALTER TABLE merchant_account +ALTER COLUMN primary_business_details DROP DEFAULT; + +ALTER TABLE merchant_account +ADD COLUMN locker_id VARCHAR(64); + +ALTER TABLE merchant_account +ADD COLUMN intent_fulfillment_time BIGINT; + +ALTER TABLE merchant_account +ADD COLUMN default_profile VARCHAR(64); + +ALTER TABLE merchant_account +ADD COLUMN payment_link_config JSONB NULL; + +ALTER TABLE merchant_account +ADD COLUMN pm_collect_link_config JSONB NULL; + +ALTER TABLE merchant_account +ADD COLUMN is_recon_enabled BOOLEAN NOT NULL DEFAULT FALSE; + +ALTER TABLE merchant_account +ADD COLUMN webhook_details JSONB NULL; diff --git a/v2_migrations/2024-07-26-065428_remove_deprecated_field_from_merchant_account/up.sql b/v2_migrations/2024-07-26-065428_remove_deprecated_field_from_merchant_account/up.sql new file mode 100644 index 00000000000..e9a349e6130 --- /dev/null +++ b/v2_migrations/2024-07-26-065428_remove_deprecated_field_from_merchant_account/up.sql @@ -0,0 +1,28 @@ +-- Your SQL goes here +ALTER TABLE merchant_account DROP COLUMN return_url; + +ALTER TABLE merchant_account DROP enable_payment_response_hash; + +ALTER TABLE merchant_account DROP payment_response_hash_key; + +ALTER TABLE merchant_account DROP redirect_to_merchant_with_http_post; + +ALTER TABLE merchant_account DROP sub_merchants_enabled; + +ALTER TABLE merchant_account DROP parent_merchant_id; + +ALTER TABLE merchant_account DROP primary_business_details; + +ALTER TABLE merchant_account DROP locker_id; + +ALTER TABLE merchant_account DROP intent_fulfillment_time; + +ALTER TABLE merchant_account DROP default_profile; + +ALTER TABLE merchant_account DROP payment_link_config; + +ALTER TABLE merchant_account DROP pm_collect_link_config; + +ALTER TABLE merchant_account DROP is_recon_enabled; + +ALTER TABLE merchant_account DROP webhook_details;
refactor
recreate id and remove deprecated fields from merchant account (#5493)
aafb115acb3e9a00b89992288ddc306c450a584b
2023-02-14 17:13:17
Kartikeya Hegde
fix: throw 500 error when redis goes down (#531)
false
diff --git a/crates/redis_interface/src/lib.rs b/crates/redis_interface/src/lib.rs index c62251cbcd3..376c438e67e 100644 --- a/crates/redis_interface/src/lib.rs +++ b/crates/redis_interface/src/lib.rs @@ -21,8 +21,12 @@ pub mod commands; pub mod errors; pub mod types; +use std::sync::{atomic, Arc}; + use common_utils::errors::CustomResult; use error_stack::{IntoReport, ResultExt}; +use fred::interfaces::ClientLike; +use futures::StreamExt; use router_env::logger; pub use self::{commands::*, types::*}; @@ -31,6 +35,7 @@ pub struct RedisConnectionPool { pub pool: fred::pool::RedisPool, config: RedisConfig, join_handles: Vec<fred::types::ConnectHandle>, + pub is_redis_available: Arc<atomic::AtomicBool>, } impl RedisConnectionPool { @@ -62,6 +67,7 @@ impl RedisConnectionPool { config.version = fred::types::RespVersion::RESP3; } config.tracing = true; + config.blocking = fred::types::Blocking::Error; let policy = fred::types::ReconnectPolicy::new_constant( conf.reconnect_max_attempts, conf.reconnect_delay, @@ -82,6 +88,7 @@ impl RedisConnectionPool { pool, config, join_handles, + is_redis_available: Arc::new(atomic::AtomicBool::new(true)), }) } @@ -95,6 +102,19 @@ impl RedisConnectionPool { }; } } + pub async fn on_error(&self) { + self.pool + .on_error() + .for_each(|err| { + logger::error!("{err:?}"); + if self.pool.state() == fred::types::ClientState::Disconnected { + self.is_redis_available + .store(false, atomic::Ordering::SeqCst); + } + futures::future::ready(()) + }) + .await; + } } struct RedisConfig { diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index d83f05bb28b..216c2050e25 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -69,6 +69,14 @@ pub enum StorageError { CustomerRedacted, #[error("Deserialization failure")] DeserializationFailed, + #[error("Received Error RedisError: {0}")] + ERedisError(error_stack::Report<RedisError>), +} + +impl From<error_stack::Report<RedisError>> for StorageError { + fn from(err: error_stack::Report<RedisError>) -> Self { + Self::ERedisError(err) + } } impl From<error_stack::Report<storage_errors::DatabaseError>> for StorageError { diff --git a/crates/router/src/db/cache.rs b/crates/router/src/db/cache.rs index 29e7ed4da27..b9a6143b928 100644 --- a/crates/router/src/db/cache.rs +++ b/crates/router/src/db/cache.rs @@ -14,7 +14,9 @@ where Fut: futures::Future<Output = CustomResult<T, errors::StorageError>> + Send, { let type_name = std::any::type_name::<T>(); - let redis = &store.redis_conn; + let redis = &store + .redis_conn() + .map_err(Into::<errors::StorageError>::into)?; let redis_val = redis.get_and_deserialize_key::<T>(key, type_name).await; match redis_val { Err(err) => match err.current_context() { @@ -46,7 +48,8 @@ where { let data = fun().await?; store - .redis_conn + .redis_conn() + .map_err(Into::<errors::StorageError>::into)? .delete_key(key) .await .change_context(errors::StorageError::KVError)?; diff --git a/crates/router/src/db/ephemeral_key.rs b/crates/router/src/db/ephemeral_key.rs index 1969cbbc83e..dc3e181340a 100644 --- a/crates/router/src/db/ephemeral_key.rs +++ b/crates/router/src/db/ephemeral_key.rs @@ -56,7 +56,8 @@ mod storage { }; match self - .redis_conn + .redis_conn() + .map_err(Into::<errors::StorageError>::into)? .serialize_and_set_multiple_hash_field_if_not_exist( &[(&secret_key, &created_ek), (&id_key, &created_ek)], "ephkey", @@ -72,11 +73,13 @@ mod storage { } Ok(_) => { let expire_at = expires.assume_utc().unix_timestamp(); - self.redis_conn + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? .set_expire_at(&secret_key, expire_at) .await .change_context(errors::StorageError::KVError)?; - self.redis_conn + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? .set_expire_at(&id_key, expire_at) .await .change_context(errors::StorageError::KVError)?; @@ -90,7 +93,8 @@ mod storage { key: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { let key = format!("epkey_{key}"); - self.redis_conn + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? .get_hash_field_and_deserialize(&key, "ephkey", "EphemeralKey") .await .change_context(errors::StorageError::KVError) @@ -101,12 +105,14 @@ mod storage { ) -> CustomResult<EphemeralKey, errors::StorageError> { let ek = self.get_ephemeral_key(id).await?; - self.redis_conn + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? .delete_key(&format!("epkey_{}", &ek.id)) .await .change_context(errors::StorageError::KVError)?; - self.redis_conn + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? .delete_key(&format!("epkey_{}", &ek.secret)) .await .change_context(errors::StorageError::KVError)?; diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index e3920fc0999..62ed97918ce 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -38,7 +38,8 @@ impl ConnectorAccessToken for Store { // being refreshed by other request then wait till it finishes and use the same access token let key = format!("access_token_{merchant_id}_{connector_name}"); let maybe_token = self - .redis_conn + .redis_conn() + .map_err(Into::<errors::StorageError>::into)? .get_key::<Option<Vec<u8>>>(&key) .await .change_context(errors::StorageError::KVError) @@ -63,7 +64,8 @@ impl ConnectorAccessToken for Store { let serialized_access_token = Encode::<types::AccessToken>::encode_to_string_of_json(&access_token) .change_context(errors::StorageError::SerializationFailed)?; - self.redis_conn + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? .set_key_with_expiry(&key, serialized_access_token, access_token.expires) .await .map_err(|error| { diff --git a/crates/router/src/db/payment_attempt.rs b/crates/router/src/db/payment_attempt.rs index 40acd8b9edf..e5e90efdbbe 100644 --- a/crates/router/src/db/payment_attempt.rs +++ b/crates/router/src/db/payment_attempt.rs @@ -387,7 +387,8 @@ mod storage { let field = format!("pa_{}", created_attempt.attempt_id); match self - .redis_conn + .redis_conn() + .map_err(Into::<errors::StorageError>::into)? .serialize_and_set_hash_field_if_not_exist(&key, &field, &created_attempt) .await { @@ -462,7 +463,8 @@ mod storage { .change_context(errors::StorageError::KVError)?; let field = format!("pa_{}", updated_attempt.attempt_id); let updated_attempt = self - .redis_conn + .redis_conn() + .map_err(Into::<errors::StorageError>::into)? .set_hash_fields(&key, (&field, &redis_value)) .await .map(|_| updated_attempt) @@ -538,11 +540,13 @@ mod storage { .into_report()?; db_utils::try_redis_get_else_try_database_get( - self.redis_conn.get_hash_field_and_deserialize( - &lookup.pk_id, - &lookup.sk_id, - "PaymentAttempt", - ), + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? + .get_hash_field_and_deserialize( + &lookup.pk_id, + &lookup.sk_id, + "PaymentAttempt", + ), database_call, ) .await @@ -582,11 +586,9 @@ mod storage { let key = &lookup.pk_id; db_utils::try_redis_get_else_try_database_get( - self.redis_conn.get_hash_field_and_deserialize( - key, - &lookup.sk_id, - "PaymentAttempt", - ), + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? + .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"), database_call, ) .await @@ -645,11 +647,9 @@ mod storage { let key = &lookup.pk_id; db_utils::try_redis_get_else_try_database_get( - self.redis_conn.get_hash_field_and_deserialize( - key, - &lookup.sk_id, - "PaymentAttempt", - ), + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? + .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"), database_call, ) .await @@ -682,11 +682,9 @@ mod storage { .into_report()?; let key = &lookup.pk_id; db_utils::try_redis_get_else_try_database_get( - self.redis_conn.get_hash_field_and_deserialize( - key, - &lookup.sk_id, - "PaymentAttempt", - ), + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? + .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"), database_call, ) .await diff --git a/crates/router/src/db/payment_intent.rs b/crates/router/src/db/payment_intent.rs index 0af74c153da..f9e8d4c0755 100644 --- a/crates/router/src/db/payment_intent.rs +++ b/crates/router/src/db/payment_intent.rs @@ -95,7 +95,8 @@ mod storage { }; match self - .redis_conn + .redis_conn() + .map_err(Into::<errors::StorageError>::into)? .serialize_and_set_hash_field_if_not_exist(&key, "pi", &created_intent) .await { @@ -152,7 +153,8 @@ mod storage { .change_context(errors::StorageError::SerializationFailed)?; let updated_intent = self - .redis_conn + .redis_conn() + .map_err(Into::<errors::StorageError>::into)? .set_hash_fields(&key, ("pi", &redis_value)) .await .map(|_| updated_intent) @@ -201,7 +203,8 @@ mod storage { enums::MerchantStorageScheme::RedisKv => { let key = format!("{merchant_id}_{payment_id}"); db_utils::try_redis_get_else_try_database_get( - self.redis_conn + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? .get_hash_field_and_deserialize(&key, "pi", "PaymentIntent"), database_call, ) diff --git a/crates/router/src/db/queue.rs b/crates/router/src/db/queue.rs index ce0401886a0..590dd55918a 100644 --- a/crates/router/src/db/queue.rs +++ b/crates/router/src/db/queue.rs @@ -23,9 +23,15 @@ pub trait QueueInterface { id: &RedisEntryId, ) -> CustomResult<(), RedisError>; - async fn acquire_pt_lock(&self, tag: &str, lock_key: &str, lock_val: &str, ttl: i64) -> bool; + async fn acquire_pt_lock( + &self, + tag: &str, + lock_key: &str, + lock_val: &str, + ttl: i64, + ) -> CustomResult<bool, RedisError>; - async fn release_pt_lock(&self, tag: &str, lock_key: &str) -> bool; + async fn release_pt_lock(&self, tag: &str, lock_key: &str) -> CustomResult<bool, RedisError>; async fn stream_append_entry( &self, @@ -47,7 +53,10 @@ impl QueueInterface for Store { ) -> CustomResult<Vec<storage::ProcessTracker>, ProcessTrackerError> { crate::scheduler::consumer::fetch_consumer_tasks( self, - &self.redis_conn.clone(), + &self + .redis_conn() + .map_err(ProcessTrackerError::ERedisError)? + .clone(), stream_name, group_name, consumer_name, @@ -61,15 +70,21 @@ impl QueueInterface for Store { group: &str, id: &RedisEntryId, ) -> CustomResult<(), RedisError> { - self.redis_conn + self.redis_conn()? .consumer_group_create(stream, group, id) .await } - async fn acquire_pt_lock(&self, tag: &str, lock_key: &str, lock_val: &str, ttl: i64) -> bool { - let conn = self.redis_conn.clone(); + async fn acquire_pt_lock( + &self, + tag: &str, + lock_key: &str, + lock_val: &str, + ttl: i64, + ) -> CustomResult<bool, RedisError> { + let conn = self.redis_conn()?.clone(); let is_lock_acquired = conn.set_key_if_not_exist(lock_key, lock_val).await; - match is_lock_acquired { + Ok(match is_lock_acquired { Ok(SetnxReply::KeySet) => match conn.set_expiry(lock_key, ttl).await { Ok(()) => true, @@ -88,18 +103,18 @@ impl QueueInterface for Store { logger::error!(error=%error.current_context(), %tag, "Error while locking"); false } - } + }) } - async fn release_pt_lock(&self, tag: &str, lock_key: &str) -> bool { - let is_lock_released = self.redis_conn.delete_key(lock_key).await; - match is_lock_released { + async fn release_pt_lock(&self, tag: &str, lock_key: &str) -> CustomResult<bool, RedisError> { + let is_lock_released = self.redis_conn()?.delete_key(lock_key).await; + Ok(match is_lock_released { Ok(()) => true, Err(error) => { logger::error!(error=%error.current_context(), %tag, "Error while releasing lock"); false } - } + }) } async fn stream_append_entry( @@ -108,13 +123,13 @@ impl QueueInterface for Store { entry_id: &RedisEntryId, fields: Vec<(&str, String)>, ) -> CustomResult<(), RedisError> { - self.redis_conn + self.redis_conn()? .stream_append_entry(stream, entry_id, fields) .await } async fn get_key(&self, key: &str) -> CustomResult<Vec<u8>, RedisError> { - self.redis_conn.get_key::<Vec<u8>>(key).await + self.redis_conn()?.get_key::<Vec<u8>>(key).await } } @@ -148,14 +163,14 @@ impl QueueInterface for MockDb { _lock_key: &str, _lock_val: &str, _ttl: i64, - ) -> bool { + ) -> CustomResult<bool, RedisError> { // [#172]: Implement function for `MockDb` - false + Ok(false) } - async fn release_pt_lock(&self, _tag: &str, _lock_key: &str) -> bool { + async fn release_pt_lock(&self, _tag: &str, _lock_key: &str) -> CustomResult<bool, RedisError> { // [#172]: Implement function for `MockDb` - false + Ok(false) } async fn stream_append_entry( diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index dbf7d1c96cb..8e3d69ee5f0 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -242,11 +242,9 @@ mod storage { let key = &lookup.pk_id; db_utils::try_redis_get_else_try_database_get( - self.redis_conn.get_hash_field_and_deserialize( - key, - &lookup.sk_id, - "Refund", - ), + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? + .get_hash_field_and_deserialize(key, &lookup.sk_id, "Refund"), database_call, ) .await @@ -300,7 +298,8 @@ mod storage { &created_refund.attempt_id, &created_refund.refund_id ); match self - .redis_conn + .redis_conn() + .map_err(Into::<errors::StorageError>::into)? .serialize_and_set_hash_field_if_not_exist(&key, &field, &created_refund) .await { @@ -391,7 +390,8 @@ mod storage { let pattern = db_utils::generate_hscan_pattern_for_refund(&lookup.sk_id); - self.redis_conn + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? .hscan_and_deserialize(key, &pattern, None) .await .change_context(errors::StorageError::KVError) @@ -433,7 +433,8 @@ mod storage { ) .change_context(errors::StorageError::SerializationFailed)?; - self.redis_conn + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? .set_hash_fields(&lookup.pk_id, (field, redis_value)) .await .change_context(errors::StorageError::KVError)?; @@ -484,11 +485,9 @@ mod storage { let key = &lookup.pk_id; db_utils::try_redis_get_else_try_database_get( - self.redis_conn.get_hash_field_and_deserialize( - key, - &lookup.sk_id, - "Refund", - ), + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? + .get_hash_field_and_deserialize(key, &lookup.sk_id, "Refund"), database_call, ) .await @@ -535,7 +534,8 @@ mod storage { let pattern = db_utils::generate_hscan_pattern_for_refund(&lookup.sk_id); - self.redis_conn + self.redis_conn() + .map_err(Into::<errors::StorageError>::into)? .hscan_and_deserialize(&key, &pattern, None) .await .change_context(errors::StorageError::KVError) diff --git a/crates/router/src/scheduler/producer.rs b/crates/router/src/scheduler/producer.rs index 04c5d4b7ce8..7218bd86d5c 100644 --- a/crates/router/src/scheduler/producer.rs +++ b/crates/router/src/scheduler/producer.rs @@ -62,20 +62,16 @@ pub async fn run_producer_flow( op: &SchedulerOptions, settings: &SchedulerSettings, ) -> CustomResult<(), errors::ProcessTrackerError> { - lock_acquire_release::<_, _, error_stack::Report<errors::ProcessTrackerError>>( - state, - settings, - move || async { - let tasks = fetch_producer_tasks(&*state.store, op, settings).await?; - debug!("Producer count of tasks {}", tasks.len()); + lock_acquire_release::<_, _>(state, settings, move || async { + let tasks = fetch_producer_tasks(&*state.store, op, settings).await?; + debug!("Producer count of tasks {}", tasks.len()); - // [#268]: Allow task based segregation of tasks + // [#268]: Allow task based segregation of tasks - divide_and_append_tasks(state, SchedulerFlow::Producer, tasks, settings).await?; + divide_and_append_tasks(state, SchedulerFlow::Producer, tasks, settings).await?; - Ok(()) - }, - ) + Ok(()) + }) .await?; Ok(()) diff --git a/crates/router/src/scheduler/utils.rs b/crates/router/src/scheduler/utils.rs index 94d656370e3..c9faf265c33 100644 --- a/crates/router/src/scheduler/utils.rs +++ b/crates/router/src/scheduler/utils.rs @@ -331,14 +331,14 @@ fn get_delay<'a>( } } -pub(crate) async fn lock_acquire_release<F, Fut, E>( +pub(crate) async fn lock_acquire_release<F, Fut>( state: &AppState, settings: &SchedulerSettings, callback: F, -) -> Result<(), E> +) -> CustomResult<(), errors::ProcessTrackerError> where F: Fn() -> Fut, - Fut: futures::Future<Output = Result<(), E>>, + Fut: futures::Future<Output = CustomResult<(), errors::ProcessTrackerError>>, { let tag = "PRODUCER_LOCK"; let lock_key = &settings.producer.lock_key; @@ -349,9 +349,15 @@ where .store .acquire_pt_lock(tag, lock_key, lock_val, ttl) .await - { + .change_context(errors::ProcessTrackerError::ERedisError( + errors::RedisError::RedisConnectionError.into(), + ))? { let result = callback().await; - state.store.release_pt_lock(tag, lock_key).await; + state + .store + .release_pt_lock(tag, lock_key) + .await + .map_err(errors::ProcessTrackerError::ERedisError)?; result } else { Ok(()) diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index 3492b3e5c50..6e6c57281ef 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -4,12 +4,17 @@ pub mod authentication; pub mod encryption; pub mod logger; -use std::sync::Arc; +use std::sync::{atomic, Arc}; + +use redis_interface::errors::RedisError; pub use self::api::*; #[cfg(feature = "basilisk")] pub use self::encryption::*; -use crate::connection::{diesel_make_pg_pool, PgPool}; +use crate::{ + connection::{diesel_make_pg_pool, PgPool}, + core::errors, +}; #[derive(Clone)] pub struct Store { @@ -30,11 +35,18 @@ pub(crate) struct StoreConfig { impl Store { pub async fn new(config: &crate::configs::settings::Settings, test_transaction: bool) -> Self { + let redis_conn = Arc::new(crate::connection::redis_connection(config).await); + let redis_clone = redis_conn.clone(); + + tokio::spawn(async move { + redis_clone.on_error().await; + }); + Self { master_pool: diesel_make_pg_pool(&config.master_database, test_transaction).await, #[cfg(feature = "olap")] replica_pool: diesel_make_pg_pool(&config.replica_database, test_transaction).await, - redis_conn: Arc::new(crate::connection::redis_connection(config).await), + redis_conn, #[cfg(feature = "kv_store")] config: StoreConfig { drainer_stream_name: config.drainer.stream_name.clone(), @@ -49,6 +61,20 @@ impl Store { format!("{{{}}}_{}", shard_key, self.config.drainer_stream_name,) } + pub fn redis_conn( + &self, + ) -> errors::CustomResult<Arc<redis_interface::RedisConnectionPool>, RedisError> { + if self + .redis_conn + .is_redis_available + .load(atomic::Ordering::SeqCst) + { + Ok(self.redis_conn.clone()) + } else { + Err(RedisError::RedisConnectionError.into()) + } + } + #[cfg(feature = "kv_store")] pub(crate) async fn push_to_drainer_stream<T>( &self,
fix
throw 500 error when redis goes down (#531)
31a38db8005e6e566c3c7330bdcfca0cbdca19eb
2024-11-13 14:53:14
Uzair Khan
docs(analytics): add setup instructions for currency_conversion service (#6516)
false
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.
docs
add setup instructions for currency_conversion service (#6516)
cf72dcdbb6d2164b83b22593f4ebd1be9c774b58
2023-06-22 16:40:10
Sai Harsha Vardhan
fix(connector): [ACI] fix cancel and refund request encoder (#1507)
false
diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs index 46e98d9663d..c956a8e0ae2 100644 --- a/crates/router/src/connector/aci.rs +++ b/crates/router/src/connector/aci.rs @@ -374,7 +374,7 @@ impl let connector_req = aci::AciCancelRequest::try_from(req)?; let aci_req = types::RequestBody::log_and_get_request_body( &connector_req, - utils::Encode::<aci::AciCancelRequest>::encode_to_string_of_json, + utils::Encode::<aci::AciCancelRequest>::url_encode, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(aci_req)) @@ -483,7 +483,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref let connector_req = aci::AciRefundRequest::try_from(req)?; let body = types::RequestBody::log_and_get_request_body( &connector_req, - utils::Encode::<aci::AciRefundRequest>::encode_to_string_of_json, + utils::Encode::<aci::AciRefundRequest>::url_encode, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(body))
fix
[ACI] fix cancel and refund request encoder (#1507)
78ce8f756357b89795fbb6351e897bfe6d1117c0
2023-07-20 19:40:41
Prasunna Soppa
fix(connector): [Adyen] Fix error message for fraud check from Adyen connector (#1763)
false
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index d04fd1b84e9..dbb48f60bc9 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2003,8 +2003,9 @@ pub fn get_adyen_response( .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: response .refusal_reason + .clone() .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), - reason: None, + reason: response.refusal_reason, status_code, }) } else { diff --git a/crates/router/tests/connectors/adyen_uk_ui.rs b/crates/router/tests/connectors/adyen_uk_ui.rs index e6f64614b19..6cf4aa2782c 100644 --- a/crates/router/tests/connectors/adyen_uk_ui.rs +++ b/crates/router/tests/connectors/adyen_uk_ui.rs @@ -749,5 +749,3 @@ fn should_make_adyen_dana_payment_test() { fn should_make_adyen_online_banking_fpx_payment_test() { tester!(should_make_adyen_online_banking_fpx_payment); } - -// https://hs-payments-test.netlify.app/paypal-redirect?amount=70.00&country=US&currency=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&apikey=dev_uFpxA0r6jjbVaxHSY3X0BZLL3erDUzvg3i51abwB1Bknu3fdiPxw475DQgnByn1z
fix
[Adyen] Fix error message for fraud check from Adyen connector (#1763)
2f3ec7f951967359d3995f743a486f3b380dd1f8
2024-02-28 17:52:08
AkshayaFoiger
refactor(connector): [Gocardless] Mask PII data (#3844)
false
diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs index d3703bc6bf8..21fc44fe84f 100644 --- a/crates/router/src/connector/gocardless/transformers.rs +++ b/crates/router/src/connector/gocardless/transformers.rs @@ -547,7 +547,7 @@ pub struct GocardlessMandateResponse { #[derive(Debug, Clone, Deserialize, Serialize)] pub struct MandateResponse { - id: String, + id: Secret<String>, } impl<F> @@ -570,7 +570,7 @@ impl<F> >, ) -> Result<Self, Self::Error> { let mandate_reference = Some(MandateReference { - connector_mandate_id: Some(item.response.mandates.id.clone()), + connector_mandate_id: Some(item.response.mandates.id.clone().expose()), payment_method_id: None, }); Ok(Self {
refactor
[Gocardless] Mask PII data (#3844)
c36c5d69a7cbfdb8c62641e99c530752c3802653
2024-08-22 17:24:16
GORAKHNATH YADAV
docs: Adding redirect url details (#5507)
false
diff --git a/api-reference/introduction.mdx b/api-reference/introduction.mdx index 5c59dbc11eb..5f92f11fda2 100644 --- a/api-reference/introduction.mdx +++ b/api-reference/introduction.mdx @@ -49,3 +49,16 @@ Hyperswitch handles the complex functionality of a comprehensive payments flow t | failed | The payments object transitions to a failed state when the payment processor confirms the processing failure. | | expired | You can expire the payments object while it is in any state except when it is under ‘processing’ or ‘succeeded’ state. | <img src="assets/images/image.png" /> + +## Redirect URL +This is what a url looks like after redirection + + ```https://app.hyperswitch.io?status=succeeded&payment_intent_client_secret=pay_NCv9vc19f8aa75OpFxH8_secret_V4zAc7V0C8WAw6FECMKM&amount=10000&manual_retry_allowed=false&signature=4fae0cfa775e4551db9356563d4b98b55662fe3c1c945fe215d90ccf3541282c535909ae901d82174d6b1e46ba1684aa0aa4c8861be0e2a9ef6f950a975d5014&signature_algorithm=HMAC-SHA512``` + +The available parameters are as follows: + +- **status** - can have values of `succeeded`, `processing`and `failed`. +- **payment_intent_client_secret** - This is the client secret associated with the payment. This can be used to retrieve the payment status from hyperswitch. +- **manual_retry_allowed** - whether this payment can be retried or not. +- **signature** - A HMAC signature of the payload, this can be verified using the `payment_response_hash_key`. +- **signature_algorithm** - The HMAC algorithm used to calculate the signature. diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index d556c09c6df..63dae96511a 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -14863,17 +14863,6 @@ } } }, - { - "type": "object", - "required": [ - "paypal" - ], - "properties": { - "paypal": { - "type": "object" - } - } - }, { "type": "object", "required": [ diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index e5b0d4cad0b..b02d44f9806 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -2985,7 +2985,6 @@ where | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard {} | PaymentMethodDataResponse::PayLater(_) - | PaymentMethodDataResponse::Paypal {} | PaymentMethodDataResponse::RealTimePayment {} | PaymentMethodDataResponse::Upi {} | PaymentMethodDataResponse::Wallet {} @@ -3012,7 +3011,6 @@ pub enum PaymentMethodDataResponse { BankTransfer {}, Wallet {}, PayLater(Box<PaylaterResponse>), - Paypal {}, BankRedirect {}, Crypto {}, BankDebit {},
docs
Adding redirect url details (#5507)
9314d1446326fd8a69f1f69657a976bbe7c27901
2023-11-03 18:57:20
chikke srujan
fix(connector): [Bluesnap] fix psync status to failure when it is '403' (#2772)
false
diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs index 24d5787aa8d..6c39fc41b72 100644 --- a/crates/router/src/connector/bluesnap.rs +++ b/crates/router/src/connector/bluesnap.rs @@ -37,6 +37,8 @@ use crate::{ utils::{self, BytesExt}, }; +pub const BLUESNAP_TRANSACTION_NOT_FOUND: &str = "is not authorized to view merchant-transaction:"; + #[derive(Debug, Clone)] pub struct Bluesnap; @@ -132,12 +134,24 @@ impl ConnectorCommon for Bluesnap { message: error_res.error_name.clone().unwrap_or(error_res.error_code), reason: Some(error_res.error_description), }, - bluesnap::BluesnapErrors::General(error_response) => ErrorResponse { - status_code: res.status_code, - code: consts::NO_ERROR_CODE.to_string(), - message: error_response.clone(), - reason: Some(error_response), - }, + bluesnap::BluesnapErrors::General(error_response) => { + let error_res = if res.status_code == 403 + && error_response.contains(BLUESNAP_TRANSACTION_NOT_FOUND) + { + format!( + "{} in bluesnap dashboard", + consts::REQUEST_TIMEOUT_PAYMENT_NOT_FOUND + ) + } else { + error_response.clone() + }; + ErrorResponse { + status_code: res.status_code, + code: consts::NO_ERROR_CODE.to_string(), + message: error_response, + reason: Some(error_res), + } + } }; Ok(response_error_message) } @@ -322,21 +336,26 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - let meta_data: CustomResult<bluesnap::BluesnapConnectorMetaData, errors::ConnectorError> = - connector_utils::to_connector_meta_from_secret(req.connector_meta_data.clone()); - - match meta_data { - // if merchant_id is present, psync can be made using merchant_transaction_id - Ok(data) => get_url_with_merchant_transaction_id( - self.base_url(connectors).to_string(), - data.merchant_id, - req.attempt_id.to_owned(), - ), - // otherwise psync is made using connector_transaction_id - Err(_) => get_psync_url_with_connector_transaction_id( - &req.request.connector_transaction_id, - self.base_url(connectors).to_string(), - ), + let connector_transaction_id = req.request.connector_transaction_id.clone(); + match connector_transaction_id { + // if connector_transaction_id is present, we always sync with connector_transaction_id + types::ResponseId::ConnectorTransactionId(trans_id) => { + get_psync_url_with_connector_transaction_id( + trans_id, + self.base_url(connectors).to_string(), + ) + } + _ => { + // if connector_transaction_id is not present, we sync with merchant_transaction_id + let meta_data: bluesnap::BluesnapConnectorMetaData = + connector_utils::to_connector_meta_from_secret(req.connector_meta_data.clone()) + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + get_url_with_merchant_transaction_id( + self.base_url(connectors).to_string(), + meta_data.merchant_id, + req.attempt_id.to_owned(), + ) + } } } @@ -1269,12 +1288,9 @@ fn get_url_with_merchant_transaction_id( } fn get_psync_url_with_connector_transaction_id( - connector_transaction_id: &types::ResponseId, + connector_transaction_id: String, base_url: String, ) -> CustomResult<String, errors::ConnectorError> { - let connector_transaction_id = connector_transaction_id - .get_connector_transaction_id() - .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; Ok(format!( "{}{}{}", base_url, "services/2/transactions/", connector_transaction_id diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index f76df746658..2f2563ee397 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -13,6 +13,7 @@ pub(crate) const ALPHABETS: [char; 62] = [ pub const REQUEST_TIME_OUT: u64 = 30; pub const REQUEST_TIMEOUT_ERROR_CODE: &str = "TIMEOUT"; pub const REQUEST_TIMEOUT_ERROR_MESSAGE: &str = "Connector did not respond in specified time"; +pub const REQUEST_TIMEOUT_PAYMENT_NOT_FOUND: &str = "Timed out ,payment not found"; pub const REQUEST_TIMEOUT_ERROR_MESSAGE_FROM_PSYNC: &str = "This Payment has been moved to failed as there is no response from the connector"; diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 1467da7f816..60d3bc165a9 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -326,7 +326,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( match err.status_code { // marking failure for 2xx because this is genuine payment failure 200..=299 => storage::enums::AttemptStatus::Failure, - _ => payment_data.payment_attempt.status, + _ => router_data.status, } } else { match err.status_code { diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index a1e657c7d92..3d618d047ea 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -10,7 +10,7 @@ use std::{ }; use actix_web::{body, web, FromRequest, HttpRequest, HttpResponse, Responder, ResponseError}; -use api_models::enums::CaptureMethod; +use api_models::enums::{AttemptStatus, CaptureMethod}; pub use client::{proxy_bypass_urls, ApiClient, MockApiClient, ProxyClient}; pub use common_utils::request::{ContentType, Method, Request, RequestBuilder}; use common_utils::{ @@ -403,7 +403,21 @@ where 500..=511 => { connector_integration.get_5xx_error_response(body)? } - _ => connector_integration.get_error_response(body)?, + _ => { + let error_res = + connector_integration.get_error_response(body)?; + if router_data.connector == "bluesnap" + && error_res.status_code == 403 + && error_res.reason + == Some(format!( + "{} in bluesnap dashboard", + consts::REQUEST_TIMEOUT_PAYMENT_NOT_FOUND + )) + { + router_data.status = AttemptStatus::Failure; + }; + error_res + } }; router_data.response = Err(error);
fix
[Bluesnap] fix psync status to failure when it is '403' (#2772)
642c3f3a45d5cdb5da5a0c246eb1a8b2ef699202
2023-03-28 00:20:17
Abhishek
refactor(services): make AppState impl generic using AppStateInfo (#805)
false
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index de437df04dc..066716190e7 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -12,7 +12,7 @@ use crate::{ errors::{self, RouterResult}, }, db::StorageInterface, - routes::{app::AppStateInfo, AppState}, + routes::app::AppStateInfo, services::api, types::storage, utils::OptionExt, @@ -124,14 +124,17 @@ where pub struct MerchantIdAuth(pub String); #[async_trait] -impl AuthenticateAndFetch<storage::MerchantAccount, AppState> for MerchantIdAuth { +impl<A> AuthenticateAndFetch<storage::MerchantAccount, A> for MerchantIdAuth +where + A: AppStateInfo + Sync, +{ async fn authenticate_and_fetch( &self, _request_headers: &HeaderMap, - state: &AppState, + state: &A, ) -> RouterResult<storage::MerchantAccount> { state - .store + .store() .find_merchant_account_by_merchant_id(self.0.as_ref()) .await .map_err(|e| { @@ -148,16 +151,19 @@ impl AuthenticateAndFetch<storage::MerchantAccount, AppState> for MerchantIdAuth pub struct PublishableKeyAuth; #[async_trait] -impl AuthenticateAndFetch<storage::MerchantAccount, AppState> for PublishableKeyAuth { +impl<A> AuthenticateAndFetch<storage::MerchantAccount, A> for PublishableKeyAuth +where + A: AppStateInfo + Sync, +{ async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, - state: &AppState, + state: &A, ) -> RouterResult<storage::MerchantAccount> { let publishable_key = get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; state - .store + .store() .find_merchant_account_by_publishable_key(publishable_key) .await .map_err(|e| { @@ -250,10 +256,10 @@ where Box::new(default_auth) } -pub fn get_auth_type_and_flow( +pub fn get_auth_type_and_flow<A: AppStateInfo + Sync>( headers: &HeaderMap, ) -> RouterResult<( - Box<dyn AuthenticateAndFetch<storage::MerchantAccount, AppState>>, + Box<dyn AuthenticateAndFetch<storage::MerchantAccount, A>>, api::AuthFlow, )> { let api_key = get_api_key(headers)?; @@ -298,11 +304,11 @@ where Ok((Box::new(ApiKeyAuth), api::AuthFlow::Merchant)) } -pub async fn is_ephemeral_auth( +pub async fn is_ephemeral_auth<A: AppStateInfo + Sync>( headers: &HeaderMap, db: &dyn StorageInterface, customer_id: &str, -) -> RouterResult<Box<dyn AuthenticateAndFetch<storage::MerchantAccount, AppState>>> { +) -> RouterResult<Box<dyn AuthenticateAndFetch<storage::MerchantAccount, A>>> { let api_key = get_api_key(headers)?; if !api_key.starts_with("epk") {
refactor
make AppState impl generic using AppStateInfo (#805)
3963219e44bd771353d754aa356097e2d78a1392
2024-04-10 18:08:40
Sampras Lopes
feat(events): Add events framework for registering events (#4115)
false
diff --git a/Cargo.lock b/Cargo.lock index f17cd059480..5aaf6b67235 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2799,6 +2799,19 @@ version = "2.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" +[[package]] +name = "events" +version = "0.1.0" +dependencies = [ + "error-stack", + "masking", + "router_env", + "serde", + "serde_json", + "thiserror", + "time", +] + [[package]] name = "external_services" version = "0.1.0" @@ -5589,6 +5602,7 @@ dependencies = [ "erased-serde", "error-stack", "euclid", + "events", "external_services", "futures 0.3.30", "hex", diff --git a/crates/events/Cargo.toml b/crates/events/Cargo.toml new file mode 100644 index 00000000000..b0d352f81e8 --- /dev/null +++ b/crates/events/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "events" +description = "Events framework for generating events & some sample implementations" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true +license.workspace = true + +[dependencies] +# First Party crates +masking = { version = "0.1.0", path = "../masking" } +router_env = { version = "0.1.0", path = "../router_env" } + +# Third Party crates +error-stack = "0.4.1" +serde = "1.0.197" +serde_json = "1.0.114" +thiserror = "1.0.58" +time = "0.3.34" diff --git a/crates/events/src/lib.rs b/crates/events/src/lib.rs new file mode 100644 index 00000000000..03bccbb517f --- /dev/null +++ b/crates/events/src/lib.rs @@ -0,0 +1,267 @@ +#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide))] +#![cfg_attr(docsrs, doc(cfg_hide(doc)))] +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +//! +//! A generic event handler system. +//! This library consists of 4 parts: +//! Event Sink: A trait that defines how events are published. This could be a simple logger, a message queue, or a database. +//! EventContext: A struct that holds the event sink and metadata about the event. This is used to create events. This can be used to add metadata to all events, such as the user who triggered the event. +//! EventInfo: A trait that defines the metadata that is sent with the event. It works with the EventContext to add metadata to all events. +//! Event: A trait that defines the event itself. This trait is used to define the data that is sent with the event and defines the event's type & identifier. +//! + +use std::{collections::HashMap, sync::Arc}; + +use error_stack::{Result, ResultExt}; +use masking::{ErasedMaskSerialize, Serialize}; +use router_env::logger; +use serde::Serializer; +use serde_json::Value; +use time::PrimitiveDateTime; + +/// Errors that can occur when working with events. +#[derive(Debug, Clone, thiserror::Error)] +pub enum EventsError { + /// An error occurred when publishing the event. + #[error("Generic Error")] + GenericError, + /// An error occurred when serializing the event. + #[error("Event serialization error")] + SerializationError, + /// An error occurred when publishing/producing the event. + #[error("Event publishing error")] + PublishError, +} + +/// An event that can be published. +pub trait Event: EventInfo { + /// The type of the event. + type EventType; + /// The timestamp of the event. + fn timestamp(&self) -> PrimitiveDateTime; + + /// The (unique) identifier of the event. + fn identifier(&self) -> String; + + /// The class/type of the event. This is used to group/categorize events together. + fn class(&self) -> Self::EventType; +} + +/// Hold the context information for any events +#[derive(Clone)] +pub struct EventContext<T, A> +where + A: MessagingInterface<MessageClass = T>, +{ + message_sink: Arc<A>, + metadata: HashMap<String, Value>, +} + +/// intermediary structure to build events with in-place info. +#[must_use] +pub struct EventBuilder<T, A, E, D> +where + A: MessagingInterface<MessageClass = T>, + E: Event<EventType = T, Data = D>, +{ + message_sink: Arc<A>, + metadata: HashMap<String, Value>, + event: E, +} + +struct RawEvent<T, A: Event<EventType = T>>(HashMap<String, Value>, A); + +impl<T, A, E, D> EventBuilder<T, A, E, D> +where + A: MessagingInterface<MessageClass = T>, + E: Event<EventType = T, Data = D>, +{ + /// Add metadata to the event. + pub fn with<F: ErasedMaskSerialize, G: EventInfo<Data = F> + 'static>( + mut self, + info: G, + ) -> Self { + info.data() + .and_then(|i| { + i.masked_serialize() + .change_context(EventsError::SerializationError) + }) + .map_err(|e| { + logger::error!("Error adding event info: {:?}", e); + }) + .ok() + .and_then(|data| self.metadata.insert(info.key(), data)); + self + } + /// Emit the event and log any errors. + pub fn emit(self) { + self.try_emit() + .map_err(|e| { + logger::error!("Error emitting event: {:?}", e); + }) + .ok(); + } + + /// Emit the event. + #[must_use = "make sure to call `emit` to actually emit the event"] + pub fn try_emit(self) -> Result<(), EventsError> { + let ts = self.event.timestamp(); + self.message_sink + .send_message(RawEvent(self.metadata, self.event), ts) + } +} + +impl<T, A> Serialize for RawEvent<T, A> +where + A: Event<EventType = T>, +{ + fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error> + where + S: Serializer, + { + let mut serialize_map: HashMap<_, _> = self + .0 + .iter() + .filter_map(|(k, v)| Some((k.clone(), v.masked_serialize().ok()?))) + .collect(); + match self.1.data().map(|i| i.masked_serialize()) { + Ok(Ok(Value::Object(map))) => { + for (k, v) in map.into_iter() { + serialize_map.insert(k, v); + } + } + Ok(Ok(i)) => { + serialize_map.insert(self.1.key(), i); + } + i => { + logger::error!("Error serializing event: {:?}", i); + } + }; + serialize_map.serialize(serializer) + } +} + +impl<T, A> EventContext<T, A> +where + A: MessagingInterface<MessageClass = T>, +{ + /// Create a new event context. + pub fn new(message_sink: A) -> Self { + Self { + message_sink: Arc::new(message_sink), + metadata: HashMap::new(), + } + } + + /// Add metadata to the event context. + #[track_caller] + pub fn record_info<G: ErasedMaskSerialize, E: EventInfo<Data = G> + 'static>( + &mut self, + info: E, + ) { + match info.data().and_then(|i| { + i.masked_serialize() + .change_context(EventsError::SerializationError) + }) { + Ok(data) => { + self.metadata.insert(info.key(), data); + } + Err(e) => { + logger::error!("Error recording event info: {:?}", e); + } + } + } + + /// Emit an event. + pub fn try_emit<E: Event<EventType = T>>(&self, event: E) -> Result<(), EventsError> { + EventBuilder { + message_sink: self.message_sink.clone(), + metadata: self.metadata.clone(), + event, + } + .try_emit() + } + + /// Emit an event. + pub fn emit<D, E: Event<EventType = T, Data = D>>(&self, event: E) { + EventBuilder { + message_sink: self.message_sink.clone(), + metadata: self.metadata.clone(), + event, + } + .emit() + } + + /// Create an event builder. + pub fn event<D, E: Event<EventType = T, Data = D>>( + &self, + event: E, + ) -> EventBuilder<T, A, E, D> { + EventBuilder { + message_sink: self.message_sink.clone(), + metadata: self.metadata.clone(), + event, + } + } +} + +/// Add information/metadata to the current context of an event. +pub trait EventInfo { + /// The data that is sent with the event. + type Data: ErasedMaskSerialize; + /// The data that is sent with the event. + fn data(&self) -> Result<Self::Data, EventsError>; + + /// The key identifying the data for an event. + fn key(&self) -> String; +} + +impl EventInfo for (String, String) { + type Data = String; + fn data(&self) -> Result<String, EventsError> { + Ok(self.1.clone()) + } + + fn key(&self) -> String { + self.0.clone() + } +} + +/// A messaging interface for sending messages/events. +/// This can be implemented for any messaging system, such as a message queue, a logger, or a database. +pub trait MessagingInterface { + /// The type of the event used for categorization by the event publisher. + type MessageClass; + /// Send a message that follows the defined message class. + fn send_message<T>(&self, data: T, timestamp: PrimitiveDateTime) -> Result<(), EventsError> + where + T: Message<Class = Self::MessageClass> + ErasedMaskSerialize; +} + +/// A message that can be sent. +pub trait Message { + /// The type of the event used for categorization by the event publisher. + type Class; + /// The type of the event used for categorization by the event publisher. + fn get_message_class(&self) -> Self::Class; + + /// The (unique) identifier of the event. + fn identifier(&self) -> String; +} + +impl<T, A> Message for RawEvent<T, A> +where + A: Event<EventType = T>, +{ + type Class = T; + + fn get_message_class(&self) -> Self::Class { + self.1.class() + } + + fn identifier(&self) -> String { + self.1.identifier() + } +} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 002e22ec4d8..1adecf37c67 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -124,6 +124,7 @@ rdkafka = "0.36.2" isocountry = "0.3.2" iso_currency = "0.4.4" actix-http = "3.6.0" +events = { version = "0.1.0", path = "../events" } [build-dependencies] router_env = { version = "0.1.0", path = "../router_env", default-features = false } diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index a9c2b8995b5..b3e72008cc4 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -122,7 +122,7 @@ pub mod routes { state, &req, domain.into_inner(), - |_, _, domain: analytics::AnalyticsDomain| async { + |_, _, domain: analytics::AnalyticsDomain, _| async { analytics::core::get_domain_info(domain) .await .map(ApplicationResponse::Json) @@ -154,7 +154,7 @@ pub mod routes { state, &req, payload, - |state, auth: AuthenticationData, req| async move { + |state, auth: AuthenticationData, req, _| async move { analytics::payments::get_metrics( &state.pool, &auth.merchant_account.merchant_id, @@ -190,7 +190,7 @@ pub mod routes { state, &req, payload, - |state, auth: AuthenticationData, req| async move { + |state, auth: AuthenticationData, req, _| async move { analytics::refunds::get_metrics( &state.pool, &auth.merchant_account.merchant_id, @@ -226,7 +226,7 @@ pub mod routes { state, &req, payload, - |state, auth: AuthenticationData, req| async move { + |state, auth: AuthenticationData, req, _| async move { analytics::sdk_events::get_metrics( &state.pool, auth.merchant_account.publishable_key.as_ref(), @@ -252,7 +252,7 @@ pub mod routes { state, &req, json_payload.into_inner(), - |state, auth: AuthenticationData, req| async move { + |state, auth: AuthenticationData, req, _| async move { analytics::payments::get_filters( &state.pool, req, @@ -278,7 +278,7 @@ pub mod routes { state, &req, json_payload.into_inner(), - |state, auth: AuthenticationData, req: GetRefundFilterRequest| async move { + |state, auth: AuthenticationData, req: GetRefundFilterRequest, _| async move { analytics::refunds::get_filters( &state.pool, req, @@ -304,7 +304,7 @@ pub mod routes { state, &req, json_payload.into_inner(), - |state, auth: AuthenticationData, req| async move { + |state, auth: AuthenticationData, req, _| async move { analytics::sdk_events::get_filters( &state.pool, req, @@ -330,7 +330,7 @@ pub mod routes { state, &req, json_payload.into_inner(), - |state, auth: AuthenticationData, req| async move { + |state, auth: AuthenticationData, req, _| async move { api_events_core(&state.pool, req, auth.merchant_account.merchant_id) .await .map(ApplicationResponse::Json) @@ -354,7 +354,7 @@ pub mod routes { state, &req, json_payload.into_inner(), - |state, auth: AuthenticationData, req| async move { + |state, auth: AuthenticationData, req, _| async move { outgoing_webhook_events_core(&state.pool, req, auth.merchant_account.merchant_id) .await .map(ApplicationResponse::Json) @@ -376,7 +376,7 @@ pub mod routes { state, &req, json_payload.into_inner(), - |state, auth: AuthenticationData, req| async move { + |state, auth: AuthenticationData, req, _| async move { sdk_events_core( &state.pool, req, @@ -402,7 +402,7 @@ pub mod routes { state.clone(), &req, json_payload.into_inner(), - |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload| async move { + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { let user = UserInterface::find_user_by_id(&*state.store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; @@ -444,7 +444,7 @@ pub mod routes { state.clone(), &req, json_payload.into_inner(), - |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload| async move { + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { let user = UserInterface::find_user_by_id(&*state.store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; @@ -486,7 +486,7 @@ pub mod routes { state.clone(), &req, json_payload.into_inner(), - |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload| async move { + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { let user = UserInterface::find_user_by_id(&*state.store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; @@ -538,7 +538,7 @@ pub mod routes { state.clone(), &req, payload, - |state, auth: AuthenticationData, req| async move { + |state, auth: AuthenticationData, req, _| async move { analytics::api_event::get_api_event_metrics( &state.pool, &auth.merchant_account.merchant_id, @@ -564,7 +564,7 @@ pub mod routes { state.clone(), &req, json_payload.into_inner(), - |state, auth: AuthenticationData, req| async move { + |state, auth: AuthenticationData, req, _| async move { analytics::api_event::get_filters( &state.pool, req, @@ -590,7 +590,7 @@ pub mod routes { state, &req, json_payload.into_inner(), - |state, auth: AuthenticationData, req| async move { + |state, auth: AuthenticationData, req, _| async move { connector_events_core(&state.pool, req, auth.merchant_account.merchant_id) .await .map(ApplicationResponse::Json) @@ -612,7 +612,7 @@ pub mod routes { state.clone(), &req, json_payload.into_inner(), - |state, auth: AuthenticationData, req| async move { + |state, auth: AuthenticationData, req, _| async move { analytics::search::msearch_results( req, &auth.merchant_account.merchant_id, @@ -643,7 +643,7 @@ pub mod routes { state.clone(), &req, indexed_req, - |state, auth: AuthenticationData, req| async move { + |state, auth: AuthenticationData, req, _| async move { analytics::search::search_results( req, &auth.merchant_account.merchant_id, @@ -669,7 +669,7 @@ pub mod routes { state, &req, json_payload.into_inner(), - |state, auth: AuthenticationData, req| async move { + |state, auth: AuthenticationData, req, _| async move { analytics::disputes::get_filters( &state.pool, req, @@ -704,7 +704,7 @@ pub mod routes { state, &req, payload, - |state, auth: AuthenticationData, req| async move { + |state, auth: AuthenticationData, req, _| async move { analytics::disputes::get_metrics( &state.pool, &auth.merchant_account.merchant_id, diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs index cd2ce4835e5..3628c72a31c 100644 --- a/crates/router/src/compatibility/stripe/customers.rs +++ b/crates/router/src/compatibility/stripe/customers.rs @@ -35,7 +35,6 @@ pub async fn customer_create( _, _, _, - _, types::CreateCustomerResponse, errors::StripeErrorCode, _, @@ -44,7 +43,7 @@ pub async fn customer_create( state.into_inner(), &req, create_cust_req, - |state, auth, req| { + |state, auth, req, _| { customers::create_customer(state, auth.merchant_account, auth.key_store, req) }, &auth::ApiKeyAuth, @@ -70,7 +69,6 @@ pub async fn customer_retrieve( _, _, _, - _, types::CustomerRetrieveResponse, errors::StripeErrorCode, _, @@ -79,7 +77,7 @@ pub async fn customer_retrieve( state.into_inner(), &req, payload, - |state, auth, req| { + |state, auth, req, _| { customers::retrieve_customer(state, auth.merchant_account, auth.key_store, req) }, &auth::ApiKeyAuth, @@ -114,7 +112,6 @@ pub async fn customer_update( _, _, _, - _, types::CustomerUpdateResponse, errors::StripeErrorCode, _, @@ -123,7 +120,7 @@ pub async fn customer_update( state.into_inner(), &req, cust_update_req, - |state, auth, req| { + |state, auth, req, _| { customers::update_customer(state, auth.merchant_account, req, auth.key_store) }, &auth::ApiKeyAuth, @@ -149,7 +146,6 @@ pub async fn customer_delete( _, _, _, - _, types::CustomerDeleteResponse, errors::StripeErrorCode, _, @@ -158,7 +154,7 @@ pub async fn customer_delete( state.into_inner(), &req, payload, - |state, auth, req| { + |state, auth, req, _| { customers::delete_customer(state, auth.merchant_account, req, auth.key_store) }, &auth::ApiKeyAuth, @@ -183,7 +179,6 @@ pub async fn list_customer_payment_method_api( _, _, _, - _, types::CustomerPaymentMethodListResponse, errors::StripeErrorCode, _, @@ -192,7 +187,7 @@ pub async fn list_customer_payment_method_api( state.into_inner(), &req, payload, - |state, auth, req| { + |state, auth, req, _| { cards::do_list_customer_pm_fetch_customer_if_not_passed( state, auth.merchant_account, diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs index 87560032ea4..609116fd887 100644 --- a/crates/router/src/compatibility/stripe/payment_intents.rs +++ b/crates/router/src/compatibility/stripe/payment_intents.rs @@ -43,7 +43,6 @@ pub async fn payment_intents_create( _, _, _, - _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, @@ -52,7 +51,7 @@ pub async fn payment_intents_create( state.into_inner(), &req, create_payment_req, - |state, auth, req| { + |state, auth, req, _| { let eligible_connectors = req.connector.clone(); payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _,Oss>( state, @@ -104,7 +103,6 @@ pub async fn payment_intents_retrieve( _, _, _, - _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, @@ -113,7 +111,7 @@ pub async fn payment_intents_retrieve( state.into_inner(), &req, payload, - |state, auth, payload| { + |state, auth, payload, _| { payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _, Oss>( state, auth.merchant_account, @@ -174,7 +172,6 @@ pub async fn payment_intents_retrieve_with_gateway_creds( _, _, _, - _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, @@ -183,7 +180,7 @@ pub async fn payment_intents_retrieve_with_gateway_creds( state.into_inner(), &req, payload, - |state, auth, req| { + |state, auth, req, _| { payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _,Oss>( state, auth.merchant_account, @@ -239,7 +236,6 @@ pub async fn payment_intents_update( _, _, _, - _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, @@ -248,7 +244,7 @@ pub async fn payment_intents_update( state.into_inner(), &req, payload, - |state, auth, req| { + |state, auth, req, _| { let eligible_connectors = req.connector.clone(); payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _,Oss>( state, @@ -311,7 +307,6 @@ pub async fn payment_intents_confirm( _, _, _, - _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, @@ -320,7 +315,7 @@ pub async fn payment_intents_confirm( state.into_inner(), &req, payload, - |state, auth, req| { + |state, auth, req, _| { let eligible_connectors = req.connector.clone(); payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _,Oss>( state, @@ -373,7 +368,6 @@ pub async fn payment_intents_capture( _, _, _, - _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, @@ -382,7 +376,7 @@ pub async fn payment_intents_capture( state.into_inner(), &req, payload, - |state, auth, payload| { + |state, auth, payload, _| { payments::payments_core::<api_types::Capture, api_types::PaymentsResponse, _, _, _,Oss>( state, auth.merchant_account, @@ -438,7 +432,6 @@ pub async fn payment_intents_cancel( _, _, _, - _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, @@ -447,7 +440,7 @@ pub async fn payment_intents_cancel( state.into_inner(), &req, payload, - |state, auth, req| { + |state, auth, req, _| { payments::payments_core::<api_types::Void, api_types::PaymentsResponse, _, _, _, Oss>( state, auth.merchant_account, @@ -484,7 +477,6 @@ pub async fn payment_intent_list( _, _, _, - _, types::StripePaymentIntentListResponse, errors::StripeErrorCode, _, @@ -493,7 +485,7 @@ pub async fn payment_intent_list( state.into_inner(), &req, payload, - |state, auth, req| payments::list_payments(state, auth.merchant_account, req), + |state, auth, req, _| payments::list_payments(state, auth.merchant_account, req), &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rs index 80ebbc4f84d..da68e79e422 100644 --- a/crates/router/src/compatibility/stripe/refunds.rs +++ b/crates/router/src/compatibility/stripe/refunds.rs @@ -40,7 +40,6 @@ pub async fn refund_create( _, _, _, - _, types::StripeRefundResponse, errors::StripeErrorCode, _, @@ -49,7 +48,7 @@ pub async fn refund_create( state.into_inner(), &req, create_refund_req, - |state, auth, req| { + |state, auth, req, _| { refunds::refund_create_core(state, auth.merchant_account, auth.key_store, req) }, &auth::ApiKeyAuth, @@ -85,7 +84,6 @@ pub async fn refund_retrieve_with_gateway_creds( _, _, _, - _, types::StripeRefundResponse, errors::StripeErrorCode, _, @@ -94,7 +92,7 @@ pub async fn refund_retrieve_with_gateway_creds( state.into_inner(), &req, refund_request, - |state, auth, refund_request| { + |state, auth, refund_request, _| { refunds::refund_response_wrapper( state, auth.merchant_account, @@ -128,7 +126,6 @@ pub async fn refund_retrieve( _, _, _, - _, types::StripeRefundResponse, errors::StripeErrorCode, _, @@ -137,7 +134,7 @@ pub async fn refund_retrieve( state.into_inner(), &req, refund_request, - |state, auth, refund_request| { + |state, auth, refund_request, _| { refunds::refund_response_wrapper( state, auth.merchant_account, @@ -169,7 +166,6 @@ pub async fn refund_update( _, _, _, - _, types::StripeRefundResponse, errors::StripeErrorCode, _, @@ -178,7 +174,7 @@ pub async fn refund_update( state.into_inner(), &req, create_refund_update_req, - |state, auth, req| refunds::refund_update_core(state, auth.merchant_account, req), + |state, auth, req, _| refunds::refund_update_core(state, auth.merchant_account, req), &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs index 6522dc4697c..d56937e91c4 100644 --- a/crates/router/src/compatibility/stripe/setup_intents.rs +++ b/crates/router/src/compatibility/stripe/setup_intents.rs @@ -44,7 +44,6 @@ pub async fn setup_intents_create( _, _, _, - _, types::StripeSetupIntentResponse, errors::StripeErrorCode, _, @@ -53,7 +52,7 @@ pub async fn setup_intents_create( state.into_inner(), &req, create_payment_req, - |state, auth, req| { + |state, auth, req, _| { payments::payments_core::< api_types::SetupMandate, api_types::PaymentsResponse, @@ -111,7 +110,6 @@ pub async fn setup_intents_retrieve( _, _, _, - _, types::StripeSetupIntentResponse, errors::StripeErrorCode, _, @@ -120,7 +118,7 @@ pub async fn setup_intents_retrieve( state.into_inner(), &req, payload, - |state, auth, payload| { + |state, auth, payload, _| { payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _, Oss>( state, auth.merchant_account, @@ -177,7 +175,6 @@ pub async fn setup_intents_update( _, _, _, - _, types::StripeSetupIntentResponse, errors::StripeErrorCode, _, @@ -186,7 +183,7 @@ pub async fn setup_intents_update( state.into_inner(), &req, payload, - |state, auth, req| { + |state, auth, req, _| { payments::payments_core::< api_types::SetupMandate, api_types::PaymentsResponse, @@ -251,7 +248,6 @@ pub async fn setup_intents_confirm( _, _, _, - _, types::StripeSetupIntentResponse, errors::StripeErrorCode, _, @@ -260,7 +256,7 @@ pub async fn setup_intents_confirm( state.into_inner(), &req, payload, - |state, auth, req| { + |state, auth, req, _| { payments::payments_core::< api_types::SetupMandate, api_types::PaymentsResponse, diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs index da9a7f3d163..96163727da3 100644 --- a/crates/router/src/compatibility/wrap.rs +++ b/crates/router/src/compatibility/wrap.rs @@ -8,22 +8,25 @@ use serde::Serialize; use crate::{ core::{api_locking, errors}, events::api_logs::ApiEventMetric, - routes::{app::AppStateInfo, metrics}, + routes::{ + app::{AppStateInfo, ReqState}, + metrics, AppState, + }, services::{self, api, authentication as auth, logger}, }; #[instrument(skip(request, payload, state, func, api_authentication))] -pub async fn compatibility_api_wrap<'a, 'b, A, U, T, Q, F, Fut, S, E, E2>( +pub async fn compatibility_api_wrap<'a, 'b, U, T, Q, F, Fut, S, E, E2>( flow: impl router_env::types::FlowMetric, - state: Arc<A>, + state: Arc<AppState>, request: &'a HttpRequest, payload: T, func: F, - api_authentication: &dyn auth::AuthenticateAndFetch<U, A>, + api_authentication: &dyn auth::AuthenticateAndFetch<U, AppState>, lock_action: api_locking::LockAction, ) -> HttpResponse where - F: Fn(A, U, T) -> Fut, + F: Fn(AppState, U, T, ReqState) -> Fut, Fut: Future<Output = CustomResult<api::ApplicationResponse<Q>, E2>>, E2: ErrorSwitch<E> + std::error::Error + Send + Sync + 'static, Q: Serialize + std::fmt::Debug + 'a + ApiEventMetric, @@ -32,7 +35,6 @@ where error_stack::Report<E>: services::EmbedError, errors::ApiErrorResponse: ErrorSwitch<E>, T: std::fmt::Debug + Serialize + ApiEventMetric, - A: AppStateInfo + Clone, { let request_method = request.method().as_str(); let url_path = request.path(); @@ -41,11 +43,13 @@ where let start_instant = Instant::now(); logger::info!(tag = ?Tag::BeginRequest, payload = ?payload); + let req_state = state.get_req_state(); let server_wrap_util_res = metrics::request::record_request_time_metric( api::server_wrap_util( &flow, state.clone().into(), + req_state, request, payload, func, diff --git a/crates/router/src/core/connector_onboarding.rs b/crates/router/src/core/connector_onboarding.rs index 21377d0ba0b..b69b2996a6a 100644 --- a/crates/router/src/core/connector_onboarding.rs +++ b/crates/router/src/core/connector_onboarding.rs @@ -3,8 +3,9 @@ use masking::Secret; use crate::{ core::errors::{ApiErrorResponse, RouterResponse, RouterResult}, + routes::app::ReqState, services::{authentication as auth, ApplicationResponse}, - types::{self as oss_types}, + types as oss_types, utils::connector_onboarding as utils, AppState, }; @@ -20,6 +21,7 @@ pub async fn get_action_url( state: AppState, user_from_token: auth::UserFromToken, request: api::ActionUrlRequest, + _req_state: ReqState, ) -> RouterResponse<api::ActionUrlResponse> { utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id) .await?; @@ -54,6 +56,7 @@ pub async fn sync_onboarding_status( state: AppState, user_from_token: auth::UserFromToken, request: api::OnboardingSyncRequest, + _req_state: ReqState, ) -> RouterResponse<api::OnboardingStatus> { utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id) .await?; @@ -107,6 +110,7 @@ pub async fn reset_tracking_id( state: AppState, user_from_token: auth::UserFromToken, request: api::ResetTrackingIdRequest, + _req_state: ReqState, ) -> RouterResponse<()> { utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id) .await?; diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 50fd094d8d0..364af0f83dd 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -15,7 +15,7 @@ use super::errors::{StorageErrorExt, UserErrors, UserResponse, UserResult}; use crate::services::email::types as email_types; use crate::{ consts, - routes::AppState, + routes::{app::ReqState, AppState}, services::{authentication as auth, authorization::roles, ApplicationResponse}, types::{domain, transformers::ForeignInto}, utils, @@ -429,6 +429,7 @@ pub async fn invite_user( state: AppState, request: user_api::InviteUserRequest, user_from_token: auth::UserFromToken, + req_state: ReqState, ) -> UserResponse<user_api::InviteUserResponse> { let inviter_user = state .store @@ -571,6 +572,9 @@ pub async fn invite_user( let is_email_sent; #[cfg(feature = "email")] { + // Doing this to avoid clippy lints + // will add actual usage for this later + let _ = req_state.clone(); let email_contents = email_types::InviteUser { recipient_email: invitee_email, user_name: domain::UserName::new(new_user.get_name())?, @@ -603,6 +607,7 @@ pub async fn invite_user( state.clone(), invited_user_token, set_metadata_request, + req_state, ) .await?; } @@ -624,6 +629,7 @@ pub async fn invite_multiple_user( state: AppState, user_from_token: auth::UserFromToken, requests: Vec<user_api::InviteUserRequest>, + req_state: ReqState, ) -> UserResponse<Vec<InviteMultipleUserResponse>> { if requests.len() > 10 { return Err(report!(UserErrors::MaxInvitationsError)) @@ -631,7 +637,7 @@ pub async fn invite_multiple_user( } let responses = futures::future::join_all(requests.iter().map(|request| async { - match handle_invitation(&state, &user_from_token, request).await { + match handle_invitation(&state, &user_from_token, request, &req_state).await { Ok(response) => response, Err(error) => InviteMultipleUserResponse { email: request.email.clone(), @@ -650,6 +656,7 @@ async fn handle_invitation( state: &AppState, user_from_token: &auth::UserFromToken, request: &user_api::InviteUserRequest, + req_state: &ReqState, ) -> UserResult<InviteMultipleUserResponse> { let inviter_user = user_from_token.get_user_from_db(state).await?; @@ -688,7 +695,7 @@ async fn handle_invitation( .err() .unwrap_or(false) { - handle_new_user_invitation(state, user_from_token, request).await + handle_new_user_invitation(state, user_from_token, request, req_state.clone()).await } else { Err(UserErrors::InternalServerError.into()) } @@ -770,6 +777,7 @@ async fn handle_new_user_invitation( state: &AppState, user_from_token: &auth::UserFromToken, request: &user_api::InviteUserRequest, + req_state: ReqState, ) -> UserResult<InviteMultipleUserResponse> { let new_user = domain::NewUser::try_from((request.clone(), user_from_token.clone()))?; @@ -810,6 +818,9 @@ async fn handle_new_user_invitation( let is_email_sent; #[cfg(feature = "email")] { + // TODO: Adding this to avoid clippy lints + // Will be adding actual usage for this variable later + let _ = req_state.clone(); let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; let email_contents = email_types::InviteUser { recipient_email: invitee_email, @@ -840,8 +851,13 @@ async fn handle_new_user_invitation( }; let set_metadata_request = SetMetaDataRequest::IsChangePasswordRequired; - dashboard_metadata::set_metadata(state.clone(), invited_user_token, set_metadata_request) - .await?; + dashboard_metadata::set_metadata( + state.clone(), + invited_user_token, + set_metadata_request, + req_state, + ) + .await?; } Ok(InviteMultipleUserResponse { @@ -861,6 +877,7 @@ pub async fn resend_invite( state: AppState, user_from_token: auth::UserFromToken, request: user_api::ReInviteUserRequest, + _req_state: ReqState, ) -> UserResponse<()> { let invitee_email = domain::UserEmail::from_pii_email(request.email)?; let user: domain::UserFromStorage = state @@ -1210,6 +1227,7 @@ pub async fn get_user_details_in_merchant_account( state: AppState, user_from_token: auth::UserFromToken, request: user_api::GetUserDetailsRequest, + _req_state: ReqState, ) -> UserResponse<user_api::GetUserDetailsResponse> { let required_user = utils::user::get_user_from_db_by_email(&state, request.email.try_into()?) .await @@ -1458,6 +1476,7 @@ pub async fn update_user_details( state: AppState, user_token: auth::UserFromToken, req: user_api::UpdateUserAccountDetailsRequest, + _req_state: ReqState, ) -> UserResponse<()> { let user: domain::UserFromStorage = state .store diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index 328a54c540b..bd4b2c3a10d 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -10,7 +10,7 @@ use router_env::logger; use crate::{ core::errors::{UserErrors, UserResponse, UserResult}, - routes::AppState, + routes::{app::ReqState, AppState}, services::{authentication::UserFromToken, ApplicationResponse}, types::domain::{user::dashboard_metadata as types, MerchantKeyStore}, utils::user::dashboard_metadata as utils, @@ -22,6 +22,7 @@ pub async fn set_metadata( state: AppState, user: UserFromToken, request: api::SetMetaDataRequest, + _req_state: ReqState, ) -> UserResponse<()> { let metadata_value = parse_set_request(request)?; let metadata_key = DBEnum::from(&metadata_value); @@ -35,6 +36,7 @@ pub async fn get_multiple_metadata( state: AppState, user: UserFromToken, request: GetMultipleMetaDataPayload, + _req_state: ReqState, ) -> UserResponse<Vec<api::GetMetaDataResponse>> { let metadata_keys: Vec<DBEnum> = request.results.into_iter().map(parse_get_request).collect(); diff --git a/crates/router/src/core/user/sample_data.rs b/crates/router/src/core/user/sample_data.rs index 19b7d3bd815..f95f48f19e7 100644 --- a/crates/router/src/core/user/sample_data.rs +++ b/crates/router/src/core/user/sample_data.rs @@ -7,7 +7,7 @@ pub type SampleDataApiResponse<T> = SampleDataResult<ApplicationResponse<T>>; use crate::{ core::errors::sample_data::SampleDataResult, - routes::AppState, + routes::{app::ReqState, AppState}, services::{authentication::UserFromToken, ApplicationResponse}, utils::user::sample_data::generate_sample_data, }; @@ -16,6 +16,7 @@ pub async fn generate_sample_data_for_user( state: AppState, user_from_token: UserFromToken, req: SampleDataRequest, + _req_state: ReqState, ) -> SampleDataApiResponse<()> { let sample_data = generate_sample_data(&state, req, user_from_token.merchant_id.as_str()).await?; @@ -59,6 +60,7 @@ pub async fn delete_sample_data_for_user( state: AppState, user_from_token: UserFromToken, _req: SampleDataRequest, + _req_state: ReqState, ) -> SampleDataApiResponse<()> { let merchant_id_del = user_from_token.merchant_id.as_str(); diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 2939c7d51b3..6ddab570aed 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -7,9 +7,9 @@ use router_env::logger; use crate::{ consts, core::errors::{StorageErrorExt, UserErrors, UserResponse}, - routes::AppState, + routes::{app::ReqState, AppState}, services::{ - authentication::{self as auth}, + authentication as auth, authorization::{info, roles}, ApplicationResponse, }, @@ -50,6 +50,7 @@ pub async fn update_user_role( state: AppState, user_from_token: auth::UserFromToken, req: user_role_api::UpdateUserRoleRequest, + _req_state: ReqState, ) -> UserResponse<()> { let role_info = roles::RoleInfo::from_role_id( &state, @@ -120,6 +121,7 @@ pub async fn transfer_org_ownership( state: AppState, user_from_token: auth::UserFromToken, req: user_role_api::TransferOrgOwnershipRequest, + _req_state: ReqState, ) -> UserResponse<user_api::DashboardEntryResponse> { if user_from_token.role_id != consts::user_role::ROLE_ID_ORGANIZATION_ADMIN { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( @@ -171,6 +173,7 @@ pub async fn accept_invitation( state: AppState, user_token: auth::UserWithoutMerchantFromToken, req: user_role_api::AcceptInvitationRequest, + _req_state: ReqState, ) -> UserResponse<user_api::DashboardEntryResponse> { let user_role = futures::future::join_all(req.merchant_ids.iter().map(|merchant_id| async { state @@ -223,6 +226,7 @@ pub async fn delete_user_role( state: AppState, user_from_token: auth::UserFromToken, request: user_role_api::DeleteUserRoleRequest, + _req_state: ReqState, ) -> UserResponse<()> { let user_from_db: domain::UserFromStorage = state .store diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index a0cf5a6caf9..504d5dd632b 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -7,7 +7,7 @@ use error_stack::{report, ResultExt}; use crate::{ consts, core::errors::{StorageErrorExt, UserErrors, UserResponse}, - routes::AppState, + routes::{app::ReqState, AppState}, services::{ authentication::{blacklist, UserFromToken}, authorization::roles::{self, predefined_roles::PREDEFINED_ROLES}, @@ -57,6 +57,7 @@ pub async fn create_role( state: AppState, user_from_token: UserFromToken, req: role_api::CreateRoleRequest, + _req_state: ReqState, ) -> UserResponse<role_api::RoleInfoWithGroupsResponse> { let now = common_utils::date_time::now(); let role_name = RoleName::new(req.role_name)?; diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs index d02b42d4176..d226c2bdbed 100644 --- a/crates/router/src/events.rs +++ b/crates/router/src/events.rs @@ -1,8 +1,11 @@ use data_models::errors::{StorageError, StorageResult}; use error_stack::ResultExt; +use events::{EventsError, Message, MessagingInterface}; +use masking::ErasedMaskSerialize; use router_env::logger; use serde::{Deserialize, Serialize}; use storage_impl::errors::ApplicationError; +use time::PrimitiveDateTime; use crate::{ db::KafkaProducer, @@ -14,7 +17,6 @@ pub mod audit_events; pub mod connector_api_logs; pub mod event_logger; pub mod outgoing_webhook_logs; - #[derive(Debug, Serialize, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum EventType { @@ -84,3 +86,21 @@ impl EventsHandler { }; } } + +impl MessagingInterface for EventsHandler { + type MessageClass = EventType; + + fn send_message<T>( + &self, + data: T, + timestamp: PrimitiveDateTime, + ) -> error_stack::Result<(), EventsError> + where + T: Message<Class = Self::MessageClass> + ErasedMaskSerialize, + { + match self { + Self::Kafka(a) => a.send_message(data, timestamp), + Self::Logs(a) => a.send_message(data, timestamp), + } + } +} diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs index 6000d37527d..90fc8cfe769 100644 --- a/crates/router/src/events/audit_events.rs +++ b/crates/router/src/events/audit_events.rs @@ -1,31 +1,24 @@ -use data_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent}; +use events::{Event, EventInfo}; use serde::Serialize; - -use crate::services::kafka::KafkaMessage; +use time::PrimitiveDateTime; #[derive(Debug, Clone, Serialize)] pub enum AuditEventType { - Error { - error_message: String, - }, + Error { error_message: String }, PaymentCreated, ConnectorDecided, ConnectorCalled, RefundCreated, RefundSuccess, RefundFail, - PaymentUpdate { - payment_id: String, - merchant_id: String, - payment_intent: PaymentIntent, - payment_attempt: PaymentAttempt, - }, + PaymentCancelled { cancellation_reason: Option<String> }, } #[derive(Debug, Clone, Serialize)] pub struct AuditEvent { event_type: AuditEventType, - created_at: time::PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + created_at: PrimitiveDateTime, } impl AuditEvent { @@ -37,12 +30,43 @@ impl AuditEvent { } } -impl KafkaMessage for AuditEvent { - fn key(&self) -> String { - format!("{}", self.created_at.assume_utc().unix_timestamp_nanos()) +impl Event for AuditEvent { + type EventType = super::EventType; + + fn timestamp(&self) -> PrimitiveDateTime { + self.created_at } - fn event_type(&self) -> super::EventType { + fn identifier(&self) -> String { + let event_type = match &self.event_type { + AuditEventType::Error { .. } => "error", + AuditEventType::PaymentCreated => "payment_created", + AuditEventType::ConnectorDecided => "connector_decided", + AuditEventType::ConnectorCalled => "connector_called", + AuditEventType::RefundCreated => "refund_created", + AuditEventType::RefundSuccess => "refund_success", + AuditEventType::RefundFail => "refund_fail", + AuditEventType::PaymentCancelled { .. } => "payment_cancelled", + }; + format!( + "{event_type}-{}", + self.timestamp().assume_utc().unix_timestamp_nanos() + ) + } + + fn class(&self) -> Self::EventType { super::EventType::AuditEvent } } + +impl EventInfo for AuditEvent { + type Data = Self; + + fn data(&self) -> error_stack::Result<Self::Data, events::EventsError> { + Ok(self.clone()) + } + + fn key(&self) -> String { + "event".to_string() + } +} diff --git a/crates/router/src/events/event_logger.rs b/crates/router/src/events/event_logger.rs index 6851128bf46..235ee4a3e3c 100644 --- a/crates/router/src/events/event_logger.rs +++ b/crates/router/src/events/event_logger.rs @@ -1,3 +1,8 @@ +use events::{EventsError, Message, MessagingInterface}; +use masking::ErasedMaskSerialize; +use time::PrimitiveDateTime; + +use super::EventType; use crate::services::{kafka::KafkaMessage, logger}; #[derive(Clone, Debug, Default)] @@ -6,6 +11,22 @@ pub struct EventLogger {} impl EventLogger { #[track_caller] pub(super) fn log_event<T: KafkaMessage>(&self, event: &T) { - logger::info!(event = ?serde_json::to_value(event).unwrap_or(serde_json::json!({"error": "serialization failed"})), event_type =? event.event_type(), event_id =? event.key(), log_type = "event"); + logger::info!(event = ?event.masked_serialize().unwrap_or_else(|e| serde_json::json!({"error": e.to_string()})), event_type =? event.event_type(), event_id =? event.key(), log_type =? "event"); + } +} + +impl MessagingInterface for EventLogger { + type MessageClass = EventType; + + fn send_message<T>( + &self, + data: T, + _timestamp: PrimitiveDateTime, + ) -> error_stack::Result<(), EventsError> + where + T: Message<Class = Self::MessageClass> + ErasedMaskSerialize, + { + logger::info!(event =? data.masked_serialize().unwrap_or_else(|e| serde_json::json!({"error": e.to_string()})), event_type =? data.get_message_class(), event_id =? data.identifier(), log_type =? "event"); + Ok(()) } } diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index f5a6a49b9c9..bc534dde390 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -35,7 +35,7 @@ pub async fn merchant_account_create( state, &req, json_payload.into_inner(), - |state, _, req| create_merchant_account(state, req), + |state, _, req, _| create_merchant_account(state, req), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) @@ -74,7 +74,7 @@ pub async fn retrieve_merchant_account( state, &req, payload, - |state, _, req| get_merchant_account(state, req), + |state, _, req, _| get_merchant_account(state, req), auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { @@ -102,7 +102,7 @@ pub async fn merchant_account_list( state, &req, query_params.into_inner(), - |state, _, request| list_merchant_account(state, request), + |state, _, request, _| list_merchant_account(state, request), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) @@ -139,7 +139,7 @@ pub async fn update_merchant_account( state, &req, json_payload.into_inner(), - |state, _, req| merchant_account_update(state, &merchant_id, req), + |state, _, req, _| merchant_account_update(state, &merchant_id, req), auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { @@ -184,7 +184,7 @@ pub async fn delete_merchant_account( state, &req, payload, - |state, _, req| merchant_account_delete(state, req.merchant_id), + |state, _, req, _| merchant_account_delete(state, req.merchant_id), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, ) @@ -219,7 +219,7 @@ pub async fn payment_connector_create( state, &req, json_payload.into_inner(), - |state, _, req| create_payment_connector(state, req, &merchant_id), + |state, _, req, _| create_payment_connector(state, req, &merchant_id), auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { @@ -270,7 +270,7 @@ pub async fn payment_connector_retrieve( state, &req, payload, - |state, _, req| { + |state, _, req, _| { retrieve_payment_connector(state, req.merchant_id, req.merchant_connector_id) }, auth::auth_type( @@ -317,7 +317,7 @@ pub async fn payment_connector_list( state, &req, merchant_id.to_owned(), - |state, _, merchant_id| list_payment_connectors(state, merchant_id), + |state, _, merchant_id, _| list_payment_connectors(state, merchant_id), auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { @@ -365,7 +365,9 @@ pub async fn payment_connector_update( state, &req, json_payload.into_inner(), - |state, _, req| update_payment_connector(state, &merchant_id, &merchant_connector_id, req), + |state, _, req, _| { + update_payment_connector(state, &merchant_id, &merchant_connector_id, req) + }, auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { @@ -416,7 +418,9 @@ pub async fn payment_connector_delete( state, &req, payload, - |state, _, req| delete_payment_connector(state, req.merchant_id, req.merchant_connector_id), + |state, _, req, _| { + delete_payment_connector(state, req.merchant_id, req.merchant_connector_id) + }, auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { @@ -448,7 +452,7 @@ pub async fn merchant_account_toggle_kv( state, &req, payload, - |state, _, payload| kv_for_merchant(state, payload.merchant_id, payload.kv_enabled), + |state, _, payload, _| kv_for_merchant(state, payload.merchant_id, payload.kv_enabled), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, ) @@ -470,7 +474,7 @@ pub async fn business_profile_create( state, &req, payload, - |state, _, req| create_business_profile(state, req, &merchant_id), + |state, _, req, _| create_business_profile(state, req, &merchant_id), auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { @@ -497,7 +501,7 @@ pub async fn business_profile_retrieve( state, &req, profile_id, - |state, _, profile_id| retrieve_business_profile(state, profile_id), + |state, _, profile_id, _| retrieve_business_profile(state, profile_id), auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { @@ -525,7 +529,7 @@ pub async fn business_profile_update( state, &req, json_payload.into_inner(), - |state, _, req| update_business_profile(state, &profile_id, &merchant_id, req), + |state, _, req, _| update_business_profile(state, &profile_id, &merchant_id, req), auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { @@ -552,7 +556,7 @@ pub async fn business_profile_delete( state, &req, profile_id, - |state, _, profile_id| delete_business_profile(state, profile_id, &merchant_id), + |state, _, profile_id, _| delete_business_profile(state, profile_id, &merchant_id), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, ) @@ -572,7 +576,7 @@ pub async fn business_profiles_list( state, &req, merchant_id.clone(), - |state, _, merchant_id| list_business_profile(state, merchant_id), + |state, _, merchant_id, _| list_business_profile(state, merchant_id), auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { @@ -602,7 +606,7 @@ pub async fn merchant_account_kv_status( state, &req, merchant_id, - |state, _, req| check_merchant_account_kv_status(state, req), + |state, _, req, _| check_merchant_account_kv_status(state, req), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, ) diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index 2e95fd536cf..55959589152 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -41,7 +41,7 @@ pub async fn api_key_create( state, &req, payload, - |state, _, payload| async { + |state, _, payload, _| async { api_keys::create_api_key(state, payload, merchant_id.clone()).await }, auth::auth_type( @@ -88,7 +88,7 @@ pub async fn api_key_retrieve( state, &req, (&merchant_id, &key_id), - |state, _, (merchant_id, key_id)| api_keys::retrieve_api_key(state, merchant_id, key_id), + |state, _, (merchant_id, key_id), _| api_keys::retrieve_api_key(state, merchant_id, key_id), auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { @@ -138,7 +138,7 @@ pub async fn api_key_update( state, &req, payload, - |state, _, payload| api_keys::update_api_key(state, payload), + |state, _, payload, _| api_keys::update_api_key(state, payload), auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { @@ -184,7 +184,7 @@ pub async fn api_key_revoke( state, &req, (&merchant_id, &key_id), - |state, _, (merchant_id, key_id)| api_keys::revoke_api_key(state, merchant_id, key_id), + |state, _, (merchant_id, key_id), _| api_keys::revoke_api_key(state, merchant_id, key_id), auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { @@ -233,7 +233,7 @@ pub async fn api_key_list( state, &req, (limit, offset, merchant_id.clone()), - |state, _, (limit, offset, merchant_id)| async move { + |state, _, (limit, offset, merchant_id), _| async move { api_keys::list_api_keys(state, merchant_id, limit, offset).await }, auth::auth_type( diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index e0e3045aa8a..74bb8bbc242 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -57,6 +57,11 @@ pub use crate::{ services::get_store, }; +#[derive(Clone)] +pub struct ReqState { + pub event_context: events::EventContext<crate::events::EventType, EventsHandler>, +} + #[derive(Clone)] pub struct AppState { pub flow_name: String, @@ -239,6 +244,12 @@ impl AppState { )) .await } + + pub fn get_req_state(&self) -> ReqState { + ReqState { + event_context: events::EventContext::new(self.event_handler.clone()), + } + } } pub struct Health; diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs index 87072d2c777..bd0ae9f6c66 100644 --- a/crates/router/src/routes/blocklist.rs +++ b/crates/router/src/routes/blocklist.rs @@ -31,7 +31,7 @@ pub async fn add_entry_to_blocklist( state, &req, json_payload.into_inner(), - |state, auth: auth::AuthenticationData, body| { + |state, auth: auth::AuthenticationData, body, _| { blocklist::add_entry_to_blocklist(state, auth.merchant_account, body) }, auth::auth_type( @@ -67,7 +67,7 @@ pub async fn remove_entry_from_blocklist( state, &req, json_payload.into_inner(), - |state, auth: auth::AuthenticationData, body| { + |state, auth: auth::AuthenticationData, body, _| { blocklist::remove_entry_from_blocklist(state, auth.merchant_account, body) }, auth::auth_type( @@ -105,7 +105,7 @@ pub async fn list_blocked_payment_methods( state, &req, query_payload.into_inner(), - |state, auth: auth::AuthenticationData, query| { + |state, auth: auth::AuthenticationData, query, _| { blocklist::list_blocklist_entries(state, auth.merchant_account, query) }, auth::auth_type( @@ -143,7 +143,7 @@ pub async fn toggle_blocklist_guard( state, &req, query_payload.into_inner(), - |state, auth: auth::AuthenticationData, query| { + |state, auth: auth::AuthenticationData, query, _| { blocklist::toggle_blocklist_guard(state, auth.merchant_account, query) }, auth::auth_type( diff --git a/crates/router/src/routes/cache.rs b/crates/router/src/routes/cache.rs index 520d6ab7db2..e7742d2d18c 100644 --- a/crates/router/src/routes/cache.rs +++ b/crates/router/src/routes/cache.rs @@ -22,7 +22,7 @@ pub async fn invalidate( state, &req, &key, - |state, _, key| cache::invalidate(state, key), + |state, _, key, _| cache::invalidate(state, key), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, ) diff --git a/crates/router/src/routes/cards_info.rs b/crates/router/src/routes/cards_info.rs index 79a2061ac4c..4d65fc72036 100644 --- a/crates/router/src/routes/cards_info.rs +++ b/crates/router/src/routes/cards_info.rs @@ -46,7 +46,7 @@ pub async fn card_iin_info( state, &req, payload, - |state, auth, req| cards_info::retrieve_card_info(state, auth.merchant_account, req), + |state, auth, req, _| cards_info::retrieve_card_info(state, auth.merchant_account, req), &*auth, api_locking::LockAction::NotApplicable, ) diff --git a/crates/router/src/routes/configs.rs b/crates/router/src/routes/configs.rs index d7e96f40235..74b9cd73b1e 100644 --- a/crates/router/src/routes/configs.rs +++ b/crates/router/src/routes/configs.rs @@ -22,7 +22,7 @@ pub async fn config_key_create( state, &req, payload, - |state, _, data| configs::set_config(state, data), + |state, _, data, _| configs::set_config(state, data), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, ) @@ -42,7 +42,7 @@ pub async fn config_key_retrieve( state, &req, &key, - |state, _, key| configs::read_config(state, key), + |state, _, key, _| configs::read_config(state, key), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, ) @@ -65,7 +65,7 @@ pub async fn config_key_update( state, &req, &payload, - |state, _, payload| configs::update_config(state, payload), + |state, _, payload, _| configs::update_config(state, payload), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, ) @@ -86,7 +86,7 @@ pub async fn config_key_delete( state, &req, key, - |state, _, key| configs::config_delete(state, key), + |state, _, key, _| configs::config_delete(state, key), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, ) diff --git a/crates/router/src/routes/currency.rs b/crates/router/src/routes/currency.rs index 74a559e88e9..e80bd53d8df 100644 --- a/crates/router/src/routes/currency.rs +++ b/crates/router/src/routes/currency.rs @@ -14,7 +14,7 @@ pub async fn retrieve_forex(state: web::Data<AppState>, req: HttpRequest) -> Htt state, &req, (), - |state, _auth: auth::AuthenticationData, _| currency::retrieve_forex(state), + |state, _auth: auth::AuthenticationData, _, _| currency::retrieve_forex(state), auth::auth_type( &auth::ApiKeyAuth, &auth::DashboardNoPermissionAuth, @@ -39,7 +39,7 @@ pub async fn convert_forex( state.clone(), &req, (), - |state, _, _| { + |state, _, _, _| { currency::convert_forex( state, *amount, diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index a20d2dd026b..64fa8e83d49 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -20,7 +20,7 @@ pub async fn customers_create( state, &req, json_payload.into_inner(), - |state, auth, req| create_customer(state, auth.merchant_account, auth.key_store, req), + |state, auth, req, _| create_customer(state, auth.merchant_account, auth.key_store, req), auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::CustomerWrite), @@ -57,7 +57,7 @@ pub async fn customers_retrieve( state, &req, payload, - |state, auth, req| retrieve_customer(state, auth.merchant_account, auth.key_store, req), + |state, auth, req, _| retrieve_customer(state, auth.merchant_account, auth.key_store, req), &*auth, api_locking::LockAction::NotApplicable, ) @@ -73,7 +73,9 @@ pub async fn customers_list(state: web::Data<AppState>, req: HttpRequest) -> Htt state, &req, (), - |state, auth, _| list_customers(state, auth.merchant_account.merchant_id, auth.key_store), + |state, auth, _, _| { + list_customers(state, auth.merchant_account.merchant_id, auth.key_store) + }, auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::CustomerRead), @@ -99,7 +101,7 @@ pub async fn customers_update( state, &req, json_payload.into_inner(), - |state, auth, req| update_customer(state, auth.merchant_account, req, auth.key_store), + |state, auth, req, _| update_customer(state, auth.merchant_account, req, auth.key_store), auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::CustomerWrite), @@ -126,7 +128,7 @@ pub async fn customers_delete( state, &req, payload, - |state, auth, req| delete_customer(state, auth.merchant_account, req, auth.key_store), + |state, auth, req, _| delete_customer(state, auth.merchant_account, req, auth.key_store), auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::CustomerWrite), @@ -152,7 +154,7 @@ pub async fn get_customer_mandates( state, &req, customer_id, - |state, auth, req| { + |state, auth, req, _| { crate::core::mandate::get_customer_mandates( state, auth.merchant_account, diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs index 28b3e0db211..a4a6c7507a4 100644 --- a/crates/router/src/routes/disputes.rs +++ b/crates/router/src/routes/disputes.rs @@ -43,7 +43,7 @@ pub async fn retrieve_dispute( state, &req, dispute_id, - |state, auth, req| disputes::retrieve_dispute(state, auth.merchant_account, req), + |state, auth, req, _| disputes::retrieve_dispute(state, auth.merchant_account, req), auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::DisputeRead), @@ -90,7 +90,7 @@ pub async fn retrieve_disputes_list( state, &req, payload, - |state, auth, req| disputes::retrieve_disputes_list(state, auth.merchant_account, req), + |state, auth, req, _| disputes::retrieve_disputes_list(state, auth.merchant_account, req), auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::DisputeRead), @@ -130,7 +130,7 @@ pub async fn accept_dispute( state, &req, dispute_id, - |state, auth, req| { + |state, auth, req, _| { disputes::accept_dispute(state, auth.merchant_account, auth.key_store, req) }, auth::auth_type( @@ -167,7 +167,7 @@ pub async fn submit_dispute_evidence( state, &req, json_payload.into_inner(), - |state, auth, req| { + |state, auth, req, _| { disputes::submit_evidence(state, auth.merchant_account, auth.key_store, req) }, auth::auth_type( @@ -212,7 +212,7 @@ pub async fn attach_dispute_evidence( state, &req, attach_evidence_request, - |state, auth, req| { + |state, auth, req, _| { disputes::attach_evidence(state, auth.merchant_account, auth.key_store, req) }, auth::auth_type( @@ -255,7 +255,9 @@ pub async fn retrieve_dispute_evidence( state, &req, dispute_id, - |state, auth, req| disputes::retrieve_dispute_evidence(state, auth.merchant_account, req), + |state, auth, req, _| { + disputes::retrieve_dispute_evidence(state, auth.merchant_account, req) + }, auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::DisputeRead), @@ -293,7 +295,7 @@ pub async fn delete_dispute_evidence( state, &req, json_payload.into_inner(), - |state, auth, req| disputes::delete_evidence(state, auth.merchant_account, req), + |state, auth, req, _| disputes::delete_evidence(state, auth.merchant_account, req), auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::DisputeWrite), diff --git a/crates/router/src/routes/dummy_connector.rs b/crates/router/src/routes/dummy_connector.rs index 7d2aad7e348..79338fc620c 100644 --- a/crates/router/src/routes/dummy_connector.rs +++ b/crates/router/src/routes/dummy_connector.rs @@ -27,7 +27,7 @@ pub async fn dummy_connector_authorize_payment( state, &req, payload, - |state, _, req| core::payment_authorize(state, req), + |state, _, req, _| core::payment_authorize(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, ) @@ -51,7 +51,7 @@ pub async fn dummy_connector_complete_payment( state, &req, payload, - |state, _, req| core::payment_complete(state, req), + |state, _, req, _| core::payment_complete(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, ) @@ -70,7 +70,7 @@ pub async fn dummy_connector_payment( state, &req, payload, - |state, _, req| core::payment(state, req), + |state, _, req, _| core::payment(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, ) @@ -90,7 +90,7 @@ pub async fn dummy_connector_payment_data( state, &req, payload, - |state, _, req| core::payment_data(state, req), + |state, _, req, _| core::payment_data(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, ) @@ -111,7 +111,7 @@ pub async fn dummy_connector_refund( state, &req, payload, - |state, _, req| core::refund_payment(state, req), + |state, _, req, _| core::refund_payment(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, ) @@ -131,7 +131,7 @@ pub async fn dummy_connector_refund_data( state, &req, payload, - |state, _, req| core::refund_data(state, req), + |state, _, req, _| core::refund_data(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, ) diff --git a/crates/router/src/routes/ephemeral_key.rs b/crates/router/src/routes/ephemeral_key.rs index a9e70c1b33c..bfe7c353c28 100644 --- a/crates/router/src/routes/ephemeral_key.rs +++ b/crates/router/src/routes/ephemeral_key.rs @@ -21,7 +21,7 @@ pub async fn ephemeral_key_create( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { helpers::make_ephemeral_key(state, req.customer_id, auth.merchant_account.merchant_id) }, &auth::ApiKeyAuth, @@ -42,7 +42,7 @@ pub async fn ephemeral_key_delete( state, &req, payload, - |state, _, req| helpers::delete_ephemeral_key(state, req), + |state, _, req, _| helpers::delete_ephemeral_key(state, req), &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, ) diff --git a/crates/router/src/routes/files.rs b/crates/router/src/routes/files.rs index 63dfb38c614..92be12b2bc9 100644 --- a/crates/router/src/routes/files.rs +++ b/crates/router/src/routes/files.rs @@ -44,7 +44,7 @@ pub async fn files_create( state, &req, create_file_request, - |state, auth, req| files_create_core(state, auth.merchant_account, auth.key_store, req), + |state, auth, req, _| files_create_core(state, auth.merchant_account, auth.key_store, req), auth::auth_type( &auth::ApiKeyAuth, &auth::DashboardNoPermissionAuth, @@ -86,7 +86,7 @@ pub async fn files_delete( state, &req, file_id, - |state, auth, req| files_delete_core(state, auth.merchant_account, req), + |state, auth, req, _| files_delete_core(state, auth.merchant_account, req), auth::auth_type( &auth::ApiKeyAuth, &auth::DashboardNoPermissionAuth, @@ -128,7 +128,9 @@ pub async fn files_retrieve( state, &req, file_id, - |state, auth, req| files_retrieve_core(state, auth.merchant_account, auth.key_store, req), + |state, auth, req, _| { + files_retrieve_core(state, auth.merchant_account, auth.key_store, req) + }, auth::auth_type( &auth::ApiKeyAuth, &auth::DashboardNoPermissionAuth, diff --git a/crates/router/src/routes/fraud_check.rs b/crates/router/src/routes/fraud_check.rs index d4363a236bb..f0b73015f3c 100644 --- a/crates/router/src/routes/fraud_check.rs +++ b/crates/router/src/routes/fraud_check.rs @@ -20,7 +20,7 @@ pub async fn frm_fulfillment( state.clone(), &req, json_payload.into_inner(), - |state, auth, req| { + |state, auth, req, _| { frm_core::frm_fulfillment_core(state, auth.merchant_account, auth.key_store, req) }, &services::authentication::ApiKeyAuth, diff --git a/crates/router/src/routes/gsm.rs b/crates/router/src/routes/gsm.rs index ff70635959f..77a0cb0a645 100644 --- a/crates/router/src/routes/gsm.rs +++ b/crates/router/src/routes/gsm.rs @@ -39,7 +39,7 @@ pub async fn create_gsm_rule( state.clone(), &req, payload, - |state, _, payload| gsm::create_gsm_rule(state, payload), + |state, _, payload, _| gsm::create_gsm_rule(state, payload), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) @@ -76,7 +76,7 @@ pub async fn get_gsm_rule( state.clone(), &req, gsm_retrieve_req, - |state, _, gsm_retrieve_req| gsm::retrieve_gsm_rule(state, gsm_retrieve_req), + |state, _, gsm_retrieve_req, _| gsm::retrieve_gsm_rule(state, gsm_retrieve_req), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) @@ -114,7 +114,7 @@ pub async fn update_gsm_rule( state.clone(), &req, payload, - |state, _, payload| gsm::update_gsm_rule(state, payload), + |state, _, payload, _| gsm::update_gsm_rule(state, payload), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) @@ -153,7 +153,7 @@ pub async fn delete_gsm_rule( state, &req, payload, - |state, _, payload| gsm::delete_gsm_rule(state, payload), + |state, _, payload, _| gsm::delete_gsm_rule(state, payload), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/health.rs b/crates/router/src/routes/health.rs index 2afb1c064ec..fbfcd893a63 100644 --- a/crates/router/src/routes/health.rs +++ b/crates/router/src/routes/health.rs @@ -33,7 +33,7 @@ pub async fn deep_health_check( state, &request, (), - |state, _, _| deep_health_check_func(state), + |state, _, _, _| deep_health_check_func(state), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/locker_migration.rs b/crates/router/src/routes/locker_migration.rs index a3df0c3a229..2a8b1ca7911 100644 --- a/crates/router/src/routes/locker_migration.rs +++ b/crates/router/src/routes/locker_migration.rs @@ -19,7 +19,7 @@ pub async fn rust_locker_migration( state, &req, &merchant_id, - |state, _, _| locker_migration::rust_locker_migration(state, &merchant_id), + |state, _, _, _| locker_migration::rust_locker_migration(state, &merchant_id), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index 3e47d78da8a..365f9a43248 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -41,7 +41,9 @@ pub async fn get_mandate( state, &req, mandate_id, - |state, auth, req| mandate::get_mandate(state, auth.merchant_account, auth.key_store, req), + |state, auth, req, _| { + mandate::get_mandate(state, auth.merchant_account, auth.key_store, req) + }, &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, ) @@ -80,7 +82,7 @@ pub async fn revoke_mandate( state, &req, mandate_id, - |state, auth, req| { + |state, auth, req, _| { mandate::revoke_mandate(state, auth.merchant_account, auth.key_store, req) }, &auth::ApiKeyAuth, @@ -124,7 +126,7 @@ pub async fn retrieve_mandates_list( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { mandate::retrieve_mandates_list(state, auth.merchant_account, auth.key_store, req) }, auth::auth_type( diff --git a/crates/router/src/routes/payment_link.rs b/crates/router/src/routes/payment_link.rs index dd6898724c5..7742f6c1c0e 100644 --- a/crates/router/src/routes/payment_link.rs +++ b/crates/router/src/routes/payment_link.rs @@ -44,7 +44,7 @@ pub async fn payment_link_retrieve( state, &req, payload.clone(), - |state, _auth, _| retrieve_payment_link(state, path.clone()), + |state, _auth, _, _| retrieve_payment_link(state, path.clone()), &*auth_type, api_locking::LockAction::NotApplicable, ) @@ -67,7 +67,7 @@ pub async fn initiate_payment_link( state, &req, payload.clone(), - |state, auth, _| { + |state, auth, _, _| { initiate_payment_link_flow( state, auth.merchant_account, @@ -117,7 +117,7 @@ pub async fn payments_link_list( state, &req, payload, - |state, auth, payload| list_payment_link(state, auth.merchant_account, payload), + |state, auth, payload, _| list_payment_link(state, auth.merchant_account, payload), &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, ) @@ -140,7 +140,7 @@ pub async fn payment_link_status( state, &req, payload.clone(), - |state, auth, _| { + |state, auth, _, _| { get_payment_link_status( state, auth.merchant_account, diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 7ef20994e2e..555410a416b 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -28,7 +28,7 @@ pub async fn create_payment_method_api( state, &req, json_payload.into_inner(), - |state, auth, req| async move { + |state, auth, req, _| async move { Box::pin(cards::add_payment_method( state, req, @@ -61,7 +61,7 @@ pub async fn list_payment_method_api( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { cards::list_payment_methods(state, auth.merchant_account, auth.key_store, req) }, &*auth, @@ -113,7 +113,7 @@ pub async fn list_customer_payment_method_api( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { cards::do_list_customer_pm_fetch_customer_if_not_passed( state, auth.merchant_account, @@ -169,7 +169,7 @@ pub async fn list_customer_payment_method_api_client( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { cards::do_list_customer_pm_fetch_customer_if_not_passed( state, auth.merchant_account, @@ -201,7 +201,7 @@ pub async fn payment_method_retrieve_api( state, &req, payload, - |state, auth, pm| cards::retrieve_payment_method(state, pm, auth.key_store), + |state, auth, pm, _| cards::retrieve_payment_method(state, pm, auth.key_store), &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, )) @@ -223,7 +223,7 @@ pub async fn payment_method_update_api( state, &req, json_payload.into_inner(), - |state, auth, payload| { + |state, auth, payload, _| { cards::update_customer_payment_method( state, auth.merchant_account, @@ -253,7 +253,7 @@ pub async fn payment_method_delete_api( state, &req, pm, - |state, auth, req| { + |state, auth, req, _| { cards::delete_payment_method(state, auth.merchant_account, req, auth.key_store) }, &auth::ApiKeyAuth, @@ -275,7 +275,7 @@ pub async fn list_countries_currencies_for_connector_payment_method( state, &req, payload, - |state, _auth: auth::AuthenticationData, req| { + |state, _auth: auth::AuthenticationData, req, _| { cards::list_countries_currencies_for_connector_payment_method(state, req) }, #[cfg(not(feature = "release"))] @@ -312,7 +312,7 @@ pub async fn default_payment_method_set_api( state, &req, payload, - |_state, auth: auth::AuthenticationData, default_payment_method| { + |_state, auth: auth::AuthenticationData, default_payment_method, _| { cards::set_default_payment_method( db, auth.merchant_account.merchant_id, diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index eda181f5a8b..cf12878c2fb 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -123,7 +123,7 @@ pub async fn payments_create( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { authorize_verify_select::<_, Oss>( payments::PaymentCreate, state, @@ -186,7 +186,7 @@ pub async fn payments_start( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { payments::payments_core::< api_types::Authorize, payment_types::PaymentsResponse, @@ -267,7 +267,7 @@ pub async fn payments_retrieve( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _,Oss>( state, auth.merchant_account, @@ -339,7 +339,7 @@ pub async fn payments_retrieve_with_gateway_creds( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _,Oss>( state, auth.merchant_account, @@ -408,7 +408,7 @@ pub async fn payments_update( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { authorize_verify_select::<_, Oss>( payments::PaymentUpdate, state, @@ -485,7 +485,7 @@ pub async fn payments_confirm( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { authorize_verify_select::<_, Oss>( payments::PaymentConfirm, state, @@ -543,7 +543,7 @@ pub async fn payments_capture( state, &req, payload, - |state, auth, payload| { + |state, auth, payload, _| { payments::payments_core::< api_types::Capture, payment_types::PaymentsResponse, @@ -601,7 +601,7 @@ pub async fn payments_connector_session( state, &req, payload, - |state, auth, payload| { + |state, auth, payload, _| { payments::payments_core::< api_types::Session, payment_types::PaymentsSessionResponse, @@ -672,7 +672,7 @@ pub async fn payments_redirect_response( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { <payments::PaymentRedirectSync as PaymentRedirectFlow<Oss>>::handle_payments_redirect_response( &payments::PaymentRedirectSync {}, state, @@ -732,7 +732,7 @@ pub async fn payments_redirect_response_with_creds_identifier( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { <payments::PaymentRedirectSync as PaymentRedirectFlow<Oss>>::handle_payments_redirect_response( &payments::PaymentRedirectSync {}, state, @@ -774,7 +774,7 @@ pub async fn payments_complete_authorize( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { <payments::PaymentRedirectCompleteAuthorize as PaymentRedirectFlow<Oss>>::handle_payments_redirect_response( &payments::PaymentRedirectCompleteAuthorize {}, @@ -828,7 +828,7 @@ pub async fn payments_cancel( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { payments::payments_core::<api_types::Void, payment_types::PaymentsResponse, _, _, _,Oss>( state, auth.merchant_account, @@ -885,7 +885,7 @@ pub async fn payments_list( state, &req, payload, - |state, auth, req| payments::list_payments(state, auth.merchant_account, req), + |state, auth, req, _| payments::list_payments(state, auth.merchant_account, req), auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::PaymentRead), @@ -909,7 +909,9 @@ pub async fn payments_list_by_filter( state, &req, payload, - |state, auth, req| payments::apply_filters_on_payments(state, auth.merchant_account, req), + |state, auth, req, _| { + payments::apply_filters_on_payments(state, auth.merchant_account, req) + }, auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::PaymentRead), @@ -933,7 +935,7 @@ pub async fn get_filters_for_payments( state, &req, payload, - |state, auth, req| payments::get_filters_for_payments(state, auth.merchant_account, req), + |state, auth, req, _| payments::get_filters_for_payments(state, auth.merchant_account, req), auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::PaymentRead), @@ -968,7 +970,7 @@ pub async fn payments_approve( state, &http_req, payload.clone(), - |state, auth, req| { + |state, auth, req, _| { payments::payments_core::< api_types::Capture, payment_types::PaymentsResponse, @@ -1028,7 +1030,7 @@ pub async fn payments_reject( state, &http_req, payload.clone(), - |state, auth, req| { + |state, auth, req, _| { payments::payments_core::< api_types::Void, payment_types::PaymentsResponse, @@ -1182,7 +1184,7 @@ pub async fn payments_incremental_authorization( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { payments::payments_core::< api_types::IncrementalAuthorization, payment_types::PaymentsResponse, @@ -1246,7 +1248,7 @@ pub async fn payments_external_authentication( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { payments::payment_external_authentication( state, auth.merchant_account, @@ -1304,7 +1306,7 @@ pub async fn post_3ds_payments_authorize( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { <payments::PaymentAuthenticateCompleteAuthorize as PaymentRedirectFlow<Oss>>::handle_payments_redirect_response( &payments::PaymentAuthenticateCompleteAuthorize {}, state, diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs index 2a429126c85..f3b6a7cd477 100644 --- a/crates/router/src/routes/payouts.rs +++ b/crates/router/src/routes/payouts.rs @@ -38,7 +38,9 @@ pub async fn payouts_create( state, &req, json_payload.into_inner(), - |state, auth, req| payouts_create_core(state, auth.merchant_account, auth.key_store, req), + |state, auth, req, _| { + payouts_create_core(state, auth.merchant_account, auth.key_store, req) + }, &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, )) @@ -76,7 +78,9 @@ pub async fn payouts_retrieve( state, &req, payout_retrieve_request, - |state, auth, req| payouts_retrieve_core(state, auth.merchant_account, auth.key_store, req), + |state, auth, req, _| { + payouts_retrieve_core(state, auth.merchant_account, auth.key_store, req) + }, auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::PayoutRead), @@ -118,7 +122,9 @@ pub async fn payouts_update( state, &req, payout_update_payload, - |state, auth, req| payouts_update_core(state, auth.merchant_account, auth.key_store, req), + |state, auth, req, _| { + payouts_update_core(state, auth.merchant_account, auth.key_store, req) + }, &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, )) @@ -156,7 +162,9 @@ pub async fn payouts_cancel( state, &req, payload, - |state, auth, req| payouts_cancel_core(state, auth.merchant_account, auth.key_store, req), + |state, auth, req, _| { + payouts_cancel_core(state, auth.merchant_account, auth.key_store, req) + }, &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, )) @@ -194,7 +202,9 @@ pub async fn payouts_fulfill( state, &req, payload, - |state, auth, req| payouts_fulfill_core(state, auth.merchant_account, auth.key_store, req), + |state, auth, req, _| { + payouts_fulfill_core(state, auth.merchant_account, auth.key_store, req) + }, &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, )) @@ -228,7 +238,7 @@ pub async fn payouts_list( state, &req, payload, - |state, auth, req| payouts_list_core(state, auth.merchant_account, auth.key_store, req), + |state, auth, req, _| payouts_list_core(state, auth.merchant_account, auth.key_store, req), auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::PayoutRead), @@ -266,7 +276,7 @@ pub async fn payouts_list_by_filter( state, &req, payload, - |state, auth, req| { + |state, auth, req, _| { payouts_filtered_list_core(state, auth.merchant_account, auth.key_store, req) }, auth::auth_type( @@ -306,7 +316,9 @@ pub async fn payouts_list_available_filters( state, &req, payload, - |state, auth, req| payouts_list_available_filters_core(state, auth.merchant_account, req), + |state, auth, req, _| { + payouts_list_available_filters_core(state, auth.merchant_account, req) + }, auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::PayoutRead), diff --git a/crates/router/src/routes/pm_auth.rs b/crates/router/src/routes/pm_auth.rs index cfadd787c31..e0cce9c515c 100644 --- a/crates/router/src/routes/pm_auth.rs +++ b/crates/router/src/routes/pm_auth.rs @@ -24,7 +24,7 @@ pub async fn link_token_create( state, &req, payload, - |state, auth, payload| { + |state, auth, payload, _| { crate::core::pm_auth::create_link_token( state, auth.merchant_account, @@ -58,7 +58,7 @@ pub async fn exchange_token( state, &req, payload, - |state, auth, payload| { + |state, auth, payload, _| { crate::core::pm_auth::exchange_token_core( state, auth.merchant_account, diff --git a/crates/router/src/routes/recon.rs b/crates/router/src/routes/recon.rs index faa41d9d1d2..7845f52c924 100644 --- a/crates/router/src/routes/recon.rs +++ b/crates/router/src/routes/recon.rs @@ -35,7 +35,7 @@ pub async fn update_merchant( state, &req, json_payload.into_inner(), - |state, _user, req| recon_merchant_account_update(state, req), + |state, _user, req, _| recon_merchant_account_update(state, req), &auth::ReconAdmin, api_locking::LockAction::NotApplicable, )) @@ -49,7 +49,7 @@ pub async fn request_for_recon(state: web::Data<AppState>, http_req: HttpRequest state, &http_req, (), - |state, user: UserFromToken, _req| send_recon_request(state, user), + |state, user: UserFromToken, _req, _| send_recon_request(state, user), &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) @@ -63,7 +63,7 @@ pub async fn get_recon_token(state: web::Data<AppState>, req: HttpRequest) -> Ht state, &req, (), - |state, user: ReconUser, _| generate_recon_token(state, user), + |state, user: ReconUser, _, _| generate_recon_token(state, user), &auth::ReconJWT, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index ef9ffb41124..d68c7138213 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -36,7 +36,7 @@ pub async fn refunds_create( state, &req, json_payload.into_inner(), - |state, auth, req| refund_create_core(state, auth.merchant_account, auth.key_store, req), + |state, auth, req, _| refund_create_core(state, auth.merchant_account, auth.key_store, req), auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::RefundWrite), @@ -88,7 +88,7 @@ pub async fn refunds_retrieve( state, &req, refund_request, - |state, auth, refund_request| { + |state, auth, refund_request, _| { refund_response_wrapper( state, auth.merchant_account, @@ -139,7 +139,7 @@ pub async fn refunds_retrieve_with_body( state, &req, json_payload.into_inner(), - |state, auth, req| { + |state, auth, req, _| { refund_response_wrapper( state, auth.merchant_account, @@ -187,7 +187,7 @@ pub async fn refunds_update( state, &req, refund_update_req, - |state, auth, req| refund_update_core(state, auth.merchant_account, req), + |state, auth, req, _| refund_update_core(state, auth.merchant_account, req), &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, ) @@ -220,7 +220,7 @@ pub async fn refunds_list( state, &req, payload.into_inner(), - |state, auth, req| refund_list(state, auth.merchant_account, req), + |state, auth, req, _| refund_list(state, auth.merchant_account, req), auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::RefundRead), @@ -257,7 +257,7 @@ pub async fn refunds_filter_list( state, &req, payload.into_inner(), - |state, auth, req| refund_filter_list(state, auth.merchant_account, req), + |state, auth, req, _| refund_filter_list(state, auth.merchant_account, req), auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::RefundRead), diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index 5d8330a05b4..8438424546c 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -31,7 +31,7 @@ pub async fn routing_create_config( state, &req, json_payload.into_inner(), - |state, auth: auth::AuthenticationData, payload| { + |state, auth: auth::AuthenticationData, payload, _| { routing::create_routing_config( state, auth.merchant_account, @@ -67,7 +67,7 @@ pub async fn routing_link_config( state, &req, path.into_inner(), - |state, auth: auth::AuthenticationData, algorithm_id| { + |state, auth: auth::AuthenticationData, algorithm_id, _| { routing::link_routing_config( state, auth.merchant_account, @@ -104,7 +104,7 @@ pub async fn routing_retrieve_config( state, &req, algorithm_id, - |state, auth: auth::AuthenticationData, algorithm_id| { + |state, auth: auth::AuthenticationData, algorithm_id, _| { routing::retrieve_routing_config(state, auth.merchant_account, algorithm_id) }, #[cfg(not(feature = "release"))] @@ -136,7 +136,7 @@ pub async fn list_routing_configs( state, &req, query.into_inner(), - |state, auth: auth::AuthenticationData, query_params| { + |state, auth: auth::AuthenticationData, query_params, _| { routing::retrieve_merchant_routing_dictionary( state, auth.merchant_account, @@ -165,7 +165,7 @@ pub async fn list_routing_configs( state, &req, (), - |state, auth: auth::AuthenticationData, _| { + |state, auth: auth::AuthenticationData, _, _| { routing::retrieve_merchant_routing_dictionary(state, auth.merchant_account) }, #[cfg(not(feature = "release"))] @@ -200,7 +200,7 @@ pub async fn routing_unlink_config( state, &req, payload.into_inner(), - |state, auth: auth::AuthenticationData, payload_req| { + |state, auth: auth::AuthenticationData, payload_req, _| { routing::unlink_routing_config( state, auth.merchant_account, @@ -229,7 +229,7 @@ pub async fn routing_unlink_config( state, &req, (), - |state, auth: auth::AuthenticationData, _| { + |state, auth: auth::AuthenticationData, _, _| { routing::unlink_routing_config( state, auth.merchant_account, @@ -264,7 +264,7 @@ pub async fn routing_update_default_config( state, &req, json_payload.into_inner(), - |state, auth: auth::AuthenticationData, updated_config| { + |state, auth: auth::AuthenticationData, updated_config, _| { routing::update_default_routing_config( state, auth.merchant_account, @@ -297,7 +297,7 @@ pub async fn routing_retrieve_default_config( state, &req, (), - |state, auth: auth::AuthenticationData, _| { + |state, auth: auth::AuthenticationData, _, _| { routing::retrieve_default_routing_config(state, auth.merchant_account, transaction_type) }, #[cfg(not(feature = "release"))] @@ -326,7 +326,7 @@ pub async fn upsert_surcharge_decision_manager_config( state, &req, json_payload.into_inner(), - |state, auth: auth::AuthenticationData, update_decision| { + |state, auth: auth::AuthenticationData, update_decision, _| { surcharge_decision_config::upsert_surcharge_decision_config( state, auth.key_store, @@ -358,7 +358,7 @@ pub async fn delete_surcharge_decision_manager_config( state, &req, (), - |state, auth: auth::AuthenticationData, ()| { + |state, auth: auth::AuthenticationData, (), _| { surcharge_decision_config::delete_surcharge_decision_config( state, auth.key_store, @@ -390,7 +390,7 @@ pub async fn retrieve_surcharge_decision_manager_config( state, &req, (), - |state, auth: auth::AuthenticationData, _| { + |state, auth: auth::AuthenticationData, _, _| { surcharge_decision_config::retrieve_surcharge_decision_config( state, auth.merchant_account, @@ -422,7 +422,7 @@ pub async fn upsert_decision_manager_config( state, &req, json_payload.into_inner(), - |state, auth: auth::AuthenticationData, update_decision| { + |state, auth: auth::AuthenticationData, update_decision, _| { conditional_config::upsert_conditional_config( state, auth.key_store, @@ -455,7 +455,7 @@ pub async fn delete_decision_manager_config( state, &req, (), - |state, auth: auth::AuthenticationData, ()| { + |state, auth: auth::AuthenticationData, (), _| { conditional_config::delete_conditional_config( state, auth.key_store, @@ -487,7 +487,7 @@ pub async fn retrieve_decision_manager_config( state, &req, (), - |state, auth: auth::AuthenticationData, _| { + |state, auth: auth::AuthenticationData, _, _| { conditional_config::retrieve_conditional_config(state, auth.merchant_account) }, #[cfg(not(feature = "release"))] @@ -520,7 +520,7 @@ pub async fn routing_retrieve_linked_config( state, &req, query.into_inner(), - |state, auth: AuthenticationData, query_params| { + |state, auth: AuthenticationData, query_params, _| { routing::retrieve_linked_routing_config( state, auth.merchant_account, @@ -549,7 +549,7 @@ pub async fn routing_retrieve_linked_config( state, &req, (), - |state, auth: auth::AuthenticationData, _| { + |state, auth: auth::AuthenticationData, _, _| { routing::retrieve_linked_routing_config(state, auth.merchant_account) }, #[cfg(not(feature = "release"))] @@ -584,7 +584,7 @@ pub async fn upsert_connector_agnostic_mandate_config( state, &req, json_payload.into_inner(), - |state, _auth: AuthenticationData, mandate_config| { + |state, _auth: AuthenticationData, mandate_config, _| { Box::pin(routing::upsert_connector_agnostic_mandate_config( state, &business_profile_id, @@ -613,7 +613,7 @@ pub async fn routing_retrieve_default_config_for_profiles( state, &req, (), - |state, auth: auth::AuthenticationData, _| { + |state, auth: auth::AuthenticationData, _, _| { routing::retrieve_default_routing_config_for_profiles( state, auth.merchant_account, @@ -655,7 +655,7 @@ pub async fn routing_update_default_config_for_profile( state, &req, routing_payload_wrapper, - |state, auth: auth::AuthenticationData, wrapper| { + |state, auth: auth::AuthenticationData, wrapper, _| { routing::update_default_routing_config_for_profile( state, auth.merchant_account, diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 3e5061b401d..eb34c8ae321 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -32,7 +32,7 @@ pub async fn user_signup_with_merchant_id( state, &http_req, req_payload.clone(), - |state, _, req_body| user_core::signup_with_merchant_id(state, req_body), + |state, _, req_body, _| user_core::signup_with_merchant_id(state, req_body), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) @@ -51,7 +51,7 @@ pub async fn user_signup( state, &http_req, req_payload.clone(), - |state, _, req_body| user_core::signup(state, req_body), + |state, _, req_body, _| user_core::signup(state, req_body), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -70,7 +70,7 @@ pub async fn user_signin_without_invite_checks( state, &http_req, req_payload.clone(), - |state, _, req_body| user_core::signin_without_invite_checks(state, req_body), + |state, _, req_body, _| user_core::signin_without_invite_checks(state, req_body), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -89,7 +89,7 @@ pub async fn user_signin( state, &http_req, req_payload.clone(), - |state, _, req_body| user_core::signin(state, req_body), + |state, _, req_body, _| user_core::signin(state, req_body), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -109,7 +109,7 @@ pub async fn user_connect_account( state, &http_req, req_payload.clone(), - |state, _, req_body| user_core::connect_account(state, req_body), + |state, _, req_body, _| user_core::connect_account(state, req_body), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -123,7 +123,7 @@ pub async fn signout(state: web::Data<AppState>, http_req: HttpRequest) -> HttpR state.clone(), &http_req, (), - |state, user, _| user_core::signout(state, user), + |state, user, _, _| user_core::signout(state, user), &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) @@ -141,7 +141,7 @@ pub async fn change_password( state.clone(), &http_req, json_payload.into_inner(), - |state, user, req| user_core::change_password(state, req, user), + |state, user, req, _| user_core::change_password(state, req, user), &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) @@ -211,7 +211,7 @@ pub async fn internal_user_signup( state.clone(), &http_req, json_payload.into_inner(), - |state, _, req| user_core::create_internal_user(state, req), + |state, _, req, _| user_core::create_internal_user(state, req), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) @@ -229,7 +229,7 @@ pub async fn switch_merchant_id( state.clone(), &http_req, json_payload.into_inner(), - |state, user, req| user_core::switch_merchant_id(state, req, user), + |state, user, req, _| user_core::switch_merchant_id(state, req, user), &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) @@ -247,7 +247,7 @@ pub async fn user_merchant_account_create( state, &req, json_payload.into_inner(), - |state, auth: auth::UserFromToken, json_payload| { + |state, auth: auth::UserFromToken, json_payload, _| { user_core::create_merchant_account(state, auth, json_payload) }, &auth::JWTAuth(Permission::MerchantAccountCreate), @@ -304,7 +304,7 @@ pub async fn list_merchants_for_user(state: web::Data<AppState>, req: HttpReques state, &req, (), - |state, user, _| user_core::list_merchants_for_user(state, user), + |state, user, _, _| user_core::list_merchants_for_user(state, user), &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) @@ -339,7 +339,7 @@ pub async fn list_users_for_merchant_account( state.clone(), &req, (), - |state, user, _| user_core::list_users_for_merchant_account(state, user), + |state, user, _, _| user_core::list_users_for_merchant_account(state, user), &auth::JWTAuth(Permission::UsersRead), api_locking::LockAction::NotApplicable, )) @@ -358,7 +358,7 @@ pub async fn forgot_password( state.clone(), &req, payload.into_inner(), - |state, _, payload| user_core::forgot_password(state, payload), + |state, _, payload, _| user_core::forgot_password(state, payload), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -377,7 +377,7 @@ pub async fn reset_password( state.clone(), &req, payload.into_inner(), - |state, _, payload| user_core::reset_password(state, payload), + |state, _, payload, _| user_core::reset_password(state, payload), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -395,7 +395,7 @@ pub async fn invite_user( state.clone(), &req, payload.into_inner(), - |state, user, payload| user_core::invite_user(state, payload, user), + |state, user, payload, req_state| user_core::invite_user(state, payload, user, req_state), &auth::JWTAuth(Permission::UsersWrite), api_locking::LockAction::NotApplicable, )) @@ -450,7 +450,7 @@ pub async fn accept_invite_from_email( state.clone(), &req, payload.into_inner(), - |state, _, request_payload| user_core::accept_invite_from_email(state, request_payload), + |state, _, request_payload, _| user_core::accept_invite_from_email(state, request_payload), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -469,7 +469,9 @@ pub async fn verify_email_without_invite_checks( state, &http_req, json_payload.into_inner(), - |state, _, req_payload| user_core::verify_email_without_invite_checks(state, req_payload), + |state, _, req_payload, _| { + user_core::verify_email_without_invite_checks(state, req_payload) + }, &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -488,7 +490,7 @@ pub async fn verify_email( state, &http_req, json_payload.into_inner(), - |state, _, req_payload| user_core::verify_email(state, req_payload), + |state, _, req_payload, _| user_core::verify_email(state, req_payload), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -507,7 +509,7 @@ pub async fn verify_email_request( state.clone(), &http_req, json_payload.into_inner(), - |state, _, req_body| user_core::send_verification_mail(state, req_body), + |state, _, req_body, _| user_core::send_verification_mail(state, req_body), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -522,7 +524,7 @@ pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpReques state.clone(), &http_req, (), - |state, user, _req| user_core::verify_token(state, user), + |state, user, _req, _| user_core::verify_token(state, user), &auth::ReconJWT, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index 65e2aa4cdb8..7ffcc8d09df 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -27,7 +27,7 @@ pub async fn get_authorization_info( state.clone(), &http_req, (), - |state, _: (), _| async move { + |state, _: (), _, _| async move { // TODO: Permissions to be deprecated once groups are stable if respond_with_groups { user_role_core::get_authorization_info_with_groups(state).await @@ -54,7 +54,7 @@ pub async fn get_role_from_token( state.clone(), &req, (), - |state, user, _| async move { + |state, user, _, _| async move { // TODO: Permissions to be deprecated once groups are stable if respond_with_groups { role_core::get_role_from_token_with_groups(state, user).await @@ -98,7 +98,7 @@ pub async fn list_all_roles( state.clone(), &req, (), - |state, user, _| async move { + |state, user, _, _| async move { // TODO: Permissions to be deprecated once groups are stable if respond_with_groups { role_core::list_invitable_roles_with_groups(state, user).await @@ -128,7 +128,7 @@ pub async fn get_role( state.clone(), &req, request_payload, - |state, user, payload| async move { + |state, user, payload, _| async move { // TODO: Permissions to be deprecated once groups are stable if respond_with_groups { role_core::get_role_with_groups(state, user, payload).await @@ -156,7 +156,7 @@ pub async fn update_role( state.clone(), &req, json_payload.into_inner(), - |state, user, req| role_core::update_role(state, user, req, &role_id), + |state, user, req, _| role_core::update_role(state, user, req, &role_id), &auth::JWTAuth(Permission::UsersWrite), api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/verification.rs b/crates/router/src/routes/verification.rs index 91fd204ba2f..00662663113 100644 --- a/crates/router/src/routes/verification.rs +++ b/crates/router/src/routes/verification.rs @@ -22,7 +22,7 @@ pub async fn apple_pay_merchant_registration( state, &req, json_payload.into_inner(), - |state, _, body| { + |state, _, body, _| { verification::verify_merchant_creds_for_applepay( state.clone(), body, @@ -54,7 +54,7 @@ pub async fn retrieve_apple_pay_verified_domains( state, &req, merchant_id.clone(), - |state, _, _| { + |state, _, _, _| { verification::get_verified_apple_domains_with_mid_mca_id( state, merchant_id.to_string(), diff --git a/crates/router/src/routes/verify_connector.rs b/crates/router/src/routes/verify_connector.rs index bfb1b781ada..c045b3a8e6a 100644 --- a/crates/router/src/routes/verify_connector.rs +++ b/crates/router/src/routes/verify_connector.rs @@ -20,7 +20,7 @@ pub async fn payment_connector_verify( state, &req, json_payload.into_inner(), - |state, _: (), req| verify_connector::verify_connector_credentials(state, req), + |state, _: (), req, _| verify_connector::verify_connector_credentials(state, req), &auth::JWTAuth(Permission::MerchantConnectorAccountWrite), api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/webhook_events.rs b/crates/router/src/routes/webhook_events.rs index 2ee18cbe767..ef1d64f54e9 100644 --- a/crates/router/src/routes/webhook_events.rs +++ b/crates/router/src/routes/webhook_events.rs @@ -32,7 +32,7 @@ pub async fn list_initial_webhook_delivery_attempts( state, &req, request_internal, - |state, _, request_internal| { + |state, _, request_internal, _| { webhook_events::list_initial_delivery_attempts( state, request_internal.merchant_id_or_profile_id, @@ -71,7 +71,7 @@ pub async fn list_webhook_delivery_attempts( state, &req, request_internal, - |state, _, request_internal| { + |state, _, request_internal, _| { webhook_events::list_delivery_attempts( state, request_internal.merchant_id_or_profile_id, @@ -110,7 +110,7 @@ pub async fn retry_webhook_delivery_attempt( state, &req, request_internal, - |state, _, request_internal| { + |state, _, request_internal, _| { webhook_events::retry_delivery_attempt( state, request_internal.merchant_id_or_profile_id, diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rs index 10eb4ef75e4..b9be68bbd57 100644 --- a/crates/router/src/routes/webhooks.rs +++ b/crates/router/src/routes/webhooks.rs @@ -26,7 +26,7 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>( state, &req, WebhookBytes(body), - |state, auth, payload| { + |state, auth, payload, _| { webhooks::webhooks_wrapper::<W, Oss>( &flow, state.to_owned(), diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 5a139d8da35..854574069f8 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -45,7 +45,7 @@ use crate::{ }, logger, routes::{ - app::AppStateInfo, + app::{AppStateInfo, ReqState}, metrics::{self, request as metrics_request}, AppState, }, @@ -943,23 +943,27 @@ pub enum AuthFlow { Merchant, } -#[instrument(skip(request, payload, state, func, api_auth), fields(merchant_id))] -pub async fn server_wrap_util<'a, 'b, A, U, T, Q, F, Fut, E, OErr>( +#[allow(clippy::too_many_arguments)] +#[instrument( + skip(request, payload, state, func, api_auth, request_state), + fields(merchant_id) +)] +pub async fn server_wrap_util<'a, 'b, U, T, Q, F, Fut, E, OErr>( flow: &'a impl router_env::types::FlowMetric, - state: web::Data<A>, + state: web::Data<AppState>, + request_state: ReqState, request: &'a HttpRequest, payload: T, func: F, - api_auth: &dyn AuthenticateAndFetch<U, A>, + api_auth: &dyn AuthenticateAndFetch<U, AppState>, lock_action: api_locking::LockAction, ) -> CustomResult<ApplicationResponse<Q>, OErr> where - F: Fn(A, U, T) -> Fut, + F: Fn(AppState, U, T, ReqState) -> Fut, 'b: 'a, Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>, Q: Serialize + Debug + 'a + ApiEventMetric, T: Debug + Serialize + ApiEventMetric, - A: AppStateInfo + Clone, E: ErrorSwitch<OErr> + error_stack::Context, OErr: ResponseError + error_stack::Context + Serialize, errors::ApiErrorResponse: ErrorSwitch<OErr>, @@ -969,9 +973,9 @@ where .attach_printable("Unable to extract request id from request") .change_context(errors::ApiErrorResponse::InternalServerError.switch())?; - let mut request_state = state.get_ref().clone(); + let mut app_state = state.get_ref().clone(); - request_state.add_request_id(request_id); + app_state.add_request_id(request_id); let start_instant = Instant::now(); let serialized_request = masking::masked_serialize(&payload) .attach_printable("Failed to serialize json request") @@ -981,7 +985,7 @@ where // Currently auth failures are not recorded as API events let (auth_out, auth_type) = api_auth - .authenticate_and_fetch(request.headers(), &request_state) + .authenticate_and_fetch(request.headers(), &app_state) .await .switch()?; @@ -990,23 +994,23 @@ where .unwrap_or("MERCHANT_ID_NOT_FOUND") .to_string(); - request_state.add_merchant_id(Some(merchant_id.clone())); + app_state.add_merchant_id(Some(merchant_id.clone())); - request_state.add_flow_name(flow.to_string()); + app_state.add_flow_name(flow.to_string()); tracing::Span::current().record("merchant_id", &merchant_id); let output = { lock_action .clone() - .perform_locking_action(&request_state, merchant_id.to_owned()) + .perform_locking_action(&app_state, merchant_id.to_owned()) .await .switch()?; - let res = func(request_state.clone(), auth_out, payload) + let res = func(app_state.clone(), auth_out, payload, request_state) .await .switch(); lock_action - .free_lock_action(&request_state, merchant_id.to_owned()) + .free_lock_action(&app_state, merchant_id.to_owned()) .await .switch()?; res @@ -1082,24 +1086,24 @@ where skip(request, state, func, api_auth, payload), fields(request_method, request_url_path, status_code) )] -pub async fn server_wrap<'a, A, T, U, Q, F, Fut, E>( +pub async fn server_wrap<'a, T, U, Q, F, Fut, E>( flow: impl router_env::types::FlowMetric, - state: web::Data<A>, + state: web::Data<AppState>, request: &'a HttpRequest, payload: T, func: F, - api_auth: &dyn AuthenticateAndFetch<U, A>, + api_auth: &dyn AuthenticateAndFetch<U, AppState>, lock_action: api_locking::LockAction, ) -> HttpResponse where - F: Fn(A, U, T) -> Fut, + F: Fn(AppState, U, T, ReqState) -> Fut, Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>, Q: Serialize + Debug + ApiEventMetric + 'a, T: Debug + Serialize + ApiEventMetric, - A: AppStateInfo + Clone, ApplicationResponse<Q>: Debug, E: ErrorSwitch<api_models::errors::types::ApiErrorResponse> + error_stack::Context, { + let req_state = state.get_req_state(); let request_method = request.method().as_str(); let url_path = request.path(); @@ -1136,6 +1140,7 @@ where server_wrap_util( &flow, state.clone(), + req_state, request, payload, func, diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index 166df034cc9..3ae923e246f 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -1,7 +1,9 @@ use std::sync::Arc; +use bigdecimal::ToPrimitive; use common_utils::errors::CustomResult; use error_stack::{report, ResultExt}; +use events::{EventsError, Message, MessagingInterface}; use rdkafka::{ config::FromClientConfig, producer::{BaseRecord, DefaultProducerContext, Producer, ThreadedProducer}, @@ -16,7 +18,7 @@ mod refund; use data_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent}; use diesel_models::refund::Refund; use serde::Serialize; -use time::OffsetDateTime; +use time::{OffsetDateTime, PrimitiveDateTime}; #[cfg(feature = "payouts")] use self::payout::KafkaPayout; @@ -410,3 +412,41 @@ impl Drop for RdKafkaProducer { } } } + +impl MessagingInterface for KafkaProducer { + type MessageClass = EventType; + + fn send_message<T>( + &self, + data: T, + timestamp: PrimitiveDateTime, + ) -> error_stack::Result<(), EventsError> + where + T: Message<Class = Self::MessageClass> + masking::ErasedMaskSerialize, + { + let topic = self.get_topic(data.get_message_class()); + let json_data = data + .masked_serialize() + .and_then(|i| serde_json::to_vec(&i)) + .change_context(EventsError::SerializationError)?; + self.producer + .0 + .send( + BaseRecord::to(topic) + .key(&data.identifier()) + .payload(&json_data) + .timestamp( + (timestamp.assume_utc().unix_timestamp_nanos() / 1_000) + .to_i64() + .unwrap_or_else(|| { + // kafka producer accepts milliseconds + // try converting nanos to millis if that fails convert seconds to millis + timestamp.assume_utc().unix_timestamp() * 1_000 + }), + ), + ) + .map_err(|(error, record)| report!(error).attach_printable(format!("{record:?}"))) + .change_context(KafkaError::GenericError) + .change_context(EventsError::PublishError) + } +}
feat
Add events framework for registering events (#4115)
8d9c7bc45ce2515759b9e2a36eb2d8a8a2c813ad
2024-05-27 05:45:16
github-actions
chore(version): 2024.05.27.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 01c606d38d4..0e59a94df3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,20 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.05.27.0 + +### Refactors + +- **core:** Inclusion of constraint graph for merchant Payment Method list ([#4626](https://github.com/juspay/hyperswitch/pull/4626)) ([`2cabb0b`](https://github.com/juspay/hyperswitch/commit/2cabb0bedcdf0d1adf568f2533b6ab9ce8d9fc57)) + +### Miscellaneous Tasks + +- Add missing migrations for recently added currencies ([#4760](https://github.com/juspay/hyperswitch/pull/4760)) ([`1026f47`](https://github.com/juspay/hyperswitch/commit/1026f4783000a13b43f22e4db0b36c217d39e541)) + +**Full Changelog:** [`2024.05.24.1...2024.05.27.0`](https://github.com/juspay/hyperswitch/compare/2024.05.24.1...2024.05.27.0) + +- - - + ## 2024.05.24.1 ### Features
chore
2024.05.27.0
0688972814cf03edbff4bf125a59c338a7e49593
2025-02-23 02:28:10
chikke srujan
feat(connector): Add support for passive churn recovery webhooks (#7109)
false
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 06796b4486b..16fcefac0ee 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -13397,6 +13397,19 @@ } } }, + "PaymentAttemptFeatureMetadata": { + "type": "object", + "properties": { + "revenue_recovery": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentAttemptRevenueRecoveryData" + } + ], + "nullable": true + } + } + }, "PaymentAttemptResponse": { "type": "object", "required": [ @@ -13405,7 +13418,8 @@ "amount", "authentication_type", "created_at", - "modified_at" + "modified_at", + "connector_payment_id" ], "properties": { "id": { @@ -13501,9 +13515,7 @@ }, "connector_payment_id": { "type": "string", - "description": "A unique identifier for a payment provided by the connector", - "example": "993672945374576J", - "nullable": true + "description": "A unique identifier for a payment provided by the connector" }, "payment_method_id": { "type": "string", @@ -13520,6 +13532,27 @@ "type": "string", "description": "Value passed in X-CLIENT-VERSION header during payments confirm request by the client", "nullable": true + }, + "feature_metadata": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentAttemptFeatureMetadata" + } + ], + "nullable": true + } + } + }, + "PaymentAttemptRevenueRecoveryData": { + "type": "object", + "properties": { + "attempt_triggered_by": { + "allOf": [ + { + "$ref": "#/components/schemas/TriggeredBy" + } + ], + "nullable": true } } }, @@ -21526,6 +21559,13 @@ "payout" ] }, + "TriggeredBy": { + "type": "string", + "enum": [ + "internal", + "external" + ] + }, "UIWidgetFormLayout": { "type": "string", "enum": [ diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 632d800f47e..8e62ba302ab 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -26144,6 +26144,13 @@ "payout" ] }, + "TriggeredBy": { + "type": "string", + "enum": [ + "internal", + "external" + ] + }, "UIWidgetFormLayout": { "type": "string", "enum": [ diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index c159af97249..2b84c50bba9 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -22,6 +22,7 @@ customer_v2 = ["common_utils/customer_v2"] payment_methods_v2 = ["common_utils/payment_methods_v2"] dynamic_routing = [] control_center_theme = ["dep:actix-web", "dep:actix-multipart"] +revenue_recovery = [] [dependencies] actix-multipart = { version = "0.6.1", optional = true } diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index faee2e38877..22e845c5e0c 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1511,8 +1511,8 @@ pub struct PaymentAttemptResponse { pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector - #[schema(value_type = Option<String>, example = "993672945374576J")] - pub connector_payment_id: Option<String>, + #[schema(value_type = String)] + pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] @@ -1522,6 +1522,24 @@ pub struct PaymentAttemptResponse { pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, + + /// Additional data that might be required by hyperswitch, to enable some specific features. + pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, +} + +#[cfg(feature = "v2")] +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] +pub struct PaymentAttemptFeatureMetadata { + /// Revenue recovery metadata that might be required by hyperswitch. + pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, +} + +#[cfg(feature = "v2")] +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] +pub struct PaymentAttemptRevenueRecoveryData { + /// Flag to find out whether an attempt was created by external or internal system. + #[schema(value_type = Option<TriggeredBy>, example = "internal")] + pub attempt_triggered_by: common_enums::TriggeredBy, } #[derive( @@ -5563,6 +5581,26 @@ pub struct PaymentsRetrieveResponse { pub attempts: Option<Vec<PaymentAttemptResponse>>, } +#[cfg(feature = "v2")] +impl PaymentsRetrieveResponse { + pub fn find_attempt_in_attempts_list_using_connector_transaction_id( + self, + connector_transaction_id: &common_utils::types::ConnectorTransactionId, + ) -> Option<PaymentAttemptResponse> { + self.attempts + .as_ref() + .and_then(|attempts| { + attempts.iter().find(|attempt| { + attempt + .connector_payment_id + .as_ref() + .is_some_and(|txn_id| txn_id == connector_transaction_id) + }) + }) + .cloned() + } +} + #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs index ddefea542c2..c3e96c47c64 100644 --- a/crates/api_models/src/webhooks.rs +++ b/crates/api_models/src/webhooks.rs @@ -57,6 +57,14 @@ pub enum IncomingWebhookEvent { PayoutExpired, #[cfg(feature = "payouts")] PayoutReversed, + #[cfg(all(feature = "revenue_recovery", feature = "v2"))] + RecoveryPaymentFailure, + #[cfg(all(feature = "revenue_recovery", feature = "v2"))] + RecoveryPaymentSuccess, + #[cfg(all(feature = "revenue_recovery", feature = "v2"))] + RecoveryPaymentPending, + #[cfg(all(feature = "revenue_recovery", feature = "v2"))] + RecoveryInvoiceCancel, } pub enum WebhookFlow { @@ -71,6 +79,8 @@ pub enum WebhookFlow { Mandate, ExternalAuthentication, FraudCheck, + #[cfg(all(feature = "revenue_recovery", feature = "v2"))] + Recovery, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] @@ -197,6 +207,11 @@ impl From<IncomingWebhookEvent> for WebhookFlow { | IncomingWebhookEvent::PayoutCreated | IncomingWebhookEvent::PayoutExpired | IncomingWebhookEvent::PayoutReversed => Self::Payout, + #[cfg(all(feature = "revenue_recovery", feature = "v2"))] + IncomingWebhookEvent::RecoveryInvoiceCancel + | IncomingWebhookEvent::RecoveryPaymentFailure + | IncomingWebhookEvent::RecoveryPaymentPending + | IncomingWebhookEvent::RecoveryPaymentSuccess => Self::Recovery, } } } @@ -236,6 +251,14 @@ pub enum ObjectReferenceId { ExternalAuthenticationID(AuthenticationIdType), #[cfg(feature = "payouts")] PayoutId(PayoutIdType), + #[cfg(all(feature = "revenue_recovery", feature = "v2"))] + InvoiceId(InvoiceIdType), +} + +#[cfg(all(feature = "revenue_recovery", feature = "v2"))] +#[derive(Clone)] +pub enum InvoiceIdType { + ConnectorInvoiceId(String), } pub struct IncomingWebhookDetails { @@ -303,3 +326,15 @@ pub struct ConnectorWebhookSecrets { pub secret: Vec<u8>, pub additional_secret: Option<masking::Secret<String>>, } + +#[cfg(all(feature = "v2", feature = "revenue_recovery"))] +impl IncomingWebhookEvent { + pub fn is_recovery_transaction_event(&self) -> bool { + matches!( + self, + Self::RecoveryPaymentFailure + | Self::RecoveryPaymentSuccess + | Self::RecoveryPaymentPending + ) + } +} diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index c286ae04d5f..660474e91ee 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -7591,3 +7591,28 @@ pub enum PaymentConnectorTransmission { /// Payment Connector call succeeded ConnectorCallSucceeded, } + +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum TriggeredBy { + /// Denotes payment attempt is been created by internal system. + #[default] + Internal, + /// Denotes payment attempt is been created by external system. + External, +} diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs index 945056aafef..6bdeae9b6d9 100644 --- a/crates/common_utils/src/ext_traits.rs +++ b/crates/common_utils/src/ext_traits.rs @@ -4,6 +4,8 @@ use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret, Strategy}; use quick_xml::de; +#[cfg(all(feature = "logs", feature = "async_ext"))] +use router_env::logger; use serde::{Deserialize, Serialize}; use crate::{ @@ -295,28 +297,34 @@ impl<T> StringExt<T> for String { /// Extending functionalities of Wrapper types for idiomatic #[cfg(feature = "async_ext")] #[cfg_attr(feature = "async_ext", async_trait::async_trait)] -pub trait AsyncExt<A, B> { +pub trait AsyncExt<A> { /// Output type of the map function type WrappedSelf<T>; /// Extending map by allowing functions which are async - async fn async_map<F, Fut>(self, func: F) -> Self::WrappedSelf<B> + async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = B> + Send; /// Extending the `and_then` by allowing functions which are async - async fn async_and_then<F, Fut>(self, func: F) -> Self::WrappedSelf<B> + async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send; + + /// Extending `unwrap_or_else` to allow async fallback + async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A + where + F: FnOnce() -> Fut + Send, + Fut: futures::Future<Output = A> + Send; } #[cfg(feature = "async_ext")] #[cfg_attr(feature = "async_ext", async_trait::async_trait)] -impl<A: Send, B, E: Send> AsyncExt<A, B> for Result<A, E> { +impl<A: Send, E: Send + std::fmt::Debug> AsyncExt<A> for Result<A, E> { type WrappedSelf<T> = Result<T, E>; - async fn async_and_then<F, Fut>(self, func: F) -> Self::WrappedSelf<B> + async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send, @@ -327,7 +335,7 @@ impl<A: Send, B, E: Send> AsyncExt<A, B> for Result<A, E> { } } - async fn async_map<F, Fut>(self, func: F) -> Self::WrappedSelf<B> + async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = B> + Send, @@ -337,13 +345,28 @@ impl<A: Send, B, E: Send> AsyncExt<A, B> for Result<A, E> { Err(err) => Err(err), } } + + async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A + where + F: FnOnce() -> Fut + Send, + Fut: futures::Future<Output = A> + Send, + { + match self { + Ok(a) => a, + Err(_err) => { + #[cfg(feature = "logs")] + logger::error!("Error: {:?}", _err); + func().await + } + } + } } #[cfg(feature = "async_ext")] #[cfg_attr(feature = "async_ext", async_trait::async_trait)] -impl<A: Send, B> AsyncExt<A, B> for Option<A> { +impl<A: Send> AsyncExt<A> for Option<A> { type WrappedSelf<T> = Option<T>; - async fn async_and_then<F, Fut>(self, func: F) -> Self::WrappedSelf<B> + async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send, @@ -354,7 +377,7 @@ impl<A: Send, B> AsyncExt<A, B> for Option<A> { } } - async fn async_map<F, Fut>(self, func: F) -> Self::WrappedSelf<B> + async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = B> + Send, @@ -364,6 +387,17 @@ impl<A: Send, B> AsyncExt<A, B> for Option<A> { None => None, } } + + async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A + where + F: FnOnce() -> Fut + Send, + Fut: futures::Future<Output = A> + Send, + { + match self { + Some(a) => a, + None => func().await, + } + } } /// Extension trait for validating application configuration. This trait provides utilities to diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 8cf6b604b92..9409be94163 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -101,6 +101,7 @@ pub struct PaymentAttempt { pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<storage_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, + pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v1")] @@ -316,6 +317,7 @@ pub struct PaymentAttemptNew { pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, pub capture_before: Option<PrimitiveDateTime>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, + pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v1")] @@ -835,6 +837,7 @@ pub struct PaymentAttemptUpdateInternal { // customer_acceptance: Option<pii::SecretSerdeValue>, // card_network: Option<String>, pub connector_token_details: Option<ConnectorTokenDetails>, + pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v1")] @@ -3525,6 +3528,27 @@ pub enum RedirectForm { common_utils::impl_to_sql_from_sql_json!(RedirectForm); +#[cfg(feature = "v2")] +#[derive( + Clone, Debug, serde::Deserialize, serde::Serialize, Eq, PartialEq, diesel::AsExpression, +)] +#[diesel(sql_type = diesel::pg::sql_types::Jsonb)] +pub struct PaymentAttemptFeatureMetadata { + pub revenue_recovery: Option<PaymentAttemptRecoveryData>, +} + +#[cfg(feature = "v2")] +#[derive( + Clone, Debug, serde::Deserialize, serde::Serialize, Eq, PartialEq, diesel::AsExpression, +)] +#[diesel(sql_type = diesel::pg::sql_types::Jsonb)] +pub struct PaymentAttemptRecoveryData { + pub attempt_triggered_by: common_enums::TriggeredBy, +} + +#[cfg(feature = "v2")] +common_utils::impl_to_sql_from_sql_json!(PaymentAttemptFeatureMetadata); + mod tests { #[test] diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index c4db38c0ee7..69ba37e8df6 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -883,6 +883,7 @@ diesel::table! { capture_before -> Nullable<Timestamp>, card_discovery -> Nullable<CardDiscovery>, charges -> Nullable<Jsonb>, + feature_metadata -> Nullable<Jsonb>, } } diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml index ced2151e52b..3de5358a2bd 100644 --- a/crates/hyperswitch_domain_models/Cargo.toml +++ b/crates/hyperswitch_domain_models/Cargo.toml @@ -17,6 +17,7 @@ v2 = ["api_models/v2", "diesel_models/v2", "common_utils/v2"] v1 = ["api_models/v1", "diesel_models/v1", "common_utils/v1"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2"] payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2"] +revenue_recovery= [] [dependencies] # First party deps diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index 3a1bd933b51..ef2cbe064d6 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -20,6 +20,8 @@ pub mod payments; pub mod payouts; pub mod refunds; pub mod relay; +#[cfg(all(feature = "v2", feature = "revenue_recovery"))] +pub mod revenue_recovery; pub mod router_data; pub mod router_data_v2; pub mod router_flow_types; diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index dfce21f28b6..f512711987b 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -20,6 +20,11 @@ use diesel_models::{ PaymentAttemptNew as DieselPaymentAttemptNew, PaymentAttemptUpdate as DieselPaymentAttemptUpdate, }; +#[cfg(feature = "v2")] +use diesel_models::{ + PaymentAttemptFeatureMetadata as DieselPaymentAttemptFeatureMetadata, + PaymentAttemptRecoveryData as DieselPassiveChurnRecoveryData, +}; use error_stack::ResultExt; #[cfg(feature = "v2")] use masking::PeekInterface; @@ -435,6 +440,8 @@ pub struct PaymentAttempt { pub card_discovery: Option<common_enums::CardDiscovery>, /// Split payment data pub charges: Option<common_types::payments::ConnectorChargeResponseData>, + /// Additional data that might be required by hyperswitch, to enable some specific features. + pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } impl PaymentAttempt { @@ -558,6 +565,7 @@ impl PaymentAttempt { consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH, )), }), + feature_metadata: None, id, card_discovery: None, }) @@ -1854,6 +1862,7 @@ impl behaviour::Conversion for PaymentAttempt { connector_token_details, card_discovery, charges, + feature_metadata, } = self; let AttemptAmountDetails { @@ -1870,6 +1879,7 @@ impl behaviour::Conversion for PaymentAttempt { .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); + let feature_metadata = feature_metadata.as_ref().map(From::from); Ok(DieselPaymentAttempt { payment_id, @@ -1935,6 +1945,7 @@ impl behaviour::Conversion for PaymentAttempt { extended_authorization_applied: None, capture_before: None, charges, + feature_metadata, }) } @@ -2047,6 +2058,7 @@ impl behaviour::Conversion for PaymentAttempt { payment_method_billing_address, connector_token_details: storage_model.connector_token_details, card_discovery: storage_model.card_discovery, + feature_metadata: storage_model.feature_metadata.map(From::from), }) } .await @@ -2102,6 +2114,7 @@ impl behaviour::Conversion for PaymentAttempt { connector_token_details, card_discovery, charges, + feature_metadata, } = self; let card_network = payment_method_data @@ -2177,6 +2190,7 @@ impl behaviour::Conversion for PaymentAttempt { extended_authorization_applied: None, request_extended_authorization: None, capture_before: None, + feature_metadata: feature_metadata.as_ref().map(From::from), }) } } @@ -2210,6 +2224,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal amount_to_capture: None, connector_token_details: None, authentication_type: Some(authentication_type), + feature_metadata: None, }, PaymentAttemptUpdate::ErrorUpdate { status, @@ -2236,6 +2251,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal amount_to_capture: None, connector_token_details: None, authentication_type: None, + feature_metadata: None, }, PaymentAttemptUpdate::ConfirmIntentResponse(confirm_intent_response_update) => { let ConfirmIntentResponseUpdate { @@ -2267,6 +2283,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal amount_to_capture: None, connector_token_details, authentication_type: None, + feature_metadata: None, } } PaymentAttemptUpdate::SyncUpdate { @@ -2292,6 +2309,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal amount_to_capture: None, connector_token_details: None, authentication_type: None, + feature_metadata: None, }, PaymentAttemptUpdate::CaptureUpdate { status, @@ -2316,6 +2334,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal connector_metadata: None, connector_token_details: None, authentication_type: None, + feature_metadata: None, }, PaymentAttemptUpdate::PreCaptureUpdate { amount_to_capture, @@ -2339,7 +2358,44 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal amount_capturable: None, connector_token_details: None, authentication_type: None, + feature_metadata: None, }, } } } +#[cfg(feature = "v2")] +#[derive(Debug, Clone, serde::Serialize, PartialEq)] +pub struct PaymentAttemptFeatureMetadata { + pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, +} + +#[cfg(feature = "v2")] +#[derive(Debug, Clone, serde::Serialize, PartialEq)] +pub struct PaymentAttemptRevenueRecoveryData { + pub attempt_triggered_by: common_enums::TriggeredBy, +} + +#[cfg(feature = "v2")] +impl From<&PaymentAttemptFeatureMetadata> for DieselPaymentAttemptFeatureMetadata { + fn from(item: &PaymentAttemptFeatureMetadata) -> Self { + let revenue_recovery = + item.revenue_recovery + .as_ref() + .map(|recovery_data| DieselPassiveChurnRecoveryData { + attempt_triggered_by: recovery_data.attempt_triggered_by, + }); + Self { revenue_recovery } + } +} + +#[cfg(feature = "v2")] +impl From<DieselPaymentAttemptFeatureMetadata> for PaymentAttemptFeatureMetadata { + fn from(item: DieselPaymentAttemptFeatureMetadata) -> Self { + let revenue_recovery = + item.revenue_recovery + .map(|recovery_data| PaymentAttemptRevenueRecoveryData { + attempt_triggered_by: recovery_data.attempt_triggered_by, + }); + Self { revenue_recovery } + } +} diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rs new file mode 100644 index 00000000000..8467189d27a --- /dev/null +++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs @@ -0,0 +1,190 @@ +use api_models::webhooks; +use time::PrimitiveDateTime; + +/// Recovery payload is unified struct constructed from billing connectors +#[derive(Debug)] +pub struct RevenueRecoveryAttemptData { + /// transaction amount against invoice, accepted in minor unit. + pub amount: common_utils::types::MinorUnit, + /// currency of the transaction + pub currency: common_enums::enums::Currency, + /// merchant reference id at billing connector. ex: invoice_id + pub merchant_reference_id: common_utils::id_type::PaymentReferenceId, + /// transaction id reference at payment connector + pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, + /// error code sent by billing connector. + pub error_code: Option<String>, + /// error message sent by billing connector. + pub error_message: Option<String>, + /// mandate token at payment processor end. + pub processor_payment_method_token: Option<String>, + /// customer id at payment connector for which mandate is attached. + pub connector_customer_id: Option<String>, + /// Payment gateway identifier id at billing processor. + pub connector_account_reference_id: Option<String>, + /// timestamp at which transaction has been created at billing connector + pub transaction_created_at: Option<PrimitiveDateTime>, + /// transaction status at billing connector equivalent to payment attempt status. + pub status: common_enums::enums::AttemptStatus, + /// payment method of payment attempt. + pub payment_method_type: common_enums::enums::PaymentMethod, + /// payment method sub type of the payment attempt. + pub payment_method_sub_type: common_enums::enums::PaymentMethodType, +} + +/// This is unified struct for Revenue Recovery Invoice Data and it is constructed from billing connectors +#[derive(Debug)] +pub struct RevenueRecoveryInvoiceData { + /// invoice amount at billing connector + pub amount: common_utils::types::MinorUnit, + /// currency of the amount. + pub currency: common_enums::enums::Currency, + /// merchant reference id at billing connector. ex: invoice_id + pub merchant_reference_id: common_utils::id_type::PaymentReferenceId, +} + +/// type of action that needs to taken after consuming recovery payload +#[derive(Debug)] +pub enum RecoveryAction { + /// Stops the process tracker and update the payment intent. + CancelInvoice, + /// Records the external transaction against payment intent. + ScheduleFailedPayment, + /// Records the external payment and stops the internal process tracker. + SuccessPaymentExternal, + /// Pending payments from billing processor. + PendingPayment, + /// No action required. + NoAction, + /// Invalid event has been received. + InvalidAction, +} + +pub struct RecoveryPaymentIntent { + pub payment_id: common_utils::id_type::GlobalPaymentId, + pub status: common_enums::enums::IntentStatus, + pub feature_metadata: Option<api_models::payments::FeatureMetadata>, +} + +pub struct RecoveryPaymentAttempt { + pub attempt_id: common_utils::id_type::GlobalAttemptId, + pub attempt_status: common_enums::AttemptStatus, + pub feature_metadata: Option<api_models::payments::PaymentAttemptFeatureMetadata>, +} + +impl RecoveryPaymentAttempt { + pub fn get_attempt_triggered_by(self) -> Option<common_enums::TriggeredBy> { + self.feature_metadata.and_then(|metadata| { + metadata + .revenue_recovery + .map(|recovery| recovery.attempt_triggered_by) + }) + } +} + +impl RecoveryAction { + pub fn get_action( + event_type: webhooks::IncomingWebhookEvent, + attempt_triggered_by: Option<common_enums::TriggeredBy>, + ) -> Self { + match event_type { + webhooks::IncomingWebhookEvent::PaymentIntentFailure + | webhooks::IncomingWebhookEvent::PaymentIntentSuccess + | webhooks::IncomingWebhookEvent::PaymentIntentProcessing + | webhooks::IncomingWebhookEvent::PaymentIntentPartiallyFunded + | webhooks::IncomingWebhookEvent::PaymentIntentCancelled + | webhooks::IncomingWebhookEvent::PaymentIntentCancelFailure + | webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationSuccess + | webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationFailure + | webhooks::IncomingWebhookEvent::PaymentIntentCaptureSuccess + | webhooks::IncomingWebhookEvent::PaymentIntentCaptureFailure + | webhooks::IncomingWebhookEvent::PaymentActionRequired + | webhooks::IncomingWebhookEvent::EventNotSupported + | webhooks::IncomingWebhookEvent::SourceChargeable + | webhooks::IncomingWebhookEvent::SourceTransactionCreated + | webhooks::IncomingWebhookEvent::RefundFailure + | webhooks::IncomingWebhookEvent::RefundSuccess + | webhooks::IncomingWebhookEvent::DisputeOpened + | webhooks::IncomingWebhookEvent::DisputeExpired + | webhooks::IncomingWebhookEvent::DisputeAccepted + | webhooks::IncomingWebhookEvent::DisputeCancelled + | webhooks::IncomingWebhookEvent::DisputeChallenged + | webhooks::IncomingWebhookEvent::DisputeWon + | webhooks::IncomingWebhookEvent::DisputeLost + | webhooks::IncomingWebhookEvent::MandateActive + | webhooks::IncomingWebhookEvent::MandateRevoked + | webhooks::IncomingWebhookEvent::EndpointVerification + | webhooks::IncomingWebhookEvent::ExternalAuthenticationARes + | webhooks::IncomingWebhookEvent::FrmApproved + | webhooks::IncomingWebhookEvent::FrmRejected + | webhooks::IncomingWebhookEvent::PayoutSuccess + | webhooks::IncomingWebhookEvent::PayoutFailure + | webhooks::IncomingWebhookEvent::PayoutProcessing + | webhooks::IncomingWebhookEvent::PayoutCancelled + | webhooks::IncomingWebhookEvent::PayoutCreated + | webhooks::IncomingWebhookEvent::PayoutExpired + | webhooks::IncomingWebhookEvent::PayoutReversed => Self::InvalidAction, + webhooks::IncomingWebhookEvent::RecoveryPaymentFailure => match attempt_triggered_by { + Some(common_enums::TriggeredBy::Internal) => Self::NoAction, + Some(common_enums::TriggeredBy::External) | None => Self::ScheduleFailedPayment, + }, + webhooks::IncomingWebhookEvent::RecoveryPaymentSuccess => match attempt_triggered_by { + Some(common_enums::TriggeredBy::Internal) => Self::NoAction, + Some(common_enums::TriggeredBy::External) | None => Self::SuccessPaymentExternal, + }, + webhooks::IncomingWebhookEvent::RecoveryPaymentPending => Self::PendingPayment, + webhooks::IncomingWebhookEvent::RecoveryInvoiceCancel => Self::CancelInvoice, + } + } +} + +impl From<&RevenueRecoveryInvoiceData> for api_models::payments::AmountDetails { + fn from(data: &RevenueRecoveryInvoiceData) -> Self { + let amount = api_models::payments::AmountDetailsSetter { + order_amount: data.amount.into(), + currency: data.currency, + shipping_cost: None, + order_tax_amount: None, + skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, + skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, + surcharge_amount: None, + tax_on_surcharge: None, + }; + Self::new(amount) + } +} + +impl From<&RevenueRecoveryInvoiceData> for api_models::payments::PaymentsCreateIntentRequest { + fn from(data: &RevenueRecoveryInvoiceData) -> Self { + let amount_details = api_models::payments::AmountDetails::from(data); + Self { + amount_details, + merchant_reference_id: Some(data.merchant_reference_id.clone()), + routing_algorithm_id: None, + // Payments in the revenue recovery flow are always recurring transactions, + // so capture method will be always automatic. + capture_method: Some(common_enums::CaptureMethod::Automatic), + authentication_type: Some(common_enums::AuthenticationType::NoThreeDs), + billing: None, + shipping: None, + customer_id: None, + customer_present: Some(common_enums::PresenceOfCustomerDuringPayment::Absent), + 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_enabled: None, + payment_link_config: None, + request_incremental_authorization: None, + session_expiry: None, + frm_metadata: None, + request_external_three_ds_authentication: None, + } + } +} diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.toml index 99a06ff2e3a..f0402c45f74 100644 --- a/crates/hyperswitch_interfaces/Cargo.toml +++ b/crates/hyperswitch_interfaces/Cargo.toml @@ -10,8 +10,10 @@ license.workspace = true default = ["dummy_connector", "frm", "payouts"] dummy_connector = [] v1 = ["hyperswitch_domain_models/v1", "api_models/v1", "common_utils/v1"] +v2 = [] payouts = ["hyperswitch_domain_models/payouts"] frm = ["hyperswitch_domain_models/frm"] +revenue_recovery= [] [dependencies] actix-web = "4.5.1" diff --git a/crates/hyperswitch_interfaces/src/webhooks.rs b/crates/hyperswitch_interfaces/src/webhooks.rs index cc3bd487645..6a243cf09f7 100644 --- a/crates/hyperswitch_interfaces/src/webhooks.rs +++ b/crates/hyperswitch_interfaces/src/webhooks.rs @@ -275,4 +275,33 @@ pub trait IncomingWebhook: ConnectorCommon + Sync { > { Ok(None) } + + #[cfg(all(feature = "revenue_recovery", feature = "v2"))] + /// get revenue recovery invoice details + fn get_revenue_recovery_attempt_details( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult< + hyperswitch_domain_models::revenue_recovery::RevenueRecoveryAttemptData, + errors::ConnectorError, + > { + Err(errors::ConnectorError::NotImplemented( + "get_revenue_recovery_attempt_details method".to_string(), + ) + .into()) + } + #[cfg(all(feature = "revenue_recovery", feature = "v2"))] + /// get revenue recovery transaction details + fn get_revenue_recovery_invoice_details( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult< + hyperswitch_domain_models::revenue_recovery::RevenueRecoveryInvoiceData, + errors::ConnectorError, + > { + Err(errors::ConnectorError::NotImplemented( + "get_revenue_recovery_invoice_details method".to_string(), + ) + .into()) + } } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index b75d1d22854..1b6f73fb1cd 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -281,6 +281,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::PaymentType, api_models::enums::ScaExemptionType, api_models::enums::PaymentMethod, + api_models::enums::TriggeredBy, api_models::enums::PaymentMethodType, api_models::enums::ConnectorType, api_models::enums::PayoutConnectors, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 752bd9707ff..a4eb67b64f4 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -316,6 +316,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::AddressDetails, api_models::payments::BankDebitData, api_models::payments::AliPayQr, + api_models::payments::PaymentAttemptFeatureMetadata, + api_models::payments::PaymentAttemptRevenueRecoveryData, api_models::payments::AliPayRedirection, api_models::payments::MomoRedirection, api_models::payments::TouchNGoRedirection, @@ -477,6 +479,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentRevenueRecoveryMetadata, api_models::payments::BillingConnectorPaymentDetails, api_models::enums::PaymentConnectorTransmission, + api_models::enums::TriggeredBy, api_models::payments::PaymentAttemptResponse, api_models::payments::PaymentAttemptAmountDetails, api_models::payments::CaptureResponse, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index d590797d642..8197670acf3 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -33,11 +33,12 @@ payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors payout_retry = ["payouts"] recon = ["email", "api_models/recon"] retry = [] -v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2"] +v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2","hyperswitch_interfaces/v2"] 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", "hyperswitch_connectors/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", "api_models/dynamic_routing"] +revenue_recovery =["api_models/revenue_recovery","hyperswitch_interfaces/revenue_recovery","hyperswitch_domain_models/revenue_recovery"] # 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/errors.rs b/crates/router/src/core/errors.rs index 3dbaa999219..d06ffea581f 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -445,3 +445,20 @@ pub enum NetworkTokenizationError { #[error("Failed while calling Network Token Service API")] ApiError, } + +#[cfg(all(feature = "revenue_recovery", feature = "v2"))] +#[derive(Debug, thiserror::Error)] +pub enum RevenueRecoveryError { + #[error("Failed to fetch payment intent")] + PaymentIntentFetchFailed, + #[error("Failed to fetch payment attempt")] + PaymentAttemptFetchFailed, + #[error("Failed to get revenue recovery invoice webhook")] + InvoiceWebhookProcessingFailed, + #[error("Failed to get revenue recovery invoice transaction")] + TransactionWebhookProcessingFailed, + #[error("Failed to create payment intent")] + PaymentIntentCreateFailed, + #[error("Source verification failed for billing connector")] + WebhookAuthenticationFailed, +} diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 74ac9dc0f37..1898dd40666 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1803,7 +1803,7 @@ pub(crate) async fn payments_create_and_confirm_intent( #[cfg(feature = "v2")] #[inline] -fn handle_payments_intent_response<T>( +pub fn handle_payments_intent_response<T>( response: hyperswitch_domain_models::api::ApplicationResponse<T>, ) -> CustomResult<T, errors::ApiErrorResponse> { match response { diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 5c77452b677..661bd73b506 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1616,7 +1616,7 @@ where let error = payment_attempt .error - .clone() + .as_ref() .map(api_models::payments::ErrorDetails::foreign_from); let payment_address = self.payment_address; @@ -1704,6 +1704,7 @@ where let error = optional_payment_attempt .and_then(|payment_attempt| payment_attempt.error.clone()) + .as_ref() .map(api_models::payments::ErrorDetails::foreign_from); let attempts = self.attempts.as_ref().map(|attempts| { attempts @@ -2811,7 +2812,7 @@ impl ForeignFrom<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> error: pa .as_ref() .and_then(|p| p.error.as_ref()) - .map(|e| api_models::payments::ErrorDetails::foreign_from(e.clone())), + .map(api_models::payments::ErrorDetails::foreign_from), cancellation_reason: pa.as_ref().and_then(|p| p.cancellation_reason.clone()), order_details: None, return_url: pi.return_url, @@ -4245,7 +4246,7 @@ impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::PaymentA connector: attempt.connector.clone(), error: attempt .error - .clone() + .as_ref() .map(api_models::payments::ErrorDetails::foreign_from), authentication_type: attempt.authentication_type, created_at: attempt.created_at, @@ -4257,10 +4258,16 @@ impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::PaymentA payment_method_type: attempt.payment_method_type, connector_reference_id: attempt.connector_response_reference_id.clone(), payment_method_subtype: attempt.get_payment_method_type(), - connector_payment_id: attempt.get_connector_payment_id().map(ToString::to_string), + connector_payment_id: attempt + .get_connector_payment_id() + .map(|str| common_utils::types::ConnectorTransactionId::from(str.to_owned())), payment_method_id: attempt.payment_method_id.clone(), client_source: attempt.client_source.clone(), client_version: attempt.client_version.clone(), + feature_metadata: attempt + .feature_metadata + .as_ref() + .map(api_models::payments::PaymentAttemptFeatureMetadata::foreign_from), } } } @@ -4285,29 +4292,39 @@ impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::AttemptA } #[cfg(feature = "v2")] -impl ForeignFrom<hyperswitch_domain_models::payments::payment_attempt::ErrorDetails> +impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::ErrorDetails> for api_models::payments::ErrorDetails { fn foreign_from( - amount_details: hyperswitch_domain_models::payments::payment_attempt::ErrorDetails, + error_details: &hyperswitch_domain_models::payments::payment_attempt::ErrorDetails, ) -> Self { - let hyperswitch_domain_models::payments::payment_attempt::ErrorDetails { - code, - message, - reason, - unified_code, - unified_message, - } = amount_details; - Self { - code, - message: reason.unwrap_or(message), - unified_code, - unified_message, + code: error_details.code.to_owned(), + message: error_details.message.to_owned(), + unified_code: error_details.unified_code.clone(), + unified_message: error_details.unified_message.clone(), } } } +#[cfg(feature = "v2")] +impl + ForeignFrom< + &hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptFeatureMetadata, + > for api_models::payments::PaymentAttemptFeatureMetadata +{ + fn foreign_from( + feature_metadata: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptFeatureMetadata, + ) -> Self { + let revenue_recovery = feature_metadata.revenue_recovery.as_ref().map(|recovery| { + api_models::payments::PaymentAttemptRevenueRecoveryData { + attempt_triggered_by: recovery.attempt_triggered_by, + } + }); + Self { revenue_recovery } + } +} + #[cfg(feature = "v2")] impl ForeignFrom<hyperswitch_domain_models::payments::AmountDetails> for api_models::payments::AmountDetailsResponse diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 64c5617398b..4a9c4106b9f 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -4,6 +4,8 @@ mod incoming; mod incoming_v2; #[cfg(feature = "v1")] mod outgoing; +#[cfg(all(feature = "revenue_recovery", feature = "v2"))] +mod recovery_incoming; pub mod types; pub mod utils; #[cfg(feature = "olap")] diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rs index 900a455f993..c564b405836 100644 --- a/crates/router/src/core/webhooks/incoming_v2.rs +++ b/crates/router/src/core/webhooks/incoming_v2.rs @@ -15,6 +15,8 @@ use hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails; use router_env::{instrument, tracing, tracing_actix_web::RequestId}; use super::{types, utils, MERCHANT_ID}; +#[cfg(feature = "revenue_recovery")] +use crate::core::webhooks::recovery_incoming; use crate::{ core::{ api_locking, @@ -349,6 +351,24 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( api::WebhookFlow::Payout => todo!(), api::WebhookFlow::Subscription => todo!(), + #[cfg(all(feature = "revenue_recovery", feature = "v2"))] + api::WebhookFlow::Recovery => { + Box::pin(recovery_incoming::recovery_incoming_webhook_flow( + state.clone(), + merchant_account, + profile, + key_store, + webhook_details, + source_verified, + &connector, + &request_details, + event_type, + req_state, + )) + .await + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("Failed to process recovery incoming webhook")? + } } } } diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs new file mode 100644 index 00000000000..3634acfab97 --- /dev/null +++ b/crates/router/src/core/webhooks/recovery_incoming.rs @@ -0,0 +1,307 @@ +use api_models::webhooks; +use common_utils::ext_traits::AsyncExt; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::revenue_recovery; +use hyperswitch_interfaces::webhooks as interface_webhooks; +use router_env::{instrument, tracing}; + +use crate::{ + core::{ + errors::{self, CustomResult}, + payments::{self, operations}, + }, + routes::{app::ReqState, SessionState}, + services::{self, connector_integration_interface}, + types::{api, domain}, +}; + +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +#[cfg(feature = "revenue_recovery")] +pub async fn recovery_incoming_webhook_flow( + state: SessionState, + merchant_account: domain::MerchantAccount, + business_profile: domain::Profile, + key_store: domain::MerchantKeyStore, + _webhook_details: api::IncomingWebhookDetails, + source_verified: bool, + connector: &connector_integration_interface::ConnectorEnum, + request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, + event_type: webhooks::IncomingWebhookEvent, + req_state: ReqState, +) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { + // Source verification is necessary for revenue recovery webhooks flow since We don't have payment intent/attempt object created before in our system. + + common_utils::fp_utils::when(!source_verified, || { + Err(report!( + errors::RevenueRecoveryError::WebhookAuthenticationFailed + )) + })?; + + let invoice_details = RevenueRecoveryInvoice( + interface_webhooks::IncomingWebhook::get_revenue_recovery_invoice_details( + connector, + request_details, + ) + .change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed) + .attach_printable("Failed while getting revenue recovery invoice details")?, + ); + // Fetch the intent using merchant reference id, if not found create new intent. + let payment_intent = invoice_details + .get_payment_intent( + &state, + &req_state, + &merchant_account, + &business_profile, + &key_store, + ) + .await + .transpose() + .async_unwrap_or_else(|| async { + invoice_details + .create_payment_intent( + &state, + &req_state, + &merchant_account, + &business_profile, + &key_store, + ) + .await + }) + .await?; + + let payment_attempt = match event_type.is_recovery_transaction_event() { + true => { + let invoice_transaction_details = RevenueRecoveryAttempt( + interface_webhooks::IncomingWebhook::get_revenue_recovery_attempt_details( + connector, + request_details, + ) + .change_context(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed)?, + ); + + invoice_transaction_details + .get_payment_attempt( + &state, + &req_state, + &merchant_account, + &business_profile, + &key_store, + payment_intent.payment_id.clone(), + ) + .await? + } + false => None, + }; + + let attempt_triggered_by = payment_attempt + .and_then(revenue_recovery::RecoveryPaymentAttempt::get_attempt_triggered_by); + + let action = revenue_recovery::RecoveryAction::get_action(event_type, attempt_triggered_by); + + match action { + revenue_recovery::RecoveryAction::CancelInvoice => todo!(), + revenue_recovery::RecoveryAction::ScheduleFailedPayment => { + todo!() + } + revenue_recovery::RecoveryAction::SuccessPaymentExternal => { + todo!() + } + revenue_recovery::RecoveryAction::PendingPayment => { + router_env::logger::info!( + "Pending transactions are not consumed by the revenue recovery webhooks" + ); + Ok(webhooks::WebhookResponseTracker::NoEffect) + } + revenue_recovery::RecoveryAction::NoAction => { + router_env::logger::info!( + "No Recovery action is taken place for recovery event : {:?} and attempt triggered_by : {:?} ", event_type.clone(), attempt_triggered_by + ); + Ok(webhooks::WebhookResponseTracker::NoEffect) + } + revenue_recovery::RecoveryAction::InvalidAction => { + router_env::logger::error!( + "Invalid Revenue recovery action state has been received, event : {:?}, triggered_by : {:?}", event_type, attempt_triggered_by + ); + Ok(webhooks::WebhookResponseTracker::NoEffect) + } + } +} + +pub struct RevenueRecoveryInvoice(revenue_recovery::RevenueRecoveryInvoiceData); +pub struct RevenueRecoveryAttempt(revenue_recovery::RevenueRecoveryAttemptData); + +impl RevenueRecoveryInvoice { + async fn get_payment_intent( + &self, + state: &SessionState, + req_state: &ReqState, + merchant_account: &domain::MerchantAccount, + profile: &domain::Profile, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<Option<revenue_recovery::RecoveryPaymentIntent>, errors::RevenueRecoveryError> + { + let payment_response = Box::pin(payments::payments_get_intent_using_merchant_reference( + state.clone(), + merchant_account.clone(), + profile.clone(), + key_store.clone(), + req_state.clone(), + &self.0.merchant_reference_id, + hyperswitch_domain_models::payments::HeaderPayload::default(), + None, + )) + .await; + let response = match payment_response { + Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => { + let payment_id = payments_response.id.clone(); + let status = payments_response.status; + let feature_metadata = payments_response.feature_metadata; + Ok(Some(revenue_recovery::RecoveryPaymentIntent { + payment_id, + status, + feature_metadata, + })) + } + Err(err) + if matches!( + err.current_context(), + &errors::ApiErrorResponse::PaymentNotFound + ) => + { + Ok(None) + } + Ok(_) => Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed) + .attach_printable("Unexpected response from payment intent core"), + error @ Err(_) => { + router_env::logger::error!(?error); + Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed) + .attach_printable("failed to fetch payment intent recovery webhook flow") + } + }?; + Ok(response) + } + async fn create_payment_intent( + &self, + state: &SessionState, + req_state: &ReqState, + merchant_account: &domain::MerchantAccount, + profile: &domain::Profile, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<revenue_recovery::RecoveryPaymentIntent, errors::RevenueRecoveryError> { + let payload = api_models::payments::PaymentsCreateIntentRequest::from(&self.0); + let global_payment_id = + common_utils::id_type::GlobalPaymentId::generate(&state.conf.cell_information.id); + + let create_intent_response = Box::pin(payments::payments_intent_core::< + hyperswitch_domain_models::router_flow_types::payments::PaymentCreateIntent, + api_models::payments::PaymentsIntentResponse, + _, + _, + hyperswitch_domain_models::payments::PaymentIntentData< + hyperswitch_domain_models::router_flow_types::payments::PaymentCreateIntent, + >, + >( + state.clone(), + req_state.clone(), + merchant_account.clone(), + profile.clone(), + key_store.clone(), + payments::operations::PaymentIntentCreate, + payload, + global_payment_id, + hyperswitch_domain_models::payments::HeaderPayload::default(), + None, + )) + .await + .change_context(errors::RevenueRecoveryError::PaymentIntentCreateFailed)?; + let response = payments::handle_payments_intent_response(create_intent_response) + .change_context(errors::RevenueRecoveryError::PaymentIntentCreateFailed)?; + + Ok(revenue_recovery::RecoveryPaymentIntent { + payment_id: response.id, + status: response.status, + feature_metadata: response.feature_metadata, + }) + } +} + +impl RevenueRecoveryAttempt { + async fn get_payment_attempt( + &self, + state: &SessionState, + req_state: &ReqState, + merchant_account: &domain::MerchantAccount, + profile: &domain::Profile, + key_store: &domain::MerchantKeyStore, + payment_id: common_utils::id_type::GlobalPaymentId, + ) -> CustomResult<Option<revenue_recovery::RecoveryPaymentAttempt>, errors::RevenueRecoveryError> + { + let attempt_response = Box::pin(payments::payments_core::< + hyperswitch_domain_models::router_flow_types::payments::PSync, + api_models::payments::PaymentsRetrieveResponse, + _, + _, + _, + hyperswitch_domain_models::payments::PaymentStatusData< + hyperswitch_domain_models::router_flow_types::payments::PSync, + >, + >( + state.clone(), + req_state.clone(), + merchant_account.clone(), + profile.clone(), + key_store.clone(), + payments::operations::PaymentGet, + api_models::payments::PaymentsRetrieveRequest { + force_sync: false, + expand_attempts: true, + param: None, + }, + payment_id.clone(), + payments::CallConnectorAction::Avoid, + hyperswitch_domain_models::payments::HeaderPayload::default(), + )) + .await; + let response = match attempt_response { + Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => { + let final_attempt = + self.0 + .connector_transaction_id + .as_ref() + .and_then(|transaction_id| { + payments_response + .find_attempt_in_attempts_list_using_connector_transaction_id( + transaction_id, + ) + }); + let payment_attempt = + final_attempt.map(|attempt_res| revenue_recovery::RecoveryPaymentAttempt { + attempt_id: attempt_res.id.to_owned(), + attempt_status: attempt_res.status.to_owned(), + feature_metadata: attempt_res.feature_metadata.to_owned(), + }); + Ok(payment_attempt) + } + Ok(_) => Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed) + .attach_printable("Unexpected response from payment intent core"), + error @ Err(_) => { + router_env::logger::error!(?error); + Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed) + .attach_printable("failed to fetch payment intent recovery webhook flow") + } + }?; + Ok(response) + } + async fn record_payment_attempt( + &self, + _state: &SessionState, + _req_state: &ReqState, + _merchant_account: &domain::MerchantAccount, + _profile: &domain::Profile, + _key_store: &domain::MerchantKeyStore, + _payment_id: common_utils::id_type::GlobalPaymentId, + ) -> CustomResult<revenue_recovery::RecoveryPaymentAttempt, errors::RevenueRecoveryError> { + todo!() + } +} diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index b589d4755f8..0b506611665 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -60,6 +60,9 @@ pub mod verify_connector; pub mod webhook_events; pub mod webhooks; +#[cfg(all(feature = "v2", feature = "revenue_recovery"))] +pub mod recovery_webhooks; + pub mod relay; #[cfg(feature = "dummy_connector")] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index b8acc66d522..760afc26b0d 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -46,6 +46,8 @@ use super::payouts::*; use super::pm_auth; #[cfg(feature = "oltp")] use super::poll; +#[cfg(all(feature = "v2", feature = "revenue_recovery", feature = "oltp"))] +use super::recovery_webhooks::*; #[cfg(feature = "olap")] use super::routing; #[cfg(all(feature = "olap", feature = "v1"))] @@ -1642,6 +1644,16 @@ impl Webhooks { ), ); + #[cfg(all(feature = "revenue_recovery", feature = "v2"))] + { + route = route.service( + web::resource("/recovery/{merchant_id}/{profile_id}/{connector_id}").route( + web::post() + .to(recovery_receive_incoming_webhook::<webhook_type::OutgoingWebhook>), + ), + ); + } + route } } diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index a50a27b9ec4..f48a7970fde 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -178,7 +178,8 @@ impl From<Flow> for ApiIdentifier { | Flow::IncomingRelayWebhookReceive | Flow::WebhookEventInitialDeliveryAttemptList | Flow::WebhookEventDeliveryAttemptList - | Flow::WebhookEventDeliveryRetry => Self::Webhooks, + | Flow::WebhookEventDeliveryRetry + | Flow::RecoveryIncomingWebhookReceive => Self::Webhooks, Flow::ApiKeyCreate | Flow::ApiKeyRetrieve diff --git a/crates/router/src/routes/recovery_webhooks.rs b/crates/router/src/routes/recovery_webhooks.rs new file mode 100644 index 00000000000..0c83ba1b395 --- /dev/null +++ b/crates/router/src/routes/recovery_webhooks.rs @@ -0,0 +1,53 @@ +use actix_web::{web, HttpRequest, Responder}; +use router_env::{instrument, tracing, Flow}; + +use super::app::AppState; +use crate::{ + core::{ + api_locking, + webhooks::{self, types}, + }, + services::{api, authentication as auth}, +}; + +#[instrument(skip_all, fields(flow = ?Flow::IncomingWebhookReceive))] +pub async fn recovery_receive_incoming_webhook<W: types::OutgoingWebhookType>( + state: web::Data<AppState>, + req: HttpRequest, + body: web::Bytes, + path: web::Path<( + common_utils::id_type::MerchantId, + common_utils::id_type::ProfileId, + common_utils::id_type::MerchantConnectorAccountId, + )>, +) -> impl Responder { + let flow = Flow::RecoveryIncomingWebhookReceive; + let (merchant_id, profile_id, connector_id) = path.into_inner(); + + Box::pin(api::server_wrap( + flow.clone(), + state, + &req, + (), + |state, auth, _, req_state| { + webhooks::incoming_webhooks_wrapper::<W>( + &flow, + state.to_owned(), + req_state, + &req, + auth.merchant_account, + auth.profile, + auth.key_store, + &connector_id, + body.clone(), + false, + ) + }, + &auth::MerchantIdAndProfileIdAuth { + merchant_id, + profile_id, + }, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/services/connector_integration_interface.rs b/crates/router/src/services/connector_integration_interface.rs index 5903c8e9cc0..d9b04f57344 100644 --- a/crates/router/src/services/connector_integration_interface.rs +++ b/crates/router/src/services/connector_integration_interface.rs @@ -338,6 +338,34 @@ impl api::IncomingWebhook for ConnectorEnum { Self::New(connector) => connector.get_network_txn_id(request), } } + + #[cfg(all(feature = "revenue_recovery", feature = "v2"))] + fn get_revenue_recovery_attempt_details( + &self, + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult< + hyperswitch_domain_models::revenue_recovery::RevenueRecoveryAttemptData, + errors::ConnectorError, + > { + match self { + Self::Old(connector) => connector.get_revenue_recovery_attempt_details(request), + Self::New(connector) => connector.get_revenue_recovery_attempt_details(request), + } + } + + #[cfg(all(feature = "revenue_recovery", feature = "v2"))] + fn get_revenue_recovery_invoice_details( + &self, + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult< + hyperswitch_domain_models::revenue_recovery::RevenueRecoveryInvoiceData, + errors::ConnectorError, + > { + match self { + Self::Old(connector) => connector.get_revenue_recovery_invoice_details(request), + Self::New(connector) => connector.get_revenue_recovery_invoice_details(request), + } + } } impl api::ConnectorTransactionId for ConnectorEnum { diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 3eda63bdbaa..6021ee70d9f 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -267,6 +267,8 @@ pub enum Flow { ToggleBlocklistGuard, /// Incoming Webhook Receive IncomingWebhookReceive, + /// Recovery incoming webhook receive + RecoveryIncomingWebhookReceive, /// Validate payment method flow ValidatePaymentMethod, /// API Key create flow diff --git a/v2_migrations/2025-01-17-042122_add_feature_metadata_in_payment_attempt/down.sql b/v2_migrations/2025-01-17-042122_add_feature_metadata_in_payment_attempt/down.sql new file mode 100644 index 00000000000..ec6a51ca794 --- /dev/null +++ b/v2_migrations/2025-01-17-042122_add_feature_metadata_in_payment_attempt/down.sql @@ -0,0 +1,2 @@ +ALTER TABLE payment_attempt +DROP COLUMN IF EXISTS feature_metadata; \ No newline at end of file diff --git a/v2_migrations/2025-01-17-042122_add_feature_metadata_in_payment_attempt/up.sql b/v2_migrations/2025-01-17-042122_add_feature_metadata_in_payment_attempt/up.sql new file mode 100644 index 00000000000..bf06a98f7a3 --- /dev/null +++ b/v2_migrations/2025-01-17-042122_add_feature_metadata_in_payment_attempt/up.sql @@ -0,0 +1,2 @@ +ALTER TABLE payment_attempt +ADD COLUMN feature_metadata JSONB; \ No newline at end of file
feat
Add support for passive churn recovery webhooks (#7109)
7f582e4737c1c7dfe906e7d01de239e131511f84
2024-07-18 18:51:42
Sanchith Hegde
build: remove unused dependencies (#5343)
false
diff --git a/Cargo.lock b/Cargo.lock index 0188b3d6f1c..193f19453b9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -344,7 +344,6 @@ dependencies = [ "common_utils", "diesel_models", "error-stack", - "external_services", "futures 0.3.30", "hyperswitch_domain_models", "hyperswitch_interfaces", @@ -449,8 +448,6 @@ dependencies = [ "common_utils", "error-stack", "euclid", - "frunk", - "frunk_core", "masking", "mime", "reqwest", @@ -1996,8 +1993,6 @@ name = "common_enums" version = "0.1.0" dependencies = [ "diesel", - "frunk", - "frunk_core", "router_derive", "serde", "serde_json", @@ -2032,11 +2027,9 @@ dependencies = [ "regex", "reqwest", "ring 0.17.8", - "router_derive", "router_env", "rust_decimal", "rustc-hash", - "rusty-money", "semver 1.0.22", "serde", "serde_json", @@ -2708,8 +2701,6 @@ dependencies = [ "common_utils", "diesel", "error-stack", - "frunk", - "frunk_core", "masking", "router_derive", "router_env", @@ -2966,10 +2957,7 @@ dependencies = [ "common_enums", "common_utils", "criterion", - "erased-serde 0.4.4", "euclid_macros", - "frunk", - "frunk_core", "hyperswitch_constraint_graph", "nom", "once_cell", @@ -3225,58 +3213,6 @@ dependencies = [ "urlencoding", ] -[[package]] -name = "frunk" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11a351b59e12f97b4176ee78497dff72e4276fb1ceb13e19056aca7fa0206287" -dependencies = [ - "frunk_core", - "frunk_derives", - "frunk_proc_macros", -] - -[[package]] -name = "frunk_core" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af2469fab0bd07e64ccf0ad57a1438f63160c69b2e57f04a439653d68eb558d6" - -[[package]] -name = "frunk_derives" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" -dependencies = [ - "frunk_proc_macro_helpers", - "quote", - "syn 2.0.57", -] - -[[package]] -name = "frunk_proc_macro_helpers" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35b54add839292b743aeda6ebedbd8b11e93404f902c56223e51b9ec18a13d2c" -dependencies = [ - "frunk_core", - "proc-macro2", - "quote", - "syn 2.0.57", -] - -[[package]] -name = "frunk_proc_macros" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71b85a1d4a9a6b300b41c05e8e13ef2feca03e0334127f29eca9506a7fe13a93" -dependencies = [ - "frunk_core", - "frunk_proc_macro_helpers", - "quote", - "syn 2.0.57", -] - [[package]] name = "fuchsia-zircon" version = "0.3.3" @@ -3900,7 +3836,6 @@ dependencies = [ "graphviz-rust", "rustc-hash", "serde", - "serde_json", "strum 0.25.0", "thiserror", ] @@ -3954,7 +3889,6 @@ dependencies = [ "router_env", "serde", "serde_json", - "storage_impl", "thiserror", "time", ] @@ -5483,8 +5417,6 @@ dependencies = [ "http 0.2.12", "masking", "mime", - "router_derive", - "router_env", "serde", "serde_json", "strum 0.26.2", @@ -6123,7 +6055,6 @@ dependencies = [ "digest", "dyn-clone", "encoding_rs", - "erased-serde 0.4.4", "error-stack", "euclid", "events", @@ -6179,7 +6110,6 @@ dependencies = [ "serde_with", "serial_test", "sha1", - "sqlx", "storage_impl", "strum 0.26.2", "tera", @@ -6221,7 +6151,6 @@ name = "router_env" version = "0.1.0" dependencies = [ "cargo_metadata 0.18.1", - "common_enums", "config", "error-stack", "gethostname", @@ -6548,7 +6477,6 @@ dependencies = [ "external_services", "futures 0.3.30", "hyperswitch_domain_models", - "masking", "num_cpus", "once_cell", "rand", @@ -7235,7 +7163,6 @@ dependencies = [ name = "storage_impl" version = "0.1.0" dependencies = [ - "actix-web", "api_models", "async-bb8-diesel", "async-trait", @@ -7250,10 +7177,8 @@ dependencies = [ "dyn-clone", "error-stack", "futures 0.3.30", - "http 0.2.12", "hyperswitch_domain_models", "masking", - "mime", "moka", "once_cell", "redis_interface", diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml index 8cf4b9b911c..9ef0e624fc2 100644 --- a/crates/analytics/Cargo.toml +++ b/crates/analytics/Cargo.toml @@ -6,28 +6,17 @@ edition.workspace = true rust-version.workspace = true license.workspace = true -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - - [dependencies] # First party crates -api_models = { version = "0.1.0", path = "../api_models", features = [ - "errors", -] } -storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false } +api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] } common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils" } -external_services = { version = "0.1.0", path = "../external_services", default-features = false } +diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } +hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } 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", -] } -diesel_models = { version = "0.1.0", path = "../diesel_models", features = [ - "kv_store", -] } -hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } +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 } #Third Party dependencies actix-web = "4.5.1" @@ -38,18 +27,12 @@ aws-smithy-types = { version = "1.1.8" } bigdecimal = { version = "0.3.1", features = ["serde"] } error-stack = "0.4.1" futures = "0.3.30" -opensearch = { version = "2.2.0", features = ["aws-auth"] } once_cell = "1.19.0" +opensearch = { version = "2.2.0", features = ["aws-auth"] } reqwest = { version = "0.11.27", features = ["serde_json"] } serde = { version = "1.0.197", features = ["derive", "rc"] } serde_json = "1.0.115" -sqlx = { version = "0.7.3", features = [ - "postgres", - "runtime-tokio", - "runtime-tokio-native-tls", - "time", - "bigdecimal", -] } +sqlx = { version = "0.7.3", features = ["postgres", "runtime-tokio", "runtime-tokio-native-tls", "time", "bigdecimal"] } strum = { version = "0.26.2", features = ["derive"] } thiserror = "1.0.58" time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] } diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index 0595bdc3e75..9c9e1b85015 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -30,8 +30,7 @@ strum = { version = "0.26", features = ["derive"] } time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] } url = { version = "2.5.0", features = ["serde"] } utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] } -frunk = "0.4.2" -frunk_core = "0.4.2" + # First party crates cards = { version = "0.1.0", path = "../cards" } common_enums = { version = "0.1.0", path = "../common_enums" } diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 1161602435b..2fc709bf1f4 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -618,7 +618,6 @@ pub enum LockerChoice { serde::Deserialize, strum::Display, strum::EnumString, - frunk::LabelledGeneric, ToSchema, )] #[serde(rename_all = "snake_case")] diff --git a/crates/common_enums/Cargo.toml b/crates/common_enums/Cargo.toml index c69676c01da..e29261192fe 100644 --- a/crates/common_enums/Cargo.toml +++ b/crates/common_enums/Cargo.toml @@ -13,14 +13,12 @@ openapi = [] payouts = [] [dependencies] -thiserror = "1.0.58" diesel = { version = "2.1.5", features = ["postgres"] } serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" strum = { version = "0.26", features = ["derive"] } +thiserror = "1.0.58" utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] } -frunk = "0.4.2" -frunk_core = "0.4.2" # First party crates router_derive = { version = "0.1.0", path = "../router_derive" } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 5be7dcd66f9..4cc57d180a8 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -326,7 +326,6 @@ pub enum AuthenticationType { serde::Deserialize, strum::Display, strum::EnumString, - frunk::LabelledGeneric, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index f6c3d8b6d0d..df6b4400633 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -17,6 +17,7 @@ metrics = ["dep:router_env", "dep:futures"] [dependencies] async-trait = { version = "0.1.79", optional = true } +blake3 = { version = "1.5.1", features = ["serde"] } bytes = "1.6.0" diesel = "2.1.5" error-stack = "0.4.1" @@ -25,6 +26,7 @@ hex = "0.4.3" http = "0.2.12" md5 = "0.7.0" nanoid = "0.4.0" +nutype = { version = "0.4.2", features = ["serde"] } once_cell = "1.19.0" phonenumber = "0.3.3" quick-xml = { version = "0.31.0", features = ["serialize"] } @@ -46,16 +48,11 @@ tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"], optional url = { version = "2.5.0", features = ["serde"] } utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] } uuid = { version = "1.8.0", features = ["v7"] } -blake3 = { version = "1.5.1", features = ["serde"] } - # First party crates -rusty-money = { git = "https://github.com/varunsrin/rusty_money", rev = "bbc0150742a0fff905225ff11ee09388e9babdcc", features = ["iso", "crypto"] } common_enums = { version = "0.1.0", path = "../common_enums" } masking = { version = "0.1.0", path = "../masking" } -router_derive = { version = "0.1.0", path = "../router_derive" } router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"], optional = true } -nutype = { version = "0.4.2", features = ["serde"] } [target.'cfg(not(target_os = "windows"))'.dependencies] signal-hook-tokio = { version = "0.3.1", features = ["futures-v0_3"], optional = true } diff --git a/crates/connector_configs/Cargo.toml b/crates/connector_configs/Cargo.toml index de0c963d7b6..4b0f810df29 100644 --- a/crates/connector_configs/Cargo.toml +++ b/crates/connector_configs/Cargo.toml @@ -15,7 +15,10 @@ dummy_connector = ["api_models/dummy_connector", "development"] payouts = ["api_models/payouts"] [dependencies] +# First party crates api_models = { version = "0.1.0", path = "../api_models", package = "api_models" } + +# Third party crates serde = { version = "1.0.197", features = ["derive"] } serde_with = "3.7.0" toml = "0.8.12" diff --git a/crates/currency_conversion/Cargo.toml b/crates/currency_conversion/Cargo.toml index 40129258a67..bc255c57e16 100644 --- a/crates/currency_conversion/Cargo.toml +++ b/crates/currency_conversion/Cargo.toml @@ -6,7 +6,6 @@ edition.workspace = true rust-version.workspace = true license.workspace = true -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] # First party crates common_enums = { version = "0.1.0", path = "../common_enums", package = "common_enums" } diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml index 577233cdf1a..f33427aaf30 100644 --- a/crates/diesel_models/Cargo.toml +++ b/crates/diesel_models/Cargo.toml @@ -15,8 +15,6 @@ kv_store = [] async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } diesel = { version = "2.1.5", features = ["postgres", "serde_json", "time", "64-column-tables"] } error-stack = "0.4.1" -frunk = "0.4.2" -frunk_core = "0.4.2" serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" strum = { version = "0.26.2", features = ["derive"] } diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index 5eeed2990af..96678a7a3e1 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -205,7 +205,6 @@ pub enum FraudCheckType { serde::Deserialize, strum::Display, strum::EnumString, - frunk::LabelledGeneric, )] #[diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] @@ -228,7 +227,6 @@ pub enum FraudCheckLastStep { serde::Deserialize, strum::Display, strum::EnumString, - frunk::LabelledGeneric, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] @@ -249,7 +247,6 @@ pub enum UserStatus { serde::Serialize, strum::Display, strum::EnumString, - frunk::LabelledGeneric, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] @@ -291,7 +288,6 @@ pub enum DashboardMetadata { serde::Deserialize, strum::Display, strum::EnumString, - frunk::LabelledGeneric, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml index 424ca658847..c3e6b42135f 100644 --- a/crates/drainer/Cargo.toml +++ b/crates/drainer/Cargo.toml @@ -14,6 +14,7 @@ vergen = ["router_env/vergen"] [dependencies] actix-web = "4.5.1" async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } +async-trait = "0.1.79" bb8 = "0.8" clap = { version = "4.4.18", default-features = false, features = ["std", "derive", "help", "usage"] } config = { version = "0.14.0", features = ["toml"] } @@ -27,7 +28,6 @@ serde_json = "1.0.115" serde_path_to_error = "0.1.16" thiserror = "1.0.58" tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] } -async-trait = "0.1.79" # First Party Crates common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals"] } diff --git a/crates/euclid/Cargo.toml b/crates/euclid/Cargo.toml index 63c9c1508d9..c8cf00eb416 100644 --- a/crates/euclid/Cargo.toml +++ b/crates/euclid/Cargo.toml @@ -7,9 +7,6 @@ rust-version.workspace = true license.workspace = true [dependencies] -erased-serde = "0.4.4" -frunk = "0.4.2" -frunk_core = "0.4.2" nom = { version = "7.1.3", features = ["alloc"], optional = true } once_cell = "1.19.0" rustc-hash = "1.1.0" @@ -21,9 +18,9 @@ utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order # First party dependencies common_enums = { version = "0.1.0", path = "../common_enums" } -hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph", features = ["viz"] } +common_utils = { version = "0.1.0", path = "../common_utils" } euclid_macros = { version = "0.1.0", path = "../euclid_macros" } -common_utils = { version = "0.1.0", path = "../common_utils"} +hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph", features = ["viz"] } [features] default = [] diff --git a/crates/euclid_wasm/Cargo.toml b/crates/euclid_wasm/Cargo.toml index be8f61240d6..47127c8212e 100644 --- a/crates/euclid_wasm/Cargo.toml +++ b/crates/euclid_wasm/Cargo.toml @@ -6,7 +6,6 @@ edition.workspace = true rust-version.workspace = true license.workspace = true -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [lib] crate-type = ["cdylib"] @@ -21,12 +20,12 @@ payouts = ["api_models/payouts", "euclid/payouts"] [dependencies] api_models = { version = "0.1.0", path = "../api_models", package = "api_models" } -hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" } -currency_conversion = { version = "0.1.0", path = "../currency_conversion" } +common_enums = { version = "0.1.0", path = "../common_enums" } connector_configs = { version = "0.1.0", path = "../connector_configs" } +currency_conversion = { version = "0.1.0", path = "../currency_conversion" } euclid = { version = "0.1.0", path = "../euclid", features = [] } +hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" } kgraph_utils = { version = "0.1.0", path = "../kgraph_utils" } -common_enums = { version = "0.1.0", path = "../common_enums" } # Third party crates getrandom = { version = "0.2.12", features = ["js"] } diff --git a/crates/events/Cargo.toml b/crates/events/Cargo.toml index 228fba60a68..335a3941d56 100644 --- a/crates/events/Cargo.toml +++ b/crates/events/Cargo.toml @@ -7,9 +7,9 @@ rust-version.workspace = true license.workspace = true [dependencies] -# First Party crates +# First Party crates 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"]} +router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } # Third Party crates error-stack = "0.4.1" diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index 31e22d4a640..85df79701a7 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -17,21 +17,21 @@ hashicorp-vault = ["dep:vaultrs"] async-trait = "0.1.79" aws-config = { version = "0.55.3", optional = true } aws-sdk-kms = { version = "0.28.0", optional = true } +aws-sdk-s3 = { version = "0.28.0", optional = true } aws-sdk-sesv2 = "0.28.0" aws-sdk-sts = "0.28.0" -aws-sdk-s3 = { version = "0.28.0", optional = true } aws-smithy-client = "0.55.3" base64 = "0.22.0" dyn-clone = "1.0.17" error-stack = "0.4.1" +hex = "0.4.3" +hyper = "0.14.28" +hyper-proxy = "0.9.1" once_cell = "1.19.0" serde = { version = "1.0.197", features = ["derive"] } thiserror = "1.0.58" tokio = "1.37.0" -hyper-proxy = "0.9.1" -hyper = "0.14.28" vaultrs = { version = "0.7.2", optional = true } -hex = "0.4.3" # First party crates common_utils = { version = "0.1.0", path = "../common_utils" } diff --git a/crates/hsdev/Cargo.toml b/crates/hsdev/Cargo.toml index 6600d41d9fc..3864996ecee 100644 --- a/crates/hsdev/Cargo.toml +++ b/crates/hsdev/Cargo.toml @@ -1,16 +1,16 @@ [package] name = "hsdev" version = "0.1.0" -license.workspace = true +license.workspace = true edition.workspace = true -rust-version.workspace = true +rust-version.workspace = true description = "A simple diesel postgres migrator that uses TOML files" repository = "https://github.com/juspay/hyperswitch.git" readme = "README.md" [dependencies] +clap = { version = "4.1.8", features = ["derive"] } diesel = { version = "2.1.6", features = ["postgres"] } diesel_migrations = "2.1.0" -toml = "0.5" -clap = { version = "4.1.8", features = ["derive"] } serde = { version = "1.0", features = ["derive"] } +toml = "0.5" diff --git a/crates/hyperswitch_constraint_graph/Cargo.toml b/crates/hyperswitch_constraint_graph/Cargo.toml index 4fe97b2b1ac..34cf535d08e 100644 --- a/crates/hyperswitch_constraint_graph/Cargo.toml +++ b/crates/hyperswitch_constraint_graph/Cargo.toml @@ -5,8 +5,6 @@ version = "0.1.0" edition.workspace = true rust-version.workspace = true -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - [features] viz = ["dep:graphviz-rust"] @@ -15,6 +13,5 @@ erased-serde = "0.3.28" graphviz-rust = { version = "0.6.2", optional = true } rustc-hash = "1.1.0" serde = { version = "1.0.163", features = ["derive", "rc"] } -serde_json = "1.0.96" strum = { version = "0.25", features = ["derive"] } thiserror = "1.0.43" diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml index 320d44cf21e..ab569464684 100644 --- a/crates/hyperswitch_domain_models/Cargo.toml +++ b/crates/hyperswitch_domain_models/Cargo.toml @@ -16,11 +16,11 @@ frm = ["api_models/frm"] [dependencies] # First party deps api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] } +cards = { version = "0.1.0", path = "../cards" } common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext", "metrics"] } -masking = { version = "0.1.0", path = "../masking" } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } -cards = { version = "0.1.0", path = "../cards" } +masking = { version = "0.1.0", path = "../masking" } router_derive = { version = "0.1.0", path = "../router_derive" } router_env = { version = "0.1.0", path = "../router_env" } @@ -28,6 +28,7 @@ router_env = { version = "0.1.0", path = "../router_env" } actix-web = "4.5.1" async-trait = "0.1.79" error-stack = "0.4.1" +futures = "0.3.30" http = "0.2.12" mime = "0.3.17" serde = { version = "1.0.197", features = ["derive"] } @@ -37,4 +38,3 @@ thiserror = "1.0.58" time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] } url = { version = "2.5.0", features = ["serde"] } utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order", "time"] } -futures = "0.3.30" diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.toml index 3c481caef1b..db61a05436b 100644 --- a/crates/hyperswitch_interfaces/Cargo.toml +++ b/crates/hyperswitch_interfaces/Cargo.toml @@ -34,4 +34,3 @@ hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_m masking = { version = "0.1.0", path = "../masking" } router_derive = { version = "0.1.0", path = "../router_derive" } router_env = { version = "0.1.0", path = "../router_env" } -storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false } \ No newline at end of file diff --git a/crates/kgraph_utils/Cargo.toml b/crates/kgraph_utils/Cargo.toml index 6172e75629f..d4110ae618f 100644 --- a/crates/kgraph_utils/Cargo.toml +++ b/crates/kgraph_utils/Cargo.toml @@ -13,16 +13,16 @@ dummy_connector = ["api_models/dummy_connector", "euclid/dummy_connector"] [dependencies] api_models = { version = "0.1.0", path = "../api_models", package = "api_models" } common_enums = { version = "0.1.0", path = "../common_enums" } -hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph", features = ["viz"] } +common_utils = { version = "0.1.0", path = "../common_utils" } euclid = { version = "0.1.0", path = "../euclid" } +hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph", features = ["viz"] } masking = { version = "0.1.0", path = "../masking/" } -common_utils = {version = "0.1.0", path = "../common_utils"} # Third party crates serde = "1.0.197" serde_json = "1.0.115" -thiserror = "1.0.58" strum = { version = "0.26", features = ["derive"] } +thiserror = "1.0.58" [dev-dependencies] criterion = "0.5" diff --git a/crates/masking/Cargo.toml b/crates/masking/Cargo.toml index 5c73ed7ea32..c65fdaa96a8 100644 --- a/crates/masking/Cargo.toml +++ b/crates/masking/Cargo.toml @@ -24,7 +24,7 @@ erased-serde = "0.4.4" serde = { version = "1", features = ["derive"], optional = true } serde_json = { version = "1.0.115", optional = true } subtle = "2.5.0" -time = {version = "0.3.35", optional = true, features = ["serde-human-readable"] } +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 } diff --git a/crates/openapi/Cargo.toml b/crates/openapi/Cargo.toml index 9b81225bcba..e3e3bcc4a8f 100644 --- a/crates/openapi/Cargo.toml +++ b/crates/openapi/Cargo.toml @@ -5,12 +5,12 @@ edition.workspace = true rust-version.workspace = true license.workspace = true -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - [dependencies] +# Third party crates serde_json = "1.0.115" utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order", "time"] } +# First party crates api_models = { version = "0.1.0", path = "../api_models", features = ["frm", "payouts", "openapi"] } common_utils = { version = "0.1.0", path = "../common_utils" } router_env = { version = "0.1.0", path = "../router_env" } diff --git a/crates/pm_auth/Cargo.toml b/crates/pm_auth/Cargo.toml index bb56db6f232..a3c47e97d78 100644 --- a/crates/pm_auth/Cargo.toml +++ b/crates/pm_auth/Cargo.toml @@ -13,8 +13,6 @@ api_models = { version = "0.1.0", path = "../api_models" } common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils" } masking = { version = "0.1.0", path = "../masking" } -router_derive = { version = "0.1.0", path = "../router_derive" } -router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } # Third party crates async-trait = "0.1.79" diff --git a/crates/redis_interface/Cargo.toml b/crates/redis_interface/Cargo.toml index d55ff86bcea..e9dfc8cb518 100644 --- a/crates/redis_interface/Cargo.toml +++ b/crates/redis_interface/Cargo.toml @@ -14,7 +14,7 @@ futures = "0.3" serde = { version = "1.0.197", features = ["derive"] } thiserror = "1.0.58" tokio = "1.37.0" -tokio-stream = {version = "0.1.15", features = ["sync"]} +tokio-stream = { version = "0.1.15", features = ["sync"] } tracing = { workspace = true } # First party crates diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 438e0dc323d..1379b17eec4 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -11,12 +11,12 @@ license.workspace = true [features] default = ["kv_store", "stripe", "oltp", "olap", "accounts_cache", "dummy_connector", "payouts", "payout_retry", "retry", "frm", "tls"] tls = ["actix-web/rustls-0_22"] -keymanager_mtls = ["reqwest/rustls-tls","common_utils/keymanager_mtls"] +keymanager_mtls = ["reqwest/rustls-tls", "common_utils/keymanager_mtls"] email = ["external_services/email", "scheduler/email", "olap"] keymanager_create = [] frm = ["api_models/frm", "hyperswitch_domain_models/frm"] stripe = ["dep:serde_qs"] -release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3","keymanager_mtls","keymanager_create"] +release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3", "keymanager_mtls", "keymanager_create"] olap = ["hyperswitch_domain_models/olap", "storage_impl/olap", "scheduler/olap", "api_models/olap", "dep:analytics"] oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"] @@ -33,11 +33,12 @@ v2 = ["api_models/v2"] [dependencies] actix-cors = "0.6.5" +actix-http = "3.6.0" actix-multipart = "0.6.1" actix-rt = "2.9.0" actix-web = "4.5.1" -async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } argon2 = { version = "0.5.3", features = ["std"] } +async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } async-trait = "0.1.79" base64 = "0.22.0" bb8 = "0.8" @@ -60,6 +61,8 @@ http = "0.2.12" hyper = "0.14.28" image = { version = "0.25.1", default-features = false, features = ["png"] } infer = "0.15.0" +iso_currency = "0.4.4" +isocountry = "0.3.2" josekit = "0.8.6" jsonwebtoken = "9.2.0" maud = { version = "0.26.0", features = ["actix-web"] } @@ -68,11 +71,13 @@ mime = "0.3.17" nanoid = "0.4.0" num_cpus = "1.16.0" once_cell = "1.19.0" -openidconnect = "3.5.0" # TODO: remove reqwest +openidconnect = "3.5.0" # TODO: remove reqwest openssl = "0.10.64" qrcode = "0.14.0" +quick-xml = { version = "0.31.0", features = ["serialize"] } rand = "0.8.5" rand_chacha = "0.3.1" +rdkafka = "0.36.2" regex = "1.10.4" reqwest = { version = "0.11.27", features = ["json", "native-tls", "__rustls", "gzip", "multipart"] } ring = "0.17.8" @@ -85,54 +90,47 @@ serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" serde_path_to_error = "0.1.16" serde_qs = { version = "0.12.0", optional = true } +serde_repr = "0.1.19" serde_urlencoded = "0.7.1" serde_with = "3.7.0" sha1 = { version = "0.10.6" } -sqlx = { version = "0.7.3", features = ["postgres", "runtime-tokio", "runtime-tokio-native-tls", "time", "bigdecimal"] } strum = { version = "0.26", features = ["derive"] } tera = "1.19.1" thiserror = "1.0.58" time = { version = "0.3.35", features = ["serde", "serde-well-known", "std", "parsing", "serde-human-readable"] } tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] } +totp-rs = { version = "5.5.1", features = ["gen_secret", "otpauth"] } +tracing-futures = { version = "0.2.5", features = ["tokio"] } unicode-segmentation = "1.11.0" +unidecode = "0.3.0" url = { version = "2.5.0", features = ["serde"] } utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order", "time"] } uuid = { version = "1.8.0", features = ["v4"] } validator = "0.17.0" x509-parser = "0.16.0" -tracing-futures = { version = "0.2.5", features = ["tokio"] } # First party crates -api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] } analytics = { version = "0.1.0", path = "../analytics", optional = true } +api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] } cards = { version = "0.1.0", path = "../cards" } common_enums = { version = "0.1.0", path = "../common_enums" } -common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics","keymanager"] } -hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" } +common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics", "keymanager"] } currency_conversion = { version = "0.1.0", path = "../currency_conversion" } -hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } euclid = { version = "0.1.0", path = "../euclid", features = ["valued_jit"] } -pm_auth = { version = "0.1.0", path = "../pm_auth", package = "pm_auth" } +events = { version = "0.1.0", path = "../events" } external_services = { version = "0.1.0", path = "../external_services" } +hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" } +hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" } kgraph_utils = { version = "0.1.0", path = "../kgraph_utils" } masking = { version = "0.1.0", path = "../masking" } +pm_auth = { version = "0.1.0", path = "../pm_auth", package = "pm_auth" } redis_interface = { version = "0.1.0", path = "../redis_interface" } router_derive = { version = "0.1.0", path = "../router_derive" } router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } scheduler = { version = "0.1.0", path = "../scheduler", default-features = false } storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false } -erased-serde = "0.4.4" -quick-xml = { version = "0.31.0", features = ["serialize"] } -rdkafka = "0.36.2" -isocountry = "0.3.2" -iso_currency = "0.4.4" -actix-http = "3.6.0" -events = { version = "0.1.0", path = "../events" } -totp-rs = { version = "5.5.1", features = ["gen_secret", "otpauth"] } -serde_repr = "0.1.19" -unidecode = "0.3.0" [build-dependencies] router_env = { version = "0.1.0", path = "../router_env", default-features = false } diff --git a/crates/router_derive/Cargo.toml b/crates/router_derive/Cargo.toml index 99e50bf5528..82535e1bd1d 100644 --- a/crates/router_derive/Cargo.toml +++ b/crates/router_derive/Cargo.toml @@ -15,8 +15,8 @@ doctest = false indexmap = "2.2.6" proc-macro2 = "1.0.79" quote = "1.0.35" -syn = { version = "2.0.57", features = ["full", "extra-traits"] } # the full feature does not seem to encompass all the features strum = { version = "0.26.2", features = ["derive"] } +syn = { version = "2.0.57", features = ["full", "extra-traits"] } # the full feature does not seem to encompass all the features [dev-dependencies] diesel = { version = "2.1.5", features = ["postgres"] } diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml index 59bfb4d5c8e..b9b1184fedf 100644 --- a/crates/router_env/Cargo.toml +++ b/crates/router_env/Cargo.toml @@ -14,7 +14,6 @@ error-stack = "0.4.1" gethostname = "0.4.3" once_cell = "1.19.0" opentelemetry = { version = "0.19.0", features = ["rt-tokio-current-thread", "metrics"] } -common_enums = { path = "../common_enums" } opentelemetry-otlp = { version = "0.12.0", features = ["metrics"] } rustc-hash = "1.1" serde = { version = "1.0.197", features = ["derive"] } diff --git a/crates/scheduler/Cargo.toml b/crates/scheduler/Cargo.toml index 73832a1ad6a..14a0c8884e1 100644 --- a/crates/scheduler/Cargo.toml +++ b/crates/scheduler/Cargo.toml @@ -31,12 +31,7 @@ uuid = { version = "1.8.0", features = ["v4"] } common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext"] } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } external_services = { version = "0.1.0", path = "../external_services" } -masking = { version = "0.1.0", path = "../masking" } +hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } redis_interface = { version = "0.1.0", path = "../redis_interface" } 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 } -hyperswitch_domain_models = {version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } - -# [[bin]] -# name = "scheduler" -# path = "src/bin/scheduler.rs" diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml index d96d5ac7d57..54374643f44 100644 --- a/crates/storage_impl/Cargo.toml +++ b/crates/storage_impl/Cargo.toml @@ -7,7 +7,6 @@ rust-version.workspace = true readme = "README.md" license.workspace = true -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [features] default = ["olap", "oltp"] oltp = [] @@ -17,17 +16,16 @@ payouts = ["hyperswitch_domain_models/payouts"] [dependencies] # First Party dependencies api_models = { version = "0.1.0", path = "../api_models" } -common_utils = { version = "0.1.0", path = "../common_utils" } common_enums = { version = "0.1.0", path = "../common_enums" } -hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } +common_utils = { version = "0.1.0", path = "../common_utils" } diesel_models = { version = "0.1.0", path = "../diesel_models" } +hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } masking = { version = "0.1.0", path = "../masking" } redis_interface = { version = "0.1.0", path = "../redis_interface" } router_derive = { version = "0.1.0", path = "../router_derive" } router_env = { version = "0.1.0", path = "../router_env" } # Third party crates -actix-web = "4.5.1" async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } async-trait = "0.1.79" bb8 = "0.8.3" @@ -38,8 +36,6 @@ diesel = { version = "2.1.5", default-features = false, features = ["postgres"] dyn-clone = "1.0.17" error-stack = "0.4.1" futures = "0.3.30" -http = "0.2.12" -mime = "0.3.17" moka = { version = "0.12", features = ["future"] } once_cell = "1.19.0" serde = { version = "1.0.197", features = ["derive"] } diff --git a/crates/test_utils/Cargo.toml b/crates/test_utils/Cargo.toml index 6d8663c0300..3b9eaa73292 100644 --- a/crates/test_utils/Cargo.toml +++ b/crates/test_utils/Cargo.toml @@ -13,8 +13,8 @@ dummy_connector = [] payouts = [] [dependencies] -async-trait = "0.1.79" anyhow = "1.0.81" +async-trait = "0.1.79" base64 = "0.22.0" clap = { version = "4.4.18", default-features = false, features = ["std", "derive", "help", "usage"] } rand = "0.8.5"
build
remove unused dependencies (#5343)
322c615c56c37554ae9760b9a584bf3b0032cf43
2023-08-28 14:39:04
SamraatBansal
fix(connector): [Noon] handle 2 digit exp year and 3ds checked status (#2022)
false
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index b7b200804cf..a27ae6d9b70 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use crate::{ connector::utils::{ - self as conn_utils, PaymentsAuthorizeRequestData, RefundsRequestData, RouterData, + self as conn_utils, CardData, PaymentsAuthorizeRequestData, RefundsRequestData, RouterData, WalletData, }, core::errors, @@ -181,10 +181,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { _ => ( match item.request.payment_method_data.clone() { api::PaymentMethodData::Card(req_card) => Ok(NoonPaymentData::Card(NoonCard { - name_on_card: req_card.card_holder_name, - number_plain: req_card.card_number, - expiry_month: req_card.card_exp_month, - expiry_year: req_card.card_exp_year, + name_on_card: req_card.card_holder_name.clone(), + number_plain: req_card.card_number.clone(), + expiry_month: req_card.card_exp_month.clone(), + expiry_year: req_card.get_expiry_year_4_digit(), cvv: req_card.card_cvc, })), api::PaymentMethodData::Wallet(wallet_data) => match wallet_data.clone() { @@ -312,6 +312,8 @@ pub enum NoonPaymentStatus { Cancelled, #[serde(rename = "3DS_ENROLL_INITIATED")] ThreeDsEnrollInitiated, + #[serde(rename = "3DS_ENROLL_CHECKED")] + ThreeDsEnrollChecked, Failed, #[default] Pending, @@ -324,7 +326,9 @@ impl From<NoonPaymentStatus> for enums::AttemptStatus { NoonPaymentStatus::Captured | NoonPaymentStatus::PartiallyCaptured => Self::Charged, NoonPaymentStatus::Reversed => Self::Voided, NoonPaymentStatus::Cancelled => Self::AuthenticationFailed, - NoonPaymentStatus::ThreeDsEnrollInitiated => Self::AuthenticationPending, + NoonPaymentStatus::ThreeDsEnrollInitiated | NoonPaymentStatus::ThreeDsEnrollChecked => { + Self::AuthenticationPending + } NoonPaymentStatus::Failed => Self::Failure, NoonPaymentStatus::Pending => Self::Pending, }
fix
[Noon] handle 2 digit exp year and 3ds checked status (#2022)
9a54838b0529013ab8f449ec6b347a104b55f8f7
2024-01-25 15:45:49
chikke srujan
fix(connector): fix connector template script (#3453)
false
diff --git a/connector-template/mod.rs b/connector-template/mod.rs index 6258d437076..c64ce431968 100644 --- a/connector-template/mod.rs +++ b/connector-template/mod.rs @@ -167,10 +167,8 @@ impl req.request.amount, req, ))?; - let req_obj = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest::try_from(&connector_router_data)?; - let {{project-name | downcase}}_req = types::RequestBody::log_and_get_request_body(&req_obj, utils::Encode::<{{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest>::encode_to_string_of_json) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some({{project-name | downcase}}_req)) + let connector_req = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( @@ -385,10 +383,8 @@ impl req.request.refund_amount, req, ))?; - let req_obj = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}RefundRequest::try_from(&connector_router_data)?; - let {{project-name | downcase}}_req = types::RequestBody::log_and_get_request_body(&req_obj, utils::Encode::<{{project-name | downcase}}::{{project-name | downcase | pascal_case}}RefundRequest>::encode_to_string_of_json) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some({{project-name | downcase}}_req)) + let connector_req = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}RefundRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request(&self, req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors,) -> CustomResult<Option<services::Request>,errors::ConnectorError> {
fix
fix connector template script (#3453)
d0eec9e357a2ef6074c9a02239337378fbf8412a
2023-09-20 17:27:30
Prasunna Soppa
feat(connector): [Trustpay] Add Blik payment method for trustpay (#2152)
false
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index c03f0496584..5bc2c0e9d9e 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -1,7 +1,10 @@ use std::collections::HashMap; use api_models::payments::BankRedirectData; -use common_utils::{errors::CustomResult, pii}; +use common_utils::{ + errors::CustomResult, + pii::{self, Email}, +}; use error_stack::{report, IntoReport, ResultExt}; use masking::{PeekInterface, Secret}; use reqwest::Url; @@ -47,13 +50,14 @@ impl TryFrom<&types::ConnectorAuthType> for TrustpayAuthType { } } -#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] pub enum TrustpayPaymentMethod { #[serde(rename = "EPS")] Eps, Giropay, IDeal, Sofort, + Blik, } #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)] @@ -88,11 +92,20 @@ pub struct StatusReasonInformation { pub reason: Reason, } +#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] +#[serde(rename_all = "PascalCase")] +pub struct DebtorInformation { + pub name: Secret<String>, + pub email: Email, +} + #[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] #[serde(rename_all = "PascalCase")] pub struct BankPaymentInformation { pub amount: Amount, pub references: References, + #[serde(skip_serializing_if = "Option::is_none")] + pub debtor: Option<DebtorInformation>, } #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] @@ -131,7 +144,7 @@ pub struct PaymentRequestCards { #[serde(rename = "billing[postcode]")] pub billing_postcode: Secret<String>, #[serde(rename = "customer[email]")] - pub customer_email: pii::Email, + pub customer_email: Email, #[serde(rename = "customer[ipAddress]")] pub customer_ip_address: Secret<String, pii::IpAddress>, #[serde(rename = "browser[acceptHeader]")] @@ -193,6 +206,7 @@ impl TryFrom<&BankRedirectData> for TrustpayPaymentMethod { api_models::payments::BankRedirectData::Eps { .. } => Ok(Self::Eps), api_models::payments::BankRedirectData::Ideal { .. } => Ok(Self::IDeal), api_models::payments::BankRedirectData::Sofort { .. } => Ok(Self::Sofort), + api_models::payments::BankRedirectData::Blik { .. } => Ok(Self::Blik), _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } @@ -229,7 +243,7 @@ fn get_card_request_data( .get_billing()? .address .as_ref() - .map(|address| address.last_name.clone().unwrap_or_default()); + .and_then(|address| address.last_name.clone()); Ok(TrustpayPaymentsRequest::CardsPaymentRequest(Box::new( PaymentRequestCards { amount, @@ -237,12 +251,7 @@ fn get_card_request_data( pan: ccard.card_number.clone(), cvv: ccard.card_cvc.clone(), expiry_date: ccard.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned()), - cardholder: match billing_last_name { - Some(last_name) => { - format!("{} {}", params.billing_first_name.peek(), last_name.peek()).into() - } - None => params.billing_first_name, - }, + cardholder: get_full_name(params.billing_first_name, billing_last_name), reference: item.payment_id.clone(), redirect_url: return_url, billing_city: params.billing_city, @@ -267,16 +276,50 @@ fn get_card_request_data( ))) } +fn get_full_name( + billing_first_name: Secret<String>, + billing_last_name: Option<Secret<String>>, +) -> Secret<String> { + match billing_last_name { + Some(last_name) => format!("{} {}", billing_first_name.peek(), last_name.peek()).into(), + None => billing_first_name, + } +} + +fn get_debtor_info( + item: &types::PaymentsAuthorizeRouterData, + pm: TrustpayPaymentMethod, + params: TrustpayMandatoryParams, +) -> CustomResult<Option<DebtorInformation>, errors::ConnectorError> { + let billing_last_name = item + .get_billing()? + .address + .as_ref() + .and_then(|address| address.last_name.clone()); + Ok(match pm { + TrustpayPaymentMethod::Blik => Some(DebtorInformation { + name: get_full_name(params.billing_first_name, billing_last_name), + email: item.request.get_email()?, + }), + TrustpayPaymentMethod::Eps + | TrustpayPaymentMethod::Giropay + | TrustpayPaymentMethod::IDeal + | TrustpayPaymentMethod::Sofort => None, + }) +} + fn get_bank_redirection_request_data( item: &types::PaymentsAuthorizeRouterData, bank_redirection_data: &BankRedirectData, + params: TrustpayMandatoryParams, amount: String, auth: TrustpayAuthType, ) -> Result<TrustpayPaymentsRequest, error_stack::Report<errors::ConnectorError>> { + let pm = TrustpayPaymentMethod::try_from(bank_redirection_data)?; let return_url = item.request.get_return_url()?; let payment_request = TrustpayPaymentsRequest::BankRedirectPaymentRequest(Box::new(PaymentRequestBankRedirect { - payment_method: TrustpayPaymentMethod::try_from(bank_redirection_data)?, + payment_method: pm.clone(), merchant_identification: MerchantIdentification { project_id: auth.project_id, }, @@ -288,6 +331,7 @@ fn get_bank_redirection_request_data( references: References { merchant_reference: item.payment_id.clone(), }, + debtor: get_debtor_info(item, pm, params)?, }, callback_urls: CallbackURLs { success: format!("{return_url}?status=SuccessOk"), @@ -334,7 +378,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TrustpayPaymentsRequest { item.request.get_return_url()?, )?), api::PaymentMethodData::BankRedirect(ref bank_redirection_data) => { - get_bank_redirection_request_data(item, bank_redirection_data, amount, auth) + get_bank_redirection_request_data(item, bank_redirection_data, params, amount, auth) } _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), } @@ -1256,6 +1300,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for TrustpayRefundRequest { references: References { merchant_reference: item.request.refund_id.clone(), }, + debtor: None, }, }, )))
feat
[Trustpay] Add Blik payment method for trustpay (#2152)
5918014da158abbf44540c855e35b0b5bb363fb2
2024-12-07 14:35:44
Prajjwal Kumar
feat(dynamic_routing): analytics improvement using separate postgres table (#6723)
false
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index c4c2f072b1e..eeb67d679ee 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -740,7 +740,6 @@ pub struct ToggleDynamicRoutingPath { #[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>, } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index e94b40a4af8..7d835980056 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -20,7 +20,9 @@ pub mod diesel_exports { DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, DbRefundStatus as RefundStatus, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, - DbScaExemptionType as ScaExemptionType, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, + DbScaExemptionType as ScaExemptionType, + DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, + DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } @@ -3283,10 +3285,20 @@ pub enum DeleteStatus { } #[derive( - Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, Hash, + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + Hash, + strum::EnumString, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] +#[router_derive::diesel_enum(storage_type = "db_enum")] pub enum SuccessBasedRoutingConclusiveState { // pc: payment connector // sc: success based routing outcome/first connector diff --git a/crates/diesel_models/src/dynamic_routing_stats.rs b/crates/diesel_models/src/dynamic_routing_stats.rs new file mode 100644 index 00000000000..168699d7f56 --- /dev/null +++ b/crates/diesel_models/src/dynamic_routing_stats.rs @@ -0,0 +1,41 @@ +use diesel::{Insertable, Queryable, Selectable}; + +use crate::schema::dynamic_routing_stats; + +#[derive(Clone, Debug, Eq, Insertable, PartialEq)] +#[diesel(table_name = dynamic_routing_stats)] +pub struct DynamicRoutingStatsNew { + pub payment_id: common_utils::id_type::PaymentId, + pub attempt_id: String, + pub merchant_id: common_utils::id_type::MerchantId, + pub profile_id: common_utils::id_type::ProfileId, + pub amount: common_utils::types::MinorUnit, + pub success_based_routing_connector: String, + pub payment_connector: String, + pub currency: Option<common_enums::Currency>, + pub payment_method: Option<common_enums::PaymentMethod>, + pub capture_method: Option<common_enums::CaptureMethod>, + pub authentication_type: Option<common_enums::AuthenticationType>, + pub payment_status: common_enums::AttemptStatus, + pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState, + pub created_at: time::PrimitiveDateTime, +} + +#[derive(Clone, Debug, Eq, PartialEq, Queryable, Selectable, Insertable)] +#[diesel(table_name = dynamic_routing_stats, primary_key(payment_id), check_for_backend(diesel::pg::Pg))] +pub struct DynamicRoutingStats { + pub payment_id: common_utils::id_type::PaymentId, + pub attempt_id: String, + pub merchant_id: common_utils::id_type::MerchantId, + pub profile_id: common_utils::id_type::ProfileId, + pub amount: common_utils::types::MinorUnit, + pub success_based_routing_connector: String, + pub payment_connector: String, + pub currency: Option<common_enums::Currency>, + pub payment_method: Option<common_enums::PaymentMethod>, + pub capture_method: Option<common_enums::CaptureMethod>, + pub authentication_type: Option<common_enums::AuthenticationType>, + pub payment_status: common_enums::AttemptStatus, + pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState, + pub created_at: time::PrimitiveDateTime, +} diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index 5de048e32ef..19f3bf0a382 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -20,9 +20,11 @@ pub mod diesel_exports { DbRefundStatus as RefundStatus, DbRefundType as RefundType, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbRoleScope as RoleScope, DbRoutingAlgorithmKind as RoutingAlgorithmKind, - DbScaExemptionType as ScaExemptionType, DbTotpStatus as TotpStatus, - DbTransactionType as TransactionType, DbUserRoleVersion as UserRoleVersion, - DbUserStatus as UserStatus, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, + DbScaExemptionType as ScaExemptionType, + DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, + DbTotpStatus as TotpStatus, DbTransactionType as TransactionType, + DbUserRoleVersion as UserRoleVersion, DbUserStatus as UserStatus, + DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub use common_enums::*; diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index 7e476662ea7..d07f84aa65e 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -12,6 +12,7 @@ pub mod blocklist; pub mod blocklist_fingerprint; pub mod customers; pub mod dispute; +pub mod dynamic_routing_stats; pub mod enums; pub mod ephemeral_key; pub mod errors; diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs index f966e90acba..ab044b5c6e6 100644 --- a/crates/diesel_models/src/query.rs +++ b/crates/diesel_models/src/query.rs @@ -13,6 +13,7 @@ pub mod blocklist_fingerprint; pub mod customers; pub mod dashboard_metadata; pub mod dispute; +pub mod dynamic_routing_stats; pub mod events; pub mod file; pub mod fraud_check; diff --git a/crates/diesel_models/src/query/dynamic_routing_stats.rs b/crates/diesel_models/src/query/dynamic_routing_stats.rs new file mode 100644 index 00000000000..f6771cd103d --- /dev/null +++ b/crates/diesel_models/src/query/dynamic_routing_stats.rs @@ -0,0 +1,11 @@ +use super::generics; +use crate::{ + dynamic_routing_stats::{DynamicRoutingStats, DynamicRoutingStatsNew}, + PgPooledConn, StorageResult, +}; + +impl DynamicRoutingStatsNew { + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<DynamicRoutingStats> { + generics::generic_insert(conn, self).await + } +} diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 936428bd46c..c30562de991 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -389,6 +389,35 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + dynamic_routing_stats (attempt_id, merchant_id) { + #[max_length = 64] + payment_id -> Varchar, + #[max_length = 64] + attempt_id -> Varchar, + #[max_length = 64] + merchant_id -> Varchar, + #[max_length = 64] + profile_id -> Varchar, + amount -> Int8, + #[max_length = 64] + success_based_routing_connector -> Varchar, + #[max_length = 64] + payment_connector -> Varchar, + currency -> Nullable<Currency>, + #[max_length = 64] + payment_method -> Nullable<Varchar>, + capture_method -> Nullable<CaptureMethod>, + authentication_type -> Nullable<AuthenticationType>, + payment_status -> AttemptStatus, + conclusive_classification -> SuccessBasedRoutingConclusiveState, + created_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1414,6 +1443,7 @@ diesel::allow_tables_to_appear_in_same_query!( customers, dashboard_metadata, dispute, + dynamic_routing_stats, events, file_metadata, fraud_check, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 8a1733fc986..12bb19c0a7f 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -401,6 +401,35 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + dynamic_routing_stats (attempt_id, merchant_id) { + #[max_length = 64] + payment_id -> Varchar, + #[max_length = 64] + attempt_id -> Varchar, + #[max_length = 64] + merchant_id -> Varchar, + #[max_length = 64] + profile_id -> Varchar, + amount -> Int8, + #[max_length = 64] + success_based_routing_connector -> Varchar, + #[max_length = 64] + payment_connector -> Varchar, + currency -> Nullable<Currency>, + #[max_length = 64] + payment_method -> Nullable<Varchar>, + capture_method -> Nullable<CaptureMethod>, + authentication_type -> Nullable<AuthenticationType>, + payment_status -> AttemptStatus, + conclusive_classification -> SuccessBasedRoutingConclusiveState, + created_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1362,6 +1391,7 @@ diesel::allow_tables_to_appear_in_same_query!( customers, dashboard_metadata, dispute, + dynamic_routing_stats, events, file_metadata, fraud_check, diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 6a5e3bd0264..112c014202e 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -12,6 +12,8 @@ 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(all(feature = "v1", feature = "dynamic_routing"))] +use diesel_models::dynamic_routing_stats::DynamicRoutingStatsNew; #[cfg(feature = "v1")] use diesel_models::routing_algorithm; use error_stack::ResultExt; @@ -751,6 +753,23 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( first_success_based_connector.to_string(), ); + let dynamic_routing_stats = DynamicRoutingStatsNew { + payment_id: payment_attempt.payment_id.to_owned(), + attempt_id: payment_attempt.attempt_id.clone(), + merchant_id: payment_attempt.merchant_id.to_owned(), + profile_id: payment_attempt.profile_id.to_owned(), + amount: payment_attempt.get_total_amount(), + success_based_routing_connector: first_success_based_connector.to_string(), + payment_connector: payment_connector.to_string(), + currency: payment_attempt.currency, + payment_method: payment_attempt.payment_method, + capture_method: payment_attempt.capture_method, + authentication_type: payment_attempt.authentication_type, + payment_status: payment_attempt.status, + conclusive_classification: outcome, + created_at: common_utils::date_time::now(), + }; + core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add( &metrics::CONTEXT, 1, @@ -812,6 +831,13 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( ); logger::debug!("successfully pushed success_based_routing metrics"); + state + .store + .insert_dynamic_routing_stat_entry(dynamic_routing_stats) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to push dynamic routing stats to db")?; + client .update_success_rate( tenant_business_profile_id, diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 1ed83be4283..cc9a1e2f436 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -12,6 +12,7 @@ pub mod configs; pub mod customers; pub mod dashboard_metadata; pub mod dispute; +pub mod dynamic_routing_stats; pub mod ephemeral_key; pub mod events; pub mod file; @@ -107,6 +108,7 @@ pub trait StorageInterface: + payment_method::PaymentMethodInterface + blocklist::BlocklistInterface + blocklist_fingerprint::BlocklistFingerprintInterface + + dynamic_routing_stats::DynamicRoutingStatsInterface + scheduler::SchedulerInterface + PayoutAttemptInterface + PayoutsInterface diff --git a/crates/router/src/db/dynamic_routing_stats.rs b/crates/router/src/db/dynamic_routing_stats.rs new file mode 100644 index 00000000000..d22f4fdd40b --- /dev/null +++ b/crates/router/src/db/dynamic_routing_stats.rs @@ -0,0 +1,58 @@ +use error_stack::report; +use router_env::{instrument, tracing}; +use storage_impl::MockDb; + +use super::Store; +use crate::{ + connection, + core::errors::{self, CustomResult}, + db::kafka_store::KafkaStore, + types::storage, +}; + +#[async_trait::async_trait] +pub trait DynamicRoutingStatsInterface { + async fn insert_dynamic_routing_stat_entry( + &self, + dynamic_routing_stat_new: storage::DynamicRoutingStatsNew, + ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError>; +} + +#[async_trait::async_trait] +impl DynamicRoutingStatsInterface for Store { + #[instrument(skip_all)] + async fn insert_dynamic_routing_stat_entry( + &self, + dynamic_routing_stat: storage::DynamicRoutingStatsNew, + ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + dynamic_routing_stat + .insert(&conn) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } +} + +#[async_trait::async_trait] +impl DynamicRoutingStatsInterface for MockDb { + #[instrument(skip_all)] + async fn insert_dynamic_routing_stat_entry( + &self, + _dynamic_routing_stat: storage::DynamicRoutingStatsNew, + ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } +} + +#[async_trait::async_trait] +impl DynamicRoutingStatsInterface for KafkaStore { + #[instrument(skip_all)] + async fn insert_dynamic_routing_stat_entry( + &self, + dynamic_routing_stat: storage::DynamicRoutingStatsNew, + ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { + self.diesel_store + .insert_dynamic_routing_stat_entry(dynamic_routing_stat) + .await + } +} diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 41ece363b4f..24573548d79 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -12,6 +12,7 @@ pub mod configs; pub mod customers; pub mod dashboard_metadata; pub mod dispute; +pub mod dynamic_routing_stats; pub mod enums; pub mod ephemeral_key; pub mod events; @@ -63,12 +64,12 @@ pub use scheduler::db::process_tracker; pub use self::{ address::*, api_keys::*, authentication::*, authorization::*, blocklist::*, blocklist_fingerprint::*, blocklist_lookup::*, business_profile::*, capture::*, cards_info::*, - configs::*, customers::*, dashboard_metadata::*, dispute::*, ephemeral_key::*, events::*, - file::*, fraud_check::*, generic_link::*, gsm::*, locker_mock_up::*, mandate::*, - merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*, - payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*, - routing_algorithm::*, unified_translations::*, user::*, user_authentication_method::*, - user_role::*, + configs::*, customers::*, dashboard_metadata::*, dispute::*, dynamic_routing_stats::*, + ephemeral_key::*, events::*, file::*, fraud_check::*, generic_link::*, gsm::*, + locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*, + merchant_key_store::*, payment_link::*, payment_method::*, process_tracker::*, refund::*, + reverse_lookup::*, role::*, routing_algorithm::*, unified_translations::*, user::*, + user_authentication_method::*, user_role::*, }; use crate::types::api::routing; diff --git a/crates/router/src/types/storage/dynamic_routing_stats.rs b/crates/router/src/types/storage/dynamic_routing_stats.rs new file mode 100644 index 00000000000..ba692a25255 --- /dev/null +++ b/crates/router/src/types/storage/dynamic_routing_stats.rs @@ -0,0 +1 @@ +pub use diesel_models::dynamic_routing_stats::{DynamicRoutingStats, DynamicRoutingStatsNew}; diff --git a/migrations/2024-12-02-095127_add_new_table_dynamic_routing_stats/down.sql b/migrations/2024-12-02-095127_add_new_table_dynamic_routing_stats/down.sql new file mode 100644 index 00000000000..993a082c234 --- /dev/null +++ b/migrations/2024-12-02-095127_add_new_table_dynamic_routing_stats/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +DROP TABLE IF EXISTS dynamic_routing_stats; +DROP TYPE IF EXISTS "SuccessBasedRoutingConclusiveState"; diff --git a/migrations/2024-12-02-095127_add_new_table_dynamic_routing_stats/up.sql b/migrations/2024-12-02-095127_add_new_table_dynamic_routing_stats/up.sql new file mode 100644 index 00000000000..6b37787d722 --- /dev/null +++ b/migrations/2024-12-02-095127_add_new_table_dynamic_routing_stats/up.sql @@ -0,0 +1,26 @@ +--- Your SQL goes here +CREATE TYPE "SuccessBasedRoutingConclusiveState" AS ENUM( + 'true_positive', + 'false_positive', + 'true_negative', + 'false_negative' +); + +CREATE TABLE IF NOT EXISTS dynamic_routing_stats ( + payment_id VARCHAR(64) NOT NULL, + attempt_id VARCHAR(64) NOT NULL, + merchant_id VARCHAR(64) NOT NULL, + profile_id VARCHAR(64) NOT NULL, + amount BIGINT NOT NULL, + success_based_routing_connector VARCHAR(64) NOT NULL, + payment_connector VARCHAR(64) NOT NULL, + currency "Currency", + payment_method VARCHAR(64), + capture_method "CaptureMethod", + authentication_type "AuthenticationType", + payment_status "AttemptStatus" NOT NULL, + conclusive_classification "SuccessBasedRoutingConclusiveState" NOT NULL, + created_at TIMESTAMP NOT NULL, + PRIMARY KEY(attempt_id, merchant_id) +); +CREATE INDEX profile_id_index ON dynamic_routing_stats (profile_id);
feat
analytics improvement using separate postgres table (#6723)
66cd5b2fc9a32085608ed34e0af477dcafe4b957
2024-01-25 20:34:52
Swangi Kumari
refactor(connector): use utility function to raise payment method not implemented errors (#1871)
false
diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs index c671560765d..6d830f85110 100644 --- a/crates/router/src/connector/boku/transformers.rs +++ b/crates/router/src/connector/boku/transformers.rs @@ -6,7 +6,7 @@ use url::Url; use uuid::Uuid; use crate::{ - connector::utils::{AddressDetailsData, RouterData}, + connector::utils::{self, AddressDetailsData, RouterData}, core::errors, services::{self, RedirectForm}, types::{self, api, storage::enums}, @@ -81,10 +81,23 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BokuPaymentsRequest { api_models::payments::PaymentMethodData::Wallet(wallet_data) => { Self::try_from((item, &wallet_data)) } - _ => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.request.payment_method_type), - connector: "Boku", - })?, + api_models::payments::PaymentMethodData::Card(_) + | api_models::payments::PaymentMethodData::CardRedirect(_) + | api_models::payments::PaymentMethodData::PayLater(_) + | api_models::payments::PaymentMethodData::BankRedirect(_) + | api_models::payments::PaymentMethodData::BankDebit(_) + | api_models::payments::PaymentMethodData::BankTransfer(_) + | api_models::payments::PaymentMethodData::Crypto(_) + | api_models::payments::PaymentMethodData::MandatePayment + | api_models::payments::PaymentMethodData::Reward + | api_models::payments::PaymentMethodData::Upi(_) + | api_models::payments::PaymentMethodData::Voucher(_) + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("boku"), + ))? + } } } } @@ -136,9 +149,31 @@ fn get_wallet_type(wallet_data: &api::WalletData) -> Result<String, errors::Conn api_models::payments::WalletData::KakaoPayRedirect { .. } => { Ok(BokuPaymentType::Kakaopay.to_string()) } - _ => Err(errors::ConnectorError::NotImplemented( - "Payment method".to_string(), - )), + api_models::payments::WalletData::AliPayQr(_) + | api_models::payments::WalletData::AliPayRedirect(_) + | api_models::payments::WalletData::AliPayHkRedirect(_) + | api_models::payments::WalletData::ApplePay(_) + | api_models::payments::WalletData::ApplePayRedirect(_) + | api_models::payments::WalletData::ApplePayThirdPartySdk(_) + | api_models::payments::WalletData::GooglePay(_) + | api_models::payments::WalletData::GooglePayRedirect(_) + | api_models::payments::WalletData::GooglePayThirdPartySdk(_) + | api_models::payments::WalletData::MbWayRedirect(_) + | api_models::payments::WalletData::MobilePayRedirect(_) + | api_models::payments::WalletData::PaypalRedirect(_) + | api_models::payments::WalletData::PaypalSdk(_) + | api_models::payments::WalletData::SamsungPay(_) + | api_models::payments::WalletData::TwintRedirect {} + | api_models::payments::WalletData::VippsRedirect {} + | api_models::payments::WalletData::TouchNGoRedirect(_) + | api_models::payments::WalletData::WeChatPayRedirect(_) + | api_models::payments::WalletData::WeChatPayQr(_) + | api_models::payments::WalletData::CashappQr(_) + | api_models::payments::WalletData::SwishQr(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("boku"), + )) + } } } diff --git a/crates/router/src/connector/globepay/transformers.rs b/crates/router/src/connector/globepay/transformers.rs index f6adacb814d..a874fc21d29 100644 --- a/crates/router/src/connector/globepay/transformers.rs +++ b/crates/router/src/connector/globepay/transformers.rs @@ -3,7 +3,7 @@ use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::RouterData, + connector::utils::{self, RouterData}, consts, core::errors, types::{self, api, storage::enums}, @@ -31,12 +31,47 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for GlobepayPaymentsRequest { api::PaymentMethodData::Wallet(ref wallet_data) => match wallet_data { api::WalletData::AliPayQr(_) => GlobepayChannel::Alipay, api::WalletData::WeChatPayQr(_) => GlobepayChannel::Wechat, - _ => Err(errors::ConnectorError::NotImplemented( - "Payment method".to_string(), + api::WalletData::AliPayRedirect(_) + | api::WalletData::AliPayHkRedirect(_) + | api::WalletData::MomoRedirect(_) + | api::WalletData::KakaoPayRedirect(_) + | api::WalletData::GoPayRedirect(_) + | api::WalletData::GcashRedirect(_) + | api::WalletData::ApplePay(_) + | api::WalletData::ApplePayRedirect(_) + | api::WalletData::ApplePayThirdPartySdk(_) + | api::WalletData::DanaRedirect {} + | api::WalletData::GooglePay(_) + | api::WalletData::GooglePayRedirect(_) + | api::WalletData::GooglePayThirdPartySdk(_) + | api::WalletData::MbWayRedirect(_) + | api::WalletData::MobilePayRedirect(_) + | api::WalletData::PaypalRedirect(_) + | api::WalletData::PaypalSdk(_) + | api::WalletData::SamsungPay(_) + | api::WalletData::TwintRedirect {} + | api::WalletData::VippsRedirect {} + | api::WalletData::TouchNGoRedirect(_) + | api::WalletData::WeChatPayRedirect(_) + | api::WalletData::CashappQr(_) + | api::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("globepay"), ))?, }, - _ => Err(errors::ConnectorError::NotImplemented( - "Payment method".to_string(), + api::PaymentMethodData::Card(_) + | api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::MandatePayment + | api::PaymentMethodData::Reward + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("globepay"), ))?, }; let description = item.get_description()?; diff --git a/crates/router/src/connector/iatapay.rs b/crates/router/src/connector/iatapay.rs index 72d7b70b061..c5ac0f43833 100644 --- a/crates/router/src/connector/iatapay.rs +++ b/crates/router/src/connector/iatapay.rs @@ -685,12 +685,18 @@ impl api::IncomingWebhook for Iatapay { &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - let notif: IatapayPaymentsResponse = - request - .body - .parse_struct("IatapayPaymentsResponse") - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + let notif: iatapay::IatapayWebhookResponse = request + .body + .parse_struct("IatapayWebhookResponse") + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - Ok(Box::new(notif)) + match notif { + iatapay::IatapayWebhookResponse::IatapayPaymentWebhookBody(wh_body) => { + Ok(Box::new(wh_body)) + } + iatapay::IatapayWebhookResponse::IatapayRefundWebhookBody(refund_wh_body) => { + Ok(Box::new(refund_wh_body)) + } + } } } diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index 14b37d1418d..4557fda0390 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -265,9 +265,6 @@ pub struct IatapayPaymentsResponse { pub merchant_payment_id: Option<String>, pub amount: f64, pub currency: String, - pub country: Option<String>, - pub locale: Option<String>, - pub bank_transfer_description: Option<String>, pub checkout_methods: Option<CheckoutMethod>, pub failure_code: Option<String>, pub failure_details: Option<String>, @@ -532,6 +529,9 @@ pub struct IatapayPaymentWebhookBody { pub merchant_payment_id: Option<String>, pub failure_code: Option<String>, pub failure_details: Option<String>, + pub amount: f64, + pub currency: String, + pub checkout_methods: Option<CheckoutMethod>, } #[derive(Debug, Serialize, Deserialize)] @@ -542,9 +542,12 @@ pub struct IatapayRefundWebhookBody { pub merchant_refund_id: Option<String>, pub failure_code: Option<String>, pub failure_details: Option<String>, + pub amount: f64, + pub currency: String, } #[derive(Debug, Serialize, Deserialize)] +#[serde(untagged)] pub enum IatapayWebhookResponse { IatapayPaymentWebhookBody(IatapayPaymentWebhookBody), IatapayRefundWebhookBody(IatapayRefundWebhookBody),
refactor
use utility function to raise payment method not implemented errors (#1871)
a8889530043efb455b6a20ebffd2e972b5224b6f
2023-08-25 14:44:17
Sampras Lopes
fix(payment): fix max limit on payment intents list (#2014)
false
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index bcc274c1560..c65f30150a0 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1923,9 +1923,9 @@ pub struct PaymentListConstraints { pub ending_before: Option<String>, /// limit on the number of objects to return - #[schema(default = 10)] + #[schema(default = 10, maximum = 100)] #[serde(default = "default_limit")] - pub limit: i64, + pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] @@ -2037,7 +2037,7 @@ pub struct VerifyResponse { pub error_message: Option<String>, } -fn default_limit() -> i64 { +fn default_limit() -> u32 { 10 } diff --git a/crates/data_models/src/payments/payment_intent.rs b/crates/data_models/src/payments/payment_intent.rs index 824049837ec..a2110900eff 100644 --- a/crates/data_models/src/payments/payment_intent.rs +++ b/crates/data_models/src/payments/payment_intent.rs @@ -4,7 +4,8 @@ use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{errors, MerchantStorageScheme}; - +const QUERY_LIMIT: u32 = 20; +const MAX_LIMIT: u32 = 100; #[async_trait::async_trait] pub trait PaymentIntentInterface { async fn update_payment_intent( @@ -353,7 +354,7 @@ pub enum PaymentIntentFetchConstraints { payment_intent_id: String, }, List { - offset: Option<u32>, + offset: u32, starting_at: Option<PrimitiveDateTime>, ending_at: Option<PrimitiveDateTime>, connector: Option<Vec<api_models::enums::Connector>>, @@ -370,7 +371,7 @@ pub enum PaymentIntentFetchConstraints { impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchConstraints { fn from(value: api_models::payments::PaymentListConstraints) -> Self { Self::List { - offset: None, + offset: 0, starting_at: value.created_gte.or(value.created_gt).or(value.created), ending_at: value.created_lte.or(value.created_lt).or(value.created), connector: None, @@ -380,7 +381,7 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo customer_id: value.customer_id, starting_after_id: value.starting_after, ending_before_id: value.ending_before, - limit: None, + limit: Some(std::cmp::min(value.limit, MAX_LIMIT)), } } } @@ -388,7 +389,7 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo impl From<api_models::payments::TimeRange> for PaymentIntentFetchConstraints { fn from(value: api_models::payments::TimeRange) -> Self { Self::List { - offset: None, + offset: 0, starting_at: Some(value.start_time), ending_at: value.end_time, connector: None, @@ -409,7 +410,7 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentF Self::Single { payment_intent_id } } else { Self::List { - offset: value.offset, + offset: value.offset.unwrap_or_default(), starting_at: value.time_range.map(|t| t.start_time), ending_at: value.time_range.and_then(|t| t.end_time), connector: value.connector, @@ -419,7 +420,7 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentF customer_id: None, starting_after_id: None, ending_before_id: None, - limit: None, + limit: Some(QUERY_LIMIT), } } } diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 8bc66328333..51ccf61377a 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -586,7 +586,7 @@ pub struct StripePaymentListConstraints { pub starting_after: Option<String>, pub ending_before: Option<String>, #[serde(default = "default_limit")] - pub limit: i64, + pub limit: u32, pub created: Option<i64>, #[serde(rename = "created[lt]")] pub created_lt: Option<i64>, @@ -598,7 +598,7 @@ pub struct StripePaymentListConstraints { pub created_gte: Option<i64>, } -fn default_limit() -> i64 { +fn default_limit() -> u32 { 10 } diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 896183da0d6..32caf4308c5 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -511,7 +511,7 @@ pub struct StripePaymentListConstraints { pub starting_after: Option<String>, pub ending_before: Option<String>, #[serde(default = "default_limit")] - pub limit: i64, + pub limit: u32, pub created: Option<i64>, #[serde(rename = "created[lt]")] pub created_lt: Option<i64>, @@ -523,7 +523,7 @@ pub struct StripePaymentListConstraints { pub created_gte: Option<i64>, } -fn default_limit() -> i64 { +fn default_limit() -> u32 { 10 } diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index 72437afd297..9b5ce8ee587 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -39,9 +39,6 @@ use crate::{ DataModelExt, DatabaseStore, KVRouterStore, }; -#[cfg(feature = "olap")] -const QUERY_LIMIT: u32 = 20; - #[async_trait::async_trait] impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { async fn insert_payment_intent( @@ -339,7 +336,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { query = query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned())); } PaymentIntentFetchConstraints::List { - offset: _, + offset, starting_at, ending_at, connector: _, @@ -351,7 +348,9 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { ending_before_id, limit, } => { - query = query.limit(limit.unwrap_or(QUERY_LIMIT).into()); + if let Some(limit) = limit { + query = query.limit((*limit).into()); + }; if let Some(customer_id) = customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); @@ -390,6 +389,8 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { } (None, None) => query, }; + query = query.offset((*offset).into()); + query = match currency { Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())), None => query, @@ -470,7 +471,9 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { ending_before_id, limit, } => { - query = query.limit(limit.unwrap_or(QUERY_LIMIT).into()); + if let Some(limit) = limit { + query = query.limit((*limit).into()); + } if let Some(customer_id) = customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); @@ -510,10 +513,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { (None, None) => query, }; - query = match offset { - Some(offset) => query.offset((*offset).into()), - None => query, - }; + query = query.offset((*offset).into()); query = match currency { Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())), diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 7a7bc9d8910..f9618b98b88 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -7661,9 +7661,11 @@ }, "limit": { "type": "integer", - "format": "int64", + "format": "int32", "description": "limit on the number of objects to return", - "default": 10 + "default": 10, + "maximum": 100.0, + "minimum": 0.0 }, "created": { "type": "string",
fix
fix max limit on payment intents list (#2014)
53cb95378e3974d1d46ff76873a95b4c5c9a4991
2024-07-10 22:09:36
Narayan Bhat
fix(payments_create): save the `customer_id` in payments create (#5262)
false
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 97fc20d9444..d63ac8a030f 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -518,6 +518,139 @@ pub struct PaymentsRequest { pub merchant_order_reference_id: Option<String>, } +/// Checks if the inner values of two options are equal +/// Returns true if values are not equal, returns false in other cases +fn are_optional_values_invalid<T: PartialEq>( + first_option: Option<&T>, + second_option: Option<&T>, +) -> bool { + match (first_option, second_option) { + (Some(first_option), Some(second_option)) => first_option != second_option, + _ => false, + } +} + +impl PaymentsRequest { + /// Get the customer id + /// + /// First check the id for `customer.id` + /// If not present, check for `customer_id` at the root level + pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { + self.customer_id + .as_ref() + .or(self.customer.as_ref().map(|customer| &customer.id)) + } + + /// Checks if the customer details are passed in both places + /// If they are passed in both places, check for both the values to be equal + /// Or else, return the field which has inconsistent data + pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { + if let Some(CustomerDetails { + id, + name, + email, + phone, + phone_country_code, + }) = self.customer.as_ref() + { + let invalid_fields = [ + are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) + .then_some("customer_id and customer.id"), + are_optional_values_invalid(self.email.as_ref(), email.as_ref()) + .then_some("email and customer.email"), + are_optional_values_invalid(self.name.as_ref(), name.as_ref()) + .then_some("name and customer.name"), + are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) + .then_some("phone and customer.phone"), + are_optional_values_invalid( + self.phone_country_code.as_ref(), + phone_country_code.as_ref(), + ) + .then_some("phone_country_code and customer.phone_country_code"), + ] + .into_iter() + .flatten() + .collect::<Vec<_>>(); + + if invalid_fields.is_empty() { + None + } else { + Some(invalid_fields) + } + } else { + None + } + } +} + +#[cfg(test)] +mod payments_request_test { + use common_utils::generate_customer_id_of_default_length; + + use super::*; + + #[test] + fn test_valid_case_where_customer_details_are_passed_only_once() { + let customer_id = generate_customer_id_of_default_length(); + let payments_request = PaymentsRequest { + customer_id: Some(customer_id), + ..Default::default() + }; + + assert!(payments_request + .validate_customer_details_in_request() + .is_none()); + } + + #[test] + fn test_valid_case_where_customer_id_is_passed_in_both_places() { + let customer_id = generate_customer_id_of_default_length(); + + let customer_object = CustomerDetails { + id: customer_id.clone(), + name: None, + email: None, + phone: None, + phone_country_code: None, + }; + + let payments_request = PaymentsRequest { + customer_id: Some(customer_id), + customer: Some(customer_object), + ..Default::default() + }; + + assert!(payments_request + .validate_customer_details_in_request() + .is_none()); + } + + #[test] + fn test_invalid_case_where_customer_id_is_passed_in_both_places() { + let customer_id = generate_customer_id_of_default_length(); + let another_customer_id = generate_customer_id_of_default_length(); + + let customer_object = CustomerDetails { + id: customer_id.clone(), + name: None, + email: None, + phone: None, + phone_country_code: None, + }; + + let payments_request = PaymentsRequest { + customer_id: Some(another_customer_id), + customer: Some(customer_object), + ..Default::default() + }; + + assert_eq!( + payments_request.validate_customer_details_in_request(), + Some(vec!["customer_id and customer.id"]) + ); + } +} + /// Fee information to be charged on the payment being collected #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 745a69a1f56..2f332530df7 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -451,7 +451,7 @@ pub async fn get_token_pm_type_mandate_details( merchant_account: &domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, payment_method_id: Option<String>, - customer_id: &Option<id_type::CustomerId>, + payment_intent_customer_id: Option<&id_type::CustomerId>, ) -> RouterResult<MandateGenericData> { let mandate_data = request.mandate_data.clone().map(MandateData::foreign_from); let ( @@ -505,14 +505,15 @@ pub async fn get_token_pm_type_mandate_details( .to_not_found_response( errors::ApiErrorResponse::PaymentMethodNotFound, )?; - let customer_id = get_customer_id_from_payment_request(request) + let customer_id = request + .get_customer_id() .get_required_value("customer_id")?; verify_mandate_details_for_recurring_payments( &payment_method_info.merchant_id, &merchant_account.merchant_id, &payment_method_info.customer_id, - &customer_id, + customer_id, )?; ( @@ -552,10 +553,9 @@ pub async fn get_token_pm_type_mandate_details( || request.payment_method_type == Some(api_models::enums::PaymentMethodType::GooglePay) { - let payment_request_customer_id = - get_customer_id_from_payment_request(request); + let payment_request_customer_id = request.get_customer_id(); if let Some(customer_id) = - &payment_request_customer_id.or(customer_id.clone()) + payment_request_customer_id.or(payment_intent_customer_id) { let customer_saved_pm_option = match state .store @@ -711,10 +711,10 @@ pub async fn get_token_for_recurring_mandate( .map(|pi| pi.amount.get_amount_as_i64()); let original_payment_authorized_currency = original_payment_intent.clone().and_then(|pi| pi.currency); - let customer = get_customer_id_from_payment_request(req).get_required_value("customer_id")?; + let customer = req.get_customer_id().get_required_value("customer_id")?; let payment_method_id = { - if mandate.customer_id != customer { + if &mandate.customer_id != customer { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "customer_id must match mandate customer_id".into() }))? @@ -1459,25 +1459,6 @@ pub async fn get_customer_from_details<F: Clone>( } } -// Checks if the inner values of two options are not equal and throws appropriate error -fn validate_options_for_inequality<T: PartialEq>( - first_option: Option<&T>, - second_option: Option<&T>, - field_name: &str, -) -> Result<(), errors::ApiErrorResponse> { - fp_utils::when( - first_option - .zip(second_option) - .map(|(value1, value2)| value1 != value2) - .unwrap_or(false), - || { - Err(errors::ApiErrorResponse::PreconditionFailed { - message: format!("The field name `{field_name}` sent in both places is ambiguous"), - }) - }, - ) -} - pub fn validate_max_amount( amount: api_models::payments::Amount, ) -> CustomResult<(), errors::ApiErrorResponse> { @@ -1496,44 +1477,21 @@ pub fn validate_max_amount( } } -// Checks if the customer details are passed in both places -// If so, raise an error -pub fn validate_customer_details_in_request( +/// Check whether the customer information that is sent in the root of payments request +/// and in the customer object are same, if the values mismatch return an error +pub fn validate_customer_information( request: &api_models::payments::PaymentsRequest, -) -> Result<(), errors::ApiErrorResponse> { - if let Some(customer_details) = request.customer.as_ref() { - validate_options_for_inequality( - request.customer_id.as_ref(), - Some(&customer_details.id), - "customer_id", - )?; - - validate_options_for_inequality( - request.email.as_ref(), - customer_details.email.as_ref(), - "email", - )?; - - validate_options_for_inequality( - request.name.as_ref(), - customer_details.name.as_ref(), - "name", - )?; - - validate_options_for_inequality( - request.phone.as_ref(), - customer_details.phone.as_ref(), - "phone", - )?; - - validate_options_for_inequality( - request.phone_country_code.as_ref(), - customer_details.phone_country_code.as_ref(), - "phone_country_code", - )?; +) -> RouterResult<()> { + if let Some(mismatched_fields) = request.validate_customer_details_in_request() { + let mismatched_fields = mismatched_fields.join(", "); + Err(errors::ApiErrorResponse::PreconditionFailed { + message: format!( + "The field names `{mismatched_fields}` sent in both places is ambiguous" + ), + })? + } else { + Ok(()) } - - Ok(()) } /// Get the customer details from customer field if present @@ -1542,12 +1500,7 @@ pub fn validate_customer_details_in_request( pub fn get_customer_details_from_request( request: &api_models::payments::PaymentsRequest, ) -> CustomerDetails { - let customer_id = request - .customer - .as_ref() - .map(|customer_details| &customer_details.id) - .or(request.customer_id.as_ref()) - .map(ToOwned::to_owned); + let customer_id = request.get_customer_id().map(ToOwned::to_owned); let customer_name = request .customer @@ -1582,16 +1535,6 @@ pub fn get_customer_details_from_request( } } -fn get_customer_id_from_payment_request( - request: &api_models::payments::PaymentsRequest, -) -> Option<id_type::CustomerId> { - request - .customer - .as_ref() - .map(|customer| customer.id.clone()) - .or(request.customer_id.clone()) -} - pub async fn get_connector_default( _state: &SessionState, request_connector: Option<serde_json::Value>, @@ -4142,8 +4085,8 @@ pub fn validate_customer_access( auth_flow: services::AuthFlow, request: &api::PaymentsRequest, ) -> Result<(), errors::ApiErrorResponse> { - if auth_flow == services::AuthFlow::Client && request.customer_id.is_some() { - let is_same_customer = request.customer_id == payment_intent.customer_id; + if auth_flow == services::AuthFlow::Client && request.get_customer_id().is_some() { + let is_same_customer = request.get_customer_id() == payment_intent.customer_id.as_ref(); if !is_same_customer { Err(errors::ApiErrorResponse::GenericUnauthorized { message: "Unauthorised access to update customer".to_string(), diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 060acf51549..9c48df1dd53 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -126,7 +126,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co merchant_account, key_store, payment_attempt.payment_method_id.clone(), - &payment_intent.customer_id, + payment_intent.customer_id.as_ref(), ) .await?; let customer_acceptance: Option<CustomerAcceptance> = request @@ -188,12 +188,15 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.get_total_amount().into(); + let customer_id = payment_intent + .customer_id + .as_ref() + .or(request.get_customer_id()) + .cloned(); + helpers::validate_customer_id_mandatory_cases( request.setup_future_usage.is_some(), - payment_intent - .customer_id - .as_ref() - .or(request.customer_id.as_ref()), + customer_id.as_ref(), )?; let shipping_address = helpers::create_or_update_address_for_payment_by_request( @@ -337,7 +340,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co }; let customer_details = Some(CustomerDetails { - customer_id: request.customer_id.clone(), + customer_id, name: request.name.clone(), email: request.email.clone(), phone: request.phone.clone(), diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 9fe28c38106..771ee137474 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -508,7 +508,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa &m_merchant_account, &m_key_store, None, - &payment_intent_customer_id, + payment_intent_customer_id.as_ref(), ) .await } @@ -1353,7 +1353,8 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfir BoxedOperation<'b, F, api::PaymentsRequest>, operations::ValidateResult<'a>, )> { - helpers::validate_customer_details_in_request(request)?; + helpers::validate_customer_information(request)?; + if let Some(amount) = request.amount { helpers::validate_max_amount(amount)?; } diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 4204972411a..4e0bbec9f17 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -136,7 +136,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa merchant_account, merchant_key_store, None, - &request.customer_id, + None, ) .await?; @@ -684,7 +684,8 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate BoxedOperation<'b, F, api::PaymentsRequest>, operations::ValidateResult<'a>, )> { - helpers::validate_customer_details_in_request(request)?; + helpers::validate_customer_information(request)?; + if let Some(amount) = request.amount { helpers::validate_max_amount(amount)?; } @@ -749,11 +750,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate helpers::validate_customer_id_mandatory_cases( request.setup_future_usage.is_some(), - request - .customer - .as_ref() - .map(|customer| &customer.id) - .or(request.customer_id.as_ref()), + request.get_customer_id(), )?; } @@ -1066,7 +1063,7 @@ impl PaymentCreate { .await; // Derivation of directly supplied Customer data in our Payment Create Request - let raw_customer_details = if request.customer_id.is_none() + let raw_customer_details = if request.get_customer_id().is_none() && (request.name.is_some() || request.email.is_some() || request.phone.is_some() @@ -1115,7 +1112,7 @@ impl PaymentCreate { ), order_details, amount_captured: None, - customer_id: None, + customer_id: request.get_customer_id().cloned(), connector_id: None, allowed_payment_method_types, connector_metadata, @@ -1149,10 +1146,10 @@ impl PaymentCreate { state: &SessionState, merchant_account: &domain::MerchantAccount, ) -> Option<ephemeral_key::EphemeralKey> { - match request.customer_id.clone() { + match request.get_customer_id() { Some(customer_id) => helpers::make_ephemeral_key( state.clone(), - customer_id, + customer_id.clone(), merchant_account.merchant_id.clone(), ) .await diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 0bccd409cac..8af5a86d7c3 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -151,7 +151,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa merchant_account, key_store, None, - &payment_intent.customer_id, + payment_intent.customer_id.as_ref(), ) .await?; helpers::validate_amount_to_capture_and_capture_method(Some(&payment_attempt), request)?; @@ -807,7 +807,8 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate BoxedOperation<'b, F, api::PaymentsRequest>, operations::ValidateResult<'a>, )> { - helpers::validate_customer_details_in_request(request)?; + helpers::validate_customer_information(request)?; + if let Some(amount) = request.amount { helpers::validate_max_amount(amount)?; }
fix
save the `customer_id` in payments create (#5262)
ce2485c3c77d86a2bce01d20c410ae11ac08c555
2025-02-05 19:11:41
Sagnik Mitra
feat(connector): [INESPAY] Integrate Sepa Bank Debit (#6755)
false
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index ebb93fd8a11..7556a4e7765 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -6716,6 +6716,7 @@ "gocardless", "gpayments", "helcim", + "inespay", "iatapay", "itaubank", "jpmorgan", @@ -18734,6 +18735,7 @@ "gocardless", "helcim", "iatapay", + "inespay", "itaubank", "jpmorgan", "klarna", diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index bce5ac3c8e8..ea0a95c1d57 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -9298,6 +9298,7 @@ "gocardless", "gpayments", "helcim", + "inespay", "iatapay", "itaubank", "jpmorgan", @@ -23995,6 +23996,7 @@ "gocardless", "helcim", "iatapay", + "inespay", "itaubank", "jpmorgan", "klarna", diff --git a/config/development.toml b/config/development.toml index 2b81123d873..473c453d1c8 100644 --- a/config/development.toml +++ b/config/development.toml @@ -565,6 +565,9 @@ debit = { currency = "USD" } [pm_filters.fiuu] duit_now = { country = "MY", currency = "MYR" } +[pm_filters.inespay] +sepa = { currency = "EUR" } + [tokenization] stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } } checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization" } diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 288520722c3..28dbf33d97d 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -85,7 +85,7 @@ pub enum RoutableConnectors { Gocardless, Helcim, Iatapay, - // Inespay, + Inespay, Itaubank, Jpmorgan, Klarna, @@ -221,7 +221,7 @@ pub enum Connector { Gocardless, Gpayments, Helcim, - // Inespay, + Inespay, Iatapay, Itaubank, Jpmorgan, @@ -370,7 +370,7 @@ impl Connector { | Self::Gpayments | Self::Helcim | Self::Iatapay - // | Self::Inespay + | Self::Inespay | Self::Itaubank | Self::Jpmorgan | Self::Klarna @@ -540,6 +540,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Plaid => Self::Plaid, RoutableConnectors::Zsl => Self::Zsl, RoutableConnectors::Xendit => Self::Xendit, + RoutableConnectors::Inespay => Self::Inespay, } } } diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 791a0679ea3..3175bbde8f2 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -196,7 +196,7 @@ pub struct ConnectorConfig { pub gocardless: Option<ConnectorTomlConfig>, pub gpayments: Option<ConnectorTomlConfig>, pub helcim: Option<ConnectorTomlConfig>, - // pub inespay: Option<ConnectorTomlConfig>, + pub inespay: Option<ConnectorTomlConfig>, pub jpmorgan: Option<ConnectorTomlConfig>, pub klarna: Option<ConnectorTomlConfig>, pub mifinity: Option<ConnectorTomlConfig>, @@ -358,7 +358,7 @@ impl ConnectorConfig { Connector::Gocardless => Ok(connector_data.gocardless), Connector::Gpayments => Ok(connector_data.gpayments), Connector::Helcim => Ok(connector_data.helcim), - // Connector::Inespay => Ok(connector_data.inespay), + Connector::Inespay => Ok(connector_data.inespay), Connector::Jpmorgan => Ok(connector_data.jpmorgan), Connector::Klarna => Ok(connector_data.klarna), Connector::Mifinity => Ok(connector_data.mifinity), diff --git a/crates/hyperswitch_connectors/src/connectors/inespay.rs b/crates/hyperswitch_connectors/src/connectors/inespay.rs index 3d3ea346b78..41ae798ade3 100644 --- a/crates/hyperswitch_connectors/src/connectors/inespay.rs +++ b/crates/hyperswitch_connectors/src/connectors/inespay.rs @@ -1,12 +1,15 @@ pub mod transformers; +use base64::Engine; use common_utils::{ + consts::BASE64_ENGINE, + crypto, errors::CustomResult, - ext_traits::BytesExt, + ext_traits::{ByteSliceExt, BytesExt}, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, }; -use error_stack::{report, ResultExt}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ @@ -36,7 +39,8 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks, }; -use masking::{ExposeInterface, Mask}; +use masking::{ExposeInterface, Mask, Secret}; +use ring::hmac; use transformers as inespay; use crate::{constants::headers, types::ResponseRouterData, utils}; @@ -86,8 +90,8 @@ where 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); + let mut auth_headers = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut auth_headers); Ok(header) } } @@ -98,10 +102,7 @@ impl ConnectorCommon for Inespay { } 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 + api::CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { @@ -118,10 +119,16 @@ impl ConnectorCommon for Inespay { ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = inespay::InespayAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - Ok(vec![( - headers::AUTHORIZATION.to_string(), - auth.api_key.expose().into_masked(), - )]) + Ok(vec![ + ( + headers::AUTHORIZATION.to_string(), + auth.authorization.expose().into_masked(), + ), + ( + headers::X_API_KEY.to_string(), + auth.api_key.expose().into_masked(), + ), + ]) } fn build_error_response( @@ -139,9 +146,9 @@ impl ConnectorCommon for Inespay { Ok(ErrorResponse { status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, + code: response.status, + message: response.status_desc, + reason: None, attempt_status: None, connector_transaction_id: None, }) @@ -176,9 +183,9 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData fn get_url( &self, _req: &PaymentsAuthorizeRouterData, - _connectors: &Connectors, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Ok(format!("{}/payins/single/init", self.base_url(connectors))) } fn get_request_body( @@ -192,9 +199,19 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req.request.currency, )?; - let connector_router_data = inespay::InespayRouterData::from((amount, req)); - let connector_req = inespay::InespayPaymentsRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) + match req.request.currency { + common_enums::Currency::EUR => { + let connector_router_data = inespay::InespayRouterData::from((amount, req)); + let connector_req = + inespay::InespayPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + _ => Err(errors::ConnectorError::CurrencyNotSupported { + message: req.request.currency.to_string(), + connector: "Inespay", + } + .into()), + } } fn build_request( @@ -262,10 +279,20 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Ine fn get_url( &self, - _req: &PaymentsSyncRouterData, - _connectors: &Connectors, + req: &PaymentsSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let connector_payment_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + Ok(format!( + "{}{}{}", + self.base_url(connectors), + "/payins/single/", + connector_payment_id, + )) } fn build_request( @@ -289,7 +316,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Ine event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { - let response: inespay::InespayPaymentsResponse = res + let response: inespay::InespayPSyncResponse = res .response .parse_struct("inespay PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -406,9 +433,9 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Inespay fn get_url( &self, _req: &RefundsRouterData<Execute>, - _connectors: &Connectors, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Ok(format!("{}/refunds/init", self.base_url(connectors))) } fn get_request_body( @@ -452,9 +479,9 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Inespay event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { - let response: inespay::RefundResponse = res + let response: inespay::InespayRefundsResponse = res .response - .parse_struct("inespay RefundResponse") + .parse_struct("inespay InespayRefundsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -489,10 +516,20 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Inespay { fn get_url( &self, - _req: &RefundSyncRouterData, - _connectors: &Connectors, + req: &RefundSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let connector_refund_id = req + .request + .connector_refund_id + .clone() + .ok_or(errors::ConnectorError::MissingConnectorRefundID)?; + Ok(format!( + "{}{}{}", + self.base_url(connectors), + "/refunds/", + connector_refund_id, + )) } fn build_request( @@ -519,7 +556,7 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Inespay { event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { - let response: inespay::RefundResponse = res + let response: inespay::InespayRSyncResponse = res .response .parse_struct("inespay RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -541,27 +578,133 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Inespay { } } +fn get_webhook_body( + body: &[u8], +) -> CustomResult<inespay::InespayWebhookEventData, errors::ConnectorError> { + let notif_item: inespay::InespayWebhookEvent = + serde_urlencoded::from_bytes::<inespay::InespayWebhookEvent>(body) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + let encoded_data_return = notif_item.data_return; + let decoded_data_return = BASE64_ENGINE + .decode(encoded_data_return) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + let data_return: inespay::InespayWebhookEventData = decoded_data_return + .parse_struct("inespay InespayWebhookEventData") + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + Ok(data_return) +} + #[async_trait::async_trait] impl webhooks::IncomingWebhook for Inespay { - fn get_webhook_object_reference_id( + fn get_webhook_source_verification_algorithm( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { + Ok(Box::new(crypto::HmacSha256)) + } + + fn get_webhook_source_verification_signature( + &self, + request: &webhooks::IncomingWebhookRequestDetails<'_>, + _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let notif_item = serde_urlencoded::from_bytes::<inespay::InespayWebhookEvent>(request.body) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + + Ok(notif_item.signature_data_return.as_bytes().to_owned()) + } + + fn get_webhook_source_verification_message( + &self, + request: &webhooks::IncomingWebhookRequestDetails<'_>, + _merchant_id: &common_utils::id_type::MerchantId, + _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let notif_item = serde_urlencoded::from_bytes::<inespay::InespayWebhookEvent>(request.body) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + + Ok(notif_item.data_return.into_bytes()) + } + + async fn verify_webhook_source( + &self, + request: &webhooks::IncomingWebhookRequestDetails<'_>, + merchant_id: &common_utils::id_type::MerchantId, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, + connector_label: &str, + ) -> CustomResult<bool, errors::ConnectorError> { + let connector_webhook_secrets = self + .get_webhook_source_verification_merchant_secret( + merchant_id, + connector_label, + connector_webhook_details, + ) + .await?; + let signature = + self.get_webhook_source_verification_signature(request, &connector_webhook_secrets)?; + + let message = self.get_webhook_source_verification_message( + request, + merchant_id, + &connector_webhook_secrets, + )?; + let secret = connector_webhook_secrets.secret; + + let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &secret); + let signed_message = hmac::sign(&signing_key, &message); + let computed_signature = hex::encode(signed_message.as_ref()); + let payload_sign = BASE64_ENGINE.encode(computed_signature); + Ok(payload_sign.as_bytes().eq(&signature)) + } + + fn get_webhook_object_reference_id( + &self, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let data_return = get_webhook_body(request.body) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + match data_return { + inespay::InespayWebhookEventData::Payment(data) => { + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId( + data.single_payin_id, + ), + )) + } + inespay::InespayWebhookEventData::Refund(data) => { + Ok(api_models::webhooks::ObjectReferenceId::RefundId( + api_models::webhooks::RefundIdType::ConnectorRefundId(data.refund_id), + )) + } + } } fn get_webhook_event_type( &self, - _request: &webhooks::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let data_return = get_webhook_body(request.body) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + Ok(api_models::webhooks::IncomingWebhookEvent::from( + data_return, + )) } fn get_webhook_resource_object( &self, - _request: &webhooks::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let data_return = get_webhook_body(request.body) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + Ok(match data_return { + inespay::InespayWebhookEventData::Payment(payment_webhook_data) => { + Box::new(payment_webhook_data) + } + inespay::InespayWebhookEventData::Refund(refund_webhook_data) => { + Box::new(refund_webhook_data) + } + }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs index 296d76546c8..2739aa66bee 100644 --- a/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs @@ -1,31 +1,33 @@ use common_enums::enums; -use common_utils::types::StringMinorUnit; +use common_utils::{ + request::Method, + types::{MinorUnit, StringMinorUnit, StringMinorUnitForConnector}, +}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ - payment_method_data::PaymentMethodData, - router_data::{ConnectorAuthType, RouterData}, + payment_method_data::{BankDebitData, PaymentMethodData}, + router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; +use url::Url; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, - utils::PaymentsAuthorizeRequestData, + utils::{self, PaymentsAuthorizeRequestData, RouterData as _}, }; - -//TODO: Fill the struct with respective fields pub struct InespayRouterData<T> { - pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub amount: StringMinorUnit, pub router_data: T, } impl<T> From<(StringMinorUnit, T)> for InespayRouterData<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, @@ -33,20 +35,15 @@ impl<T> From<(StringMinorUnit, T)> for InespayRouterData<T> { } } -//TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] pub struct InespayPaymentsRequest { + description: String, amount: StringMinorUnit, - card: InespayCard, -} - -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct InespayCard { - number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, + reference: String, + debtor_account: Option<Secret<String>>, + success_link_redirect: Option<String>, + notif_url: Option<String>, } impl TryFrom<&InespayRouterData<&PaymentsAuthorizeRouterData>> for InespayPaymentsRequest { @@ -55,17 +52,17 @@ impl TryFrom<&InespayRouterData<&PaymentsAuthorizeRouterData>> for InespayPaymen item: &InespayRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(req_card) => { - let card = InespayCard { - 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()?, - }; + PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => { + let order_id = item.router_data.connector_request_reference_id.clone(); + let webhook_url = item.router_data.request.get_webhook_url()?; + let return_url = item.router_data.request.get_router_return_url()?; Ok(Self { + description: item.router_data.get_description()?, amount: item.amount.clone(), - card, + reference: order_id, + debtor_account: Some(iban), + success_link_redirect: Some(return_url), + notif_url: Some(webhook_url), }) } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), @@ -73,156 +70,422 @@ impl TryFrom<&InespayRouterData<&PaymentsAuthorizeRouterData>> for InespayPaymen } } -//TODO: Fill the struct with respective fields -// Auth Struct pub struct InespayAuthType { pub(super) api_key: Secret<String>, + pub authorization: Secret<String>, } impl TryFrom<&ConnectorAuthType> for InespayAuthType { 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 { + ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { api_key: api_key.to_owned(), + authorization: key1.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 InespayPaymentStatus { - Succeeded, + +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct InespayPaymentsResponseData { + status: String, + status_desc: String, + single_payin_id: String, + single_payin_link: String, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum InespayPaymentsResponse { + InespayPaymentsData(InespayPaymentsResponseData), + InespayPaymentsError(InespayErrorResponse), +} + +impl<F, T> TryFrom<ResponseRouterData<F, InespayPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, InespayPaymentsResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let (status, response) = match item.response { + InespayPaymentsResponse::InespayPaymentsData(data) => { + let redirection_url = Url::parse(data.single_payin_link.as_str()) + .change_context(errors::ConnectorError::ParsingFailed)?; + let redirection_data = RedirectForm::from((redirection_url, Method::Get)); + + ( + common_enums::AttemptStatus::AuthenticationPending, + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + data.single_payin_id.clone(), + ), + redirection_data: Box::new(Some(redirection_data)), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charge_id: None, + }), + ) + } + InespayPaymentsResponse::InespayPaymentsError(data) => ( + common_enums::AttemptStatus::Failure, + Err(ErrorResponse { + code: data.status.clone(), + message: data.status_desc.clone(), + reason: Some(data.status_desc.clone()), + attempt_status: None, + connector_transaction_id: None, + status_code: item.http_code, + }), + ), + }; + Ok(Self { + status, + response, + ..item.data + }) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum InespayPSyncStatus { + Ok, + Created, + Opened, + BankSelected, + Initiated, + Pending, + Aborted, + Unfinished, + Rejected, + Cancelled, + PartiallyAccepted, Failed, - #[default] - Processing, + Settled, + PartRefunded, + Refunded, } -impl From<InespayPaymentStatus> for common_enums::AttemptStatus { - fn from(item: InespayPaymentStatus) -> Self { +impl From<InespayPSyncStatus> for common_enums::AttemptStatus { + fn from(item: InespayPSyncStatus) -> Self { match item { - InespayPaymentStatus::Succeeded => Self::Charged, - InespayPaymentStatus::Failed => Self::Failure, - InespayPaymentStatus::Processing => Self::Authorizing, + InespayPSyncStatus::Ok | InespayPSyncStatus::Settled => Self::Charged, + InespayPSyncStatus::Created + | InespayPSyncStatus::Opened + | InespayPSyncStatus::BankSelected + | InespayPSyncStatus::Initiated + | InespayPSyncStatus::Pending + | InespayPSyncStatus::Unfinished + | InespayPSyncStatus::PartiallyAccepted => Self::AuthenticationPending, + InespayPSyncStatus::Aborted + | InespayPSyncStatus::Rejected + | InespayPSyncStatus::Cancelled + | InespayPSyncStatus::Failed => Self::Failure, + InespayPSyncStatus::PartRefunded | InespayPSyncStatus::Refunded => Self::AutoRefunded, } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct InespayPaymentsResponse { - status: InespayPaymentStatus, - id: String, +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct InespayPSyncResponseData { + cod_status: InespayPSyncStatus, + status_desc: String, + single_payin_id: String, + single_payin_link: String, } -impl<F, T> TryFrom<ResponseRouterData<F, InespayPaymentsResponse, T, PaymentsResponseData>> +#[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum InespayPSyncResponse { + InespayPSyncData(InespayPSyncResponseData), + InespayPSyncWebhook(InespayPaymentWebhookData), + InespayPSyncError(InespayErrorResponse), +} + +impl<F, T> TryFrom<ResponseRouterData<F, InespayPSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: ResponseRouterData<F, InespayPaymentsResponse, T, PaymentsResponseData>, + item: ResponseRouterData<F, InespayPSyncResponse, 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, + match item.response { + InespayPSyncResponse::InespayPSyncData(data) => { + let redirection_url = Url::parse(data.single_payin_link.as_str()) + .change_context(errors::ConnectorError::ParsingFailed)?; + let redirection_data = RedirectForm::from((redirection_url, Method::Get)); + + Ok(Self { + status: common_enums::AttemptStatus::from(data.cod_status), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + data.single_payin_id.clone(), + ), + redirection_data: Box::new(Some(redirection_data)), + 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 + }) + } + InespayPSyncResponse::InespayPSyncWebhook(data) => { + let status = enums::AttemptStatus::from(data.cod_status); + Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + data.single_payin_id.clone(), + ), + 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 + }) + } + InespayPSyncResponse::InespayPSyncError(data) => Ok(Self { + response: Err(ErrorResponse { + code: data.status.clone(), + message: data.status_desc.clone(), + reason: Some(data.status_desc.clone()), + attempt_status: None, + connector_transaction_id: None, + status_code: item.http_code, + }), + ..item.data }), - ..item.data - }) + } } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] pub struct InespayRefundRequest { - pub amount: StringMinorUnit, + single_payin_id: String, + amount: Option<MinorUnit>, } impl<F> TryFrom<&InespayRouterData<&RefundsRouterData<F>>> for InespayRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &InespayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + let amount = utils::convert_back_amount_to_minor_units( + &StringMinorUnitForConnector, + item.amount.to_owned(), + item.router_data.request.currency, + )?; Ok(Self { - amount: item.amount.to_owned(), + single_payin_id: item.router_data.request.connector_transaction_id.clone(), + amount: Some(amount), }) } } -// Type definition for Refund Response - -#[allow(dead_code)] -#[derive(Debug, Serialize, Default, Deserialize, Clone)] -pub enum RefundStatus { - Succeeded, - Failed, +#[derive(Debug, Serialize, Default, Deserialize, Clone, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum InespayRSyncStatus { + Confirmed, #[default] - Processing, + Pending, + Rejected, + Denied, + Reversed, + Mistake, } -impl From<RefundStatus> for enums::RefundStatus { - fn from(item: RefundStatus) -> Self { +impl From<InespayRSyncStatus> for enums::RefundStatus { + fn from(item: InespayRSyncStatus) -> Self { match item { - RefundStatus::Succeeded => Self::Success, - RefundStatus::Failed => Self::Failure, - RefundStatus::Processing => Self::Pending, - //TODO: Review mapping + InespayRSyncStatus::Confirmed => Self::Success, + InespayRSyncStatus::Pending => Self::Pending, + InespayRSyncStatus::Rejected + | InespayRSyncStatus::Denied + | InespayRSyncStatus::Reversed + | InespayRSyncStatus::Mistake => Self::Failure, } } } -//TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] -pub struct RefundResponse { - id: String, - status: RefundStatus, +#[serde(rename_all = "camelCase")] +pub struct RefundsData { + status: String, + status_desc: String, + refund_id: String, } -impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { +#[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum InespayRefundsResponse { + InespayRefundsData(RefundsData), + InespayRefundsError(InespayErrorResponse), +} + +impl TryFrom<RefundsResponseRouterData<Execute, InespayRefundsResponse>> + for RefundsRouterData<Execute> +{ type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: RefundsResponseRouterData<Execute, RefundResponse>, + item: RefundsResponseRouterData<Execute, InespayRefundsResponse>, ) -> 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), + match item.response { + InespayRefundsResponse::InespayRefundsData(data) => Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: data.refund_id, + refund_status: enums::RefundStatus::Pending, + }), + ..item.data }), - ..item.data - }) + InespayRefundsResponse::InespayRefundsError(data) => Ok(Self { + response: Err(ErrorResponse { + code: data.status.clone(), + message: data.status_desc.clone(), + reason: Some(data.status_desc.clone()), + attempt_status: None, + connector_transaction_id: None, + status_code: item.http_code, + }), + ..item.data + }), + } } } -impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct InespayRSyncResponseData { + cod_status: InespayRSyncStatus, + status_desc: String, + refund_id: String, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum InespayRSyncResponse { + InespayRSyncData(InespayRSyncResponseData), + InespayRSyncWebhook(InespayRefundWebhookData), + InespayRSyncError(InespayErrorResponse), +} + +impl TryFrom<RefundsResponseRouterData<RSync, InespayRSyncResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: RefundsResponseRouterData<RSync, RefundResponse>, + item: RefundsResponseRouterData<RSync, InespayRSyncResponse>, ) -> 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), + let response = match item.response { + InespayRSyncResponse::InespayRSyncData(data) => Ok(RefundsResponseData { + connector_refund_id: data.refund_id, + refund_status: enums::RefundStatus::from(data.cod_status), + }), + InespayRSyncResponse::InespayRSyncWebhook(data) => Ok(RefundsResponseData { + connector_refund_id: data.refund_id, + refund_status: enums::RefundStatus::from(data.cod_status), + }), + InespayRSyncResponse::InespayRSyncError(data) => Err(ErrorResponse { + code: data.status.clone(), + message: data.status_desc.clone(), + reason: Some(data.status_desc.clone()), + attempt_status: None, + connector_transaction_id: None, + status_code: item.http_code, }), + }; + Ok(Self { + response, ..item.data }) } } -//TODO: Fill the struct with respective fields +#[derive(Serialize, Deserialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct InespayPaymentWebhookData { + pub single_payin_id: String, + pub cod_status: InespayPSyncStatus, + pub description: String, + pub amount: MinorUnit, + pub reference: String, + pub creditor_account: Secret<String>, + pub debtor_name: Secret<String>, + pub debtor_account: Secret<String>, + pub custom_data: Option<String>, +} + +#[derive(Serialize, Deserialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct InespayRefundWebhookData { + pub refund_id: String, + pub simple_payin_id: String, + pub cod_status: InespayRSyncStatus, + pub description: String, + pub amount: MinorUnit, + pub reference: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(untagged)] +pub enum InespayWebhookEventData { + Payment(InespayPaymentWebhookData), + Refund(InespayRefundWebhookData), +} + +#[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct InespayWebhookEvent { + pub data_return: String, + pub signature_data_return: String, +} + #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] pub struct InespayErrorResponse { - pub status_code: u16, - pub code: String, - pub message: String, - pub reason: Option<String>, + pub status: String, + pub status_desc: String, +} + +impl From<InespayWebhookEventData> for api_models::webhooks::IncomingWebhookEvent { + fn from(item: InespayWebhookEventData) -> Self { + match item { + InespayWebhookEventData::Payment(payment_data) => match payment_data.cod_status { + InespayPSyncStatus::Ok | InespayPSyncStatus::Settled => Self::PaymentIntentSuccess, + InespayPSyncStatus::Failed | InespayPSyncStatus::Rejected => { + Self::PaymentIntentFailure + } + InespayPSyncStatus::Created + | InespayPSyncStatus::Opened + | InespayPSyncStatus::BankSelected + | InespayPSyncStatus::Initiated + | InespayPSyncStatus::Pending + | InespayPSyncStatus::Unfinished + | InespayPSyncStatus::PartiallyAccepted => Self::PaymentIntentProcessing, + InespayPSyncStatus::Aborted + | InespayPSyncStatus::Cancelled + | InespayPSyncStatus::PartRefunded + | InespayPSyncStatus::Refunded => Self::EventNotSupported, + }, + InespayWebhookEventData::Refund(refund_data) => match refund_data.cod_status { + InespayRSyncStatus::Confirmed => Self::RefundSuccess, + InespayRSyncStatus::Rejected + | InespayRSyncStatus::Denied + | InespayRSyncStatus::Reversed + | InespayRSyncStatus::Mistake => Self::RefundFailure, + InespayRSyncStatus::Pending => Self::EventNotSupported, + }, + } + } } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 3ec9d76397b..7b4cbb282df 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1395,10 +1395,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { iatapay::transformers::IatapayAuthType::try_from(self.auth_type)?; Ok(()) } - // api_enums::Connector::Inespay => { - // inespay::transformers::InespayAuthType::try_from(self.auth_type)?; - // Ok(()) - // } + api_enums::Connector::Inespay => { + inespay::transformers::InespayAuthType::try_from(self.auth_type)?; + Ok(()) + } api_enums::Connector::Itaubank => { itaubank::transformers::ItaubankAuthType::try_from(self.auth_type)?; Ok(()) diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 114a877d26f..4dc5da6475f 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -442,9 +442,9 @@ impl ConnectorData { enums::Connector::Iatapay => { Ok(ConnectorEnum::Old(Box::new(connector::Iatapay::new()))) } - // enums::Connector::Inespay => { - // Ok(ConnectorEnum::Old(Box::new(connector::Inespay::new()))) - // } + enums::Connector::Inespay => { + Ok(ConnectorEnum::Old(Box::new(connector::Inespay::new()))) + } enums::Connector::Itaubank => { Ok(ConnectorEnum::Old(Box::new(connector::Itaubank::new()))) } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index c1d9b35be82..2a287a337c9 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -255,7 +255,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { } api_enums::Connector::Helcim => Self::Helcim, api_enums::Connector::Iatapay => Self::Iatapay, - // api_enums::Connector::Inespay => Self::Inespay, + api_enums::Connector::Inespay => Self::Inespay, api_enums::Connector::Itaubank => Self::Itaubank, api_enums::Connector::Jpmorgan => Self::Jpmorgan, api_enums::Connector::Klarna => Self::Klarna,
feat
[INESPAY] Integrate Sepa Bank Debit (#6755)
35ddf94766bf86cc3284c7e3a3eedb95e0641bb3
2023-01-20 00:45:33
chikke srujan
chore: update sandbox base url (#430)
false
diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index fa094a85bb3..8ef5f409489 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -25,7 +25,7 @@ Use the following base URLs when making requests to the APIs: | Environment | Base URL | |---------------|------------------------------------------------------| -| Sandbox | <https://sandbox-router.juspay.io> | +| Sandbox | <https://sandbox.hyperswitch.io> | | Production | <https://router.juspay.io> | ## Authentication @@ -39,7 +39,7 @@ Never share your secret api keys. Keep them guarded and secure. "#, ), servers( - (url = "https://sandbox-router.juspay.io", description = "Sandbox Environment"), + (url = "https://sandbox.hyperswitch.io", description = "Sandbox Environment"), (url = "https://router.juspay.io", description = "Production Environment") ), paths( diff --git a/openapi/generated.json b/openapi/generated.json index 8cd43594414..56b77eea880 100644 --- a/openapi/generated.json +++ b/openapi/generated.json @@ -2,7 +2,7 @@ "openapi": "3.0.3", "info": { "title": "Juspay Router - API Documentation", - "description": "\n## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments.\nOur APIs accept and return JSON in the HTTP body, and return standard HTTP response codes.\n\nYou can consume the APIs directly using your favorite HTTP/REST library.\n\nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without\naffecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n|---------------|------------------------------------------------------|\n| Sandbox | <https://sandbox-router.juspay.io> |\n| Production | <https://router.juspay.io> |\n\n## Authentication\n\nWhen you sign up on our [dashboard](https://dashboard-hyperswitch.netlify.app) and create a merchant\naccount, you are given a secret key (also referred as api-key).\nYou may authenticate all API requests with Juspay server by providing the appropriate key in the\nrequest Authorization header.\n\nNever share your secret api keys. Keep them guarded and secure.\n", + "description": "\n## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments.\nOur APIs accept and return JSON in the HTTP body, and return standard HTTP response codes.\n\nYou can consume the APIs directly using your favorite HTTP/REST library.\n\nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without\naffecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n|---------------|------------------------------------------------------|\n| Sandbox | <https://sandbox.hyperswitch.io> |\n| Production | <https://router.juspay.io> |\n\n## Authentication\n\nWhen you sign up on our [dashboard](https://dashboard-hyperswitch.netlify.app) and create a merchant\naccount, you are given a secret key (also referred as api-key).\nYou may authenticate all API requests with Juspay server by providing the appropriate key in the\nrequest Authorization header.\n\nNever share your secret api keys. Keep them guarded and secure.\n", "contact": { "name": "Juspay Support", "url": "https://juspay.io", @@ -15,7 +15,7 @@ }, "servers": [ { - "url": "https://sandbox-router.juspay.io", + "url": "https://sandbox.hyperswitch.io", "description": "Sandbox Environment" }, { diff --git a/openapi/open_api_spec.yaml b/openapi/open_api_spec.yaml index 0bc2c1bf437..84e31e02857 100644 --- a/openapi/open_api_spec.yaml +++ b/openapi/open_api_spec.yaml @@ -25,7 +25,7 @@ info: | Environment | Base URL | |---------------|------------------------------------------------------| - | Sandbox | <https://sandbox-router.juspay.io> | + | Sandbox | <https://sandbox.hyperswitch.io> | | Production | <https://router.juspay.io> | # Authentication @@ -35,7 +35,7 @@ info: Never share your secret api keys. Keep them guarded and secure. servers: - - url: https://sandbox-router.juspay.io + - url: https://sandbox.hyperswitch.io description: Sandbox Environment - url: https://router.juspay.io description: Production Environment diff --git a/postman/collection.postman.json b/postman/collection.postman.json index 7e8f391063e..2c5c2f1fd8c 100644 --- a/postman/collection.postman.json +++ b/postman/collection.postman.json @@ -8342,7 +8342,7 @@ "variable": [ { "type": "string", - "value": "https://sandbox-router.juspay.io", + "value": "https://sandbox.hyperswitch.io", "key": "baseUrl" } ], @@ -8351,7 +8351,7 @@ "name": "Juspay Router - API Documentation", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", "description": { - "content": "## Get started\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes</a>.\nYou can consume the APIs directly using your favorite HTTP/REST library.\nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n### Base URLs\nUse the following base URLs when making requests to the APIs:\n\n | Environment | Base URL |\n |---------------|------------------------------------------------------|\n | Sandbox | <https://sandbox-router.juspay.io> |\n | Production | <https://router.juspay.io> |\n\n# Authentication\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header.\nNever share your secret api keys. Keep them guarded and secure.\n\n\nContact Support:\n Name: Juspay Support\n Email: [email protected]", + "content": "## Get started\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes</a>.\nYou can consume the APIs directly using your favorite HTTP/REST library.\nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n### Base URLs\nUse the following base URLs when making requests to the APIs:\n\n | Environment | Base URL |\n |---------------|------------------------------------------------------|\n | Sandbox | <https://sandbox.hyperswitch.io> |\n | Production | <https://router.juspay.io> |\n\n# Authentication\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header.\nNever share your secret api keys. Keep them guarded and secure.\n\n\nContact Support:\n Name: Juspay Support\n Email: [email protected]", "type": "text/plain" } }
chore
update sandbox base url (#430)
e458e4907e39961f386900f21382c9ace3b7c392
2024-04-19 12:19:35
AkshayaFoiger
feat(router): [BOA/CYBS] add avs_response and cvv validation result in the response (#4376)
false
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 5eca31278a8..3ea736486ef 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -378,6 +378,12 @@ impl<F, T> let error_response = get_error_response_if_failure((&info_response, mandate_status, item.http_code)); + let connector_response = info_response + .processor_information + .as_ref() + .map(types::AdditionalPaymentMethodConnectorResponse::from) + .map(types::ConnectorResponseData::with_additional_payment_method_data); + Ok(Self { status: mandate_status, response: match error_response { @@ -400,6 +406,7 @@ impl<F, T> incremental_authorization_allowed: None, }), }, + connector_response, ..item.data }) } @@ -714,7 +721,16 @@ pub struct ClientReferenceInformation { #[serde(rename_all = "camelCase")] pub struct ClientProcessorInformation { avs: Option<Avs>, + card_verification: Option<CardVerification>, } + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CardVerification { + result_code: Option<String>, + result_code_raw: Option<String>, +} + #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientRiskInformation { @@ -1383,23 +1399,20 @@ fn get_payment_response( }); Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()), - redirection_data: None, - mandate_reference, - connector_metadata: info_response - .processor_information - .as_ref() - .map(|processor_information| serde_json::json!({"avs_response": processor_information.avs})), - network_txn_id: None, - connector_response_reference_id: Some( - info_response - .client_reference_information - .code - .clone() - .unwrap_or(info_response.id.clone()), - ), - incremental_authorization_allowed: None, - }) + resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()), + redirection_data: None, + mandate_reference, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some( + info_response + .client_reference_information + .code + .clone() + .unwrap_or(info_response.id.clone()), + ), + incremental_authorization_allowed: None, + }) } } } @@ -1849,9 +1862,15 @@ impl<F> || is_setup_mandate_payment(&item.data.request), )); let response = get_payment_response((&info_response, status, item.http_code)); + let connector_response = info_response + .processor_information + .as_ref() + .map(types::AdditionalPaymentMethodConnectorResponse::from) + .map(types::ConnectorResponseData::with_additional_payment_method_data); Ok(Self { status, response, + connector_response, ..item.data }) } @@ -1892,9 +1911,16 @@ impl<F> item.data.request.is_auto_capture()?, )); let response = get_payment_response((&info_response, status, item.http_code)); + let connector_response = info_response + .processor_information + .as_ref() + .map(types::AdditionalPaymentMethodConnectorResponse::from) + .map(types::ConnectorResponseData::with_additional_payment_method_data); + Ok(Self { status, response, + connector_response, ..item.data }) } @@ -1909,6 +1935,19 @@ impl<F> } } +impl From<&ClientProcessorInformation> for types::AdditionalPaymentMethodConnectorResponse { + fn from(processor_information: &ClientProcessorInformation) -> Self { + let payment_checks = Some( + serde_json::json!({"avs_response": processor_information.avs, "card_verification": processor_information.card_verification}), + ); + + Self::Card { + authentication_data: None, + payment_checks, + } + } +} + impl<F> TryFrom< types::ResponseRouterData< diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 338048b8783..a3756770aeb 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1630,6 +1630,14 @@ pub struct ClientReferenceInformation { pub struct ClientProcessorInformation { network_transaction_id: Option<String>, avs: Option<Avs>, + card_verification: Option<CardVerification>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CardVerification { + result_code: Option<String>, + result_code_raw: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -1753,15 +1761,15 @@ fn get_payment_response( .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, }); + Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()), redirection_data: None, mandate_reference, - connector_metadata: info_response - .processor_information - .as_ref() - .map(|processor_information| serde_json::json!({"avs_response": processor_information.avs})), - network_txn_id: info_response.processor_information.as_ref().and_then(|processor_information| processor_information.network_transaction_id.clone()), + connector_metadata: None, + network_txn_id: info_response.processor_information.as_ref().and_then( + |processor_information| processor_information.network_transaction_id.clone(), + ), connector_response_reference_id: Some( info_response .client_reference_information @@ -1801,9 +1809,16 @@ impl<F> item.data.request.is_auto_capture()?, )); let response = get_payment_response((&info_response, status, item.http_code)); + let connector_response = info_response + .processor_information + .as_ref() + .map(types::AdditionalPaymentMethodConnectorResponse::from) + .map(types::ConnectorResponseData::with_additional_payment_method_data); + Ok(Self { status, response, + connector_response, ..item.data }) } @@ -2286,9 +2301,16 @@ impl<F> item.data.request.is_auto_capture()?, )); let response = get_payment_response((&info_response, status, item.http_code)); + let connector_response = info_response + .processor_information + .as_ref() + .map(types::AdditionalPaymentMethodConnectorResponse::from) + .map(types::ConnectorResponseData::with_additional_payment_method_data); + Ok(Self { status, response, + connector_response, ..item.data }) } @@ -2301,6 +2323,19 @@ impl<F> } } +impl From<&ClientProcessorInformation> for types::AdditionalPaymentMethodConnectorResponse { + fn from(processor_information: &ClientProcessorInformation) -> Self { + let payment_checks = Some( + serde_json::json!({"avs_response": processor_information.avs, "card_verification": processor_information.card_verification}), + ); + + Self::Card { + authentication_data: None, + payment_checks, + } + } +} + impl<F> TryFrom< types::ResponseRouterData< @@ -2414,6 +2449,12 @@ impl<F, T> let error_response = get_error_response_if_failure((&info_response, mandate_status, item.http_code)); + let connector_response = info_response + .processor_information + .as_ref() + .map(types::AdditionalPaymentMethodConnectorResponse::from) + .map(types::ConnectorResponseData::with_additional_payment_method_data); + Ok(Self { status: mandate_status, response: match error_response { @@ -2442,6 +2483,7 @@ impl<F, T> ), }), }, + connector_response, ..item.data }) }
feat
[BOA/CYBS] add avs_response and cvv validation result in the response (#4376)
245e489d13209da19d6e9af01219056eec04e897
2023-11-21 21:51:39
github-actions
test(postman): update postman collection files
false
diff --git a/postman/collection-json/stripe.postman_collection.json b/postman/collection-json/stripe.postman_collection.json index 06ccae91b2c..9c9a8a5d685 100644 --- a/postman/collection-json/stripe.postman_collection.json +++ b/postman/collection-json/stripe.postman_collection.json @@ -8504,7 +8504,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1,\"customer_id\":\"bernard123\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000009995\",\"card_exp_month\":\"01\",\"card_exp_year\":\"24\",\"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\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000009995\",\"card_exp_month\":\"01\",\"card_exp_year\":\"24\",\"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\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -8784,7 +8784,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1,\"customer_id\":\"bernard123\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"24\",\"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\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"24\",\"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\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -9436,7 +9436,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1,\"customer_id\":\"bernard123\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"24\",\"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\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"24\",\"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\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -13998,7 +13998,7 @@ "language": "json" } }, - "raw": "{\"amount\":6570,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":6570,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6570,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments",
test
update postman collection files
15106233e973fb7539799b96975a1004c2925663
2023-08-29 16:12:19
anji-reddy-j
refactor(recon): updating user flow for recon (#2029)
false
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 2e38fe7fbd6..2c78705f57f 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -9,6 +9,7 @@ use utoipa::ToSchema; use super::payments::AddressDetails; use crate::{ + enums, enums::{self as api_enums}, payment_methods, }; @@ -272,6 +273,10 @@ pub struct MerchantAccountResponse { /// The default business profile that must be used for creating merchant accounts and payments #[schema(max_length = 64)] pub default_profile: Option<String>, + + /// A enum value to indicate the status of recon service. By default it is not_requested. + #[schema(value_type = ReconStatus, example = "not_requested")] + pub recon_status: enums::ReconStatus, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 469ba6ee3b4..e0a2f24abb6 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1682,3 +1682,28 @@ pub enum CancelTransaction { #[default] FrmCancelTransaction, } + +#[derive( + Clone, + Debug, + Eq, + Default, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + utoipa::ToSchema, + Copy, +)] +#[router_derive::diesel_enum(storage_type = "pg_enum")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum ReconStatus { + #[default] + NotRequested, + Requested, + Active, + Disabled, +} diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index 54d98bc4e08..2ab72bc7bb4 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -12,7 +12,7 @@ pub mod diesel_exports { DbMerchantStorageScheme as MerchantStorageScheme, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPayoutStatus as PayoutStatus, DbPayoutType as PayoutType, DbProcessTrackerStatus as ProcessTrackerStatus, - DbRefundStatus as RefundStatus, DbRefundType as RefundType, + DbReconStatus as ReconStatus, DbRefundStatus as RefundStatus, DbRefundType as RefundType, }; } pub use common_enums::*; diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rs index 3f3c12e9aa8..2b63d4bf9b2 100644 --- a/crates/diesel_models/src/merchant_account.rs +++ b/crates/diesel_models/src/merchant_account.rs @@ -39,6 +39,7 @@ pub struct MerchantAccount { pub organization_id: Option<String>, pub is_recon_enabled: bool, pub default_profile: Option<String>, + pub recon_status: storage_enums::ReconStatus, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] @@ -67,6 +68,7 @@ pub struct MerchantAccountNew { pub organization_id: Option<String>, pub is_recon_enabled: bool, pub default_profile: Option<String>, + pub recon_status: storage_enums::ReconStatus, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] @@ -94,4 +96,5 @@ pub struct MerchantAccountUpdateInternal { pub organization_id: Option<String>, pub is_recon_enabled: bool, pub default_profile: Option<Option<String>>, + pub recon_status: storage_enums::ReconStatus, } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 87cec699883..e85a9be0735 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -432,6 +432,7 @@ diesel::table! { is_recon_enabled -> Bool, #[max_length = 64] default_profile -> Nullable<Varchar>, + recon_status -> ReconStatus, } } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 406a4eb7550..22ac930f404 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -166,6 +166,7 @@ pub async fn create_merchant_account( organization_id: req.organization_id, is_recon_enabled: false, default_profile: None, + recon_status: diesel_models::enums::ReconStatus::NotRequested, }) } .await diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index 32e3ca14d74..248dcd74a10 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -165,6 +165,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::RetryAction, api_models::enums::AttemptStatus, api_models::enums::CaptureStatus, + api_models::enums::ReconStatus, api_models::admin::MerchantConnectorCreate, api_models::admin::MerchantConnectorUpdate, api_models::admin::PrimaryBusinessDetails, diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 52d774464a0..6a73c39bb22 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -45,6 +45,7 @@ impl TryFrom<domain::MerchantAccount> for MerchantAccountResponse { organization_id: item.organization_id, is_recon_enabled: item.is_recon_enabled, default_profile: item.default_profile, + recon_status: item.recon_status, }) } } diff --git a/crates/router/src/types/domain/merchant_account.rs b/crates/router/src/types/domain/merchant_account.rs index f75955c3326..a5620724ac7 100644 --- a/crates/router/src/types/domain/merchant_account.rs +++ b/crates/router/src/types/domain/merchant_account.rs @@ -43,6 +43,7 @@ pub struct MerchantAccount { pub organization_id: Option<String>, pub is_recon_enabled: bool, pub default_profile: Option<String>, + pub recon_status: diesel_models::enums::ReconStatus, } #[allow(clippy::large_enum_variant)] @@ -72,7 +73,7 @@ pub enum MerchantAccountUpdate { storage_scheme: MerchantStorageScheme, }, ReconUpdate { - is_recon_enabled: bool, + recon_status: diesel_models::enums::ReconStatus, }, } @@ -125,8 +126,8 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { modified_at: Some(date_time::now()), ..Default::default() }, - MerchantAccountUpdate::ReconUpdate { is_recon_enabled } => Self { - is_recon_enabled, + MerchantAccountUpdate::ReconUpdate { recon_status } => Self { + recon_status, ..Default::default() }, } @@ -166,6 +167,7 @@ impl super::behaviour::Conversion for MerchantAccount { organization_id: self.organization_id, is_recon_enabled: self.is_recon_enabled, default_profile: self.default_profile, + recon_status: self.recon_status, }) } @@ -209,6 +211,7 @@ impl super::behaviour::Conversion for MerchantAccount { organization_id: item.organization_id, is_recon_enabled: item.is_recon_enabled, default_profile: item.default_profile, + recon_status: item.recon_status, }) } .await @@ -243,6 +246,7 @@ impl super::behaviour::Conversion for MerchantAccount { organization_id: self.organization_id, is_recon_enabled: self.is_recon_enabled, default_profile: self.default_profile, + recon_status: self.recon_status, }) } } diff --git a/migrations/2023-08-25-094551_add_recon_status_in_merchant_account/down.sql b/migrations/2023-08-25-094551_add_recon_status_in_merchant_account/down.sql new file mode 100644 index 00000000000..355b7d53323 --- /dev/null +++ b/migrations/2023-08-25-094551_add_recon_status_in_merchant_account/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE merchant_account DROP COLUMN recon_status; +DROP TYPE "ReconStatus"; \ No newline at end of file diff --git a/migrations/2023-08-25-094551_add_recon_status_in_merchant_account/up.sql b/migrations/2023-08-25-094551_add_recon_status_in_merchant_account/up.sql new file mode 100644 index 00000000000..adbf787700f --- /dev/null +++ b/migrations/2023-08-25-094551_add_recon_status_in_merchant_account/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +CREATE TYPE "ReconStatus" AS ENUM ('requested','active', 'disabled','not_requested'); +ALTER TABLE merchant_account ADD recon_status "ReconStatus" NOT NULL DEFAULT "ReconStatus"('not_requested'); \ No newline at end of file diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 0dd862cbe35..85a2ad1dbda 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -6093,7 +6093,8 @@ "enable_payment_response_hash", "redirect_to_merchant_with_http_post", "primary_business_details", - "is_recon_enabled" + "is_recon_enabled", + "recon_status" ], "properties": { "merchant_id": { @@ -6232,6 +6233,9 @@ "description": "The default business profile that must be used for creating merchant accounts and payments", "nullable": true, "maxLength": 64 + }, + "recon_status": { + "$ref": "#/components/schemas/ReconStatus" } } }, @@ -10066,6 +10070,15 @@ } } }, + "ReconStatus": { + "type": "string", + "enum": [ + "not_requested", + "requested", + "active", + "disabled" + ] + }, "RedirectResponse": { "type": "object", "properties": {
refactor
updating user flow for recon (#2029)
5ed3f34c24c82d182921d317361bc9fc72be58ce
2023-08-04 01:45:38
AkshayaFoiger
feat(connector): [Adyen] implement Oxxo (#1808)
false
diff --git a/config/config.example.toml b/config/config.example.toml index 7f3177d0aa7..48874643029 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -343,6 +343,7 @@ danamon_va = {country = "ID", currency = "IDR"} mandiri_va = {country = "ID", currency = "IDR"} alfamart = {country = "ID", currency = "IDR"} indomaret = {country = "ID", currency = "IDR"} +oxxo = {country = "MX", currency = "MXN"} pay_safe_card = {country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,UAE,UK,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,ISK,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU"} [pm_filters.zen] diff --git a/config/development.toml b/config/development.toml index 0f556650131..fa05727e0f2 100644 --- a/config/development.toml +++ b/config/development.toml @@ -281,6 +281,7 @@ danamon_va = {country = "ID", currency = "IDR"} mandiri_va = {country = "ID", currency = "IDR"} alfamart = {country = "ID", currency = "IDR"} indomaret = {country = "ID", currency = "IDR"} +oxxo = {country = "MX", currency = "MXN"} pay_safe_card = {country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,UAE,UK,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,ISK,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU"} [pm_filters.braintree] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 9e6dc440aa7..7e0d4df6dff 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -226,6 +226,7 @@ danamon_va = {country = "ID", currency = "IDR"} mandiri_va = {country = "ID", currency = "IDR"} alfamart = {country = "ID", currency = "IDR"} indomaret = {country = "ID", currency = "IDR"} +oxxo = {country = "MX", currency = "MXN"} pay_safe_card = {country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,UAE,UK,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,ISK,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU"} [pm_filters.zen] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index cf7006a740f..a8659809a45 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1292,6 +1292,7 @@ pub enum VoucherData { RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), + Oxxo, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 22c20e639fb..50f3d34e713 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -917,6 +917,7 @@ pub enum PaymentMethodType { OnlineBankingFpx, OnlineBankingPoland, OnlineBankingSlovakia, + Oxxo, PagoEfectivo, PermataBankTransfer, PayBright, diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index 55f5408210f..97704f79ca6 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1606,6 +1606,7 @@ impl From<PaymentMethodType> for PaymentMethod { PaymentMethodType::RedPagos => Self::Voucher, PaymentMethodType::Cashapp => Self::Wallet, PaymentMethodType::Givex => Self::GiftCard, + PaymentMethodType::Oxxo => Self::Voucher, } } } diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 895ea4f98e1..3624fb82737 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -408,6 +408,8 @@ pub enum AdyenPaymentMethod<'a> { OnlineBankingFpx(Box<OnlineBankingFpxData>), #[serde(rename = "molpay_ebanking_TH")] OnlineBankingThailand(Box<OnlineBankingThailandData>), + #[serde(rename = "oxxo")] + Oxxo, #[serde(rename = "paysafecard")] PaySafeCard, #[serde(rename = "paybright")] @@ -975,6 +977,8 @@ pub enum PaymentType { OnlineBankingFpx, #[serde(rename = "molpay_ebanking_TH")] OnlineBankingThailand, + #[serde(rename = "oxxo")] + Oxxo, #[serde(rename = "paysafecard")] PaySafeCard, PayBright, @@ -1411,6 +1415,7 @@ fn get_social_security_number( | payments::VoucherData::Efecty | payments::VoucherData::PagoEfectivo | payments::VoucherData::RedCompra + | payments::VoucherData::Oxxo | payments::VoucherData::RedPagos => None, } } @@ -1493,6 +1498,7 @@ impl<'a> TryFrom<&api_models::payments::VoucherData> for AdyenPaymentMethod<'a> shopper_email: indomaret_data.email.clone(), }))) } + payments::VoucherData::Oxxo => Ok(AdyenPaymentMethod::Oxxo), payments::VoucherData::Efecty | payments::VoucherData::PagoEfectivo | payments::VoucherData::RedCompra @@ -2794,6 +2800,7 @@ pub fn get_wait_screen_metadata( }))) } PaymentType::Affirm + | PaymentType::Oxxo | PaymentType::Afterpaytouch | PaymentType::Alipay | PaymentType::AlipayHk @@ -2856,7 +2863,10 @@ pub fn get_present_to_shopper_metadata( let reference = response.action.reference.clone(); match response.action.payment_method_type { - PaymentType::Alfamart | PaymentType::Indomaret | PaymentType::BoletoBancario => { + PaymentType::Alfamart + | PaymentType::Indomaret + | PaymentType::BoletoBancario + | PaymentType::Oxxo => { let voucher_data = payments::VoucherNextStepData { expires_at: response.action.expires_at.clone(), reference, diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 016c0b59039..6d144a4a462 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -611,6 +611,7 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { | enums::PaymentMethodType::PermataBankTransfer | enums::PaymentMethodType::PaySafeCard | enums::PaymentMethodType::Givex + | enums::PaymentMethodType::Oxxo | enums::PaymentMethodType::Walley => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) @@ -909,6 +910,7 @@ fn infer_stripe_pay_later_type( | enums::PaymentMethodType::PermataBankTransfer | enums::PaymentMethodType::PaySafeCard | enums::PaymentMethodType::Givex + | enums::PaymentMethodType::Oxxo | enums::PaymentMethodType::WeChatPay => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), )), diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index a98400c26eb..877778c5047 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -75,7 +75,7 @@ pub trait RouterData { } pub fn get_unimplemented_payment_method_error_message(connector: &str) -> String { - format!("Selected paymemt method through {}", connector) + format!("Selected payment method through {}", connector) } impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Response> { diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index 88f85abcaad..97208e6fe1a 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -246,7 +246,8 @@ impl } api_models::payments::VoucherData::RedPagos => ZenPaymentChannels::PclBoacompraRedpagos, api_models::payments::VoucherData::Alfamart { .. } - | api_models::payments::VoucherData::Indomaret { .. } => Err( + | api_models::payments::VoucherData::Indomaret { .. } + | api_models::payments::VoucherData::Oxxo { .. } => Err( errors::ConnectorError::NotImplemented("payment method".to_string()), )?, }; diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 511d0534a8b..335a18075e8 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1570,6 +1570,7 @@ pub fn validate_payment_method_type_against_payment_method( | api_enums::PaymentMethodType::RedPagos | api_enums::PaymentMethodType::Indomaret | api_enums::PaymentMethodType::Alfamart + | api_enums::PaymentMethodType::Oxxo ), api_enums::PaymentMethod::GiftCard => { matches!( diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index b45b3e11d0d..0d6e014b34c 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -195,6 +195,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::UpiData, api_models::payments::VoucherData, api_models::payments::BoletoVoucherData, + api_models::payments::AlfamartVoucherData, + api_models::payments::IndomaretVoucherData, api_models::payments::Address, api_models::payments::VoucherData, api_models::payments::AlfamartVoucherData, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index bbf076f3c66..95f8f3c0fd2 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -225,6 +225,7 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { | api_enums::PaymentMethodType::RedCompra | api_enums::PaymentMethodType::Alfamart | api_enums::PaymentMethodType::Indomaret + | api_enums::PaymentMethodType::Oxxo | api_enums::PaymentMethodType::RedPagos => Self::Voucher, api_enums::PaymentMethodType::Pse | api_enums::PaymentMethodType::Multibanco diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index d06f9611f8e..72243b17a5a 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -7719,6 +7719,7 @@ "online_banking_fpx", "online_banking_poland", "online_banking_slovakia", + "oxxo", "pago_efectivo", "permata_bank_transfer", "pay_bright", @@ -10366,6 +10367,12 @@ "$ref": "#/components/schemas/IndomaretVoucherData" } } + }, + { + "type": "string", + "enum": [ + "oxxo" + ] } ] },
feat
[Adyen] implement Oxxo (#1808)
e4a35d366b7db151378d6c1f61e4d01d1c7ed37f
2024-09-30 15:46:54
Pa1NarK
feat(ci): add cypress tests to github ci (#5183)
false
diff --git a/.github/workflows/cypress-tests-runner.yml b/.github/workflows/cypress-tests-runner.yml new file mode 100644 index 00000000000..3a10dceb37e --- /dev/null +++ b/.github/workflows/cypress-tests-runner.yml @@ -0,0 +1,218 @@ +name: Run Cypress tests + +on: + merge_group: + types: + - checks_requested + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + CARGO_INCREMENTAL: 0 + CARGO_NET_RETRY: 10 + CONNECTORS: stripe + RUST_BACKTRACE: short + RUSTUP_MAX_RETRIES: 10 + RUN_TESTS: ${{ ((github.event_name == 'pull_request') && (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name)) || (github.event_name == 'merge_group')}} + DEBUG: cypress:cli + RUST_MIN_STACK: 10485760 + +jobs: + runner: + name: Run Cypress tests + runs-on: hyperswitch-runners + + services: + redis: + image: "public.ecr.aws/docker/library/redis:alpine" + options: >- + --health-cmd "redis-cli ping" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + ports: + - 6379:6379 + postgres: + image: "public.ecr.aws/docker/library/postgres:alpine" + env: + POSTGRES_USER: db_user + POSTGRES_PASSWORD: db_pass + POSTGRES_DB: hyperswitch_db + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + ports: + - 5432:5432 + + steps: + - name: Skip tests for PRs from forks + shell: bash + if: ${{ env.RUN_TESTS == 'false' }} + run: echo 'Skipping tests for PRs from forks' + + - name: Checkout repository + if: ${{ env.RUN_TESTS == 'true' }} + uses: actions/checkout@v4 + + - name: Download Encrypted TOML from S3 and Decrypt + if: ${{ env.RUN_TESTS == 'true' }} + env: + AWS_ACCESS_KEY_ID: ${{ secrets.CONNECTOR_CREDS_AWS_ACCESS_KEY_ID }} + AWS_REGION: ${{ secrets.CONNECTOR_CREDS_AWS_REGION }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.CONNECTOR_CREDS_AWS_SECRET_ACCESS_KEY }} + CONNECTOR_AUTH_PASSPHRASE: ${{ secrets.CONNECTOR_AUTH_PASSPHRASE }} + CONNECTOR_CREDS_S3_BUCKET_URI: ${{ secrets.CONNECTOR_CREDS_S3_BUCKET_URI}} + DESTINATION_FILE_NAME: "creds.json.gpg" + S3_SOURCE_FILE_NAME: "f64157fe-a8f7-43a8-a268-b17e9a8c305f.json.gpg" + shell: bash + run: | + mkdir -p ".github/secrets" ".github/test" + + aws s3 cp "${CONNECTOR_CREDS_S3_BUCKET_URI}/${S3_SOURCE_FILE_NAME}" ".github/secrets/${DESTINATION_FILE_NAME}" + gpg --quiet --batch --yes --decrypt --passphrase="${CONNECTOR_AUTH_PASSPHRASE}" --output ".github/test/creds.json" ".github/secrets/${DESTINATION_FILE_NAME}" + + - name: Set paths in env + if: ${{ env.RUN_TESTS == 'true' }} + shell: bash + run: | + echo "CYPRESS_CONNECTOR_AUTH_FILE_PATH=${{ github.workspace }}/.github/test/creds.json" >> $GITHUB_ENV + + - name: Fetch keys + if: ${{ env.RUN_TESTS == 'true' }} + env: + TOML_PATH: "./config/development.toml" + run: | + LOCAL_ADMIN_API_KEY=$(yq '.secrets.admin_api_key' ${TOML_PATH}) + echo "CYPRESS_ADMINAPIKEY=${LOCAL_ADMIN_API_KEY}" >> $GITHUB_ENV + + - name: Install mold linker + if: ${{ runner.os == 'Linux' && env.RUN_TESTS == 'true' }} + uses: rui314/setup-mold@v1 + with: + make-default: true + + - name: Install Rust + if: ${{ env.RUN_TESTS == 'true' }} + uses: dtolnay/rust-toolchain@master + with: + toolchain: stable 2 weeks ago + components: clippy + + - name: Install sccache + if: ${{ env.RUN_TESTS == 'true' }} + uses: taiki-e/[email protected] + with: + tool: sccache + checksum: true + + - name: Install cargo-nextest + if: ${{ env.RUN_TESTS == 'true' }} + uses: taiki-e/[email protected] + with: + tool: cargo-nextest + checksum: true + + - name: Install Diesel CLI + if: ${{ env.RUN_TESTS == 'true' }} + uses: baptiste0928/[email protected] + with: + crate: diesel_cli + features: postgres + args: --no-default-features + + - name: Install Just + if: ${{ env.RUN_TESTS == 'true' }} + uses: taiki-e/[email protected] + with: + tool: just + checksum: true + + - name: Install Node.js + if: ${{ env.RUN_TESTS == 'true' }} + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'npm' + + - name: Install Cypress and dependencies + if: ${{ env.RUN_TESTS == 'true' }} + run: | + npm ci --prefix ./cypress-tests + + - name: Run database migrations + if: ${{ env.RUN_TESTS == 'true' }} + shell: bash + env: + DATABASE_URL: postgres://db_user:db_pass@localhost:5432/hyperswitch_db + run: just migrate run --locked-schema + + - name: Build project + if: ${{ env.RUN_TESTS == 'true' }} + run: cargo build --package router --bin router --jobs 6 + + - name: Setup Local Server + if: ${{ env.RUN_TESTS == 'true' }} + run: | + # Start the server in the background + target/debug/router & + + SERVER_PID=$! + echo "PID=${SERVER_PID}" >> $GITHUB_ENV + + # Wait for the server to start in port 8080 + COUNT=0 + while ! nc -z localhost 8080; do + if [ $COUNT -gt 12 ]; then # Wait for up to 2 minutes (12 * 10 seconds) + echo "Server did not start within a reasonable time. Exiting." + kill ${SERVER_PID} + exit 1 + else + COUNT=$((COUNT+1)) + sleep 10 + fi + done + + - name: Run Cypress tests + if: ${{ env.RUN_TESTS == 'true' }} + env: + CYPRESS_BASEURL: "http://localhost:8080" + shell: bash -leuo pipefail {0} + run: | + cd cypress-tests + + RED='\033[0;31m' + RESET='\033[0m' + + failed_connectors=() + + for connector in $(echo "${CONNECTORS}" | tr "," "\n"); do + echo "${connector}" + for service in "payments" "payouts"; do + if ! ROUTER__SERVER__WORKERS=4 CYPRESS_CONNECTOR="${connector}" npm run cypress:"${service}"; then + failed_connectors+=("${connector}-${service}") + fi + done + done + + if [ ${#failed_connectors[@]} -gt 0 ]; then + echo -e "${RED}One or more connectors failed to run:${RESET}" + printf '%s\n' "${failed_connectors[@]}" + exit 1 + fi + + kill "${{ env.PID }}" + + - name: Upload Cypress test results + if: env.RUN_TESTS == 'true' && failure() + uses: actions/upload-artifact@v4 + with: + name: cypress-test-results + path: | + cypress-tests/cypress/reports/*.json + cypress-tests/cypress/reports/*.html + retention-days: 1
feat
add cypress tests to github ci (#5183)
e9fc34ff626c13ec117f4ec9b091a69892bddf4f
2023-05-03 01:56:52
Jeeva
refactor(stripe): return all the missing fields in a request (#935)
false
diff --git a/.gitignore b/.gitignore index ced4be3d728..a8e6412fb1a 100644 --- a/.gitignore +++ b/.gitignore @@ -256,3 +256,5 @@ loadtest/*.tmp/ # Nix output result* + +.idea/ diff --git a/Cargo.lock b/Cargo.lock index d065e56825f..0f7fa1ae308 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1221,7 +1221,7 @@ dependencies = [ "num-integer", "num-traits", "serde", - "time 0.1.43", + "time 0.1.45", "wasm-bindgen", "winapi", ] @@ -4420,11 +4420,12 @@ dependencies = [ [[package]] name = "time" -version = "0.1.43" +version = "0.1.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca8a50ef2360fbd1eeb0ecd46795a87a19024eb4b53c5dc916ca1fd95fe62438" +checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a" dependencies = [ "libc", + "wasi 0.10.0+wasi-snapshot-preview1", "winapi", ] @@ -5018,6 +5019,12 @@ version = "0.9.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" +[[package]] +name = "wasi" +version = "0.10.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" + [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index bd3d6c6dca3..a8f24cb6603 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -37,7 +37,6 @@ ring = "0.16.20" serde = { version = "1.0.160", features = ["derive"] } serde_json = "1.0.96" serde_urlencoded = "0.7.1" -signal-hook-tokio = { version = "0.3.1", features = ["futures-v0_3"], optional = true } signal-hook = { version = "0.3.15", optional = true } tokio = { version = "1.27.0", features = ["macros", "rt-multi-thread"], optional = true } thiserror = "1.0.40" @@ -48,6 +47,9 @@ md5 = "0.7.0" 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"], optional = true } +[target.'cfg(not(target_os = "windows"))'.dependencies] +signal-hook-tokio = { version = "0.3.1", features = ["futures-v0_3"], optional = true } + [dev-dependencies] fake = "2.5.0" proptest = "1.1.0" diff --git a/crates/common_utils/src/signals.rs b/crates/common_utils/src/signals.rs index 44118f39e30..5bde366bf3c 100644 --- a/crates/common_utils/src/signals.rs +++ b/crates/common_utils/src/signals.rs @@ -1,6 +1,8 @@ //! Provide Interface for worker services to handle signals +#[cfg(not(target_os = "windows"))] use futures::StreamExt; +#[cfg(not(target_os = "windows"))] use router_env::logger; use tokio::sync::mpsc; @@ -8,6 +10,7 @@ use tokio::sync::mpsc; /// This functions is meant to run in parallel to the application. /// It will send a signal to the receiver when a SIGTERM or SIGINT is received /// +#[cfg(not(target_os = "windows"))] pub async fn signal_handler(mut sig: signal_hook_tokio::Signals, sender: mpsc::Sender<()>) { if let Some(signal) = sig.next().await { logger::info!( @@ -31,9 +34,47 @@ pub async fn signal_handler(mut sig: signal_hook_tokio::Signals, sender: mpsc::S } } +/// +/// This functions is meant to run in parallel to the application. +/// It will send a signal to the receiver when a SIGTERM or SIGINT is received +/// +#[cfg(target_os = "windows")] +pub async fn signal_handler(_sig: DummySignal, _sender: mpsc::Sender<()>) {} + /// /// This function is used to generate a list of signals that the signal_handler should listen for /// +#[cfg(not(target_os = "windows"))] pub fn get_allowed_signals() -> Result<signal_hook_tokio::SignalsInfo, std::io::Error> { signal_hook_tokio::Signals::new([signal_hook::consts::SIGTERM, signal_hook::consts::SIGINT]) } + +/// +/// This function is used to generate a list of signals that the signal_handler should listen for +/// +#[cfg(target_os = "windows")] +pub fn get_allowed_signals() -> Result<DummySignal, std::io::Error> { + Ok(DummySignal) +} + +/// +/// Dummy Signal Handler for windows +/// +#[cfg(target_os = "windows")] +#[derive(Debug, Clone)] +pub struct DummySignal; + +#[cfg(target_os = "windows")] +impl DummySignal { + /// + /// Dummy handler for signals in windows (empty) + /// + pub fn handle(&self) -> Self { + self.clone() + } + + /// + /// Hollow implementation, for windows compatibility + /// + pub fn close(self) {} +} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index be6d7cf5bba..102d0287ff7 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -69,7 +69,6 @@ serde_path_to_error = "0.1.11" serde_qs = { version = "0.12.0", optional = true } serde_urlencoded = "0.7.1" serde_with = "2.3.2" -signal-hook-tokio = { version = "0.3.1", features = ["futures-v0_3"] } signal-hook = "0.3.15" strum = { version = "0.24.1", features = ["derive"] } thiserror = "1.0.40" @@ -94,6 +93,9 @@ aws-sdk-s3 = "0.25.0" aws-config = "0.55.1" infer = "0.13.0" +[target.'cfg(not(target_os = "windows"))'.dependencies] +signal-hook-tokio = { version = "0.3.1", features = ["futures-v0_3"]} + [build-dependencies] router_env = { version = "0.1.0", path = "../router_env", default-features = false } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 7b7cbe86945..6c355d52eef 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1,6 +1,6 @@ use api_models::{self, enums as api_enums, payments}; use base64::Engine; -use common_utils::{errors::CustomResult, fp_utils, pii}; +use common_utils::{errors::CustomResult, pii}; use error_stack::{IntoReport, ResultExt}; use masking::{ExposeInterface, ExposeOptionInterface, Secret}; use serde::{Deserialize, Serialize}; @@ -8,7 +8,7 @@ use url::Url; use uuid::Uuid; use crate::{ - consts, + collect_missing_value_keys, consts, core::errors, services, types::{self, api, storage::enums}, @@ -429,30 +429,21 @@ fn validate_shipping_address_against_payment_method( payment_method: &StripePaymentMethodType, ) -> Result<(), error_stack::Report<errors::ConnectorError>> { if let StripePaymentMethodType::AfterpayClearpay = payment_method { - fp_utils::when(shipping_address.name.is_none(), || { - Err(errors::ConnectorError::MissingRequiredField { - field_name: "shipping.address.first_name", - }) - })?; - - fp_utils::when(shipping_address.line1.is_none(), || { - Err(errors::ConnectorError::MissingRequiredField { - field_name: "shipping.address.line1", - }) - })?; - - fp_utils::when(shipping_address.country.is_none(), || { - Err(errors::ConnectorError::MissingRequiredField { - field_name: "shipping.address.country", - }) - })?; + let missing_fields = collect_missing_value_keys!( + ("shipping.address.first_name", shipping_address.name), + ("shipping.address.line1", shipping_address.line1), + ("shipping.address.country", shipping_address.country), + ("shipping.address.zip", shipping_address.zip) + ); - fp_utils::when(shipping_address.zip.is_none(), || { - Err(errors::ConnectorError::MissingRequiredField { - field_name: "shipping.address.zip", + if !missing_fields.is_empty() { + return Err(errors::ConnectorError::MissingRequiredFields { + field_names: missing_fields, }) - })?; + .into_report(); + } } + Ok(()) } @@ -1799,3 +1790,192 @@ pub struct DisputeObj { pub dispute_id: String, pub status: String, } + +#[cfg(test)] +mod test_validate_shipping_address_against_payment_method { + #![allow(clippy::unwrap_used)] + use api_models::enums::CountryCode; + use masking::Secret; + + use crate::{ + connector::stripe::transformers::{ + validate_shipping_address_against_payment_method, StripePaymentMethodType, + StripeShippingAddress, + }, + core::errors, + }; + + #[test] + fn should_return_ok() { + // Arrange + let stripe_shipping_address = create_stripe_shipping_address( + Some("name".to_string()), + Some("line1".to_string()), + Some(CountryCode::AD), + Some("zip".to_string()), + ); + + let payment_method = &StripePaymentMethodType::AfterpayClearpay; + + //Act + let result = validate_shipping_address_against_payment_method( + &stripe_shipping_address, + payment_method, + ); + + // Assert + assert!(result.is_ok()); + } + + #[test] + fn should_return_err_for_empty_name() { + // Arrange + let stripe_shipping_address = create_stripe_shipping_address( + None, + Some("line1".to_string()), + Some(CountryCode::AD), + Some("zip".to_string()), + ); + + let payment_method = &StripePaymentMethodType::AfterpayClearpay; + + //Act + let result = validate_shipping_address_against_payment_method( + &stripe_shipping_address, + payment_method, + ); + + // Assert + assert!(result.is_err()); + let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); + assert_eq!(missing_fields.len(), 1); + assert_eq!(missing_fields[0], "shipping.address.first_name"); + } + + #[test] + fn should_return_err_for_empty_line1() { + // Arrange + let stripe_shipping_address = create_stripe_shipping_address( + Some("name".to_string()), + None, + Some(CountryCode::AD), + Some("zip".to_string()), + ); + + let payment_method = &StripePaymentMethodType::AfterpayClearpay; + + //Act + let result = validate_shipping_address_against_payment_method( + &stripe_shipping_address, + payment_method, + ); + + // Assert + assert!(result.is_err()); + let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); + assert_eq!(missing_fields.len(), 1); + assert_eq!(missing_fields[0], "shipping.address.line1"); + } + + #[test] + fn should_return_err_for_empty_country() { + // Arrange + let stripe_shipping_address = create_stripe_shipping_address( + Some("name".to_string()), + Some("line1".to_string()), + None, + Some("zip".to_string()), + ); + + let payment_method = &StripePaymentMethodType::AfterpayClearpay; + + //Act + let result = validate_shipping_address_against_payment_method( + &stripe_shipping_address, + payment_method, + ); + + // Assert + assert!(result.is_err()); + let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); + assert_eq!(missing_fields.len(), 1); + assert_eq!(missing_fields[0], "shipping.address.country"); + } + + #[test] + fn should_return_err_for_empty_zip() { + // Arrange + let stripe_shipping_address = create_stripe_shipping_address( + Some("name".to_string()), + Some("line1".to_string()), + Some(CountryCode::AD), + None, + ); + let payment_method = &StripePaymentMethodType::AfterpayClearpay; + + //Act + let result = validate_shipping_address_against_payment_method( + &stripe_shipping_address, + payment_method, + ); + + // Assert + assert!(result.is_err()); + let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); + assert_eq!(missing_fields.len(), 1); + assert_eq!(missing_fields[0], "shipping.address.zip"); + } + + #[test] + fn should_return_error_when_missing_multiple_fields() { + // Arrange + let expected_missing_field_names: Vec<&'static str> = + vec!["shipping.address.zip", "shipping.address.country"]; + let stripe_shipping_address = create_stripe_shipping_address( + Some("name".to_string()), + Some("line1".to_string()), + None, + None, + ); + let payment_method = &StripePaymentMethodType::AfterpayClearpay; + + //Act + let result = validate_shipping_address_against_payment_method( + &stripe_shipping_address, + payment_method, + ); + + // Assert + assert!(result.is_err()); + let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); + for field in missing_fields { + assert!(expected_missing_field_names.contains(&field)); + } + } + + fn get_missing_fields(connector_error: &errors::ConnectorError) -> Vec<&'static str> { + if let errors::ConnectorError::MissingRequiredFields { field_names } = connector_error { + return field_names.to_vec(); + } + + vec![] + } + + fn create_stripe_shipping_address( + name: Option<String>, + line1: Option<String>, + country: Option<CountryCode>, + zip: Option<String>, + ) -> StripeShippingAddress { + StripeShippingAddress { + name: name.map(Secret::new), + line1: line1.map(Secret::new), + country, + zip: zip.map(Secret::new), + city: Some(String::from("city")), + line2: Some(Secret::new(String::from("line2"))), + state: Some(Secret::new(String::from("state"))), + phone: Some(Secret::new(String::from("pbone number"))), + } + } +} diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index c4a6a7d863e..1377f3019a7 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -241,6 +241,8 @@ pub enum ConnectorError { ResponseHandlingFailed, #[error("Missing required field: {field_name}")] MissingRequiredField { field_name: &'static str }, + #[error("Missing required fields: {field_names:?}")] + MissingRequiredFields { field_names: Vec<&'static str> }, #[error("Failed to obtain authentication type")] FailedToObtainAuthType, #[error("Failed to obtain certificate")] diff --git a/crates/router/src/macros.rs b/crates/router/src/macros.rs index 2cd6310faf0..33ed43fcc7a 100644 --- a/crates/router/src/macros.rs +++ b/crates/router/src/macros.rs @@ -51,3 +51,18 @@ macro_rules! async_spawn { tokio::spawn(async move { $t }); }; } + +#[macro_export] +macro_rules! collect_missing_value_keys { + [$(($key:literal, $option:expr)),+] => { + { + let mut keys: Vec<&'static str> = Vec::new(); + $( + if $option.is_none() { + keys.push($key); + } + )* + keys + } + }; +} diff --git a/crates/router/src/scheduler/utils.rs b/crates/router/src/scheduler/utils.rs index 24ddf6b2a86..a58b02561a8 100644 --- a/crates/router/src/scheduler/utils.rs +++ b/crates/router/src/scheduler/utils.rs @@ -4,8 +4,11 @@ use std::{ }; use error_stack::{report, ResultExt}; +#[cfg(not(target_os = "windows"))] +use futures::StreamExt; use redis_interface::{RedisConnectionPool, RedisEntryId}; use router_env::opentelemetry; +use tokio::sync::oneshot; use uuid::Uuid; use super::{consumer, metrics, process_data, workflows}; @@ -376,3 +379,36 @@ where Ok(()) } } + +#[cfg(not(target_os = "windows"))] +pub(crate) async fn signal_handler( + mut sig: signal_hook_tokio::Signals, + sender: oneshot::Sender<()>, +) { + if let Some(signal) = sig.next().await { + logger::info!( + "Received signal: {:?}", + signal_hook::low_level::signal_name(signal) + ); + match signal { + signal_hook::consts::SIGTERM | signal_hook::consts::SIGINT => match sender.send(()) { + Ok(_) => { + logger::info!("Request for force shutdown received") + } + Err(_) => { + logger::error!( + "The receiver is closed, a termination call might already be sent" + ) + } + }, + _ => {} + } + } +} + +#[cfg(target_os = "windows")] +pub(crate) async fn signal_handler( + _sig: common_utils::signals::DummySignal, + _sender: oneshot::Sender<()>, +) { +}
refactor
return all the missing fields in a request (#935)
f690c5f3ead64c353ac1d36401e009582c1f0ecf
2023-08-23 16:33:00
Nishant Joshi
fix(webhooks): handling errors inside source verification (#1994)
false
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index a26d4db3e4c..c605afd5255 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -803,6 +803,13 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType>( object_ref_id.clone(), ) .await + .or_else(|error| match error.current_context() { + errors::ConnectorError::WebhookSourceVerificationFailed => { + logger::error!(?error, "Source Verification Failed"); + Ok(false) + } + _ => Err(error), + }) .switch() .attach_printable("There was an issue in incoming webhook source verification")?;
fix
handling errors inside source verification (#1994)
34a1e2a840b9a5918c5566e2caf3394bd7a3b834
2024-09-29 18:19:36
Prajjwal Kumar
refactor(router): add dynamic_routing feature flag in release features (#6144)
false
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 69c23730b94..31cfae49875 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -21,7 +21,7 @@ encryption_service = ["hyperswitch_domain_models/encryption_service", "common_ut km_forward_x_request_id = ["common_utils/km_forward_x_request_id"] frm = ["api_models/frm", "hyperswitch_domain_models/frm", "hyperswitch_connectors/frm", "hyperswitch_interfaces/frm"] stripe = [] -release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3", "keymanager_mtls", "keymanager_create", "encryption_service"] +release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3", "keymanager_mtls", "keymanager_create", "encryption_service", "dynamic_routing"] oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"] accounts_cache = []
refactor
add dynamic_routing feature flag in release features (#6144)
9df4e0193ffeb6d1cc323bdebb7e2bdfb2a375e2
2023-11-29 17:04:53
Sampras Lopes
feat(analytics): Add Clickhouse based analytics (#2988)
false
diff --git a/Cargo.lock b/Cargo.lock index 96bdcff3f86..417e6d85db6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -332,6 +332,36 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" +[[package]] +name = "analytics" +version = "0.1.0" +dependencies = [ + "actix-web", + "api_models", + "async-trait", + "aws-config", + "aws-sdk-lambda", + "aws-smithy-types", + "bigdecimal", + "common_utils", + "diesel_models", + "error-stack", + "external_services", + "futures 0.3.28", + "masking", + "once_cell", + "reqwest", + "router_env", + "serde", + "serde_json", + "sqlx", + "storage_impl", + "strum 0.25.0", + "thiserror", + "time", + "tokio 1.32.0", +] + [[package]] name = "android-tzdata" version = "0.1.1" @@ -729,6 +759,31 @@ dependencies = [ "tracing", ] +[[package]] +name = "aws-sdk-lambda" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3ad176ffaa3aafa532246eb6a9f18a7d68da19950704ecc95d33d9dc3c62a9b" +dependencies = [ + "aws-credential-types", + "aws-endpoint", + "aws-http", + "aws-sig-auth", + "aws-smithy-async", + "aws-smithy-client", + "aws-smithy-http", + "aws-smithy-http-tower", + "aws-smithy-json", + "aws-smithy-types", + "aws-types", + "bytes 1.5.0", + "http", + "regex", + "tokio-stream", + "tower", + "tracing", +] + [[package]] name = "aws-sdk-s3" version = "0.28.0" @@ -1148,6 +1203,7 @@ dependencies = [ "num-bigint", "num-integer", "num-traits", + "serde", ] [[package]] @@ -1256,7 +1312,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f404657a7ea7b5249e36808dff544bc88a28f26e0ac40009f674b7a009d14be3" dependencies = [ "once_cell", - "proc-macro-crate", + "proc-macro-crate 2.0.0", "proc-macro2", "quote", "syn 2.0.38", @@ -3862,6 +3918,27 @@ dependencies = [ "libc", ] +[[package]] +name = "num_enum" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f646caf906c20226733ed5b1374287eb97e3c2a5c227ce668c1f2ce20ae57c9" +dependencies = [ + "num_enum_derive", +] + +[[package]] +name = "num_enum_derive" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcbff9bc912032c62bf65ef1d5aea88983b420f4f839db1e9b0c281a25c9c799" +dependencies = [ + "proc-macro-crate 1.3.1", + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "object" version = "0.32.1" @@ -4395,6 +4472,16 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit 0.19.10", +] + [[package]] name = "proc-macro-crate" version = "2.0.0" @@ -4688,6 +4775,36 @@ dependencies = [ "crossbeam-utils 0.8.16", ] +[[package]] +name = "rdkafka" +version = "0.36.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d54f02a5a40220f8a2dfa47ddb38ba9064475a5807a69504b6f91711df2eea63" +dependencies = [ + "futures-channel", + "futures-util", + "libc", + "log", + "rdkafka-sys", + "serde", + "serde_derive", + "serde_json", + "slab", + "tokio 1.32.0", +] + +[[package]] +name = "rdkafka-sys" +version = "4.7.0+2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55e0d2f9ba6253f6ec72385e453294f8618e9e15c2c6aba2a5c01ccf9622d615" +dependencies = [ + "libc", + "libz-sys", + "num_enum", + "pkg-config", +] + [[package]] name = "redis-protocol" version = "4.1.0" @@ -4939,6 +5056,7 @@ dependencies = [ "actix-multipart", "actix-rt", "actix-web", + "analytics", "api_models", "argon2", "async-bb8-diesel", @@ -4988,6 +5106,7 @@ dependencies = [ "qrcode", "rand 0.8.5", "rand_chacha 0.3.1", + "rdkafka", "redis_interface", "regex", "reqwest", diff --git a/Dockerfile b/Dockerfile index 8eb321dd2af..e9591e5e9f2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM rust:slim-bookworm as builder +FROM rust:bookworm as builder ARG EXTRA_FEATURES="" @@ -36,7 +36,7 @@ RUN cargo build --release --features release ${EXTRA_FEATURES} -FROM debian:bookworm-slim +FROM debian:bookworm # Placing config and binary executable in different directories ARG CONFIG_DIR=/local/config diff --git a/config/development.toml b/config/development.toml index f2620bd3713..fa5fddb0d60 100644 --- a/config/development.toml +++ b/config/development.toml @@ -475,3 +475,33 @@ delay_between_retries_in_milliseconds = 500 [kv_config] ttl = 900 # 15 * 60 seconds + +[events] +source = "logs" + +[events.kafka] +brokers = ["localhost:9092"] +intent_analytics_topic = "hyperswitch-payment-intent-events" +attempt_analytics_topic = "hyperswitch-payment-attempt-events" +refund_analytics_topic = "hyperswitch-refund-events" +api_logs_topic = "hyperswitch-api-log-events" +connector_events_topic = "hyperswitch-connector-api-events" + +[analytics] +source = "sqlx" + +[analytics.clickhouse] +username = "default" +# password = "" +host = "http://localhost:8123" +database_name = "default" + +[analytics.sqlx] +username = "db_user" +password = "db_pass" +host = "localhost" +port = 5432 +dbname = "hyperswitch_db" +pool_size = 5 +connection_timeout = 10 +queue_strategy = "Fifo" \ No newline at end of file diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 445e1e85684..4d50600e1bf 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -333,16 +333,32 @@ supported_connectors = "braintree" redis_lock_expiry_seconds = 180 # 3 * 60 seconds delay_between_retries_in_milliseconds = 500 +[events.kafka] +brokers = ["localhost:9092"] +intent_analytics_topic = "hyperswitch-payment-intent-events" +attempt_analytics_topic = "hyperswitch-payment-attempt-events" +refund_analytics_topic = "hyperswitch-refund-events" +api_logs_topic = "hyperswitch-api-log-events" +connector_events_topic = "hyperswitch-connector-api-events" + [analytics] source = "sqlx" +[analytics.clickhouse] +username = "default" +# password = "" +host = "http://localhost:8123" +database_name = "default" + [analytics.sqlx] username = "db_user" password = "db_pass" -host = "pg" +host = "localhost" port = 5432 dbname = "hyperswitch_db" pool_size = 5 +connection_timeout = 10 +queue_strategy = "Fifo" [kv_config] ttl = 900 # 15 * 60 seconds diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml new file mode 100644 index 00000000000..f49fe322ae3 --- /dev/null +++ b/crates/analytics/Cargo.toml @@ -0,0 +1,37 @@ +[package] +name = "analytics" +version = "0.1.0" +description = "Analytics / Reports related functionality" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + + +[dependencies] +# First party crates +api_models = { version = "0.1.0", path = "../api_models" , features = ["errors"]} +storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false } +common_utils = { version = "0.1.0", path = "../common_utils"} +external_services = { version = "0.1.0", path = "../external_services", default-features = false} +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"] } +diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } + +#Third Party dependencies +actix-web = "4.3.1" +async-trait = "0.1.68" +aws-config = { version = "0.55.3" } +aws-sdk-lambda = { version = "0.28.0" } +aws-smithy-types = { version = "0.55.3" } +bigdecimal = { version = "0.3.1", features = ["serde"] } +error-stack = "0.3.1" +futures = "0.3.28" +once_cell = "1.18.0" +reqwest = { version = "0.11.18", features = ["serde_json"] } +serde = { version = "1.0.163", features = ["derive", "rc"] } +serde_json = "1.0.96" +sqlx = { version = "0.6.3", features = ["postgres", "runtime-actix", "runtime-actix-native-tls", "time", "bigdecimal"] } +strum = { version = "0.25.0", features = ["derive"] } +thiserror = "1.0.43" +time = { version = "0.3.21", features = ["serde", "serde-well-known", "std"] } +tokio = { version = "1.28.2", features = ["macros", "rt-multi-thread"] } diff --git a/crates/analytics/docs/clickhouse/README.md b/crates/analytics/docs/clickhouse/README.md new file mode 100644 index 00000000000..2fd48a30c29 --- /dev/null +++ b/crates/analytics/docs/clickhouse/README.md @@ -0,0 +1,45 @@ +#### Starting the containers + +In our use case we rely on kafka for ingesting events. +hence we can use docker compose to start all the components + +``` +docker compose up -d clickhouse-server kafka-ui +``` + +> kafka-ui is a visual tool for inspecting kafka on localhost:8090 + +#### Setting up Clickhouse + +Once clickhouse is up & running you need to create the required tables for it + +you can either visit the url (http://localhost:8123/play) in which the clickhouse-server is running to get a playground +Alternatively you can bash into the clickhouse container & execute commands manually +``` +# On your local terminal +docker compose exec clickhouse-server bash + +# Inside the clickhouse-server container shell +clickhouse-client --user default + +# Inside the clickhouse-client shell +SHOW TABLES; +CREATE TABLE ...... +``` + +The table creation scripts are provided [here](./scripts) + +#### Running/Debugging your application +Once setup you can run your application either via docker compose or normally via cargo run + +Remember to enable the kafka_events via development.toml/docker_compose.toml files + +Inspect the [kafka-ui](http://localhost:8090) to check the messages being inserted in queue + +If the messages/topic are available then you can run select queries on your clickhouse table to ensure data is being populated... + +If the data is not being populated in clickhouse, you can check the error logs in clickhouse server via +``` +# Inside the clickhouse-server container shell +tail -f /var/log/clickhouse-server/clickhouse-server.err.log +``` \ No newline at end of file diff --git a/crates/analytics/docs/clickhouse/cluster_setup/README.md b/crates/analytics/docs/clickhouse/cluster_setup/README.md new file mode 100644 index 00000000000..cd5f2dfeb02 --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/README.md @@ -0,0 +1,347 @@ +# Tutorial for set up clickhouse server + + +## Single server with docker + + +- Run server + +``` +docker run -d --name clickhouse-server -p 9000:9000 --ulimit nofile=262144:262144 yandex/clickhouse-server + +``` + +- Run client + +``` +docker run -it --rm --link clickhouse-server:clickhouse-server yandex/clickhouse-client --host clickhouse-server +``` + +Now you can see if it success setup or not. + + +## Setup Cluster + + +This part we will setup + +- 1 cluster, with 3 shards +- Each shard has 2 replica server +- Use ReplicatedMergeTree & Distributed table to setup our table. + + +### Cluster + +Let's see our docker-compose.yml first. + +``` +version: '3' + +services: + clickhouse-zookeeper: + image: zookeeper + ports: + - "2181:2181" + - "2182:2182" + container_name: clickhouse-zookeeper + hostname: clickhouse-zookeeper + + clickhouse-01: + image: yandex/clickhouse-server + hostname: clickhouse-01 + container_name: clickhouse-01 + ports: + - 9001:9000 + volumes: + - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml + - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml + - ./config/macros/macros-01.xml:/etc/clickhouse-server/config.d/macros.xml + # - ./data/server-01:/var/lib/clickhouse + ulimits: + nofile: + soft: 262144 + hard: 262144 + depends_on: + - "clickhouse-zookeeper" + + clickhouse-02: + image: yandex/clickhouse-server + hostname: clickhouse-02 + container_name: clickhouse-02 + ports: + - 9002:9000 + volumes: + - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml + - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml + - ./config/macros/macros-02.xml:/etc/clickhouse-server/config.d/macros.xml + # - ./data/server-02:/var/lib/clickhouse + ulimits: + nofile: + soft: 262144 + hard: 262144 + depends_on: + - "clickhouse-zookeeper" + + clickhouse-03: + image: yandex/clickhouse-server + hostname: clickhouse-03 + container_name: clickhouse-03 + ports: + - 9003:9000 + volumes: + - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml + - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml + - ./config/macros/macros-03.xml:/etc/clickhouse-server/config.d/macros.xml + # - ./data/server-03:/var/lib/clickhouse + ulimits: + nofile: + soft: 262144 + hard: 262144 + depends_on: + - "clickhouse-zookeeper" + + clickhouse-04: + image: yandex/clickhouse-server + hostname: clickhouse-04 + container_name: clickhouse-04 + ports: + - 9004:9000 + volumes: + - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml + - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml + - ./config/macros/macros-04.xml:/etc/clickhouse-server/config.d/macros.xml + # - ./data/server-04:/var/lib/clickhouse + ulimits: + nofile: + soft: 262144 + hard: 262144 + depends_on: + - "clickhouse-zookeeper" + + clickhouse-05: + image: yandex/clickhouse-server + hostname: clickhouse-05 + container_name: clickhouse-05 + ports: + - 9005:9000 + volumes: + - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml + - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml + - ./config/macros/macros-05.xml:/etc/clickhouse-server/config.d/macros.xml + # - ./data/server-05:/var/lib/clickhouse + ulimits: + nofile: + soft: 262144 + hard: 262144 + depends_on: + - "clickhouse-zookeeper" + + clickhouse-06: + image: yandex/clickhouse-server + hostname: clickhouse-06 + container_name: clickhouse-06 + ports: + - 9006:9000 + volumes: + - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml + - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml + - ./config/macros/macros-06.xml:/etc/clickhouse-server/config.d/macros.xml + # - ./data/server-06:/var/lib/clickhouse + ulimits: + nofile: + soft: 262144 + hard: 262144 + depends_on: + - "clickhouse-zookeeper" +networks: + default: + external: + name: clickhouse-net +``` + + +We have 6 clickhouse server container and one zookeeper container. + + +**To enable replication ZooKeeper is required. ClickHouse will take care of data consistency on all replicas and run restore procedure after failure automatically. It's recommended to deploy ZooKeeper cluster to separate servers.** + +**ZooKeeper is not a requirement — in some simple cases you can duplicate the data by writing it into all the replicas from your application code. This approach is not recommended — in this case ClickHouse is not able to guarantee data consistency on all replicas. This remains the responsibility of your application.** + + +Let's see config file. + +`./config/clickhouse_config.xml` is the default config file in docker, we copy it out and add this line + +``` + <!-- If element has 'incl' attribute, then for it's value will be used corresponding substitution from another file. + By default, path to file with substitutions is /etc/metrika.xml. It could be changed in config in 'include_from' element. + Values for substitutions are specified in /yandex/name_of_substitution elements in that file. + --> + <include_from>/etc/clickhouse-server/metrika.xml</include_from> +``` + + +So lets see `clickhouse_metrika.xml` + +``` +<yandex> + <clickhouse_remote_servers> + <cluster_1> + <shard> + <weight>1</weight> + <internal_replication>true</internal_replication> + <replica> + <host>clickhouse-01</host> + <port>9000</port> + </replica> + <replica> + <host>clickhouse-06</host> + <port>9000</port> + </replica> + </shard> + <shard> + <weight>1</weight> + <internal_replication>true</internal_replication> + <replica> + <host>clickhouse-02</host> + <port>9000</port> + </replica> + <replica> + <host>clickhouse-03</host> + <port>9000</port> + </replica> + </shard> + <shard> + <weight>1</weight> + <internal_replication>true</internal_replication> + + <replica> + <host>clickhouse-04</host> + <port>9000</port> + </replica> + <replica> + <host>clickhouse-05</host> + <port>9000</port> + </replica> + </shard> + </cluster_1> + </clickhouse_remote_servers> + <zookeeper-servers> + <node index="1"> + <host>clickhouse-zookeeper</host> + <port>2181</port> + </node> + </zookeeper-servers> + <networks> + <ip>::/0</ip> + </networks> + <clickhouse_compression> + <case> + <min_part_size>10000000000</min_part_size> + <min_part_size_ratio>0.01</min_part_size_ratio> + <method>lz4</method> + </case> + </clickhouse_compression> +</yandex> +``` + +and macros.xml, each instances has there own macros settings, like server 1: + +``` +<yandex> + <macros> + <replica>clickhouse-01</replica> + <shard>01</shard> + <layer>01</layer> + </macros> +</yandex> +``` + + +**Make sure your macros settings is equal to remote server settings in metrika.xml** + +So now you can start the server. + +``` +docker network create clickhouse-net +docker-compose up -d +``` + +Conn to server and see if the cluster settings fine; + +``` +docker run -it --rm --network="clickhouse-net" --link clickhouse-01:clickhouse-server yandex/clickhouse-client --host clickhouse-server +``` + +```sql +clickhouse-01 :) select * from system.clusters; + +SELECT * +FROM system.clusters + +┌─cluster─────────────────────┬─shard_num─┬─shard_weight─┬─replica_num─┬─host_name─────┬─host_address─┬─port─┬─is_local─┬─user────┬─default_database─┐ +│ cluster_1 │ 1 │ 1 │ 1 │ clickhouse-01 │ 172.21.0.4 │ 9000 │ 1 │ default │ │ +│ cluster_1 │ 1 │ 1 │ 2 │ clickhouse-06 │ 172.21.0.5 │ 9000 │ 1 │ default │ │ +│ cluster_1 │ 2 │ 1 │ 1 │ clickhouse-02 │ 172.21.0.8 │ 9000 │ 0 │ default │ │ +│ cluster_1 │ 2 │ 1 │ 2 │ clickhouse-03 │ 172.21.0.6 │ 9000 │ 0 │ default │ │ +│ cluster_1 │ 3 │ 1 │ 1 │ clickhouse-04 │ 172.21.0.7 │ 9000 │ 0 │ default │ │ +│ cluster_1 │ 3 │ 1 │ 2 │ clickhouse-05 │ 172.21.0.3 │ 9000 │ 0 │ default │ │ +│ test_shard_localhost │ 1 │ 1 │ 1 │ localhost │ 127.0.0.1 │ 9000 │ 1 │ default │ │ +│ test_shard_localhost_secure │ 1 │ 1 │ 1 │ localhost │ 127.0.0.1 │ 9440 │ 0 │ default │ │ +└─────────────────────────────┴───────────┴──────────────┴─────────────┴───────────────┴──────────────┴──────┴──────────┴─────────┴──────────────────┘ +``` + +If you see this, it means cluster's settings work well(but not conn fine). + + +### Replica Table + +So now we have a cluster and replica settings. For clickhouse, we need to create ReplicatedMergeTree Table as a local table in every server. + +```sql +CREATE TABLE ttt (id Int32) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{layer}-{shard}/ttt', '{replica}') PARTITION BY id ORDER BY id +``` + +and Create Distributed Table conn to local table + +```sql +CREATE TABLE ttt_all as ttt ENGINE = Distributed(cluster_1, default, ttt, rand()); +``` + + +### Insert and test + +gen some data and test. + + +``` +# docker exec into client server 1 and +for ((idx=1;idx<=100;++idx)); do clickhouse-client --host clickhouse-server --query "Insert into default.ttt_all values ($idx)"; done; +``` + +For Distributed table. + +``` +select count(*) from ttt_all; +``` + +For loacl table. + +``` +select count(*) from ttt; +``` + + +## Authentication + +Please see config/users.xml + + +- Conn +```bash +docker run -it --rm --network="clickhouse-net" --link clickhouse-01:clickhouse-server yandex/clickhouse-client --host clickhouse-server -u user1 --password 123456 +``` + +## Source + +- https://clickhouse.yandex/docs/en/operations/table_engines/replication/#creating-replicated-tables diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_config.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_config.xml new file mode 100644 index 00000000000..94c854dc273 --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_config.xml @@ -0,0 +1,370 @@ +<?xml version="1.0"?> +<yandex> + <logger> + <!-- Possible levels: https://github.com/pocoproject/poco/blob/develop/Foundation/include/Poco/Logger.h#L105 --> + <level>error</level> + <size>1000M</size> + <console>1</console> + <count>10</count> + <!-- <console>1</console> --> <!-- Default behavior is autodetection (log to console if not daemon mode and is tty) --> + </logger> + <!--display_name>production</display_name--> <!-- It is the name that will be shown in the client --> + <http_port>8123</http_port> + <tcp_port>9000</tcp_port> + + <!-- For HTTPS and SSL over native protocol. --> + <!-- + <https_port>8443</https_port> + <tcp_port_secure>9440</tcp_port_secure> + --> + + <!-- Used with https_port and tcp_port_secure. Full ssl options list: https://github.com/ClickHouse-Extras/poco/blob/master/NetSSL_OpenSSL/include/Poco/Net/SSLManager.h#L71 --> + <openSSL> + <server> <!-- Used for https server AND secure tcp port --> + <!-- openssl req -subj "/CN=localhost" -new -newkey rsa:2048 -days 365 -nodes -x509 -keyout /etc/clickhouse-server/server.key -out /etc/clickhouse-server/server.crt --> + <certificateFile>/etc/clickhouse-server/server.crt</certificateFile> + <privateKeyFile>/etc/clickhouse-server/server.key</privateKeyFile> + <!-- openssl dhparam -out /etc/clickhouse-server/dhparam.pem 4096 --> + <dhParamsFile>/etc/clickhouse-server/dhparam.pem</dhParamsFile> + <verificationMode>none</verificationMode> + <loadDefaultCAFile>true</loadDefaultCAFile> + <cacheSessions>true</cacheSessions> + <disableProtocols>sslv2,sslv3</disableProtocols> + <preferServerCiphers>true</preferServerCiphers> + </server> + + <client> <!-- Used for connecting to https dictionary source --> + <loadDefaultCAFile>true</loadDefaultCAFile> + <cacheSessions>true</cacheSessions> + <disableProtocols>sslv2,sslv3</disableProtocols> + <preferServerCiphers>true</preferServerCiphers> + <!-- Use for self-signed: <verificationMode>none</verificationMode> --> + <invalidCertificateHandler> + <!-- Use for self-signed: <name>AcceptCertificateHandler</name> --> + <name>RejectCertificateHandler</name> + </invalidCertificateHandler> + </client> + </openSSL> + + <!-- Default root page on http[s] server. For example load UI from https://tabix.io/ when opening http://localhost:8123 --> + <!-- + <http_server_default_response><![CDATA[<html ng-app="SMI2"><head><base href="http://ui.tabix.io/"></head><body><div ui-view="" class="content-ui"></div><script src="http://loader.tabix.io/master.js"></script></body></html>]]></http_server_default_response> + --> + + <!-- Port for communication between replicas. Used for data exchange. --> + <interserver_http_port>9009</interserver_http_port> + + <!-- Hostname that is used by other replicas to request this server. + If not specified, than it is determined analogous to 'hostname -f' command. + This setting could be used to switch replication to another network interface. + --> + <!-- + <interserver_http_host>example.yandex.ru</interserver_http_host> + --> + + <!-- Listen specified host. use :: (wildcard IPv6 address), if you want to accept connections both with IPv4 and IPv6 from everywhere. --> + <!-- <listen_host>::</listen_host> --> + <!-- Same for hosts with disabled ipv6: --> + <!-- <listen_host>0.0.0.0</listen_host> --> + + <!-- Default values - try listen localhost on ipv4 and ipv6: --> + <!-- + <listen_host>::1</listen_host> + <listen_host>127.0.0.1</listen_host> + --> + <!-- Don't exit if ipv6 or ipv4 unavailable, but listen_host with this protocol specified --> + <!-- <listen_try>0</listen_try> --> + + <!-- Allow listen on same address:port --> + <!-- <listen_reuse_port>0</listen_reuse_port> --> + + <!-- <listen_backlog>64</listen_backlog> --> + + <max_connections>4096</max_connections> + <keep_alive_timeout>3</keep_alive_timeout> + + <!-- Maximum number of concurrent queries. --> + <max_concurrent_queries>100</max_concurrent_queries> + + <!-- Set limit on number of open files (default: maximum). This setting makes sense on Mac OS X because getrlimit() fails to retrieve + correct maximum value. --> + <!-- <max_open_files>262144</max_open_files> --> + + <!-- Size of cache of uncompressed blocks of data, used in tables of MergeTree family. + In bytes. Cache is single for server. Memory is allocated only on demand. + Cache is used when 'use_uncompressed_cache' user setting turned on (off by default). + Uncompressed cache is advantageous only for very short queries and in rare cases. + --> + <uncompressed_cache_size>8589934592</uncompressed_cache_size> + + <!-- Approximate size of mark cache, used in tables of MergeTree family. + In bytes. Cache is single for server. Memory is allocated only on demand. + You should not lower this value. + --> + <mark_cache_size>5368709120</mark_cache_size> + + + <!-- Path to data directory, with trailing slash. --> + <path>/var/lib/clickhouse/</path> + + <!-- Path to temporary data for processing hard queries. --> + <tmp_path>/var/lib/clickhouse/tmp/</tmp_path> + + <!-- Directory with user provided files that are accessible by 'file' table function. --> + <user_files_path>/var/lib/clickhouse/user_files/</user_files_path> + + <!-- Path to configuration file with users, access rights, profiles of settings, quotas. --> + <users_config>users.xml</users_config> + + <!-- Default profile of settings. --> + <default_profile>default</default_profile> + + <!-- System profile of settings. This settings are used by internal processes (Buffer storage, Distributed DDL worker and so on). --> + <!-- <system_profile>default</system_profile> --> + + <!-- Default database. --> + <default_database>default</default_database> + + <!-- Server time zone could be set here. + + Time zone is used when converting between String and DateTime types, + when printing DateTime in text formats and parsing DateTime from text, + it is used in date and time related functions, if specific time zone was not passed as an argument. + + Time zone is specified as identifier from IANA time zone database, like UTC or Africa/Abidjan. + If not specified, system time zone at server startup is used. + + Please note, that server could display time zone alias instead of specified name. + Example: W-SU is an alias for Europe/Moscow and Zulu is an alias for UTC. + --> + <!-- <timezone>Europe/Moscow</timezone> --> + + <!-- You can specify umask here (see "man umask"). Server will apply it on startup. + Number is always parsed as octal. Default umask is 027 (other users cannot read logs, data files, etc; group can only read). + --> + <!-- <umask>022</umask> --> + + <!-- Configuration of clusters that could be used in Distributed tables. + https://clickhouse.yandex/docs/en/table_engines/distributed/ + --> + <remote_servers incl="clickhouse_remote_servers" > + <!-- Test only shard config for testing distributed storage --> + <test_shard_localhost> + <shard> + <replica> + <host>localhost</host> + <port>9000</port> + </replica> + </shard> + </test_shard_localhost> + <test_shard_localhost_secure> + <shard> + <replica> + <host>localhost</host> + <port>9440</port> + <secure>1</secure> + </replica> + </shard> + </test_shard_localhost_secure> + </remote_servers> + + + <!-- If element has 'incl' attribute, then for it's value will be used corresponding substitution from another file. + By default, path to file with substitutions is /etc/metrika.xml. It could be changed in config in 'include_from' element. + Values for substitutions are specified in /yandex/name_of_substitution elements in that file. + --> + <include_from>/etc/clickhouse-server/metrika.xml</include_from> + <!-- ZooKeeper is used to store metadata about replicas, when using Replicated tables. + Optional. If you don't use replicated tables, you could omit that. + + See https://clickhouse.yandex/docs/en/table_engines/replication/ + --> + <zookeeper incl="zookeeper-servers" optional="true" /> + + <!-- Substitutions for parameters of replicated tables. + Optional. If you don't use replicated tables, you could omit that. + + See https://clickhouse.yandex/docs/en/table_engines/replication/#creating-replicated-tables + --> + <macros incl="macros" optional="true" /> + + + <!-- Reloading interval for embedded dictionaries, in seconds. Default: 3600. --> + <builtin_dictionaries_reload_interval>3600</builtin_dictionaries_reload_interval> + + + <!-- Maximum session timeout, in seconds. Default: 3600. --> + <max_session_timeout>3600</max_session_timeout> + + <!-- Default session timeout, in seconds. Default: 60. --> + <default_session_timeout>60</default_session_timeout> + + <!-- Sending data to Graphite for monitoring. Several sections can be defined. --> + <!-- + interval - send every X second + root_path - prefix for keys + hostname_in_path - append hostname to root_path (default = true) + metrics - send data from table system.metrics + events - send data from table system.events + asynchronous_metrics - send data from table system.asynchronous_metrics + --> + <!-- + <graphite> + <host>localhost</host> + <port>42000</port> + <timeout>0.1</timeout> + <interval>60</interval> + <root_path>one_min</root_path> + <hostname_in_path>true</hostname_in_path> + + <metrics>true</metrics> + <events>true</events> + <asynchronous_metrics>true</asynchronous_metrics> + </graphite> + <graphite> + <host>localhost</host> + <port>42000</port> + <timeout>0.1</timeout> + <interval>1</interval> + <root_path>one_sec</root_path> + + <metrics>true</metrics> + <events>true</events> + <asynchronous_metrics>false</asynchronous_metrics> + </graphite> + --> + + + <!-- Query log. Used only for queries with setting log_queries = 1. --> + <query_log> + <!-- What table to insert data. If table is not exist, it will be created. + When query log structure is changed after system update, + then old table will be renamed and new table will be created automatically. + --> + <database>system</database> + <table>query_log</table> + <!-- + PARTITION BY expr https://clickhouse.yandex/docs/en/table_engines/custom_partitioning_key/ + Example: + event_date + toMonday(event_date) + toYYYYMM(event_date) + toStartOfHour(event_time) + --> + <partition_by>toYYYYMM(event_date)</partition_by> + <!-- Interval of flushing data. --> + <flush_interval_milliseconds>7500</flush_interval_milliseconds> + </query_log> + + + <!-- Uncomment if use part_log + <part_log> + <database>system</database> + <table>part_log</table> + + <flush_interval_milliseconds>7500</flush_interval_milliseconds> + </part_log> + --> + + + <!-- Parameters for embedded dictionaries, used in Yandex.Metrica. + See https://clickhouse.yandex/docs/en/dicts/internal_dicts/ + --> + + <!-- Path to file with region hierarchy. --> + <!-- <path_to_regions_hierarchy_file>/opt/geo/regions_hierarchy.txt</path_to_regions_hierarchy_file> --> + + <!-- Path to directory with files containing names of regions --> + <!-- <path_to_regions_names_files>/opt/geo/</path_to_regions_names_files> --> + + + <!-- Configuration of external dictionaries. See: + https://clickhouse.yandex/docs/en/dicts/external_dicts/ + --> + <dictionaries_config>*_dictionary.xml</dictionaries_config> + + <!-- Uncomment if you want data to be compressed 30-100% better. + Don't do that if you just started using ClickHouse. + --> + <compression incl="clickhouse_compression"> + <!-- + <!- - Set of variants. Checked in order. Last matching case wins. If nothing matches, lz4 will be used. - -> + <case> + + <!- - Conditions. All must be satisfied. Some conditions may be omitted. - -> + <min_part_size>10000000000</min_part_size> <!- - Min part size in bytes. - -> + <min_part_size_ratio>0.01</min_part_size_ratio> <!- - Min size of part relative to whole table size. - -> + + <!- - What compression method to use. - -> + <method>zstd</method> + </case> + --> + </compression> + + <!-- Allow to execute distributed DDL queries (CREATE, DROP, ALTER, RENAME) on cluster. + Works only if ZooKeeper is enabled. Comment it if such functionality isn't required. --> + <distributed_ddl> + <!-- Path in ZooKeeper to queue with DDL queries --> + <path>/clickhouse/task_queue/ddl</path> + + <!-- Settings from this profile will be used to execute DDL queries --> + <!-- <profile>default</profile> --> + </distributed_ddl> + + <!-- Settings to fine tune MergeTree tables. See documentation in source code, in MergeTreeSettings.h --> + <!-- + <merge_tree> + <max_suspicious_broken_parts>5</max_suspicious_broken_parts> + </merge_tree> + --> + + <!-- Protection from accidental DROP. + If size of a MergeTree table is greater than max_table_size_to_drop (in bytes) than table could not be dropped with any DROP query. + If you want do delete one table and don't want to restart clickhouse-server, you could create special file <clickhouse-path>/flags/force_drop_table and make DROP once. + By default max_table_size_to_drop is 50GB; max_table_size_to_drop=0 allows to DROP any tables. + The same for max_partition_size_to_drop. + Uncomment to disable protection. + --> + <!-- <max_table_size_to_drop>0</max_table_size_to_drop> --> + <!-- <max_partition_size_to_drop>0</max_partition_size_to_drop> --> + + <!-- Example of parameters for GraphiteMergeTree table engine --> + <graphite_rollup_example> + <pattern> + <regexp>click_cost</regexp> + <function>any</function> + <retention> + <age>0</age> + <precision>3600</precision> + </retention> + <retention> + <age>86400</age> + <precision>60</precision> + </retention> + </pattern> + <default> + <function>max</function> + <retention> + <age>0</age> + <precision>60</precision> + </retention> + <retention> + <age>3600</age> + <precision>300</precision> + </retention> + <retention> + <age>86400</age> + <precision>3600</precision> + </retention> + </default> + </graphite_rollup_example> + + <!-- Directory in <clickhouse-path> containing schema files for various input formats. + The directory will be created if it doesn't exist. + --> + <format_schema_path>/var/lib/clickhouse/format_schemas/</format_schema_path> + + <!-- Uncomment to disable ClickHouse internal DNS caching. --> + <!-- <disable_internal_dns_cache>1</disable_internal_dns_cache> --> +</yandex> + diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_metrika.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_metrika.xml new file mode 100644 index 00000000000..b58ffc34bc2 --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_metrika.xml @@ -0,0 +1,60 @@ +<yandex> + <clickhouse_remote_servers> + <cluster_1> + <shard> + <weight>1</weight> + <internal_replication>true</internal_replication> + <replica> + <host>clickhouse-01</host> + <port>9000</port> + </replica> + <replica> + <host>clickhouse-06</host> + <port>9000</port> + </replica> + </shard> + <shard> + <weight>1</weight> + <internal_replication>true</internal_replication> + <replica> + <host>clickhouse-02</host> + <port>9000</port> + </replica> + <replica> + <host>clickhouse-03</host> + <port>9000</port> + </replica> + </shard> + <shard> + <weight>1</weight> + <internal_replication>true</internal_replication> + + <replica> + <host>clickhouse-04</host> + <port>9000</port> + </replica> + <replica> + <host>clickhouse-05</host> + <port>9000</port> + </replica> + </shard> + </cluster_1> + </clickhouse_remote_servers> + <zookeeper-servers> + <node index="1"> + <host>clickhouse-zookeeper</host> + <port>2181</port> + </node> + </zookeeper-servers> + <networks> + <ip>::/0</ip> + </networks> + <clickhouse_compression> + <case> + <min_part_size>10000000000</min_part_size> + <min_part_size_ratio>0.01</min_part_size_ratio> + <method>lz4</method> + </case> + </clickhouse_compression> +</yandex> + diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-01.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-01.xml new file mode 100644 index 00000000000..75df1c5916e --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-01.xml @@ -0,0 +1,9 @@ +<yandex> + <macros> + <replica>clickhouse-01</replica> + <shard>01</shard> + <layer>01</layer> + <installation>data</installation> + <cluster>cluster_1</cluster> + </macros> +</yandex> diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-02.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-02.xml new file mode 100644 index 00000000000..67e4a545b30 --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-02.xml @@ -0,0 +1,9 @@ +<yandex> + <macros> + <replica>clickhouse-02</replica> + <shard>02</shard> + <layer>01</layer> + <installation>data</installation> + <cluster>cluster_1</cluster> + </macros> +</yandex> diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-03.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-03.xml new file mode 100644 index 00000000000..e9278191b80 --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-03.xml @@ -0,0 +1,9 @@ +<yandex> + <macros> + <replica>clickhouse-03</replica> + <shard>02</shard> + <layer>01</layer> + <installation>data</installation> + <cluster>cluster_1</cluster> + </macros> +</yandex> diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-04.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-04.xml new file mode 100644 index 00000000000..033c0ad1152 --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-04.xml @@ -0,0 +1,9 @@ +<yandex> + <macros> + <replica>clickhouse-04</replica> + <shard>03</shard> + <layer>01</layer> + <installation>data</installation> + <cluster>cluster_1</cluster> + </macros> +</yandex> diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-05.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-05.xml new file mode 100644 index 00000000000..c63314c5ace --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-05.xml @@ -0,0 +1,9 @@ +<yandex> + <macros> + <replica>clickhouse-05</replica> + <shard>03</shard> + <layer>01</layer> + <installation>data</installation> + <cluster>cluster_1</cluster> + </macros> +</yandex> diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-06.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-06.xml new file mode 100644 index 00000000000..4b01bda9948 --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-06.xml @@ -0,0 +1,9 @@ +<yandex> + <macros> + <replica>clickhouse-06</replica> + <shard>01</shard> + <layer>01</layer> + <installation>data</installation> + <cluster>cluster_1</cluster> + </macros> +</yandex> diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/users.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/users.xml new file mode 100644 index 00000000000..e1b8de78e37 --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/config/users.xml @@ -0,0 +1,117 @@ +<?xml version="1.0"?> +<yandex> + <!-- Profiles of settings. --> + <profiles> + <!-- Default settings. --> + <default> + <!-- Maximum memory usage for processing single query, in bytes. --> + <max_memory_usage>10000000000</max_memory_usage> + + <!-- Use cache of uncompressed blocks of data. Meaningful only for processing many of very short queries. --> + <use_uncompressed_cache>0</use_uncompressed_cache> + + <!-- How to choose between replicas during distributed query processing. + random - choose random replica from set of replicas with minimum number of errors + nearest_hostname - from set of replicas with minimum number of errors, choose replica + with minimum number of different symbols between replica's hostname and local hostname + (Hamming distance). + in_order - first live replica is chosen in specified order. + --> + <load_balancing>random</load_balancing> + </default> + + <!-- Profile that allows only read queries. --> + <readonly> + <readonly>1</readonly> + </readonly> + </profiles> + + <!-- Users and ACL. --> + <users> + <user1> + <password>123456</password> + <networks incl="networks" replace="replace"> + <ip>::/0</ip> + </networks> + <profile>default</profile> + <quota>default</quota> + </user1> + <!-- If user name was not specified, 'default' user is used. --> + <default> + <!-- Password could be specified in plaintext or in SHA256 (in hex format). + + If you want to specify password in plaintext (not recommended), place it in 'password' element. + Example: <password>qwerty</password>. + Password could be empty. + + If you want to specify SHA256, place it in 'password_sha256_hex' element. + Example: <password_sha256_hex>65e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5</password_sha256_hex> + + How to generate decent password: + Execute: PASSWORD=$(base64 < /dev/urandom | head -c8); echo "$PASSWORD"; echo -n "$PASSWORD" | sha256sum | tr -d '-' + In first line will be password and in second - corresponding SHA256. + --> + <password></password> + + <!-- List of networks with open access. + + To open access from everywhere, specify: + <ip>::/0</ip> + + To open access only from localhost, specify: + <ip>::1</ip> + <ip>127.0.0.1</ip> + + Each element of list has one of the following forms: + <ip> IP-address or network mask. Examples: 213.180.204.3 or 10.0.0.1/8 or 10.0.0.1/255.255.255.0 + 2a02:6b8::3 or 2a02:6b8::3/64 or 2a02:6b8::3/ffff:ffff:ffff:ffff::. + <host> Hostname. Example: server01.yandex.ru. + To check access, DNS query is performed, and all received addresses compared to peer address. + <host_regexp> Regular expression for host names. Example, ^server\d\d-\d\d-\d\.yandex\.ru$ + To check access, DNS PTR query is performed for peer address and then regexp is applied. + Then, for result of PTR query, another DNS query is performed and all received addresses compared to peer address. + Strongly recommended that regexp is ends with $ + All results of DNS requests are cached till server restart. + --> + <networks incl="networks" replace="replace"> + <ip>::/0</ip> + </networks> + + <!-- Settings profile for user. --> + <profile>default</profile> + + <!-- Quota for user. --> + <quota>default</quota> + </default> + + <!-- Example of user with readonly access. --> + <readonly> + <password></password> + <networks incl="networks" replace="replace"> + <ip>::1</ip> + <ip>127.0.0.1</ip> + </networks> + <profile>readonly</profile> + <quota>default</quota> + </readonly> + </users> + + <!-- Quotas. --> + <quotas> + <!-- Name of quota. --> + <default> + <!-- Limits for time interval. You could specify many intervals with different limits. --> + <interval> + <!-- Length of interval. --> + <duration>3600</duration> + + <!-- No limits. Just calculate resource usage for time interval. --> + <queries>0</queries> + <errors>0</errors> + <result_rows>0</result_rows> + <read_rows>0</read_rows> + <execution_time>0</execution_time> + </interval> + </default> + </quotas> +</yandex> diff --git a/crates/analytics/docs/clickhouse/cluster_setup/docker-compose.yml b/crates/analytics/docs/clickhouse/cluster_setup/docker-compose.yml new file mode 100644 index 00000000000..96d7618b47e --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/docker-compose.yml @@ -0,0 +1,198 @@ +version: '3' + +networks: + ckh_net: + +services: + clickhouse-zookeeper: + image: zookeeper + ports: + - "2181:2181" + - "2182:2182" + container_name: clickhouse-zookeeper + hostname: clickhouse-zookeeper + networks: + - ckh_net + + clickhouse-01: + image: clickhouse/clickhouse-server + hostname: clickhouse-01 + container_name: clickhouse-01 + networks: + - ckh_net + ports: + - 9001:9000 + - 8124:8123 + volumes: + - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml + - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml + - ./config/macros/macros-01.xml:/etc/clickhouse-server/config.d/macros.xml + - ./config/users.xml:/etc/clickhouse-server/users.xml + # - ./data/server-01:/var/lib/clickhouse + ulimits: + nofile: + soft: 262144 + hard: 262144 + depends_on: + - "clickhouse-zookeeper" + + clickhouse-02: + image: clickhouse/clickhouse-server + hostname: clickhouse-02 + container_name: clickhouse-02 + networks: + - ckh_net + ports: + - 9002:9000 + - 8125:8123 + volumes: + - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml + - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml + - ./config/macros/macros-02.xml:/etc/clickhouse-server/config.d/macros.xml + - ./config/users.xml:/etc/clickhouse-server/users.xml + # - ./data/server-02:/var/lib/clickhouse + ulimits: + nofile: + soft: 262144 + hard: 262144 + depends_on: + - "clickhouse-zookeeper" + + clickhouse-03: + image: clickhouse/clickhouse-server + hostname: clickhouse-03 + container_name: clickhouse-03 + networks: + - ckh_net + ports: + - 9003:9000 + - 8126:8123 + volumes: + - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml + - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml + - ./config/macros/macros-03.xml:/etc/clickhouse-server/config.d/macros.xml + - ./config/users.xml:/etc/clickhouse-server/users.xml + # - ./data/server-03:/var/lib/clickhouse + ulimits: + nofile: + soft: 262144 + hard: 262144 + depends_on: + - "clickhouse-zookeeper" + + clickhouse-04: + image: clickhouse/clickhouse-server + hostname: clickhouse-04 + container_name: clickhouse-04 + networks: + - ckh_net + ports: + - 9004:9000 + - 8127:8123 + volumes: + - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml + - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml + - ./config/macros/macros-04.xml:/etc/clickhouse-server/config.d/macros.xml + - ./config/users.xml:/etc/clickhouse-server/users.xml + # - ./data/server-04:/var/lib/clickhouse + ulimits: + nofile: + soft: 262144 + hard: 262144 + depends_on: + - "clickhouse-zookeeper" + + clickhouse-05: + image: clickhouse/clickhouse-server + hostname: clickhouse-05 + container_name: clickhouse-05 + networks: + - ckh_net + ports: + - 9005:9000 + - 8128:8123 + volumes: + - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml + - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml + - ./config/macros/macros-05.xml:/etc/clickhouse-server/config.d/macros.xml + - ./config/users.xml:/etc/clickhouse-server/users.xml + # - ./data/server-05:/var/lib/clickhouse + ulimits: + nofile: + soft: 262144 + hard: 262144 + depends_on: + - "clickhouse-zookeeper" + + clickhouse-06: + image: clickhouse/clickhouse-server + hostname: clickhouse-06 + container_name: clickhouse-06 + networks: + - ckh_net + ports: + - 9006:9000 + - 8129:8123 + volumes: + - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml + - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml + - ./config/macros/macros-06.xml:/etc/clickhouse-server/config.d/macros.xml + - ./config/users.xml:/etc/clickhouse-server/users.xml + # - ./data/server-06:/var/lib/clickhouse + ulimits: + nofile: + soft: 262144 + hard: 262144 + depends_on: + - "clickhouse-zookeeper" + + kafka0: + image: confluentinc/cp-kafka:7.0.5 + hostname: kafka0 + container_name: kafka0 + ports: + - 9092:9092 + - 9093 + - 9997 + - 29092 + environment: + KAFKA_BROKER_ID: 1 + KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,CONTROLLER:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT + KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka0:29092,PLAINTEXT_HOST://localhost:9092 + KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT + KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 + KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0 + KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1 + KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1 + KAFKA_PROCESS_ROLES: 'broker,controller' + KAFKA_NODE_ID: 1 + KAFKA_CONTROLLER_QUORUM_VOTERS: '1@kafka0:29093' + KAFKA_LISTENERS: 'PLAINTEXT://kafka0:29092,CONTROLLER://kafka0:29093,PLAINTEXT_HOST://0.0.0.0:9092' + KAFKA_CONTROLLER_LISTENER_NAMES: 'CONTROLLER' + KAFKA_LOG_DIRS: '/tmp/kraft-combined-logs' + JMX_PORT: 9997 + KAFKA_JMX_OPTS: -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=kafka0 -Dcom.sun.management.jmxremote.rmi.port=9997 + volumes: + - ./kafka-script.sh:/tmp/update_run.sh + command: "bash -c 'if [ ! -f /tmp/update_run.sh ]; then echo \"ERROR: Did you forget the update_run.sh file that came with this docker-compose.yml file?\" && exit 1 ; else /tmp/update_run.sh && /etc/confluent/docker/run ; fi'" + networks: + ckh_net: + aliases: + - hyper-c1-kafka-brokers.kafka-cluster.svc.cluster.local + + + # Kafka UI for debugging kafka queues + kafka-ui: + container_name: kafka-ui + image: provectuslabs/kafka-ui:latest + ports: + - 8090:8080 + depends_on: + - kafka0 + networks: + - ckh_net + environment: + KAFKA_CLUSTERS_0_NAME: local + KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka0:29092 + KAFKA_CLUSTERS_0_JMXPORT: 9997 + diff --git a/crates/analytics/docs/clickhouse/cluster_setup/kafka-script.sh b/crates/analytics/docs/clickhouse/cluster_setup/kafka-script.sh new file mode 100755 index 00000000000..023c832b4e1 --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/kafka-script.sh @@ -0,0 +1,11 @@ +# This script is required to run kafka cluster (without zookeeper) +#!/bin/sh + +# Docker workaround: Remove check for KAFKA_ZOOKEEPER_CONNECT parameter +sed -i '/KAFKA_ZOOKEEPER_CONNECT/d' /etc/confluent/docker/configure + +# Docker workaround: Ignore cub zk-ready +sed -i 's/cub zk-ready/echo ignore zk-ready/' /etc/confluent/docker/ensure + +# KRaft required step: Format the storage directory with a new cluster ID +echo "kafka-storage format --ignore-formatted -t $(kafka-storage random-uuid) -c /etc/kafka/kafka.properties" >> /etc/confluent/docker/ensure \ No newline at end of file diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql new file mode 100644 index 00000000000..0fe194a0e67 --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql @@ -0,0 +1,237 @@ +CREATE TABLE hyperswitch.api_events_queue on cluster '{cluster}' ( + `merchant_id` String, + `payment_id` Nullable(String), + `refund_id` Nullable(String), + `payment_method_id` Nullable(String), + `payment_method` Nullable(String), + `payment_method_type` Nullable(String), + `customer_id` Nullable(String), + `user_id` Nullable(String), + `request_id` String, + `flow_type` LowCardinality(String), + `api_name` LowCardinality(String), + `request` String, + `response` String, + `status_code` UInt32, + `url_path` LowCardinality(Nullable(String)), + `event_type` LowCardinality(Nullable(String)), + `created_at` DateTime CODEC(T64, LZ4), + `latency` Nullable(UInt128), + `user_agent` Nullable(String), + `ip_addr` Nullable(String) +) ENGINE = Kafka SETTINGS kafka_broker_list = 'hyper-c1-kafka-brokers.kafka-cluster.svc.cluster.local:9092', +kafka_topic_list = 'hyperswitch-api-log-events', +kafka_group_name = 'hyper-c1', +kafka_format = 'JSONEachRow', +kafka_handle_error_mode = 'stream'; + + +CREATE TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ( + `merchant_id` String, + `payment_id` Nullable(String), + `refund_id` Nullable(String), + `payment_method_id` Nullable(String), + `payment_method` Nullable(String), + `payment_method_type` Nullable(String), + `customer_id` Nullable(String), + `user_id` Nullable(String), + `request_id` Nullable(String), + `flow_type` LowCardinality(String), + `api_name` LowCardinality(String), + `request` String, + `response` String, + `status_code` UInt32, + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `latency` Nullable(UInt128), + `user_agent` Nullable(String), + `ip_addr` Nullable(String), + INDEX flowIndex flow_type TYPE bloom_filter GRANULARITY 1, + INDEX apiIndex api_name TYPE bloom_filter GRANULARITY 1, + INDEX statusIndex status_code TYPE bloom_filter GRANULARITY 1 +) ENGINE = ReplicatedMergeTree( + '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/api_events_clustered', + '{replica}' +) +PARTITION BY toStartOfDay(created_at) +ORDER BY + (created_at, merchant_id, flow_type, status_code, api_name) +TTL created_at + toIntervalMonth(6) +; + + +CREATE TABLE hyperswitch.api_events_dist on cluster '{cluster}' ( + `merchant_id` String, + `payment_id` Nullable(String), + `refund_id` Nullable(String), + `payment_method_id` Nullable(String), + `payment_method` Nullable(String), + `payment_method_type` Nullable(String), + `customer_id` Nullable(String), + `user_id` Nullable(String), + `request_id` Nullable(String), + `flow_type` LowCardinality(String), + `api_name` LowCardinality(String), + `request` String, + `response` String, + `status_code` UInt32, + `url_path` LowCardinality(Nullable(String)), + `event_type` LowCardinality(Nullable(String)), + `inserted_at` DateTime64(3), + `created_at` DateTime64(3), + `latency` Nullable(UInt128), + `user_agent` Nullable(String), + `ip_addr` Nullable(String) +) ENGINE = Distributed('{cluster}', 'hyperswitch', 'api_events_clustered', rand()); + +CREATE MATERIALIZED VIEW hyperswitch.api_events_mv on cluster '{cluster}' TO hyperswitch.api_events_dist ( + `merchant_id` String, + `payment_id` Nullable(String), + `refund_id` Nullable(String), + `payment_method_id` Nullable(String), + `payment_method` Nullable(String), + `payment_method_type` Nullable(String), + `customer_id` Nullable(String), + `user_id` Nullable(String), + `request_id` Nullable(String), + `flow_type` LowCardinality(String), + `api_name` LowCardinality(String), + `request` String, + `response` String, + `status_code` UInt32, + `url_path` LowCardinality(Nullable(String)), + `event_type` LowCardinality(Nullable(String)), + `inserted_at` DateTime64(3), + `created_at` DateTime64(3), + `latency` Nullable(UInt128), + `user_agent` Nullable(String), + `ip_addr` Nullable(String) +) AS +SELECT + merchant_id, + payment_id, + refund_id, + payment_method_id, + payment_method, + payment_method_type, + customer_id, + user_id, + request_id, + flow_type, + api_name, + request, + response, + status_code, + url_path, + event_type, + now() as inserted_at, + created_at, + latency, + user_agent, + ip_addr +FROM + hyperswitch.api_events_queue +WHERE length(_error) = 0; + + +CREATE MATERIALIZED VIEW hyperswitch.api_events_parse_errors on cluster '{cluster}' +( + `topic` String, + `partition` Int64, + `offset` Int64, + `raw` String, + `error` String +) +ENGINE = MergeTree +ORDER BY (topic, partition, offset) +SETTINGS index_granularity = 8192 AS +SELECT + _topic AS topic, + _partition AS partition, + _offset AS offset, + _raw_message AS raw, + _error AS error +FROM hyperswitch.api_events_queue +WHERE length(_error) > 0 +; + + +ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `url_path` LowCardinality(Nullable(String)); +ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `event_type` LowCardinality(Nullable(String)); + + +CREATE TABLE hyperswitch.api_audit_log ON CLUSTER '{cluster}' ( + `merchant_id` LowCardinality(String), + `payment_id` String, + `refund_id` Nullable(String), + `payment_method_id` Nullable(String), + `payment_method` Nullable(String), + `payment_method_type` Nullable(String), + `user_id` Nullable(String), + `request_id` Nullable(String), + `flow_type` LowCardinality(String), + `api_name` LowCardinality(String), + `request` String, + `response` String, + `status_code` UInt32, + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `latency` Nullable(UInt128), + `user_agent` Nullable(String), + `ip_addr` Nullable(String), + `url_path` LowCardinality(Nullable(String)), + `event_type` LowCardinality(Nullable(String)), + `customer_id` LowCardinality(Nullable(String)) +) ENGINE = ReplicatedMergeTree( '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/api_audit_log', '{replica}' ) PARTITION BY merchant_id +ORDER BY (merchant_id, payment_id) +TTL created_at + toIntervalMonth(18) +SETTINGS index_granularity = 8192 + + +CREATE MATERIALIZED VIEW hyperswitch.api_audit_log_mv ON CLUSTER `{cluster}` TO hyperswitch.api_audit_log( + `merchant_id` LowCardinality(String), + `payment_id` String, + `refund_id` Nullable(String), + `payment_method_id` Nullable(String), + `payment_method` Nullable(String), + `payment_method_type` Nullable(String), + `customer_id` Nullable(String), + `user_id` Nullable(String), + `request_id` Nullable(String), + `flow_type` LowCardinality(String), + `api_name` LowCardinality(String), + `request` String, + `response` String, + `status_code` UInt32, + `url_path` LowCardinality(Nullable(String)), + `event_type` LowCardinality(Nullable(String)), + `inserted_at` DateTime64(3), + `created_at` DateTime64(3), + `latency` Nullable(UInt128), + `user_agent` Nullable(String), + `ip_addr` Nullable(String) +) AS +SELECT + merchant_id, + multiIf(payment_id IS NULL, '', payment_id) AS payment_id, + refund_id, + payment_method_id, + payment_method, + payment_method_type, + customer_id, + user_id, + request_id, + flow_type, + api_name, + request, + response, + status_code, + url_path, + api_event_type AS event_type, + now() AS inserted_at, + created_at, + latency, + user_agent, + ip_addr +FROM hyperswitch.api_events_queue +WHERE length(_error) = 0 \ No newline at end of file diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_attempts.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_attempts.sql new file mode 100644 index 00000000000..3a6281ae905 --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_attempts.sql @@ -0,0 +1,217 @@ +CREATE TABLE hyperswitch.payment_attempt_queue on cluster '{cluster}' ( + `payment_id` String, + `merchant_id` String, + `attempt_id` String, + `status` LowCardinality(String), + `amount` Nullable(UInt32), + `currency` LowCardinality(Nullable(String)), + `connector` LowCardinality(Nullable(String)), + `save_to_locker` Nullable(Bool), + `error_message` Nullable(String), + `offer_amount` Nullable(UInt32), + `surcharge_amount` Nullable(UInt32), + `tax_amount` Nullable(UInt32), + `payment_method_id` Nullable(String), + `payment_method` LowCardinality(Nullable(String)), + `payment_method_type` LowCardinality(Nullable(String)), + `connector_transaction_id` Nullable(String), + `capture_method` LowCardinality(Nullable(String)), + `capture_on` Nullable(DateTime) CODEC(T64, LZ4), + `confirm` Bool, + `authentication_type` LowCardinality(Nullable(String)), + `cancellation_reason` Nullable(String), + `amount_to_capture` Nullable(UInt32), + `mandate_id` Nullable(String), + `browser_info` Nullable(String), + `error_code` Nullable(String), + `connector_metadata` Nullable(String), + `payment_experience` Nullable(String), + `created_at` DateTime CODEC(T64, LZ4), + `last_synced` Nullable(DateTime) CODEC(T64, LZ4), + `modified_at` DateTime CODEC(T64, LZ4), + `sign_flag` Int8 +) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', +kafka_topic_list = 'hyperswitch-payment-attempt-events', +kafka_group_name = 'hyper-c1', +kafka_format = 'JSONEachRow', +kafka_handle_error_mode = 'stream'; + + +CREATE TABLE hyperswitch.payment_attempt_dist on cluster '{cluster}' ( + `payment_id` String, + `merchant_id` String, + `attempt_id` String, + `status` LowCardinality(String), + `amount` Nullable(UInt32), + `currency` LowCardinality(Nullable(String)), + `connector` LowCardinality(Nullable(String)), + `save_to_locker` Nullable(Bool), + `error_message` Nullable(String), + `offer_amount` Nullable(UInt32), + `surcharge_amount` Nullable(UInt32), + `tax_amount` Nullable(UInt32), + `payment_method_id` Nullable(String), + `payment_method` LowCardinality(Nullable(String)), + `payment_method_type` LowCardinality(Nullable(String)), + `connector_transaction_id` Nullable(String), + `capture_method` Nullable(String), + `capture_on` Nullable(DateTime) CODEC(T64, LZ4), + `confirm` Bool, + `authentication_type` LowCardinality(Nullable(String)), + `cancellation_reason` Nullable(String), + `amount_to_capture` Nullable(UInt32), + `mandate_id` Nullable(String), + `browser_info` Nullable(String), + `error_code` Nullable(String), + `connector_metadata` Nullable(String), + `payment_experience` Nullable(String), + `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `last_synced` Nullable(DateTime) CODEC(T64, LZ4), + `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `sign_flag` Int8 +) ENGINE = Distributed('{cluster}', 'hyperswitch', 'payment_attempt_clustered', cityHash64(attempt_id)); + + + +CREATE MATERIALIZED VIEW hyperswitch.payment_attempt_mv on cluster '{cluster}' TO hyperswitch.payment_attempt_dist ( + `payment_id` String, + `merchant_id` String, + `attempt_id` String, + `status` LowCardinality(String), + `amount` Nullable(UInt32), + `currency` LowCardinality(Nullable(String)), + `connector` LowCardinality(Nullable(String)), + `save_to_locker` Nullable(Bool), + `error_message` Nullable(String), + `offer_amount` Nullable(UInt32), + `surcharge_amount` Nullable(UInt32), + `tax_amount` Nullable(UInt32), + `payment_method_id` Nullable(String), + `payment_method` LowCardinality(Nullable(String)), + `payment_method_type` LowCardinality(Nullable(String)), + `connector_transaction_id` Nullable(String), + `capture_method` Nullable(String), + `confirm` Bool, + `authentication_type` LowCardinality(Nullable(String)), + `cancellation_reason` Nullable(String), + `amount_to_capture` Nullable(UInt32), + `mandate_id` Nullable(String), + `browser_info` Nullable(String), + `error_code` Nullable(String), + `connector_metadata` Nullable(String), + `payment_experience` Nullable(String), + `created_at` DateTime64(3), + `capture_on` Nullable(DateTime64(3)), + `last_synced` Nullable(DateTime64(3)), + `modified_at` DateTime64(3), + `inserted_at` DateTime64(3), + `sign_flag` Int8 +) AS +SELECT + payment_id, + merchant_id, + attempt_id, + status, + amount, + currency, + connector, + save_to_locker, + error_message, + offer_amount, + surcharge_amount, + tax_amount, + payment_method_id, + payment_method, + payment_method_type, + connector_transaction_id, + capture_method, + confirm, + authentication_type, + cancellation_reason, + amount_to_capture, + mandate_id, + browser_info, + error_code, + connector_metadata, + payment_experience, + created_at, + capture_on, + last_synced, + modified_at, + now() as inserted_at, + sign_flag +FROM + hyperswitch.payment_attempt_queue +WHERE length(_error) = 0; + + +CREATE TABLE hyperswitch.payment_attempt_clustered on cluster '{cluster}' ( + `payment_id` String, + `merchant_id` String, + `attempt_id` String, + `status` LowCardinality(String), + `amount` Nullable(UInt32), + `currency` LowCardinality(Nullable(String)), + `connector` LowCardinality(Nullable(String)), + `save_to_locker` Nullable(Bool), + `error_message` Nullable(String), + `offer_amount` Nullable(UInt32), + `surcharge_amount` Nullable(UInt32), + `tax_amount` Nullable(UInt32), + `payment_method_id` Nullable(String), + `payment_method` LowCardinality(Nullable(String)), + `payment_method_type` LowCardinality(Nullable(String)), + `connector_transaction_id` Nullable(String), + `capture_method` Nullable(String), + `capture_on` Nullable(DateTime) CODEC(T64, LZ4), + `confirm` Bool, + `authentication_type` LowCardinality(Nullable(String)), + `cancellation_reason` Nullable(String), + `amount_to_capture` Nullable(UInt32), + `mandate_id` Nullable(String), + `browser_info` Nullable(String), + `error_code` Nullable(String), + `connector_metadata` Nullable(String), + `payment_experience` Nullable(String), + `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `last_synced` Nullable(DateTime) CODEC(T64, LZ4), + `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `sign_flag` Int8, + INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1, + INDEX paymentMethodIndex payment_method TYPE bloom_filter GRANULARITY 1, + INDEX authenticationTypeIndex authentication_type TYPE bloom_filter GRANULARITY 1, + INDEX currencyIndex currency TYPE bloom_filter GRANULARITY 1, + INDEX statusIndex status TYPE bloom_filter GRANULARITY 1 +) ENGINE = ReplicatedCollapsingMergeTree( + '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/payment_attempt_clustered', + '{replica}', + sign_flag +) +PARTITION BY toStartOfDay(created_at) +ORDER BY + (created_at, merchant_id, attempt_id) +TTL created_at + toIntervalMonth(6) +; + +CREATE MATERIALIZED VIEW hyperswitch.payment_attempt_parse_errors on cluster '{cluster}' +( + `topic` String, + `partition` Int64, + `offset` Int64, + `raw` String, + `error` String +) +ENGINE = MergeTree +ORDER BY (topic, partition, offset) +SETTINGS index_granularity = 8192 AS +SELECT + _topic AS topic, + _partition AS partition, + _offset AS offset, + _raw_message AS raw, + _error AS error +FROM hyperswitch.payment_attempt_queue +WHERE length(_error) > 0 +; \ No newline at end of file diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_intents.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_intents.sql new file mode 100644 index 00000000000..eb2d83140e9 --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_intents.sql @@ -0,0 +1,165 @@ +CREATE TABLE hyperswitch.payment_intents_queue on cluster '{cluster}' ( + `payment_id` String, + `merchant_id` String, + `status` LowCardinality(String), + `amount` UInt32, + `currency` LowCardinality(Nullable(String)), + `amount_captured` Nullable(UInt32), + `customer_id` Nullable(String), + `description` Nullable(String), + `return_url` Nullable(String), + `connector_id` LowCardinality(Nullable(String)), + `statement_descriptor_name` Nullable(String), + `statement_descriptor_suffix` Nullable(String), + `setup_future_usage` LowCardinality(Nullable(String)), + `off_session` Nullable(Bool), + `client_secret` Nullable(String), + `active_attempt_id` String, + `business_country` String, + `business_label` String, + `modified_at` DateTime, + `created_at` DateTime, + `last_synced` Nullable(DateTime) CODEC(T64, LZ4), + `sign_flag` Int8 +) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', +kafka_topic_list = 'hyperswitch-payment-intent-events', +kafka_group_name = 'hyper-c1', +kafka_format = 'JSONEachRow', +kafka_handle_error_mode = 'stream'; + +CREATE TABLE hyperswitch.payment_intents_dist on cluster '{cluster}' ( + `payment_id` String, + `merchant_id` String, + `status` LowCardinality(String), + `amount` UInt32, + `currency` LowCardinality(Nullable(String)), + `amount_captured` Nullable(UInt32), + `customer_id` Nullable(String), + `description` Nullable(String), + `return_url` Nullable(String), + `connector_id` LowCardinality(Nullable(String)), + `statement_descriptor_name` Nullable(String), + `statement_descriptor_suffix` Nullable(String), + `setup_future_usage` LowCardinality(Nullable(String)), + `off_session` Nullable(Bool), + `client_secret` Nullable(String), + `active_attempt_id` String, + `business_country` LowCardinality(String), + `business_label` String, + `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `last_synced` Nullable(DateTime) CODEC(T64, LZ4), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `sign_flag` Int8 +) ENGINE = Distributed('{cluster}', 'hyperswitch', 'payment_intents_clustered', cityHash64(payment_id)); + +CREATE TABLE hyperswitch.payment_intents_clustered on cluster '{cluster}' ( + `payment_id` String, + `merchant_id` String, + `status` LowCardinality(String), + `amount` UInt32, + `currency` LowCardinality(Nullable(String)), + `amount_captured` Nullable(UInt32), + `customer_id` Nullable(String), + `description` Nullable(String), + `return_url` Nullable(String), + `connector_id` LowCardinality(Nullable(String)), + `statement_descriptor_name` Nullable(String), + `statement_descriptor_suffix` Nullable(String), + `setup_future_usage` LowCardinality(Nullable(String)), + `off_session` Nullable(Bool), + `client_secret` Nullable(String), + `active_attempt_id` String, + `business_country` LowCardinality(String), + `business_label` String, + `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `last_synced` Nullable(DateTime) CODEC(T64, LZ4), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `sign_flag` Int8, + INDEX connectorIndex connector_id TYPE bloom_filter GRANULARITY 1, + INDEX currencyIndex currency TYPE bloom_filter GRANULARITY 1, + INDEX statusIndex status TYPE bloom_filter GRANULARITY 1 +) ENGINE = ReplicatedCollapsingMergeTree( + '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/payment_intents_clustered', + '{replica}', + sign_flag +) +PARTITION BY toStartOfDay(created_at) +ORDER BY + (created_at, merchant_id, payment_id) +TTL created_at + toIntervalMonth(6) +; + +CREATE MATERIALIZED VIEW hyperswitch.payment_intent_mv on cluster '{cluster}' TO hyperswitch.payment_intents_dist ( + `payment_id` String, + `merchant_id` String, + `status` LowCardinality(String), + `amount` UInt32, + `currency` LowCardinality(Nullable(String)), + `amount_captured` Nullable(UInt32), + `customer_id` Nullable(String), + `description` Nullable(String), + `return_url` Nullable(String), + `connector_id` LowCardinality(Nullable(String)), + `statement_descriptor_name` Nullable(String), + `statement_descriptor_suffix` Nullable(String), + `setup_future_usage` LowCardinality(Nullable(String)), + `off_session` Nullable(Bool), + `client_secret` Nullable(String), + `active_attempt_id` String, + `business_country` LowCardinality(String), + `business_label` String, + `modified_at` DateTime64(3), + `created_at` DateTime64(3), + `last_synced` Nullable(DateTime64(3)), + `inserted_at` DateTime64(3), + `sign_flag` Int8 +) AS +SELECT + payment_id, + merchant_id, + status, + amount, + currency, + amount_captured, + customer_id, + description, + return_url, + connector_id, + statement_descriptor_name, + statement_descriptor_suffix, + setup_future_usage, + off_session, + client_secret, + active_attempt_id, + business_country, + business_label, + modified_at, + created_at, + last_synced, + now() as inserted_at, + sign_flag +FROM hyperswitch.payment_intents_queue +WHERE length(_error) = 0; + +CREATE MATERIALIZED VIEW hyperswitch.payment_intent_parse_errors on cluster '{cluster}' +( + `topic` String, + `partition` Int64, + `offset` Int64, + `raw` String, + `error` String +) +ENGINE = MergeTree +ORDER BY (topic, partition, offset) +SETTINGS index_granularity = 8192 AS +SELECT + _topic AS topic, + _partition AS partition, + _offset AS offset, + _raw_message AS raw, + _error AS error +FROM hyperswitch.payment_intents_queue +WHERE length(_error) > 0 +; diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/refund_analytics.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/refund_analytics.sql new file mode 100644 index 00000000000..bf5f6e0e240 --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/scripts/refund_analytics.sql @@ -0,0 +1,173 @@ +CREATE TABLE hyperswitch.refund_queue on cluster '{cluster}' ( + `internal_reference_id` String, + `refund_id` String, + `payment_id` String, + `merchant_id` String, + `connector_transaction_id` String, + `connector` LowCardinality(Nullable(String)), + `connector_refund_id` Nullable(String), + `external_reference_id` Nullable(String), + `refund_type` LowCardinality(String), + `total_amount` Nullable(UInt32), + `currency` LowCardinality(String), + `refund_amount` Nullable(UInt32), + `refund_status` LowCardinality(String), + `sent_to_gateway` Bool, + `refund_error_message` Nullable(String), + `refund_arn` Nullable(String), + `attempt_id` String, + `description` Nullable(String), + `refund_reason` Nullable(String), + `refund_error_code` Nullable(String), + `created_at` DateTime, + `modified_at` DateTime, + `sign_flag` Int8 +) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', +kafka_topic_list = 'hyperswitch-refund-events', +kafka_group_name = 'hyper-c1', +kafka_format = 'JSONEachRow', +kafka_handle_error_mode = 'stream'; + +CREATE TABLE hyperswitch.refund_dist on cluster '{cluster}' ( + `internal_reference_id` String, + `refund_id` String, + `payment_id` String, + `merchant_id` String, + `connector_transaction_id` String, + `connector` LowCardinality(Nullable(String)), + `connector_refund_id` Nullable(String), + `external_reference_id` Nullable(String), + `refund_type` LowCardinality(String), + `total_amount` Nullable(UInt32), + `currency` LowCardinality(String), + `refund_amount` Nullable(UInt32), + `refund_status` LowCardinality(String), + `sent_to_gateway` Bool, + `refund_error_message` Nullable(String), + `refund_arn` Nullable(String), + `attempt_id` String, + `description` Nullable(String), + `refund_reason` Nullable(String), + `refund_error_code` Nullable(String), + `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `sign_flag` Int8 +) ENGINE = Distributed('{cluster}', 'hyperswitch', 'refund_clustered', cityHash64(refund_id)); + + + +CREATE TABLE hyperswitch.refund_clustered on cluster '{cluster}' ( + `internal_reference_id` String, + `refund_id` String, + `payment_id` String, + `merchant_id` String, + `connector_transaction_id` String, + `connector` LowCardinality(Nullable(String)), + `connector_refund_id` Nullable(String), + `external_reference_id` Nullable(String), + `refund_type` LowCardinality(String), + `total_amount` Nullable(UInt32), + `currency` LowCardinality(String), + `refund_amount` Nullable(UInt32), + `refund_status` LowCardinality(String), + `sent_to_gateway` Bool, + `refund_error_message` Nullable(String), + `refund_arn` Nullable(String), + `attempt_id` String, + `description` Nullable(String), + `refund_reason` Nullable(String), + `refund_error_code` Nullable(String), + `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `sign_flag` Int8, + INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1, + INDEX refundTypeIndex refund_type TYPE bloom_filter GRANULARITY 1, + INDEX currencyIndex currency TYPE bloom_filter GRANULARITY 1, + INDEX statusIndex refund_status TYPE bloom_filter GRANULARITY 1 +) ENGINE = ReplicatedCollapsingMergeTree( + '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/refund_clustered', + '{replica}', + sign_flag +) +PARTITION BY toStartOfDay(created_at) +ORDER BY + (created_at, merchant_id, refund_id) +TTL created_at + toIntervalMonth(6) +; + +CREATE MATERIALIZED VIEW hyperswitch.kafka_parse_refund on cluster '{cluster}' TO hyperswitch.refund_dist ( + `internal_reference_id` String, + `refund_id` String, + `payment_id` String, + `merchant_id` String, + `connector_transaction_id` String, + `connector` LowCardinality(Nullable(String)), + `connector_refund_id` Nullable(String), + `external_reference_id` Nullable(String), + `refund_type` LowCardinality(String), + `total_amount` Nullable(UInt32), + `currency` LowCardinality(String), + `refund_amount` Nullable(UInt32), + `refund_status` LowCardinality(String), + `sent_to_gateway` Bool, + `refund_error_message` Nullable(String), + `refund_arn` Nullable(String), + `attempt_id` String, + `description` Nullable(String), + `refund_reason` Nullable(String), + `refund_error_code` Nullable(String), + `created_at` DateTime64(3), + `modified_at` DateTime64(3), + `inserted_at` DateTime64(3), + `sign_flag` Int8 +) AS +SELECT + internal_reference_id, + refund_id, + payment_id, + merchant_id, + connector_transaction_id, + connector, + connector_refund_id, + external_reference_id, + refund_type, + total_amount, + currency, + refund_amount, + refund_status, + sent_to_gateway, + refund_error_message, + refund_arn, + attempt_id, + description, + refund_reason, + refund_error_code, + created_at, + modified_at, + now() as inserted_at, + sign_flag +FROM hyperswitch.refund_queue +WHERE length(_error) = 0; + +CREATE MATERIALIZED VIEW hyperswitch.refund_parse_errors on cluster '{cluster}' +( + `topic` String, + `partition` Int64, + `offset` Int64, + `raw` String, + `error` String +) +ENGINE = MergeTree +ORDER BY (topic, partition, offset) +SETTINGS index_granularity = 8192 AS +SELECT + _topic AS topic, + _partition AS partition, + _offset AS offset, + _raw_message AS raw, + _error AS error +FROM hyperswitch.refund_queue +WHERE length(_error) > 0 +; \ No newline at end of file diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/sdk_events.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/sdk_events.sql new file mode 100644 index 00000000000..37766392bc7 --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/scripts/sdk_events.sql @@ -0,0 +1,156 @@ +CREATE TABLE hyperswitch.sdk_events_queue on cluster '{cluster}' ( + `payment_id` Nullable(String), + `merchant_id` String, + `remote_ip` Nullable(String), + `log_type` LowCardinality(Nullable(String)), + `event_name` LowCardinality(Nullable(String)), + `first_event` LowCardinality(Nullable(String)), + `latency` Nullable(UInt32), + `timestamp` String, + `browser_name` LowCardinality(Nullable(String)), + `browser_version` Nullable(String), + `platform` LowCardinality(Nullable(String)), + `source` LowCardinality(Nullable(String)), + `category` LowCardinality(Nullable(String)), + `version` LowCardinality(Nullable(String)), + `value` Nullable(String), + `component` LowCardinality(Nullable(String)), + `payment_method` LowCardinality(Nullable(String)), + `payment_experience` LowCardinality(Nullable(String)) +) ENGINE = Kafka SETTINGS + kafka_broker_list = 'hyper-c1-kafka-brokers.kafka-cluster.svc.cluster.local:9092', + kafka_topic_list = 'hyper-sdk-logs', + kafka_group_name = 'hyper-c1', + kafka_format = 'JSONEachRow', + kafka_handle_error_mode = 'stream'; + +CREATE TABLE hyperswitch.sdk_events_clustered on cluster '{cluster}' ( + `payment_id` Nullable(String), + `merchant_id` String, + `remote_ip` Nullable(String), + `log_type` LowCardinality(Nullable(String)), + `event_name` LowCardinality(Nullable(String)), + `first_event` Bool DEFAULT 1, + `browser_name` LowCardinality(Nullable(String)), + `browser_version` Nullable(String), + `platform` LowCardinality(Nullable(String)), + `source` LowCardinality(Nullable(String)), + `category` LowCardinality(Nullable(String)), + `version` LowCardinality(Nullable(String)), + `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` DateTime64(3) DEFAULT now64() CODEC(T64, LZ4), + `latency` Nullable(UInt32) DEFAULT 0, + INDEX paymentMethodIndex payment_method TYPE bloom_filter GRANULARITY 1, + INDEX eventIndex event_name TYPE bloom_filter GRANULARITY 1, + INDEX platformIndex platform TYPE bloom_filter GRANULARITY 1, + INDEX logTypeIndex log_type TYPE bloom_filter GRANULARITY 1, + INDEX categoryIndex category TYPE bloom_filter GRANULARITY 1, + INDEX sourceIndex source TYPE bloom_filter GRANULARITY 1, + INDEX componentIndex component TYPE bloom_filter GRANULARITY 1, + INDEX firstEventIndex first_event TYPE bloom_filter GRANULARITY 1 +) ENGINE = ReplicatedMergeTree( + '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/sdk_events_clustered', '{replica}' +) +PARTITION BY + toStartOfDay(created_at) +ORDER BY + (created_at, merchant_id) +TTL + toDateTime(created_at) + toIntervalMonth(6) +SETTINGS + index_granularity = 8192 +; + +CREATE TABLE hyperswitch.sdk_events_dist on cluster '{cluster}' ( + `payment_id` Nullable(String), + `merchant_id` String, + `remote_ip` Nullable(String), + `log_type` LowCardinality(Nullable(String)), + `event_name` LowCardinality(Nullable(String)), + `first_event` Bool DEFAULT 1, + `browser_name` LowCardinality(Nullable(String)), + `browser_version` Nullable(String), + `platform` LowCardinality(Nullable(String)), + `source` LowCardinality(Nullable(String)), + `category` LowCardinality(Nullable(String)), + `version` LowCardinality(Nullable(String)), + `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` DateTime64(3) DEFAULT now64() CODEC(T64, LZ4), + `latency` Nullable(UInt32) DEFAULT 0 +) ENGINE = Distributed( + '{cluster}', 'hyperswitch', 'sdk_events_clustered', rand() +); + +CREATE MATERIALIZED VIEW hyperswitch.sdk_events_mv on cluster '{cluster}' TO hyperswitch.sdk_events_dist ( + `payment_id` Nullable(String), + `merchant_id` String, + `remote_ip` Nullable(String), + `log_type` LowCardinality(Nullable(String)), + `event_name` LowCardinality(Nullable(String)), + `first_event` Bool, + `latency` Nullable(UInt32), + `browser_name` LowCardinality(Nullable(String)), + `browser_version` Nullable(String), + `platform` LowCardinality(Nullable(String)), + `source` LowCardinality(Nullable(String)), + `category` LowCardinality(Nullable(String)), + `version` LowCardinality(Nullable(String)), + `value` Nullable(String), + `component` LowCardinality(Nullable(String)), + `payment_method` LowCardinality(Nullable(String)), + `payment_experience` LowCardinality(Nullable(String)), + `created_at` DateTime64(3) +) AS +SELECT + payment_id, + merchant_id, + remote_ip, + log_type, + event_name, + multiIf(first_event = 'true', 1, 0) AS first_event, + latency, + browser_name, + browser_version, + platform, + source, + category, + version, + value, + component, + payment_method, + payment_experience, + toDateTime64(timestamp, 3) AS created_at +FROM + hyperswitch.sdk_events_queue +WHERE length(_error) = 0 +; + +CREATE MATERIALIZED VIEW hyperswitch.sdk_parse_errors on cluster '{cluster}' ( + `topic` String, + `partition` Int64, + `offset` Int64, + `raw` String, + `error` String +) ENGINE = MergeTree + ORDER BY (topic, partition, offset) +SETTINGS + index_granularity = 8192 AS +SELECT + _topic AS topic, + _partition AS partition, + _offset AS offset, + _raw_message AS raw, + _error AS error +FROM + hyperswitch.sdk_events_queue +WHERE + length(_error) > 0 +; diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/seed_scripts.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/seed_scripts.sql new file mode 100644 index 00000000000..202b94ac604 --- /dev/null +++ b/crates/analytics/docs/clickhouse/cluster_setup/scripts/seed_scripts.sql @@ -0,0 +1 @@ +create database hyperswitch on cluster '{cluster}'; \ No newline at end of file diff --git a/crates/analytics/docs/clickhouse/scripts/api_events_v2.sql b/crates/analytics/docs/clickhouse/scripts/api_events_v2.sql new file mode 100644 index 00000000000..b41a75fe67e --- /dev/null +++ b/crates/analytics/docs/clickhouse/scripts/api_events_v2.sql @@ -0,0 +1,134 @@ +CREATE TABLE api_events_v2_queue ( + `merchant_id` String, + `payment_id` Nullable(String), + `refund_id` Nullable(String), + `payment_method_id` Nullable(String), + `payment_method` Nullable(String), + `payment_method_type` Nullable(String), + `customer_id` Nullable(String), + `user_id` Nullable(String), + `connector` Nullable(String), + `request_id` String, + `flow_type` LowCardinality(String), + `api_flow` LowCardinality(String), + `api_auth_type` LowCardinality(String), + `request` String, + `response` Nullable(String), + `authentication_data` Nullable(String), + `status_code` UInt32, + `created_at` DateTime CODEC(T64, LZ4), + `latency` UInt128, + `user_agent` String, + `ip_addr` String, +) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', +kafka_topic_list = 'hyperswitch-api-log-events', +kafka_group_name = 'hyper-c1', +kafka_format = 'JSONEachRow', +kafka_handle_error_mode = 'stream'; + + +CREATE TABLE api_events_v2_dist ( + `merchant_id` String, + `payment_id` Nullable(String), + `refund_id` Nullable(String), + `payment_method_id` Nullable(String), + `payment_method` Nullable(String), + `payment_method_type` Nullable(String), + `customer_id` Nullable(String), + `user_id` Nullable(String), + `connector` Nullable(String), + `request_id` String, + `flow_type` LowCardinality(String), + `api_flow` LowCardinality(String), + `api_auth_type` LowCardinality(String), + `request` String, + `response` Nullable(String), + `authentication_data` Nullable(String), + `status_code` UInt32, + `created_at` DateTime CODEC(T64, LZ4), + `inserted_at` DateTime CODEC(T64, LZ4), + `latency` UInt128, + `user_agent` String, + `ip_addr` String, + INDEX flowIndex flow_type TYPE bloom_filter GRANULARITY 1, + INDEX apiIndex api_flow TYPE bloom_filter GRANULARITY 1, + INDEX statusIndex status_code TYPE bloom_filter GRANULARITY 1 +) ENGINE = MergeTree +PARTITION BY toStartOfDay(created_at) +ORDER BY + (created_at, merchant_id, flow_type, status_code, api_flow) +TTL created_at + toIntervalMonth(6) +; + +CREATE MATERIALIZED VIEW api_events_v2_mv TO api_events_v2_dist ( + `merchant_id` String, + `payment_id` Nullable(String), + `refund_id` Nullable(String), + `payment_method_id` Nullable(String), + `payment_method` Nullable(String), + `payment_method_type` Nullable(String), + `customer_id` Nullable(String), + `user_id` Nullable(String), + `connector` Nullable(String), + `request_id` String, + `flow_type` LowCardinality(String), + `api_flow` LowCardinality(String), + `api_auth_type` LowCardinality(String), + `request` String, + `response` Nullable(String), + `authentication_data` Nullable(String), + `status_code` UInt32, + `created_at` DateTime CODEC(T64, LZ4), + `inserted_at` DateTime CODEC(T64, LZ4), + `latency` UInt128, + `user_agent` String, + `ip_addr` String +) AS +SELECT + merchant_id, + payment_id, + refund_id, + payment_method_id, + payment_method, + payment_method_type, + customer_id, + user_id, + connector, + request_id, + flow_type, + api_flow, + api_auth_type, + request, + response, + authentication_data, + status_code, + created_at, + now() as inserted_at, + latency, + user_agent, + ip_addr +FROM + api_events_v2_queue +where length(_error) = 0; + + +CREATE MATERIALIZED VIEW api_events_parse_errors +( + `topic` String, + `partition` Int64, + `offset` Int64, + `raw` String, + `error` String +) +ENGINE = MergeTree +ORDER BY (topic, partition, offset) +SETTINGS index_granularity = 8192 AS +SELECT + _topic AS topic, + _partition AS partition, + _offset AS offset, + _raw_message AS raw, + _error AS error +FROM api_events_v2_queue +WHERE length(_error) > 0 +; diff --git a/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql b/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql new file mode 100644 index 00000000000..276e311e57a --- /dev/null +++ b/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql @@ -0,0 +1,156 @@ +CREATE TABLE payment_attempts_queue ( + `payment_id` String, + `merchant_id` String, + `attempt_id` String, + `status` LowCardinality(String), + `amount` Nullable(UInt32), + `currency` LowCardinality(Nullable(String)), + `connector` LowCardinality(Nullable(String)), + `save_to_locker` Nullable(Bool), + `error_message` Nullable(String), + `offer_amount` Nullable(UInt32), + `surcharge_amount` Nullable(UInt32), + `tax_amount` Nullable(UInt32), + `payment_method_id` Nullable(String), + `payment_method` LowCardinality(Nullable(String)), + `payment_method_type` LowCardinality(Nullable(String)), + `connector_transaction_id` Nullable(String), + `capture_method` LowCardinality(Nullable(String)), + `capture_on` Nullable(DateTime) CODEC(T64, LZ4), + `confirm` Bool, + `authentication_type` LowCardinality(Nullable(String)), + `cancellation_reason` Nullable(String), + `amount_to_capture` Nullable(UInt32), + `mandate_id` Nullable(String), + `browser_info` Nullable(String), + `error_code` Nullable(String), + `connector_metadata` Nullable(String), + `payment_experience` Nullable(String), + `created_at` DateTime CODEC(T64, LZ4), + `last_synced` Nullable(DateTime) CODEC(T64, LZ4), + `modified_at` DateTime CODEC(T64, LZ4), + `sign_flag` Int8 +) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', +kafka_topic_list = 'hyperswitch-payment-attempt-events', +kafka_group_name = 'hyper-c1', +kafka_format = 'JSONEachRow', +kafka_handle_error_mode = 'stream'; + +CREATE TABLE payment_attempt_dist ( + `payment_id` String, + `merchant_id` String, + `attempt_id` String, + `status` LowCardinality(String), + `amount` Nullable(UInt32), + `currency` LowCardinality(Nullable(String)), + `connector` LowCardinality(Nullable(String)), + `save_to_locker` Nullable(Bool), + `error_message` Nullable(String), + `offer_amount` Nullable(UInt32), + `surcharge_amount` Nullable(UInt32), + `tax_amount` Nullable(UInt32), + `payment_method_id` Nullable(String), + `payment_method` LowCardinality(Nullable(String)), + `payment_method_type` LowCardinality(Nullable(String)), + `connector_transaction_id` Nullable(String), + `capture_method` Nullable(String), + `capture_on` Nullable(DateTime) CODEC(T64, LZ4), + `confirm` Bool, + `authentication_type` LowCardinality(Nullable(String)), + `cancellation_reason` Nullable(String), + `amount_to_capture` Nullable(UInt32), + `mandate_id` Nullable(String), + `browser_info` Nullable(String), + `error_code` Nullable(String), + `connector_metadata` Nullable(String), + `payment_experience` Nullable(String), + `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `last_synced` Nullable(DateTime) CODEC(T64, LZ4), + `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `sign_flag` Int8, + INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1, + INDEX paymentMethodIndex payment_method TYPE bloom_filter GRANULARITY 1, + INDEX authenticationTypeIndex authentication_type TYPE bloom_filter GRANULARITY 1, + INDEX currencyIndex currency TYPE bloom_filter GRANULARITY 1, + INDEX statusIndex status TYPE bloom_filter GRANULARITY 1 +) ENGINE = CollapsingMergeTree( + sign_flag +) +PARTITION BY toStartOfDay(created_at) +ORDER BY + (created_at, merchant_id, attempt_id) +TTL created_at + toIntervalMonth(6) +; + + +CREATE MATERIALIZED VIEW kafka_parse_pa TO payment_attempt_dist ( + `payment_id` String, + `merchant_id` String, + `attempt_id` String, + `status` LowCardinality(String), + `amount` Nullable(UInt32), + `currency` LowCardinality(Nullable(String)), + `connector` LowCardinality(Nullable(String)), + `save_to_locker` Nullable(Bool), + `error_message` Nullable(String), + `offer_amount` Nullable(UInt32), + `surcharge_amount` Nullable(UInt32), + `tax_amount` Nullable(UInt32), + `payment_method_id` Nullable(String), + `payment_method` LowCardinality(Nullable(String)), + `payment_method_type` LowCardinality(Nullable(String)), + `connector_transaction_id` Nullable(String), + `capture_method` Nullable(String), + `confirm` Bool, + `authentication_type` LowCardinality(Nullable(String)), + `cancellation_reason` Nullable(String), + `amount_to_capture` Nullable(UInt32), + `mandate_id` Nullable(String), + `browser_info` Nullable(String), + `error_code` Nullable(String), + `connector_metadata` Nullable(String), + `payment_experience` Nullable(String), + `created_at` DateTime64(3), + `capture_on` Nullable(DateTime64(3)), + `last_synced` Nullable(DateTime64(3)), + `modified_at` DateTime64(3), + `inserted_at` DateTime64(3), + `sign_flag` Int8 +) AS +SELECT + payment_id, + merchant_id, + attempt_id, + status, + amount, + currency, + connector, + save_to_locker, + error_message, + offer_amount, + surcharge_amount, + tax_amount, + payment_method_id, + payment_method, + payment_method_type, + connector_transaction_id, + capture_method, + confirm, + authentication_type, + cancellation_reason, + amount_to_capture, + mandate_id, + browser_info, + error_code, + connector_metadata, + payment_experience, + created_at, + capture_on, + last_synced, + modified_at, + now() as inserted_at, + sign_flag +FROM + payment_attempts_queue; + diff --git a/crates/analytics/docs/clickhouse/scripts/payment_intents.sql b/crates/analytics/docs/clickhouse/scripts/payment_intents.sql new file mode 100644 index 00000000000..8cd487f364b --- /dev/null +++ b/crates/analytics/docs/clickhouse/scripts/payment_intents.sql @@ -0,0 +1,116 @@ +CREATE TABLE payment_intents_queue ( + `payment_id` String, + `merchant_id` String, + `status` LowCardinality(String), + `amount` UInt32, + `currency` LowCardinality(Nullable(String)), + `amount_captured` Nullable(UInt32), + `customer_id` Nullable(String), + `description` Nullable(String), + `return_url` Nullable(String), + `connector_id` LowCardinality(Nullable(String)), + `statement_descriptor_name` Nullable(String), + `statement_descriptor_suffix` Nullable(String), + `setup_future_usage` LowCardinality(Nullable(String)), + `off_session` Nullable(Bool), + `client_secret` Nullable(String), + `active_attempt_id` String, + `business_country` String, + `business_label` String, + `modified_at` DateTime CODEC(T64, LZ4), + `created_at` DateTime CODEC(T64, LZ4), + `last_synced` Nullable(DateTime) CODEC(T64, LZ4), + `sign_flag` Int8 +) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', +kafka_topic_list = 'hyperswitch-payment-intent-events', +kafka_group_name = 'hyper-c1', +kafka_format = 'JSONEachRow', +kafka_handle_error_mode = 'stream'; + + +CREATE TABLE payment_intents_dist ( + `payment_id` String, + `merchant_id` String, + `status` LowCardinality(String), + `amount` UInt32, + `currency` LowCardinality(Nullable(String)), + `amount_captured` Nullable(UInt32), + `customer_id` Nullable(String), + `description` Nullable(String), + `return_url` Nullable(String), + `connector_id` LowCardinality(Nullable(String)), + `statement_descriptor_name` Nullable(String), + `statement_descriptor_suffix` Nullable(String), + `setup_future_usage` LowCardinality(Nullable(String)), + `off_session` Nullable(Bool), + `client_secret` Nullable(String), + `active_attempt_id` String, + `business_country` LowCardinality(String), + `business_label` String, + `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `last_synced` Nullable(DateTime) CODEC(T64, LZ4), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `sign_flag` Int8, + INDEX connectorIndex connector_id TYPE bloom_filter GRANULARITY 1, + INDEX currencyIndex currency TYPE bloom_filter GRANULARITY 1, + INDEX statusIndex status TYPE bloom_filter GRANULARITY 1 +) ENGINE = CollapsingMergeTree( + sign_flag +) +PARTITION BY toStartOfDay(created_at) +ORDER BY + (created_at, merchant_id, payment_id) +TTL created_at + toIntervalMonth(6) +; + +CREATE MATERIALIZED VIEW kafka_parse_payment_intent TO payment_intents_dist ( + `payment_id` String, + `merchant_id` String, + `status` LowCardinality(String), + `amount` UInt32, + `currency` LowCardinality(Nullable(String)), + `amount_captured` Nullable(UInt32), + `customer_id` Nullable(String), + `description` Nullable(String), + `return_url` Nullable(String), + `connector_id` LowCardinality(Nullable(String)), + `statement_descriptor_name` Nullable(String), + `statement_descriptor_suffix` Nullable(String), + `setup_future_usage` LowCardinality(Nullable(String)), + `off_session` Nullable(Bool), + `client_secret` Nullable(String), + `active_attempt_id` String, + `business_country` LowCardinality(String), + `business_label` String, + `modified_at` DateTime64(3), + `created_at` DateTime64(3), + `last_synced` Nullable(DateTime64(3)), + `inserted_at` DateTime64(3), + `sign_flag` Int8 +) AS +SELECT + payment_id, + merchant_id, + status, + amount, + currency, + amount_captured, + customer_id, + description, + return_url, + connector_id, + statement_descriptor_name, + statement_descriptor_suffix, + setup_future_usage, + off_session, + client_secret, + active_attempt_id, + business_country, + business_label, + modified_at, + created_at, + last_synced, + now() as inserted_at, + sign_flag +FROM payment_intents_queue; diff --git a/crates/analytics/docs/clickhouse/scripts/refunds.sql b/crates/analytics/docs/clickhouse/scripts/refunds.sql new file mode 100644 index 00000000000..a131270c132 --- /dev/null +++ b/crates/analytics/docs/clickhouse/scripts/refunds.sql @@ -0,0 +1,121 @@ +CREATE TABLE refund_queue ( + `internal_reference_id` String, + `refund_id` String, + `payment_id` String, + `merchant_id` String, + `connector_transaction_id` String, + `connector` LowCardinality(Nullable(String)), + `connector_refund_id` Nullable(String), + `external_reference_id` Nullable(String), + `refund_type` LowCardinality(String), + `total_amount` Nullable(UInt32), + `currency` LowCardinality(String), + `refund_amount` Nullable(UInt32), + `refund_status` LowCardinality(String), + `sent_to_gateway` Bool, + `refund_error_message` Nullable(String), + `refund_arn` Nullable(String), + `attempt_id` String, + `description` Nullable(String), + `refund_reason` Nullable(String), + `refund_error_code` Nullable(String), + `created_at` DateTime CODEC(T64, LZ4), + `modified_at` DateTime CODEC(T64, LZ4), + `sign_flag` Int8 +) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', +kafka_topic_list = 'hyperswitch-refund-events', +kafka_group_name = 'hyper-c1', +kafka_format = 'JSONEachRow', +kafka_handle_error_mode = 'stream'; + + +CREATE TABLE refund_dist ( + `internal_reference_id` String, + `refund_id` String, + `payment_id` String, + `merchant_id` String, + `connector_transaction_id` String, + `connector` LowCardinality(Nullable(String)), + `connector_refund_id` Nullable(String), + `external_reference_id` Nullable(String), + `refund_type` LowCardinality(String), + `total_amount` Nullable(UInt32), + `currency` LowCardinality(String), + `refund_amount` Nullable(UInt32), + `refund_status` LowCardinality(String), + `sent_to_gateway` Bool, + `refund_error_message` Nullable(String), + `refund_arn` Nullable(String), + `attempt_id` String, + `description` Nullable(String), + `refund_reason` Nullable(String), + `refund_error_code` Nullable(String), + `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `sign_flag` Int8, + INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1, + INDEX refundTypeIndex refund_type TYPE bloom_filter GRANULARITY 1, + INDEX currencyIndex currency TYPE bloom_filter GRANULARITY 1, + INDEX statusIndex refund_status TYPE bloom_filter GRANULARITY 1 +) ENGINE = CollapsingMergeTree( + sign_flag +) +PARTITION BY toStartOfDay(created_at) +ORDER BY + (created_at, merchant_id, refund_id) +TTL created_at + toIntervalMonth(6) +; + +CREATE MATERIALIZED VIEW kafka_parse_refund TO refund_dist ( + `internal_reference_id` String, + `refund_id` String, + `payment_id` String, + `merchant_id` String, + `connector_transaction_id` String, + `connector` LowCardinality(Nullable(String)), + `connector_refund_id` Nullable(String), + `external_reference_id` Nullable(String), + `refund_type` LowCardinality(String), + `total_amount` Nullable(UInt32), + `currency` LowCardinality(String), + `refund_amount` Nullable(UInt32), + `refund_status` LowCardinality(String), + `sent_to_gateway` Bool, + `refund_error_message` Nullable(String), + `refund_arn` Nullable(String), + `attempt_id` String, + `description` Nullable(String), + `refund_reason` Nullable(String), + `refund_error_code` Nullable(String), + `created_at` DateTime64(3), + `modified_at` DateTime64(3), + `inserted_at` DateTime64(3), + `sign_flag` Int8 +) AS +SELECT + internal_reference_id, + refund_id, + payment_id, + merchant_id, + connector_transaction_id, + connector, + connector_refund_id, + external_reference_id, + refund_type, + total_amount, + currency, + refund_amount, + refund_status, + sent_to_gateway, + refund_error_message, + refund_arn, + attempt_id, + description, + refund_reason, + refund_error_code, + created_at, + modified_at, + now() as inserted_at, + sign_flag +FROM refund_queue; diff --git a/crates/analytics/src/api_event.rs b/crates/analytics/src/api_event.rs new file mode 100644 index 00000000000..113344d4725 --- /dev/null +++ b/crates/analytics/src/api_event.rs @@ -0,0 +1,9 @@ +mod core; +pub mod events; +pub mod filters; +pub mod metrics; +pub mod types; + +pub trait APIEventAnalytics: events::ApiLogsFilterAnalytics {} + +pub use self::core::{api_events_core, get_api_event_metrics, get_filters}; diff --git a/crates/analytics/src/api_event/core.rs b/crates/analytics/src/api_event/core.rs new file mode 100644 index 00000000000..b368d6374f7 --- /dev/null +++ b/crates/analytics/src/api_event/core.rs @@ -0,0 +1,176 @@ +use std::collections::HashMap; + +use api_models::analytics::{ + api_event::{ + ApiEventMetricsBucketIdentifier, ApiEventMetricsBucketValue, ApiLogsRequest, + ApiMetricsBucketResponse, + }, + AnalyticsMetadata, ApiEventFiltersResponse, GetApiEventFiltersRequest, + GetApiEventMetricRequest, MetricsResponse, +}; +use error_stack::{IntoReport, ResultExt}; +use router_env::{ + instrument, logger, + tracing::{self, Instrument}, +}; + +use super::{ + events::{get_api_event, ApiLogsResult}, + metrics::ApiEventMetricRow, +}; +use crate::{ + errors::{AnalyticsError, AnalyticsResult}, + metrics, + types::FiltersError, + AnalyticsProvider, +}; + +#[instrument(skip_all)] +pub async fn api_events_core( + pool: &AnalyticsProvider, + req: ApiLogsRequest, + merchant_id: String, +) -> AnalyticsResult<Vec<ApiLogsResult>> { + let data = match pool { + AnalyticsProvider::Sqlx(_) => Err(FiltersError::NotImplemented) + .into_report() + .attach_printable("SQL Analytics is not implemented for API Events"), + AnalyticsProvider::Clickhouse(pool) => get_api_event(&merchant_id, req, pool).await, + AnalyticsProvider::CombinedSqlx(_sqlx_pool, ckh_pool) + | AnalyticsProvider::CombinedCkh(_sqlx_pool, ckh_pool) => { + get_api_event(&merchant_id, req, ckh_pool).await + } + } + .change_context(AnalyticsError::UnknownError)?; + Ok(data) +} + +pub async fn get_filters( + pool: &AnalyticsProvider, + req: GetApiEventFiltersRequest, + merchant_id: String, +) -> AnalyticsResult<ApiEventFiltersResponse> { + use api_models::analytics::{api_event::ApiEventDimensions, ApiEventFilterValue}; + + use super::filters::get_api_event_filter_for_dimension; + use crate::api_event::filters::ApiEventFilter; + + let mut res = ApiEventFiltersResponse::default(); + for dim in req.group_by_names { + let values = match pool { + AnalyticsProvider::Sqlx(_pool) => Err(FiltersError::NotImplemented) + .into_report() + .attach_printable("SQL Analytics is not implemented for API Events"), + AnalyticsProvider::Clickhouse(ckh_pool) + | AnalyticsProvider::CombinedSqlx(_, ckh_pool) + | AnalyticsProvider::CombinedCkh(_, ckh_pool) => { + get_api_event_filter_for_dimension(dim, &merchant_id, &req.time_range, ckh_pool) + .await + } + } + .change_context(AnalyticsError::UnknownError)? + .into_iter() + .filter_map(|fil: ApiEventFilter| match dim { + ApiEventDimensions::StatusCode => fil.status_code.map(|i| i.to_string()), + ApiEventDimensions::FlowType => fil.flow_type, + ApiEventDimensions::ApiFlow => fil.api_flow, + }) + .collect::<Vec<String>>(); + res.query_data.push(ApiEventFilterValue { + dimension: dim, + values, + }) + } + + Ok(res) +} + +#[instrument(skip_all)] +pub async fn get_api_event_metrics( + pool: &AnalyticsProvider, + merchant_id: &str, + req: GetApiEventMetricRequest, +) -> AnalyticsResult<MetricsResponse<ApiMetricsBucketResponse>> { + let mut metrics_accumulator: HashMap<ApiEventMetricsBucketIdentifier, ApiEventMetricRow> = + HashMap::new(); + + let mut set = tokio::task::JoinSet::new(); + for metric_type in req.metrics.iter().cloned() { + let req = req.clone(); + let pool = pool.clone(); + let task_span = tracing::debug_span!( + "analytics_api_metrics_query", + api_event_metric = metric_type.as_ref() + ); + + // TODO: lifetime issues with joinset, + // can be optimized away if joinset lifetime requirements are relaxed + let merchant_id_scoped = merchant_id.to_owned(); + set.spawn( + async move { + let data = pool + .get_api_event_metrics( + &metric_type, + &req.group_by_names.clone(), + &merchant_id_scoped, + &req.filters, + &req.time_series.map(|t| t.granularity), + &req.time_range, + ) + .await + .change_context(AnalyticsError::UnknownError); + (metric_type, data) + } + .instrument(task_span), + ); + } + + while let Some((metric, data)) = set + .join_next() + .await + .transpose() + .into_report() + .change_context(AnalyticsError::UnknownError)? + { + let data = data?; + let attributes = &[ + metrics::request::add_attributes("metric_type", metric.to_string()), + metrics::request::add_attributes("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); + } + for (id, value) in data { + metrics_accumulator + .entry(id) + .and_modify(|data| { + data.api_count = data.api_count.or(value.api_count); + data.status_code_count = data.status_code_count.or(value.status_code_count); + data.latency = data.latency.or(value.latency); + }) + .or_insert(value); + } + } + + let query_data: Vec<ApiMetricsBucketResponse> = metrics_accumulator + .into_iter() + .map(|(id, val)| ApiMetricsBucketResponse { + values: ApiEventMetricsBucketValue { + latency: val.latency, + api_count: val.api_count, + status_code_count: val.status_code_count, + }, + dimensions: id, + }) + .collect(); + + Ok(MetricsResponse { + query_data, + meta_data: [AnalyticsMetadata { + current_time_range: req.time_range, + }], + }) +} diff --git a/crates/analytics/src/api_event/events.rs b/crates/analytics/src/api_event/events.rs new file mode 100644 index 00000000000..73b3fb9cbad --- /dev/null +++ b/crates/analytics/src/api_event/events.rs @@ -0,0 +1,105 @@ +use api_models::analytics::{ + api_event::{ApiLogsRequest, QueryType}, + Granularity, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use router_env::Flow; +use time::PrimitiveDateTime; + +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow}, +}; +pub trait ApiLogsFilterAnalytics: LoadRow<ApiLogsResult> {} + +pub async fn get_api_event<T>( + merchant_id: &String, + query_param: ApiLogsRequest, + pool: &T, +) -> FiltersResult<Vec<ApiLogsResult>> +where + T: AnalyticsDataSource + ApiLogsFilterAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ApiEvents); + query_builder.add_select_column("*").switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + match query_param.query_param { + QueryType::Payment { payment_id } => query_builder + .add_filter_clause("payment_id", payment_id) + .switch()?, + QueryType::Refund { + payment_id, + refund_id, + } => { + query_builder + .add_filter_clause("payment_id", payment_id) + .switch()?; + query_builder + .add_filter_clause("refund_id", refund_id) + .switch()?; + } + } + if let Some(list_api_name) = query_param.api_name_filter { + query_builder + .add_filter_in_range_clause("api_flow", &list_api_name) + .switch()?; + } else { + query_builder + .add_filter_in_range_clause( + "api_flow", + &[ + Flow::PaymentsCancel, + Flow::PaymentsCapture, + Flow::PaymentsConfirm, + Flow::PaymentsCreate, + Flow::PaymentsStart, + Flow::PaymentsUpdate, + Flow::RefundsCreate, + Flow::IncomingWebhookReceive, + ], + ) + .switch()?; + } + //TODO!: update the execute_query function to return reports instead of plain errors... + query_builder + .execute_query::<ApiLogsResult, _>(pool) + .await + .change_context(FiltersError::QueryBuildingError)? + .change_context(FiltersError::QueryExecutionFailure) +} +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct ApiLogsResult { + pub merchant_id: String, + pub payment_id: Option<String>, + pub refund_id: Option<String>, + pub payment_method_id: Option<String>, + pub payment_method: Option<String>, + pub payment_method_type: Option<String>, + pub customer_id: Option<String>, + pub user_id: Option<String>, + pub connector: Option<String>, + pub request_id: Option<String>, + pub flow_type: String, + pub api_flow: String, + pub api_auth_type: Option<String>, + pub request: String, + pub response: Option<String>, + pub error: Option<String>, + pub authentication_data: Option<String>, + pub status_code: u16, + pub latency: Option<u128>, + pub user_agent: Option<String>, + pub hs_latency: Option<u128>, + pub ip_addr: Option<String>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, +} diff --git a/crates/analytics/src/api_event/filters.rs b/crates/analytics/src/api_event/filters.rs new file mode 100644 index 00000000000..87414ebad4b --- /dev/null +++ b/crates/analytics/src/api_event/filters.rs @@ -0,0 +1,53 @@ +use api_models::analytics::{api_event::ApiEventDimensions, Granularity, TimeRange}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow}, +}; + +pub trait ApiEventFilterAnalytics: LoadRow<ApiEventFilter> {} + +pub async fn get_api_event_filter_for_dimension<T>( + dimension: ApiEventDimensions, + merchant_id: &String, + time_range: &TimeRange, + pool: &T, +) -> FiltersResult<Vec<ApiEventFilter>> +where + T: AnalyticsDataSource + ApiEventFilterAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ApiEvents); + + query_builder.add_select_column(dimension).switch()?; + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + + query_builder.set_distinct(); + + query_builder + .execute_query::<ApiEventFilter, _>(pool) + .await + .change_context(FiltersError::QueryBuildingError)? + .change_context(FiltersError::QueryExecutionFailure) +} + +#[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] +pub struct ApiEventFilter { + pub status_code: Option<i32>, + pub flow_type: Option<String>, + pub api_flow: Option<String>, +} diff --git a/crates/analytics/src/api_event/metrics.rs b/crates/analytics/src/api_event/metrics.rs new file mode 100644 index 00000000000..16f2d7a2f5a --- /dev/null +++ b/crates/analytics/src/api_event/metrics.rs @@ -0,0 +1,110 @@ +use api_models::analytics::{ + api_event::{ + ApiEventDimensions, ApiEventFilters, ApiEventMetrics, ApiEventMetricsBucketIdentifier, + }, + Granularity, TimeRange, +}; +use time::PrimitiveDateTime; + +use crate::{ + query::{Aggregate, GroupByClause, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, MetricsResult}, +}; + +mod api_count; +pub mod latency; +mod status_code_count; +use api_count::ApiCount; +use latency::MaxLatency; +use status_code_count::StatusCodeCount; + +use self::latency::LatencyAvg; + +#[derive(Debug, PartialEq, Eq, serde::Deserialize)] +pub struct ApiEventMetricRow { + pub latency: Option<u64>, + pub api_count: Option<u64>, + pub status_code_count: Option<u64>, + #[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 ApiEventMetricAnalytics: LoadRow<ApiEventMetricRow> + LoadRow<LatencyAvg> {} + +#[async_trait::async_trait] +pub trait ApiEventMetric<T> +where + T: AnalyticsDataSource + ApiEventMetricAnalytics, +{ + async fn load_metrics( + &self, + dimensions: &[ApiEventDimensions], + merchant_id: &str, + filters: &ApiEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>>; +} + +#[async_trait::async_trait] +impl<T> ApiEventMetric<T> for ApiEventMetrics +where + T: AnalyticsDataSource + ApiEventMetricAnalytics, + 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: &[ApiEventDimensions], + merchant_id: &str, + filters: &ApiEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { + match self { + Self::Latency => { + MaxLatency + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::ApiCount => { + ApiCount + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::StatusCodeCount => { + StatusCodeCount + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + } + } +} diff --git a/crates/analytics/src/api_event/metrics/api_count.rs b/crates/analytics/src/api_event/metrics/api_count.rs new file mode 100644 index 00000000000..7f5f291aa53 --- /dev/null +++ b/crates/analytics/src/api_event/metrics/api_count.rs @@ -0,0 +1,106 @@ +use api_models::analytics::{ + api_event::{ApiEventDimensions, ApiEventFilters, ApiEventMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::ApiEventMetricRow; +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct ApiCount; + +#[async_trait::async_trait] +impl<T> super::ApiEventMetric<T> for ApiCount +where + T: AnalyticsDataSource + super::ApiEventMetricAnalytics, + 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: &[ApiEventDimensions], + merchant_id: &str, + filters: &ApiEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ApiEvents); + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("api_count"), + }) + .switch()?; + if !filters.flow_type.is_empty() { + query_builder + .add_filter_in_range_clause(ApiEventDimensions::FlowType, &filters.flow_type) + .attach_printable("Error adding flow_type filter") + .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()?; + 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("merchant_id", merchant_id) + .switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + query_builder + .execute_query::<ApiEventMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + ApiEventMetricsBucketIdentifier::new(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<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/api_event/metrics/latency.rs b/crates/analytics/src/api_event/metrics/latency.rs new file mode 100644 index 00000000000..379b39fbeb9 --- /dev/null +++ b/crates/analytics/src/api_event/metrics/latency.rs @@ -0,0 +1,138 @@ +use api_models::analytics::{ + api_event::{ApiEventDimensions, ApiEventFilters, ApiEventMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::ApiEventMetricRow; +use crate::{ + query::{ + Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, + Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct MaxLatency; + +#[async_trait::async_trait] +impl<T> super::ApiEventMetric<T> for MaxLatency +where + T: AnalyticsDataSource + super::ApiEventMetricAnalytics, + 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: &[ApiEventDimensions], + merchant_id: &str, + filters: &ApiEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ApiEvents); + + query_builder + .add_select_column(Aggregate::Sum { + field: "latency", + alias: Some("latency_sum"), + }) + .switch()?; + + query_builder + .add_select_column(Aggregate::Count { + field: Some("latency"), + alias: Some("latency_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()?; + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + filters.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + query_builder + .add_custom_filter_clause("request", "10.63.134.6", FilterTypes::NotLike) + .attach_printable("Error filtering out locker IP") + .switch()?; + + query_builder + .execute_query::<LatencyAvg, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + ApiEventMetricsBucketIdentifier::new(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(), + )?, + }), + ApiEventMetricRow { + latency: if i.latency_count != 0 { + Some(i.latency_sum.unwrap_or(0) / i.latency_count) + } else { + None + }, + api_count: None, + status_code_count: None, + start_bucket: i.start_bucket, + end_bucket: i.end_bucket, + }, + )) + }) + .collect::<error_stack::Result< + Vec<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} + +#[derive(Debug, PartialEq, Eq, serde::Deserialize)] +pub struct LatencyAvg { + latency_sum: Option<u64>, + latency_count: u64, + #[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>, +} diff --git a/crates/analytics/src/api_event/metrics/status_code_count.rs b/crates/analytics/src/api_event/metrics/status_code_count.rs new file mode 100644 index 00000000000..5c652fd8e0c --- /dev/null +++ b/crates/analytics/src/api_event/metrics/status_code_count.rs @@ -0,0 +1,103 @@ +use api_models::analytics::{ + api_event::{ApiEventDimensions, ApiEventFilters, ApiEventMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::ApiEventMetricRow; +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct StatusCodeCount; + +#[async_trait::async_trait] +impl<T> super::ApiEventMetric<T> for StatusCodeCount +where + T: AnalyticsDataSource + super::ApiEventMetricAnalytics, + 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: &[ApiEventDimensions], + merchant_id: &str, + filters: &ApiEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ApiEvents); + + query_builder + .add_select_column(Aggregate::Count { + field: Some("status_code"), + alias: Some("status_code_count"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .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()?; + 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::<ApiEventMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + ApiEventMetricsBucketIdentifier::new(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<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/api_event/types.rs b/crates/analytics/src/api_event/types.rs new file mode 100644 index 00000000000..72205fc72ab --- /dev/null +++ b/crates/analytics/src/api_event/types.rs @@ -0,0 +1,33 @@ +use api_models::analytics::api_event::{ApiEventDimensions, ApiEventFilters}; +use error_stack::ResultExt; + +use crate::{ + query::{QueryBuilder, QueryFilter, QueryResult, ToSql}, + types::{AnalyticsCollection, AnalyticsDataSource}, +}; + +impl<T> QueryFilter<T> for ApiEventFilters +where + T: AnalyticsDataSource, + AnalyticsCollection: ToSql<T>, +{ + fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> { + if !self.status_code.is_empty() { + builder + .add_filter_in_range_clause(ApiEventDimensions::StatusCode, &self.status_code) + .attach_printable("Error adding status_code filter")?; + } + if !self.flow_type.is_empty() { + builder + .add_filter_in_range_clause(ApiEventDimensions::FlowType, &self.flow_type) + .attach_printable("Error adding flow_type filter")?; + } + if !self.api_flow.is_empty() { + builder + .add_filter_in_range_clause(ApiEventDimensions::ApiFlow, &self.api_flow) + .attach_printable("Error adding api_name filter")?; + } + + Ok(()) + } +} diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs new file mode 100644 index 00000000000..964486c9364 --- /dev/null +++ b/crates/analytics/src/clickhouse.rs @@ -0,0 +1,458 @@ +use std::sync::Arc; + +use actix_web::http::StatusCode; +use common_utils::errors::ParsingError; +use error_stack::{IntoReport, Report, ResultExt}; +use router_env::logger; +use time::PrimitiveDateTime; + +use super::{ + payments::{ + distribution::PaymentDistributionRow, filters::FilterRow, metrics::PaymentMetricRow, + }, + query::{Aggregate, ToSql, Window}, + refunds::{filters::RefundFilterRow, metrics::RefundMetricRow}, + sdk_events::{filters::SdkEventFilter, metrics::SdkEventMetricRow}, + types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, QueryExecutionError}, +}; +use crate::{ + api_event::{ + events::ApiLogsResult, + filters::ApiEventFilter, + metrics::{latency::LatencyAvg, ApiEventMetricRow}, + }, + sdk_events::events::SdkEventsResult, + types::TableEngine, +}; + +pub type ClickhouseResult<T> = error_stack::Result<T, ClickhouseError>; + +#[derive(Clone, Debug)] +pub struct ClickhouseClient { + pub config: Arc<ClickhouseConfig>, +} + +#[derive(Clone, Debug, serde::Deserialize)] +pub struct ClickhouseConfig { + username: String, + password: Option<String>, + host: String, + database_name: String, +} + +impl Default for ClickhouseConfig { + fn default() -> Self { + Self { + username: "default".to_string(), + password: None, + host: "http://localhost:8123".to_string(), + database_name: "default".to_string(), + } + } +} + +impl ClickhouseClient { + async fn execute_query(&self, query: &str) -> ClickhouseResult<Vec<serde_json::Value>> { + logger::debug!("Executing query: {query}"); + let client = reqwest::Client::new(); + let params = CkhQuery { + date_time_output_format: String::from("iso"), + output_format_json_quote_64bit_integers: 0, + database: self.config.database_name.clone(), + }; + let response = client + .post(&self.config.host) + .query(&params) + .basic_auth(self.config.username.clone(), self.config.password.clone()) + .body(format!("{query}\nFORMAT JSON")) + .send() + .await + .into_report() + .change_context(ClickhouseError::ConnectionError)?; + + logger::debug!(clickhouse_response=?response, query=?query, "Clickhouse response"); + if response.status() != StatusCode::OK { + response.text().await.map_or_else( + |er| { + Err(ClickhouseError::ResponseError) + .into_report() + .attach_printable_lazy(|| format!("Error: {er:?}")) + }, + |t| Err(ClickhouseError::ResponseNotOK(t)).into_report(), + ) + } else { + Ok(response + .json::<CkhOutput<serde_json::Value>>() + .await + .into_report() + .change_context(ClickhouseError::ResponseError)? + .data) + } + } +} + +#[async_trait::async_trait] +impl AnalyticsDataSource for ClickhouseClient { + type Row = serde_json::Value; + + async fn load_results<T>( + &self, + query: &str, + ) -> common_utils::errors::CustomResult<Vec<T>, QueryExecutionError> + where + Self: LoadRow<T>, + { + self.execute_query(query) + .await + .change_context(QueryExecutionError::DatabaseError)? + .into_iter() + .map(Self::load_row) + .collect::<Result<Vec<_>, _>>() + .change_context(QueryExecutionError::RowExtractionFailure) + } + + fn get_table_engine(table: AnalyticsCollection) -> TableEngine { + match table { + AnalyticsCollection::Payment + | AnalyticsCollection::Refund + | AnalyticsCollection::PaymentIntent => { + TableEngine::CollapsingMergeTree { sign: "sign_flag" } + } + AnalyticsCollection::SdkEvents => TableEngine::BasicTree, + AnalyticsCollection::ApiEvents => TableEngine::BasicTree, + } + } +} + +impl<T, E> LoadRow<T> for ClickhouseClient +where + Self::Row: TryInto<T, Error = Report<E>>, +{ + fn load_row(row: Self::Row) -> common_utils::errors::CustomResult<T, QueryExecutionError> { + row.try_into() + .change_context(QueryExecutionError::RowExtractionFailure) + } +} + +impl super::payments::filters::PaymentFilterAnalytics for ClickhouseClient {} +impl super::payments::metrics::PaymentMetricAnalytics for ClickhouseClient {} +impl super::payments::distribution::PaymentDistributionAnalytics for ClickhouseClient {} +impl super::refunds::metrics::RefundMetricAnalytics for ClickhouseClient {} +impl super::refunds::filters::RefundFilterAnalytics for ClickhouseClient {} +impl super::sdk_events::filters::SdkEventFilterAnalytics for ClickhouseClient {} +impl super::sdk_events::metrics::SdkEventMetricAnalytics for ClickhouseClient {} +impl super::sdk_events::events::SdkEventsFilterAnalytics for ClickhouseClient {} +impl super::api_event::events::ApiLogsFilterAnalytics for ClickhouseClient {} +impl super::api_event::filters::ApiEventFilterAnalytics for ClickhouseClient {} +impl super::api_event::metrics::ApiEventMetricAnalytics for ClickhouseClient {} + +#[derive(Debug, serde::Serialize)] +struct CkhQuery { + date_time_output_format: String, + output_format_json_quote_64bit_integers: u8, + database: String, +} + +#[derive(Debug, serde::Deserialize)] +struct CkhOutput<T> { + data: Vec<T>, +} + +impl TryInto<ApiLogsResult> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<ApiLogsResult, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse ApiLogsResult in clickhouse results", + )) + } +} + +impl TryInto<SdkEventsResult> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<SdkEventsResult, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse SdkEventsResult in clickhouse results", + )) + } +} + +impl TryInto<PaymentMetricRow> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<PaymentMetricRow, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse PaymentMetricRow in clickhouse results", + )) + } +} + +impl TryInto<PaymentDistributionRow> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<PaymentDistributionRow, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse PaymentDistributionRow in clickhouse results", + )) + } +} + +impl TryInto<FilterRow> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<FilterRow, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse FilterRow in clickhouse results", + )) + } +} + +impl TryInto<RefundMetricRow> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<RefundMetricRow, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse RefundMetricRow in clickhouse results", + )) + } +} + +impl TryInto<RefundFilterRow> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<RefundFilterRow, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse RefundFilterRow in clickhouse results", + )) + } +} + +impl TryInto<ApiEventMetricRow> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<ApiEventMetricRow, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse ApiEventMetricRow in clickhouse results", + )) + } +} + +impl TryInto<LatencyAvg> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<LatencyAvg, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse LatencyAvg in clickhouse results", + )) + } +} + +impl TryInto<SdkEventMetricRow> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<SdkEventMetricRow, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse SdkEventMetricRow in clickhouse results", + )) + } +} + +impl TryInto<SdkEventFilter> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<SdkEventFilter, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse SdkEventFilter in clickhouse results", + )) + } +} + +impl TryInto<ApiEventFilter> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<ApiEventFilter, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse ApiEventFilter in clickhouse results", + )) + } +} + +impl ToSql<ClickhouseClient> for PrimitiveDateTime { + fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { + let format = + time::format_description::parse("[year]-[month]-[day] [hour]:[minute]:[second]") + .into_report() + .change_context(ParsingError::DateTimeParsingError) + .attach_printable("Failed to parse format description")?; + self.format(&format) + .into_report() + .change_context(ParsingError::EncodeError( + "failed to encode to clickhouse date-time format", + )) + .attach_printable("Failed to format date time") + } +} + +impl ToSql<ClickhouseClient> for AnalyticsCollection { + fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { + match self { + Self::Payment => Ok("payment_attempt_dist".to_string()), + Self::Refund => Ok("refund_dist".to_string()), + Self::SdkEvents => Ok("sdk_events_dist".to_string()), + Self::ApiEvents => Ok("api_audit_log".to_string()), + Self::PaymentIntent => Ok("payment_intents_dist".to_string()), + } + } +} + +impl<T> ToSql<ClickhouseClient> for Aggregate<T> +where + T: ToSql<ClickhouseClient>, +{ + fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { + Ok(match self { + Self::Count { field: _, alias } => { + let query = match table_engine { + TableEngine::CollapsingMergeTree { sign } => format!("sum({sign})"), + TableEngine::BasicTree => "count(*)".to_string(), + }; + format!( + "{query}{}", + alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias)) + ) + } + Self::Sum { field, alias } => { + let query = match table_engine { + TableEngine::CollapsingMergeTree { sign } => format!( + "sum({sign} * {})", + field + .to_sql(table_engine) + .attach_printable("Failed to sum aggregate")? + ), + TableEngine::BasicTree => format!( + "sum({})", + field + .to_sql(table_engine) + .attach_printable("Failed to sum aggregate")? + ), + }; + format!( + "{query}{}", + alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias)) + ) + } + Self::Min { field, alias } => { + format!( + "min({}){}", + field + .to_sql(table_engine) + .attach_printable("Failed to min aggregate")?, + alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias)) + ) + } + Self::Max { field, alias } => { + format!( + "max({}){}", + field + .to_sql(table_engine) + .attach_printable("Failed to max aggregate")?, + alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias)) + ) + } + }) + } +} + +impl<T> ToSql<ClickhouseClient> for Window<T> +where + T: ToSql<ClickhouseClient>, +{ + fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { + Ok(match self { + Self::Sum { + field, + partition_by, + order_by, + alias, + } => { + format!( + "sum({}) over ({}{}){}", + field + .to_sql(table_engine) + .attach_printable("Failed to sum window")?, + partition_by.as_ref().map_or_else( + || "".to_owned(), + |partition_by| format!("partition by {}", partition_by.to_owned()) + ), + order_by.as_ref().map_or_else( + || "".to_owned(), + |(order_column, order)| format!( + " order by {} {}", + order_column.to_owned(), + order.to_string() + ) + ), + alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias)) + ) + } + Self::RowNumber { + field: _, + partition_by, + order_by, + alias, + } => { + format!( + "row_number() over ({}{}){}", + partition_by.as_ref().map_or_else( + || "".to_owned(), + |partition_by| format!("partition by {}", partition_by.to_owned()) + ), + order_by.as_ref().map_or_else( + || "".to_owned(), + |(order_column, order)| format!( + " order by {} {}", + order_column.to_owned(), + order.to_string() + ) + ), + alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias)) + ) + } + }) + } +} + +#[derive(Debug, thiserror::Error)] +pub enum ClickhouseError { + #[error("Clickhouse connection error")] + ConnectionError, + #[error("Clickhouse NON-200 response content: '{0}'")] + ResponseNotOK(String), + #[error("Clickhouse response error")] + ResponseError, +} diff --git a/crates/analytics/src/core.rs b/crates/analytics/src/core.rs new file mode 100644 index 00000000000..354e1e2f176 --- /dev/null +++ b/crates/analytics/src/core.rs @@ -0,0 +1,31 @@ +use api_models::analytics::GetInfoResponse; + +use crate::{types::AnalyticsDomain, utils}; + +pub async fn get_domain_info( + domain: AnalyticsDomain, +) -> crate::errors::AnalyticsResult<GetInfoResponse> { + let info = match domain { + AnalyticsDomain::Payments => GetInfoResponse { + metrics: utils::get_payment_metrics_info(), + download_dimensions: None, + dimensions: utils::get_payment_dimensions(), + }, + AnalyticsDomain::Refunds => GetInfoResponse { + metrics: utils::get_refund_metrics_info(), + download_dimensions: None, + dimensions: utils::get_refund_dimensions(), + }, + AnalyticsDomain::SdkEvents => GetInfoResponse { + metrics: utils::get_sdk_event_metrics_info(), + download_dimensions: None, + dimensions: utils::get_sdk_event_dimensions(), + }, + AnalyticsDomain::ApiEvents => GetInfoResponse { + metrics: utils::get_api_event_metrics_info(), + download_dimensions: None, + dimensions: utils::get_api_event_dimensions(), + }, + }; + Ok(info) +} diff --git a/crates/router/src/analytics/errors.rs b/crates/analytics/src/errors.rs similarity index 100% rename from crates/router/src/analytics/errors.rs rename to crates/analytics/src/errors.rs diff --git a/crates/analytics/src/lambda_utils.rs b/crates/analytics/src/lambda_utils.rs new file mode 100644 index 00000000000..f9446a402b4 --- /dev/null +++ b/crates/analytics/src/lambda_utils.rs @@ -0,0 +1,36 @@ +use aws_config::{self, meta::region::RegionProviderChain}; +use aws_sdk_lambda::{config::Region, types::InvocationType::Event, Client}; +use aws_smithy_types::Blob; +use common_utils::errors::CustomResult; +use error_stack::{IntoReport, ResultExt}; + +use crate::errors::AnalyticsError; + +async fn get_aws_client(region: String) -> Client { + let region_provider = RegionProviderChain::first_try(Region::new(region)); + let sdk_config = aws_config::from_env().region(region_provider).load().await; + Client::new(&sdk_config) +} + +pub async fn invoke_lambda( + function_name: &str, + region: &str, + json_bytes: &[u8], +) -> CustomResult<(), AnalyticsError> { + get_aws_client(region.to_string()) + .await + .invoke() + .function_name(function_name) + .invocation_type(Event) + .payload(Blob::new(json_bytes.to_owned())) + .send() + .await + .into_report() + .map_err(|er| { + let er_rep = format!("{er:?}"); + er.attach_printable(er_rep) + }) + .change_context(AnalyticsError::UnknownError) + .attach_printable("Lambda invocation failed")?; + Ok(()) +} diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs new file mode 100644 index 00000000000..24da77f84f2 --- /dev/null +++ b/crates/analytics/src/lib.rs @@ -0,0 +1,509 @@ +mod clickhouse; +pub mod core; +pub mod errors; +pub mod metrics; +pub mod payments; +mod query; +pub mod refunds; + +pub mod api_event; +pub mod sdk_events; +mod sqlx; +mod types; +use api_event::metrics::{ApiEventMetric, ApiEventMetricRow}; +pub use types::AnalyticsDomain; +pub mod lambda_utils; +pub mod utils; + +use std::sync::Arc; + +use api_models::analytics::{ + api_event::{ + ApiEventDimensions, ApiEventFilters, ApiEventMetrics, ApiEventMetricsBucketIdentifier, + }, + payments::{PaymentDimensions, PaymentFilters, PaymentMetrics, PaymentMetricsBucketIdentifier}, + refunds::{RefundDimensions, RefundFilters, RefundMetrics, RefundMetricsBucketIdentifier}, + sdk_events::{ + SdkEventDimensions, SdkEventFilters, SdkEventMetrics, SdkEventMetricsBucketIdentifier, + }, + Distribution, Granularity, TimeRange, +}; +use clickhouse::ClickhouseClient; +pub use clickhouse::ClickhouseConfig; +use error_stack::IntoReport; +use router_env::{ + logger, + tracing::{self, instrument}, +}; +use storage_impl::config::Database; + +use self::{ + payments::{ + distribution::{PaymentDistribution, PaymentDistributionRow}, + metrics::{PaymentMetric, PaymentMetricRow}, + }, + refunds::metrics::{RefundMetric, RefundMetricRow}, + sdk_events::metrics::{SdkEventMetric, SdkEventMetricRow}, + sqlx::SqlxClient, + types::MetricsError, +}; + +#[derive(Clone, Debug)] +pub enum AnalyticsProvider { + Sqlx(SqlxClient), + Clickhouse(ClickhouseClient), + CombinedCkh(SqlxClient, ClickhouseClient), + CombinedSqlx(SqlxClient, ClickhouseClient), +} + +impl Default for AnalyticsProvider { + fn default() -> Self { + Self::Sqlx(SqlxClient::default()) + } +} + +impl ToString for AnalyticsProvider { + fn to_string(&self) -> String { + String::from(match self { + Self::Clickhouse(_) => "Clickhouse", + Self::Sqlx(_) => "Sqlx", + Self::CombinedCkh(_, _) => "CombinedCkh", + Self::CombinedSqlx(_, _) => "CombinedSqlx", + }) + } +} + +impl AnalyticsProvider { + #[instrument(skip_all)] + pub async fn get_payment_metrics( + &self, + metric: &PaymentMetrics, + dimensions: &[PaymentDimensions], + merchant_id: &str, + filters: &PaymentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + ) -> types::MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + // Metrics to get the fetch time for each payment metric + metrics::request::record_operation_time( + async { + match self { + Self::Sqlx(pool) => { + metric + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::Clickhouse(pool) => { + metric + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::CombinedCkh(sqlx_pool, ckh_pool) => { + let (ckh_result, sqlx_result) = tokio::join!(metric + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + ckh_pool, + ), + metric + .load_metrics( + dimensions, + merchant_id, + 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 metrics") + }, + _ => {} + + }; + + ckh_result + } + Self::CombinedSqlx(sqlx_pool, ckh_pool) => { + let (ckh_result, sqlx_result) = tokio::join!(metric + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + ckh_pool, + ), + metric + .load_metrics( + dimensions, + merchant_id, + 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 metrics") + }, + _ => {} + + }; + + sqlx_result + } + } + }, + &metrics::METRIC_FETCH_TIME, + metric, + self, + ) + .await + } + + pub async fn get_payment_distribution( + &self, + distribution: &Distribution, + dimensions: &[PaymentDimensions], + merchant_id: &str, + filters: &PaymentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + ) -> types::MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>> { + // 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, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::Clickhouse(pool) => { + distribution.distribution_for + .load_distribution( + distribution, + dimensions, + merchant_id, + 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, + merchant_id, + filters, + granularity, + time_range, + ckh_pool, + ), + distribution.distribution_for + .load_distribution( + distribution, + dimensions, + merchant_id, + 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, + merchant_id, + filters, + granularity, + time_range, + ckh_pool, + ), + distribution.distribution_for + .load_distribution( + distribution, + dimensions, + merchant_id, + 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_refund_metrics( + &self, + metric: &RefundMetrics, + dimensions: &[RefundDimensions], + merchant_id: &str, + filters: &RefundFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + ) -> types::MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { + // Metrics to get the fetch time for each refund metric + metrics::request::record_operation_time( + async { + match self { + Self::Sqlx(pool) => { + metric + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::Clickhouse(pool) => { + metric + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::CombinedCkh(sqlx_pool, ckh_pool) => { + let (ckh_result, sqlx_result) = tokio::join!( + metric.load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + ckh_pool, + ), + metric.load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + sqlx_pool, + ) + ); + match (&sqlx_result, &ckh_result) { + (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { + logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres refunds analytics metrics") + } + _ => {} + }; + ckh_result + } + Self::CombinedSqlx(sqlx_pool, ckh_pool) => { + let (ckh_result, sqlx_result) = tokio::join!( + metric.load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + ckh_pool, + ), + metric.load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + sqlx_pool, + ) + ); + match (&sqlx_result, &ckh_result) { + (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { + logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres refunds analytics metrics") + } + _ => {} + }; + sqlx_result + } + } + }, + &metrics::METRIC_FETCH_TIME, + metric, + self, + ) + .await + } + + pub async fn get_sdk_event_metrics( + &self, + metric: &SdkEventMetrics, + dimensions: &[SdkEventDimensions], + pub_key: &str, + filters: &SdkEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + ) -> types::MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + match self { + Self::Sqlx(_pool) => Err(MetricsError::NotImplemented).into_report(), + Self::Clickhouse(pool) => { + metric + .load_metrics(dimensions, pub_key, filters, granularity, time_range, pool) + .await + } + Self::CombinedCkh(_sqlx_pool, ckh_pool) | Self::CombinedSqlx(_sqlx_pool, ckh_pool) => { + metric + .load_metrics( + dimensions, + pub_key, + filters, + granularity, + // Since SDK events are ckh only use ckh here + time_range, + ckh_pool, + ) + .await + } + } + } + + pub async fn get_api_event_metrics( + &self, + metric: &ApiEventMetrics, + dimensions: &[ApiEventDimensions], + pub_key: &str, + filters: &ApiEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + ) -> types::MetricsResult<Vec<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> { + match self { + Self::Sqlx(_pool) => Err(MetricsError::NotImplemented).into_report(), + Self::Clickhouse(ckh_pool) + | Self::CombinedCkh(_, ckh_pool) + | Self::CombinedSqlx(_, ckh_pool) => { + // Since API events are ckh only use ckh here + metric + .load_metrics( + dimensions, + pub_key, + filters, + granularity, + time_range, + ckh_pool, + ) + .await + } + } + } + + pub async fn from_conf(config: &AnalyticsConfig) -> Self { + match config { + AnalyticsConfig::Sqlx { sqlx } => Self::Sqlx(SqlxClient::from_conf(sqlx).await), + AnalyticsConfig::Clickhouse { clickhouse } => Self::Clickhouse(ClickhouseClient { + config: Arc::new(clickhouse.clone()), + }), + AnalyticsConfig::CombinedCkh { sqlx, clickhouse } => Self::CombinedCkh( + SqlxClient::from_conf(sqlx).await, + ClickhouseClient { + config: Arc::new(clickhouse.clone()), + }, + ), + AnalyticsConfig::CombinedSqlx { sqlx, clickhouse } => Self::CombinedSqlx( + SqlxClient::from_conf(sqlx).await, + ClickhouseClient { + config: Arc::new(clickhouse.clone()), + }, + ), + } + } +} + +#[derive(Clone, Debug, serde::Deserialize)] +#[serde(tag = "source")] +#[serde(rename_all = "lowercase")] +pub enum AnalyticsConfig { + Sqlx { + sqlx: Database, + }, + Clickhouse { + clickhouse: ClickhouseConfig, + }, + CombinedCkh { + sqlx: Database, + clickhouse: ClickhouseConfig, + }, + CombinedSqlx { + sqlx: Database, + clickhouse: ClickhouseConfig, + }, +} + +impl Default for AnalyticsConfig { + fn default() -> Self { + Self::Sqlx { + sqlx: Database::default(), + } + } +} + +#[derive(Clone, Debug, serde::Deserialize, Default, serde::Serialize)] +pub struct ReportConfig { + pub payment_function: String, + pub refund_function: String, + pub dispute_function: String, + pub region: String, +} diff --git a/crates/analytics/src/main.rs b/crates/analytics/src/main.rs new file mode 100644 index 00000000000..5bf256ea978 --- /dev/null +++ b/crates/analytics/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello world"); +} diff --git a/crates/router/src/analytics/metrics.rs b/crates/analytics/src/metrics.rs similarity index 100% rename from crates/router/src/analytics/metrics.rs rename to crates/analytics/src/metrics.rs diff --git a/crates/router/src/analytics/metrics/request.rs b/crates/analytics/src/metrics/request.rs similarity index 51% rename from crates/router/src/analytics/metrics/request.rs rename to crates/analytics/src/metrics/request.rs index b7c202f2db2..3d1a78808f3 100644 --- a/crates/router/src/analytics/metrics/request.rs +++ b/crates/analytics/src/metrics/request.rs @@ -6,24 +6,20 @@ pub fn add_attributes<T: Into<router_env::opentelemetry::Value>>( } #[inline] -pub async fn record_operation_time<F, R>( +pub async fn record_operation_time<F, R, T>( future: F, metric: &once_cell::sync::Lazy<router_env::opentelemetry::metrics::Histogram<f64>>, - metric_name: &api_models::analytics::payments::PaymentMetrics, - source: &crate::analytics::AnalyticsProvider, + metric_name: &T, + source: &crate::AnalyticsProvider, ) -> R where F: futures::Future<Output = R>, + T: ToString, { let (result, time) = time_future(future).await; let attributes = &[ add_attributes("metric_name", metric_name.to_string()), - add_attributes( - "source", - match source { - crate::analytics::AnalyticsProvider::Sqlx(_) => "Sqlx", - }, - ), + add_attributes("source", source.to_string()), ]; let value = time.as_secs_f64(); metric.record(&super::CONTEXT, value, attributes); @@ -44,17 +40,3 @@ where let time_spent = start.elapsed(); (result, time_spent) } - -#[macro_export] -macro_rules! histogram_metric { - ($name:ident, $meter:ident) => { - pub(crate) static $name: once_cell::sync::Lazy< - $crate::opentelemetry::metrics::Histogram<u64>, - > = once_cell::sync::Lazy::new(|| $meter.u64_histogram(stringify!($name)).init()); - }; - ($name:ident, $meter:ident, $description:literal) => { - pub(crate) static $name: once_cell::sync::Lazy< - $crate::opentelemetry::metrics::Histogram<u64>, - > = once_cell::sync::Lazy::new(|| $meter.u64_histogram($description).init()); - }; -} diff --git a/crates/analytics/src/payments.rs b/crates/analytics/src/payments.rs new file mode 100644 index 00000000000..984647172c5 --- /dev/null +++ b/crates/analytics/src/payments.rs @@ -0,0 +1,16 @@ +pub mod accumulator; +mod core; +pub mod distribution; +pub mod filters; +pub mod metrics; +pub mod types; +pub use accumulator::{ + PaymentDistributionAccumulator, PaymentMetricAccumulator, PaymentMetricsAccumulator, +}; + +pub trait PaymentAnalytics: + metrics::PaymentMetricAnalytics + filters::PaymentFilterAnalytics +{ +} + +pub use self::core::{get_filters, get_metrics}; diff --git a/crates/router/src/analytics/payments/accumulator.rs b/crates/analytics/src/payments/accumulator.rs similarity index 62% rename from crates/router/src/analytics/payments/accumulator.rs rename to crates/analytics/src/payments/accumulator.rs index 5eebd097469..c340f2888f8 100644 --- a/crates/router/src/analytics/payments/accumulator.rs +++ b/crates/analytics/src/payments/accumulator.rs @@ -1,8 +1,9 @@ -use api_models::analytics::payments::PaymentMetricsBucketValue; -use common_enums::enums as storage_enums; +use api_models::analytics::payments::{ErrorResult, PaymentMetricsBucketValue}; +use bigdecimal::ToPrimitive; +use diesel_models::enums as storage_enums; use router_env::logger; -use super::metrics::PaymentMetricRow; +use super::{distribution::PaymentDistributionRow, metrics::PaymentMetricRow}; #[derive(Debug, Default)] pub struct PaymentMetricsAccumulator { @@ -11,6 +12,22 @@ pub struct PaymentMetricsAccumulator { pub payment_success: CountAccumulator, pub processed_amount: SumAccumulator, pub avg_ticket_size: AverageAccumulator, + pub payment_error_message: ErrorDistributionAccumulator, + pub retries_count: CountAccumulator, + pub retries_amount_processed: SumAccumulator, + pub connector_success_rate: SuccessRateAccumulator, +} + +#[derive(Debug, Default)] +pub struct ErrorDistributionRow { + pub count: i64, + pub total: i64, + pub error_message: String, +} + +#[derive(Debug, Default)] +pub struct ErrorDistributionAccumulator { + pub error_vec: Vec<ErrorDistributionRow>, } #[derive(Debug, Default)] @@ -45,6 +62,51 @@ pub trait PaymentMetricAccumulator { fn collect(self) -> Self::MetricOutput; } +pub trait PaymentDistributionAccumulator { + type DistributionOutput; + + fn add_distribution_bucket(&mut self, distribution: &PaymentDistributionRow); + + fn collect(self) -> Self::DistributionOutput; +} + +impl PaymentDistributionAccumulator for ErrorDistributionAccumulator { + type DistributionOutput = Option<Vec<ErrorResult>>; + + fn add_distribution_bucket(&mut self, distribution: &PaymentDistributionRow) { + self.error_vec.push(ErrorDistributionRow { + count: distribution.count.unwrap_or_default(), + total: distribution + .total + .clone() + .map(|i| i.to_i64().unwrap_or_default()) + .unwrap_or_default(), + error_message: distribution.error_message.clone().unwrap_or("".to_string()), + }) + } + + fn collect(mut self) -> Self::DistributionOutput { + if self.error_vec.is_empty() { + None + } else { + self.error_vec.sort_by(|a, b| b.count.cmp(&a.count)); + let mut res: Vec<ErrorResult> = Vec::new(); + for val in self.error_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(ErrorResult { + reason: val.error_message, + count: val.count, + percentage: (perc * 100.0).round() / 100.0, + }) + } + + Some(res) + } + } +} + impl PaymentMetricAccumulator for SuccessRateAccumulator { type MetricOutput = Option<f64>; @@ -145,6 +207,10 @@ impl PaymentMetricsAccumulator { payment_success_count: self.payment_success.collect(), payment_processed_amount: self.processed_amount.collect(), avg_ticket_size: self.avg_ticket_size.collect(), + payment_error_message: self.payment_error_message.collect(), + retries_count: self.retries_count.collect(), + retries_amount_processed: self.retries_amount_processed.collect(), + connector_success_rate: self.connector_success_rate.collect(), } } } diff --git a/crates/analytics/src/payments/core.rs b/crates/analytics/src/payments/core.rs new file mode 100644 index 00000000000..138e8878932 --- /dev/null +++ b/crates/analytics/src/payments/core.rs @@ -0,0 +1,303 @@ +#![allow(dead_code)] +use std::collections::HashMap; + +use api_models::analytics::{ + payments::{ + MetricsBucketResponse, PaymentDimensions, PaymentDistributions, PaymentMetrics, + PaymentMetricsBucketIdentifier, + }, + AnalyticsMetadata, FilterValue, GetPaymentFiltersRequest, GetPaymentMetricRequest, + MetricsResponse, PaymentFiltersResponse, +}; +use common_utils::errors::CustomResult; +use error_stack::{IntoReport, ResultExt}; +use router_env::{ + instrument, logger, + tracing::{self, Instrument}, +}; + +use super::{ + distribution::PaymentDistributionRow, + filters::{get_payment_filter_for_dimension, FilterRow}, + metrics::PaymentMetricRow, + PaymentMetricsAccumulator, +}; +use crate::{ + errors::{AnalyticsError, AnalyticsResult}, + metrics, + payments::{PaymentDistributionAccumulator, PaymentMetricAccumulator}, + AnalyticsProvider, +}; + +#[derive(Debug)] +pub enum TaskType { + MetricTask( + PaymentMetrics, + CustomResult<Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, AnalyticsError>, + ), + DistributionTask( + PaymentDistributions, + CustomResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>, AnalyticsError>, + ), +} + +#[instrument(skip_all)] +pub async fn get_metrics( + pool: &AnalyticsProvider, + merchant_id: &str, + req: GetPaymentMetricRequest, +) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> { + let mut metrics_accumulator: HashMap< + PaymentMetricsBucketIdentifier, + PaymentMetricsAccumulator, + > = HashMap::new(); + + let mut set = tokio::task::JoinSet::new(); + for metric_type in req.metrics.iter().cloned() { + let req = req.clone(); + let pool = pool.clone(); + let task_span = tracing::debug_span!( + "analytics_payments_metrics_query", + payment_metric = metric_type.as_ref() + ); + + // TODO: lifetime issues with joinset, + // can be optimized away if joinset lifetime requirements are relaxed + let merchant_id_scoped = merchant_id.to_owned(); + set.spawn( + async move { + let data = pool + .get_payment_metrics( + &metric_type, + &req.group_by_names.clone(), + &merchant_id_scoped, + &req.filters, + &req.time_series.map(|t| t.granularity), + &req.time_range, + ) + .await + .change_context(AnalyticsError::UnknownError); + 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_payments_distribution_query", + payment_distribution = distribution.distribution_for.as_ref() + ); + + let merchant_id_scoped = merchant_id.to_owned(); + set.spawn( + async move { + let data = pool + .get_payment_distribution( + &distribution, + &req.group_by_names.clone(), + &merchant_id_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(task_type) = set + .join_next() + .await + .transpose() + .into_report() + .change_context(AnalyticsError::UnknownError)? + { + match task_type { + TaskType::MetricTask(metric, data) => { + let data = data?; + let attributes = &[ + metrics::request::add_attributes("metric_type", metric.to_string()), + metrics::request::add_attributes("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); + } + + 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 { + PaymentMetrics::PaymentSuccessRate => metrics_builder + .payment_success_rate + .add_metrics_bucket(&value), + PaymentMetrics::PaymentCount => { + metrics_builder.payment_count.add_metrics_bucket(&value) + } + PaymentMetrics::PaymentSuccessCount => { + metrics_builder.payment_success.add_metrics_bucket(&value) + } + PaymentMetrics::PaymentProcessedAmount => { + metrics_builder.processed_amount.add_metrics_bucket(&value) + } + PaymentMetrics::AvgTicketSize => { + metrics_builder.avg_ticket_size.add_metrics_bucket(&value) + } + PaymentMetrics::RetriesCount => { + metrics_builder.retries_count.add_metrics_bucket(&value); + metrics_builder + .retries_amount_processed + .add_metrics_bucket(&value) + } + PaymentMetrics::ConnectorSuccessRate => { + metrics_builder + .connector_success_rate + .add_metrics_bucket(&value); + } + } + } + + logger::debug!( + "Analytics Accumulated Results: metric: {}, results: {:#?}", + metric, + metrics_accumulator + ); + } + TaskType::DistributionTask(distribution, data) => { + let data = data?; + let attributes = &[ + metrics::request::add_attributes("distribution_type", distribution.to_string()), + metrics::request::add_attributes("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); + } + + for (id, value) in data { + logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for distribution {distribution}"); + let metrics_accumulator = metrics_accumulator.entry(id).or_default(); + match distribution { + PaymentDistributions::PaymentErrorMessage => metrics_accumulator + .payment_error_message + .add_distribution_bucket(&value), + } + } + + logger::debug!( + "Analytics Accumulated Results: distribution: {}, results: {:#?}", + distribution, + metrics_accumulator + ); + } + } + } + + let query_data: Vec<MetricsBucketResponse> = metrics_accumulator + .into_iter() + .map(|(id, val)| MetricsBucketResponse { + values: val.collect(), + dimensions: id, + }) + .collect(); + + Ok(MetricsResponse { + query_data, + meta_data: [AnalyticsMetadata { + current_time_range: req.time_range, + }], + }) +} + +pub async fn get_filters( + pool: &AnalyticsProvider, + req: GetPaymentFiltersRequest, + merchant_id: &String, +) -> AnalyticsResult<PaymentFiltersResponse> { + let mut res = PaymentFiltersResponse::default(); + + for dim in req.group_by_names { + let values = match pool { + AnalyticsProvider::Sqlx(pool) => { + get_payment_filter_for_dimension(dim, merchant_id, &req.time_range, pool) + .await + } + AnalyticsProvider::Clickhouse(pool) => { + get_payment_filter_for_dimension(dim, merchant_id, &req.time_range, pool) + .await + } + AnalyticsProvider::CombinedCkh(sqlx_poll, ckh_pool) => { + let ckh_result = get_payment_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + ckh_pool, + ) + .await; + let sqlx_result = get_payment_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + sqlx_poll, + ) + .await; + 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 filters") + }, + _ => {} + }; + ckh_result + } + AnalyticsProvider::CombinedSqlx(sqlx_poll, ckh_pool) => { + let ckh_result = get_payment_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + ckh_pool, + ) + .await; + let sqlx_result = get_payment_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + sqlx_poll, + ) + .await; + 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 filters") + }, + _ => {} + }; + sqlx_result + } + } + .change_context(AnalyticsError::UnknownError)? + .into_iter() + .filter_map(|fil: FilterRow| match dim { + PaymentDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()), + PaymentDimensions::PaymentStatus => fil.status.map(|i| i.as_ref().to_string()), + PaymentDimensions::Connector => fil.connector, + PaymentDimensions::AuthType => fil.authentication_type.map(|i| i.as_ref().to_string()), + PaymentDimensions::PaymentMethod => fil.payment_method, + PaymentDimensions::PaymentMethodType => fil.payment_method_type, + }) + .collect::<Vec<String>>(); + res.query_data.push(FilterValue { + dimension: dim, + values, + }) + } + Ok(res) +} diff --git a/crates/analytics/src/payments/distribution.rs b/crates/analytics/src/payments/distribution.rs new file mode 100644 index 00000000000..cf18c26310a --- /dev/null +++ b/crates/analytics/src/payments/distribution.rs @@ -0,0 +1,92 @@ +use api_models::analytics::{ + payments::{ + PaymentDimensions, PaymentDistributions, PaymentFilters, PaymentMetricsBucketIdentifier, + }, + Distribution, Granularity, TimeRange, +}; +use diesel_models::enums as storage_enums; +use time::PrimitiveDateTime; + +use crate::{ + query::{Aggregate, GroupByClause, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, +}; + +mod payment_error_message; + +use payment_error_message::PaymentErrorMessage; + +#[derive(Debug, PartialEq, Eq, serde::Deserialize)] +pub struct PaymentDistributionRow { + pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, + pub status: Option<DBEnumWrapper<storage_enums::AttemptStatus>>, + pub connector: Option<String>, + pub authentication_type: Option<DBEnumWrapper<storage_enums::AuthenticationType>>, + pub payment_method: Option<String>, + pub payment_method_type: Option<String>, + pub total: Option<bigdecimal::BigDecimal>, + pub count: Option<i64>, + pub 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 PaymentDistributionAnalytics: LoadRow<PaymentDistributionRow> {} + +#[async_trait::async_trait] +pub trait PaymentDistribution<T> +where + T: AnalyticsDataSource + PaymentDistributionAnalytics, +{ + #[allow(clippy::too_many_arguments)] + async fn load_distribution( + &self, + distribution: &Distribution, + dimensions: &[PaymentDimensions], + merchant_id: &str, + filters: &PaymentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>>; +} + +#[async_trait::async_trait] +impl<T> PaymentDistribution<T> for PaymentDistributions +where + T: AnalyticsDataSource + PaymentDistributionAnalytics, + 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: &Distribution, + dimensions: &[PaymentDimensions], + merchant_id: &str, + filters: &PaymentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>> { + match self { + Self::PaymentErrorMessage => { + PaymentErrorMessage + .load_distribution( + distribution, + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + } + } +} diff --git a/crates/analytics/src/payments/distribution/payment_error_message.rs b/crates/analytics/src/payments/distribution/payment_error_message.rs new file mode 100644 index 00000000000..c70fc09aeac --- /dev/null +++ b/crates/analytics/src/payments/distribution/payment_error_message.rs @@ -0,0 +1,176 @@ +use api_models::analytics::{ + payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, + Distribution, Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use diesel_models::enums as storage_enums; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::{PaymentDistribution, PaymentDistributionRow}; +use crate::{ + query::{ + Aggregate, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct PaymentErrorMessage; + +#[async_trait::async_trait] +impl<T> PaymentDistribution<T> for PaymentErrorMessage +where + T: AnalyticsDataSource + super::PaymentDistributionAnalytics, + 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: &Distribution, + dimensions: &[PaymentDimensions], + merchant_id: &str, + filters: &PaymentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>> { + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Payment); + + 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()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .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()?; + } + + query_builder + .add_filter_clause( + PaymentDimensions::PaymentStatus, + storage_enums::AttemptStatus::Failure, + ) + .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::<PaymentDistributionRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + i.status.as_ref().map(|i| i.0), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.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<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/router/src/analytics/payments/filters.rs b/crates/analytics/src/payments/filters.rs similarity index 87% rename from crates/router/src/analytics/payments/filters.rs rename to crates/analytics/src/payments/filters.rs index f009aaa7632..6c165f78a8e 100644 --- a/crates/router/src/analytics/payments/filters.rs +++ b/crates/analytics/src/payments/filters.rs @@ -1,11 +1,11 @@ use api_models::analytics::{payments::PaymentDimensions, Granularity, TimeRange}; -use common_enums::enums::{AttemptStatus, AuthenticationType, Currency}; use common_utils::errors::ReportSwitchExt; +use diesel_models::enums::{AttemptStatus, AuthenticationType, Currency}; use error_stack::ResultExt; use time::PrimitiveDateTime; -use crate::analytics::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql}, +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{ AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, FiltersError, FiltersResult, LoadRow, @@ -26,6 +26,7 @@ where AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Payment); @@ -48,11 +49,12 @@ where .change_context(FiltersError::QueryExecutionFailure) } -#[derive(Debug, serde::Serialize, Eq, PartialEq)] +#[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] pub struct FilterRow { pub currency: Option<DBEnumWrapper<Currency>>, pub status: Option<DBEnumWrapper<AttemptStatus>>, pub connector: Option<String>, pub authentication_type: Option<DBEnumWrapper<AuthenticationType>>, pub payment_method: Option<String>, + pub payment_method_type: Option<String>, } diff --git a/crates/router/src/analytics/payments/metrics.rs b/crates/analytics/src/payments/metrics.rs similarity index 76% rename from crates/router/src/analytics/payments/metrics.rs rename to crates/analytics/src/payments/metrics.rs index f492e5bd4df..6fe6b6260d4 100644 --- a/crates/router/src/analytics/payments/metrics.rs +++ b/crates/analytics/src/payments/metrics.rs @@ -2,36 +2,44 @@ use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetrics, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, }; -use common_enums::enums as storage_enums; +use diesel_models::enums as storage_enums; use time::PrimitiveDateTime; -use crate::analytics::{ - query::{Aggregate, GroupByClause, ToSql}, +use crate::{ + query::{Aggregate, GroupByClause, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, }; mod avg_ticket_size; +mod connector_success_rate; mod payment_count; mod payment_processed_amount; mod payment_success_count; +mod retries_count; mod success_rate; use avg_ticket_size::AvgTicketSize; +use connector_success_rate::ConnectorSuccessRate; use payment_count::PaymentCount; use payment_processed_amount::PaymentProcessedAmount; use payment_success_count::PaymentSuccessCount; use success_rate::PaymentSuccessRate; -#[derive(Debug, PartialEq, Eq)] +use self::retries_count::RetriesCount; + +#[derive(Debug, PartialEq, Eq, serde::Deserialize)] pub struct PaymentMetricRow { pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, pub status: Option<DBEnumWrapper<storage_enums::AttemptStatus>>, pub connector: Option<String>, pub authentication_type: Option<DBEnumWrapper<storage_enums::AuthenticationType>>, pub payment_method: Option<String>, + pub payment_method_type: Option<String>, pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, + #[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>, } @@ -61,6 +69,7 @@ where AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, @@ -132,6 +141,30 @@ where ) .await } + Self::RetriesCount => { + RetriesCount + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::ConnectorSuccessRate => { + ConnectorSuccessRate + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } } } } diff --git a/crates/router/src/analytics/payments/metrics/avg_ticket_size.rs b/crates/analytics/src/payments/metrics/avg_ticket_size.rs similarity index 90% rename from crates/router/src/analytics/payments/metrics/avg_ticket_size.rs rename to crates/analytics/src/payments/metrics/avg_ticket_size.rs index 2230d870e68..9475d5288a6 100644 --- a/crates/router/src/analytics/payments/metrics/avg_ticket_size.rs +++ b/crates/analytics/src/payments/metrics/avg_ticket_size.rs @@ -3,12 +3,13 @@ use api_models::analytics::{ Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; +use diesel_models::enums as storage_enums; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::{PaymentMetric, PaymentMetricRow}; -use crate::analytics::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql}, +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -23,6 +24,7 @@ where AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, @@ -89,6 +91,13 @@ where .switch()?; } + query_builder + .add_filter_clause( + PaymentDimensions::PaymentStatus, + storage_enums::AttemptStatus::Charged, + ) + .switch()?; + query_builder .execute_query::<PaymentMetricRow, _>(pool) .await @@ -103,6 +112,7 @@ where i.connector.clone(), i.authentication_type.as_ref().map(|i| i.0), i.payment_method.clone(), + i.payment_method_type.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, @@ -119,7 +129,7 @@ where }) .collect::<error_stack::Result< Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, - crate::analytics::query::PostProcessingError, + crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } diff --git a/crates/analytics/src/payments/metrics/connector_success_rate.rs b/crates/analytics/src/payments/metrics/connector_success_rate.rs new file mode 100644 index 00000000000..0c4d19b2e0b --- /dev/null +++ b/crates/analytics/src/payments/metrics/connector_success_rate.rs @@ -0,0 +1,130 @@ +use api_models::analytics::{ + payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentMetricRow; +use crate::{ + query::{ + Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, + Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct ConnectorSuccessRate; + +#[async_trait::async_trait] +impl<T> super::PaymentMetric<T> for ConnectorSuccessRate +where + T: AnalyticsDataSource + super::PaymentMetricAnalytics, + 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: &[PaymentDimensions], + merchant_id: &str, + filters: &PaymentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Payment); + let mut dimensions = dimensions.to_vec(); + + dimensions.push(PaymentDimensions::PaymentStatus); + + 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()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + query_builder + .add_custom_filter_clause(PaymentDimensions::Connector, "NULL", FilterTypes::IsNotNull) + .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::<PaymentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + None, + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.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<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/router/src/analytics/payments/metrics/payment_count.rs b/crates/analytics/src/payments/metrics/payment_count.rs similarity index 94% rename from crates/router/src/analytics/payments/metrics/payment_count.rs rename to crates/analytics/src/payments/metrics/payment_count.rs index 661cec3dac3..34e71f3da6f 100644 --- a/crates/router/src/analytics/payments/metrics/payment_count.rs +++ b/crates/analytics/src/payments/metrics/payment_count.rs @@ -7,8 +7,8 @@ use error_stack::ResultExt; use time::PrimitiveDateTime; use super::PaymentMetricRow; -use crate::analytics::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql}, +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -23,6 +23,7 @@ where AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, @@ -97,6 +98,7 @@ where i.connector.clone(), i.authentication_type.as_ref().map(|i| i.0), i.payment_method.clone(), + i.payment_method_type.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, @@ -111,7 +113,7 @@ where i, )) }) - .collect::<error_stack::Result<Vec<_>, crate::analytics::query::PostProcessingError>>() + .collect::<error_stack::Result<Vec<_>, crate::query::PostProcessingError>>() .change_context(MetricsError::PostProcessingFailure) } } diff --git a/crates/router/src/analytics/payments/metrics/payment_processed_amount.rs b/crates/analytics/src/payments/metrics/payment_processed_amount.rs similarity index 94% rename from crates/router/src/analytics/payments/metrics/payment_processed_amount.rs rename to crates/analytics/src/payments/metrics/payment_processed_amount.rs index 2ec0c6f18f9..f2dbf97e0db 100644 --- a/crates/router/src/analytics/payments/metrics/payment_processed_amount.rs +++ b/crates/analytics/src/payments/metrics/payment_processed_amount.rs @@ -2,14 +2,14 @@ use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, }; -use common_enums::enums as storage_enums; use common_utils::errors::ReportSwitchExt; +use diesel_models::enums as storage_enums; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::PaymentMetricRow; -use crate::analytics::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql}, +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -24,6 +24,7 @@ where AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, @@ -105,6 +106,7 @@ where i.connector.clone(), i.authentication_type.as_ref().map(|i| i.0), i.payment_method.clone(), + i.payment_method_type.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, @@ -121,7 +123,7 @@ where }) .collect::<error_stack::Result< Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, - crate::analytics::query::PostProcessingError, + crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } diff --git a/crates/router/src/analytics/payments/metrics/payment_success_count.rs b/crates/analytics/src/payments/metrics/payment_success_count.rs similarity index 94% rename from crates/router/src/analytics/payments/metrics/payment_success_count.rs rename to crates/analytics/src/payments/metrics/payment_success_count.rs index 8245fe7aeb8..a6fb8ed2239 100644 --- a/crates/router/src/analytics/payments/metrics/payment_success_count.rs +++ b/crates/analytics/src/payments/metrics/payment_success_count.rs @@ -2,14 +2,14 @@ use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, }; -use common_enums::enums as storage_enums; use common_utils::errors::ReportSwitchExt; +use diesel_models::enums as storage_enums; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::PaymentMetricRow; -use crate::analytics::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql}, +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -24,6 +24,7 @@ where AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, @@ -104,6 +105,7 @@ where i.connector.clone(), i.authentication_type.as_ref().map(|i| i.0), i.payment_method.clone(), + i.payment_method_type.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, @@ -120,7 +122,7 @@ where }) .collect::<error_stack::Result< Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, - crate::analytics::query::PostProcessingError, + crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } diff --git a/crates/analytics/src/payments/metrics/retries_count.rs b/crates/analytics/src/payments/metrics/retries_count.rs new file mode 100644 index 00000000000..91952adb569 --- /dev/null +++ b/crates/analytics/src/payments/metrics/retries_count.rs @@ -0,0 +1,122 @@ +use api_models::analytics::{ + payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentMetricRow; +use crate::{ + query::{ + Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, + Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct RetriesCount; + +#[async_trait::async_trait] +impl<T> super::PaymentMetric<T> for RetriesCount +where + T: AnalyticsDataSource + super::PaymentMetricAnalytics, + 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: &[PaymentDimensions], + merchant_id: &str, + _filters: &PaymentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentIntent); + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .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()?; + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + query_builder + .add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt) + .switch()?; + query_builder + .add_custom_filter_clause("status", "succeeded", FilterTypes::Equal) + .switch()?; + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .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::<PaymentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + None, + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.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<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/router/src/analytics/payments/metrics/success_rate.rs b/crates/analytics/src/payments/metrics/success_rate.rs similarity index 95% rename from crates/router/src/analytics/payments/metrics/success_rate.rs rename to crates/analytics/src/payments/metrics/success_rate.rs index c63956d4b15..9e688240ddb 100644 --- a/crates/router/src/analytics/payments/metrics/success_rate.rs +++ b/crates/analytics/src/payments/metrics/success_rate.rs @@ -7,8 +7,8 @@ use error_stack::ResultExt; use time::PrimitiveDateTime; use super::PaymentMetricRow; -use crate::analytics::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql}, +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -23,6 +23,7 @@ where AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, @@ -100,6 +101,7 @@ where i.connector.clone(), i.authentication_type.as_ref().map(|i| i.0), i.payment_method.clone(), + i.payment_method_type.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, @@ -116,7 +118,7 @@ where }) .collect::<error_stack::Result< Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, - crate::analytics::query::PostProcessingError, + crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } diff --git a/crates/router/src/analytics/payments/types.rs b/crates/analytics/src/payments/types.rs similarity index 82% rename from crates/router/src/analytics/payments/types.rs rename to crates/analytics/src/payments/types.rs index fdfbedef383..d5d8eca13e5 100644 --- a/crates/router/src/analytics/payments/types.rs +++ b/crates/analytics/src/payments/types.rs @@ -1,7 +1,7 @@ use api_models::analytics::payments::{PaymentDimensions, PaymentFilters}; use error_stack::ResultExt; -use crate::analytics::{ +use crate::{ query::{QueryBuilder, QueryFilter, QueryResult, ToSql}, types::{AnalyticsCollection, AnalyticsDataSource}, }; @@ -41,6 +41,15 @@ where .add_filter_in_range_clause(PaymentDimensions::PaymentMethod, &self.payment_method) .attach_printable("Error adding payment method filter")?; } + + if !self.payment_method_type.is_empty() { + builder + .add_filter_in_range_clause( + PaymentDimensions::PaymentMethodType, + &self.payment_method_type, + ) + .attach_printable("Error adding payment method filter")?; + } Ok(()) } } diff --git a/crates/router/src/analytics/query.rs b/crates/analytics/src/query.rs similarity index 65% rename from crates/router/src/analytics/query.rs rename to crates/analytics/src/query.rs index b1f621d8153..b924987f004 100644 --- a/crates/router/src/analytics/query.rs +++ b/crates/analytics/src/query.rs @@ -1,26 +1,26 @@ -#![allow(dead_code)] use std::marker::PhantomData; use api_models::{ analytics::{ self as analytics_api, - payments::PaymentDimensions, + api_event::ApiEventDimensions, + payments::{PaymentDimensions, PaymentDistributions}, refunds::{RefundDimensions, RefundType}, + sdk_events::{SdkEventDimensions, SdkEventNames}, Granularity, }, - enums::Connector, + enums::{ + AttemptStatus, AuthenticationType, Connector, Currency, PaymentMethod, PaymentMethodType, + }, refunds::RefundStatus, }; -use common_enums::{ - enums as storage_enums, - enums::{AttemptStatus, AuthenticationType, Currency, PaymentMethod}, -}; use common_utils::errors::{CustomResult, ParsingError}; +use diesel_models::enums as storage_enums; use error_stack::{IntoReport, ResultExt}; -use router_env::logger; +use router_env::{logger, Flow}; -use super::types::{AnalyticsCollection, AnalyticsDataSource, LoadRow}; -use crate::analytics::types::QueryExecutionError; +use super::types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, TableEngine}; +use crate::types::QueryExecutionError; pub type QueryResult<T> = error_stack::Result<T, QueryBuildingError>; pub trait QueryFilter<T> where @@ -89,12 +89,12 @@ impl GroupByClause<super::SqlxClient> for Granularity { let granularity_divisor = self.get_bucket_size(); builder - .add_group_by_clause(format!("DATE_TRUNC('{trunc_scale}', modified_at)")) + .add_group_by_clause(format!("DATE_TRUNC('{trunc_scale}', created_at)")) .attach_printable("Error adding time prune group by")?; if let Some(scale) = granularity_bucket_scale { builder .add_group_by_clause(format!( - "FLOOR(DATE_PART('{scale}', modified_at)/{granularity_divisor})" + "FLOOR(DATE_PART('{scale}', created_at)/{granularity_divisor})" )) .attach_printable("Error adding time binning group by")?; } @@ -102,6 +102,26 @@ impl GroupByClause<super::SqlxClient> for Granularity { } } +impl GroupByClause<super::ClickhouseClient> for Granularity { + fn set_group_by_clause( + &self, + builder: &mut QueryBuilder<super::ClickhouseClient>, + ) -> QueryResult<()> { + let interval = match self { + Self::OneMin => "toStartOfMinute(created_at)", + Self::FiveMin => "toStartOfFiveMinutes(created_at)", + Self::FifteenMin => "toStartOfFifteenMinutes(created_at)", + Self::ThirtyMin => "toStartOfInterval(created_at, INTERVAL 30 minute)", + Self::OneHour => "toStartOfHour(created_at)", + Self::OneDay => "toStartOfDay(created_at)", + }; + + builder + .add_group_by_clause(interval) + .attach_printable("Error adding interval group by") + } +} + #[derive(strum::Display)] #[strum(serialize_all = "lowercase")] pub enum TimeGranularityLevel { @@ -229,6 +249,76 @@ pub enum Aggregate<R> { }, } +// Window functions in query +// --- +// Description - +// field: to_sql type value used as expr in aggregation +// partition_by: partition by fields in window +// order_by: order by fields and order (Ascending / Descending) in window +// alias: alias of window expr in query +// --- +// Usage - +// Window::Sum { +// field: "count", +// partition_by: Some(query_builder.transform_to_sql_values(&dimensions).switch()?), +// order_by: Some(("value", Descending)), +// alias: Some("total"), +// } +#[derive(Debug)] +pub enum Window<R> { + Sum { + field: R, + partition_by: Option<String>, + order_by: Option<(String, Order)>, + alias: Option<&'static str>, + }, + RowNumber { + field: R, + partition_by: Option<String>, + order_by: Option<(String, Order)>, + alias: Option<&'static str>, + }, +} + +#[derive(Debug, Clone, Copy)] +pub enum Order { + Ascending, + Descending, +} + +impl ToString for Order { + fn to_string(&self) -> String { + String::from(match self { + Self::Ascending => "asc", + Self::Descending => "desc", + }) + } +} + +// Select TopN values for a group based on a metric +// --- +// Description - +// columns: Columns in group to select TopN values for +// count: N in TopN +// order_column: metric used to sort and limit TopN +// order: sort order of metric (Ascending / Descending) +// --- +// Usage - +// Use via add_top_n_clause fn of query_builder +// add_top_n_clause( +// &dimensions, +// distribution.distribution_cardinality.into(), +// "count", +// Order::Descending, +// ) +#[derive(Debug)] +pub struct TopN { + pub columns: String, + pub count: u64, + pub order_column: String, + pub order: Order, +} + #[derive(Debug)] pub struct QueryBuilder<T> where @@ -239,13 +329,16 @@ where filters: Vec<(String, FilterTypes, String)>, group_by: Vec<String>, having: Option<Vec<(String, FilterTypes, String)>>, + outer_select: Vec<String>, + top_n: Option<TopN>, table: AnalyticsCollection, distinct: bool, db_type: PhantomData<T>, + table_engine: TableEngine, } pub trait ToSql<T: AnalyticsDataSource> { - fn to_sql(&self) -> error_stack::Result<String, ParsingError>; + fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError>; } /// Implement `ToSql` on arrays of types that impl `ToString`. @@ -253,7 +346,7 @@ macro_rules! impl_to_sql_for_to_string { ($($type:ty),+) => { $( impl<T: AnalyticsDataSource> ToSql<T> for $type { - fn to_sql(&self) -> error_stack::Result<String, ParsingError> { + fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.to_string()) } } @@ -267,8 +360,10 @@ impl_to_sql_for_to_string!( &PaymentDimensions, &RefundDimensions, PaymentDimensions, + &PaymentDistributions, RefundDimensions, PaymentMethod, + PaymentMethodType, AuthenticationType, Connector, AttemptStatus, @@ -276,12 +371,18 @@ impl_to_sql_for_to_string!( storage_enums::RefundStatus, Currency, RefundType, + Flow, &String, &bool, - &u64 + &u64, + u64, + Order ); -#[allow(dead_code)] +impl_to_sql_for_to_string!(&SdkEventDimensions, SdkEventDimensions, SdkEventNames); + +impl_to_sql_for_to_string!(&ApiEventDimensions, ApiEventDimensions); + #[derive(Debug)] pub enum FilterTypes { Equal, @@ -290,6 +391,23 @@ pub enum FilterTypes { Gte, Lte, Gt, + Like, + NotLike, + IsNotNull, +} + +pub fn filter_type_to_sql(l: &String, op: &FilterTypes, r: &String) -> String { + match op { + FilterTypes::EqualBool => format!("{l} = {r}"), + FilterTypes::Equal => format!("{l} = '{r}'"), + FilterTypes::In => format!("{l} IN ({r})"), + FilterTypes::Gte => format!("{l} >= '{r}'"), + FilterTypes::Gt => format!("{l} > {r}"), + FilterTypes::Lte => format!("{l} <= '{r}'"), + FilterTypes::Like => format!("{l} LIKE '%{r}%'"), + FilterTypes::NotLike => format!("{l} NOT LIKE '%{r}%'"), + FilterTypes::IsNotNull => format!("{l} IS NOT NULL"), + } } impl<T> QueryBuilder<T> @@ -303,22 +421,68 @@ where filters: Default::default(), group_by: Default::default(), having: Default::default(), + outer_select: Default::default(), + top_n: Default::default(), table, distinct: Default::default(), db_type: Default::default(), + table_engine: T::get_table_engine(table), } } pub fn add_select_column(&mut self, column: impl ToSql<T>) -> QueryResult<()> { self.columns.push( column - .to_sql() + .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing select column")?, ); Ok(()) } + pub fn transform_to_sql_values(&mut self, values: &[impl ToSql<T>]) -> QueryResult<String> { + let res = values + .iter() + .map(|i| i.to_sql(&self.table_engine)) + .collect::<error_stack::Result<Vec<String>, ParsingError>>() + .change_context(QueryBuildingError::SqlSerializeError) + .attach_printable("Error serializing range filter value")? + .join(", "); + Ok(res) + } + + pub fn add_top_n_clause( + &mut self, + columns: &[impl ToSql<T>], + count: u64, + order_column: impl ToSql<T>, + order: Order, + ) -> QueryResult<()> + where + Window<&'static str>: ToSql<T>, + { + let partition_by_columns = self.transform_to_sql_values(columns)?; + let order_by_column = order_column + .to_sql(&self.table_engine) + .change_context(QueryBuildingError::SqlSerializeError) + .attach_printable("Error serializing select column")?; + + self.add_outer_select_column(Window::RowNumber { + field: "", + partition_by: Some(partition_by_columns.clone()), + order_by: Some((order_by_column.clone(), order)), + alias: Some("top_n"), + })?; + + self.top_n = Some(TopN { + columns: partition_by_columns, + count, + order_column: order_by_column, + order, + }); + Ok(()) + } + pub fn set_distinct(&mut self) { self.distinct = true } @@ -346,11 +510,11 @@ where comparison: FilterTypes, ) -> QueryResult<()> { self.filters.push(( - lhs.to_sql() + lhs.to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing filter key")?, comparison, - rhs.to_sql() + rhs.to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing filter value")?, )); @@ -366,7 +530,7 @@ where .iter() .map(|i| { // trimming whitespaces from the filter values received in request, to prevent a possibility of an SQL injection - i.to_sql().map(|s| { + i.to_sql(&self.table_engine).map(|s| { let trimmed_str = s.replace(' ', ""); format!("'{trimmed_str}'") }) @@ -381,7 +545,7 @@ where pub fn add_group_by_clause(&mut self, column: impl ToSql<T>) -> QueryResult<()> { self.group_by.push( column - .to_sql() + .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing group by field")?, ); @@ -406,14 +570,7 @@ where fn get_filter_clause(&self) -> String { self.filters .iter() - .map(|(l, op, r)| match op { - FilterTypes::EqualBool => format!("{l} = {r}"), - FilterTypes::Equal => format!("{l} = '{r}'"), - FilterTypes::In => format!("{l} IN ({r})"), - FilterTypes::Gte => format!("{l} >= '{r}'"), - FilterTypes::Gt => format!("{l} > {r}"), - FilterTypes::Lte => format!("{l} <= '{r}'"), - }) + .map(|(l, op, r)| filter_type_to_sql(l, op, r)) .collect::<Vec<String>>() .join(" AND ") } @@ -426,7 +583,10 @@ where self.group_by.join(", ") } - #[allow(dead_code)] + fn get_outer_select_clause(&self) -> String { + self.outer_select.join(", ") + } + pub fn add_having_clause<R>( &mut self, aggregate: Aggregate<R>, @@ -437,11 +597,11 @@ where Aggregate<R>: ToSql<T>, { let aggregate = aggregate - .to_sql() + .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing having aggregate")?; let value = value - .to_sql() + .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing having value")?; let entry = (aggregate, filter_type, value); @@ -453,16 +613,20 @@ where Ok(()) } + pub fn add_outer_select_column(&mut self, column: impl ToSql<T>) -> QueryResult<()> { + self.outer_select.push( + column + .to_sql(&self.table_engine) + .change_context(QueryBuildingError::SqlSerializeError) + .attach_printable("Error serializing outer select column")?, + ); + Ok(()) + } + pub fn get_filter_type_clause(&self) -> Option<String> { self.having.as_ref().map(|vec| { vec.iter() - .map(|(l, op, r)| match op { - FilterTypes::Equal | FilterTypes::EqualBool => format!("{l} = {r}"), - FilterTypes::In => format!("{l} IN ({r})"), - FilterTypes::Gte => format!("{l} >= {r}"), - FilterTypes::Lte => format!("{l} < {r}"), - FilterTypes::Gt => format!("{l} > {r}"), - }) + .map(|(l, op, r)| filter_type_to_sql(l, op, r)) .collect::<Vec<String>>() .join(" AND ") }) @@ -471,6 +635,7 @@ where pub fn build_query(&mut self) -> QueryResult<String> where Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, { if self.columns.is_empty() { Err(QueryBuildingError::InvalidQuery( @@ -491,7 +656,7 @@ where query.push_str( &self .table - .to_sql() + .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing table value")?, ); @@ -504,6 +669,16 @@ where if !self.group_by.is_empty() { query.push_str(" GROUP BY "); query.push_str(&self.get_group_by_clause()); + if let TableEngine::CollapsingMergeTree { sign } = self.table_engine { + self.add_having_clause( + Aggregate::Count { + field: Some(sign), + alias: None, + }, + FilterTypes::Gte, + "1", + )?; + } } if self.having.is_some() { @@ -512,6 +687,22 @@ where query.push_str(condition.as_str()); } } + + if !self.outer_select.is_empty() { + query.insert_str( + 0, + format!("SELECT {} FROM (", &self.get_outer_select_clause()).as_str(), + ); + query.push_str(") _"); + } + + if let Some(top_n) = &self.top_n { + query.insert_str(0, "SELECT * FROM ("); + query.push_str(format!(") _ WHERE top_n <= {}", top_n.count).as_str()); + } + + println!("{}", query); + Ok(query) } @@ -522,6 +713,7 @@ where where P: LoadRow<R>, Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, { let query = self .build_query() diff --git a/crates/router/src/analytics/refunds.rs b/crates/analytics/src/refunds.rs similarity index 81% rename from crates/router/src/analytics/refunds.rs rename to crates/analytics/src/refunds.rs index a8b52effe76..53481e23281 100644 --- a/crates/router/src/analytics/refunds.rs +++ b/crates/analytics/src/refunds.rs @@ -7,4 +7,4 @@ pub mod types; pub use accumulator::{RefundMetricAccumulator, RefundMetricsAccumulator}; pub trait RefundAnalytics: metrics::RefundMetricAnalytics {} -pub use self::core::get_metrics; +pub use self::core::{get_filters, get_metrics}; diff --git a/crates/router/src/analytics/refunds/accumulator.rs b/crates/analytics/src/refunds/accumulator.rs similarity index 98% rename from crates/router/src/analytics/refunds/accumulator.rs rename to crates/analytics/src/refunds/accumulator.rs index 3d0c0e659f6..9c51defdcf9 100644 --- a/crates/router/src/analytics/refunds/accumulator.rs +++ b/crates/analytics/src/refunds/accumulator.rs @@ -1,5 +1,5 @@ use api_models::analytics::refunds::RefundMetricsBucketValue; -use common_enums::enums as storage_enums; +use diesel_models::enums as storage_enums; use super::metrics::RefundMetricRow; #[derive(Debug, Default)] @@ -15,13 +15,11 @@ pub struct SuccessRateAccumulator { pub success: i64, pub total: i64, } - #[derive(Debug, Default)] #[repr(transparent)] pub struct CountAccumulator { pub count: Option<i64>, } - #[derive(Debug, Default)] #[repr(transparent)] pub struct SumAccumulator { diff --git a/crates/analytics/src/refunds/core.rs b/crates/analytics/src/refunds/core.rs new file mode 100644 index 00000000000..25a1e228f56 --- /dev/null +++ b/crates/analytics/src/refunds/core.rs @@ -0,0 +1,203 @@ +#![allow(dead_code)] +use std::collections::HashMap; + +use api_models::analytics::{ + refunds::{ + RefundDimensions, RefundMetrics, RefundMetricsBucketIdentifier, RefundMetricsBucketResponse, + }, + AnalyticsMetadata, GetRefundFilterRequest, GetRefundMetricRequest, MetricsResponse, + RefundFilterValue, RefundFiltersResponse, +}; +use error_stack::{IntoReport, ResultExt}; +use router_env::{ + logger, + tracing::{self, Instrument}, +}; + +use super::{ + filters::{get_refund_filter_for_dimension, RefundFilterRow}, + RefundMetricsAccumulator, +}; +use crate::{ + errors::{AnalyticsError, AnalyticsResult}, + metrics, + refunds::RefundMetricAccumulator, + AnalyticsProvider, +}; + +pub async fn get_metrics( + pool: &AnalyticsProvider, + merchant_id: &String, + req: GetRefundMetricRequest, +) -> AnalyticsResult<MetricsResponse<RefundMetricsBucketResponse>> { + let mut metrics_accumulator: HashMap<RefundMetricsBucketIdentifier, RefundMetricsAccumulator> = + HashMap::new(); + let mut set = tokio::task::JoinSet::new(); + for metric_type in req.metrics.iter().cloned() { + let req = req.clone(); + let pool = pool.clone(); + let task_span = tracing::debug_span!( + "analytics_refund_query", + refund_metric = metric_type.as_ref() + ); + // Currently JoinSet works with only static lifetime references even if the task pool does not outlive the given reference + // We can optimize away this clone once that is fixed + let merchant_id_scoped = merchant_id.to_owned(); + set.spawn( + async move { + let data = pool + .get_refund_metrics( + &metric_type, + &req.group_by_names.clone(), + &merchant_id_scoped, + &req.filters, + &req.time_series.map(|t| t.granularity), + &req.time_range, + ) + .await + .change_context(AnalyticsError::UnknownError); + (metric_type, data) + } + .instrument(task_span), + ); + } + + while let Some((metric, data)) = set + .join_next() + .await + .transpose() + .into_report() + .change_context(AnalyticsError::UnknownError)? + { + let data = data?; + let attributes = &[ + metrics::request::add_attributes("metric_type", metric.to_string()), + metrics::request::add_attributes("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); + } + + 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 => metrics_builder + .refund_success_rate + .add_metrics_bucket(&value), + RefundMetrics::RefundCount => { + metrics_builder.refund_count.add_metrics_bucket(&value) + } + RefundMetrics::RefundSuccessCount => { + metrics_builder.refund_success.add_metrics_bucket(&value) + } + RefundMetrics::RefundProcessedAmount => { + metrics_builder.processed_amount.add_metrics_bucket(&value) + } + } + } + + logger::debug!( + "Analytics Accumulated Results: metric: {}, results: {:#?}", + metric, + metrics_accumulator + ); + } + let query_data: Vec<RefundMetricsBucketResponse> = metrics_accumulator + .into_iter() + .map(|(id, val)| RefundMetricsBucketResponse { + values: val.collect(), + dimensions: id, + }) + .collect(); + + Ok(MetricsResponse { + query_data, + meta_data: [AnalyticsMetadata { + current_time_range: req.time_range, + }], + }) +} + +pub async fn get_filters( + pool: &AnalyticsProvider, + req: GetRefundFilterRequest, + merchant_id: &String, +) -> AnalyticsResult<RefundFiltersResponse> { + let mut res = RefundFiltersResponse::default(); + for dim in req.group_by_names { + let values = match pool { + AnalyticsProvider::Sqlx(pool) => { + get_refund_filter_for_dimension(dim, merchant_id, &req.time_range, pool) + .await + } + AnalyticsProvider::Clickhouse(pool) => { + get_refund_filter_for_dimension(dim, merchant_id, &req.time_range, pool) + .await + } + AnalyticsProvider::CombinedCkh(sqlx_pool, ckh_pool) => { + let ckh_result = get_refund_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + ckh_pool, + ) + .await; + let sqlx_result = get_refund_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + sqlx_pool, + ) + .await; + 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 refunds analytics filters") + }, + _ => {} + }; + ckh_result + } + AnalyticsProvider::CombinedSqlx(sqlx_pool, ckh_pool) => { + let ckh_result = get_refund_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + ckh_pool, + ) + .await; + let sqlx_result = get_refund_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + sqlx_pool, + ) + .await; + 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 refunds analytics filters") + }, + _ => {} + }; + sqlx_result + } + } + .change_context(AnalyticsError::UnknownError)? + .into_iter() + .filter_map(|fil: RefundFilterRow| match dim { + RefundDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()), + RefundDimensions::RefundStatus => fil.refund_status.map(|i| i.as_ref().to_string()), + RefundDimensions::Connector => fil.connector, + RefundDimensions::RefundType => fil.refund_type.map(|i| i.as_ref().to_string()), + }) + .collect::<Vec<String>>(); + res.query_data.push(RefundFilterValue { + dimension: dim, + values, + }) + } + Ok(res) +} diff --git a/crates/router/src/analytics/refunds/filters.rs b/crates/analytics/src/refunds/filters.rs similarity index 90% rename from crates/router/src/analytics/refunds/filters.rs rename to crates/analytics/src/refunds/filters.rs index 6b45e9194fa..29375483eb9 100644 --- a/crates/router/src/analytics/refunds/filters.rs +++ b/crates/analytics/src/refunds/filters.rs @@ -2,13 +2,13 @@ use api_models::analytics::{ refunds::{RefundDimensions, RefundType}, Granularity, TimeRange, }; -use common_enums::enums::{Currency, RefundStatus}; use common_utils::errors::ReportSwitchExt; +use diesel_models::enums::{Currency, RefundStatus}; use error_stack::ResultExt; use time::PrimitiveDateTime; -use crate::analytics::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql}, +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{ AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, FiltersError, FiltersResult, LoadRow, @@ -28,6 +28,7 @@ where AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Refund); @@ -49,8 +50,7 @@ where .change_context(FiltersError::QueryBuildingError)? .change_context(FiltersError::QueryExecutionFailure) } - -#[derive(Debug, serde::Serialize, Eq, PartialEq)] +#[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] pub struct RefundFilterRow { pub currency: Option<DBEnumWrapper<Currency>>, pub refund_status: Option<DBEnumWrapper<RefundStatus>>, diff --git a/crates/router/src/analytics/refunds/metrics.rs b/crates/analytics/src/refunds/metrics.rs similarity index 91% rename from crates/router/src/analytics/refunds/metrics.rs rename to crates/analytics/src/refunds/metrics.rs index d4f509b4a1e..10cd0354677 100644 --- a/crates/router/src/analytics/refunds/metrics.rs +++ b/crates/analytics/src/refunds/metrics.rs @@ -4,7 +4,7 @@ use api_models::analytics::{ }, Granularity, TimeRange, }; -use common_enums::enums as storage_enums; +use diesel_models::enums as storage_enums; use time::PrimitiveDateTime; mod refund_count; mod refund_processed_amount; @@ -15,12 +15,11 @@ use refund_processed_amount::RefundProcessedAmount; use refund_success_count::RefundSuccessCount; use refund_success_rate::RefundSuccessRate; -use crate::analytics::{ - query::{Aggregate, GroupByClause, ToSql}, +use crate::{ + query::{Aggregate, GroupByClause, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, }; - -#[derive(Debug, Eq, PartialEq)] +#[derive(Debug, Eq, PartialEq, serde::Deserialize)] pub struct RefundMetricRow { pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, pub refund_status: Option<DBEnumWrapper<storage_enums::RefundStatus>>, @@ -28,7 +27,9 @@ pub struct RefundMetricRow { pub refund_type: Option<DBEnumWrapper<RefundType>>, pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, + #[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>, } @@ -42,6 +43,7 @@ where AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, @@ -62,6 +64,7 @@ where AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, diff --git a/crates/router/src/analytics/refunds/metrics/refund_count.rs b/crates/analytics/src/refunds/metrics/refund_count.rs similarity index 94% rename from crates/router/src/analytics/refunds/metrics/refund_count.rs rename to crates/analytics/src/refunds/metrics/refund_count.rs index 47132723507..cf3c7a50927 100644 --- a/crates/router/src/analytics/refunds/metrics/refund_count.rs +++ b/crates/analytics/src/refunds/metrics/refund_count.rs @@ -7,8 +7,8 @@ use error_stack::ResultExt; use time::PrimitiveDateTime; use super::RefundMetricRow; -use crate::analytics::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql}, +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -23,6 +23,7 @@ where AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, @@ -93,7 +94,7 @@ where Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), - i.refund_status.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()), TimeRange { @@ -110,7 +111,7 @@ where i, )) }) - .collect::<error_stack::Result<Vec<_>, crate::analytics::query::PostProcessingError>>() + .collect::<error_stack::Result<Vec<_>, crate::query::PostProcessingError>>() .change_context(MetricsError::PostProcessingFailure) } } diff --git a/crates/router/src/analytics/refunds/metrics/refund_processed_amount.rs b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs similarity index 95% rename from crates/router/src/analytics/refunds/metrics/refund_processed_amount.rs rename to crates/analytics/src/refunds/metrics/refund_processed_amount.rs index c5f3a706aae..661fca57b28 100644 --- a/crates/router/src/analytics/refunds/metrics/refund_processed_amount.rs +++ b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs @@ -2,14 +2,14 @@ use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, }; -use common_enums::enums as storage_enums; use common_utils::errors::ReportSwitchExt; +use diesel_models::enums as storage_enums; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::RefundMetricRow; -use crate::analytics::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql}, +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] @@ -23,6 +23,7 @@ where AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, @@ -116,7 +117,7 @@ where i, )) }) - .collect::<error_stack::Result<Vec<_>, crate::analytics::query::PostProcessingError>>() + .collect::<error_stack::Result<Vec<_>, crate::query::PostProcessingError>>() .change_context(MetricsError::PostProcessingFailure) } } diff --git a/crates/router/src/analytics/refunds/metrics/refund_success_count.rs b/crates/analytics/src/refunds/metrics/refund_success_count.rs similarity index 95% rename from crates/router/src/analytics/refunds/metrics/refund_success_count.rs rename to crates/analytics/src/refunds/metrics/refund_success_count.rs index 0c8032908fd..bc09d8b7ab6 100644 --- a/crates/router/src/analytics/refunds/metrics/refund_success_count.rs +++ b/crates/analytics/src/refunds/metrics/refund_success_count.rs @@ -2,14 +2,14 @@ use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, }; -use common_enums::enums as storage_enums; use common_utils::errors::ReportSwitchExt; +use diesel_models::enums as storage_enums; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::RefundMetricRow; -use crate::analytics::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql}, +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -24,6 +24,7 @@ where AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, @@ -115,7 +116,7 @@ where }) .collect::<error_stack::Result< Vec<(RefundMetricsBucketIdentifier, RefundMetricRow)>, - crate::analytics::query::PostProcessingError, + crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } diff --git a/crates/router/src/analytics/refunds/metrics/refund_success_rate.rs b/crates/analytics/src/refunds/metrics/refund_success_rate.rs similarity index 96% rename from crates/router/src/analytics/refunds/metrics/refund_success_rate.rs rename to crates/analytics/src/refunds/metrics/refund_success_rate.rs index 42f9ccf8d3c..29b73b885d8 100644 --- a/crates/router/src/analytics/refunds/metrics/refund_success_rate.rs +++ b/crates/analytics/src/refunds/metrics/refund_success_rate.rs @@ -7,8 +7,8 @@ use error_stack::ResultExt; use time::PrimitiveDateTime; use super::RefundMetricRow; -use crate::analytics::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql}, +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] @@ -22,6 +22,7 @@ where AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, @@ -110,7 +111,7 @@ where }) .collect::<error_stack::Result< Vec<(RefundMetricsBucketIdentifier, RefundMetricRow)>, - crate::analytics::query::PostProcessingError, + crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } diff --git a/crates/router/src/analytics/refunds/types.rs b/crates/analytics/src/refunds/types.rs similarity index 98% rename from crates/router/src/analytics/refunds/types.rs rename to crates/analytics/src/refunds/types.rs index fbfd6997267..d7d739e1aba 100644 --- a/crates/router/src/analytics/refunds/types.rs +++ b/crates/analytics/src/refunds/types.rs @@ -1,7 +1,7 @@ use api_models::analytics::refunds::{RefundDimensions, RefundFilters}; use error_stack::ResultExt; -use crate::analytics::{ +use crate::{ query::{QueryBuilder, QueryFilter, QueryResult, ToSql}, types::{AnalyticsCollection, AnalyticsDataSource}, }; diff --git a/crates/analytics/src/sdk_events.rs b/crates/analytics/src/sdk_events.rs new file mode 100644 index 00000000000..fe8af7cfe2d --- /dev/null +++ b/crates/analytics/src/sdk_events.rs @@ -0,0 +1,14 @@ +pub mod accumulator; +mod core; +pub mod events; +pub mod filters; +pub mod metrics; +pub mod types; +pub use accumulator::{SdkEventMetricAccumulator, SdkEventMetricsAccumulator}; +pub trait SDKEventAnalytics: events::SdkEventsFilterAnalytics {} +pub trait SdkEventAnalytics: + metrics::SdkEventMetricAnalytics + filters::SdkEventFilterAnalytics +{ +} + +pub use self::core::{get_filters, get_metrics, sdk_events_core}; diff --git a/crates/analytics/src/sdk_events/accumulator.rs b/crates/analytics/src/sdk_events/accumulator.rs new file mode 100644 index 00000000000..ab9e9309434 --- /dev/null +++ b/crates/analytics/src/sdk_events/accumulator.rs @@ -0,0 +1,98 @@ +use api_models::analytics::sdk_events::SdkEventMetricsBucketValue; +use router_env::logger; + +use super::metrics::SdkEventMetricRow; + +#[derive(Debug, Default)] +pub struct SdkEventMetricsAccumulator { + pub payment_attempts: CountAccumulator, + pub payment_success: CountAccumulator, + pub payment_methods_call_count: CountAccumulator, + pub average_payment_time: AverageAccumulator, + pub sdk_initiated_count: CountAccumulator, + pub sdk_rendered_count: CountAccumulator, + pub payment_method_selected_count: CountAccumulator, + pub payment_data_filled_count: CountAccumulator, +} + +#[derive(Debug, Default)] +#[repr(transparent)] +pub struct CountAccumulator { + pub count: Option<i64>, +} + +#[derive(Debug, Default)] +pub struct AverageAccumulator { + pub total: u32, + pub count: u32, +} + +pub trait SdkEventMetricAccumulator { + type MetricOutput; + + fn add_metrics_bucket(&mut self, metrics: &SdkEventMetricRow); + + fn collect(self) -> Self::MetricOutput; +} + +impl SdkEventMetricAccumulator for CountAccumulator { + type MetricOutput = Option<u64>; + #[inline] + fn add_metrics_bucket(&mut self, metrics: &SdkEventMetricRow) { + 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.count.and_then(|i| u64::try_from(i).ok()) + } +} + +impl SdkEventMetricAccumulator for AverageAccumulator { + type MetricOutput = Option<f64>; + + fn add_metrics_bucket(&mut self, metrics: &SdkEventMetricRow) { + let total = metrics + .total + .as_ref() + .and_then(bigdecimal::ToPrimitive::to_u32); + let count = metrics.count.and_then(|total| u32::try_from(total).ok()); + + match (total, count) { + (Some(total), Some(count)) => { + self.total += total; + self.count += count; + } + _ => { + logger::error!(message="Dropping metrics for average accumulator", metric=?metrics); + } + } + } + + fn collect(self) -> Self::MetricOutput { + if self.count == 0 { + None + } else { + Some(f64::from(self.total) / f64::from(self.count)) + } + } +} + +impl SdkEventMetricsAccumulator { + #[allow(dead_code)] + pub fn collect(self) -> SdkEventMetricsBucketValue { + SdkEventMetricsBucketValue { + payment_attempts: self.payment_attempts.collect(), + payment_success_count: self.payment_success.collect(), + payment_methods_call_count: self.payment_methods_call_count.collect(), + average_payment_time: self.average_payment_time.collect(), + sdk_initiated_count: self.sdk_initiated_count.collect(), + sdk_rendered_count: self.sdk_rendered_count.collect(), + payment_method_selected_count: self.payment_method_selected_count.collect(), + payment_data_filled_count: self.payment_data_filled_count.collect(), + } + } +} diff --git a/crates/analytics/src/sdk_events/core.rs b/crates/analytics/src/sdk_events/core.rs new file mode 100644 index 00000000000..34f23c745b0 --- /dev/null +++ b/crates/analytics/src/sdk_events/core.rs @@ -0,0 +1,201 @@ +use std::collections::HashMap; + +use api_models::analytics::{ + sdk_events::{ + MetricsBucketResponse, SdkEventMetrics, SdkEventMetricsBucketIdentifier, SdkEventsRequest, + }, + AnalyticsMetadata, GetSdkEventFiltersRequest, GetSdkEventMetricRequest, MetricsResponse, + SdkEventFiltersResponse, +}; +use error_stack::{IntoReport, ResultExt}; +use router_env::{instrument, logger, tracing}; + +use super::{ + events::{get_sdk_event, SdkEventsResult}, + SdkEventMetricsAccumulator, +}; +use crate::{ + errors::{AnalyticsError, AnalyticsResult}, + sdk_events::SdkEventMetricAccumulator, + types::FiltersError, + AnalyticsProvider, +}; + +#[instrument(skip_all)] +pub async fn sdk_events_core( + pool: &AnalyticsProvider, + req: SdkEventsRequest, + publishable_key: String, +) -> AnalyticsResult<Vec<SdkEventsResult>> { + match pool { + AnalyticsProvider::Sqlx(_) => Err(FiltersError::NotImplemented) + .into_report() + .attach_printable("SQL Analytics is not implemented for Sdk Events"), + AnalyticsProvider::Clickhouse(pool) => get_sdk_event(&publishable_key, req, pool).await, + AnalyticsProvider::CombinedSqlx(_sqlx_pool, ckh_pool) + | AnalyticsProvider::CombinedCkh(_sqlx_pool, ckh_pool) => { + get_sdk_event(&publishable_key, req, ckh_pool).await + } + } + .change_context(AnalyticsError::UnknownError) +} + +#[instrument(skip_all)] +pub async fn get_metrics( + pool: &AnalyticsProvider, + publishable_key: Option<&String>, + req: GetSdkEventMetricRequest, +) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> { + let mut metrics_accumulator: HashMap< + SdkEventMetricsBucketIdentifier, + SdkEventMetricsAccumulator, + > = HashMap::new(); + + if let Some(publishable_key) = publishable_key { + let mut set = tokio::task::JoinSet::new(); + for metric_type in req.metrics.iter().cloned() { + let req = req.clone(); + let publishable_key_scoped = publishable_key.to_owned(); + let pool = pool.clone(); + set.spawn(async move { + let data = pool + .get_sdk_event_metrics( + &metric_type, + &req.group_by_names.clone(), + &publishable_key_scoped, + &req.filters, + &req.time_series.map(|t| t.granularity), + &req.time_range, + ) + .await + .change_context(AnalyticsError::UnknownError); + (metric_type, data) + }); + } + + while let Some((metric, data)) = set + .join_next() + .await + .transpose() + .into_report() + .change_context(AnalyticsError::UnknownError)? + { + logger::info!("Logging Result {:?}", data); + for (id, value) in data? { + let metrics_builder = metrics_accumulator.entry(id).or_default(); + match metric { + SdkEventMetrics::PaymentAttempts => { + metrics_builder.payment_attempts.add_metrics_bucket(&value) + } + SdkEventMetrics::PaymentSuccessCount => { + metrics_builder.payment_success.add_metrics_bucket(&value) + } + SdkEventMetrics::PaymentMethodsCallCount => metrics_builder + .payment_methods_call_count + .add_metrics_bucket(&value), + SdkEventMetrics::SdkRenderedCount => metrics_builder + .sdk_rendered_count + .add_metrics_bucket(&value), + SdkEventMetrics::SdkInitiatedCount => metrics_builder + .sdk_initiated_count + .add_metrics_bucket(&value), + SdkEventMetrics::PaymentMethodSelectedCount => metrics_builder + .payment_method_selected_count + .add_metrics_bucket(&value), + SdkEventMetrics::PaymentDataFilledCount => metrics_builder + .payment_data_filled_count + .add_metrics_bucket(&value), + SdkEventMetrics::AveragePaymentTime => metrics_builder + .average_payment_time + .add_metrics_bucket(&value), + } + } + + logger::debug!( + "Analytics Accumulated Results: metric: {}, results: {:#?}", + metric, + metrics_accumulator + ); + } + + let query_data: Vec<MetricsBucketResponse> = metrics_accumulator + .into_iter() + .map(|(id, val)| MetricsBucketResponse { + values: val.collect(), + dimensions: id, + }) + .collect(); + + Ok(MetricsResponse { + query_data, + meta_data: [AnalyticsMetadata { + current_time_range: req.time_range, + }], + }) + } else { + logger::error!("Publishable key not present for merchant ID"); + Ok(MetricsResponse { + query_data: vec![], + meta_data: [AnalyticsMetadata { + current_time_range: req.time_range, + }], + }) + } +} + +#[allow(dead_code)] +pub async fn get_filters( + pool: &AnalyticsProvider, + req: GetSdkEventFiltersRequest, + publishable_key: Option<&String>, +) -> AnalyticsResult<SdkEventFiltersResponse> { + use api_models::analytics::{sdk_events::SdkEventDimensions, SdkEventFilterValue}; + + use super::filters::get_sdk_event_filter_for_dimension; + use crate::sdk_events::filters::SdkEventFilter; + + let mut res = SdkEventFiltersResponse::default(); + + if let Some(publishable_key) = publishable_key { + for dim in req.group_by_names { + let values = match pool { + AnalyticsProvider::Sqlx(_pool) => Err(FiltersError::NotImplemented) + .into_report() + .attach_printable("SQL Analytics is not implemented for SDK Events"), + AnalyticsProvider::Clickhouse(pool) => { + get_sdk_event_filter_for_dimension(dim, publishable_key, &req.time_range, pool) + .await + } + AnalyticsProvider::CombinedSqlx(_sqlx_pool, ckh_pool) + | AnalyticsProvider::CombinedCkh(_sqlx_pool, ckh_pool) => { + get_sdk_event_filter_for_dimension( + dim, + publishable_key, + &req.time_range, + ckh_pool, + ) + .await + } + } + .change_context(AnalyticsError::UnknownError)? + .into_iter() + .filter_map(|fil: SdkEventFilter| match dim { + SdkEventDimensions::PaymentMethod => fil.payment_method, + SdkEventDimensions::Platform => fil.platform, + SdkEventDimensions::BrowserName => fil.browser_name, + SdkEventDimensions::Source => fil.source, + SdkEventDimensions::Component => fil.component, + SdkEventDimensions::PaymentExperience => fil.payment_experience, + }) + .collect::<Vec<String>>(); + res.query_data.push(SdkEventFilterValue { + dimension: dim, + values, + }) + } + } else { + router_env::logger::error!("Publishable key not found for merchant"); + } + + Ok(res) +} diff --git a/crates/analytics/src/sdk_events/events.rs b/crates/analytics/src/sdk_events/events.rs new file mode 100644 index 00000000000..a4d044267e9 --- /dev/null +++ b/crates/analytics/src/sdk_events/events.rs @@ -0,0 +1,80 @@ +use api_models::analytics::{ + sdk_events::{SdkEventNames, SdkEventsRequest}, + Granularity, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use strum::IntoEnumIterator; +use time::PrimitiveDateTime; + +use crate::{ + query::{Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow}, +}; +pub trait SdkEventsFilterAnalytics: LoadRow<SdkEventsResult> {} + +pub async fn get_sdk_event<T>( + merchant_id: &str, + request: SdkEventsRequest, + pool: &T, +) -> FiltersResult<Vec<SdkEventsResult>> +where + T: AnalyticsDataSource + SdkEventsFilterAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + let static_event_list = SdkEventNames::iter() + .map(|i| format!("'{}'", i.as_ref())) + .collect::<Vec<String>>() + .join(","); + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents); + query_builder.add_select_column("*").switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + query_builder + .add_filter_clause("payment_id", request.payment_id) + .switch()?; + query_builder + .add_custom_filter_clause("event_name", static_event_list, FilterTypes::In) + .switch()?; + let _ = &request + .time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + //TODO!: update the execute_query function to return reports instead of plain errors... + query_builder + .execute_query::<SdkEventsResult, _>(pool) + .await + .change_context(FiltersError::QueryBuildingError)? + .change_context(FiltersError::QueryExecutionFailure) +} +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct SdkEventsResult { + pub merchant_id: String, + pub payment_id: String, + pub event_name: Option<String>, + pub log_type: Option<String>, + pub first_event: bool, + pub browser_name: Option<String>, + pub browser_version: Option<String>, + pub source: Option<String>, + pub category: Option<String>, + pub version: Option<String>, + pub value: Option<String>, + pub platform: Option<String>, + pub component: Option<String>, + pub payment_method: Option<String>, + pub payment_experience: Option<String>, + pub latency: Option<u64>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at_precise: PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, +} diff --git a/crates/analytics/src/sdk_events/filters.rs b/crates/analytics/src/sdk_events/filters.rs new file mode 100644 index 00000000000..9963f51ef94 --- /dev/null +++ b/crates/analytics/src/sdk_events/filters.rs @@ -0,0 +1,56 @@ +use api_models::analytics::{sdk_events::SdkEventDimensions, Granularity, TimeRange}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow}, +}; + +pub trait SdkEventFilterAnalytics: LoadRow<SdkEventFilter> {} + +pub async fn get_sdk_event_filter_for_dimension<T>( + dimension: SdkEventDimensions, + publishable_key: &String, + time_range: &TimeRange, + pool: &T, +) -> FiltersResult<Vec<SdkEventFilter>> +where + T: AnalyticsDataSource + SdkEventFilterAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents); + + query_builder.add_select_column(dimension).switch()?; + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + query_builder + .add_filter_clause("merchant_id", publishable_key) + .switch()?; + + query_builder.set_distinct(); + + query_builder + .execute_query::<SdkEventFilter, _>(pool) + .await + .change_context(FiltersError::QueryBuildingError)? + .change_context(FiltersError::QueryExecutionFailure) +} + +#[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] +pub struct SdkEventFilter { + pub payment_method: Option<String>, + pub platform: Option<String>, + pub browser_name: Option<String>, + pub source: Option<String>, + pub component: Option<String>, + pub payment_experience: Option<String>, +} diff --git a/crates/analytics/src/sdk_events/metrics.rs b/crates/analytics/src/sdk_events/metrics.rs new file mode 100644 index 00000000000..354d2270d18 --- /dev/null +++ b/crates/analytics/src/sdk_events/metrics.rs @@ -0,0 +1,181 @@ +use api_models::analytics::{ + sdk_events::{ + SdkEventDimensions, SdkEventFilters, SdkEventMetrics, SdkEventMetricsBucketIdentifier, + }, + Granularity, TimeRange, +}; +use time::PrimitiveDateTime; + +use crate::{ + query::{Aggregate, GroupByClause, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, MetricsResult}, +}; + +mod average_payment_time; +mod payment_attempts; +mod payment_data_filled_count; +mod payment_method_selected_count; +mod payment_methods_call_count; +mod payment_success_count; +mod sdk_initiated_count; +mod sdk_rendered_count; + +use average_payment_time::AveragePaymentTime; +use payment_attempts::PaymentAttempts; +use payment_data_filled_count::PaymentDataFilledCount; +use payment_method_selected_count::PaymentMethodSelectedCount; +use payment_methods_call_count::PaymentMethodsCallCount; +use payment_success_count::PaymentSuccessCount; +use sdk_initiated_count::SdkInitiatedCount; +use sdk_rendered_count::SdkRenderedCount; + +#[derive(Debug, PartialEq, Eq, serde::Deserialize)] +pub struct SdkEventMetricRow { + pub total: Option<bigdecimal::BigDecimal>, + pub count: Option<i64>, + pub time_bucket: Option<String>, + pub payment_method: Option<String>, + pub platform: Option<String>, + pub browser_name: Option<String>, + pub source: Option<String>, + pub component: Option<String>, + pub payment_experience: Option<String>, +} + +pub trait SdkEventMetricAnalytics: LoadRow<SdkEventMetricRow> {} + +#[async_trait::async_trait] +pub trait SdkEventMetric<T> +where + T: AnalyticsDataSource + SdkEventMetricAnalytics, +{ + async fn load_metrics( + &self, + dimensions: &[SdkEventDimensions], + publishable_key: &str, + filters: &SdkEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>>; +} + +#[async_trait::async_trait] +impl<T> SdkEventMetric<T> for SdkEventMetrics +where + T: AnalyticsDataSource + SdkEventMetricAnalytics, + 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: &[SdkEventDimensions], + publishable_key: &str, + filters: &SdkEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + match self { + Self::PaymentAttempts => { + PaymentAttempts + .load_metrics( + dimensions, + publishable_key, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::PaymentSuccessCount => { + PaymentSuccessCount + .load_metrics( + dimensions, + publishable_key, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::PaymentMethodsCallCount => { + PaymentMethodsCallCount + .load_metrics( + dimensions, + publishable_key, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::SdkRenderedCount => { + SdkRenderedCount + .load_metrics( + dimensions, + publishable_key, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::SdkInitiatedCount => { + SdkInitiatedCount + .load_metrics( + dimensions, + publishable_key, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::PaymentMethodSelectedCount => { + PaymentMethodSelectedCount + .load_metrics( + dimensions, + publishable_key, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::PaymentDataFilledCount => { + PaymentDataFilledCount + .load_metrics( + dimensions, + publishable_key, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::AveragePaymentTime => { + AveragePaymentTime + .load_metrics( + dimensions, + publishable_key, + filters, + granularity, + time_range, + pool, + ) + .await + } + } + } +} diff --git a/crates/analytics/src/sdk_events/metrics/average_payment_time.rs b/crates/analytics/src/sdk_events/metrics/average_payment_time.rs new file mode 100644 index 00000000000..db7171524ae --- /dev/null +++ b/crates/analytics/src/sdk_events/metrics/average_payment_time.rs @@ -0,0 +1,129 @@ +use api_models::analytics::{ + sdk_events::{ + SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::SdkEventMetricRow; +use crate::{ + query::{Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct AveragePaymentTime; + +#[async_trait::async_trait] +impl<T> super::SdkEventMetric<T> for AveragePaymentTime +where + T: AnalyticsDataSource + super::SdkEventMetricAnalytics, + 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: &[SdkEventDimensions], + publishable_key: &str, + filters: &SdkEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents); + let dimensions = dimensions.to_vec(); + + 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::Sum { + field: "latency", + alias: Some("total"), + }) + .switch()?; + + if let Some(granularity) = granularity.as_ref() { + query_builder + .add_granularity_in_mins(granularity) + .switch()?; + } + + filters.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_filter_clause("merchant_id", publishable_key) + .switch()?; + + query_builder + .add_bool_filter_clause("first_event", 1) + .switch()?; + + query_builder + .add_filter_clause("event_name", SdkEventNames::PaymentAttempt) + .switch()?; + + query_builder + .add_custom_filter_clause("latency", 0, FilterTypes::Gt) + .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() { + query_builder + .add_group_by_clause("time_bucket") + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<SdkEventMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + SdkEventMetricsBucketIdentifier::new( + i.payment_method.clone(), + i.platform.clone(), + i.browser_name.clone(), + i.source.clone(), + i.component.clone(), + i.payment_experience.clone(), + i.time_bucket.clone(), + ), + i, + )) + }) + .collect::<error_stack::Result< + Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/sdk_events/metrics/payment_attempts.rs b/crates/analytics/src/sdk_events/metrics/payment_attempts.rs new file mode 100644 index 00000000000..b2a78188c4f --- /dev/null +++ b/crates/analytics/src/sdk_events/metrics/payment_attempts.rs @@ -0,0 +1,118 @@ +use api_models::analytics::{ + sdk_events::{ + SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::SdkEventMetricRow; +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct PaymentAttempts; + +#[async_trait::async_trait] +impl<T> super::SdkEventMetric<T> for PaymentAttempts +where + T: AnalyticsDataSource + super::SdkEventMetricAnalytics, + 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: &[SdkEventDimensions], + publishable_key: &str, + filters: &SdkEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents); + let dimensions = dimensions.to_vec(); + + 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()?; + + if let Some(granularity) = granularity.as_ref() { + query_builder + .add_granularity_in_mins(granularity) + .switch()?; + } + + filters.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_filter_clause("merchant_id", publishable_key) + .switch()?; + + query_builder + .add_bool_filter_clause("first_event", 1) + .switch()?; + + query_builder + .add_filter_clause("event_name", SdkEventNames::PaymentAttempt) + .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() { + query_builder + .add_group_by_clause("time_bucket") + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<SdkEventMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + SdkEventMetricsBucketIdentifier::new( + i.payment_method.clone(), + i.platform.clone(), + i.browser_name.clone(), + i.source.clone(), + i.component.clone(), + i.payment_experience.clone(), + i.time_bucket.clone(), + ), + i, + )) + }) + .collect::<error_stack::Result< + Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/sdk_events/metrics/payment_data_filled_count.rs b/crates/analytics/src/sdk_events/metrics/payment_data_filled_count.rs new file mode 100644 index 00000000000..a3c94baeda2 --- /dev/null +++ b/crates/analytics/src/sdk_events/metrics/payment_data_filled_count.rs @@ -0,0 +1,118 @@ +use api_models::analytics::{ + sdk_events::{ + SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::SdkEventMetricRow; +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct PaymentDataFilledCount; + +#[async_trait::async_trait] +impl<T> super::SdkEventMetric<T> for PaymentDataFilledCount +where + T: AnalyticsDataSource + super::SdkEventMetricAnalytics, + 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: &[SdkEventDimensions], + publishable_key: &str, + filters: &SdkEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents); + let dimensions = dimensions.to_vec(); + + 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()?; + + if let Some(granularity) = granularity.as_ref() { + query_builder + .add_granularity_in_mins(granularity) + .switch()?; + } + + filters.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_filter_clause("merchant_id", publishable_key) + .switch()?; + + query_builder + .add_bool_filter_clause("first_event", 1) + .switch()?; + + query_builder + .add_filter_clause("event_name", SdkEventNames::PaymentDataFilled) + .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() { + query_builder + .add_group_by_clause("time_bucket") + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<SdkEventMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + SdkEventMetricsBucketIdentifier::new( + i.payment_method.clone(), + i.platform.clone(), + i.browser_name.clone(), + i.source.clone(), + i.component.clone(), + i.payment_experience.clone(), + i.time_bucket.clone(), + ), + i, + )) + }) + .collect::<error_stack::Result< + Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/sdk_events/metrics/payment_method_selected_count.rs b/crates/analytics/src/sdk_events/metrics/payment_method_selected_count.rs new file mode 100644 index 00000000000..11aeac5e6ff --- /dev/null +++ b/crates/analytics/src/sdk_events/metrics/payment_method_selected_count.rs @@ -0,0 +1,118 @@ +use api_models::analytics::{ + sdk_events::{ + SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::SdkEventMetricRow; +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct PaymentMethodSelectedCount; + +#[async_trait::async_trait] +impl<T> super::SdkEventMetric<T> for PaymentMethodSelectedCount +where + T: AnalyticsDataSource + super::SdkEventMetricAnalytics, + 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: &[SdkEventDimensions], + publishable_key: &str, + filters: &SdkEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents); + let dimensions = dimensions.to_vec(); + + 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()?; + + if let Some(granularity) = granularity.as_ref() { + query_builder + .add_granularity_in_mins(granularity) + .switch()?; + } + + filters.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_filter_clause("merchant_id", publishable_key) + .switch()?; + + query_builder + .add_bool_filter_clause("first_event", 1) + .switch()?; + + query_builder + .add_filter_clause("event_name", SdkEventNames::PaymentMethodChanged) + .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() { + query_builder + .add_group_by_clause("time_bucket") + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<SdkEventMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + SdkEventMetricsBucketIdentifier::new( + i.payment_method.clone(), + i.platform.clone(), + i.browser_name.clone(), + i.source.clone(), + i.component.clone(), + i.payment_experience.clone(), + i.time_bucket.clone(), + ), + i, + )) + }) + .collect::<error_stack::Result< + Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/sdk_events/metrics/payment_methods_call_count.rs b/crates/analytics/src/sdk_events/metrics/payment_methods_call_count.rs new file mode 100644 index 00000000000..7570f1292e5 --- /dev/null +++ b/crates/analytics/src/sdk_events/metrics/payment_methods_call_count.rs @@ -0,0 +1,126 @@ +use api_models::analytics::{ + sdk_events::{ + SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::SdkEventMetricRow; +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct PaymentMethodsCallCount; + +#[async_trait::async_trait] +impl<T> super::SdkEventMetric<T> for PaymentMethodsCallCount +where + T: AnalyticsDataSource + super::SdkEventMetricAnalytics, + 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: &[SdkEventDimensions], + publishable_key: &str, + filters: &SdkEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents); + let dimensions = dimensions.to_vec(); + + 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()?; + + if let Some(granularity) = granularity.as_ref() { + query_builder + .add_granularity_in_mins(granularity) + .switch()?; + } + + filters.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_filter_clause("merchant_id", publishable_key) + .switch()?; + + query_builder + .add_bool_filter_clause("first_event", 1) + .switch()?; + + query_builder + .add_filter_clause("event_name", SdkEventNames::PaymentMethodsCall) + .switch()?; + + query_builder + .add_filter_clause("log_type", "INFO") + .switch()?; + + query_builder + .add_filter_clause("category", "API") + .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() { + query_builder + .add_group_by_clause("time_bucket") + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<SdkEventMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + SdkEventMetricsBucketIdentifier::new( + i.payment_method.clone(), + i.platform.clone(), + i.browser_name.clone(), + i.source.clone(), + i.component.clone(), + i.payment_experience.clone(), + i.time_bucket.clone(), + ), + i, + )) + }) + .collect::<error_stack::Result< + Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/sdk_events/metrics/payment_success_count.rs b/crates/analytics/src/sdk_events/metrics/payment_success_count.rs new file mode 100644 index 00000000000..3faf8213632 --- /dev/null +++ b/crates/analytics/src/sdk_events/metrics/payment_success_count.rs @@ -0,0 +1,118 @@ +use api_models::analytics::{ + sdk_events::{ + SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::SdkEventMetricRow; +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct PaymentSuccessCount; + +#[async_trait::async_trait] +impl<T> super::SdkEventMetric<T> for PaymentSuccessCount +where + T: AnalyticsDataSource + super::SdkEventMetricAnalytics, + 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: &[SdkEventDimensions], + publishable_key: &str, + filters: &SdkEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents); + let dimensions = dimensions.to_vec(); + + 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()?; + + if let Some(granularity) = granularity.as_ref() { + query_builder + .add_granularity_in_mins(granularity) + .switch()?; + } + + filters.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_filter_clause("merchant_id", publishable_key) + .switch()?; + + query_builder + .add_bool_filter_clause("first_event", 1) + .switch()?; + + query_builder + .add_filter_clause("event_name", SdkEventNames::PaymentSuccess) + .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() { + query_builder + .add_group_by_clause("time_bucket") + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<SdkEventMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + SdkEventMetricsBucketIdentifier::new( + i.payment_method.clone(), + i.platform.clone(), + i.browser_name.clone(), + i.source.clone(), + i.component.clone(), + i.payment_experience.clone(), + i.time_bucket.clone(), + ), + i, + )) + }) + .collect::<error_stack::Result< + Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs b/crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs new file mode 100644 index 00000000000..a525e7890b7 --- /dev/null +++ b/crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs @@ -0,0 +1,118 @@ +use api_models::analytics::{ + sdk_events::{ + SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::SdkEventMetricRow; +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct SdkInitiatedCount; + +#[async_trait::async_trait] +impl<T> super::SdkEventMetric<T> for SdkInitiatedCount +where + T: AnalyticsDataSource + super::SdkEventMetricAnalytics, + 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: &[SdkEventDimensions], + publishable_key: &str, + filters: &SdkEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents); + let dimensions = dimensions.to_vec(); + + 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()?; + + if let Some(granularity) = granularity.as_ref() { + query_builder + .add_granularity_in_mins(granularity) + .switch()?; + } + + filters.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_filter_clause("merchant_id", publishable_key) + .switch()?; + + query_builder + .add_bool_filter_clause("first_event", 1) + .switch()?; + + query_builder + .add_filter_clause("event_name", SdkEventNames::StripeElementsCalled) + .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() { + query_builder + .add_group_by_clause("time_bucket") + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<SdkEventMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + SdkEventMetricsBucketIdentifier::new( + i.payment_method.clone(), + i.platform.clone(), + i.browser_name.clone(), + i.source.clone(), + i.component.clone(), + i.payment_experience.clone(), + i.time_bucket.clone(), + ), + i, + )) + }) + .collect::<error_stack::Result< + Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/sdk_events/metrics/sdk_rendered_count.rs b/crates/analytics/src/sdk_events/metrics/sdk_rendered_count.rs new file mode 100644 index 00000000000..ed9e776423a --- /dev/null +++ b/crates/analytics/src/sdk_events/metrics/sdk_rendered_count.rs @@ -0,0 +1,118 @@ +use api_models::analytics::{ + sdk_events::{ + SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::SdkEventMetricRow; +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct SdkRenderedCount; + +#[async_trait::async_trait] +impl<T> super::SdkEventMetric<T> for SdkRenderedCount +where + T: AnalyticsDataSource + super::SdkEventMetricAnalytics, + 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: &[SdkEventDimensions], + publishable_key: &str, + filters: &SdkEventFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents); + let dimensions = dimensions.to_vec(); + + 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()?; + + if let Some(granularity) = granularity.as_ref() { + query_builder + .add_granularity_in_mins(granularity) + .switch()?; + } + + filters.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_filter_clause("merchant_id", publishable_key) + .switch()?; + + query_builder + .add_bool_filter_clause("first_event", 1) + .switch()?; + + query_builder + .add_filter_clause("event_name", SdkEventNames::AppRendered) + .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() { + query_builder + .add_group_by_clause("time_bucket") + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<SdkEventMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + SdkEventMetricsBucketIdentifier::new( + i.payment_method.clone(), + i.platform.clone(), + i.browser_name.clone(), + i.source.clone(), + i.component.clone(), + i.payment_experience.clone(), + i.time_bucket.clone(), + ), + i, + )) + }) + .collect::<error_stack::Result< + Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/sdk_events/types.rs b/crates/analytics/src/sdk_events/types.rs new file mode 100644 index 00000000000..d631b3158ed --- /dev/null +++ b/crates/analytics/src/sdk_events/types.rs @@ -0,0 +1,50 @@ +use api_models::analytics::sdk_events::{SdkEventDimensions, SdkEventFilters}; +use error_stack::ResultExt; + +use crate::{ + query::{QueryBuilder, QueryFilter, QueryResult, ToSql}, + types::{AnalyticsCollection, AnalyticsDataSource}, +}; + +impl<T> QueryFilter<T> for SdkEventFilters +where + T: AnalyticsDataSource, + AnalyticsCollection: ToSql<T>, +{ + fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> { + if !self.payment_method.is_empty() { + builder + .add_filter_in_range_clause(SdkEventDimensions::PaymentMethod, &self.payment_method) + .attach_printable("Error adding payment method filter")?; + } + if !self.platform.is_empty() { + builder + .add_filter_in_range_clause(SdkEventDimensions::Platform, &self.platform) + .attach_printable("Error adding platform filter")?; + } + if !self.browser_name.is_empty() { + builder + .add_filter_in_range_clause(SdkEventDimensions::BrowserName, &self.browser_name) + .attach_printable("Error adding browser name filter")?; + } + if !self.source.is_empty() { + builder + .add_filter_in_range_clause(SdkEventDimensions::Source, &self.source) + .attach_printable("Error adding source filter")?; + } + if !self.component.is_empty() { + builder + .add_filter_in_range_clause(SdkEventDimensions::Component, &self.component) + .attach_printable("Error adding component filter")?; + } + if !self.payment_experience.is_empty() { + builder + .add_filter_in_range_clause( + SdkEventDimensions::PaymentExperience, + &self.payment_experience, + ) + .attach_printable("Error adding payment experience filter")?; + } + Ok(()) + } +} diff --git a/crates/router/src/analytics/sqlx.rs b/crates/analytics/src/sqlx.rs similarity index 64% rename from crates/router/src/analytics/sqlx.rs rename to crates/analytics/src/sqlx.rs index b88a2065f0b..cdd2647e4e7 100644 --- a/crates/router/src/analytics/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -1,14 +1,11 @@ use std::{fmt::Display, str::FromStr}; use api_models::analytics::refunds::RefundType; -use common_enums::enums::{ +use common_utils::errors::{CustomResult, ParsingError}; +use diesel_models::enums::{ AttemptStatus, AuthenticationType, Currency, PaymentMethod, RefundStatus, }; -use common_utils::errors::{CustomResult, ParsingError}; use error_stack::{IntoReport, ResultExt}; -#[cfg(feature = "kms")] -use external_services::{kms, kms::decrypt::KmsDecrypt}; -#[cfg(not(feature = "kms"))] use masking::PeekInterface; use sqlx::{ postgres::{PgArgumentBuffer, PgPoolOptions, PgRow, PgTypeInfo, PgValueRef}, @@ -16,15 +13,16 @@ use sqlx::{ Error::ColumnNotFound, FromRow, Pool, Postgres, Row, }; +use storage_impl::config::Database; use time::PrimitiveDateTime; use super::{ - query::{Aggregate, ToSql}, + query::{Aggregate, ToSql, Window}, types::{ AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, QueryExecutionError, + TableEngine, }, }; -use crate::configs::settings::Database; #[derive(Debug, Clone)] pub struct SqlxClient { @@ -47,19 +45,7 @@ impl Default for SqlxClient { } impl SqlxClient { - pub async fn from_conf( - conf: &Database, - #[cfg(feature = "kms")] kms_client: &kms::KmsClient, - ) -> Self { - #[cfg(feature = "kms")] - #[allow(clippy::expect_used)] - let password = conf - .password - .decrypt_inner(kms_client) - .await - .expect("Failed to KMS decrypt database password"); - - #[cfg(not(feature = "kms"))] + pub async fn from_conf(conf: &Database) -> Self { let password = &conf.password.peek(); let database_url = format!( "postgres://{}:{}@{}:{}/{}", @@ -154,6 +140,7 @@ where impl super::payments::filters::PaymentFilterAnalytics for SqlxClient {} impl super::payments::metrics::PaymentMetricAnalytics for SqlxClient {} +impl super::payments::distribution::PaymentDistributionAnalytics for SqlxClient {} impl super::refunds::metrics::RefundMetricAnalytics for SqlxClient {} impl super::refunds::filters::RefundFilterAnalytics for SqlxClient {} @@ -207,7 +194,7 @@ impl<'a> FromRow<'a, PgRow> for super::refunds::metrics::RefundMetricRow { 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()); @@ -253,6 +240,11 @@ impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow { 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 total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -261,7 +253,72 @@ impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow { 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, + status, + connector, + authentication_type, + payment_method, + payment_method_type, + total, + count, + start_bucket, + end_bucket, + }) + } +} +impl<'a> FromRow<'a, PgRow> for super::payments::distribution::PaymentDistributionRow { + 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 status: Option<DBEnumWrapper<AttemptStatus>> = + row.try_get("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 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 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 error_message: Option<String> = row.try_get("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()); @@ -274,8 +331,10 @@ impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow { connector, authentication_type, payment_method, + payment_method_type, total, count, + error_message, start_bucket, end_bucket, }) @@ -308,12 +367,18 @@ impl<'a> FromRow<'a, PgRow> for super::payments::filters::FilterRow { 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), + })?; Ok(Self { currency, status, connector, authentication_type, payment_method, + payment_method_type, }) } } @@ -349,16 +414,21 @@ impl<'a> FromRow<'a, PgRow> for super::refunds::filters::RefundFilterRow { } impl ToSql<SqlxClient> for PrimitiveDateTime { - fn to_sql(&self) -> error_stack::Result<String, ParsingError> { + fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.to_string()) } } impl ToSql<SqlxClient> for AnalyticsCollection { - fn to_sql(&self) -> error_stack::Result<String, ParsingError> { + fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { match self { Self::Payment => Ok("payment_attempt".to_string()), Self::Refund => Ok("refund".to_string()), + Self::SdkEvents => Err(error_stack::report!(ParsingError::UnknownError) + .attach_printable("SdkEvents table is not implemented for Sqlx"))?, + Self::ApiEvents => Err(error_stack::report!(ParsingError::UnknownError) + .attach_printable("ApiEvents table is not implemented for Sqlx"))?, + Self::PaymentIntent => Ok("payment_intent".to_string()), } } } @@ -367,7 +437,7 @@ impl<T> ToSql<SqlxClient> for Aggregate<T> where T: ToSql<SqlxClient>, { - fn to_sql(&self) -> error_stack::Result<String, ParsingError> { + fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(match self { Self::Count { field: _, alias } => { format!( @@ -378,21 +448,86 @@ where Self::Sum { field, alias } => { format!( "sum({}){}", - field.to_sql().attach_printable("Failed to sum aggregate")?, + field + .to_sql(table_engine) + .attach_printable("Failed to sum aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias)) ) } Self::Min { field, alias } => { format!( "min({}){}", - field.to_sql().attach_printable("Failed to min aggregate")?, + field + .to_sql(table_engine) + .attach_printable("Failed to min aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias)) ) } Self::Max { field, alias } => { format!( "max({}){}", - field.to_sql().attach_printable("Failed to max aggregate")?, + field + .to_sql(table_engine) + .attach_printable("Failed to max aggregate")?, + alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias)) + ) + } + }) + } +} + +impl<T> ToSql<SqlxClient> for Window<T> +where + T: ToSql<SqlxClient>, +{ + fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { + Ok(match self { + Self::Sum { + field, + partition_by, + order_by, + alias, + } => { + format!( + "sum({}) over ({}{}){}", + field + .to_sql(table_engine) + .attach_printable("Failed to sum window")?, + partition_by.as_ref().map_or_else( + || "".to_owned(), + |partition_by| format!("partition by {}", partition_by.to_owned()) + ), + order_by.as_ref().map_or_else( + || "".to_owned(), + |(order_column, order)| format!( + " order by {} {}", + order_column.to_owned(), + order.to_string() + ) + ), + alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias)) + ) + } + Self::RowNumber { + field: _, + partition_by, + order_by, + alias, + } => { + format!( + "row_number() over ({}{}){}", + partition_by.as_ref().map_or_else( + || "".to_owned(), + |partition_by| format!("partition by {}", partition_by.to_owned()) + ), + order_by.as_ref().map_or_else( + || "".to_owned(), + |(order_column, order)| format!( + " order by {} {}", + order_column.to_owned(), + order.to_string() + ) + ), alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias)) ) } diff --git a/crates/router/src/analytics/types.rs b/crates/analytics/src/types.rs similarity index 83% rename from crates/router/src/analytics/types.rs rename to crates/analytics/src/types.rs index fe20e812a9b..16d342d3d2e 100644 --- a/crates/router/src/analytics/types.rs +++ b/crates/analytics/src/types.rs @@ -2,25 +2,36 @@ use std::{fmt::Display, str::FromStr}; use common_utils::{ errors::{CustomResult, ErrorSwitch, ParsingError}, - events::ApiEventMetric, + events::{ApiEventMetric, ApiEventsType}, + impl_misc_api_event_type, }; use error_stack::{report, Report, ResultExt}; use super::query::QueryBuildingError; -#[derive(serde::Deserialize, Debug, masking::Serialize)] +#[derive(serde::Deserialize, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AnalyticsDomain { Payments, Refunds, + SdkEvents, + ApiEvents, } -impl ApiEventMetric for AnalyticsDomain {} - #[derive(Debug, strum::AsRefStr, strum::Display, Clone, Copy)] pub enum AnalyticsCollection { Payment, Refund, + SdkEvents, + ApiEvents, + PaymentIntent, +} + +#[allow(dead_code)] +#[derive(Debug)] +pub enum TableEngine { + CollapsingMergeTree { sign: &'static str }, + BasicTree, } #[derive(Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq)] @@ -50,6 +61,7 @@ where // Analytics Framework pub trait RefundAnalytics {} +pub trait SdkEventAnalytics {} #[async_trait::async_trait] pub trait AnalyticsDataSource @@ -60,6 +72,10 @@ where async fn load_results<T>(&self, query: &str) -> CustomResult<Vec<T>, QueryExecutionError> where Self: LoadRow<T>; + + fn get_table_engine(_table: AnalyticsCollection) -> TableEngine { + TableEngine::BasicTree + } } pub trait LoadRow<T> @@ -117,3 +133,5 @@ impl ErrorSwitch<FiltersError> for QueryBuildingError { FiltersError::QueryBuildingError } } + +impl_misc_api_event_type!(AnalyticsDomain); diff --git a/crates/router/src/analytics/utils.rs b/crates/analytics/src/utils.rs similarity index 52% rename from crates/router/src/analytics/utils.rs rename to crates/analytics/src/utils.rs index f7e6ea69dc3..6a0aa973a1e 100644 --- a/crates/router/src/analytics/utils.rs +++ b/crates/analytics/src/utils.rs @@ -1,6 +1,8 @@ use api_models::analytics::{ + api_event::{ApiEventDimensions, ApiEventMetrics}, payments::{PaymentDimensions, PaymentMetrics}, refunds::{RefundDimensions, RefundMetrics}, + sdk_events::{SdkEventDimensions, SdkEventMetrics}, NameDescription, }; use strum::IntoEnumIterator; @@ -13,6 +15,14 @@ pub fn get_refund_dimensions() -> Vec<NameDescription> { RefundDimensions::iter().map(Into::into).collect() } +pub fn get_sdk_event_dimensions() -> Vec<NameDescription> { + SdkEventDimensions::iter().map(Into::into).collect() +} + +pub fn get_api_event_dimensions() -> Vec<NameDescription> { + ApiEventDimensions::iter().map(Into::into).collect() +} + pub fn get_payment_metrics_info() -> Vec<NameDescription> { PaymentMetrics::iter().map(Into::into).collect() } @@ -20,3 +30,11 @@ pub fn get_payment_metrics_info() -> Vec<NameDescription> { pub fn get_refund_metrics_info() -> Vec<NameDescription> { RefundMetrics::iter().map(Into::into).collect() } + +pub fn get_sdk_event_metrics_info() -> Vec<NameDescription> { + SdkEventMetrics::iter().map(Into::into).collect() +} + +pub fn get_api_event_metrics_info() -> Vec<NameDescription> { + ApiEventMetrics::iter().map(Into::into).collect() +} diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 0358b6b313c..0263427b0fd 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -1,15 +1,20 @@ use std::collections::HashSet; -use common_utils::events::ApiEventMetric; -use time::PrimitiveDateTime; +use common_utils::pii::EmailStrategy; +use masking::Secret; use self::{ - payments::{PaymentDimensions, PaymentMetrics}, + api_event::{ApiEventDimensions, ApiEventMetrics}, + payments::{PaymentDimensions, PaymentDistributions, PaymentMetrics}, refunds::{RefundDimensions, RefundMetrics}, + sdk_events::{SdkEventDimensions, SdkEventMetrics}, }; +pub use crate::payments::TimeRange; +pub mod api_event; pub mod payments; pub mod refunds; +pub mod sdk_events; #[derive(Debug, serde::Serialize)] pub struct NameDescription { @@ -25,23 +30,12 @@ pub struct GetInfoResponse { pub dimensions: Vec<NameDescription>, } -impl ApiEventMetric for GetInfoResponse {} - -#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash)] -#[serde(rename_all = "camelCase")] -pub struct TimeRange { - #[serde(with = "common_utils::custom_serde::iso8601")] - pub start_time: PrimitiveDateTime, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub end_time: Option<PrimitiveDateTime>, -} - -#[derive(Clone, Copy, Debug, serde::Deserialize, masking::Serialize)] +#[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)] pub struct TimeSeries { pub granularity: Granularity, } -#[derive(Clone, Copy, Debug, serde::Deserialize, masking::Serialize)] +#[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)] pub enum Granularity { #[serde(rename = "G_ONEMIN")] OneMin, @@ -57,7 +51,7 @@ pub enum Granularity { OneDay, } -#[derive(Clone, Debug, serde::Deserialize, masking::Serialize)] +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentMetricRequest { pub time_series: Option<TimeSeries>, @@ -67,13 +61,51 @@ pub struct GetPaymentMetricRequest { #[serde(default)] pub filters: payments::PaymentFilters, pub metrics: HashSet<PaymentMetrics>, + pub distribution: Option<Distribution>, #[serde(default)] pub delta: bool, } -impl ApiEventMetric for GetPaymentMetricRequest {} +#[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)] +pub enum QueryLimit { + #[serde(rename = "TOP_5")] + Top5, + #[serde(rename = "TOP_10")] + Top10, +} + +#[allow(clippy::from_over_into)] +impl Into<u64> for QueryLimit { + fn into(self) -> u64 { + match self { + Self::Top5 => 5, + Self::Top10 => 10, + } + } +} + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Distribution { + pub distribution_for: PaymentDistributions, + pub distribution_cardinality: QueryLimit, +} + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ReportRequest { + pub time_range: TimeRange, +} + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GenerateReportRequest { + pub request: ReportRequest, + pub merchant_id: String, + pub email: Secret<String, EmailStrategy>, +} -#[derive(Clone, Debug, serde::Deserialize, masking::Serialize)] +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetRefundMetricRequest { pub time_series: Option<TimeSeries>, @@ -87,14 +119,26 @@ pub struct GetRefundMetricRequest { pub delta: bool, } -impl ApiEventMetric for GetRefundMetricRequest {} +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GetSdkEventMetricRequest { + pub time_series: Option<TimeSeries>, + pub time_range: TimeRange, + #[serde(default)] + pub group_by_names: Vec<SdkEventDimensions>, + #[serde(default)] + pub filters: sdk_events::SdkEventFilters, + pub metrics: HashSet<SdkEventMetrics>, + #[serde(default)] + pub delta: bool, +} #[derive(Debug, serde::Serialize)] pub struct AnalyticsMetadata { pub current_time_range: TimeRange, } -#[derive(Debug, serde::Deserialize, masking::Serialize)] +#[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentFiltersRequest { pub time_range: TimeRange, @@ -102,16 +146,12 @@ pub struct GetPaymentFiltersRequest { pub group_by_names: Vec<PaymentDimensions>, } -impl ApiEventMetric for GetPaymentFiltersRequest {} - #[derive(Debug, Default, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentFiltersResponse { pub query_data: Vec<FilterValue>, } -impl ApiEventMetric for PaymentFiltersResponse {} - #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct FilterValue { @@ -119,34 +159,88 @@ pub struct FilterValue { pub values: Vec<String>, } -#[derive(Debug, serde::Deserialize, masking::Serialize)] +#[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] + pub struct GetRefundFilterRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<RefundDimensions>, } -impl ApiEventMetric for GetRefundFilterRequest {} - #[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct RefundFiltersResponse { pub query_data: Vec<RefundFilterValue>, } -impl ApiEventMetric for RefundFiltersResponse {} - #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] + pub struct RefundFilterValue { pub dimension: RefundDimensions, pub values: Vec<String>, } +#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GetSdkEventFiltersRequest { + pub time_range: TimeRange, + #[serde(default)] + pub group_by_names: Vec<SdkEventDimensions>, +} + +#[derive(Debug, Default, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SdkEventFiltersResponse { + pub query_data: Vec<SdkEventFilterValue>, +} + +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SdkEventFilterValue { + pub dimension: SdkEventDimensions, + pub values: Vec<String>, +} + #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct MetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [AnalyticsMetadata; 1], } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GetApiEventFiltersRequest { + pub time_range: TimeRange, + #[serde(default)] + pub group_by_names: Vec<ApiEventDimensions>, +} + +#[derive(Debug, Default, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ApiEventFiltersResponse { + pub query_data: Vec<ApiEventFilterValue>, +} + +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ApiEventFilterValue { + pub dimension: ApiEventDimensions, + pub values: Vec<String>, +} + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GetApiEventMetricRequest { + pub time_series: Option<TimeSeries>, + pub time_range: TimeRange, + #[serde(default)] + pub group_by_names: Vec<ApiEventDimensions>, + #[serde(default)] + pub filters: api_event::ApiEventFilters, + pub metrics: HashSet<ApiEventMetrics>, + #[serde(default)] + pub delta: bool, +} diff --git a/crates/api_models/src/analytics/api_event.rs b/crates/api_models/src/analytics/api_event.rs new file mode 100644 index 00000000000..62fe829f01b --- /dev/null +++ b/crates/api_models/src/analytics/api_event.rs @@ -0,0 +1,148 @@ +use std::{ + collections::hash_map::DefaultHasher, + hash::{Hash, Hasher}, +}; + +use super::{NameDescription, TimeRange}; +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct ApiLogsRequest { + #[serde(flatten)] + pub query_param: QueryType, + pub api_name_filter: Option<Vec<String>>, +} + +pub enum FilterType { + ApiCountFilter, + LatencyFilter, + StatusCodeFilter, +} + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(tag = "type")] +pub enum QueryType { + Payment { + payment_id: String, + }, + Refund { + payment_id: String, + refund_id: String, + }, +} + +#[derive( + Debug, + serde::Serialize, + serde::Deserialize, + strum::AsRefStr, + PartialEq, + PartialOrd, + Eq, + Ord, + strum::Display, + strum::EnumIter, + Clone, + Copy, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum ApiEventDimensions { + // Do not change the order of these enums + // Consult the Dashboard FE folks since these also affects the order of metrics on FE + StatusCode, + FlowType, + ApiFlow, +} + +impl From<ApiEventDimensions> for NameDescription { + fn from(value: ApiEventDimensions) -> Self { + Self { + name: value.to_string(), + desc: String::new(), + } + } +} +#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] +pub struct ApiEventFilters { + pub status_code: Vec<u64>, + pub flow_type: Vec<String>, + pub api_flow: Vec<String>, +} + +#[derive( + Clone, + Debug, + Hash, + PartialEq, + Eq, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumIter, + strum::AsRefStr, +)] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum ApiEventMetrics { + Latency, + ApiCount, + StatusCodeCount, +} + +impl From<ApiEventMetrics> for NameDescription { + fn from(value: ApiEventMetrics) -> Self { + Self { + name: value.to_string(), + desc: String::new(), + } + } +} + +#[derive(Debug, serde::Serialize, Eq)] +pub struct ApiEventMetricsBucketIdentifier { + #[serde(rename = "time_range")] + pub time_bucket: TimeRange, + // Coz FE sucks + #[serde(rename = "time_bucket")] + #[serde(with = "common_utils::custom_serde::iso8601custom")] + pub start_time: time::PrimitiveDateTime, +} + +impl ApiEventMetricsBucketIdentifier { + pub fn new(normalized_time_range: TimeRange) -> Self { + Self { + time_bucket: normalized_time_range, + start_time: normalized_time_range.start_time, + } + } +} + +impl Hash for ApiEventMetricsBucketIdentifier { + fn hash<H: Hasher>(&self, state: &mut H) { + self.time_bucket.hash(state); + } +} + +impl PartialEq for ApiEventMetricsBucketIdentifier { + fn eq(&self, other: &Self) -> bool { + let mut left = DefaultHasher::new(); + self.hash(&mut left); + let mut right = DefaultHasher::new(); + other.hash(&mut right); + left.finish() == right.finish() + } +} + +#[derive(Debug, serde::Serialize)] +pub struct ApiEventMetricsBucketValue { + pub latency: Option<u64>, + pub api_count: Option<u64>, + pub status_code_count: Option<u64>, +} + +#[derive(Debug, serde::Serialize)] +pub struct ApiMetricsBucketResponse { + #[serde(flatten)] + pub values: ApiEventMetricsBucketValue, + #[serde(flatten)] + pub dimensions: ApiEventMetricsBucketIdentifier, +} diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs index b5e5852d628..2d7ae262f48 100644 --- a/crates/api_models/src/analytics/payments.rs +++ b/crates/api_models/src/analytics/payments.rs @@ -3,13 +3,12 @@ use std::{ hash::{Hash, Hasher}, }; -use common_enums::enums::{AttemptStatus, AuthenticationType, Currency, PaymentMethod}; -use common_utils::events::ApiEventMetric; - use super::{NameDescription, TimeRange}; -use crate::{analytics::MetricsResponse, enums::Connector}; +use crate::enums::{ + AttemptStatus, AuthenticationType, Connector, Currency, PaymentMethod, PaymentMethodType, +}; -#[derive(Clone, Debug, Default, serde::Deserialize, masking::Serialize)] +#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct PaymentFilters { #[serde(default)] pub currency: Vec<Currency>, @@ -21,6 +20,8 @@ pub struct PaymentFilters { pub auth_type: Vec<AuthenticationType>, #[serde(default)] pub payment_method: Vec<PaymentMethod>, + #[serde(default)] + pub payment_method_type: Vec<PaymentMethodType>, } #[derive( @@ -44,6 +45,7 @@ pub enum PaymentDimensions { // Consult the Dashboard FE folks since these also affects the order of metrics on FE Connector, PaymentMethod, + PaymentMethodType, Currency, #[strum(serialize = "authentication_type")] #[serde(rename = "authentication_type")] @@ -73,6 +75,35 @@ pub enum PaymentMetrics { PaymentSuccessCount, PaymentProcessedAmount, AvgTicketSize, + RetriesCount, + ConnectorSuccessRate, +} + +#[derive(Debug, Default, serde::Serialize)] +pub struct ErrorResult { + pub reason: String, + pub count: i64, + pub percentage: f64, +} + +#[derive( + Clone, + Copy, + Debug, + Hash, + PartialEq, + Eq, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumIter, + strum::AsRefStr, +)] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum PaymentDistributions { + #[strum(serialize = "error_message")] + PaymentErrorMessage, } pub mod metric_behaviour { @@ -109,6 +140,7 @@ pub struct PaymentMetricsBucketIdentifier { #[serde(rename = "authentication_type")] pub auth_type: Option<AuthenticationType>, pub payment_method: Option<String>, + pub payment_method_type: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, // Coz FE sucks @@ -124,6 +156,7 @@ impl PaymentMetricsBucketIdentifier { connector: Option<String>, auth_type: Option<AuthenticationType>, payment_method: Option<String>, + payment_method_type: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { @@ -132,6 +165,7 @@ impl PaymentMetricsBucketIdentifier { connector, auth_type, payment_method, + payment_method_type, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } @@ -145,6 +179,7 @@ impl Hash for PaymentMetricsBucketIdentifier { 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.time_bucket.hash(state); } } @@ -166,6 +201,10 @@ pub struct PaymentMetricsBucketValue { pub payment_success_count: Option<u64>, pub payment_processed_amount: Option<u64>, pub avg_ticket_size: Option<f64>, + pub payment_error_message: Option<Vec<ErrorResult>>, + pub retries_count: Option<u64>, + pub retries_amount_processed: Option<u64>, + pub connector_success_rate: Option<f64>, } #[derive(Debug, serde::Serialize)] @@ -175,6 +214,3 @@ pub struct MetricsBucketResponse { #[serde(flatten)] pub dimensions: PaymentMetricsBucketIdentifier, } - -impl ApiEventMetric for MetricsBucketResponse {} -impl ApiEventMetric for MetricsResponse<MetricsBucketResponse> {} diff --git a/crates/api_models/src/analytics/refunds.rs b/crates/api_models/src/analytics/refunds.rs index c5d444338d3..5ecdf1cecb3 100644 --- a/crates/api_models/src/analytics/refunds.rs +++ b/crates/api_models/src/analytics/refunds.rs @@ -3,10 +3,7 @@ use std::{ hash::{Hash, Hasher}, }; -use common_enums::enums::{Currency, RefundStatus}; -use common_utils::events::ApiEventMetric; - -use crate::analytics::MetricsResponse; +use crate::{enums::Currency, refunds::RefundStatus}; #[derive( Clone, @@ -20,7 +17,7 @@ use crate::analytics::MetricsResponse; strum::Display, strum::EnumString, )] -// TODO RefundType common_enums need to mapped to storage_model +// TODO RefundType api_models_oss need to mapped to storage_model #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RefundType { @@ -31,7 +28,7 @@ pub enum RefundType { } use super::{NameDescription, TimeRange}; -#[derive(Clone, Debug, Default, serde::Deserialize, masking::Serialize)] +#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct RefundFilters { #[serde(default)] pub currency: Vec<Currency>, @@ -115,8 +112,9 @@ impl From<RefundDimensions> for NameDescription { #[derive(Debug, serde::Serialize, Eq)] pub struct RefundMetricsBucketIdentifier { pub currency: Option<Currency>, - pub refund_status: Option<RefundStatus>, + pub refund_status: Option<String>, pub connector: Option<String>, + pub refund_type: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, @@ -128,7 +126,7 @@ pub struct RefundMetricsBucketIdentifier { impl Hash for RefundMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.currency.hash(state); - self.refund_status.map(|i| i.to_string()).hash(state); + self.refund_status.hash(state); self.connector.hash(state); self.refund_type.hash(state); self.time_bucket.hash(state); @@ -147,7 +145,7 @@ impl PartialEq for RefundMetricsBucketIdentifier { impl RefundMetricsBucketIdentifier { pub fn new( currency: Option<Currency>, - refund_status: Option<RefundStatus>, + refund_status: Option<String>, connector: Option<String>, refund_type: Option<String>, normalized_time_range: TimeRange, @@ -162,7 +160,6 @@ impl RefundMetricsBucketIdentifier { } } } - #[derive(Debug, serde::Serialize)] pub struct RefundMetricsBucketValue { pub refund_success_rate: Option<f64>, @@ -170,7 +167,6 @@ pub struct RefundMetricsBucketValue { pub refund_success_count: Option<u64>, pub refund_processed_amount: Option<u64>, } - #[derive(Debug, serde::Serialize)] pub struct RefundMetricsBucketResponse { #[serde(flatten)] @@ -178,6 +174,3 @@ pub struct RefundMetricsBucketResponse { #[serde(flatten)] pub dimensions: RefundMetricsBucketIdentifier, } - -impl ApiEventMetric for RefundMetricsBucketResponse {} -impl ApiEventMetric for MetricsResponse<RefundMetricsBucketResponse> {} diff --git a/crates/api_models/src/analytics/sdk_events.rs b/crates/api_models/src/analytics/sdk_events.rs new file mode 100644 index 00000000000..76ccb29867f --- /dev/null +++ b/crates/api_models/src/analytics/sdk_events.rs @@ -0,0 +1,215 @@ +use std::{ + collections::hash_map::DefaultHasher, + hash::{Hash, Hasher}, +}; + +use super::{NameDescription, TimeRange}; + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SdkEventsRequest { + pub payment_id: String, + pub time_range: TimeRange, +} + +#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] +pub struct SdkEventFilters { + #[serde(default)] + pub payment_method: Vec<String>, + #[serde(default)] + pub platform: Vec<String>, + #[serde(default)] + pub browser_name: Vec<String>, + #[serde(default)] + pub source: Vec<String>, + #[serde(default)] + pub component: Vec<String>, + #[serde(default)] + pub payment_experience: Vec<String>, +} + +#[derive( + Debug, + serde::Serialize, + serde::Deserialize, + strum::AsRefStr, + PartialEq, + PartialOrd, + Eq, + Ord, + strum::Display, + strum::EnumIter, + Clone, + Copy, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum SdkEventDimensions { + // Do not change the order of these enums + // Consult the Dashboard FE folks since these also affects the order of metrics on FE + PaymentMethod, + Platform, + BrowserName, + Source, + Component, + PaymentExperience, +} + +#[derive( + Clone, + Debug, + Hash, + PartialEq, + Eq, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumIter, + strum::AsRefStr, +)] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum SdkEventMetrics { + PaymentAttempts, + PaymentSuccessCount, + PaymentMethodsCallCount, + SdkRenderedCount, + SdkInitiatedCount, + PaymentMethodSelectedCount, + PaymentDataFilledCount, + AveragePaymentTime, +} + +#[derive( + Clone, + Debug, + Hash, + PartialEq, + Eq, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumIter, + strum::AsRefStr, +)] +#[strum(serialize_all = "SCREAMING_SNAKE_CASE")] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum SdkEventNames { + StripeElementsCalled, + AppRendered, + PaymentMethodChanged, + PaymentDataFilled, + PaymentAttempt, + PaymentSuccess, + PaymentMethodsCall, + ConfirmCall, + SessionsCall, + CustomerPaymentMethodsCall, + RedirectingUser, + DisplayBankTransferInfoPage, + DisplayQrCodeInfoPage, +} + +pub mod metric_behaviour { + pub struct PaymentAttempts; + pub struct PaymentSuccessCount; + pub struct PaymentMethodsCallCount; + pub struct SdkRenderedCount; + pub struct SdkInitiatedCount; + pub struct PaymentMethodSelectedCount; + pub struct PaymentDataFilledCount; + pub struct AveragePaymentTime; +} + +impl From<SdkEventMetrics> for NameDescription { + fn from(value: SdkEventMetrics) -> Self { + Self { + name: value.to_string(), + desc: String::new(), + } + } +} + +impl From<SdkEventDimensions> for NameDescription { + fn from(value: SdkEventDimensions) -> Self { + Self { + name: value.to_string(), + desc: String::new(), + } + } +} + +#[derive(Debug, serde::Serialize, Eq)] +pub struct SdkEventMetricsBucketIdentifier { + pub payment_method: Option<String>, + pub platform: Option<String>, + pub browser_name: Option<String>, + pub source: Option<String>, + pub component: Option<String>, + pub payment_experience: Option<String>, + pub time_bucket: Option<String>, +} + +impl SdkEventMetricsBucketIdentifier { + pub fn new( + payment_method: Option<String>, + platform: Option<String>, + browser_name: Option<String>, + source: Option<String>, + component: Option<String>, + payment_experience: Option<String>, + time_bucket: Option<String>, + ) -> Self { + Self { + payment_method, + platform, + browser_name, + source, + component, + payment_experience, + time_bucket, + } + } +} + +impl Hash for SdkEventMetricsBucketIdentifier { + fn hash<H: Hasher>(&self, state: &mut H) { + self.payment_method.hash(state); + self.platform.hash(state); + self.browser_name.hash(state); + self.source.hash(state); + self.component.hash(state); + self.payment_experience.hash(state); + self.time_bucket.hash(state); + } +} + +impl PartialEq for SdkEventMetricsBucketIdentifier { + fn eq(&self, other: &Self) -> bool { + let mut left = DefaultHasher::new(); + self.hash(&mut left); + let mut right = DefaultHasher::new(); + other.hash(&mut right); + left.finish() == right.finish() + } +} + +#[derive(Debug, serde::Serialize)] +pub struct SdkEventMetricsBucketValue { + pub payment_attempts: Option<u64>, + pub payment_success_count: Option<u64>, + pub payment_methods_call_count: Option<u64>, + pub average_payment_time: Option<f64>, + pub sdk_rendered_count: Option<u64>, + pub sdk_initiated_count: Option<u64>, + pub payment_method_selected_count: Option<u64>, + pub payment_data_filled_count: Option<u64>, +} + +#[derive(Debug, serde::Serialize)] +pub struct MetricsBucketResponse { + #[serde(flatten)] + pub values: SdkEventMetricsBucketValue, + #[serde(flatten)] + pub dimensions: SdkEventMetricsBucketIdentifier, +} diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 782c02be7a3..345f827daea 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -14,8 +14,16 @@ use common_utils::{ }; use crate::{ - admin::*, api_keys::*, cards_info::*, disputes::*, files::*, mandates::*, payment_methods::*, - payments::*, verifications::*, + admin::*, + analytics::{api_event::*, sdk_events::*, *}, + api_keys::*, + cards_info::*, + disputes::*, + files::*, + mandates::*, + payment_methods::*, + payments::*, + verifications::*, }; impl ApiEventMetric for TimeRange {} @@ -63,7 +71,23 @@ impl_misc_api_event_type!( ApplepayMerchantVerificationRequest, ApplepayMerchantResponse, ApplepayVerifiedDomainsResponse, - UpdateApiKeyRequest + UpdateApiKeyRequest, + GetApiEventFiltersRequest, + ApiEventFiltersResponse, + GetInfoResponse, + GetPaymentMetricRequest, + GetRefundMetricRequest, + GetSdkEventMetricRequest, + GetPaymentFiltersRequest, + PaymentFiltersResponse, + GetRefundFilterRequest, + RefundFiltersResponse, + GetSdkEventFiltersRequest, + SdkEventFiltersResponse, + ApiLogsRequest, + GetApiEventMetricRequest, + SdkEventsRequest, + ReportRequest ); #[cfg(feature = "stripe")] @@ -76,3 +100,9 @@ impl_misc_api_event_type!( CustomerPaymentMethodListResponse, CreateCustomerResponse ); + +impl<T> ApiEventMetric for MetricsResponse<T> { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Miscellaneous) + } +} diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index acb9bbdd6cd..bd4c59211e2 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -2339,9 +2339,11 @@ pub struct PaymentListFilters { pub struct TimeRange { /// The start time to filter payments list or to get list of filters. To get list of filters start time is needed to be passed #[serde(with = "common_utils::custom_serde::iso8601")] + #[serde(alias = "startTime")] pub start_time: PrimitiveDateTime, /// The end time to filter payments list or to get list of filters. If not passed the default time is now #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + #[serde(alias = "endTime")] pub end_time: Option<PrimitiveDateTime>, } diff --git a/crates/data_models/Cargo.toml b/crates/data_models/Cargo.toml index 57ae1ec1ec8..857d53b6999 100644 --- a/crates/data_models/Cargo.toml +++ b/crates/data_models/Cargo.toml @@ -18,7 +18,6 @@ common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils" } masking = { version = "0.1.0", path = "../masking" } - # Third party deps async-trait = "0.1.68" error-stack = "0.3.1" diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index b51dc045b20..f508460574d 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -16,7 +16,7 @@ email = ["external_services/email", "dep:aws-config", "olap"] basilisk = ["kms"] stripe = ["dep:serde_qs"] release = ["kms", "stripe", "basilisk", "s3", "email", "business_profile_routing", "accounts_cache", "kv_store", "profile_specific_fallback_routing"] -olap = ["data_models/olap", "storage_impl/olap", "scheduler/olap"] +olap = ["data_models/olap", "storage_impl/olap", "scheduler/olap", "dep:analytics"] oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"] accounts_cache = [] @@ -102,6 +102,7 @@ tracing-futures = { version = "0.2.5", features = ["tokio"] } # First party crates api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] } +analytics = { version = "0.1.0", path = "../analytics", optional = true } cards = { version = "0.1.0", path = "../cards" } common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs"] } @@ -118,6 +119,7 @@ router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra scheduler = { version = "0.1.0", path = "../scheduler", default-features = false } storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false } erased-serde = "0.3.31" +rdkafka = "0.36.0" [build-dependencies] router_env = { version = "0.1.0", path = "../router_env", default-features = false } diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index d57403d9298..f31e908e0dc 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -1,129 +1,560 @@ -mod core; -mod errors; -pub mod metrics; -mod payments; -mod query; -mod refunds; -pub mod routes; - -mod sqlx; -mod types; -mod utils; - -use api_models::analytics::{ - payments::{PaymentDimensions, PaymentFilters, PaymentMetrics, PaymentMetricsBucketIdentifier}, - refunds::{RefundDimensions, RefundFilters, RefundMetrics, RefundMetricsBucketIdentifier}, - Granularity, TimeRange, -}; -use router_env::{instrument, tracing}; - -use self::{ - payments::metrics::{PaymentMetric, PaymentMetricRow}, - refunds::metrics::{RefundMetric, RefundMetricRow}, - sqlx::SqlxClient, -}; -use crate::configs::settings::Database; - -#[derive(Clone, Debug)] -pub enum AnalyticsProvider { - Sqlx(SqlxClient), -} +pub use analytics::*; + +pub mod routes { + use actix_web::{web, Responder, Scope}; + use analytics::{ + api_event::api_events_core, errors::AnalyticsError, lambda_utils::invoke_lambda, + sdk_events::sdk_events_core, + }; + use api_models::analytics::{ + GenerateReportRequest, GetApiEventFiltersRequest, GetApiEventMetricRequest, + GetPaymentFiltersRequest, GetPaymentMetricRequest, GetRefundFilterRequest, + GetRefundMetricRequest, GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest, + }; + use error_stack::ResultExt; + use router_env::AnalyticsFlow; + + use crate::{ + core::api_locking, + db::user::UserInterface, + routes::AppState, + services::{ + api, + authentication::{self as auth, AuthToken, AuthenticationData}, + authorization::permissions::Permission, + ApplicationResponse, + }, + types::domain::UserEmail, + }; + + pub struct Analytics; + + impl Analytics { + pub fn server(state: AppState) -> Scope { + let mut route = web::scope("/analytics/v1").app_data(web::Data::new(state)); + { + route = route + .service( + web::resource("metrics/payments") + .route(web::post().to(get_payment_metrics)), + ) + .service( + web::resource("metrics/refunds").route(web::post().to(get_refunds_metrics)), + ) + .service( + web::resource("filters/payments") + .route(web::post().to(get_payment_filters)), + ) + .service( + web::resource("filters/refunds").route(web::post().to(get_refund_filters)), + ) + .service(web::resource("{domain}/info").route(web::get().to(get_info))) + .service( + web::resource("report/dispute") + .route(web::post().to(generate_dispute_report)), + ) + .service( + web::resource("report/refunds") + .route(web::post().to(generate_refund_report)), + ) + .service( + web::resource("report/payments") + .route(web::post().to(generate_payment_report)), + ) + .service( + web::resource("metrics/sdk_events") + .route(web::post().to(get_sdk_event_metrics)), + ) + .service( + web::resource("filters/sdk_events") + .route(web::post().to(get_sdk_event_filters)), + ) + .service(web::resource("api_event_logs").route(web::get().to(get_api_events))) + .service(web::resource("sdk_event_logs").route(web::post().to(get_sdk_events))) + .service( + web::resource("filters/api_events") + .route(web::post().to(get_api_event_filters)), + ) + .service( + web::resource("metrics/api_events") + .route(web::post().to(get_api_events_metrics)), + ) + } + route + } + } -impl Default for AnalyticsProvider { - fn default() -> Self { - Self::Sqlx(SqlxClient::default()) + pub async fn get_info( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + domain: actix_web::web::Path<analytics::AnalyticsDomain>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetInfo; + Box::pin(api::server_wrap( + flow, + state, + &req, + domain.into_inner(), + |_, _, domain| async { + analytics::core::get_domain_info(domain) + .await + .map(ApplicationResponse::Json) + }, + &auth::NoAuth, + api_locking::LockAction::NotApplicable, + )) + .await } -} -impl AnalyticsProvider { - #[instrument(skip_all)] + /// # Panics + /// + /// Panics if `json_payload` array does not contain one `GetPaymentMetricRequest` element. pub async fn get_payment_metrics( - &self, - metric: &PaymentMetrics, - dimensions: &[PaymentDimensions], - merchant_id: &str, - filters: &PaymentFilters, - granularity: &Option<Granularity>, - time_range: &TimeRange, - ) -> types::MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { - // Metrics to get the fetch time for each payment metric - metrics::request::record_operation_time( - async { - match self { - Self::Sqlx(pool) => { - metric - .load_metrics( - dimensions, - merchant_id, - filters, - granularity, - time_range, - pool, - ) - .await - } - } + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<[GetPaymentMetricRequest; 1]>, + ) -> impl Responder { + // safety: This shouldn't panic owing to the data type + #[allow(clippy::expect_used)] + let payload = json_payload + .into_inner() + .to_vec() + .pop() + .expect("Couldn't get GetPaymentMetricRequest"); + let flow = AnalyticsFlow::GetPaymentMetrics; + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: AuthenticationData, req| async move { + analytics::payments::get_metrics( + &state.pool, + &auth.merchant_account.merchant_id, + req, + ) + .await + .map(ApplicationResponse::Json) }, - &metrics::METRIC_FETCH_TIME, - metric, - self, - ) + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) .await } - pub async fn get_refund_metrics( - &self, - metric: &RefundMetrics, - dimensions: &[RefundDimensions], - merchant_id: &str, - filters: &RefundFilters, - granularity: &Option<Granularity>, - time_range: &TimeRange, - ) -> types::MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { - match self { - Self::Sqlx(pool) => { - metric - .load_metrics( - dimensions, - merchant_id, - filters, - granularity, - time_range, - pool, - ) + /// # Panics + /// + /// Panics if `json_payload` array does not contain one `GetRefundMetricRequest` element. + pub async fn get_refunds_metrics( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<[GetRefundMetricRequest; 1]>, + ) -> impl Responder { + #[allow(clippy::expect_used)] + // safety: This shouldn't panic owing to the data type + let payload = json_payload + .into_inner() + .to_vec() + .pop() + .expect("Couldn't get GetRefundMetricRequest"); + let flow = AnalyticsFlow::GetRefundsMetrics; + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: AuthenticationData, req| async move { + analytics::refunds::get_metrics( + &state.pool, + &auth.merchant_account.merchant_id, + req, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } + + /// # Panics + /// + /// Panics if `json_payload` array does not contain one `GetSdkEventMetricRequest` element. + pub async fn get_sdk_event_metrics( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<[GetSdkEventMetricRequest; 1]>, + ) -> impl Responder { + // safety: This shouldn't panic owing to the data type + #[allow(clippy::expect_used)] + let payload = json_payload + .into_inner() + .to_vec() + .pop() + .expect("Couldn't get GetSdkEventMetricRequest"); + let flow = AnalyticsFlow::GetSdkMetrics; + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: AuthenticationData, req| async move { + analytics::sdk_events::get_metrics( + &state.pool, + auth.merchant_account.publishable_key.as_ref(), + req, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } + + pub async fn get_payment_filters( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<GetPaymentFiltersRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetPaymentFilters; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req| async move { + analytics::payments::get_filters( + &state.pool, + req, + &auth.merchant_account.merchant_id, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } + + pub async fn get_refund_filters( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<GetRefundFilterRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetRefundFilters; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req: GetRefundFilterRequest| async move { + analytics::refunds::get_filters( + &state.pool, + req, + &auth.merchant_account.merchant_id, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } + + pub async fn get_sdk_event_filters( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<GetSdkEventFiltersRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetSdkEventFilters; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req| async move { + analytics::sdk_events::get_filters( + &state.pool, + req, + auth.merchant_account.publishable_key.as_ref(), + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } + + pub async fn get_api_events( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Query<api_models::analytics::api_event::ApiLogsRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetApiEvents; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req| async move { + api_events_core(&state.pool, req, auth.merchant_account.merchant_id) .await - } - } + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await } - pub async fn from_conf( - config: &AnalyticsConfig, - #[cfg(feature = "kms")] kms_client: &external_services::kms::KmsClient, - ) -> Self { - match config { - AnalyticsConfig::Sqlx { sqlx } => Self::Sqlx( - SqlxClient::from_conf( - sqlx, - #[cfg(feature = "kms")] - kms_client, + pub async fn get_sdk_events( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<api_models::analytics::sdk_events::SdkEventsRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetSdkEvents; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req| async move { + sdk_events_core( + &state.pool, + req, + auth.merchant_account.publishable_key.unwrap_or_default(), ) - .await, - ), - } + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await } -} -#[derive(Clone, Debug, serde::Deserialize)] -#[serde(tag = "source")] -#[serde(rename_all = "lowercase")] -pub enum AnalyticsConfig { - Sqlx { sqlx: Database }, -} + pub async fn generate_refund_report( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<ReportRequest>, + ) -> impl Responder { + let state_ref = &state; + let req_headers = &req.headers(); -impl Default for AnalyticsConfig { - fn default() -> Self { - Self::Sqlx { - sqlx: Database::default(), - } + let flow = AnalyticsFlow::GenerateRefundReport; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, payload| async move { + let jwt_payload = + auth::parse_jwt_payload::<AppState, AuthToken>(req_headers, state_ref).await; + + let user_id = jwt_payload + .change_context(AnalyticsError::UnknownError)? + .user_id; + + let user = UserInterface::find_user_by_id(&*state.store, &user_id) + .await + .change_context(AnalyticsError::UnknownError)?; + + let user_email = UserEmail::from_pii_email(user.email) + .change_context(AnalyticsError::UnknownError)? + .get_secret(); + + let lambda_req = GenerateReportRequest { + request: payload, + merchant_id: auth.merchant_account.merchant_id.to_string(), + email: user_email, + }; + + let json_bytes = + serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; + invoke_lambda( + &state.conf.report_download_config.refund_function, + &state.conf.report_download_config.region, + &json_bytes, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } + + pub async fn generate_dispute_report( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<ReportRequest>, + ) -> impl Responder { + let state_ref = &state; + let req_headers = &req.headers(); + + let flow = AnalyticsFlow::GenerateDisputeReport; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, payload| async move { + let jwt_payload = + auth::parse_jwt_payload::<AppState, AuthToken>(req_headers, state_ref).await; + + let user_id = jwt_payload + .change_context(AnalyticsError::UnknownError)? + .user_id; + + let user = UserInterface::find_user_by_id(&*state.store, &user_id) + .await + .change_context(AnalyticsError::UnknownError)?; + + let user_email = UserEmail::from_pii_email(user.email) + .change_context(AnalyticsError::UnknownError)? + .get_secret(); + + let lambda_req = GenerateReportRequest { + request: payload, + merchant_id: auth.merchant_account.merchant_id.to_string(), + email: user_email, + }; + + let json_bytes = + serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; + invoke_lambda( + &state.conf.report_download_config.dispute_function, + &state.conf.report_download_config.region, + &json_bytes, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } + + pub async fn generate_payment_report( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<ReportRequest>, + ) -> impl Responder { + let state_ref = &state; + let req_headers = &req.headers(); + + let flow = AnalyticsFlow::GeneratePaymentReport; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, payload| async move { + let jwt_payload = + auth::parse_jwt_payload::<AppState, AuthToken>(req_headers, state_ref).await; + + let user_id = jwt_payload + .change_context(AnalyticsError::UnknownError)? + .user_id; + + let user = UserInterface::find_user_by_id(&*state.store, &user_id) + .await + .change_context(AnalyticsError::UnknownError)?; + + let user_email = UserEmail::from_pii_email(user.email) + .change_context(AnalyticsError::UnknownError)? + .get_secret(); + + let lambda_req = GenerateReportRequest { + request: payload, + merchant_id: auth.merchant_account.merchant_id.to_string(), + email: user_email, + }; + + let json_bytes = + serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; + invoke_lambda( + &state.conf.report_download_config.payment_function, + &state.conf.report_download_config.region, + &json_bytes, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } + + /// # Panics + /// + /// Panics if `json_payload` array does not contain one `GetApiEventMetricRequest` element. + pub async fn get_api_events_metrics( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<[GetApiEventMetricRequest; 1]>, + ) -> impl Responder { + // safety: This shouldn't panic owing to the data type + #[allow(clippy::expect_used)] + let payload = json_payload + .into_inner() + .to_vec() + .pop() + .expect("Couldn't get GetApiEventMetricRequest"); + let flow = AnalyticsFlow::GetApiEventMetrics; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + payload, + |state, auth: AuthenticationData, req| async move { + analytics::api_event::get_api_event_metrics( + &state.pool, + &auth.merchant_account.merchant_id, + req, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } + + pub async fn get_api_event_filters( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<GetApiEventFiltersRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetApiEventFilters; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req| async move { + analytics::api_event::get_filters( + &state.pool, + req, + auth.merchant_account.merchant_id, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await } } diff --git a/crates/router/src/analytics/core.rs b/crates/router/src/analytics/core.rs deleted file mode 100644 index bf124a6c0e8..00000000000 --- a/crates/router/src/analytics/core.rs +++ /dev/null @@ -1,96 +0,0 @@ -use api_models::analytics::{ - payments::PaymentDimensions, refunds::RefundDimensions, FilterValue, GetInfoResponse, - GetPaymentFiltersRequest, GetRefundFilterRequest, PaymentFiltersResponse, RefundFilterValue, - RefundFiltersResponse, -}; -use error_stack::ResultExt; - -use super::{ - errors::{self, AnalyticsError}, - payments::filters::{get_payment_filter_for_dimension, FilterRow}, - refunds::filters::{get_refund_filter_for_dimension, RefundFilterRow}, - types::AnalyticsDomain, - utils, AnalyticsProvider, -}; -use crate::{services::ApplicationResponse, types::domain}; - -pub type AnalyticsApiResponse<T> = errors::AnalyticsResult<ApplicationResponse<T>>; - -pub async fn get_domain_info(domain: AnalyticsDomain) -> AnalyticsApiResponse<GetInfoResponse> { - let info = match domain { - AnalyticsDomain::Payments => GetInfoResponse { - metrics: utils::get_payment_metrics_info(), - download_dimensions: None, - dimensions: utils::get_payment_dimensions(), - }, - AnalyticsDomain::Refunds => GetInfoResponse { - metrics: utils::get_refund_metrics_info(), - download_dimensions: None, - dimensions: utils::get_refund_dimensions(), - }, - }; - Ok(ApplicationResponse::Json(info)) -} - -pub async fn payment_filters_core( - pool: AnalyticsProvider, - req: GetPaymentFiltersRequest, - merchant: domain::MerchantAccount, -) -> AnalyticsApiResponse<PaymentFiltersResponse> { - let mut res = PaymentFiltersResponse::default(); - - for dim in req.group_by_names { - let values = match pool.clone() { - AnalyticsProvider::Sqlx(pool) => { - get_payment_filter_for_dimension(dim, &merchant.merchant_id, &req.time_range, &pool) - .await - } - } - .change_context(AnalyticsError::UnknownError)? - .into_iter() - .filter_map(|fil: FilterRow| match dim { - PaymentDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()), - PaymentDimensions::PaymentStatus => fil.status.map(|i| i.as_ref().to_string()), - PaymentDimensions::Connector => fil.connector, - PaymentDimensions::AuthType => fil.authentication_type.map(|i| i.as_ref().to_string()), - PaymentDimensions::PaymentMethod => fil.payment_method, - }) - .collect::<Vec<String>>(); - res.query_data.push(FilterValue { - dimension: dim, - values, - }) - } - - Ok(ApplicationResponse::Json(res)) -} - -pub async fn refund_filter_core( - pool: AnalyticsProvider, - req: GetRefundFilterRequest, - merchant: domain::MerchantAccount, -) -> AnalyticsApiResponse<RefundFiltersResponse> { - let mut res = RefundFiltersResponse::default(); - for dim in req.group_by_names { - let values = match pool.clone() { - AnalyticsProvider::Sqlx(pool) => { - get_refund_filter_for_dimension(dim, &merchant.merchant_id, &req.time_range, &pool) - .await - } - } - .change_context(AnalyticsError::UnknownError)? - .into_iter() - .filter_map(|fil: RefundFilterRow| match dim { - RefundDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()), - RefundDimensions::RefundStatus => fil.refund_status.map(|i| i.as_ref().to_string()), - RefundDimensions::Connector => fil.connector, - RefundDimensions::RefundType => fil.refund_type.map(|i| i.as_ref().to_string()), - }) - .collect::<Vec<String>>(); - res.query_data.push(RefundFilterValue { - dimension: dim, - values, - }) - } - Ok(ApplicationResponse::Json(res)) -} diff --git a/crates/router/src/analytics/payments.rs b/crates/router/src/analytics/payments.rs deleted file mode 100644 index 527bf75a3c7..00000000000 --- a/crates/router/src/analytics/payments.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub mod accumulator; -mod core; -pub mod filters; -pub mod metrics; -pub mod types; -pub use accumulator::{PaymentMetricAccumulator, PaymentMetricsAccumulator}; - -pub trait PaymentAnalytics: - metrics::PaymentMetricAnalytics + filters::PaymentFilterAnalytics -{ -} - -pub use self::core::get_metrics; diff --git a/crates/router/src/analytics/payments/core.rs b/crates/router/src/analytics/payments/core.rs deleted file mode 100644 index 23eca8879a7..00000000000 --- a/crates/router/src/analytics/payments/core.rs +++ /dev/null @@ -1,129 +0,0 @@ -use std::collections::HashMap; - -use api_models::analytics::{ - payments::{MetricsBucketResponse, PaymentMetrics, PaymentMetricsBucketIdentifier}, - AnalyticsMetadata, GetPaymentMetricRequest, MetricsResponse, -}; -use error_stack::{IntoReport, ResultExt}; -use router_env::{ - instrument, logger, - tracing::{self, Instrument}, -}; - -use super::PaymentMetricsAccumulator; -use crate::{ - analytics::{ - core::AnalyticsApiResponse, errors::AnalyticsError, metrics, - payments::PaymentMetricAccumulator, AnalyticsProvider, - }, - services::ApplicationResponse, - types::domain, -}; - -#[instrument(skip_all)] -pub async fn get_metrics( - pool: AnalyticsProvider, - merchant_account: domain::MerchantAccount, - req: GetPaymentMetricRequest, -) -> AnalyticsApiResponse<MetricsResponse<MetricsBucketResponse>> { - let mut metrics_accumulator: HashMap< - PaymentMetricsBucketIdentifier, - PaymentMetricsAccumulator, - > = HashMap::new(); - - let mut set = tokio::task::JoinSet::new(); - for metric_type in req.metrics.iter().cloned() { - let req = req.clone(); - let merchant_id = merchant_account.merchant_id.clone(); - let pool = pool.clone(); - let task_span = tracing::debug_span!( - "analytics_payments_query", - payment_metric = metric_type.as_ref() - ); - set.spawn( - async move { - let data = pool - .get_payment_metrics( - &metric_type, - &req.group_by_names.clone(), - &merchant_id, - &req.filters, - &req.time_series.map(|t| t.granularity), - &req.time_range, - ) - .await - .change_context(AnalyticsError::UnknownError); - (metric_type, data) - } - .instrument(task_span), - ); - } - - while let Some((metric, data)) = set - .join_next() - .await - .transpose() - .into_report() - .change_context(AnalyticsError::UnknownError)? - { - let data = data?; - let attributes = &[ - metrics::request::add_attributes("metric_type", metric.to_string()), - metrics::request::add_attributes( - "source", - match pool { - crate::analytics::AnalyticsProvider::Sqlx(_) => "Sqlx", - }, - ), - ]; - - 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); - } - - 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 { - PaymentMetrics::PaymentSuccessRate => metrics_builder - .payment_success_rate - .add_metrics_bucket(&value), - PaymentMetrics::PaymentCount => { - metrics_builder.payment_count.add_metrics_bucket(&value) - } - PaymentMetrics::PaymentSuccessCount => { - metrics_builder.payment_success.add_metrics_bucket(&value) - } - PaymentMetrics::PaymentProcessedAmount => { - metrics_builder.processed_amount.add_metrics_bucket(&value) - } - PaymentMetrics::AvgTicketSize => { - metrics_builder.avg_ticket_size.add_metrics_bucket(&value) - } - } - } - - logger::debug!( - "Analytics Accumulated Results: metric: {}, results: {:#?}", - metric, - metrics_accumulator - ); - } - - let query_data: Vec<MetricsBucketResponse> = metrics_accumulator - .into_iter() - .map(|(id, val)| MetricsBucketResponse { - values: val.collect(), - dimensions: id, - }) - .collect(); - - Ok(ApplicationResponse::Json(MetricsResponse { - query_data, - meta_data: [AnalyticsMetadata { - current_time_range: req.time_range, - }], - })) -} diff --git a/crates/router/src/analytics/refunds/core.rs b/crates/router/src/analytics/refunds/core.rs deleted file mode 100644 index 4c2d2c39418..00000000000 --- a/crates/router/src/analytics/refunds/core.rs +++ /dev/null @@ -1,104 +0,0 @@ -use std::collections::HashMap; - -use api_models::analytics::{ - refunds::{RefundMetrics, RefundMetricsBucketIdentifier, RefundMetricsBucketResponse}, - AnalyticsMetadata, GetRefundMetricRequest, MetricsResponse, -}; -use error_stack::{IntoReport, ResultExt}; -use router_env::{ - logger, - tracing::{self, Instrument}, -}; - -use super::RefundMetricsAccumulator; -use crate::{ - analytics::{ - core::AnalyticsApiResponse, errors::AnalyticsError, refunds::RefundMetricAccumulator, - AnalyticsProvider, - }, - services::ApplicationResponse, - types::domain, -}; - -pub async fn get_metrics( - pool: AnalyticsProvider, - merchant_account: domain::MerchantAccount, - req: GetRefundMetricRequest, -) -> AnalyticsApiResponse<MetricsResponse<RefundMetricsBucketResponse>> { - let mut metrics_accumulator: HashMap<RefundMetricsBucketIdentifier, RefundMetricsAccumulator> = - HashMap::new(); - let mut set = tokio::task::JoinSet::new(); - for metric_type in req.metrics.iter().cloned() { - let req = req.clone(); - let merchant_id = merchant_account.merchant_id.clone(); - let pool = pool.clone(); - let task_span = tracing::debug_span!( - "analytics_refund_query", - refund_metric = metric_type.as_ref() - ); - set.spawn( - async move { - let data = pool - .get_refund_metrics( - &metric_type, - &req.group_by_names.clone(), - &merchant_id, - &req.filters, - &req.time_series.map(|t| t.granularity), - &req.time_range, - ) - .await - .change_context(AnalyticsError::UnknownError); - (metric_type, data) - } - .instrument(task_span), - ); - } - - while let Some((metric, data)) = set - .join_next() - .await - .transpose() - .into_report() - .change_context(AnalyticsError::UnknownError)? - { - 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 => metrics_builder - .refund_success_rate - .add_metrics_bucket(&value), - RefundMetrics::RefundCount => { - metrics_builder.refund_count.add_metrics_bucket(&value) - } - RefundMetrics::RefundSuccessCount => { - metrics_builder.refund_success.add_metrics_bucket(&value) - } - RefundMetrics::RefundProcessedAmount => { - metrics_builder.processed_amount.add_metrics_bucket(&value) - } - } - } - - logger::debug!( - "Analytics Accumulated Results: metric: {}, results: {:#?}", - metric, - metrics_accumulator - ); - } - let query_data: Vec<RefundMetricsBucketResponse> = metrics_accumulator - .into_iter() - .map(|(id, val)| RefundMetricsBucketResponse { - values: val.collect(), - dimensions: id, - }) - .collect(); - - Ok(ApplicationResponse::Json(MetricsResponse { - query_data, - meta_data: [AnalyticsMetadata { - current_time_range: req.time_range, - }], - })) -} diff --git a/crates/router/src/analytics/routes.rs b/crates/router/src/analytics/routes.rs deleted file mode 100644 index 113312cdf10..00000000000 --- a/crates/router/src/analytics/routes.rs +++ /dev/null @@ -1,164 +0,0 @@ -use actix_web::{web, Responder, Scope}; -use api_models::analytics::{ - GetPaymentFiltersRequest, GetPaymentMetricRequest, GetRefundFilterRequest, - GetRefundMetricRequest, -}; -use router_env::AnalyticsFlow; - -use super::{core::*, payments, refunds, types::AnalyticsDomain}; -use crate::{ - core::api_locking, - services::{ - api, authentication as auth, authentication::AuthenticationData, - authorization::permissions::Permission, - }, - AppState, -}; - -pub struct Analytics; - -impl Analytics { - pub fn server(state: AppState) -> Scope { - let route = web::scope("/analytics/v1").app_data(web::Data::new(state)); - route - .service(web::resource("metrics/payments").route(web::post().to(get_payment_metrics))) - .service(web::resource("metrics/refunds").route(web::post().to(get_refunds_metrics))) - .service(web::resource("filters/payments").route(web::post().to(get_payment_filters))) - .service(web::resource("filters/refunds").route(web::post().to(get_refund_filters))) - .service(web::resource("{domain}/info").route(web::get().to(get_info))) - } -} - -pub async fn get_info( - state: web::Data<AppState>, - req: actix_web::HttpRequest, - domain: actix_web::web::Path<AnalyticsDomain>, -) -> impl Responder { - let flow = AnalyticsFlow::GetInfo; - api::server_wrap( - flow, - state, - &req, - domain.into_inner(), - |_, _, domain| get_domain_info(domain), - &auth::NoAuth, - api_locking::LockAction::NotApplicable, - ) - .await -} - -/// # Panics -/// -/// Panics if `json_payload` array does not contain one `GetPaymentMetricRequest` element. -pub async fn get_payment_metrics( - state: web::Data<AppState>, - req: actix_web::HttpRequest, - json_payload: web::Json<[GetPaymentMetricRequest; 1]>, -) -> impl Responder { - // safety: This shouldn't panic owing to the data type - #[allow(clippy::expect_used)] - let payload = json_payload - .into_inner() - .to_vec() - .pop() - .expect("Couldn't get GetPaymentMetricRequest"); - let flow = AnalyticsFlow::GetPaymentMetrics; - api::server_wrap( - flow, - state, - &req, - payload, - |state, auth: AuthenticationData, req| { - payments::get_metrics(state.pool.clone(), auth.merchant_account, req) - }, - auth::auth_type( - &auth::ApiKeyAuth, - &auth::JWTAuth(Permission::Analytics), - req.headers(), - ), - api_locking::LockAction::NotApplicable, - ) - .await -} - -/// # Panics -/// -/// Panics if `json_payload` array does not contain one `GetRefundMetricRequest` element. -pub async fn get_refunds_metrics( - state: web::Data<AppState>, - req: actix_web::HttpRequest, - json_payload: web::Json<[GetRefundMetricRequest; 1]>, -) -> impl Responder { - #[allow(clippy::expect_used)] - // safety: This shouldn't panic owing to the data type - let payload = json_payload - .into_inner() - .to_vec() - .pop() - .expect("Couldn't get GetRefundMetricRequest"); - let flow = AnalyticsFlow::GetRefundsMetrics; - api::server_wrap( - flow, - state, - &req, - payload, - |state, auth: AuthenticationData, req| { - refunds::get_metrics(state.pool.clone(), auth.merchant_account, req) - }, - auth::auth_type( - &auth::ApiKeyAuth, - &auth::JWTAuth(Permission::Analytics), - req.headers(), - ), - api_locking::LockAction::NotApplicable, - ) - .await -} - -pub async fn get_payment_filters( - state: web::Data<AppState>, - req: actix_web::HttpRequest, - json_payload: web::Json<GetPaymentFiltersRequest>, -) -> impl Responder { - let flow = AnalyticsFlow::GetPaymentFilters; - api::server_wrap( - flow, - state, - &req, - json_payload.into_inner(), - |state, auth: AuthenticationData, req| { - payment_filters_core(state.pool.clone(), req, auth.merchant_account) - }, - auth::auth_type( - &auth::ApiKeyAuth, - &auth::JWTAuth(Permission::Analytics), - req.headers(), - ), - api_locking::LockAction::NotApplicable, - ) - .await -} - -pub async fn get_refund_filters( - state: web::Data<AppState>, - req: actix_web::HttpRequest, - json_payload: web::Json<GetRefundFilterRequest>, -) -> impl Responder { - let flow = AnalyticsFlow::GetRefundFilters; - api::server_wrap( - flow, - state, - &req, - json_payload.into_inner(), - |state, auth: AuthenticationData, req: GetRefundFilterRequest| { - refund_filter_core(state.pool.clone(), req, auth.merchant_account) - }, - auth::auth_type( - &auth::ApiKeyAuth, - &auth::JWTAuth(Permission::Analytics), - req.headers(), - ), - api_locking::LockAction::NotApplicable, - ) - .await -} diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index 4c19408582b..32e9cfc6ca2 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -20,7 +20,6 @@ use strum::EnumString; use tokio::sync::{mpsc, oneshot}; const SCHEDULER_FLOW: &str = "SCHEDULER_FLOW"; - #[tokio::main] async fn main() -> CustomResult<(), ProcessTrackerError> { // console_subscriber::init(); @@ -30,7 +29,6 @@ async fn main() -> CustomResult<(), ProcessTrackerError> { #[allow(clippy::expect_used)] let conf = Settings::with_config_path(cmd_line.config_path) .expect("Unable to construct application configuration"); - let api_client = Box::new( services::ProxyClient::new( conf.proxy.clone(), diff --git a/crates/router/src/configs/kms.rs b/crates/router/src/configs/kms.rs index c2f159d16cf..37f2d15774a 100644 --- a/crates/router/src/configs/kms.rs +++ b/crates/router/src/configs/kms.rs @@ -63,7 +63,7 @@ impl KmsDecrypt for settings::Database { password: self.password.decrypt_inner(kms_client).await?.into(), pool_size: self.pool_size, connection_timeout: self.connection_timeout, - queue_strategy: self.queue_strategy.into(), + queue_strategy: self.queue_strategy, min_idle: self.min_idle, max_lifetime: self.max_lifetime, }) diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 918ae6647ee..f2d962b0abe 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -4,6 +4,8 @@ use std::{ str::FromStr, }; +#[cfg(feature = "olap")] +use analytics::ReportConfig; use api_models::{enums, payment_methods::RequiredFieldInfo}; use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; @@ -16,12 +18,14 @@ pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use rust_decimal::Decimal; use scheduler::SchedulerSettings; use serde::{de::Error, Deserialize, Deserializer}; +use storage_impl::config::QueueStrategy; #[cfg(feature = "olap")] use crate::analytics::AnalyticsConfig; use crate::{ core::errors::{ApplicationError, ApplicationResult}, env::{self, logger, Env}, + events::EventsConfig, }; #[cfg(feature = "kms")] pub type Password = kms::KmsValue; @@ -109,6 +113,9 @@ pub struct Settings { pub analytics: AnalyticsConfig, #[cfg(feature = "kv_store")] pub kv_config: KvConfig, + #[cfg(feature = "olap")] + pub report_download_config: ReportConfig, + pub events: EventsConfig, } #[derive(Debug, Deserialize, Clone)] @@ -521,23 +528,6 @@ pub struct Database { pub max_lifetime: Option<u64>, } -#[derive(Debug, Deserialize, Clone, Default)] -#[serde(rename_all = "PascalCase")] -pub enum QueueStrategy { - #[default] - Fifo, - Lifo, -} - -impl From<QueueStrategy> for bb8::QueueStrategy { - fn from(value: QueueStrategy) -> Self { - match value { - QueueStrategy::Fifo => Self::Fifo, - QueueStrategy::Lifo => Self::Lifo, - } - } -} - #[cfg(not(feature = "kms"))] impl From<Database> for storage_impl::config::Database { fn from(val: Database) -> Self { @@ -837,6 +827,7 @@ impl Settings { #[cfg(feature = "s3")] self.file_upload_config.validate()?; self.lock_settings.validate()?; + self.events.validate()?; Ok(()) } } diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 2d572cee951..33435bb0ad9 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -927,7 +927,9 @@ pub async fn start_refund_workflow( ) -> Result<(), errors::ProcessTrackerError> { match refund_tracker.name.as_deref() { Some("EXECUTE_REFUND") => trigger_refund_execute_workflow(state, refund_tracker).await, - Some("SYNC_REFUND") => sync_refund_with_gateway_workflow(state, refund_tracker).await, + Some("SYNC_REFUND") => { + Box::pin(sync_refund_with_gateway_workflow(state, refund_tracker)).await + } _ => Err(errors::ProcessTrackerError::JobNotFound), } } diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 67154ae33ae..be8d118a47c 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -905,6 +905,7 @@ pub async fn webhooks_wrapper<W: types::OutgoingWebhookType, Ctx: PaymentMethodR .attach_printable("Could not convert webhook effect to string")?; let api_event = ApiEvent::new( + Some(merchant_account.merchant_id.clone()), flow, &request_id, request_duration, @@ -916,6 +917,7 @@ pub async fn webhooks_wrapper<W: types::OutgoingWebhookType, Ctx: PaymentMethodR None, api_event, req, + Some(req.method().to_string()), ); match api_event.clone().try_into() { Ok(event) => { diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 9687f7f97c9..549bda78eda 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -12,6 +12,7 @@ pub mod events; pub mod file; pub mod fraud_check; pub mod gsm; +mod kafka_store; pub mod locker_mock_up; pub mod mandate; pub mod merchant_account; @@ -31,11 +32,24 @@ pub mod user_role; use data_models::payments::{ payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface, }; +use diesel_models::{ + fraud_check::{FraudCheck, FraudCheckNew, FraudCheckUpdate}, + organization::{Organization, OrganizationNew, OrganizationUpdate}, +}; +use error_stack::ResultExt; use masking::PeekInterface; use redis_interface::errors::RedisError; -use storage_impl::{redis::kv_store::RedisConnInterface, MockDb}; - -use crate::{errors::CustomResult, services::Store}; +use storage_impl::{errors::StorageError, redis::kv_store::RedisConnInterface, MockDb}; + +pub use self::kafka_store::KafkaStore; +use self::{fraud_check::FraudCheckInterface, organization::OrganizationInterface}; +pub use crate::{ + errors::CustomResult, + services::{ + kafka::{KafkaError, KafkaProducer, MQResult}, + Store, + }, +}; #[derive(PartialEq, Eq)] pub enum StorageImpl { @@ -58,7 +72,7 @@ pub trait StorageInterface: + ephemeral_key::EphemeralKeyInterface + events::EventInterface + file::FileMetadataInterface - + fraud_check::FraudCheckInterface + + FraudCheckInterface + locker_mock_up::LockerMockUpInterface + mandate::MandateInterface + merchant_account::MerchantAccountInterface @@ -79,7 +93,7 @@ pub trait StorageInterface: + RedisConnInterface + RequestIdStore + business_profile::BusinessProfileInterface - + organization::OrganizationInterface + + OrganizationInterface + routing_algorithm::RoutingAlgorithmInterface + gsm::GsmInterface + user::UserInterface @@ -151,7 +165,6 @@ where T: serde::de::DeserializeOwned, { use common_utils::ext_traits::ByteSliceExt; - use error_stack::ResultExt; let bytes = db.get_key(key).await?; bytes @@ -160,3 +173,72 @@ where } dyn_clone::clone_trait_object!(StorageInterface); + +impl RequestIdStore for KafkaStore { + fn add_request_id(&mut self, request_id: String) { + self.diesel_store.add_request_id(request_id) + } +} + +#[async_trait::async_trait] +impl FraudCheckInterface for KafkaStore { + async fn insert_fraud_check_response( + &self, + new: FraudCheckNew, + ) -> CustomResult<FraudCheck, StorageError> { + self.diesel_store.insert_fraud_check_response(new).await + } + async fn update_fraud_check_response_with_attempt_id( + &self, + fraud_check: FraudCheck, + fraud_check_update: FraudCheckUpdate, + ) -> CustomResult<FraudCheck, StorageError> { + self.diesel_store + .update_fraud_check_response_with_attempt_id(fraud_check, fraud_check_update) + .await + } + async fn find_fraud_check_by_payment_id( + &self, + payment_id: String, + merchant_id: String, + ) -> CustomResult<FraudCheck, StorageError> { + self.diesel_store + .find_fraud_check_by_payment_id(payment_id, merchant_id) + .await + } + async fn find_fraud_check_by_payment_id_if_present( + &self, + payment_id: String, + merchant_id: String, + ) -> CustomResult<Option<FraudCheck>, StorageError> { + self.diesel_store + .find_fraud_check_by_payment_id_if_present(payment_id, merchant_id) + .await + } +} + +#[async_trait::async_trait] +impl OrganizationInterface for KafkaStore { + async fn insert_organization( + &self, + organization: OrganizationNew, + ) -> CustomResult<Organization, StorageError> { + self.diesel_store.insert_organization(organization).await + } + async fn find_organization_by_org_id( + &self, + org_id: &str, + ) -> CustomResult<Organization, StorageError> { + self.diesel_store.find_organization_by_org_id(org_id).await + } + + async fn update_organization_by_org_id( + &self, + org_id: &str, + update: OrganizationUpdate, + ) -> CustomResult<Organization, StorageError> { + self.diesel_store + .update_organization_by_org_id(org_id, update) + .await + } +} diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs new file mode 100644 index 00000000000..9cf1a7b80b8 --- /dev/null +++ b/crates/router/src/db/kafka_store.rs @@ -0,0 +1,1917 @@ +use std::sync::Arc; + +use common_enums::enums::MerchantStorageScheme; +use common_utils::errors::CustomResult; +use data_models::payments::{ + payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface, +}; +use diesel_models::{ + enums::ProcessTrackerStatus, + ephemeral_key::{EphemeralKey, EphemeralKeyNew}, + reverse_lookup::{ReverseLookup, ReverseLookupNew}, + user_role as user_storage, +}; +use masking::Secret; +use redis_interface::{errors::RedisError, RedisConnectionPool, RedisEntryId}; +use router_env::logger; +use scheduler::{ + db::{process_tracker::ProcessTrackerInterface, queue::QueueInterface}, + SchedulerInterface, +}; +use storage_impl::redis::kv_store::RedisConnInterface; +use time::PrimitiveDateTime; + +use super::{user::UserInterface, user_role::UserRoleInterface}; +use crate::{ + core::errors::{self, ProcessTrackerError}, + db::{ + address::AddressInterface, + api_keys::ApiKeyInterface, + business_profile::BusinessProfileInterface, + capture::CaptureInterface, + cards_info::CardsInfoInterface, + configs::ConfigInterface, + customers::CustomerInterface, + dispute::DisputeInterface, + ephemeral_key::EphemeralKeyInterface, + events::EventInterface, + file::FileMetadataInterface, + gsm::GsmInterface, + locker_mock_up::LockerMockUpInterface, + mandate::MandateInterface, + merchant_account::MerchantAccountInterface, + merchant_connector_account::{ConnectorAccessToken, MerchantConnectorAccountInterface}, + merchant_key_store::MerchantKeyStoreInterface, + payment_link::PaymentLinkInterface, + payment_method::PaymentMethodInterface, + payout_attempt::PayoutAttemptInterface, + payouts::PayoutsInterface, + refund::RefundInterface, + reverse_lookup::ReverseLookupInterface, + routing_algorithm::RoutingAlgorithmInterface, + MasterKeyInterface, StorageInterface, + }, + services::{authentication, kafka::KafkaProducer, Store}, + types::{ + domain, + storage::{self, business_profile}, + AccessToken, + }, +}; + +#[derive(Clone)] +pub struct KafkaStore { + kafka_producer: KafkaProducer, + pub diesel_store: Store, +} + +impl KafkaStore { + pub async fn new(store: Store, kafka_producer: KafkaProducer) -> Self { + Self { + kafka_producer, + diesel_store: store, + } + } +} + +#[async_trait::async_trait] +impl AddressInterface for KafkaStore { + async fn find_address_by_address_id( + &self, + address_id: &str, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::Address, errors::StorageError> { + self.diesel_store + .find_address_by_address_id(address_id, key_store) + .await + } + + async fn update_address( + &self, + address_id: String, + address: storage::AddressUpdate, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::Address, errors::StorageError> { + self.diesel_store + .update_address(address_id, address, key_store) + .await + } + + async fn update_address_for_payments( + &self, + this: domain::Address, + address: domain::AddressUpdate, + payment_id: String, + key_store: &domain::MerchantKeyStore, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<domain::Address, errors::StorageError> { + self.diesel_store + .update_address_for_payments(this, address, payment_id, key_store, storage_scheme) + .await + } + + async fn insert_address_for_payments( + &self, + payment_id: &str, + address: domain::Address, + key_store: &domain::MerchantKeyStore, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<domain::Address, errors::StorageError> { + self.diesel_store + .insert_address_for_payments(payment_id, address, key_store, storage_scheme) + .await + } + + async fn find_address_by_merchant_id_payment_id_address_id( + &self, + merchant_id: &str, + payment_id: &str, + address_id: &str, + key_store: &domain::MerchantKeyStore, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<domain::Address, errors::StorageError> { + self.diesel_store + .find_address_by_merchant_id_payment_id_address_id( + merchant_id, + payment_id, + address_id, + key_store, + storage_scheme, + ) + .await + } + + async fn insert_address_for_customers( + &self, + address: domain::Address, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::Address, errors::StorageError> { + self.diesel_store + .insert_address_for_customers(address, key_store) + .await + } + + async fn update_address_by_merchant_id_customer_id( + &self, + customer_id: &str, + merchant_id: &str, + address: storage::AddressUpdate, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<Vec<domain::Address>, errors::StorageError> { + self.diesel_store + .update_address_by_merchant_id_customer_id(customer_id, merchant_id, address, key_store) + .await + } +} + +#[async_trait::async_trait] +impl ApiKeyInterface for KafkaStore { + async fn insert_api_key( + &self, + api_key: storage::ApiKeyNew, + ) -> CustomResult<storage::ApiKey, errors::StorageError> { + self.diesel_store.insert_api_key(api_key).await + } + + async fn update_api_key( + &self, + merchant_id: String, + key_id: String, + api_key: storage::ApiKeyUpdate, + ) -> CustomResult<storage::ApiKey, errors::StorageError> { + self.diesel_store + .update_api_key(merchant_id, key_id, api_key) + .await + } + + async fn revoke_api_key( + &self, + merchant_id: &str, + key_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store.revoke_api_key(merchant_id, key_id).await + } + + async fn find_api_key_by_merchant_id_key_id_optional( + &self, + merchant_id: &str, + key_id: &str, + ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { + self.diesel_store + .find_api_key_by_merchant_id_key_id_optional(merchant_id, key_id) + .await + } + + async fn find_api_key_by_hash_optional( + &self, + hashed_api_key: storage::HashedApiKey, + ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { + self.diesel_store + .find_api_key_by_hash_optional(hashed_api_key) + .await + } + + async fn list_api_keys_by_merchant_id( + &self, + merchant_id: &str, + limit: Option<i64>, + offset: Option<i64>, + ) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> { + self.diesel_store + .list_api_keys_by_merchant_id(merchant_id, limit, offset) + .await + } +} + +#[async_trait::async_trait] +impl CardsInfoInterface for KafkaStore { + async fn get_card_info( + &self, + card_iin: &str, + ) -> CustomResult<Option<storage::CardInfo>, errors::StorageError> { + self.diesel_store.get_card_info(card_iin).await + } +} + +#[async_trait::async_trait] +impl ConfigInterface for KafkaStore { + async fn insert_config( + &self, + config: storage::ConfigNew, + ) -> CustomResult<storage::Config, errors::StorageError> { + self.diesel_store.insert_config(config).await + } + + async fn find_config_by_key( + &self, + key: &str, + ) -> CustomResult<storage::Config, errors::StorageError> { + self.diesel_store.find_config_by_key(key).await + } + + async fn find_config_by_key_from_db( + &self, + key: &str, + ) -> CustomResult<storage::Config, errors::StorageError> { + self.diesel_store.find_config_by_key_from_db(key).await + } + + async fn update_config_in_database( + &self, + key: &str, + config_update: storage::ConfigUpdate, + ) -> CustomResult<storage::Config, errors::StorageError> { + self.diesel_store + .update_config_in_database(key, config_update) + .await + } + + async fn update_config_by_key( + &self, + key: &str, + config_update: storage::ConfigUpdate, + ) -> CustomResult<storage::Config, errors::StorageError> { + self.diesel_store + .update_config_by_key(key, config_update) + .await + } + + async fn delete_config_by_key(&self, key: &str) -> CustomResult<bool, errors::StorageError> { + self.diesel_store.delete_config_by_key(key).await + } + + async fn find_config_by_key_unwrap_or( + &self, + key: &str, + default_config: Option<String>, + ) -> CustomResult<storage::Config, errors::StorageError> { + self.diesel_store + .find_config_by_key_unwrap_or(key, default_config) + .await + } +} + +#[async_trait::async_trait] +impl CustomerInterface for KafkaStore { + async fn delete_customer_by_customer_id_merchant_id( + &self, + customer_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store + .delete_customer_by_customer_id_merchant_id(customer_id, merchant_id) + .await + } + + async fn find_customer_optional_by_customer_id_merchant_id( + &self, + customer_id: &str, + merchant_id: &str, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<Option<domain::Customer>, errors::StorageError> { + self.diesel_store + .find_customer_optional_by_customer_id_merchant_id(customer_id, merchant_id, key_store) + .await + } + + async fn update_customer_by_customer_id_merchant_id( + &self, + customer_id: String, + merchant_id: String, + customer: storage::CustomerUpdate, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::Customer, errors::StorageError> { + self.diesel_store + .update_customer_by_customer_id_merchant_id( + customer_id, + merchant_id, + customer, + key_store, + ) + .await + } + + async fn list_customers_by_merchant_id( + &self, + merchant_id: &str, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> { + self.diesel_store + .list_customers_by_merchant_id(merchant_id, key_store) + .await + } + + async fn find_customer_by_customer_id_merchant_id( + &self, + customer_id: &str, + merchant_id: &str, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::Customer, errors::StorageError> { + self.diesel_store + .find_customer_by_customer_id_merchant_id(customer_id, merchant_id, key_store) + .await + } + + async fn insert_customer( + &self, + customer_data: domain::Customer, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::Customer, errors::StorageError> { + self.diesel_store + .insert_customer(customer_data, key_store) + .await + } +} + +#[async_trait::async_trait] +impl DisputeInterface for KafkaStore { + async fn insert_dispute( + &self, + dispute: storage::DisputeNew, + ) -> CustomResult<storage::Dispute, errors::StorageError> { + self.diesel_store.insert_dispute(dispute).await + } + + async fn find_by_merchant_id_payment_id_connector_dispute_id( + &self, + merchant_id: &str, + payment_id: &str, + connector_dispute_id: &str, + ) -> CustomResult<Option<storage::Dispute>, errors::StorageError> { + self.diesel_store + .find_by_merchant_id_payment_id_connector_dispute_id( + merchant_id, + payment_id, + connector_dispute_id, + ) + .await + } + + async fn find_dispute_by_merchant_id_dispute_id( + &self, + merchant_id: &str, + dispute_id: &str, + ) -> CustomResult<storage::Dispute, errors::StorageError> { + self.diesel_store + .find_dispute_by_merchant_id_dispute_id(merchant_id, dispute_id) + .await + } + + async fn find_disputes_by_merchant_id( + &self, + merchant_id: &str, + dispute_constraints: api_models::disputes::DisputeListConstraints, + ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { + self.diesel_store + .find_disputes_by_merchant_id(merchant_id, dispute_constraints) + .await + } + + async fn update_dispute( + &self, + this: storage::Dispute, + dispute: storage::DisputeUpdate, + ) -> CustomResult<storage::Dispute, errors::StorageError> { + self.diesel_store.update_dispute(this, dispute).await + } + + async fn find_disputes_by_merchant_id_payment_id( + &self, + merchant_id: &str, + payment_id: &str, + ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { + self.diesel_store + .find_disputes_by_merchant_id_payment_id(merchant_id, payment_id) + .await + } +} + +#[async_trait::async_trait] +impl EphemeralKeyInterface for KafkaStore { + async fn create_ephemeral_key( + &self, + ek: EphemeralKeyNew, + validity: i64, + ) -> CustomResult<EphemeralKey, errors::StorageError> { + self.diesel_store.create_ephemeral_key(ek, validity).await + } + async fn get_ephemeral_key( + &self, + key: &str, + ) -> CustomResult<EphemeralKey, errors::StorageError> { + self.diesel_store.get_ephemeral_key(key).await + } + async fn delete_ephemeral_key( + &self, + id: &str, + ) -> CustomResult<EphemeralKey, errors::StorageError> { + self.diesel_store.delete_ephemeral_key(id).await + } +} + +#[async_trait::async_trait] +impl EventInterface for KafkaStore { + async fn insert_event( + &self, + event: storage::EventNew, + ) -> CustomResult<storage::Event, errors::StorageError> { + self.diesel_store.insert_event(event).await + } + + async fn update_event( + &self, + event_id: String, + event: storage::EventUpdate, + ) -> CustomResult<storage::Event, errors::StorageError> { + self.diesel_store.update_event(event_id, event).await + } +} + +#[async_trait::async_trait] +impl LockerMockUpInterface for KafkaStore { + async fn find_locker_by_card_id( + &self, + card_id: &str, + ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { + self.diesel_store.find_locker_by_card_id(card_id).await + } + + async fn insert_locker_mock_up( + &self, + new: storage::LockerMockUpNew, + ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { + self.diesel_store.insert_locker_mock_up(new).await + } + + async fn delete_locker_mock_up( + &self, + card_id: &str, + ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { + self.diesel_store.delete_locker_mock_up(card_id).await + } +} + +#[async_trait::async_trait] +impl MandateInterface for KafkaStore { + async fn find_mandate_by_merchant_id_mandate_id( + &self, + merchant_id: &str, + mandate_id: &str, + ) -> CustomResult<storage::Mandate, errors::StorageError> { + self.diesel_store + .find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id) + .await + } + + async fn find_mandate_by_merchant_id_connector_mandate_id( + &self, + merchant_id: &str, + connector_mandate_id: &str, + ) -> CustomResult<storage::Mandate, errors::StorageError> { + self.diesel_store + .find_mandate_by_merchant_id_connector_mandate_id(merchant_id, connector_mandate_id) + .await + } + + async fn find_mandate_by_merchant_id_customer_id( + &self, + merchant_id: &str, + customer_id: &str, + ) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> { + self.diesel_store + .find_mandate_by_merchant_id_customer_id(merchant_id, customer_id) + .await + } + + async fn update_mandate_by_merchant_id_mandate_id( + &self, + merchant_id: &str, + mandate_id: &str, + mandate: storage::MandateUpdate, + ) -> CustomResult<storage::Mandate, errors::StorageError> { + self.diesel_store + .update_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id, mandate) + .await + } + + async fn find_mandates_by_merchant_id( + &self, + merchant_id: &str, + mandate_constraints: api_models::mandates::MandateListConstraints, + ) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> { + self.diesel_store + .find_mandates_by_merchant_id(merchant_id, mandate_constraints) + .await + } + + async fn insert_mandate( + &self, + mandate: storage::MandateNew, + ) -> CustomResult<storage::Mandate, errors::StorageError> { + self.diesel_store.insert_mandate(mandate).await + } +} + +#[async_trait::async_trait] +impl PaymentLinkInterface for KafkaStore { + async fn find_payment_link_by_payment_link_id( + &self, + payment_link_id: &str, + ) -> CustomResult<storage::PaymentLink, errors::StorageError> { + self.diesel_store + .find_payment_link_by_payment_link_id(payment_link_id) + .await + } + + async fn insert_payment_link( + &self, + payment_link_object: storage::PaymentLinkNew, + ) -> CustomResult<storage::PaymentLink, errors::StorageError> { + self.diesel_store + .insert_payment_link(payment_link_object) + .await + } + + async fn list_payment_link_by_merchant_id( + &self, + merchant_id: &str, + payment_link_constraints: api_models::payments::PaymentLinkListConstraints, + ) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> { + self.diesel_store + .list_payment_link_by_merchant_id(merchant_id, payment_link_constraints) + .await + } +} + +#[async_trait::async_trait] +impl MerchantAccountInterface for KafkaStore { + async fn insert_merchant( + &self, + merchant_account: domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { + self.diesel_store + .insert_merchant(merchant_account, key_store) + .await + } + + async fn find_merchant_account_by_merchant_id( + &self, + merchant_id: &str, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { + self.diesel_store + .find_merchant_account_by_merchant_id(merchant_id, key_store) + .await + } + + async fn update_merchant( + &self, + this: domain::MerchantAccount, + merchant_account: storage::MerchantAccountUpdate, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { + self.diesel_store + .update_merchant(this, merchant_account, key_store) + .await + } + + async fn update_specific_fields_in_merchant( + &self, + merchant_id: &str, + merchant_account: storage::MerchantAccountUpdate, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { + self.diesel_store + .update_specific_fields_in_merchant(merchant_id, merchant_account, key_store) + .await + } + + async fn find_merchant_account_by_publishable_key( + &self, + publishable_key: &str, + ) -> CustomResult<authentication::AuthenticationData, errors::StorageError> { + self.diesel_store + .find_merchant_account_by_publishable_key(publishable_key) + .await + } + + #[cfg(feature = "olap")] + async fn list_merchant_accounts_by_organization_id( + &self, + organization_id: &str, + ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { + self.diesel_store + .list_merchant_accounts_by_organization_id(organization_id) + .await + } + + async fn delete_merchant_account_by_merchant_id( + &self, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store + .delete_merchant_account_by_merchant_id(merchant_id) + .await + } +} + +#[async_trait::async_trait] +impl ConnectorAccessToken for KafkaStore { + async fn get_access_token( + &self, + merchant_id: &str, + connector_name: &str, + ) -> CustomResult<Option<AccessToken>, errors::StorageError> { + self.diesel_store + .get_access_token(merchant_id, connector_name) + .await + } + + async fn set_access_token( + &self, + merchant_id: &str, + connector_name: &str, + access_token: AccessToken, + ) -> CustomResult<(), errors::StorageError> { + self.diesel_store + .set_access_token(merchant_id, connector_name, access_token) + .await + } +} + +#[async_trait::async_trait] +impl FileMetadataInterface for KafkaStore { + async fn insert_file_metadata( + &self, + file: storage::FileMetadataNew, + ) -> CustomResult<storage::FileMetadata, errors::StorageError> { + self.diesel_store.insert_file_metadata(file).await + } + + async fn find_file_metadata_by_merchant_id_file_id( + &self, + merchant_id: &str, + file_id: &str, + ) -> CustomResult<storage::FileMetadata, errors::StorageError> { + self.diesel_store + .find_file_metadata_by_merchant_id_file_id(merchant_id, file_id) + .await + } + + async fn delete_file_metadata_by_merchant_id_file_id( + &self, + merchant_id: &str, + file_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store + .delete_file_metadata_by_merchant_id_file_id(merchant_id, file_id) + .await + } + + async fn update_file_metadata( + &self, + this: storage::FileMetadata, + file_metadata: storage::FileMetadataUpdate, + ) -> CustomResult<storage::FileMetadata, errors::StorageError> { + self.diesel_store + .update_file_metadata(this, file_metadata) + .await + } +} + +#[async_trait::async_trait] +impl MerchantConnectorAccountInterface for KafkaStore { + async fn find_merchant_connector_account_by_merchant_id_connector_label( + &self, + merchant_id: &str, + connector: &str, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { + self.diesel_store + .find_merchant_connector_account_by_merchant_id_connector_label( + merchant_id, + connector, + key_store, + ) + .await + } + + async fn find_merchant_connector_account_by_merchant_id_connector_name( + &self, + merchant_id: &str, + connector_name: &str, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { + self.diesel_store + .find_merchant_connector_account_by_merchant_id_connector_name( + merchant_id, + connector_name, + key_store, + ) + .await + } + + async fn find_merchant_connector_account_by_profile_id_connector_name( + &self, + profile_id: &str, + connector_name: &str, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { + self.diesel_store + .find_merchant_connector_account_by_profile_id_connector_name( + profile_id, + connector_name, + key_store, + ) + .await + } + + async fn insert_merchant_connector_account( + &self, + t: domain::MerchantConnectorAccount, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { + self.diesel_store + .insert_merchant_connector_account(t, key_store) + .await + } + + async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &self, + merchant_id: &str, + merchant_connector_id: &str, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { + self.diesel_store + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + merchant_id, + merchant_connector_id, + key_store, + ) + .await + } + + async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( + &self, + merchant_id: &str, + get_disabled: bool, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { + self.diesel_store + .find_merchant_connector_account_by_merchant_id_and_disabled_list( + merchant_id, + get_disabled, + key_store, + ) + .await + } + + async fn update_merchant_connector_account( + &self, + this: domain::MerchantConnectorAccount, + merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, + key_store: &domain::MerchantKeyStore, + ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { + self.diesel_store + .update_merchant_connector_account(this, merchant_connector_account, key_store) + .await + } + + async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( + &self, + merchant_id: &str, + merchant_connector_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store + .delete_merchant_connector_account_by_merchant_id_merchant_connector_id( + merchant_id, + merchant_connector_id, + ) + .await + } +} + +#[async_trait::async_trait] +impl QueueInterface for KafkaStore { + async fn fetch_consumer_tasks( + &self, + stream_name: &str, + group_name: &str, + consumer_name: &str, + ) -> CustomResult<Vec<storage::ProcessTracker>, ProcessTrackerError> { + self.diesel_store + .fetch_consumer_tasks(stream_name, group_name, consumer_name) + .await + } + + async fn consumer_group_create( + &self, + stream: &str, + group: &str, + id: &RedisEntryId, + ) -> CustomResult<(), RedisError> { + self.diesel_store + .consumer_group_create(stream, group, id) + .await + } + + async fn acquire_pt_lock( + &self, + tag: &str, + lock_key: &str, + lock_val: &str, + ttl: i64, + ) -> CustomResult<bool, RedisError> { + self.diesel_store + .acquire_pt_lock(tag, lock_key, lock_val, ttl) + .await + } + + async fn release_pt_lock(&self, tag: &str, lock_key: &str) -> CustomResult<bool, RedisError> { + self.diesel_store.release_pt_lock(tag, lock_key).await + } + + async fn stream_append_entry( + &self, + stream: &str, + entry_id: &RedisEntryId, + fields: Vec<(&str, String)>, + ) -> CustomResult<(), RedisError> { + self.diesel_store + .stream_append_entry(stream, entry_id, fields) + .await + } + + async fn get_key(&self, key: &str) -> CustomResult<Vec<u8>, RedisError> { + self.diesel_store.get_key(key).await + } +} + +#[async_trait::async_trait] +impl PaymentAttemptInterface for KafkaStore { + async fn insert_payment_attempt( + &self, + payment_attempt: storage::PaymentAttemptNew, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> { + let attempt = self + .diesel_store + .insert_payment_attempt(payment_attempt, storage_scheme) + .await?; + + if let Err(er) = self + .kafka_producer + .log_payment_attempt(&attempt, None) + .await + { + logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) + } + + Ok(attempt) + } + + async fn update_payment_attempt_with_attempt_id( + &self, + this: storage::PaymentAttempt, + payment_attempt: storage::PaymentAttemptUpdate, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> { + let attempt = self + .diesel_store + .update_payment_attempt_with_attempt_id(this.clone(), payment_attempt, storage_scheme) + .await?; + + if let Err(er) = self + .kafka_producer + .log_payment_attempt(&attempt, Some(this)) + .await + { + logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) + } + + Ok(attempt) + } + + async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( + &self, + connector_transaction_id: &str, + payment_id: &str, + merchant_id: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> { + self.diesel_store + .find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( + connector_transaction_id, + payment_id, + merchant_id, + storage_scheme, + ) + .await + } + + async fn find_payment_attempt_by_merchant_id_connector_txn_id( + &self, + merchant_id: &str, + connector_txn_id: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> { + self.diesel_store + .find_payment_attempt_by_merchant_id_connector_txn_id( + merchant_id, + connector_txn_id, + storage_scheme, + ) + .await + } + + async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( + &self, + payment_id: &str, + merchant_id: &str, + attempt_id: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> { + self.diesel_store + .find_payment_attempt_by_payment_id_merchant_id_attempt_id( + payment_id, + merchant_id, + attempt_id, + storage_scheme, + ) + .await + } + + async fn find_payment_attempt_by_attempt_id_merchant_id( + &self, + attempt_id: &str, + merchant_id: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> { + self.diesel_store + .find_payment_attempt_by_attempt_id_merchant_id(attempt_id, merchant_id, storage_scheme) + .await + } + + async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( + &self, + payment_id: &str, + merchant_id: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> { + self.diesel_store + .find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( + payment_id, + merchant_id, + storage_scheme, + ) + .await + } + + async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( + &self, + payment_id: &str, + merchant_id: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> { + self.diesel_store + .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( + payment_id, + merchant_id, + storage_scheme, + ) + .await + } + + async fn find_payment_attempt_by_preprocessing_id_merchant_id( + &self, + preprocessing_id: &str, + merchant_id: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> { + self.diesel_store + .find_payment_attempt_by_preprocessing_id_merchant_id( + preprocessing_id, + merchant_id, + storage_scheme, + ) + .await + } + + async fn get_filters_for_payments( + &self, + pi: &[data_models::payments::PaymentIntent], + merchant_id: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult< + data_models::payments::payment_attempt::PaymentListFilters, + errors::DataStorageError, + > { + self.diesel_store + .get_filters_for_payments(pi, merchant_id, storage_scheme) + .await + } + + async fn get_total_count_of_filtered_payment_attempts( + &self, + merchant_id: &str, + active_attempt_ids: &[String], + connector: Option<Vec<api_models::enums::Connector>>, + payment_method: Option<Vec<common_enums::PaymentMethod>>, + payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, + authentication_type: Option<Vec<common_enums::AuthenticationType>>, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<i64, errors::DataStorageError> { + self.diesel_store + .get_total_count_of_filtered_payment_attempts( + merchant_id, + active_attempt_ids, + connector, + payment_method, + payment_method_type, + authentication_type, + storage_scheme, + ) + .await + } + + async fn find_attempts_by_merchant_id_payment_id( + &self, + merchant_id: &str, + payment_id: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<Vec<storage::PaymentAttempt>, errors::DataStorageError> { + self.diesel_store + .find_attempts_by_merchant_id_payment_id(merchant_id, payment_id, storage_scheme) + .await + } +} + +#[async_trait::async_trait] +impl PaymentIntentInterface for KafkaStore { + async fn update_payment_intent( + &self, + this: storage::PaymentIntent, + payment_intent: storage::PaymentIntentUpdate, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentIntent, errors::DataStorageError> { + let intent = self + .diesel_store + .update_payment_intent(this.clone(), payment_intent, storage_scheme) + .await?; + + if let Err(er) = self + .kafka_producer + .log_payment_intent(&intent, Some(this)) + .await + { + logger::error!(message="Failed to add analytics entry for Payment Intent {intent:?}", error_message=?er); + }; + + Ok(intent) + } + + async fn insert_payment_intent( + &self, + new: storage::PaymentIntentNew, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentIntent, errors::DataStorageError> { + logger::debug!("Inserting PaymentIntent Via KafkaStore"); + let intent = self + .diesel_store + .insert_payment_intent(new, storage_scheme) + .await?; + + if let Err(er) = self.kafka_producer.log_payment_intent(&intent, None).await { + logger::error!(message="Failed to add analytics entry for Payment Intent {intent:?}", error_message=?er); + }; + + Ok(intent) + } + + async fn find_payment_intent_by_payment_id_merchant_id( + &self, + payment_id: &str, + merchant_id: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentIntent, errors::DataStorageError> { + self.diesel_store + .find_payment_intent_by_payment_id_merchant_id(payment_id, merchant_id, storage_scheme) + .await + } + + #[cfg(feature = "olap")] + async fn filter_payment_intent_by_constraints( + &self, + merchant_id: &str, + filters: &data_models::payments::payment_intent::PaymentIntentFetchConstraints, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<Vec<storage::PaymentIntent>, errors::DataStorageError> { + self.diesel_store + .filter_payment_intent_by_constraints(merchant_id, filters, storage_scheme) + .await + } + + #[cfg(feature = "olap")] + async fn filter_payment_intents_by_time_range_constraints( + &self, + merchant_id: &str, + time_range: &api_models::payments::TimeRange, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<Vec<storage::PaymentIntent>, errors::DataStorageError> { + self.diesel_store + .filter_payment_intents_by_time_range_constraints( + merchant_id, + time_range, + storage_scheme, + ) + .await + } + + #[cfg(feature = "olap")] + async fn get_filtered_payment_intents_attempt( + &self, + merchant_id: &str, + constraints: &data_models::payments::payment_intent::PaymentIntentFetchConstraints, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult< + Vec<( + data_models::payments::PaymentIntent, + data_models::payments::payment_attempt::PaymentAttempt, + )>, + errors::DataStorageError, + > { + self.diesel_store + .get_filtered_payment_intents_attempt(merchant_id, constraints, storage_scheme) + .await + } + + #[cfg(feature = "olap")] + async fn get_filtered_active_attempt_ids_for_total_count( + &self, + merchant_id: &str, + constraints: &data_models::payments::payment_intent::PaymentIntentFetchConstraints, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<Vec<String>, errors::DataStorageError> { + self.diesel_store + .get_filtered_active_attempt_ids_for_total_count( + merchant_id, + constraints, + storage_scheme, + ) + .await + } + + async fn get_active_payment_attempt( + &self, + payment: &mut storage::PaymentIntent, + storage_scheme: MerchantStorageScheme, + ) -> error_stack::Result<storage::PaymentAttempt, errors::DataStorageError> { + self.diesel_store + .get_active_payment_attempt(payment, storage_scheme) + .await + } +} + +#[async_trait::async_trait] +impl PaymentMethodInterface for KafkaStore { + async fn find_payment_method( + &self, + payment_method_id: &str, + ) -> CustomResult<storage::PaymentMethod, errors::StorageError> { + self.diesel_store + .find_payment_method(payment_method_id) + .await + } + + async fn find_payment_method_by_customer_id_merchant_id_list( + &self, + customer_id: &str, + merchant_id: &str, + ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { + self.diesel_store + .find_payment_method_by_customer_id_merchant_id_list(customer_id, merchant_id) + .await + } + + async fn insert_payment_method( + &self, + m: storage::PaymentMethodNew, + ) -> CustomResult<storage::PaymentMethod, errors::StorageError> { + self.diesel_store.insert_payment_method(m).await + } + + async fn update_payment_method( + &self, + payment_method: storage::PaymentMethod, + payment_method_update: storage::PaymentMethodUpdate, + ) -> CustomResult<storage::PaymentMethod, errors::StorageError> { + self.diesel_store + .update_payment_method(payment_method, payment_method_update) + .await + } + + async fn delete_payment_method_by_merchant_id_payment_method_id( + &self, + merchant_id: &str, + payment_method_id: &str, + ) -> CustomResult<storage::PaymentMethod, errors::StorageError> { + self.diesel_store + .delete_payment_method_by_merchant_id_payment_method_id(merchant_id, payment_method_id) + .await + } +} + +#[async_trait::async_trait] +impl PayoutAttemptInterface for KafkaStore { + async fn find_payout_attempt_by_merchant_id_payout_id( + &self, + merchant_id: &str, + payout_id: &str, + ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> { + self.diesel_store + .find_payout_attempt_by_merchant_id_payout_id(merchant_id, payout_id) + .await + } + + async fn update_payout_attempt_by_merchant_id_payout_id( + &self, + merchant_id: &str, + payout_id: &str, + payout: storage::PayoutAttemptUpdate, + ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> { + self.diesel_store + .update_payout_attempt_by_merchant_id_payout_id(merchant_id, payout_id, payout) + .await + } + + async fn insert_payout_attempt( + &self, + payout: storage::PayoutAttemptNew, + ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> { + self.diesel_store.insert_payout_attempt(payout).await + } +} + +#[async_trait::async_trait] +impl PayoutsInterface for KafkaStore { + async fn find_payout_by_merchant_id_payout_id( + &self, + merchant_id: &str, + payout_id: &str, + ) -> CustomResult<storage::Payouts, errors::StorageError> { + self.diesel_store + .find_payout_by_merchant_id_payout_id(merchant_id, payout_id) + .await + } + + async fn update_payout_by_merchant_id_payout_id( + &self, + merchant_id: &str, + payout_id: &str, + payout: storage::PayoutsUpdate, + ) -> CustomResult<storage::Payouts, errors::StorageError> { + self.diesel_store + .update_payout_by_merchant_id_payout_id(merchant_id, payout_id, payout) + .await + } + + async fn insert_payout( + &self, + payout: storage::PayoutsNew, + ) -> CustomResult<storage::Payouts, errors::StorageError> { + self.diesel_store.insert_payout(payout).await + } +} + +#[async_trait::async_trait] +impl ProcessTrackerInterface for KafkaStore { + async fn reinitialize_limbo_processes( + &self, + ids: Vec<String>, + schedule_time: PrimitiveDateTime, + ) -> CustomResult<usize, errors::StorageError> { + self.diesel_store + .reinitialize_limbo_processes(ids, schedule_time) + .await + } + + async fn find_process_by_id( + &self, + id: &str, + ) -> CustomResult<Option<storage::ProcessTracker>, errors::StorageError> { + self.diesel_store.find_process_by_id(id).await + } + + async fn update_process( + &self, + this: storage::ProcessTracker, + process: storage::ProcessTrackerUpdate, + ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { + self.diesel_store.update_process(this, process).await + } + + async fn process_tracker_update_process_status_by_ids( + &self, + task_ids: Vec<String>, + task_update: storage::ProcessTrackerUpdate, + ) -> CustomResult<usize, errors::StorageError> { + self.diesel_store + .process_tracker_update_process_status_by_ids(task_ids, task_update) + .await + } + async fn update_process_tracker( + &self, + this: storage::ProcessTracker, + process: storage::ProcessTrackerUpdate, + ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { + self.diesel_store + .update_process_tracker(this, process) + .await + } + + async fn insert_process( + &self, + new: storage::ProcessTrackerNew, + ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { + self.diesel_store.insert_process(new).await + } + + async fn find_processes_by_time_status( + &self, + time_lower_limit: PrimitiveDateTime, + time_upper_limit: PrimitiveDateTime, + status: ProcessTrackerStatus, + limit: Option<i64>, + ) -> CustomResult<Vec<storage::ProcessTracker>, errors::StorageError> { + self.diesel_store + .find_processes_by_time_status(time_lower_limit, time_upper_limit, status, limit) + .await + } +} + +#[async_trait::async_trait] +impl CaptureInterface for KafkaStore { + async fn insert_capture( + &self, + capture: storage::CaptureNew, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::Capture, errors::StorageError> { + self.diesel_store + .insert_capture(capture, storage_scheme) + .await + } + + async fn update_capture_with_capture_id( + &self, + this: storage::Capture, + capture: storage::CaptureUpdate, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::Capture, errors::StorageError> { + self.diesel_store + .update_capture_with_capture_id(this, capture, storage_scheme) + .await + } + + async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( + &self, + merchant_id: &str, + payment_id: &str, + authorized_attempt_id: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<Vec<storage::Capture>, errors::StorageError> { + self.diesel_store + .find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( + merchant_id, + payment_id, + authorized_attempt_id, + storage_scheme, + ) + .await + } +} + +#[async_trait::async_trait] +impl RefundInterface for KafkaStore { + async fn find_refund_by_internal_reference_id_merchant_id( + &self, + internal_reference_id: &str, + merchant_id: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::Refund, errors::StorageError> { + self.diesel_store + .find_refund_by_internal_reference_id_merchant_id( + internal_reference_id, + merchant_id, + storage_scheme, + ) + .await + } + + async fn find_refund_by_payment_id_merchant_id( + &self, + payment_id: &str, + merchant_id: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<Vec<storage::Refund>, errors::StorageError> { + self.diesel_store + .find_refund_by_payment_id_merchant_id(payment_id, merchant_id, storage_scheme) + .await + } + + async fn find_refund_by_merchant_id_refund_id( + &self, + merchant_id: &str, + refund_id: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::Refund, errors::StorageError> { + self.diesel_store + .find_refund_by_merchant_id_refund_id(merchant_id, refund_id, storage_scheme) + .await + } + + async fn find_refund_by_merchant_id_connector_refund_id_connector( + &self, + merchant_id: &str, + connector_refund_id: &str, + connector: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::Refund, errors::StorageError> { + self.diesel_store + .find_refund_by_merchant_id_connector_refund_id_connector( + merchant_id, + connector_refund_id, + connector, + storage_scheme, + ) + .await + } + + async fn update_refund( + &self, + this: storage::Refund, + refund: storage::RefundUpdate, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::Refund, errors::StorageError> { + let refund = self + .diesel_store + .update_refund(this.clone(), refund, storage_scheme) + .await?; + + if let Err(er) = self.kafka_producer.log_refund(&refund, Some(this)).await { + logger::error!(message="Failed to insert analytics event for Refund Update {refund?}", error_message=?er); + } + Ok(refund) + } + + async fn find_refund_by_merchant_id_connector_transaction_id( + &self, + merchant_id: &str, + connector_transaction_id: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<Vec<storage::Refund>, errors::StorageError> { + self.diesel_store + .find_refund_by_merchant_id_connector_transaction_id( + merchant_id, + connector_transaction_id, + storage_scheme, + ) + .await + } + + async fn insert_refund( + &self, + new: storage::RefundNew, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::Refund, errors::StorageError> { + let refund = self.diesel_store.insert_refund(new, storage_scheme).await?; + + if let Err(er) = self.kafka_producer.log_refund(&refund, None).await { + logger::error!(message="Failed to insert analytics event for Refund Create {refund?}", error_message=?er); + } + Ok(refund) + } + + #[cfg(feature = "olap")] + async fn filter_refund_by_constraints( + &self, + merchant_id: &str, + refund_details: &api_models::refunds::RefundListRequest, + storage_scheme: MerchantStorageScheme, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<storage::Refund>, errors::StorageError> { + self.diesel_store + .filter_refund_by_constraints( + merchant_id, + refund_details, + storage_scheme, + limit, + offset, + ) + .await + } + + #[cfg(feature = "olap")] + async fn filter_refund_by_meta_constraints( + &self, + merchant_id: &str, + refund_details: &api_models::payments::TimeRange, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> { + self.diesel_store + .filter_refund_by_meta_constraints(merchant_id, refund_details, storage_scheme) + .await + } + + #[cfg(feature = "olap")] + async fn get_total_count_of_refunds( + &self, + merchant_id: &str, + refund_details: &api_models::refunds::RefundListRequest, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<i64, errors::StorageError> { + self.diesel_store + .get_total_count_of_refunds(merchant_id, refund_details, storage_scheme) + .await + } +} + +#[async_trait::async_trait] +impl MerchantKeyStoreInterface for KafkaStore { + async fn insert_merchant_key_store( + &self, + merchant_key_store: domain::MerchantKeyStore, + key: &Secret<Vec<u8>>, + ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { + self.diesel_store + .insert_merchant_key_store(merchant_key_store, key) + .await + } + + async fn get_merchant_key_store_by_merchant_id( + &self, + merchant_id: &str, + key: &Secret<Vec<u8>>, + ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { + self.diesel_store + .get_merchant_key_store_by_merchant_id(merchant_id, key) + .await + } + + async fn delete_merchant_key_store_by_merchant_id( + &self, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store + .delete_merchant_key_store_by_merchant_id(merchant_id) + .await + } +} + +#[async_trait::async_trait] +impl BusinessProfileInterface for KafkaStore { + async fn insert_business_profile( + &self, + business_profile: business_profile::BusinessProfileNew, + ) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> { + self.diesel_store + .insert_business_profile(business_profile) + .await + } + + async fn find_business_profile_by_profile_id( + &self, + profile_id: &str, + ) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> { + self.diesel_store + .find_business_profile_by_profile_id(profile_id) + .await + } + + async fn update_business_profile_by_profile_id( + &self, + current_state: business_profile::BusinessProfile, + business_profile_update: business_profile::BusinessProfileUpdateInternal, + ) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> { + self.diesel_store + .update_business_profile_by_profile_id(current_state, business_profile_update) + .await + } + + async fn delete_business_profile_by_profile_id_merchant_id( + &self, + profile_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store + .delete_business_profile_by_profile_id_merchant_id(profile_id, merchant_id) + .await + } + + async fn list_business_profile_by_merchant_id( + &self, + merchant_id: &str, + ) -> CustomResult<Vec<business_profile::BusinessProfile>, errors::StorageError> { + self.diesel_store + .list_business_profile_by_merchant_id(merchant_id) + .await + } + + async fn find_business_profile_by_profile_name_merchant_id( + &self, + profile_name: &str, + merchant_id: &str, + ) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> { + self.diesel_store + .find_business_profile_by_profile_name_merchant_id(profile_name, merchant_id) + .await + } +} + +#[async_trait::async_trait] +impl ReverseLookupInterface for KafkaStore { + async fn insert_reverse_lookup( + &self, + new: ReverseLookupNew, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<ReverseLookup, errors::StorageError> { + self.diesel_store + .insert_reverse_lookup(new, storage_scheme) + .await + } + + async fn get_lookup_by_lookup_id( + &self, + id: &str, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<ReverseLookup, errors::StorageError> { + self.diesel_store + .get_lookup_by_lookup_id(id, storage_scheme) + .await + } +} + +#[async_trait::async_trait] +impl RoutingAlgorithmInterface for KafkaStore { + async fn insert_routing_algorithm( + &self, + routing_algorithm: storage::RoutingAlgorithm, + ) -> CustomResult<storage::RoutingAlgorithm, errors::StorageError> { + self.diesel_store + .insert_routing_algorithm(routing_algorithm) + .await + } + + async fn find_routing_algorithm_by_profile_id_algorithm_id( + &self, + profile_id: &str, + algorithm_id: &str, + ) -> CustomResult<storage::RoutingAlgorithm, errors::StorageError> { + self.diesel_store + .find_routing_algorithm_by_profile_id_algorithm_id(profile_id, algorithm_id) + .await + } + + async fn find_routing_algorithm_by_algorithm_id_merchant_id( + &self, + algorithm_id: &str, + merchant_id: &str, + ) -> CustomResult<storage::RoutingAlgorithm, errors::StorageError> { + self.diesel_store + .find_routing_algorithm_by_algorithm_id_merchant_id(algorithm_id, merchant_id) + .await + } + + async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id( + &self, + algorithm_id: &str, + profile_id: &str, + ) -> CustomResult<storage::RoutingProfileMetadata, errors::StorageError> { + self.diesel_store + .find_routing_algorithm_metadata_by_algorithm_id_profile_id(algorithm_id, profile_id) + .await + } + + async fn list_routing_algorithm_metadata_by_profile_id( + &self, + profile_id: &str, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<storage::RoutingAlgorithmMetadata>, errors::StorageError> { + self.diesel_store + .list_routing_algorithm_metadata_by_profile_id(profile_id, limit, offset) + .await + } + + async fn list_routing_algorithm_metadata_by_merchant_id( + &self, + merchant_id: &str, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<storage::RoutingProfileMetadata>, errors::StorageError> { + self.diesel_store + .list_routing_algorithm_metadata_by_merchant_id(merchant_id, limit, offset) + .await + } +} + +#[async_trait::async_trait] +impl GsmInterface for KafkaStore { + async fn add_gsm_rule( + &self, + rule: storage::GatewayStatusMappingNew, + ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + self.diesel_store.add_gsm_rule(rule).await + } + + async fn find_gsm_decision( + &self, + connector: String, + flow: String, + sub_flow: String, + code: String, + message: String, + ) -> CustomResult<String, errors::StorageError> { + self.diesel_store + .find_gsm_decision(connector, flow, sub_flow, code, message) + .await + } + + async fn find_gsm_rule( + &self, + connector: String, + flow: String, + sub_flow: String, + code: String, + message: String, + ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + self.diesel_store + .find_gsm_rule(connector, flow, sub_flow, code, message) + .await + } + + async fn update_gsm_rule( + &self, + connector: String, + flow: String, + sub_flow: String, + code: String, + message: String, + data: storage::GatewayStatusMappingUpdate, + ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + self.diesel_store + .update_gsm_rule(connector, flow, sub_flow, code, message, data) + .await + } + + async fn delete_gsm_rule( + &self, + connector: String, + flow: String, + sub_flow: String, + code: String, + message: String, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store + .delete_gsm_rule(connector, flow, sub_flow, code, message) + .await + } +} + +#[async_trait::async_trait] +impl StorageInterface for KafkaStore { + fn get_scheduler_db(&self) -> Box<dyn SchedulerInterface> { + Box::new(self.clone()) + } +} + +#[async_trait::async_trait] +impl SchedulerInterface for KafkaStore {} + +impl MasterKeyInterface for KafkaStore { + fn get_master_key(&self) -> &[u8] { + self.diesel_store.get_master_key() + } +} +#[async_trait::async_trait] +impl UserInterface for KafkaStore { + async fn insert_user( + &self, + user_data: storage::UserNew, + ) -> CustomResult<storage::User, errors::StorageError> { + self.diesel_store.insert_user(user_data).await + } + + async fn find_user_by_email( + &self, + user_email: &str, + ) -> CustomResult<storage::User, errors::StorageError> { + self.diesel_store.find_user_by_email(user_email).await + } + + async fn find_user_by_id( + &self, + user_id: &str, + ) -> CustomResult<storage::User, errors::StorageError> { + self.diesel_store.find_user_by_id(user_id).await + } + + async fn update_user_by_user_id( + &self, + user_id: &str, + user: storage::UserUpdate, + ) -> CustomResult<storage::User, errors::StorageError> { + self.diesel_store + .update_user_by_user_id(user_id, user) + .await + } + + async fn delete_user_by_user_id( + &self, + user_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store.delete_user_by_user_id(user_id).await + } +} + +impl RedisConnInterface for KafkaStore { + fn get_redis_conn(&self) -> CustomResult<Arc<RedisConnectionPool>, RedisError> { + self.diesel_store.get_redis_conn() + } +} + +#[async_trait::async_trait] +impl UserRoleInterface for KafkaStore { + async fn insert_user_role( + &self, + user_role: user_storage::UserRoleNew, + ) -> CustomResult<user_storage::UserRole, errors::StorageError> { + self.diesel_store.insert_user_role(user_role).await + } + async fn find_user_role_by_user_id( + &self, + user_id: &str, + ) -> CustomResult<user_storage::UserRole, errors::StorageError> { + self.diesel_store.find_user_role_by_user_id(user_id).await + } + async fn update_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + update: user_storage::UserRoleUpdate, + ) -> CustomResult<user_storage::UserRole, errors::StorageError> { + self.diesel_store + .update_user_role_by_user_id_merchant_id(user_id, merchant_id, update) + .await + } + async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError> { + self.diesel_store.delete_user_role(user_id).await + } + async fn list_user_roles_by_user_id( + &self, + user_id: &str, + ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> { + self.diesel_store.list_user_roles_by_user_id(user_id).await + } +} diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs index 39a8543a68c..8f980fee504 100644 --- a/crates/router/src/events.rs +++ b/crates/router/src/events.rs @@ -1,15 +1,21 @@ -use serde::Serialize; +use data_models::errors::{StorageError, StorageResult}; +use error_stack::ResultExt; +use serde::{Deserialize, Serialize}; +use storage_impl::errors::ApplicationError; + +use crate::{db::KafkaProducer, services::kafka::KafkaSettings}; pub mod api_logs; pub mod event_logger; +pub mod kafka_handler; -pub trait EventHandler: Sync + Send + dyn_clone::DynClone { +pub(super) trait EventHandler: Sync + Send + dyn_clone::DynClone { fn log_event(&self, event: RawEvent); } dyn_clone::clone_trait_object!(EventHandler); -#[derive(Debug)] +#[derive(Debug, Serialize)] pub struct RawEvent { pub event_type: EventType, pub key: String, @@ -24,3 +30,55 @@ pub enum EventType { Refund, ApiLogs, } + +#[derive(Debug, Default, Deserialize, Clone)] +#[serde(tag = "source")] +#[serde(rename_all = "lowercase")] +pub enum EventsConfig { + Kafka { + kafka: KafkaSettings, + }, + #[default] + Logs, +} + +#[derive(Debug, Clone)] +pub enum EventsHandler { + Kafka(KafkaProducer), + Logs(event_logger::EventLogger), +} + +impl Default for EventsHandler { + fn default() -> Self { + Self::Logs(event_logger::EventLogger {}) + } +} + +impl EventsConfig { + pub async fn get_event_handler(&self) -> StorageResult<EventsHandler> { + Ok(match self { + Self::Kafka { kafka } => EventsHandler::Kafka( + KafkaProducer::create(kafka) + .await + .change_context(StorageError::InitializationError)?, + ), + Self::Logs => EventsHandler::Logs(event_logger::EventLogger::default()), + }) + } + + pub fn validate(&self) -> Result<(), ApplicationError> { + match self { + Self::Kafka { kafka } => kafka.validate(), + Self::Logs => Ok(()), + } + } +} + +impl EventsHandler { + pub fn log_event(&self, event: RawEvent) { + match self { + Self::Kafka(kafka) => kafka.log_event(event), + Self::Logs(logger) => logger.log_event(event), + } + } +} diff --git a/crates/router/src/events/api_logs.rs b/crates/router/src/events/api_logs.rs index 3f598e88394..bfc10f722c1 100644 --- a/crates/router/src/events/api_logs.rs +++ b/crates/router/src/events/api_logs.rs @@ -24,6 +24,7 @@ use crate::{ #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub struct ApiEvent { + merchant_id: Option<String>, api_flow: String, created_at_timestamp: i128, request_id: String, @@ -40,11 +41,13 @@ pub struct ApiEvent { #[serde(flatten)] event_type: ApiEventsType, hs_latency: Option<u128>, + http_method: Option<String>, } impl ApiEvent { #[allow(clippy::too_many_arguments)] pub fn new( + merchant_id: Option<String>, api_flow: &impl FlowMetric, request_id: &RequestId, latency: u128, @@ -56,8 +59,10 @@ impl ApiEvent { error: Option<serde_json::Value>, event_type: ApiEventsType, http_req: &HttpRequest, + http_method: Option<String>, ) -> Self { Self { + merchant_id, api_flow: api_flow.to_string(), created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000, request_id: request_id.as_hyphenated().to_string(), @@ -78,6 +83,7 @@ impl ApiEvent { url_path: http_req.path().to_string(), event_type, hs_latency, + http_method, } } } diff --git a/crates/router/src/events/event_logger.rs b/crates/router/src/events/event_logger.rs index fda9b1a036a..1bd75341be4 100644 --- a/crates/router/src/events/event_logger.rs +++ b/crates/router/src/events/event_logger.rs @@ -7,6 +7,6 @@ pub struct EventLogger {} impl EventHandler for EventLogger { #[track_caller] fn log_event(&self, event: RawEvent) { - logger::info!(event = ?serde_json::to_string(&event.payload).unwrap_or(r#"{ "error": "Serialization failed" }"#.to_string()), event_type =? event.event_type, event_id =? event.key, log_type = "event"); + logger::info!(event = ?event.payload.to_string(), event_type =? event.event_type, event_id =? event.key, log_type = "event"); } } diff --git a/crates/router/src/events/kafka_handler.rs b/crates/router/src/events/kafka_handler.rs new file mode 100644 index 00000000000..d55847e6e8e --- /dev/null +++ b/crates/router/src/events/kafka_handler.rs @@ -0,0 +1,29 @@ +use error_stack::{IntoReport, ResultExt}; +use router_env::tracing; + +use super::{EventHandler, RawEvent}; +use crate::{ + db::MQResult, + services::kafka::{KafkaError, KafkaMessage, KafkaProducer}, +}; +impl EventHandler for KafkaProducer { + fn log_event(&self, event: RawEvent) { + let topic = self.get_topic(event.event_type); + if let Err(er) = self.log_kafka_event(topic, &event) { + tracing::error!("Failed to log event to kafka: {:?}", er); + } + } +} + +impl KafkaMessage for RawEvent { + fn key(&self) -> String { + self.key.clone() + } + + fn value(&self) -> MQResult<Vec<u8>> { + // Add better error logging here + serde_json::to_vec(&self.payload) + .into_report() + .change_context(KafkaError::GenericError) + } +} diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 2b1f9c692d8..035314f71df 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -1,8 +1,6 @@ #![forbid(unsafe_code)] #![recursion_limit = "256"] -#[cfg(feature = "olap")] -pub mod analytics; #[cfg(feature = "stripe")] pub mod compatibility; pub mod configs; @@ -17,6 +15,8 @@ pub(crate) mod macros; pub mod routes; pub mod workflows; +#[cfg(feature = "olap")] +pub mod analytics; pub mod events; pub mod middleware; pub mod openapi; @@ -35,10 +35,7 @@ use storage_impl::errors::ApplicationResult; use tokio::sync::{mpsc, oneshot}; pub use self::env::logger; -use crate::{ - configs::settings, - core::errors::{self}, -}; +use crate::{configs::settings, core::errors}; #[cfg(feature = "mimalloc")] #[global_allocator] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 1a6f36363d1..80993429c4e 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -33,7 +33,7 @@ use super::{ephemeral_key::*, payment_methods::*, webhooks::*}; pub use crate::{ configs::settings, db::{StorageImpl, StorageInterface}, - events::{event_logger::EventLogger, EventHandler}, + events::EventsHandler, routes::cards_info::card_iin_info, services::get_store, }; @@ -43,7 +43,7 @@ pub struct AppState { pub flow_name: String, pub store: Box<dyn StorageInterface>, pub conf: Arc<settings::Settings>, - pub event_handler: Box<dyn EventHandler>, + pub event_handler: EventsHandler, #[cfg(feature = "email")] pub email_client: Arc<dyn EmailService>, #[cfg(feature = "kms")] @@ -62,7 +62,7 @@ impl scheduler::SchedulerAppState for AppState { pub trait AppStateInfo { fn conf(&self) -> settings::Settings; fn store(&self) -> Box<dyn StorageInterface>; - fn event_handler(&self) -> Box<dyn EventHandler>; + fn event_handler(&self) -> EventsHandler; #[cfg(feature = "email")] fn email_client(&self) -> Arc<dyn EmailService>; fn add_request_id(&mut self, request_id: RequestId); @@ -82,8 +82,8 @@ impl AppStateInfo for AppState { fn email_client(&self) -> Arc<dyn EmailService> { self.email_client.to_owned() } - fn event_handler(&self) -> Box<dyn EventHandler> { - self.event_handler.to_owned() + fn event_handler(&self) -> EventsHandler { + self.event_handler.clone() } fn add_request_id(&mut self, request_id: RequestId) { self.api_client.add_request_id(request_id); @@ -130,13 +130,31 @@ impl AppState { #[cfg(feature = "kms")] let kms_client = kms::get_kms_client(&conf.kms).await; let testable = storage_impl == StorageImpl::PostgresqlTest; + #[allow(clippy::expect_used)] + let event_handler = conf + .events + .get_event_handler() + .await + .expect("Failed to create event handler"); let store: Box<dyn StorageInterface> = match storage_impl { - StorageImpl::Postgresql | StorageImpl::PostgresqlTest => Box::new( - #[allow(clippy::expect_used)] - get_store(&conf, shut_down_signal, testable) - .await - .expect("Failed to create store"), - ), + StorageImpl::Postgresql | StorageImpl::PostgresqlTest => match &event_handler { + EventsHandler::Kafka(kafka_client) => Box::new( + crate::db::KafkaStore::new( + #[allow(clippy::expect_used)] + get_store(&conf.clone(), shut_down_signal, testable) + .await + .expect("Failed to create store"), + kafka_client.clone(), + ) + .await, + ), + EventsHandler::Logs(_) => Box::new( + #[allow(clippy::expect_used)] + get_store(&conf, shut_down_signal, testable) + .await + .expect("Failed to create store"), + ), + }, #[allow(clippy::expect_used)] StorageImpl::Mock => Box::new( MockDb::new(&conf.redis) @@ -146,12 +164,7 @@ impl AppState { }; #[cfg(feature = "olap")] - let pool = crate::analytics::AnalyticsProvider::from_conf( - &conf.analytics, - #[cfg(feature = "kms")] - kms_client, - ) - .await; + let pool = crate::analytics::AnalyticsProvider::from_conf(&conf.analytics).await; #[cfg(feature = "kms")] #[allow(clippy::expect_used)] @@ -174,7 +187,7 @@ impl AppState { #[cfg(feature = "kms")] kms_secrets: Arc::new(kms_secrets), api_client, - event_handler: Box::<EventLogger>::default(), + event_handler, #[cfg(feature = "olap")] pool, } diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index faea707f2a1..e46612b95df 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -4,6 +4,7 @@ pub mod authorization; pub mod encryption; #[cfg(feature = "olap")] pub mod jwt; +pub mod kafka; pub mod logger; #[cfg(feature = "email")] diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 5481d5c5cf9..1ff46474db5 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -873,6 +873,7 @@ where }; let api_event = ApiEvent::new( + Some(merchant_id.clone()), flow, &request_id, request_duration, @@ -884,6 +885,7 @@ where error, event_type.unwrap_or(ApiEventsType::Miscellaneous), request, + Some(request.method().to_string()), ); match api_event.clone().try_into() { Ok(event) => { diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs new file mode 100644 index 00000000000..497ac16721b --- /dev/null +++ b/crates/router/src/services/kafka.rs @@ -0,0 +1,314 @@ +use std::sync::Arc; + +use common_utils::errors::CustomResult; +use error_stack::{report, IntoReport, ResultExt}; +use rdkafka::{ + config::FromClientConfig, + producer::{BaseRecord, DefaultProducerContext, Producer, ThreadedProducer}, +}; + +use crate::events::EventType; +mod api_event; +pub mod outgoing_request; +mod payment_attempt; +mod payment_intent; +mod refund; +pub use api_event::{ApiCallEventType, ApiEvents, ApiEventsType}; +use data_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent}; +use diesel_models::refund::Refund; +use serde::Serialize; +use time::OffsetDateTime; + +use self::{ + payment_attempt::KafkaPaymentAttempt, payment_intent::KafkaPaymentIntent, refund::KafkaRefund, +}; +// Using message queue result here to avoid confusion with Kafka result provided by library +pub type MQResult<T> = CustomResult<T, KafkaError>; + +pub trait KafkaMessage +where + Self: Serialize, +{ + fn value(&self) -> MQResult<Vec<u8>> { + // Add better error logging here + serde_json::to_vec(&self) + .into_report() + .change_context(KafkaError::GenericError) + } + + fn key(&self) -> String; + + fn creation_timestamp(&self) -> Option<i64> { + None + } +} + +#[derive(serde::Serialize, Debug)] +struct KafkaEvent<'a, T: KafkaMessage> { + #[serde(flatten)] + event: &'a T, + sign_flag: i32, +} + +impl<'a, T: KafkaMessage> KafkaEvent<'a, T> { + fn new(event: &'a T) -> Self { + Self { + event, + sign_flag: 1, + } + } + fn old(event: &'a T) -> Self { + Self { + event, + sign_flag: -1, + } + } +} + +impl<'a, T: KafkaMessage> KafkaMessage for KafkaEvent<'a, T> { + fn key(&self) -> String { + self.event.key() + } + + fn creation_timestamp(&self) -> Option<i64> { + self.event.creation_timestamp() + } +} + +#[derive(Debug, serde::Deserialize, Clone, Default)] +#[serde(default)] +pub struct KafkaSettings { + brokers: Vec<String>, + intent_analytics_topic: String, + attempt_analytics_topic: String, + refund_analytics_topic: String, + api_logs_topic: String, +} + +impl KafkaSettings { + pub fn validate(&self) -> Result<(), crate::core::errors::ApplicationError> { + use common_utils::ext_traits::ConfigExt; + + use crate::core::errors::ApplicationError; + + common_utils::fp_utils::when(self.brokers.is_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "Kafka brokers must not be empty".into(), + )) + })?; + + common_utils::fp_utils::when(self.intent_analytics_topic.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "Kafka Intent Analytics topic must not be empty".into(), + )) + })?; + + common_utils::fp_utils::when(self.attempt_analytics_topic.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "Kafka Attempt Analytics topic must not be empty".into(), + )) + })?; + + common_utils::fp_utils::when(self.refund_analytics_topic.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "Kafka Refund Analytics topic must not be empty".into(), + )) + })?; + + common_utils::fp_utils::when(self.api_logs_topic.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "Kafka API event Analytics topic must not be empty".into(), + )) + }) + } +} + +#[derive(Clone, Debug)] +pub struct KafkaProducer { + producer: Arc<RdKafkaProducer>, + intent_analytics_topic: String, + attempt_analytics_topic: String, + refund_analytics_topic: String, + api_logs_topic: String, +} + +struct RdKafkaProducer(ThreadedProducer<DefaultProducerContext>); + +impl std::fmt::Debug for RdKafkaProducer { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("RdKafkaProducer") + } +} + +#[derive(Debug, Clone, thiserror::Error)] +pub enum KafkaError { + #[error("Generic Kafka Error")] + GenericError, + #[error("Kafka not implemented")] + NotImplemented, + #[error("Kafka Initialization Error")] + InitializationError, +} + +#[allow(unused)] +impl KafkaProducer { + pub async fn create(conf: &KafkaSettings) -> MQResult<Self> { + Ok(Self { + producer: Arc::new(RdKafkaProducer( + ThreadedProducer::from_config( + rdkafka::ClientConfig::new().set("bootstrap.servers", conf.brokers.join(",")), + ) + .into_report() + .change_context(KafkaError::InitializationError)?, + )), + + intent_analytics_topic: conf.intent_analytics_topic.clone(), + attempt_analytics_topic: conf.attempt_analytics_topic.clone(), + refund_analytics_topic: conf.refund_analytics_topic.clone(), + api_logs_topic: conf.api_logs_topic.clone(), + }) + } + + pub fn log_kafka_event<T: KafkaMessage + std::fmt::Debug>( + &self, + topic: &str, + event: &T, + ) -> MQResult<()> { + router_env::logger::debug!("Logging Kafka Event {event:?}"); + self.producer + .0 + .send( + BaseRecord::to(topic) + .key(&event.key()) + .payload(&event.value()?) + .timestamp( + event + .creation_timestamp() + .unwrap_or_else(|| OffsetDateTime::now_utc().unix_timestamp()), + ), + ) + .map_err(|(error, record)| report!(error).attach_printable(format!("{record:?}"))) + .change_context(KafkaError::GenericError) + } + + pub async fn log_payment_attempt( + &self, + attempt: &PaymentAttempt, + old_attempt: Option<PaymentAttempt>, + ) -> MQResult<()> { + if let Some(negative_event) = old_attempt { + self.log_kafka_event( + &self.attempt_analytics_topic, + &KafkaEvent::old(&KafkaPaymentAttempt::from_storage(&negative_event)), + ) + .attach_printable_lazy(|| { + format!("Failed to add negative attempt event {negative_event:?}") + })?; + }; + self.log_kafka_event( + &self.attempt_analytics_topic, + &KafkaEvent::new(&KafkaPaymentAttempt::from_storage(attempt)), + ) + .attach_printable_lazy(|| format!("Failed to add positive attempt event {attempt:?}")) + } + + pub async fn log_payment_attempt_delete( + &self, + delete_old_attempt: &PaymentAttempt, + ) -> MQResult<()> { + self.log_kafka_event( + &self.attempt_analytics_topic, + &KafkaEvent::old(&KafkaPaymentAttempt::from_storage(delete_old_attempt)), + ) + .attach_printable_lazy(|| { + format!("Failed to add negative attempt event {delete_old_attempt:?}") + }) + } + + pub async fn log_payment_intent( + &self, + intent: &PaymentIntent, + old_intent: Option<PaymentIntent>, + ) -> MQResult<()> { + if let Some(negative_event) = old_intent { + self.log_kafka_event( + &self.intent_analytics_topic, + &KafkaEvent::old(&KafkaPaymentIntent::from_storage(&negative_event)), + ) + .attach_printable_lazy(|| { + format!("Failed to add negative intent event {negative_event:?}") + })?; + }; + self.log_kafka_event( + &self.intent_analytics_topic, + &KafkaEvent::new(&KafkaPaymentIntent::from_storage(intent)), + ) + .attach_printable_lazy(|| format!("Failed to add positive intent event {intent:?}")) + } + + pub async fn log_payment_intent_delete( + &self, + delete_old_intent: &PaymentIntent, + ) -> MQResult<()> { + self.log_kafka_event( + &self.intent_analytics_topic, + &KafkaEvent::old(&KafkaPaymentIntent::from_storage(delete_old_intent)), + ) + .attach_printable_lazy(|| { + format!("Failed to add negative intent event {delete_old_intent:?}") + }) + } + + pub async fn log_refund(&self, refund: &Refund, old_refund: Option<Refund>) -> MQResult<()> { + if let Some(negative_event) = old_refund { + self.log_kafka_event( + &self.refund_analytics_topic, + &KafkaEvent::old(&KafkaRefund::from_storage(&negative_event)), + ) + .attach_printable_lazy(|| { + format!("Failed to add negative refund event {negative_event:?}") + })?; + }; + self.log_kafka_event( + &self.refund_analytics_topic, + &KafkaEvent::new(&KafkaRefund::from_storage(refund)), + ) + .attach_printable_lazy(|| format!("Failed to add positive refund event {refund:?}")) + } + + pub async fn log_refund_delete(&self, delete_old_refund: &Refund) -> MQResult<()> { + self.log_kafka_event( + &self.refund_analytics_topic, + &KafkaEvent::old(&KafkaRefund::from_storage(delete_old_refund)), + ) + .attach_printable_lazy(|| { + format!("Failed to add negative refund event {delete_old_refund:?}") + }) + } + + pub async fn log_api_event(&self, event: &ApiEvents) -> MQResult<()> { + self.log_kafka_event(&self.api_logs_topic, event) + .attach_printable_lazy(|| format!("Failed to add api log event {event:?}")) + } + + pub fn get_topic(&self, event: EventType) -> &str { + match event { + EventType::ApiLogs => &self.api_logs_topic, + EventType::PaymentAttempt => &self.attempt_analytics_topic, + EventType::PaymentIntent => &self.intent_analytics_topic, + EventType::Refund => &self.refund_analytics_topic, + } + } +} + +impl Drop for RdKafkaProducer { + fn drop(&mut self) { + // Flush the producer to send any pending messages + match self.0.flush(rdkafka::util::Timeout::After( + std::time::Duration::from_secs(5), + )) { + Ok(_) => router_env::logger::info!("Kafka events flush Successful"), + Err(error) => router_env::logger::error!("Failed to flush Kafka Events {error:?}"), + } + } +} diff --git a/crates/router/src/services/kafka/api_event.rs b/crates/router/src/services/kafka/api_event.rs new file mode 100644 index 00000000000..7de27191592 --- /dev/null +++ b/crates/router/src/services/kafka/api_event.rs @@ -0,0 +1,108 @@ +use api_models::enums as api_enums; +use serde::{Deserialize, Serialize}; +use time::OffsetDateTime; + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(tag = "flow_type")] +pub enum ApiEventsType { + Payment { + payment_id: String, + }, + Refund { + payment_id: String, + refund_id: String, + }, + Default, + PaymentMethod { + payment_method_id: String, + payment_method: Option<api_enums::PaymentMethod>, + payment_method_type: Option<api_enums::PaymentMethodType>, + }, + Customer { + customer_id: String, + }, + User { + //specified merchant_id will overridden on global defined + merchant_id: String, + user_id: String, + }, + Webhooks { + connector: String, + payment_id: Option<String>, + }, + OutgoingEvent, +} + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub struct ApiEvents { + pub api_name: String, + pub request_id: Option<String>, + //It is require to solve ambiquity in case of event_type is User + #[serde(skip_serializing_if = "Option::is_none")] + pub merchant_id: Option<String>, + pub request: String, + pub response: String, + pub status_code: u16, + #[serde(with = "time::serde::timestamp")] + pub created_at: OffsetDateTime, + pub latency: u128, + //conflicting fields underlying enums will be used + #[serde(flatten)] + pub event_type: ApiEventsType, + pub user_agent: Option<String>, + pub ip_addr: Option<String>, + pub url_path: Option<String>, + pub api_event_type: Option<ApiCallEventType>, +} + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub enum ApiCallEventType { + IncomingApiEvent, + OutgoingApiEvent, +} + +impl super::KafkaMessage for ApiEvents { + fn key(&self) -> String { + match &self.event_type { + ApiEventsType::Payment { payment_id } => format!( + "{}_{}", + self.merchant_id + .as_ref() + .unwrap_or(&"default_merchant_id".to_string()), + payment_id + ), + ApiEventsType::Refund { + payment_id, + refund_id, + } => format!("{payment_id}_{refund_id}"), + ApiEventsType::Default => "key".to_string(), + ApiEventsType::PaymentMethod { + payment_method_id, + payment_method, + payment_method_type, + } => format!( + "{:?}_{:?}_{:?}", + payment_method_id.clone(), + payment_method.clone(), + payment_method_type.clone(), + ), + ApiEventsType::Customer { customer_id } => customer_id.to_string(), + ApiEventsType::User { + merchant_id, + user_id, + } => format!("{}_{}", merchant_id, user_id), + ApiEventsType::Webhooks { + connector, + payment_id, + } => format!( + "webhook_{}_{connector}", + payment_id.clone().unwrap_or_default() + ), + ApiEventsType::OutgoingEvent => "outgoing_event".to_string(), + } + } + + fn creation_timestamp(&self) -> Option<i64> { + Some(self.created_at.unix_timestamp()) + } +} diff --git a/crates/router/src/services/kafka/outgoing_request.rs b/crates/router/src/services/kafka/outgoing_request.rs new file mode 100644 index 00000000000..bb09fe91fe6 --- /dev/null +++ b/crates/router/src/services/kafka/outgoing_request.rs @@ -0,0 +1,19 @@ +use reqwest::Url; + +pub struct OutgoingRequest { + pub url: Url, + pub latency: u128, +} + +// impl super::KafkaMessage for OutgoingRequest { +// fn key(&self) -> String { +// format!( +// "{}_{}", + +// ) +// } + +// fn creation_timestamp(&self) -> Option<i64> { +// Some(self.created_at.unix_timestamp()) +// } +// } diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs new file mode 100644 index 00000000000..ea0721f418e --- /dev/null +++ b/crates/router/src/services/kafka/payment_attempt.rs @@ -0,0 +1,92 @@ +use data_models::payments::payment_attempt::PaymentAttempt; +use diesel_models::enums as storage_enums; +use time::OffsetDateTime; + +#[derive(serde::Serialize, Debug)] +pub struct KafkaPaymentAttempt<'a> { + pub payment_id: &'a String, + pub merchant_id: &'a String, + pub attempt_id: &'a String, + pub status: storage_enums::AttemptStatus, + pub amount: i64, + pub currency: Option<storage_enums::Currency>, + pub save_to_locker: Option<bool>, + pub connector: Option<&'a String>, + pub error_message: Option<&'a String>, + pub offer_amount: Option<i64>, + pub surcharge_amount: Option<i64>, + pub tax_amount: Option<i64>, + pub payment_method_id: Option<&'a String>, + pub payment_method: Option<storage_enums::PaymentMethod>, + pub connector_transaction_id: Option<&'a String>, + pub capture_method: Option<storage_enums::CaptureMethod>, + #[serde(default, with = "time::serde::timestamp::option")] + pub capture_on: Option<OffsetDateTime>, + pub confirm: bool, + pub authentication_type: Option<storage_enums::AuthenticationType>, + #[serde(with = "time::serde::timestamp")] + pub created_at: OffsetDateTime, + #[serde(with = "time::serde::timestamp")] + pub modified_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp::option")] + pub last_synced: Option<OffsetDateTime>, + pub cancellation_reason: Option<&'a String>, + pub amount_to_capture: Option<i64>, + pub mandate_id: Option<&'a String>, + pub browser_info: Option<String>, + pub error_code: Option<&'a String>, + pub connector_metadata: Option<String>, + // TODO: These types should implement copy ideally + pub payment_experience: Option<&'a storage_enums::PaymentExperience>, + pub payment_method_type: Option<&'a storage_enums::PaymentMethodType>, +} + +impl<'a> KafkaPaymentAttempt<'a> { + pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { + Self { + payment_id: &attempt.payment_id, + merchant_id: &attempt.merchant_id, + attempt_id: &attempt.attempt_id, + status: attempt.status, + amount: attempt.amount, + currency: attempt.currency, + save_to_locker: attempt.save_to_locker, + connector: attempt.connector.as_ref(), + error_message: attempt.error_message.as_ref(), + offer_amount: attempt.offer_amount, + surcharge_amount: attempt.surcharge_amount, + tax_amount: attempt.tax_amount, + payment_method_id: attempt.payment_method_id.as_ref(), + payment_method: attempt.payment_method, + connector_transaction_id: attempt.connector_transaction_id.as_ref(), + capture_method: attempt.capture_method, + capture_on: attempt.capture_on.map(|i| i.assume_utc()), + confirm: attempt.confirm, + authentication_type: attempt.authentication_type, + created_at: attempt.created_at.assume_utc(), + modified_at: attempt.modified_at.assume_utc(), + last_synced: attempt.last_synced.map(|i| i.assume_utc()), + cancellation_reason: attempt.cancellation_reason.as_ref(), + amount_to_capture: attempt.amount_to_capture, + mandate_id: attempt.mandate_id.as_ref(), + browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()), + error_code: attempt.error_code.as_ref(), + connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()), + payment_experience: attempt.payment_experience.as_ref(), + payment_method_type: attempt.payment_method_type.as_ref(), + } + } +} + +impl<'a> super::KafkaMessage for KafkaPaymentAttempt<'a> { + fn key(&self) -> String { + format!( + "{}_{}_{}", + self.merchant_id, self.payment_id, self.attempt_id + ) + } + + fn creation_timestamp(&self) -> Option<i64> { + Some(self.modified_at.unix_timestamp()) + } +} diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs new file mode 100644 index 00000000000..70980a6e865 --- /dev/null +++ b/crates/router/src/services/kafka/payment_intent.rs @@ -0,0 +1,71 @@ +use data_models::payments::PaymentIntent; +use diesel_models::enums as storage_enums; +use time::OffsetDateTime; + +#[derive(serde::Serialize, Debug)] +pub struct KafkaPaymentIntent<'a> { + pub payment_id: &'a String, + pub merchant_id: &'a String, + pub status: storage_enums::IntentStatus, + pub amount: i64, + pub currency: Option<storage_enums::Currency>, + pub amount_captured: Option<i64>, + pub customer_id: Option<&'a String>, + pub description: Option<&'a String>, + pub return_url: Option<&'a String>, + pub connector_id: Option<&'a String>, + pub statement_descriptor_name: Option<&'a String>, + pub statement_descriptor_suffix: Option<&'a String>, + #[serde(with = "time::serde::timestamp")] + pub created_at: OffsetDateTime, + #[serde(with = "time::serde::timestamp")] + pub modified_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp::option")] + pub last_synced: Option<OffsetDateTime>, + pub setup_future_usage: Option<storage_enums::FutureUsage>, + pub off_session: Option<bool>, + pub client_secret: Option<&'a String>, + pub active_attempt_id: String, + pub business_country: Option<storage_enums::CountryAlpha2>, + pub business_label: Option<&'a String>, + pub attempt_count: i16, +} + +impl<'a> KafkaPaymentIntent<'a> { + pub fn from_storage(intent: &'a PaymentIntent) -> Self { + Self { + payment_id: &intent.payment_id, + merchant_id: &intent.merchant_id, + status: intent.status, + amount: intent.amount, + currency: intent.currency, + amount_captured: intent.amount_captured, + customer_id: intent.customer_id.as_ref(), + description: intent.description.as_ref(), + return_url: intent.return_url.as_ref(), + connector_id: intent.connector_id.as_ref(), + statement_descriptor_name: intent.statement_descriptor_name.as_ref(), + statement_descriptor_suffix: intent.statement_descriptor_suffix.as_ref(), + created_at: intent.created_at.assume_utc(), + modified_at: intent.modified_at.assume_utc(), + last_synced: intent.last_synced.map(|i| i.assume_utc()), + setup_future_usage: intent.setup_future_usage, + off_session: intent.off_session, + client_secret: intent.client_secret.as_ref(), + active_attempt_id: intent.active_attempt.get_id(), + business_country: intent.business_country, + business_label: intent.business_label.as_ref(), + attempt_count: intent.attempt_count, + } + } +} + +impl<'a> super::KafkaMessage for KafkaPaymentIntent<'a> { + fn key(&self) -> String { + format!("{}_{}", self.merchant_id, self.payment_id) + } + + fn creation_timestamp(&self) -> Option<i64> { + Some(self.modified_at.unix_timestamp()) + } +} diff --git a/crates/router/src/services/kafka/refund.rs b/crates/router/src/services/kafka/refund.rs new file mode 100644 index 00000000000..0cc4865e751 --- /dev/null +++ b/crates/router/src/services/kafka/refund.rs @@ -0,0 +1,68 @@ +use diesel_models::{enums as storage_enums, refund::Refund}; +use time::OffsetDateTime; + +#[derive(serde::Serialize, Debug)] +pub struct KafkaRefund<'a> { + pub internal_reference_id: &'a String, + pub refund_id: &'a String, //merchant_reference id + pub payment_id: &'a String, + pub merchant_id: &'a String, + pub connector_transaction_id: &'a String, + pub connector: &'a String, + pub connector_refund_id: Option<&'a String>, + pub external_reference_id: Option<&'a String>, + pub refund_type: &'a storage_enums::RefundType, + pub total_amount: &'a i64, + pub currency: &'a storage_enums::Currency, + pub refund_amount: &'a i64, + pub refund_status: &'a storage_enums::RefundStatus, + pub sent_to_gateway: &'a bool, + pub refund_error_message: Option<&'a String>, + pub refund_arn: Option<&'a String>, + #[serde(default, with = "time::serde::timestamp")] + pub created_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp")] + pub modified_at: OffsetDateTime, + pub description: Option<&'a String>, + pub attempt_id: &'a String, + pub refund_reason: Option<&'a String>, + pub refund_error_code: Option<&'a String>, +} + +impl<'a> KafkaRefund<'a> { + pub fn from_storage(refund: &'a Refund) -> Self { + Self { + internal_reference_id: &refund.internal_reference_id, + refund_id: &refund.refund_id, + payment_id: &refund.payment_id, + merchant_id: &refund.merchant_id, + connector_transaction_id: &refund.connector_transaction_id, + connector: &refund.connector, + connector_refund_id: refund.connector_refund_id.as_ref(), + external_reference_id: refund.external_reference_id.as_ref(), + refund_type: &refund.refund_type, + total_amount: &refund.total_amount, + currency: &refund.currency, + refund_amount: &refund.refund_amount, + refund_status: &refund.refund_status, + sent_to_gateway: &refund.sent_to_gateway, + refund_error_message: refund.refund_error_message.as_ref(), + refund_arn: refund.refund_arn.as_ref(), + created_at: refund.created_at.assume_utc(), + modified_at: refund.updated_at.assume_utc(), + description: refund.description.as_ref(), + attempt_id: &refund.attempt_id, + refund_reason: refund.refund_reason.as_ref(), + refund_error_code: refund.refund_error_code.as_ref(), + } + } +} + +impl<'a> super::KafkaMessage for KafkaRefund<'a> { + fn key(&self) -> String { + format!( + "{}_{}_{}_{}", + self.merchant_id, self.payment_id, self.attempt_id, self.refund_id + ) + } +} diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs index f94d06997ca..13b9f3dd5d5 100644 --- a/crates/router/src/types/storage/payment_attempt.rs +++ b/crates/router/src/types/storage/payment_attempt.rs @@ -7,7 +7,6 @@ use error_stack::ResultExt; use crate::{ core::errors, errors::RouterResult, types::transformers::ForeignFrom, utils::OptionExt, }; - pub trait PaymentAttemptExt { fn make_new_capture( &self, @@ -134,9 +133,7 @@ mod tests { use crate::configs::settings::Settings; let conf = Settings::new().expect("invalid settings"); let tx: oneshot::Sender<()> = oneshot::channel().0; - let api_client = Box::new(services::MockApiClient); - let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest, tx, api_client).await; @@ -187,7 +184,6 @@ mod tests { let tx: oneshot::Sender<()> = oneshot::channel().0; let api_client = Box::new(services::MockApiClient); - let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest, tx, api_client).await; let current_time = common_utils::date_time::now(); diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index c9ee3a34f2e..e12e27708f8 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -160,6 +160,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { async fn payments_create_success() { let conf = Settings::new().unwrap(); let tx: oneshot::Sender<()> = oneshot::channel().0; + let state = routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, @@ -204,6 +205,7 @@ async fn payments_create_failure() { let conf = Settings::new().unwrap(); static CV: aci::Aci = aci::Aci; let tx: oneshot::Sender<()> = oneshot::channel().0; + let state = routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, @@ -265,6 +267,7 @@ async fn refund_for_successful_payments() { merchant_connector_id: None, }; let tx: oneshot::Sender<()> = oneshot::channel().0; + let state = routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, @@ -333,6 +336,7 @@ async fn refunds_create_failure() { merchant_connector_id: None, }; let tx: oneshot::Sender<()> = oneshot::channel().0; + let state = routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 67a0625968f..f325370e737 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -96,6 +96,7 @@ pub trait ConnectorActions: Connector { payment_info, ); let tx: oneshot::Sender<()> = oneshot::channel().0; + let state = routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, @@ -120,6 +121,7 @@ pub trait ConnectorActions: Connector { payment_info, ); let tx: oneshot::Sender<()> = oneshot::channel().0; + let state = routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, @@ -148,6 +150,7 @@ pub trait ConnectorActions: Connector { payment_info, ); let tx: oneshot::Sender<()> = oneshot::channel().0; + let state = routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, @@ -561,6 +564,7 @@ pub trait ConnectorActions: Connector { .get_connector_integration(); let mut request = self.get_payout_request(None, payout_type, payment_info); let tx: oneshot::Sender<()> = oneshot::channel().0; + let state = routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, @@ -601,6 +605,7 @@ pub trait ConnectorActions: Connector { .get_connector_integration(); let mut request = self.get_payout_request(connector_payout_id, payout_type, payment_info); let tx: oneshot::Sender<()> = oneshot::channel().0; + let state = routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, @@ -642,6 +647,7 @@ pub trait ConnectorActions: Connector { let mut request = self.get_payout_request(None, payout_type, payment_info); request.connector_customer = connector_customer; let tx: oneshot::Sender<()> = oneshot::channel().0; + let state = routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, @@ -683,6 +689,7 @@ pub trait ConnectorActions: Connector { let mut request = self.get_payout_request(Some(connector_payout_id), payout_type, payment_info); let tx: oneshot::Sender<()> = oneshot::channel().0; + let state = routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, @@ -770,6 +777,7 @@ pub trait ConnectorActions: Connector { .get_connector_integration(); let mut request = self.get_payout_request(None, payout_type, payment_info); let tx = oneshot::channel().0; + let state = routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, @@ -802,6 +810,7 @@ async fn call_connector< ) -> Result<RouterData<T, Req, Resp>, Report<ConnectorError>> { let conf = Settings::new().unwrap(); let tx: oneshot::Sender<()> = oneshot::channel().0; + let state = routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index 5d4ca844061..42e5524a15d 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -217,6 +217,7 @@ async fn payments_create_core_adyen_no_redirect() { use router::configs::settings::Settings; let conf = Settings::new().expect("invalid settings"); let tx: oneshot::Sender<()> = oneshot::channel().0; + let state = routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, diff --git a/crates/router/tests/utils.rs b/crates/router/tests/utils.rs index 6cddbc04366..339eca6fa0f 100644 --- a/crates/router/tests/utils.rs +++ b/crates/router/tests/utils.rs @@ -48,6 +48,7 @@ pub async fn mk_service( conf.connectors.stripe.base_url = url; } let tx: oneshot::Sender<()> = oneshot::channel().0; + let app_state = AppState::with_storage( conf, router::db::StorageImpl::Mock, diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs index e75606aa153..3c7ba8b93df 100644 --- a/crates/router_env/src/lib.rs +++ b/crates/router_env/src/lib.rs @@ -39,10 +39,19 @@ use crate::types::FlowMetric; #[derive(Debug, Display, Clone, PartialEq, Eq)] pub enum AnalyticsFlow { GetInfo, + GetPaymentMetrics, + GetRefundsMetrics, + GetSdkMetrics, GetPaymentFilters, GetRefundFilters, - GetRefundsMetrics, - GetPaymentMetrics, + GetSdkEventFilters, + GetApiEvents, + GetSdkEvents, + GeneratePaymentReport, + GenerateDisputeReport, + GenerateRefundReport, + GetApiEventMetrics, + GetApiEventFilters, } impl FlowMetric for AnalyticsFlow {} diff --git a/crates/scheduler/Cargo.toml b/crates/scheduler/Cargo.toml index e0b68c709e8..5e8674ab381 100644 --- a/crates/scheduler/Cargo.toml +++ b/crates/scheduler/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" [features] default = ["kv_store", "olap"] -olap = [] +olap = ["storage_impl/olap"] kv_store = [] [dependencies] diff --git a/crates/storage_impl/src/config.rs b/crates/storage_impl/src/config.rs index f53507831b1..fd95a6d315d 100644 --- a/crates/storage_impl/src/config.rs +++ b/crates/storage_impl/src/config.rs @@ -1,6 +1,6 @@ use masking::Secret; -#[derive(Debug, Clone)] +#[derive(Debug, Clone, serde::Deserialize)] pub struct Database { pub username: String, pub password: Secret<String>, @@ -9,7 +9,41 @@ pub struct Database { pub dbname: String, pub pool_size: u32, pub connection_timeout: u64, - pub queue_strategy: bb8::QueueStrategy, + pub queue_strategy: QueueStrategy, pub min_idle: Option<u32>, pub max_lifetime: Option<u64>, } + +#[derive(Debug, serde::Deserialize, Clone, Copy, Default)] +#[serde(rename_all = "PascalCase")] +pub enum QueueStrategy { + #[default] + Fifo, + Lifo, +} + +impl From<QueueStrategy> for bb8::QueueStrategy { + fn from(value: QueueStrategy) -> Self { + match value { + QueueStrategy::Fifo => Self::Fifo, + QueueStrategy::Lifo => Self::Lifo, + } + } +} + +impl Default for Database { + fn default() -> Self { + Self { + username: String::new(), + password: Secret::<String>::default(), + host: "localhost".into(), + port: 5432, + dbname: String::new(), + pool_size: 5, + connection_timeout: 10, + queue_strategy: QueueStrategy::default(), + min_idle: None, + max_lifetime: None, + } + } +} diff --git a/crates/storage_impl/src/database/store.rs b/crates/storage_impl/src/database/store.rs index c36575e37c9..75c34af14ac 100644 --- a/crates/storage_impl/src/database/store.rs +++ b/crates/storage_impl/src/database/store.rs @@ -89,7 +89,7 @@ pub async fn diesel_make_pg_pool( let mut pool = bb8::Pool::builder() .max_size(database.pool_size) .min_idle(database.min_idle) - .queue_strategy(database.queue_strategy) + .queue_strategy(database.queue_strategy.into()) .connection_timeout(std::time::Duration::from_secs(database.connection_timeout)) .max_lifetime(database.max_lifetime.map(std::time::Duration::from_secs)); diff --git a/docker-compose.yml b/docker-compose.yml index fd18906143f..f51a47aee94 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -273,3 +273,66 @@ services: - "8001:8001" volumes: - redisinsight_store:/db + + kafka0: + image: confluentinc/cp-kafka:7.0.5 + hostname: kafka0 + networks: + - router_net + ports: + - 9092:9092 + - 9093 + - 9997 + - 29092 + environment: + KAFKA_BROKER_ID: 1 + KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,CONTROLLER:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT + KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka0:29092,PLAINTEXT_HOST://localhost:9092 + KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT + KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 + KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0 + KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1 + KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1 + KAFKA_PROCESS_ROLES: 'broker,controller' + KAFKA_NODE_ID: 1 + KAFKA_CONTROLLER_QUORUM_VOTERS: '1@kafka0:29093' + KAFKA_LISTENERS: 'PLAINTEXT://kafka0:29092,CONTROLLER://kafka0:29093,PLAINTEXT_HOST://0.0.0.0:9092' + KAFKA_CONTROLLER_LISTENER_NAMES: 'CONTROLLER' + KAFKA_LOG_DIRS: '/tmp/kraft-combined-logs' + JMX_PORT: 9997 + KAFKA_JMX_OPTS: -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=kafka0 -Dcom.sun.management.jmxremote.rmi.port=9997 + profiles: + - analytics + volumes: + - ./monitoring/kafka-script.sh:/tmp/update_run.sh + command: "bash -c 'if [ ! -f /tmp/update_run.sh ]; then echo \"ERROR: Did you forget the update_run.sh file that came with this docker-compose.yml file?\" && exit 1 ; else /tmp/update_run.sh && /etc/confluent/docker/run ; fi'" + + # Kafka UI for debugging kafka queues + kafka-ui: + image: provectuslabs/kafka-ui:latest + ports: + - 8090:8080 + networks: + - router_net + depends_on: + - kafka0 + profiles: + - analytics + environment: + KAFKA_CLUSTERS_0_NAME: local + KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka0:29092 + KAFKA_CLUSTERS_0_JMXPORT: 9997 + + clickhouse-server: + image: clickhouse/clickhouse-server:23.5 + networks: + - router_net + ports: + - "9000" + - "8123:8123" + profiles: + - analytics + ulimits: + nofile: + soft: 262144 + hard: 262144 \ No newline at end of file
feat
Add Clickhouse based analytics (#2988)
a899c9738941fd1a34841369c9a13b2ac49dda9c
2023-06-27 15:52:27
BallaNitesh
refactor(mandates): refactor mandates to check for misleading error codes in mandates (#1377)
false
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index a9368b2a0ed..bd203170f3c 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -421,6 +421,8 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { errors::ApiErrorResponse::RefundFailed { data } => Self::RefundFailed, // Nothing at stripe to map errors::ApiErrorResponse::MandateUpdateFailed + | errors::ApiErrorResponse::MandateSerializationFailed + | errors::ApiErrorResponse::MandateDeserializationFailed | errors::ApiErrorResponse::InternalServerError => Self::InternalServerError, // not a stripe code errors::ApiErrorResponse::ExternalConnectorError { code, diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index e77f3ed690e..19d1561d981 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -154,6 +154,10 @@ pub enum ApiErrorResponse { MandateUpdateFailed, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "API Key does not exist in our records")] ApiKeyNotFound, + #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Invalid mandate id passed from connector")] + MandateSerializationFailed, + #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Unable to parse the mandate identifier passed from connector")] + MandateDeserializationFailed, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Return URL is not configured and not passed in payments request")] ReturnUrlUnavailable, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard")] @@ -369,7 +373,7 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::VerificationFailed { data } => { AER::BadRequest(ApiError::new("CE", 7, "Verification failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()}))) }, - Self::MandateUpdateFailed | Self::InternalServerError => { + Self::MandateUpdateFailed | Self::MandateSerializationFailed | Self::MandateDeserializationFailed | Self::InternalServerError => { AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None)) } Self::DuplicateRefundRequest => AER::BadRequest(ApiError::new("HE", 1, "Duplicate refund request. Refund already attempted with the refund ID", None)), diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index e7518e0e37b..f58da04eaab 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -144,7 +144,7 @@ where .store .find_mandate_by_merchant_id_mandate_id(resp.merchant_id.as_ref(), mandate_id) .await - .change_context(errors::ApiErrorResponse::MandateNotFound)?; + .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; let mandate = match mandate.mandate_type { storage_enums::MandateType::SingleUse => state .store @@ -197,7 +197,9 @@ where let mandate_ids = mandate_reference .map(|md| { Encode::<types::MandateReference>::encode_to_value(&md) - .change_context(errors::ApiErrorResponse::MandateNotFound) + .change_context( + errors::ApiErrorResponse::MandateSerializationFailed, + ) .map(masking::Secret::new) }) .transpose()?; @@ -224,7 +226,7 @@ where .parse_value::<api_models::payments::ConnectorMandateReferenceId>( "ConnectorMandateId", ) - .change_context(errors::ApiErrorResponse::MandateNotFound) + .change_context(errors::ApiErrorResponse::MandateDeserializationFailed) }) .transpose()? .map_or( diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index f595818823a..2ea7fa1e123 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -160,7 +160,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa let mandate = db .find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id) .await - .change_context(errors::ApiErrorResponse::MandateNotFound); + .to_not_found_response(errors::ApiErrorResponse::MandateNotFound); Some(mandate.and_then(|mandate_obj| { match ( mandate_obj.network_transaction_id, diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs index 22a96acf2b3..dfd9ba124b3 100644 --- a/crates/router/src/types/api/mandates.rs +++ b/crates/router/src/types/api/mandates.rs @@ -52,9 +52,7 @@ impl MandateResponseExt for MandateResponse { &payment_method.payment_method_id, merchant_account.locker_id.clone(), ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error getting card from card vault")?; + .await?; let card_detail = payment_methods::transformers::get_card_detail(&payment_method, card) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting card details")?;
refactor
refactor mandates to check for misleading error codes in mandates (#1377)
77fc92c99a99aaf76d270ba5b981928183a05768
2023-11-28 16:40:42
Sakil Mostak
feat(core): [Paypal] Add Preprocessing flow to CompleteAuthorize for Card 3DS Auth Verification (#2757)
false
diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs index 4e50bc924b3..9ab19b29557 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -30,6 +30,7 @@ use crate::{ types::{ self, api::{self, CompleteAuthorize, ConnectorCommon, ConnectorCommonExt, VerifyWebhookSource}, + storage::enums as storage_enums, transformers::ForeignFrom, ConnectorAuthType, ErrorResponse, Response, }, @@ -506,6 +507,161 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P } } +impl api::PaymentsPreProcessing for Paypal {} + +impl + ConnectorIntegration< + api::PreProcessing, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + > for Paypal +{ + fn get_headers( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_url( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let order_id = req + .request + .connector_transaction_id + .to_owned() + .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?; + Ok(format!( + "{}v2/checkout/orders/{}?fields=payment_source", + self.base_url(connectors), + order_id, + )) + } + + fn build_request( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::PaymentsPreProcessingType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsPreProcessingType::get_headers( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsPreProcessingRouterData, + res: Response, + ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { + let response: paypal::PaypalPreProcessingResponse = res + .response + .parse_struct("paypal PaypalPreProcessingResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + // permutation for status to continue payment + match ( + response + .payment_source + .card + .authentication_result + .three_d_secure + .enrollment_status + .as_ref(), + response + .payment_source + .card + .authentication_result + .three_d_secure + .authentication_status + .as_ref(), + response + .payment_source + .card + .authentication_result + .liability_shift + .clone(), + ) { + ( + Some(paypal::EnrollementStatus::Ready), + Some(paypal::AuthenticationStatus::Success), + paypal::LiabilityShift::Possible, + ) + | ( + Some(paypal::EnrollementStatus::Ready), + Some(paypal::AuthenticationStatus::Attempted), + paypal::LiabilityShift::Possible, + ) + | (Some(paypal::EnrollementStatus::NotReady), None, paypal::LiabilityShift::No) + | (Some(paypal::EnrollementStatus::Unavailable), None, paypal::LiabilityShift::No) + | (Some(paypal::EnrollementStatus::Bypassed), None, paypal::LiabilityShift::No) => { + Ok(types::PaymentsPreProcessingRouterData { + status: storage_enums::AttemptStatus::AuthenticationSuccessful, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + }), + ..data.clone() + }) + } + _ => Ok(types::PaymentsPreProcessingRouterData { + response: Err(ErrorResponse { + attempt_status: Some(enums::AttemptStatus::Failure), + code: consts::NO_ERROR_CODE.to_string(), + message: consts::NO_ERROR_MESSAGE.to_string(), + connector_transaction_id: None, + reason: Some(format!("{} Connector Responsded with LiabilityShift: {:?}, EnrollmentStatus: {:?}, and AuthenticationStatus: {:?}", + consts::CANNOT_CONTINUE_AUTH, + response + .payment_source + .card + .authentication_result + .liability_shift, + response + .payment_source + .card + .authentication_result + .three_d_secure + .enrollment_status + .unwrap_or(paypal::EnrollementStatus::Null), + response + .payment_source + .card + .authentication_result + .three_d_secure + .authentication_status + .unwrap_or(paypal::AuthenticationStatus::Null), + )), + status_code: res.status_code, + }), + ..data.clone() + }), + } + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + impl ConnectorIntegration< CompleteAuthorize, diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index e59ff09a1f6..04328cead23 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -925,6 +925,74 @@ pub struct PaypalThreeDsResponse { links: Vec<PaypalLinks>, } +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PaypalPreProcessingResponse { + pub payment_source: CardParams, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CardParams { + pub card: AuthResult, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AuthResult { + pub authentication_result: PaypalThreeDsParams, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PaypalThreeDsParams { + pub liability_shift: LiabilityShift, + pub three_d_secure: ThreeDsCheck, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ThreeDsCheck { + pub enrollment_status: Option<EnrollementStatus>, + pub authentication_status: Option<AuthenticationStatus>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum LiabilityShift { + Possible, + No, + Unknown, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum EnrollementStatus { + Null, + #[serde(rename = "Y")] + Ready, + #[serde(rename = "N")] + NotReady, + #[serde(rename = "U")] + Unavailable, + #[serde(rename = "B")] + Bypassed, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum AuthenticationStatus { + Null, + #[serde(rename = "Y")] + Success, + #[serde(rename = "N")] + Failed, + #[serde(rename = "R")] + Rejected, + #[serde(rename = "A")] + Attempted, + #[serde(rename = "U")] + Unable, + #[serde(rename = "C")] + ChallengeRequired, + #[serde(rename = "I")] + InfoOnly, + #[serde(rename = "D")] + Decoupled, +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaypalOrdersResponse { id: String, diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index c5490ee00e6..8937764409f 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -28,6 +28,8 @@ pub(crate) const NO_ERROR_MESSAGE: &str = "No error message"; pub(crate) const NO_ERROR_CODE: &str = "No error code"; pub(crate) const UNSUPPORTED_ERROR_MESSAGE: &str = "Unsupported response type"; pub(crate) const CONNECTOR_UNAUTHORIZED_ERROR: &str = "Authentication Error from the connector"; +pub(crate) const CANNOT_CONTINUE_AUTH: &str = + "Cannot continue with Authorization due to failed Liability Shift."; // General purpose base64 engines pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose = diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 1c40ef81f49..4fe7ea84800 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1418,7 +1418,21 @@ where (router_data, should_continue_payment) } } - _ => (router_data, should_continue_payment), + _ => { + // 3DS validation for paypal cards after verification (authorize call) + if connector.connector_name == router_types::Connector::Paypal + && payment_data.payment_attempt.payment_method + == Some(storage_enums::PaymentMethod::Card) + && matches!(format!("{operation:?}").as_str(), "CompleteAuthorize") + { + router_data = router_data.preprocessing_steps(state, connector).await?; + let is_error_in_response = router_data.response.is_err(); + // If is_error_in_response is true, should_continue_payment should be false, we should throw the error + (router_data, !is_error_in_response) + } else { + (router_data, should_continue_payment) + } + } }; Ok(router_data_and_should_continue_payment) diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 46eaca26f7c..d983cd19bdb 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -863,7 +863,6 @@ default_imp_for_pre_processing_steps!( connector::Opayo, connector::Opennode, connector::Payeezy, - connector::Paypal, connector::Payu, connector::Powertranz, connector::Prophetpay, diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 04bd7f0b433..4ef23f481a2 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -417,6 +417,30 @@ impl TryFrom<types::PaymentsAuthorizeData> for types::PaymentsPreProcessingData complete_authorize_url: data.complete_authorize_url, browser_info: data.browser_info, surcharge_details: data.surcharge_details, + connector_transaction_id: None, + }) + } +} + +impl TryFrom<types::CompleteAuthorizeData> for types::PaymentsPreProcessingData { + type Error = error_stack::Report<errors::ApiErrorResponse>; + + fn try_from(data: types::CompleteAuthorizeData) -> Result<Self, Self::Error> { + Ok(Self { + payment_method_data: data.payment_method_data, + amount: Some(data.amount), + email: data.email, + currency: Some(data.currency), + payment_method_type: None, + setup_mandate_details: data.setup_mandate_details, + capture_method: data.capture_method, + order_details: None, + router_return_url: None, + webhook_url: None, + complete_authorize_url: None, + browser_info: data.browser_info, + surcharge_details: None, + connector_transaction_id: data.connector_transaction_id, }) } } diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs index 44d8728fd4d..2d52a145fea 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -6,7 +6,7 @@ use crate::{ errors::{self, ConnectorErrorExt, RouterResult}, payments::{self, access_token, helpers, transformers, PaymentData}, }, - routes::AppState, + routes::{metrics, AppState}, services, types::{self, api, domain}, utils::OptionExt, @@ -144,6 +144,76 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData> Ok((request, true)) } + + async fn preprocessing_steps<'a>( + self, + state: &AppState, + connector: &api::ConnectorData, + ) -> RouterResult<Self> { + complete_authorize_preprocessing_steps(state, &self, true, connector).await + } +} + +pub async fn complete_authorize_preprocessing_steps<F: Clone>( + state: &AppState, + router_data: &types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>, + confirm: bool, + connector: &api::ConnectorData, +) -> RouterResult<types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>> { + if confirm { + let connector_integration: services::BoxedConnectorIntegration< + '_, + api::PreProcessing, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + let preprocessing_request_data = + types::PaymentsPreProcessingData::try_from(router_data.request.to_owned())?; + + let preprocessing_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> = + Err(types::ErrorResponse::default()); + + let preprocessing_router_data = + payments::helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>( + router_data.clone(), + preprocessing_request_data, + preprocessing_response_data, + ); + + let resp = services::execute_connector_processing_step( + state, + connector_integration, + &preprocessing_router_data, + payments::CallConnectorAction::Trigger, + None, + ) + .await + .to_payment_failed_response()?; + + metrics::PREPROCESSING_STEPS_COUNT.add( + &metrics::CONTEXT, + 1, + &[ + metrics::request::add_attributes("connector", connector.connector_name.to_string()), + metrics::request::add_attributes( + "payment_method", + router_data.payment_method.to_string(), + ), + ], + ); + + let authorize_router_data = + payments::helpers::router_data_type_conversion::<_, F, _, _, _, _>( + resp.clone(), + router_data.request.to_owned(), + resp.response, + ); + + Ok(authorize_router_data) + } else { + Ok(router_data.clone()) + } } impl TryFrom<types::CompleteAuthorizeData> for types::PaymentMethodTokenizationData { diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index f395c023128..000bbb0fc00 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1428,6 +1428,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProce complete_authorize_url, browser_info, surcharge_details: payment_data.surcharge_details, + connector_transaction_id: payment_data.payment_attempt.connector_transaction_id, }) } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 8c9d030965c..db126b81451 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -442,6 +442,7 @@ pub struct PaymentsPreProcessingData { pub complete_authorize_url: Option<String>, pub surcharge_details: Option<api_models::payment_methods::SurchargeDetailsResponse>, pub browser_info: Option<BrowserInformation>, + pub connector_transaction_id: Option<String>, } #[derive(Debug, Clone)]
feat
[Paypal] Add Preprocessing flow to CompleteAuthorize for Card 3DS Auth Verification (#2757)
10e9121341fe25d195f4c9a25dcc383c2ffd0c95
2024-06-24 18:10:50
Vrishab Srivatsa
feat: added kafka events for authentication create and update (#4991)
false
diff --git a/config/config.example.toml b/config/config.example.toml index 9bdf0b80723..8845aed80cb 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -587,17 +587,18 @@ enabled = true # Switch to enable or disable PayPal onboard source = "logs" # The event sink to push events supports kafka or logs (stdout) [events.kafka] -brokers = [] # Kafka broker urls for bootstrapping the client -intent_analytics_topic = "topic" # Kafka topic to be used for PaymentIntent events -attempt_analytics_topic = "topic" # Kafka topic to be used for PaymentAttempt events -refund_analytics_topic = "topic" # Kafka topic to be used for Refund events -api_logs_topic = "topic" # Kafka topic to be used for incoming api events -connector_logs_topic = "topic" # Kafka topic to be used for connector api events -outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webhook events -dispute_analytics_topic = "topic" # Kafka topic to be used for Dispute events -audit_events_topic = "topic" # Kafka topic to be used for Payment Audit events -payout_analytics_topic = "topic" # Kafka topic to be used for Payouts and PayoutAttempt events -consolidated_events_topic = "topic" # Kafka topic to be used for Consolidated events +brokers = [] # Kafka broker urls for bootstrapping the client +intent_analytics_topic = "topic" # Kafka topic to be used for PaymentIntent events +attempt_analytics_topic = "topic" # Kafka topic to be used for PaymentAttempt events +refund_analytics_topic = "topic" # Kafka topic to be used for Refund events +api_logs_topic = "topic" # Kafka topic to be used for incoming api events +connector_logs_topic = "topic" # Kafka topic to be used for connector api events +outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webhook events +dispute_analytics_topic = "topic" # Kafka topic to be used for Dispute events +audit_events_topic = "topic" # Kafka topic to be used for Payment Audit events +payout_analytics_topic = "topic" # Kafka topic to be used for Payouts and PayoutAttempt events +consolidated_events_topic = "topic" # Kafka topic to be used for Consolidated events +authentication_analytics_topic = "topic" # Kafka topic to be used for Authentication events # File storage configuration [file_storage] diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index ccb26042f56..ebbae551ea0 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -71,17 +71,18 @@ sts_role_session_name = "" # An identifier for the assumed role session, used to source = "logs" # The event sink to push events supports kafka or logs (stdout) [events.kafka] -brokers = [] # Kafka broker urls for bootstrapping the client -intent_analytics_topic = "topic" # Kafka topic to be used for PaymentIntent events -attempt_analytics_topic = "topic" # Kafka topic to be used for PaymentAttempt events -refund_analytics_topic = "topic" # Kafka topic to be used for Refund events -api_logs_topic = "topic" # Kafka topic to be used for incoming api events -connector_logs_topic = "topic" # Kafka topic to be used for connector api events -outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webhook events -dispute_analytics_topic = "topic" # Kafka topic to be used for Dispute events -audit_events_topic = "topic" # Kafka topic to be used for Payment Audit events -payout_analytics_topic = "topic" # Kafka topic to be used for Payouts and PayoutAttempt events -consolidated_events_topic = "topic" # Kafka topic to be used for Consolidated events +brokers = [] # Kafka broker urls for bootstrapping the client +intent_analytics_topic = "topic" # Kafka topic to be used for PaymentIntent events +attempt_analytics_topic = "topic" # Kafka topic to be used for PaymentAttempt events +refund_analytics_topic = "topic" # Kafka topic to be used for Refund events +api_logs_topic = "topic" # Kafka topic to be used for incoming api events +connector_logs_topic = "topic" # Kafka topic to be used for connector api events +outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webhook events +dispute_analytics_topic = "topic" # Kafka topic to be used for Dispute events +audit_events_topic = "topic" # Kafka topic to be used for Payment Audit events +payout_analytics_topic = "topic" # Kafka topic to be used for Payouts and PayoutAttempt events +consolidated_events_topic = "topic" # Kafka topic to be used for Consolidated events +authentication_analytics_topic = "topic" # Kafka topic to be used for Authentication events # File storage configuration [file_storage] diff --git a/config/development.toml b/config/development.toml index 29f693f6bf2..58a95994b8d 100644 --- a/config/development.toml +++ b/config/development.toml @@ -598,6 +598,7 @@ dispute_analytics_topic = "hyperswitch-dispute-events" audit_events_topic = "hyperswitch-audit-events" payout_analytics_topic = "hyperswitch-payout-events" consolidated_events_topic = "hyperswitch-consolidated-events" +authentication_analytics_topic = "hyperswitch-authentication-events" [analytics] source = "sqlx" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 1b0538d1af0..ac0c8392d16 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -442,6 +442,7 @@ dispute_analytics_topic = "hyperswitch-dispute-events" audit_events_topic = "hyperswitch-audit-events" payout_analytics_topic = "hyperswitch-payout-events" consolidated_events_topic = "hyperswitch-consolidated-events" +authentication_analytics_topic = "hyperswitch-authentication-events" [analytics] source = "sqlx" diff --git a/crates/analytics/docs/clickhouse/scripts/authentications.sql b/crates/analytics/docs/clickhouse/scripts/authentications.sql new file mode 100644 index 00000000000..0d540e64942 --- /dev/null +++ b/crates/analytics/docs/clickhouse/scripts/authentications.sql @@ -0,0 +1,194 @@ +CREATE TABLE authentication_queue ( + `authentication_id` String, + `merchant_id` String, + `authentication_connector` LowCardinality(String), + `connector_authentication_id` Nullable(String), + `authentication_data` Nullable(String), + `payment_method_id` Nullable(String), + `authentication_type` LowCardinality(Nullable(String)), + `authentication_status` LowCardinality(String), + `authentication_lifecycle_status` LowCardinality(String), + `created_at` DateTime64(3), + `modified_at` DateTime64(3), + `error_message` Nullable(String), + `error_code` Nullable(String), + `connector_metadata` Nullable(String), + `maximum_supported_version` LowCardinality(Nullable(String)), + `threeds_server_transaction_id` Nullable(String), + `cavv` Nullable(String), + `authentication_flow_type` Nullable(String), + `message_version` LowCardinality(Nullable(String)), + `eci` Nullable(String), + `trans_status` LowCardinality(Nullable(String)), + `acquirer_bin` Nullable(String), + `acquirer_merchant_id` Nullable(String), + `three_ds_method_data` Nullable(String), + `three_ds_method_url` Nullable(String), + `acs_url` Nullable(String), + `challenge_request` Nullable(String), + `acs_reference_number` Nullable(String), + `acs_trans_id` Nullable(String), + `acs_signed_content` Nullable(String), + `profile_id` String, + `payment_id` Nullable(String), + `merchant_connector_id` Nullable(String), + `ds_trans_id` Nullable(String), + `directory_server_id` Nullable(String), + `acquirer_country_code` Nullable(String), + `sign_flag` Int8 +) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', +kafka_topic_list = 'hyperswitch-authentication-events', +kafka_group_name = 'hyper', +kafka_format = 'JSONEachRow', +kafka_handle_error_mode = 'stream'; + +CREATE TABLE authentications ( + `authentication_id` String, + `merchant_id` String, + `authentication_connector` LowCardinality(String), + `connector_authentication_id` Nullable(String), + `authentication_data` Nullable(String), + `payment_method_id` Nullable(String), + `authentication_type` LowCardinality(Nullable(String)), + `authentication_status` LowCardinality(String), + `authentication_lifecycle_status` LowCardinality(String), + `created_at` DateTime64(3) DEFAULT now64(), + `inserted_at` DateTime64(3) DEFAULT now64(), + `modified_at` DateTime64(3) DEFAULT now64(), + `error_message` Nullable(String), + `error_code` Nullable(String), + `connector_metadata` Nullable(String), + `maximum_supported_version` LowCardinality(Nullable(String)), + `threeds_server_transaction_id` Nullable(String), + `cavv` Nullable(String), + `authentication_flow_type` Nullable(String), + `message_version` LowCardinality(Nullable(String)), + `eci` Nullable(String), + `trans_status` LowCardinality(Nullable(String)), + `acquirer_bin` Nullable(String), + `acquirer_merchant_id` Nullable(String), + `three_ds_method_data` Nullable(String), + `three_ds_method_url` Nullable(String), + `acs_url` Nullable(String), + `challenge_request` Nullable(String), + `acs_reference_number` Nullable(String), + `acs_trans_id` Nullable(String), + `acs_signed_content` Nullable(String), + `profile_id` String, + `payment_id` Nullable(String), + `merchant_connector_id` Nullable(String), + `ds_trans_id` Nullable(String), + `directory_server_id` Nullable(String), + `acquirer_country_code` Nullable(String), + `sign_flag` Int8, + INDEX authenticationConnectorIndex authentication_connector TYPE bloom_filter GRANULARITY 1, + INDEX transStatusIndex trans_status TYPE bloom_filter GRANULARITY 1, + INDEX authenticationTypeIndex authentication_type TYPE bloom_filter GRANULARITY 1, + INDEX authenticationStatusIndex authentication_status TYPE bloom_filter GRANULARITY 1 +) ENGINE = CollapsingMergeTree(sign_flag) PARTITION BY toStartOfDay(created_at) +ORDER BY + (created_at, merchant_id, authentication_id) TTL toStartOfDay(created_at) + toIntervalMonth(18) SETTINGS index_granularity = 8192; + +CREATE MATERIALIZED VIEW authentication_mv TO authentications ( + `authentication_id` String, + `merchant_id` String, + `authentication_connector` LowCardinality(String), + `connector_authentication_id` Nullable(String), + `authentication_data` Nullable(String), + `payment_method_id` Nullable(String), + `authentication_type` LowCardinality(Nullable(String)), + `authentication_status` LowCardinality(String), + `authentication_lifecycle_status` LowCardinality(String), + `created_at` DateTime64(3) DEFAULT now64(), + `inserted_at` DateTime64(3) DEFAULT now64(), + `modified_at` DateTime64(3) DEFAULT now64(), + `error_message` Nullable(String), + `error_code` Nullable(String), + `connector_metadata` Nullable(String), + `maximum_supported_version` LowCardinality(Nullable(String)), + `threeds_server_transaction_id` Nullable(String), + `cavv` Nullable(String), + `authentication_flow_type` Nullable(String), + `message_version` LowCardinality(Nullable(String)), + `eci` Nullable(String), + `trans_status` LowCardinality(Nullable(String)), + `acquirer_bin` Nullable(String), + `acquirer_merchant_id` Nullable(String), + `three_ds_method_data` Nullable(String), + `three_ds_method_url` Nullable(String), + `acs_url` Nullable(String), + `challenge_request` Nullable(String), + `acs_reference_number` Nullable(String), + `acs_trans_id` Nullable(String), + `acs_signed_content` Nullable(String), + `profile_id` String, + `payment_id` Nullable(String), + `merchant_connector_id` Nullable(String), + `ds_trans_id` Nullable(String), + `directory_server_id` Nullable(String), + `acquirer_country_code` Nullable(String), + `sign_flag` Int8 +) AS +SELECT + authentication_id, + merchant_id, + authentication_connector, + connector_authentication_id, + authentication_data, + payment_method_id, + authentication_type, + authentication_status, + authentication_lifecycle_status, + created_at, + now64() as inserted_at, + modified_at, + error_message, + error_code, + connector_metadata, + maximum_supported_version, + threeds_server_transaction_id, + cavv, + authentication_flow_type, + message_version, + eci, + trans_status, + acquirer_bin, + acquirer_merchant_id, + three_ds_method_data, + three_ds_method_url, + acs_url, + challenge_request, + acs_reference_number, + acs_trans_id, + acs_signed_content, + profile_id, + payment_id, + merchant_connector_id, + ds_trans_id, + directory_server_id, + acquirer_country_code, + sign_flag +FROM + authentication_queue +WHERE + length(_error) = 0; + +CREATE MATERIALIZED VIEW authentication_parse_errors ( + `topic` String, + `partition` Int64, + `offset` Int64, + `raw` String, + `error` String +) ENGINE = MergeTree +ORDER BY + (topic, partition, offset) SETTINGS index_granularity = 8192 AS +SELECT + _topic AS topic, + _partition AS partition, + _offset AS offset, + _raw_message AS raw, + _error AS error +FROM + authentication_queue +WHERE + length(_error) > 0; \ No newline at end of file diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 2964fd78bce..044b17947c5 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -2751,9 +2751,20 @@ impl AuthenticationInterface for KafkaStore { &self, authentication: storage::AuthenticationNew, ) -> CustomResult<storage::Authentication, errors::StorageError> { - self.diesel_store + let auth = self + .diesel_store .insert_authentication(authentication) + .await?; + + if let Err(er) = self + .kafka_producer + .log_authentication(&auth, None, self.tenant_id.clone()) .await + { + logger::error!(message="Failed to log analytics event for authentication {auth:?}", error_message=?er) + } + + Ok(auth) } async fn find_authentication_by_merchant_id_authentication_id( @@ -2784,12 +2795,23 @@ impl AuthenticationInterface for KafkaStore { previous_state: storage::Authentication, authentication_update: storage::AuthenticationUpdate, ) -> CustomResult<storage::Authentication, errors::StorageError> { - self.diesel_store + let auth = self + .diesel_store .update_authentication_by_merchant_id_authentication_id( - previous_state, + previous_state.clone(), authentication_update, ) + .await?; + + if let Err(er) = self + .kafka_producer + .log_authentication(&auth, Some(previous_state.clone()), self.tenant_id.clone()) .await + { + logger::error!(message="Failed to log analytics event for authentication {auth:?}", error_message=?er) + } + + Ok(auth) } } diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs index 1af515b8c22..632989c4806 100644 --- a/crates/router/src/events.rs +++ b/crates/router/src/events.rs @@ -33,6 +33,7 @@ pub enum EventType { #[cfg(feature = "payouts")] Payout, Consolidated, + Authentication, } #[derive(Debug, Default, Deserialize, Clone)] diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index 9c38917424e..b245eb3fe74 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -12,6 +12,8 @@ use rdkafka::{ #[cfg(feature = "payouts")] pub mod payout; use crate::events::EventType; +mod authentication; +mod authentication_event; mod dispute; mod dispute_event; mod payment_attempt; @@ -20,7 +22,7 @@ mod payment_intent; mod payment_intent_event; mod refund; mod refund_event; -use diesel_models::refund::Refund; +use diesel_models::{authentication::Authentication, refund::Refund}; use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent}; use serde::Serialize; use time::{OffsetDateTime, PrimitiveDateTime}; @@ -28,6 +30,7 @@ use time::{OffsetDateTime, PrimitiveDateTime}; #[cfg(feature = "payouts")] use self::payout::KafkaPayout; use self::{ + authentication::KafkaAuthentication, authentication_event::KafkaAuthenticationEvent, dispute::KafkaDispute, dispute_event::KafkaDisputeEvent, payment_attempt::KafkaPaymentAttempt, payment_attempt_event::KafkaPaymentAttemptEvent, payment_intent::KafkaPaymentIntent, payment_intent_event::KafkaPaymentIntentEvent, refund::KafkaRefund, @@ -147,6 +150,7 @@ pub struct KafkaSettings { #[cfg(feature = "payouts")] payout_analytics_topic: String, consolidated_events_topic: String, + authentication_analytics_topic: String, } impl KafkaSettings { @@ -225,6 +229,15 @@ impl KafkaSettings { )) })?; + common_utils::fp_utils::when( + self.authentication_analytics_topic.is_default_or_empty(), + || { + Err(ApplicationError::InvalidConfigurationValueError( + "Kafka Authentication Analytics topic must not be empty".into(), + )) + }, + )?; + Ok(()) } } @@ -243,6 +256,7 @@ pub struct KafkaProducer { #[cfg(feature = "payouts")] payout_analytics_topic: String, consolidated_events_topic: String, + authentication_analytics_topic: String, } struct RdKafkaProducer(ThreadedProducer<DefaultProducerContext>); @@ -285,6 +299,7 @@ impl KafkaProducer { #[cfg(feature = "payouts")] payout_analytics_topic: conf.payout_analytics_topic.clone(), consolidated_events_topic: conf.consolidated_events_topic.clone(), + authentication_analytics_topic: conf.authentication_analytics_topic.clone(), }) } @@ -350,6 +365,39 @@ impl KafkaProducer { }) } + pub async fn log_authentication( + &self, + authentication: &Authentication, + old_authentication: Option<Authentication>, + tenant_id: TenantID, + ) -> MQResult<()> { + if let Some(negative_event) = old_authentication { + self.log_event(&KafkaEvent::old( + &KafkaAuthentication::from_storage(&negative_event), + tenant_id.clone(), + )) + .attach_printable_lazy(|| { + format!("Failed to add negative authentication event {negative_event:?}") + })?; + }; + + self.log_event(&KafkaEvent::new( + &KafkaAuthentication::from_storage(authentication), + tenant_id.clone(), + )) + .attach_printable_lazy(|| { + format!("Failed to add positive authentication event {authentication:?}") + })?; + + self.log_event(&KafkaConsolidatedEvent::new( + &KafkaAuthenticationEvent::from_storage(authentication), + tenant_id.clone(), + )) + .attach_printable_lazy(|| { + format!("Failed to add consolidated authentication event {authentication:?}") + }) + } + pub async fn log_payment_intent( &self, intent: &PaymentIntent, @@ -507,6 +555,7 @@ impl KafkaProducer { #[cfg(feature = "payouts")] EventType::Payout => &self.payout_analytics_topic, EventType::Consolidated => &self.consolidated_events_topic, + EventType::Authentication => &self.authentication_analytics_topic, } } } diff --git a/crates/router/src/services/kafka/authentication.rs b/crates/router/src/services/kafka/authentication.rs new file mode 100644 index 00000000000..dce648aff64 --- /dev/null +++ b/crates/router/src/services/kafka/authentication.rs @@ -0,0 +1,97 @@ +use diesel_models::{authentication::Authentication, enums as storage_enums}; +use time::OffsetDateTime; + +#[derive(serde::Serialize, Debug)] +pub struct KafkaAuthentication<'a> { + pub authentication_id: &'a String, + pub merchant_id: &'a String, + pub authentication_connector: &'a String, + pub connector_authentication_id: Option<&'a String>, + pub authentication_data: Option<serde_json::Value>, + pub payment_method_id: &'a String, + pub authentication_type: Option<storage_enums::DecoupledAuthenticationType>, + pub authentication_status: storage_enums::AuthenticationStatus, + pub authentication_lifecycle_status: storage_enums::AuthenticationLifecycleStatus, + #[serde(default, with = "time::serde::timestamp::milliseconds")] + pub created_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp::milliseconds")] + pub modified_at: OffsetDateTime, + pub error_message: Option<&'a String>, + pub error_code: Option<&'a String>, + pub connector_metadata: Option<serde_json::Value>, + pub maximum_supported_version: Option<common_utils::types::SemanticVersion>, + pub threeds_server_transaction_id: Option<&'a String>, + pub cavv: Option<&'a String>, + pub authentication_flow_type: Option<&'a String>, + pub message_version: Option<common_utils::types::SemanticVersion>, + pub eci: Option<&'a String>, + pub trans_status: Option<storage_enums::TransactionStatus>, + pub acquirer_bin: Option<&'a String>, + pub acquirer_merchant_id: Option<&'a String>, + pub three_ds_method_data: Option<&'a String>, + pub three_ds_method_url: Option<&'a String>, + pub acs_url: Option<&'a String>, + pub challenge_request: Option<&'a String>, + pub acs_reference_number: Option<&'a String>, + pub acs_trans_id: Option<&'a String>, + pub acs_signed_content: Option<&'a String>, + pub profile_id: &'a String, + pub payment_id: Option<&'a String>, + pub merchant_connector_id: &'a String, + pub ds_trans_id: Option<&'a String>, + pub directory_server_id: Option<&'a String>, + pub acquirer_country_code: Option<&'a String>, +} + +impl<'a> KafkaAuthentication<'a> { + pub fn from_storage(authentication: &'a Authentication) -> Self { + Self { + created_at: authentication.created_at.assume_utc(), + modified_at: authentication.modified_at.assume_utc(), + authentication_id: &authentication.authentication_id, + merchant_id: &authentication.merchant_id, + authentication_status: authentication.authentication_status, + authentication_connector: &authentication.authentication_connector, + connector_authentication_id: authentication.connector_authentication_id.as_ref(), + authentication_data: authentication.authentication_data.clone(), + payment_method_id: &authentication.payment_method_id, + authentication_type: authentication.authentication_type, + authentication_lifecycle_status: authentication.authentication_lifecycle_status, + error_code: authentication.error_code.as_ref(), + error_message: authentication.error_message.as_ref(), + connector_metadata: authentication.connector_metadata.clone(), + maximum_supported_version: authentication.maximum_supported_version.clone(), + threeds_server_transaction_id: authentication.threeds_server_transaction_id.as_ref(), + cavv: authentication.cavv.as_ref(), + authentication_flow_type: authentication.authentication_flow_type.as_ref(), + message_version: authentication.message_version.clone(), + eci: authentication.eci.as_ref(), + trans_status: authentication.trans_status.clone(), + acquirer_bin: authentication.acquirer_bin.as_ref(), + acquirer_merchant_id: authentication.acquirer_merchant_id.as_ref(), + three_ds_method_data: authentication.three_ds_method_data.as_ref(), + three_ds_method_url: authentication.three_ds_method_url.as_ref(), + acs_url: authentication.acs_url.as_ref(), + challenge_request: authentication.challenge_request.as_ref(), + acs_reference_number: authentication.acs_reference_number.as_ref(), + acs_trans_id: authentication.acs_trans_id.as_ref(), + acs_signed_content: authentication.acs_signed_content.as_ref(), + profile_id: &authentication.profile_id, + payment_id: authentication.payment_id.as_ref(), + merchant_connector_id: &authentication.merchant_connector_id, + ds_trans_id: authentication.ds_trans_id.as_ref(), + directory_server_id: authentication.directory_server_id.as_ref(), + acquirer_country_code: authentication.acquirer_country_code.as_ref(), + } + } +} + +impl<'a> super::KafkaMessage for KafkaAuthentication<'a> { + fn key(&self) -> String { + format!("{}_{}", self.merchant_id, self.authentication_id) + } + + fn event_type(&self) -> crate::events::EventType { + crate::events::EventType::Authentication + } +} diff --git a/crates/router/src/services/kafka/authentication_event.rs b/crates/router/src/services/kafka/authentication_event.rs new file mode 100644 index 00000000000..6dbebe6ca76 --- /dev/null +++ b/crates/router/src/services/kafka/authentication_event.rs @@ -0,0 +1,98 @@ +use diesel_models::{authentication::Authentication, enums as storage_enums}; +use time::OffsetDateTime; + +#[serde_with::skip_serializing_none] +#[derive(serde::Serialize, Debug)] +pub struct KafkaAuthenticationEvent<'a> { + pub authentication_id: &'a String, + pub merchant_id: &'a String, + pub authentication_connector: &'a String, + pub connector_authentication_id: Option<&'a String>, + pub authentication_data: Option<serde_json::Value>, + pub payment_method_id: &'a String, + pub authentication_type: Option<storage_enums::DecoupledAuthenticationType>, + pub authentication_status: storage_enums::AuthenticationStatus, + pub authentication_lifecycle_status: storage_enums::AuthenticationLifecycleStatus, + #[serde(default, with = "time::serde::timestamp::milliseconds")] + pub created_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp::milliseconds")] + pub modified_at: OffsetDateTime, + pub error_message: Option<&'a String>, + pub error_code: Option<&'a String>, + pub connector_metadata: Option<serde_json::Value>, + pub maximum_supported_version: Option<common_utils::types::SemanticVersion>, + pub threeds_server_transaction_id: Option<&'a String>, + pub cavv: Option<&'a String>, + pub authentication_flow_type: Option<&'a String>, + pub message_version: Option<common_utils::types::SemanticVersion>, + pub eci: Option<&'a String>, + pub trans_status: Option<storage_enums::TransactionStatus>, + pub acquirer_bin: Option<&'a String>, + pub acquirer_merchant_id: Option<&'a String>, + pub three_ds_method_data: Option<&'a String>, + pub three_ds_method_url: Option<&'a String>, + pub acs_url: Option<&'a String>, + pub challenge_request: Option<&'a String>, + pub acs_reference_number: Option<&'a String>, + pub acs_trans_id: Option<&'a String>, + pub acs_signed_content: Option<&'a String>, + pub profile_id: &'a String, + pub payment_id: Option<&'a String>, + pub merchant_connector_id: &'a String, + pub ds_trans_id: Option<&'a String>, + pub directory_server_id: Option<&'a String>, + pub acquirer_country_code: Option<&'a String>, +} + +impl<'a> KafkaAuthenticationEvent<'a> { + pub fn from_storage(authentication: &'a Authentication) -> Self { + Self { + created_at: authentication.created_at.assume_utc(), + modified_at: authentication.modified_at.assume_utc(), + authentication_id: &authentication.authentication_id, + merchant_id: &authentication.merchant_id, + authentication_status: authentication.authentication_status, + authentication_connector: &authentication.authentication_connector, + connector_authentication_id: authentication.connector_authentication_id.as_ref(), + authentication_data: authentication.authentication_data.clone(), + payment_method_id: &authentication.payment_method_id, + authentication_type: authentication.authentication_type, + authentication_lifecycle_status: authentication.authentication_lifecycle_status, + error_code: authentication.error_code.as_ref(), + error_message: authentication.error_message.as_ref(), + connector_metadata: authentication.connector_metadata.clone(), + maximum_supported_version: authentication.maximum_supported_version.clone(), + threeds_server_transaction_id: authentication.threeds_server_transaction_id.as_ref(), + cavv: authentication.cavv.as_ref(), + authentication_flow_type: authentication.authentication_flow_type.as_ref(), + message_version: authentication.message_version.clone(), + eci: authentication.eci.as_ref(), + trans_status: authentication.trans_status.clone(), + acquirer_bin: authentication.acquirer_bin.as_ref(), + acquirer_merchant_id: authentication.acquirer_merchant_id.as_ref(), + three_ds_method_data: authentication.three_ds_method_data.as_ref(), + three_ds_method_url: authentication.three_ds_method_url.as_ref(), + acs_url: authentication.acs_url.as_ref(), + challenge_request: authentication.challenge_request.as_ref(), + acs_reference_number: authentication.acs_reference_number.as_ref(), + acs_trans_id: authentication.acs_trans_id.as_ref(), + acs_signed_content: authentication.acs_signed_content.as_ref(), + profile_id: &authentication.profile_id, + payment_id: authentication.payment_id.as_ref(), + merchant_connector_id: &authentication.merchant_connector_id, + ds_trans_id: authentication.ds_trans_id.as_ref(), + directory_server_id: authentication.directory_server_id.as_ref(), + acquirer_country_code: authentication.acquirer_country_code.as_ref(), + } + } +} + +impl<'a> super::KafkaMessage for KafkaAuthenticationEvent<'a> { + fn key(&self) -> String { + format!("{}_{}", self.merchant_id, self.authentication_id) + } + + fn event_type(&self) -> crate::events::EventType { + crate::events::EventType::Authentication + } +}
feat
added kafka events for authentication create and update (#4991)
eee55bdfbe67e5f4be7ed7e388f5ed93e70165ff
2023-05-09 23:55:26
Swangi Kumari
feat(Connector): [Adyen]Implement ACH Direct Debits for Adyen (#1033)
false
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 57dd2b00763..bffeb088c7c 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -488,6 +488,9 @@ pub enum BankDebitData { /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, + + #[schema(value_type = String, example = "John Test")] + bank_account_holder_name: Option<Secret<String>>, }, SepaBankDebit { /// Billing details for bank debit diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 5dc6f7d5ba4..e06f0a99b6f 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1,6 +1,4 @@ -use api_models::{ - enums::DisputeStage, payments::MandateReferenceId, webhooks::IncomingWebhookEvent, -}; +use api_models::{enums, payments, webhooks}; use cards::CardNumber; use masking::PeekInterface; use reqwest::Url; @@ -280,6 +278,17 @@ pub enum AdyenPaymentMethod<'a> { Trustly(Box<BankRedirectionPMData>), Walley(Box<WalleyData>), WeChatPayWeb(Box<WeChatPayWebData>), + AchDirectDebit(Box<AchDirectDebitData>), +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AchDirectDebitData { + #[serde(rename = "type")] + payment_type: PaymentType, + bank_account_number: Secret<String>, + bank_location_id: Secret<String>, + owner_name: Secret<String>, } #[derive(Debug, Clone, Serialize)] @@ -652,6 +661,8 @@ pub enum PaymentType { Walley, #[serde(rename = "wechatpayWeb")] WeChatPayWeb, + #[serde(rename = "ach")] + AchDirectDebit, } pub struct AdyenTestBankNames<'a>(&'a str); @@ -755,6 +766,9 @@ impl<'a> TryFrom<&types::PaymentsAuthorizeRouterData> for AdyenPaymentRequest<'a api_models::payments::PaymentMethodData::BankRedirect(ref bank_redirect) => { AdyenPaymentRequest::try_from((item, bank_redirect)) } + api_models::payments::PaymentMethodData::BankDebit(ref bank_debit) => { + AdyenPaymentRequest::try_from((item, bank_debit)) + } _ => Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.request.payment_method_type), connector: "Adyen", @@ -905,6 +919,35 @@ fn get_country_code(item: &types::PaymentsAuthorizeRouterData) -> Option<api_enu .and_then(|billing| billing.address.as_ref().and_then(|address| address.country)) } +impl<'a> TryFrom<&api_models::payments::BankDebitData> for AdyenPaymentMethod<'a> { + type Error = Error; + fn try_from( + bank_debit_data: &api_models::payments::BankDebitData, + ) -> Result<Self, Self::Error> { + match bank_debit_data { + payments::BankDebitData::AchBankDebit { + account_number, + routing_number, + billing_details: _, + bank_account_holder_name, + } => Ok(AdyenPaymentMethod::AchDirectDebit(Box::new( + AchDirectDebitData { + payment_type: PaymentType::AchDirectDebit, + bank_account_number: account_number.clone(), + bank_location_id: routing_number.clone(), + owner_name: bank_account_holder_name.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "bank_account_holder_name", + }, + )?, + }, + ))), + + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + impl<'a> TryFrom<&api::Card> for AdyenPaymentMethod<'a> { type Error = Error; fn try_from(card: &api::Card) -> Result<Self, Self::Error> { @@ -1107,12 +1150,18 @@ impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod } } -impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, MandateReferenceId)> - for AdyenPaymentRequest<'a> +impl<'a> + TryFrom<( + &types::PaymentsAuthorizeRouterData, + payments::MandateReferenceId, + )> for AdyenPaymentRequest<'a> { type Error = Error; fn try_from( - value: (&types::PaymentsAuthorizeRouterData, MandateReferenceId), + value: ( + &types::PaymentsAuthorizeRouterData, + payments::MandateReferenceId, + ), ) -> Result<Self, Self::Error> { let (item, mandate_ref_id) = value; let amount = get_amount_data(item); @@ -1124,7 +1173,7 @@ impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, MandateReferenceId)> let additional_data = get_additional_data(item); let return_url = item.request.get_return_url()?; let payment_method = match mandate_ref_id { - MandateReferenceId::ConnectorMandateId(connector_mandate_ids) => { + payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids) => { let adyen_mandate = AdyenMandate { payment_type: PaymentType::Scheme, stored_payment_method_id: connector_mandate_ids.get_connector_mandate_id()?, @@ -1133,7 +1182,7 @@ impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, MandateReferenceId)> adyen_mandate, ))) } - MandateReferenceId::NetworkMandateId(network_mandate_id) => { + payments::MandateReferenceId::NetworkMandateId(network_mandate_id) => { match item.request.payment_method_data { api::PaymentMethodData::Card(ref card) => { let card_issuer = card.get_card_issuer()?; @@ -1220,6 +1269,55 @@ impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, &api::Card)> for AdyenPay } } +impl<'a> + TryFrom<( + &types::PaymentsAuthorizeRouterData, + &api_models::payments::BankDebitData, + )> for AdyenPaymentRequest<'a> +{ + type Error = Error; + + fn try_from( + value: ( + &types::PaymentsAuthorizeRouterData, + &api_models::payments::BankDebitData, + ), + ) -> Result<Self, Self::Error> { + let (item, bank_debit_data) = value; + let amount = get_amount_data(item); + let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; + let shopper_interaction = AdyenShopperInteraction::from(item); + let recurring_processing_model = get_recurring_processing_model(item)?.0; + let browser_info = get_browser_info(item); + let additional_data = get_additional_data(item); + let return_url = item.request.get_return_url()?; + let payment_method = AdyenPaymentMethod::try_from(bank_debit_data)?; + let country_code = get_country_code(item); + let request = AdyenPaymentRequest { + amount, + merchant_account: auth_type.merchant_account, + payment_method, + reference: item.payment_id.to_string(), + return_url, + browser_info, + shopper_interaction, + recurring_processing_model, + additional_data, + shopper_name: None, + shopper_locale: None, + shopper_email: item.request.email.clone(), + telephone_number: None, + billing_address: None, + delivery_address: None, + country_code, + line_items: None, + shopper_reference: None, + store_payment_method: None, + }; + Ok(request) + } +} + impl<'a> TryFrom<( &types::PaymentsAuthorizeRouterData, @@ -1790,7 +1888,7 @@ pub fn is_chargeback_event(event_code: &WebhookEventCode) -> bool { ) } -impl ForeignFrom<(WebhookEventCode, Option<DisputeStatus>)> for IncomingWebhookEvent { +impl ForeignFrom<(WebhookEventCode, Option<DisputeStatus>)> for webhooks::IncomingWebhookEvent { fn foreign_from((code, status): (WebhookEventCode, Option<DisputeStatus>)) -> Self { match (code, status) { (WebhookEventCode::Authorisation, _) => Self::PaymentIntentSuccess, @@ -1816,7 +1914,7 @@ impl ForeignFrom<(WebhookEventCode, Option<DisputeStatus>)> for IncomingWebhookE } } -impl From<WebhookEventCode> for DisputeStage { +impl From<WebhookEventCode> for enums::DisputeStage { fn from(code: WebhookEventCode) -> Self { match code { WebhookEventCode::NotificationOfChargeback => Self::PreDispute, diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index f50337403e9..82c440dae7a 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -668,6 +668,7 @@ fn get_bank_debit_data( billing_details, account_number, routing_number, + .. } => { let ach_data = BankDebitData::Ach { account_holder_type: "individual".to_string(),
feat
[Adyen]Implement ACH Direct Debits for Adyen (#1033)
2ba186b7d1851a1a8f2356269b9901ce08555530
2023-05-08 14:41:27
Sahkal Poddar
feat(compatibility): add mandates support in stripe compatibility (#897)
false
diff --git a/config/development.toml b/config/development.toml index ced0a7b4fd3..46b0766be95 100644 --- a/config/development.toml +++ b/config/development.toml @@ -47,6 +47,7 @@ locker_decryption_key1 = "" locker_decryption_key2 = "" vault_encryption_key = "" vault_private_key = "" +tunnel_private_key = "" [connectors.supported] wallets = ["klarna", "braintree", "applepay"] diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs index 29a24449d96..aefb532471a 100644 --- a/crates/common_utils/src/ext_traits.rs +++ b/crates/common_utils/src/ext_traits.rs @@ -147,17 +147,17 @@ where /// /// Extending functionalities of `bytes::Bytes` /// -pub trait BytesExt<T> { +pub trait BytesExt { /// /// Convert `bytes::Bytes` into type `<T>` using `serde::Deserialize` /// - fn parse_struct<'de>(&'de self, type_name: &str) -> CustomResult<T, errors::ParsingError> + fn parse_struct<'de, T>(&'de self, type_name: &str) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>; } -impl<T> BytesExt<T> for bytes::Bytes { - fn parse_struct<'de>(&'de self, _type_name: &str) -> CustomResult<T, errors::ParsingError> +impl BytesExt for bytes::Bytes { + fn parse_struct<'de, T>(&'de self, _type_name: &str) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>, { diff --git a/crates/router/src/compatibility/stripe.rs b/crates/router/src/compatibility/stripe.rs index 9ce9fef1f45..5d3fd5b6cd1 100644 --- a/crates/router/src/compatibility/stripe.rs +++ b/crates/router/src/compatibility/stripe.rs @@ -20,6 +20,7 @@ impl StripeApis { .service(app::PaymentIntents::server(state.clone())) .service(app::Refunds::server(state.clone())) .service(app::Customers::server(state.clone())) - .service(app::Webhooks::server(state)) + .service(app::Webhooks::server(state.clone())) + .service(app::Mandates::server(state)) } } diff --git a/crates/router/src/compatibility/stripe/app.rs b/crates/router/src/compatibility/stripe/app.rs index 24abb90b423..540cb5df6a6 100644 --- a/crates/router/src/compatibility/stripe/app.rs +++ b/crates/router/src/compatibility/stripe/app.rs @@ -1,7 +1,7 @@ use actix_web::{web, Scope}; use super::{customers::*, payment_intents::*, refunds::*, setup_intents::*, webhooks::*}; -use crate::routes::{self, webhooks}; +use crate::routes::{self, mandates, webhooks}; pub struct PaymentIntents; @@ -111,3 +111,13 @@ impl Webhooks { ) } } + +pub struct Mandates; + +impl Mandates { + pub fn server(config: routes::AppState) -> Scope { + web::scope("/payment_methods") + .app_data(web::Data::new(config)) + .service(web::resource("/{id}/detach").route(web::post().to(mandates::revoke_mandate))) + } +} diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 0046ae3eb17..eaaf82b1f0f 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -1,6 +1,6 @@ use api_models::payments; use common_utils::{date_time, ext_traits::StringExt, pii as secret}; -use error_stack::ResultExt; +use error_stack::{IntoReport, ResultExt}; use serde::{Deserialize, Serialize}; use crate::{ @@ -10,7 +10,7 @@ use crate::{ pii::{self, Email, PeekInterface}, types::{ api::{admin, enums as api_enums}, - transformers::{ForeignFrom, ForeignInto}, + transformers::{ForeignFrom, ForeignTryFrom}, }, }; @@ -59,6 +59,7 @@ impl From<StripePaymentMethodType> for api_enums::PaymentMethod { } } } + #[derive(Default, PartialEq, Eq, Deserialize, Clone)] pub struct StripePaymentMethodData { #[serde(rename = "type")] @@ -143,12 +144,32 @@ pub struct StripePaymentIntentRequest { pub client_secret: Option<pii::Secret<String>>, pub payment_method_options: Option<StripePaymentMethodOptions>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, + pub mandate_id: Option<String>, + pub off_session: Option<bool>, } impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentIntentRequest) -> errors::RouterResult<Self> { - Ok(Self { + let (mandate_options, authentication_type) = match item.payment_method_options { + Some(pmo) => { + let StripePaymentMethodOptions::Card { + request_three_d_secure, + mandate_options, + }: StripePaymentMethodOptions = pmo; + ( + Option::<payments::MandateData>::foreign_try_from(( + mandate_options, + item.currency.to_owned(), + ))?, + Some(api_enums::AuthenticationType::foreign_from( + request_three_d_secure, + )), + ) + } + None => (None, None), + }; + let request = Ok(Self { payment_id: item.id.map(payments::PaymentIdType::PaymentIntentId), amount: item.amount.map(|amount| amount.into()), connector: item.connector, @@ -188,16 +209,15 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { statement_descriptor_suffix: item.statement_descriptor_suffix, metadata: item.metadata, client_secret: item.client_secret.map(|s| s.peek().clone()), - authentication_type: item.payment_method_options.map(|pmo| { - let StripePaymentMethodOptions::Card { - request_three_d_secure, - } = pmo; - - request_three_d_secure.foreign_into() - }), + authentication_type, + mandate_data: mandate_options, merchant_connector_details: item.merchant_connector_details, + setup_future_usage: item.setup_future_usage, + mandate_id: item.mandate_id, + off_session: item.off_session, ..Self::default() - }) + }); + request } } @@ -374,7 +394,7 @@ impl From<payments::PaymentsResponse> for StripePaymentIntentResponse { created: u64::try_from(date_time::now().assume_utc().unix_timestamp()) .unwrap_or_default(), method_type: "card".to_string(), - live_mode: false, + livemode: false, }, error_type: code, }), @@ -391,7 +411,7 @@ pub struct StripePaymentMethod { created: u64, #[serde(rename = "type")] method_type: String, - live_mode: bool, + livemode: bool, } #[derive(Default, Eq, PartialEq, Serialize)] @@ -404,7 +424,7 @@ pub struct Charges { } impl Charges { - fn new() -> Self { + pub fn new() -> Self { Self { object: "list", data: vec![], @@ -491,15 +511,83 @@ impl From<payments::PaymentListResponse> for StripePaymentIntentListResponse { } } -#[derive(PartialEq, Eq, Deserialize, Clone)] +#[derive(PartialEq, Eq, Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodOptions { Card { request_three_d_secure: Option<Request3DS>, + mandate_options: Option<MandateOption>, }, } -#[derive(Default, Eq, PartialEq, Serialize, Deserialize, Clone)] +#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] +#[serde(rename_all = "snake_case")] +pub enum StripeMandateType { + SingleUse, + MultiUse, +} + +#[derive(PartialEq, Eq, Clone, Default, Deserialize, Serialize, Debug)] +pub struct MandateOption { + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub accepted_at: Option<time::PrimitiveDateTime>, + pub user_agent: Option<String>, + pub ip_address: Option<pii::Secret<String, common_utils::pii::IpAddress>>, + pub mandate_type: Option<StripeMandateType>, + pub amount: Option<i64>, + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub start_date: Option<time::PrimitiveDateTime>, + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub end_date: Option<time::PrimitiveDateTime>, +} + +impl ForeignTryFrom<(Option<MandateOption>, Option<String>)> for Option<payments::MandateData> { + type Error = error_stack::Report<errors::ApiErrorResponse>; + fn foreign_try_from( + (mandate_options, currency): (Option<MandateOption>, Option<String>), + ) -> errors::RouterResult<Self> { + let currency = currency + .ok_or(errors::ApiErrorResponse::MissingRequiredField { + field_name: "currency", + }) + .into_report() + .and_then(|c| { + c.to_uppercase().parse_enum("currency").change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "currency", + }, + ) + })?; + let mandate_data = mandate_options.map(|mandate| payments::MandateData { + mandate_type: match mandate.mandate_type { + Some(item) => match item { + StripeMandateType::SingleUse => { + payments::MandateType::SingleUse(payments::MandateAmountData { + amount: mandate.amount.unwrap_or_default(), + currency, + start_date: mandate.start_date, + end_date: mandate.end_date, + metadata: None, + }) + } + StripeMandateType::MultiUse => payments::MandateType::MultiUse(None), + }, + None => api_models::payments::MandateType::MultiUse(None), + }, + customer_acceptance: payments::CustomerAcceptance { + acceptance_type: payments::AcceptanceType::Online, + accepted_at: mandate.accepted_at, + online: Some(payments::OnlineMandate { + ip_address: mandate.ip_address.unwrap_or_default(), + user_agent: mandate.user_agent.unwrap_or_default(), + }), + }, + }); + Ok(mandate_data) + } +} + +#[derive(Default, Eq, PartialEq, Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum Request3DS { #[default] diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs index b11be5b3465..d907c45d147 100644 --- a/crates/router/src/compatibility/stripe/setup_intents.rs +++ b/crates/router/src/compatibility/stripe/setup_intents.rs @@ -28,7 +28,11 @@ pub async fn setup_intents_create( } }; - let create_payment_req: payment_types::PaymentsRequest = payload.into(); + let create_payment_req: payment_types::PaymentsRequest = + match payment_types::PaymentsRequest::try_from(payload) { + Ok(req) => req, + Err(err) => return api::log_and_return_error_response(err), + }; wrap::compatibility_api_wrap::< _, @@ -124,7 +128,11 @@ pub async fn setup_intents_update( } }; - let mut payload: payment_types::PaymentsRequest = stripe_payload.into(); + let mut payload: payment_types::PaymentsRequest = + match payment_types::PaymentsRequest::try_from(stripe_payload) { + Ok(req) => req, + Err(err) => return api::log_and_return_error_response(err), + }; payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id)); let (auth_type, auth_flow) = @@ -179,7 +187,11 @@ pub async fn setup_intents_confirm( } }; - let mut payload: payment_types::PaymentsRequest = stripe_payload.into(); + let mut payload: payment_types::PaymentsRequest = + match payment_types::PaymentsRequest::try_from(stripe_payload) { + Ok(req) => req, + Err(err) => return api::log_and_return_error_response(err), + }; payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id)); payload.confirm = Some(true); diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 0279e36ac89..645729d083c 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -1,12 +1,21 @@ -use api_models::{payments, refunds}; +use api_models::payments; +use common_utils::{date_time, ext_traits::StringExt}; +use error_stack::ResultExt; use router_env::logger; use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::{ + compatibility::stripe::{ + payment_intents::types as payment_intent, refunds::types as stripe_refunds, + }, + consts, core::errors, pii::{self, PeekInterface}, - types::api::{self as api_types, enums as api_enums}, + types::{ + api::{self as api_types, admin, enums as api_enums}, + transformers::{ForeignFrom, ForeignTryFrom}, + }, }; #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] @@ -108,11 +117,14 @@ impl From<Shipping> for payments::Address { } } } + #[derive(Default, PartialEq, Eq, Deserialize, Clone)] + pub struct StripeSetupIntentRequest { pub confirm: Option<bool>, pub customer: Option<String>, pub description: Option<String>, + pub currency: Option<String>, pub payment_method_data: Option<StripePaymentMethodData>, pub receipt_email: Option<pii::Email>, pub return_url: Option<url::Url>, @@ -123,17 +135,46 @@ pub struct StripeSetupIntentRequest { pub statement_descriptor_suffix: Option<String>, pub metadata: Option<api_models::payments::Metadata>, pub client_secret: Option<pii::Secret<String>>, + pub payment_method_options: Option<payment_intent::StripePaymentMethodOptions>, + pub payment_method: Option<String>, + pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } -impl From<StripeSetupIntentRequest> for payments::PaymentsRequest { - fn from(item: StripeSetupIntentRequest) -> Self { - Self { +impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest { + type Error = error_stack::Report<errors::ApiErrorResponse>; + fn try_from(item: StripeSetupIntentRequest) -> errors::RouterResult<Self> { + let (mandate_options, authentication_type) = match item.payment_method_options { + Some(pmo) => { + let payment_intent::StripePaymentMethodOptions::Card { + request_three_d_secure, + mandate_options, + }: payment_intent::StripePaymentMethodOptions = pmo; + ( + Option::<payments::MandateData>::foreign_try_from(( + mandate_options, + item.currency.to_owned(), + ))?, + Some(api_enums::AuthenticationType::foreign_from( + request_three_d_secure, + )), + ) + } + None => (None, None), + }; + let request = Ok(Self { amount: Some(api_types::Amount::Zero), - currency: Some(api_enums::Currency::default()), capture_method: None, amount_to_capture: None, confirm: item.confirm, customer_id: item.customer, + currency: item + .currency + .as_ref() + .map(|c| c.to_uppercase().parse_enum("currency")) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "currency", + })?, email: item.receipt_email, name: item .billing_details @@ -163,8 +204,13 @@ impl From<StripeSetupIntentRequest> for payments::PaymentsRequest { statement_descriptor_suffix: item.statement_descriptor_suffix, metadata: item.metadata, client_secret: item.client_secret.map(|s| s.peek().clone()), + setup_future_usage: item.setup_future_usage, + merchant_connector_details: item.merchant_connector_details, + authentication_type, + mandate_data: mandate_options, ..Default::default() - } + }); + request } } @@ -232,6 +278,32 @@ impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest { } } } +#[derive(Default, Eq, PartialEq, Serialize)] +pub struct RedirectUrl { + pub return_url: Option<String>, + pub url: Option<String>, +} + +#[derive(Eq, PartialEq, Serialize)] +pub struct StripeNextAction { + #[serde(rename = "type")] + stype: payments::NextActionType, + redirect_to_url: RedirectUrl, +} + +pub(crate) fn into_stripe_next_action( + next_action: Option<payments::NextAction>, + return_url: Option<String>, +) -> Option<StripeNextAction> { + next_action.map(|n| StripeNextAction { + stype: n.next_action_type, + redirect_to_url: RedirectUrl { + return_url, + url: n.redirect_to_url, + }, + }) +} + #[derive(Default, Eq, PartialEq, Serialize)] pub struct StripeSetupIntentResponse { pub id: Option<String>, @@ -241,8 +313,35 @@ pub struct StripeSetupIntentResponse { #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<time::PrimitiveDateTime>, pub customer: Option<String>, - pub refunds: Option<Vec<refunds::RefundResponse>>, + pub refunds: Option<Vec<stripe_refunds::StripeRefundResponse>>, pub mandate_id: Option<String>, + pub next_action: Option<StripeNextAction>, + pub last_payment_error: Option<LastPaymentError>, + pub charges: payment_intent::Charges, +} + +#[derive(Default, Eq, PartialEq, Serialize)] +pub struct LastPaymentError { + charge: Option<String>, + code: Option<String>, + decline_code: Option<String>, + message: String, + param: Option<String>, + payment_method: StripePaymentMethod, + #[serde(rename = "type")] + error_type: String, +} + +#[derive(Default, Eq, PartialEq, Serialize)] +pub struct StripePaymentMethod { + #[serde(rename = "id")] + payment_method_id: String, + object: &'static str, + card: Option<StripeCard>, + created: u64, + #[serde(rename = "type")] + method_type: String, + livemode: bool, } impl From<payments::PaymentsResponse> for StripeSetupIntentResponse { @@ -251,11 +350,36 @@ impl From<payments::PaymentsResponse> for StripeSetupIntentResponse { object: "setup_intent".to_owned(), status: StripeSetupStatus::from(resp.status), client_secret: resp.client_secret, + charges: payment_intent::Charges::new(), created: resp.created, customer: resp.customer_id, id: resp.payment_id, - refunds: resp.refunds, + refunds: resp + .refunds + .map(|a| a.into_iter().map(Into::into).collect()), mandate_id: resp.mandate_id, + next_action: into_stripe_next_action(resp.next_action, resp.return_url), + last_payment_error: resp.error_code.map(|code| -> LastPaymentError { + LastPaymentError { + charge: None, + code: Some(code.to_owned()), + decline_code: None, + message: resp + .error_message + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + param: None, + payment_method: StripePaymentMethod { + payment_method_id: "place_holder_id".to_string(), + object: "payment_method", + card: None, + created: u64::try_from(date_time::now().assume_utc().unix_timestamp()) + .unwrap_or_default(), + method_type: "card".to_string(), + livemode: false, + }, + error_type: code, + } + }), } } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index f246f9eb421..9a29cd23a1a 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -266,6 +266,7 @@ pub struct Jwekey { pub locker_decryption_key2: String, pub vault_encryption_key: String, pub vault_private_key: String, + pub tunnel_private_key: String, } #[derive(Debug, Deserialize, Clone, Default)] diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 2f74ad756cc..5e6797a0963 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -489,20 +489,22 @@ impl types::PaymentsResponseData: Clone, { let id = data.request.connector_transaction_id.clone(); - let response: transformers::PaymentIntentSyncResponse = - match id.get_connector_transaction_id() { - Ok(x) if x.starts_with("set") => res - .response - .parse_struct("SetupIntentSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed), - Ok(_) => res - .response - .parse_struct("PaymentIntentSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed), - Err(err) => { - Err(err).change_context(errors::ConnectorError::MissingConnectorTransactionID) - } - }?; + let response: transformers::PaymentIntentSyncResponse = match id + .get_connector_transaction_id() + { + Ok(x) if x.starts_with("set") => res + .response + .parse_struct::<transformers::SetupIntentSyncResponse>("SetupIntentSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .map(Into::into), + Ok(_) => res + .response + .parse_struct("PaymentIntentSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed), + Err(err) => { + Err(err).change_context(errors::ConnectorError::MissingConnectorTransactionID) + } + }?; types::RouterData::try_from(types::ResponseRouterData { response, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 536b29387af..e2d9d7f4d4c 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1,12 +1,14 @@ use std::borrow::Cow; -use base64::Engine; use common_utils::{ ext_traits::{AsyncExt, ByteSliceExt, ValueExt}, fp_utils, }; // TODO : Evaluate all the helper functions () use error_stack::{report, IntoReport, ResultExt}; +#[cfg(feature = "kms")] +use external_services::kms; +use josekit::jwe; use masking::{ExposeOptionInterface, PeekInterface}; use router_env::{instrument, tracing}; use storage_models::{enums, merchant_account, payment_intent}; @@ -1546,11 +1548,12 @@ impl MerchantConnectorAccountType { } pub async fn get_merchant_connector_account( - db: &dyn StorageInterface, + state: &AppState, merchant_id: &str, connector_label: &str, creds_identifier: Option<String>, ) -> RouterResult<MerchantConnectorAccountType> { + let db = &*state.store; match creds_identifier { Some(creds_identifier) => { let mca_config = db @@ -1560,20 +1563,35 @@ pub async fn get_merchant_connector_account( errors::ApiErrorResponse::MerchantConnectorAccountNotFound, )?; - let cached_mca = consts::BASE64_ENGINE - .decode(mca_config.config.as_bytes()) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "Failed to decode merchant_connector_details sent in request and then put in cache", - )? - .parse_struct("MerchantConnectorDetails") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "Failed to parse merchant_connector_details sent in request and then put in cache", - )?; + #[cfg(feature = "kms")] + let kms_config = &state.conf.kms; + + #[cfg(feature = "kms")] + let private_key = kms::get_kms_client(kms_config) + .await + .decrypt(state.conf.jwekey.tunnel_private_key.to_owned()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error getting tunnel private key")?; + + #[cfg(not(feature = "kms"))] + let private_key = state.conf.jwekey.tunnel_private_key.to_owned(); + + let decrypted_mca = services::decrypt_jwe(mca_config.config.as_str(), services::KeyIdCheck::SkipKeyIdCheck, private_key, jwe::RSA_OAEP_256) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed to decrypt merchant_connector_details sent in request and then put in cache", + )?; + + let res = String::into_bytes(decrypted_mca) + .parse_struct("MerchantConnectorDetails") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed to parse merchant_connector_details sent in request and then put in cache", + )?; - Ok(MerchantConnectorAccountType::CacheVal(cached_mca)) + Ok(MerchantConnectorAccountType::CacheVal(res)) } None => db .find_merchant_connector_account_by_merchant_id_connector_label( diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index ba8dcfd4748..83875ca8a27 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -44,9 +44,8 @@ where connector_id, ); - let db = &*state.store; merchant_connector_account = helpers::get_merchant_connector_account( - db, + state, merchant_account.merchant_id.as_str(), &connector_label, payment_data.creds_identifier.to_owned(), @@ -695,6 +694,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::VerifyRequestDat off_session: payment_data.mandate_id.as_ref().map(|_| true), mandate_id: payment_data.mandate_id.clone(), setup_mandate_details: payment_data.setup_mandate, + return_url: payment_data.payment_intent.return_url, }) } } diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index bed8baa7726..4611cc3ebc7 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -30,8 +30,6 @@ pub async fn construct_refund_router_data<'a, F>( refund: &'a storage::Refund, creds_identifier: Option<String>, ) -> RouterResult<types::RefundsRouterData<F>> { - let db = &*state.store; - let connector_label = helpers::get_connector_label( payment_intent.business_country, &payment_intent.business_label, @@ -40,7 +38,7 @@ pub async fn construct_refund_router_data<'a, F>( ); let merchant_connector_account = helpers::get_merchant_connector_account( - db, + state, merchant_account.merchant_id.as_str(), &connector_label, creds_identifier, @@ -234,7 +232,6 @@ pub async fn construct_accept_dispute_router_data<'a>( merchant_account: &storage::MerchantAccount, dispute: &storage::Dispute, ) -> RouterResult<types::AcceptDisputeRouterData> { - let db = &*state.store; let connector_id = &dispute.connector; let connector_label = helpers::get_connector_label( payment_intent.business_country, @@ -243,7 +240,7 @@ pub async fn construct_accept_dispute_router_data<'a>( connector_id, ); let merchant_connector_account = helpers::get_merchant_connector_account( - db, + state, merchant_account.merchant_id.as_str(), &connector_label, None, @@ -296,7 +293,6 @@ pub async fn construct_submit_evidence_router_data<'a>( dispute: &storage::Dispute, submit_evidence_request_data: types::SubmitEvidenceRequestData, ) -> RouterResult<types::SubmitEvidenceRouterData> { - let db = &*state.store; let connector_id = &dispute.connector; let connector_label = helpers::get_connector_label( payment_intent.business_country, @@ -305,7 +301,7 @@ pub async fn construct_submit_evidence_router_data<'a>( connector_id, ); let merchant_connector_account = helpers::get_merchant_connector_account( - db, + state, merchant_account.merchant_id.as_str(), &connector_label, None, @@ -356,7 +352,6 @@ pub async fn construct_upload_file_router_data<'a>( connector_id: &str, file_key: String, ) -> RouterResult<types::UploadFileRouterData> { - let db = &*state.store; let connector_label = helpers::get_connector_label( payment_intent.business_country, &payment_intent.business_label, @@ -364,7 +359,7 @@ pub async fn construct_upload_file_router_data<'a>( connector_id, ); let merchant_connector_account = helpers::get_merchant_connector_account( - db, + state, merchant_account.merchant_id.as_str(), &connector_label, None, @@ -418,7 +413,7 @@ pub async fn construct_defend_dispute_router_data<'a>( merchant_account: &storage::MerchantAccount, dispute: &storage::Dispute, ) -> RouterResult<types::DefendDisputeRouterData> { - let db = &*state.store; + let _db = &*state.store; let connector_id = &dispute.connector; let connector_label = helpers::get_connector_label( payment_intent.business_country, @@ -427,7 +422,7 @@ pub async fn construct_defend_dispute_router_data<'a>( connector_id, ); let merchant_connector_account = helpers::get_merchant_connector_account( - db, + state, merchant_account.merchant_id.as_str(), &connector_label, None, diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index aecbbfe6bd6..d67dd9f7b4e 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -299,6 +299,7 @@ pub struct VerifyRequestData { pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub setup_mandate_details: Option<payments::MandateData>, + pub return_url: Option<String>, } #[derive(Debug, Clone)]
feat
add mandates support in stripe compatibility (#897)
e3a33bb5c281ddf9c5746fad485bffa274a48b44
2023-08-01 17:58:46
SargamPuram
feat(pii): implement a masking strategy for UPI VPAs (#1641)
false
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 6e489ac492a..a184382e654 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -922,7 +922,7 @@ pub struct CryptoData { #[serde(rename_all = "snake_case")] pub struct UpiData { #[schema(value_type = Option<String>, example = "successtest@iata")] - pub vpa_id: Option<Secret<String>>, + pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs index fddbdcdab82..c246d204226 100644 --- a/crates/common_utils/src/pii.rs +++ b/crates/common_utils/src/pii.rs @@ -329,13 +329,33 @@ where } } +/// Strategy for masking UPI VPA's + +#[derive(Debug)] +pub struct UpiVpaMaskingStrategy; + +impl<T> Strategy<T> for UpiVpaMaskingStrategy +where + T: AsRef<str> + std::fmt::Debug, +{ + fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let vpa_str: &str = val.as_ref(); + if let Some((user_identifier, bank_or_psp)) = vpa_str.split_once('@') { + let masked_user_identifier = "*".repeat(user_identifier.len()); + write!(f, "{masked_user_identifier}@{bank_or_psp}") + } else { + WithType::fmt(val, f) + } + } +} + #[cfg(test)] mod pii_masking_strategy_tests { use std::str::FromStr; use masking::{ExposeInterface, Secret}; - use super::{ClientSecret, Email, IpAddress}; + use super::{ClientSecret, Email, IpAddress, UpiVpaMaskingStrategy}; use crate::pii::{EmailStrategy, REDACTED}; /* @@ -435,4 +455,16 @@ mod pii_masking_strategy_tests { let secret: Secret<String> = Secret::new("+40712345678".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } + + #[test] + fn test_valid_upi_vpa_masking() { + let secret: Secret<String, UpiVpaMaskingStrategy> = Secret::new("my_name@upi".to_string()); + assert_eq!("*******@upi", format!("{secret:?}")); + } + + #[test] + fn test_invalid_upi_vpa_masking() { + let secret: Secret<String, UpiVpaMaskingStrategy> = Secret::new("my_name_upi".to_string()); + assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); + } } diff --git a/crates/masking/src/abs.rs b/crates/masking/src/abs.rs index 43eeedcfde4..f50725d9f23 100644 --- a/crates/masking/src/abs.rs +++ b/crates/masking/src/abs.rs @@ -40,3 +40,25 @@ where self.inner_secret } } + +/// Interface that consumes a secret and converts it to a secret with a different masking strategy. +pub trait SwitchStrategy<FromStrategy, ToStrategy> { + /// The type returned by `switch_strategy()`. + type Output; + + /// Consumes the secret and converts it to a secret with a different masking strategy. + fn switch_strategy(self) -> Self::Output; +} + +impl<S, FromStrategy, ToStrategy> SwitchStrategy<FromStrategy, ToStrategy> + for Secret<S, FromStrategy> +where + FromStrategy: crate::Strategy<S>, + ToStrategy: crate::Strategy<S>, +{ + type Output = Secret<S, ToStrategy>; + + fn switch_strategy(self) -> Self::Output { + Secret::new(self.inner_secret) + } +} diff --git a/crates/masking/src/lib.rs b/crates/masking/src/lib.rs index d0452d5c5bc..8c5b03bd4f1 100644 --- a/crates/masking/src/lib.rs +++ b/crates/masking/src/lib.rs @@ -16,7 +16,7 @@ mod strategy; pub use strategy::{Strategy, WithType, WithoutType}; mod abs; -pub use abs::{ExposeInterface, ExposeOptionInterface, PeekInterface}; +pub use abs::{ExposeInterface, ExposeOptionInterface, PeekInterface, SwitchStrategy}; mod secret; mod strong_secret; diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index cdbb6bffdff..3cd51886508 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -5,7 +5,7 @@ use common_utils::{ crypto::Encryptable, date_time, ext_traits::StringExt, - pii::{IpAddress, SecretSerdeValue}, + pii::{IpAddress, SecretSerdeValue, UpiVpaMaskingStrategy}, }; use error_stack::{IntoReport, ResultExt}; use serde::{Deserialize, Serialize}; @@ -63,7 +63,7 @@ pub enum StripeWallet { #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripeUpi { - pub vpa_id: masking::Secret<String>, + pub vpa_id: masking::Secret<String, UpiVpaMaskingStrategy>, } #[derive(Debug, Default, Serialize, PartialEq, Eq, Deserialize, Clone)] diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index ff200a354c0..9ad5d845d4e 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use api_models::enums::PaymentMethod; -use masking::Secret; +use masking::{Secret, SwitchStrategy}; use serde::{Deserialize, Serialize}; use crate::{ @@ -90,9 +90,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for IatapayPaymentsRequest { }; let return_url = item.get_return_url()?; let payer_info = match item.request.payment_method_data.clone() { - api::PaymentMethodData::Upi(upi_data) => { - upi_data.vpa_id.map(|id| PayerInfo { token_id: id }) - } + api::PaymentMethodData::Upi(upi_data) => upi_data.vpa_id.map(|id| PayerInfo { + token_id: id.switch_strategy(), + }), _ => None, }; let amount =
feat
implement a masking strategy for UPI VPAs (#1641)
8c37a8d857c5a58872fa2b2e194b85e755129677
2023-11-30 18:51:51
Sakil Mostak
fix(connector): [Trustpay] Add mapping to error code `800.100.165` and `900.100.100` (#2925)
false
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index 5f3fb865d33..e985eff1197 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -499,6 +499,7 @@ fn is_payment_failed(payment_status: &str) -> (bool, &'static str) { true, "Transaction declined (maximum transaction frequency exceeded)", ), + "800.100.165" => (true, "Transaction declined (card lost)"), "800.100.168" => (true, "Transaction declined (restricted card)"), "800.100.170" => (true, "Transaction declined (transaction not permitted)"), "800.100.171" => (true, "transaction declined (pick up card)"), @@ -512,6 +513,10 @@ fn is_payment_failed(payment_status: &str) -> (bool, &'static str) { true, "Transaction for the same session is currently being processed, please try again later", ), + "900.100.100" => ( + true, + "Unexpected communication error with connector/acquirer", + ), "900.100.300" => (true, "Timeout, uncertain result"), _ => (false, ""), }
fix
[Trustpay] Add mapping to error code `800.100.165` and `900.100.100` (#2925)
278292322c7c06f4239dd73861469e436bd941fa
2023-11-05 17:15:56
Shivansh Bhatnagar
refactor(connector): [Stax] Currency Unit Conversion (#2711)
false
diff --git a/crates/router/src/connector/stax.rs b/crates/router/src/connector/stax.rs index 82a4c7ff323..7f5fde71938 100644 --- a/crates/router/src/connector/stax.rs +++ b/crates/router/src/connector/stax.rs @@ -70,6 +70,10 @@ impl ConnectorCommon for Stax { "stax" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -347,7 +351,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = stax::StaxPaymentsRequest::try_from(req)?; + let connector_router_data = stax::StaxRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let req_obj = stax::StaxPaymentsRequest::try_from(&connector_router_data)?; let stax_req = types::RequestBody::log_and_get_request_body( &req_obj, @@ -503,7 +513,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme &self, req: &types::PaymentsCaptureRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = stax::StaxCaptureRequest::try_from(req)?; + let connector_router_data = stax::StaxRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount_to_capture, + req, + ))?; + let connector_req = stax::StaxCaptureRequest::try_from(&connector_router_data)?; let stax_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<stax::StaxCaptureRequest>::encode_to_string_of_json, @@ -657,7 +673,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = stax::StaxRefundRequest::try_from(req)?; + let connector_router_data = stax::StaxRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let req_obj = stax::StaxRefundRequest::try_from(&connector_router_data)?; let stax_req = types::RequestBody::log_and_get_request_body( &req_obj, utils::Encode::<stax::StaxRefundRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index 4ee28be1937..f2aae442ddd 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -11,6 +11,37 @@ use crate::{ types::{self, api, storage::enums}, }; +#[derive(Debug, Serialize)] +pub struct StaxRouterData<T> { + pub amount: f64, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for StaxRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (currency_unit, currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?; + Ok(Self { + amount, + router_data: item, + }) + } +} + #[derive(Debug, Serialize)] pub struct StaxPaymentsRequestMetaData { tax: i64, @@ -26,21 +57,23 @@ pub struct StaxPaymentsRequest { idempotency_id: Option<String>, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest { +impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - if item.request.currency != enums::Currency::USD { + fn try_from( + item: &StaxRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + if item.router_data.request.currency != enums::Currency::USD { Err(errors::ConnectorError::NotSupported { - message: item.request.currency.to_string(), + message: item.router_data.request.currency.to_string(), connector: "Stax", })? } - let total = utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?; + let total = item.amount; - match item.request.payment_method_data.clone() { + match item.router_data.request.payment_method_data.clone() { api::PaymentMethodData::Card(_) => { - let pm_token = item.get_payment_method_token()?; - let pre_auth = !item.request.is_auto_capture()?; + let pm_token = item.router_data.get_payment_method_token()?; + let pre_auth = !item.router_data.request.is_auto_capture()?; Ok(Self { meta: StaxPaymentsRequestMetaData { tax: 0 }, total, @@ -52,14 +85,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest { Err(errors::ConnectorError::InvalidWalletToken)? } }), - idempotency_id: Some(item.connector_request_reference_id.clone()), + idempotency_id: Some(item.router_data.connector_request_reference_id.clone()), }) } api::PaymentMethodData::BankDebit( api_models::payments::BankDebitData::AchBankDebit { .. }, ) => { - let pm_token = item.get_payment_method_token()?; - let pre_auth = !item.request.is_auto_capture()?; + let pm_token = item.router_data.get_payment_method_token()?; + let pre_auth = !item.router_data.request.is_auto_capture()?; Ok(Self { meta: StaxPaymentsRequestMetaData { tax: 0 }, total, @@ -71,7 +104,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest { Err(errors::ConnectorError::InvalidWalletToken)? } }), - idempotency_id: Some(item.connector_request_reference_id.clone()), + idempotency_id: Some(item.router_data.connector_request_reference_id.clone()), }) } api::PaymentMethodData::BankDebit(_) @@ -347,13 +380,12 @@ pub struct StaxCaptureRequest { total: Option<f64>, } -impl TryFrom<&types::PaymentsCaptureRouterData> for StaxCaptureRequest { +impl TryFrom<&StaxRouterData<&types::PaymentsCaptureRouterData>> for StaxCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { - let total = utils::to_currency_base_unit_asf64( - item.request.amount_to_capture, - item.request.currency, - )?; + fn try_from( + item: &StaxRouterData<&types::PaymentsCaptureRouterData>, + ) -> Result<Self, Self::Error> { + let total = item.amount; Ok(Self { total: Some(total) }) } } @@ -365,15 +397,10 @@ pub struct StaxRefundRequest { pub total: f64, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for StaxRefundRequest { +impl<F> TryFrom<&StaxRouterData<&types::RefundsRouterData<F>>> for StaxRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { - Ok(Self { - total: utils::to_currency_base_unit_asf64( - item.request.refund_amount, - item.request.currency, - )?, - }) + fn try_from(item: &StaxRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { total: item.amount }) } }
refactor
[Stax] Currency Unit Conversion (#2711)
38bb7676be4015ee6e256110f564b7d573f89c91
2025-03-05 15:25:40
Gaurav Rawat
chore: address Rust 1.85.0 clippy lints (#7376)
false
diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs index 1497c9e3622..02c25d722c1 100644 --- a/crates/hyperswitch_domain_models/src/customer.rs +++ b/crates/hyperswitch_domain_models/src/customer.rs @@ -232,8 +232,8 @@ impl super::behaviour::Conversion for Customer { connector_customer: self.connector_customer, default_payment_method_id: self.default_payment_method_id, updated_by: self.updated_by, - default_billing_address: self.default_billing_address.map(Encryption::from), - default_shipping_address: self.default_shipping_address.map(Encryption::from), + default_billing_address: self.default_billing_address, + default_shipping_address: self.default_shipping_address, version: self.version, status: self.status, }) diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs index 6fa9f9450c8..fd8e144f4f2 100644 --- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs +++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs @@ -344,7 +344,7 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon connector, reason, status_code, - } => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), reason: reason.to_owned().map(Into::into), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)), + } => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), reason: reason.to_owned(), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)), Self::PaymentAuthorizationFailed { data } => { AER::BadRequest(ApiError::new("CE", 1, "Payment failed during authorization with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()}))) } diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 70051bdd504..dea34ecfdb0 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -283,11 +283,7 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentIntentRequest) -> errors::RouterResult<Self> { let routable_connector: Option<api_enums::RoutableConnectors> = - item.connector.and_then(|v| { - v.into_iter() - .next() - .map(api_enums::RoutableConnectors::from) - }); + item.connector.and_then(|v| v.into_iter().next()); let routing = routable_connector .map(|connector| { diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 0b3c6cdd596..3692dc14b91 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -179,11 +179,7 @@ impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripeSetupIntentRequest) -> errors::RouterResult<Self> { let routable_connector: Option<api_enums::RoutableConnectors> = - item.connector.and_then(|v| { - v.into_iter() - .next() - .map(api_enums::RoutableConnectors::from) - }); + item.connector.and_then(|v| v.into_iter().next()); let routing = routable_connector .map(|connector| { diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 157b8570522..ee99c7b8ab1 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -3755,8 +3755,7 @@ impl ProfileCreateBridge for api::ProfileCreate { collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector .or(Some(false)), - outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers - .map(Into::into), + outgoing_webhook_custom_http_headers, tax_connector_id: self.tax_connector_id, is_tax_connector_enabled: self.is_tax_connector_enabled, always_collect_billing_details_from_wallet_connector: self @@ -3904,8 +3903,7 @@ impl ProfileCreateBridge for api::ProfileCreate { collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector_if_required .or(Some(false)), - outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers - .map(Into::into), + outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self @@ -4211,8 +4209,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, - outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers - .map(Into::into), + outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self @@ -4345,8 +4342,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector_if_required, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, - outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers - .map(Into::into), + outgoing_webhook_custom_http_headers, order_fulfillment_time: self .order_fulfillment_time .map(|order_fulfillment_time| order_fulfillment_time.into_inner()), diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 353c980c769..6699cf70db0 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -197,10 +197,8 @@ impl CustomerCreateBridge for customers::CustomerRequest { customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { let address = self.get_address(); - let address_details = address.map(api_models::payments::AddressDetails::from); - Ok(services::ApplicationResponse::Json( - customers::CustomerResponse::foreign_from((customer.clone(), address_details)), + customers::CustomerResponse::foreign_from((customer.clone(), address)), )) } } @@ -1265,10 +1263,8 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest { customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { let address = self.get_address(); - let address_details = address.map(api_models::payments::AddressDetails::from); - Ok(services::ApplicationResponse::Json( - customers::CustomerResponse::foreign_from((customer.clone(), address_details)), + customers::CustomerResponse::foreign_from((customer.clone(), address)), )) } } diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 452364b654c..f30fbda5c57 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -922,7 +922,7 @@ pub async fn create_payment_method_core( merchant_id, key_store, merchant_account.storage_scheme, - payment_method_billing_address.map(Into::into), + payment_method_billing_address, ) .await .attach_printable("Failed to add Payment method to DB")?; @@ -1213,7 +1213,7 @@ pub async fn payment_method_intent_create( merchant_id, key_store, merchant_account.storage_scheme, - payment_method_billing_address.map(Into::into), + payment_method_billing_address, ) .await .attach_printable("Failed to add Payment method to DB")?; diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 1f37cc157e4..548007825e3 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -804,7 +804,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( payment_method_issuer: req.payment_method_issuer.clone(), scheme: req.card_network.clone().or(card.scheme.clone()), metadata: payment_method_metadata.map(Secret::new), - payment_method_data: payment_method_data_encrypted.map(Into::into), + payment_method_data: payment_method_data_encrypted, connector_mandate_details: connector_mandate_details.clone(), customer_acceptance: None, client_secret: None, @@ -823,7 +823,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( created_at: current_time, last_modified: current_time, last_used_at: current_time, - payment_method_billing_address: payment_method_billing_address.map(Into::into), + payment_method_billing_address, updated_by: None, version: domain::consts::API_VERSION, network_token_requestor_reference_id: None, @@ -1074,7 +1074,7 @@ pub async fn get_client_secret_or_add_payment_method( Some(enums::PaymentMethodStatus::AwaitingData), None, merchant_account.storage_scheme, - payment_method_billing_address.map(Into::into), + payment_method_billing_address, None, None, None, @@ -1167,7 +1167,7 @@ pub async fn get_client_secret_or_add_payment_method_for_migration( Some(enums::PaymentMethodStatus::AwaitingData), None, merchant_account.storage_scheme, - payment_method_billing_address.map(Into::into), + payment_method_billing_address, None, None, None, @@ -1687,7 +1687,7 @@ pub async fn add_payment_method( connector_mandate_details, req.network_transaction_id.clone(), merchant_account.storage_scheme, - payment_method_billing_address.map(Into::into), + payment_method_billing_address, None, None, None, @@ -1949,7 +1949,7 @@ pub async fn save_migration_payment_method( connector_mandate_details.clone(), network_transaction_id.clone(), merchant_account.storage_scheme, - payment_method_billing_address.map(Into::into), + payment_method_billing_address, None, None, None, diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 2dc118a60fe..d95e92115ad 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -283,7 +283,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata); // The operation merges mandate data from both request and payment_attempt - let setup_mandate = mandate_data.map(Into::into); + let setup_mandate = mandate_data; let mandate_details_present = payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 6bb923f82ee..662c02e523b 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -19,7 +19,7 @@ use diesel_models::{ }; use error_stack::{self, ResultExt}; use hyperswitch_domain_models::{ - mandates::{MandateData, MandateDetails}, + mandates::MandateDetails, payments::{ payment_attempt::PaymentAttempt, payment_intent::CustomerData, FromRequestEncryptablePaymentIntent, @@ -494,7 +494,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> .transpose()?; // The operation merges mandate data from both request and payment_attempt - let setup_mandate = mandate_data.map(MandateData::from); + let setup_mandate = mandate_data; let surcharge_details = request.surcharge_details.map(|request_surcharge_details| { payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt)) diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index e7cc8a41b85..498bda53f24 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -421,7 +421,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> .transpose()?; // The operation merges mandate data from both request and payment_attempt - let setup_mandate = mandate_data.map(Into::into); + let setup_mandate = mandate_data; let mandate_details_present = payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); helpers::validate_mandate_data_and_future_usage( diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 3baf72901e4..577c7ba53ef 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -394,21 +394,20 @@ where merchant_id, pm_metadata, customer_acceptance, - pm_data_encrypted.map(Into::into), + pm_data_encrypted, key_store, None, pm_status, network_transaction_id, merchant_account.storage_scheme, - encrypted_payment_method_billing_address - .map(Into::into), + encrypted_payment_method_billing_address, resp.card.and_then(|card| { card.card_network .map(|card_network| card_network.to_string()) }), network_token_requestor_ref_id, network_token_locker_id, - pm_network_token_data_encrypted.map(Into::into), + pm_network_token_data_encrypted, ) .await } else { @@ -513,14 +512,13 @@ where merchant_id, resp.metadata.clone().map(|val| val.expose()), customer_acceptance, - pm_data_encrypted.map(Into::into), + pm_data_encrypted, key_store, None, pm_status, network_transaction_id, merchant_account.storage_scheme, - encrypted_payment_method_billing_address - .map(Into::into), + encrypted_payment_method_billing_address, resp.card.and_then(|card| { card.card_network.map(|card_network| { card_network.to_string() @@ -528,7 +526,7 @@ where }), network_token_requestor_ref_id, network_token_locker_id, - pm_network_token_data_encrypted.map(Into::into), + pm_network_token_data_encrypted, ) .await } else { @@ -733,20 +731,20 @@ where merchant_id, pm_metadata, customer_acceptance, - pm_data_encrypted.map(Into::into), + pm_data_encrypted, key_store, None, pm_status, network_transaction_id, merchant_account.storage_scheme, - encrypted_payment_method_billing_address.map(Into::into), + encrypted_payment_method_billing_address, resp.card.and_then(|card| { card.card_network .map(|card_network| card_network.to_string()) }), network_token_requestor_ref_id, network_token_locker_id, - pm_network_token_data_encrypted.map(Into::into), + pm_network_token_data_encrypted, ) .await?; }; diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 34c4c76c2ed..c4aa8d2d490 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -4050,7 +4050,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz currency: payment_data.currency, browser_info, email: payment_data.email, - payment_method_data: payment_data.payment_method_data.map(From::from), + payment_method_data: payment_data.payment_method_data, connector_transaction_id: payment_data .payment_attempt .get_connector_payment_id() @@ -4144,7 +4144,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProce let amount = payment_data.payment_attempt.get_total_amount(); Ok(Self { - payment_method_data: payment_method_data.map(From::from), + payment_method_data, email: payment_data.email, currency: Some(payment_data.currency), amount: Some(amount.get_amount_as_i64()), // need to change this once we move to connector module diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 7eb7925017e..332137b6a18 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -556,7 +556,7 @@ pub async fn save_payout_data_to_locker( merchant_account.get_id(), None, None, - card_details_encrypted.clone().map(Into::into), + card_details_encrypted.clone(), key_store, connector_mandate_details, None, diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs index c6b6946d15c..995975d12e8 100644 --- a/crates/router/src/services/authorization/roles.rs +++ b/crates/router/src/services/authorization/roles.rs @@ -165,7 +165,7 @@ impl From<diesel_models::role::Role> for RoleInfo { Self { role_id: role.role_id, role_name: role.role_name, - groups: role.groups.into_iter().map(Into::into).collect(), + groups: role.groups, scope: role.scope, entity_type: role.entity_type, is_invitable: true, diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 67e8990e113..8c720875f16 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -411,7 +411,7 @@ pub async fn create_profile_from_merchant_account( always_collect_shipping_details_from_wallet_connector: request .always_collect_shipping_details_from_wallet_connector .or(Some(false)), - outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers.map(Into::into), + outgoing_webhook_custom_http_headers, tax_connector_id: request.tax_connector_id, is_tax_connector_enabled: request.is_tax_connector_enabled, dynamic_routing_algorithm: None,
chore
address Rust 1.85.0 clippy lints (#7376)
cc8847cce0022b375626b3c86e5b07048833be71
2023-09-12 22:12:01
DEEPANSHU BANSAL
fix(connector): [SQUARE] Throw Error for Partial Capture of Payments (#2133)
false
diff --git a/crates/router/src/connector/square.rs b/crates/router/src/connector/square.rs index 842c82b7b85..8f8e693bd38 100644 --- a/crates/router/src/connector/square.rs +++ b/crates/router/src/connector/square.rs @@ -567,6 +567,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme req: &types::PaymentsCaptureRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + if req.request.amount_to_capture != req.request.payment_amount { + Err(errors::ConnectorError::NotSupported { + message: "Partial Capture".to_string(), + connector: "Square", + })? + } Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) diff --git a/crates/router/tests/connectors/square.rs b/crates/router/tests/connectors/square.rs index 2d4797ced9e..ba7416c5a15 100644 --- a/crates/router/tests/connectors/square.rs +++ b/crates/router/tests/connectors/square.rs @@ -114,6 +114,7 @@ async fn should_capture_authorized_payment() { // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] +#[ignore = "Connector does not support partial capture"] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(
fix
[SQUARE] Throw Error for Partial Capture of Payments (#2133)
d6afbe8011feedfada7561499771eb4b9d031969
2022-12-12 15:36:45
ItsMeShashank
refactor(router): move api models into separate crate (#103)
false
diff --git a/Cargo.lock b/Cargo.lock index 47aea9f5a29..71bdc995eca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -307,6 +307,19 @@ version = "1.0.66" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "216261ddc8289130e551ddcd5ce8a064710c0d064a4d2895c67151c92b5443f6" +[[package]] +name = "api_models" +version = "0.1.0" +dependencies = [ + "common_utils", + "masking", + "router_derive", + "serde", + "serde_json", + "strum", + "time", +] + [[package]] name = "arc-swap" version = "1.5.1" @@ -905,6 +918,7 @@ dependencies = [ "error-stack", "fake", "masking", + "nanoid", "once_cell", "proptest", "regex", @@ -2599,6 +2613,7 @@ dependencies = [ "actix-http", "actix-rt", "actix-web", + "api_models", "async-bb8-diesel", "async-trait", "awc", @@ -2978,6 +2993,10 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" +[[package]] +name = "storage_models" +version = "0.1.0" + [[package]] name = "strsim" version = "0.8.0" diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml new file mode 100644 index 00000000000..adcb63e16b9 --- /dev/null +++ b/crates/api_models/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "api_models" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +serde = { version = "1.0.145", features = ["derive"] } +serde_json = "1.0.85" +strum = { version = "0.24.1", features = ["derive"] } +time = { version = "0.3.14", features = ["serde", "serde-well-known", "std"] } + +# First party crates +common_utils = { version = "0.1.0", path = "../common_utils" } +masking = { version = "0.1.0", path = "../masking" } +router_derive = { version = "0.1.0", path = "../router_derive" } diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs new file mode 100644 index 00000000000..b0b3ea2e433 --- /dev/null +++ b/crates/api_models/src/admin.rs @@ -0,0 +1,126 @@ +use common_utils::pii; +use masking::{Secret, StrongSecret}; +use serde::{Deserialize, Serialize}; + +pub use self::CreateMerchantAccount as MerchantAccountResponse; +use super::payments::AddressDetails; +use crate::enums as api_enums; + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct CreateMerchantAccount { + pub merchant_id: String, + pub merchant_name: Option<String>, + pub api_key: Option<StrongSecret<String>>, + pub merchant_details: Option<MerchantDetails>, + pub return_url: Option<String>, + pub webhook_details: Option<WebhookDetails>, + pub routing_algorithm: Option<api_enums::RoutingAlgorithm>, + pub custom_routing_rules: Option<Vec<CustomRoutingRules>>, + pub sub_merchants_enabled: Option<bool>, + pub parent_merchant_id: Option<String>, + pub enable_payment_response_hash: Option<bool>, + pub payment_response_hash_key: Option<String>, + pub redirect_to_merchant_with_http_post: Option<bool>, + pub metadata: Option<serde_json::Value>, + pub publishable_key: Option<String>, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct MerchantDetails { + pub primary_contact_person: Option<Secret<String>>, + pub primary_phone: Option<Secret<String>>, + pub primary_email: Option<Secret<String, pii::Email>>, + pub secondary_contact_person: Option<Secret<String>>, + pub secondary_phone: Option<Secret<String>>, + pub secondary_email: Option<Secret<String, pii::Email>>, + pub website: Option<String>, + pub about_business: Option<String>, + pub address: Option<AddressDetails>, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct WebhookDetails { + pub webhook_version: Option<String>, + pub webhook_username: Option<String>, + pub webhook_password: Option<Secret<String>>, + pub webhook_url: Option<Secret<String>>, + pub payment_created_enabled: Option<bool>, + pub payment_succeeded_enabled: Option<bool>, + pub payment_failed_enabled: Option<bool>, +} + +#[derive(Default, Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct CustomRoutingRules { + pub payment_methods_incl: Option<Vec<api_enums::PaymentMethodType>>, //FIXME Add enums for all PM enums + pub payment_methods_excl: Option<Vec<api_enums::PaymentMethodType>>, + pub payment_method_types_incl: Option<Vec<api_enums::PaymentMethodSubType>>, + pub payment_method_types_excl: Option<Vec<api_enums::PaymentMethodSubType>>, + pub payment_method_issuers_incl: Option<Vec<String>>, + pub payment_method_issuers_excl: Option<Vec<String>>, + pub countries_incl: Option<Vec<String>>, + pub countries_excl: Option<Vec<String>>, + pub currencies_incl: Option<Vec<api_enums::Currency>>, + pub currencies_excl: Option<Vec<api_enums::Currency>>, + pub metadata_filters_keys: Option<Vec<String>>, + pub metadata_filters_values: Option<Vec<String>>, + pub connectors_pecking_order: Option<Vec<String>>, + pub connectors_traffic_weightage_key: Option<Vec<String>>, + pub connectors_traffic_weightage_value: Option<Vec<i32>>, +} + +#[derive(Debug, Serialize)] +pub struct DeleteResponse { + pub merchant_id: String, + pub deleted: bool, +} + +#[derive(Default, Debug, Deserialize, Serialize)] +pub struct MerchantId { + pub merchant_id: String, +} + +#[derive(Default, Debug, Deserialize, Serialize)] +pub struct MerchantConnectorId { + pub merchant_id: String, + pub merchant_connector_id: i32, +} +//Merchant Connector Account CRUD +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PaymentConnectorCreate { + pub connector_type: api_enums::ConnectorType, + pub connector_name: String, + pub merchant_connector_id: Option<i32>, + pub connector_account_details: Option<Secret<serde_json::Value>>, + pub test_mode: Option<bool>, + pub disabled: Option<bool>, + pub payment_methods_enabled: Option<Vec<PaymentMethods>>, + pub metadata: Option<serde_json::Value>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PaymentMethods { + pub payment_method: api_enums::PaymentMethodType, + pub payment_method_types: Option<Vec<api_enums::PaymentMethodSubType>>, + pub payment_method_issuers: Option<Vec<String>>, + pub payment_schemes: Option<Vec<String>>, + pub accepted_currencies: Option<Vec<api_enums::Currency>>, + pub accepted_countries: Option<Vec<String>>, + pub minimum_amount: Option<i32>, + pub maximum_amount: Option<i32>, + pub recurring_enabled: bool, + pub installment_payment_enabled: bool, + pub payment_experience: Option<Vec<String>>, //TODO +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct DeleteMcaResponse { + pub merchant_id: String, + pub merchant_connector_id: i32, + pub deleted: bool, +} diff --git a/crates/api_models/src/bank_accounts.rs b/crates/api_models/src/bank_accounts.rs new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/crates/api_models/src/bank_accounts.rs @@ -0,0 +1 @@ + diff --git a/crates/api_models/src/cards.rs b/crates/api_models/src/cards.rs new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/crates/api_models/src/cards.rs @@ -0,0 +1 @@ + diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs new file mode 100644 index 00000000000..27611334fe0 --- /dev/null +++ b/crates/api_models/src/customers.rs @@ -0,0 +1,51 @@ +use common_utils::{consts, custom_serde, pii}; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Default, Clone, Deserialize, Serialize)] +pub struct CustomerRequest { + #[serde(default = "generate_customer_id")] + pub customer_id: String, + #[serde(default = "unknown_merchant", skip)] + pub merchant_id: String, + pub name: Option<String>, + pub email: Option<Secret<String, pii::Email>>, + pub phone: Option<Secret<String>>, + pub description: Option<String>, + pub phone_country_code: Option<String>, + pub address: Option<Secret<serde_json::Value>>, + pub metadata: Option<serde_json::Value>, +} + +#[derive(Debug, Clone, Serialize)] +pub struct CustomerResponse { + pub customer_id: String, + pub name: Option<String>, + pub email: Option<Secret<String, pii::Email>>, + pub phone: Option<Secret<String>>, + pub phone_country_code: Option<String>, + pub description: Option<String>, + pub address: Option<Secret<serde_json::Value>>, + #[serde(with = "custom_serde::iso8601")] + pub created_at: time::PrimitiveDateTime, + pub metadata: Option<serde_json::Value>, +} + +#[derive(Default, Debug, Deserialize, Serialize)] +pub struct CustomerId { + pub customer_id: String, +} + +#[derive(Default, Debug, Deserialize, Serialize)] +pub struct CustomerDeleteResponse { + pub customer_id: String, + pub deleted: bool, +} + +pub fn generate_customer_id() -> String { + common_utils::generate_id(consts::ID_LENGTH, "cus") +} + +fn unknown_merchant() -> String { + String::from("merchant_unknown") +} diff --git a/crates/api_models/src/disputes.rs b/crates/api_models/src/disputes.rs new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/crates/api_models/src/disputes.rs @@ -0,0 +1 @@ + diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs new file mode 100644 index 00000000000..b7738d8b075 --- /dev/null +++ b/crates/api_models/src/enums.rs @@ -0,0 +1,478 @@ +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum AttemptStatus { + Started, + AuthenticationFailed, + JuspayDeclined, + PendingVbv, + VbvSuccessful, + Authorized, + AuthorizationFailed, + Charged, + Authorizing, + CodInitiated, + Voided, + VoidInitiated, + CaptureInitiated, + CaptureFailed, + VoidFailed, + AutoRefunded, + PartialCharged, + #[default] + Pending, + Failure, + PaymentMethodAwaited, + ConfirmationAwaited, +} + +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum AuthenticationType { + #[default] + ThreeDs, + NoThreeDs, +} + +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum CaptureMethod { + #[default] + Automatic, + Manual, + ManualMultiple, + Scheduled, +} + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + strum::Display, + strum::EnumString, + serde::Deserialize, + serde::Serialize, +)] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum ConnectorType { + /// PayFacs, Acquirers, Gateways, BNPL etc + PaymentProcessor, + /// Fraud, Currency Conversion, Crypto etc + PaymentVas, + /// Accounting, Billing, Invoicing, Tax etc + FinOperations, + /// Inventory, ERP, CRM, KYC etc + FizOperations, + /// Payment Networks like Visa, MasterCard etc + Networks, + /// All types of banks including corporate / commercial / personal / neo banks + BankingEntities, + /// All types of non-banking financial institutions including Insurance, Credit / Lending etc + NonBankingFinance, +} + +#[allow(clippy::upper_case_acronyms)] +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +pub enum Currency { + AED, + ALL, + AMD, + ARS, + AUD, + AWG, + AZN, + BBD, + BDT, + BHD, + BMD, + BND, + BOB, + BRL, + BSD, + BWP, + BZD, + CAD, + CHF, + CNY, + COP, + CRC, + CUP, + CZK, + DKK, + DOP, + DZD, + EGP, + ETB, + EUR, + FJD, + GBP, + GHS, + GIP, + GMD, + GTQ, + GYD, + HKD, + HNL, + HRK, + HTG, + HUF, + IDR, + ILS, + INR, + JMD, + JOD, + JPY, + KES, + KGS, + KHR, + KRW, + KWD, + KYD, + KZT, + LAK, + LBP, + LKR, + LRD, + LSL, + MAD, + MDL, + MKD, + MMK, + MNT, + MOP, + MUR, + MVR, + MWK, + MXN, + MYR, + NAD, + NGN, + NIO, + NOK, + NPR, + NZD, + OMR, + PEN, + PGK, + PHP, + PKR, + PLN, + QAR, + RUB, + SAR, + SCR, + SEK, + SGD, + SLL, + SOS, + SSP, + SVC, + SZL, + THB, + TTD, + TWD, + TZS, + #[default] + USD, + UYU, + UZS, + YER, + ZAR, +} + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum EventType { + PaymentSucceeded, +} + +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum IntentStatus { + Succeeded, + Failed, + Cancelled, + Processing, + RequiresCustomerAction, + RequiresPaymentMethod, + #[default] + RequiresConfirmation, + RequiresCapture, +} + +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum FutureUsage { + #[default] + OffSession, + OnSession, +} + +#[derive( + Clone, + Copy, + Debug, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum PaymentMethodIssuerCode { + JpHdfc, + JpIcici, + JpGooglepay, + JpApplepay, + JpPhonepay, + JpWechat, + JpSofort, + JpGiropay, + JpSepa, + JpBacs, +} + +#[derive( + Clone, + Copy, + Debug, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum PaymentMethodSubType { + Credit, + Debit, + UpiIntent, + UpiCollect, + CreditCardInstallments, + PayLaterInstallments, +} + +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum PaymentMethodType { + Card, + PaymentContainer, + #[default] + BankTransfer, + BankDebit, + PayLater, + Netbanking, + Upi, + OpenBanking, + ConsumerFinance, + Wallet, + Klarna, + Paypal, +} + +#[derive( + Clone, + Copy, + Debug, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[serde(rename_all = "lowercase")] +#[strum(serialize_all = "lowercase")] +pub enum WalletIssuer { + GooglePay, + ApplePay, +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, strum::Display, strum::EnumString)] +#[strum(serialize_all = "snake_case")] +pub enum RefundStatus { + Failure, + ManualReview, + #[default] + Pending, + Success, + TransactionFailure, +} + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum RoutingAlgorithm { + RoundRobin, + MaxConversion, + MinCost, + Custom, +} + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + Default, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum MandateStatus { + #[default] + Active, + Inactive, + Pending, + Revoked, +} + +impl From<AttemptStatus> for IntentStatus { + fn from(s: AttemptStatus) -> Self { + match s { + AttemptStatus::Charged | AttemptStatus::AutoRefunded => IntentStatus::Succeeded, + + AttemptStatus::ConfirmationAwaited => IntentStatus::RequiresConfirmation, + AttemptStatus::PaymentMethodAwaited => IntentStatus::RequiresPaymentMethod, + + AttemptStatus::Authorized => IntentStatus::RequiresCapture, + AttemptStatus::PendingVbv => IntentStatus::RequiresCustomerAction, + + AttemptStatus::PartialCharged + | AttemptStatus::Started + | AttemptStatus::VbvSuccessful + | AttemptStatus::Authorizing + | AttemptStatus::CodInitiated + | AttemptStatus::VoidInitiated + | AttemptStatus::CaptureInitiated + | AttemptStatus::Pending => IntentStatus::Processing, + + AttemptStatus::AuthenticationFailed + | AttemptStatus::AuthorizationFailed + | AttemptStatus::VoidFailed + | AttemptStatus::JuspayDeclined + | AttemptStatus::CaptureFailed + | AttemptStatus::Failure => IntentStatus::Failed, + AttemptStatus::Voided => IntentStatus::Cancelled, + } + } +} diff --git a/crates/api_models/src/files.rs b/crates/api_models/src/files.rs new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/crates/api_models/src/files.rs @@ -0,0 +1 @@ + diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs new file mode 100644 index 00000000000..e5a864c7a45 --- /dev/null +++ b/crates/api_models/src/lib.rs @@ -0,0 +1,13 @@ +pub mod admin; +pub mod bank_accounts; +pub mod cards; +pub mod customers; +pub mod disputes; +pub mod enums; +pub mod files; +pub mod mandates; +pub mod payment_methods; +pub mod payments; +pub mod payouts; +pub mod refunds; +pub mod webhooks; diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs new file mode 100644 index 00000000000..5d6462fa946 --- /dev/null +++ b/crates/api_models/src/mandates.rs @@ -0,0 +1,37 @@ +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{enums as api_enums, payments}; + +#[derive(Default, Debug, Deserialize, Serialize)] +pub struct MandateId { + pub mandate_id: String, +} + +#[derive(Default, Debug, Deserialize, Serialize)] +pub struct MandateRevokedResponse { + pub mandate_id: String, + pub status: api_enums::MandateStatus, +} + +#[derive(Default, Debug, Deserialize, Serialize)] +pub struct MandateResponse { + pub mandate_id: String, + pub status: api_enums::MandateStatus, + pub payment_method_id: String, + pub payment_method: String, + pub card: Option<MandateCardDetails>, + pub customer_acceptance: Option<payments::CustomerAcceptance>, +} + +#[derive(Default, Debug, Deserialize, Serialize)] +pub struct MandateCardDetails { + pub last4_digits: Option<String>, + pub card_exp_month: Option<Secret<String>>, + pub card_exp_year: Option<Secret<String>>, + pub card_holder_name: Option<Secret<String>>, + pub card_token: Option<Secret<String>>, + pub scheme: Option<String>, + pub issuer_country: Option<String>, + pub card_fingerprint: Option<Secret<String>>, +} diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs new file mode 100644 index 00000000000..2f93df2f0b2 --- /dev/null +++ b/crates/api_models/src/payment_methods.rs @@ -0,0 +1,189 @@ +use common_utils::pii; +use masking::Secret; +use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; + +use crate::enums as api_enums; + +#[derive(Debug, Deserialize, Serialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct CreatePaymentMethod { + pub merchant_id: Option<String>, + pub payment_method: api_enums::PaymentMethodType, + pub payment_method_type: Option<api_enums::PaymentMethodSubType>, + pub payment_method_issuer: Option<String>, + pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, + pub card: Option<CardDetail>, + pub metadata: Option<serde_json::Value>, + pub customer_id: Option<String>, +} + +#[derive(Debug, Deserialize, Serialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct CardDetail { + pub card_number: Secret<String, pii::CardNumber>, + pub card_exp_month: Secret<String>, + pub card_exp_year: Secret<String>, + pub card_holder_name: Option<Secret<String>>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct PaymentMethodResponse { + pub payment_method_id: String, + pub payment_method: api_enums::PaymentMethodType, + pub payment_method_type: Option<api_enums::PaymentMethodSubType>, + pub payment_method_issuer: Option<String>, + pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, + pub card: Option<CardDetailFromLocker>, + //TODO: Populate this on request? + // pub accepted_country: Option<Vec<String>>, + // pub accepted_currency: Option<Vec<enums::Currency>>, + // pub minimum_amount: Option<i32>, + // pub maximum_amount: Option<i32>, + pub recurring_enabled: bool, + pub installment_payment_enabled: bool, + pub payment_experience: Option<Vec<String>>, //TODO change it to enum + pub metadata: Option<serde_json::Value>, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub created: Option<PrimitiveDateTime>, +} + +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct CardDetailFromLocker { + pub scheme: Option<String>, + pub issuer_country: Option<String>, + pub last4_digits: Option<String>, + #[serde(skip)] + pub card_number: Option<Secret<String, pii::CardNumber>>, + pub expiry_month: Option<Secret<String>>, + pub expiry_year: Option<Secret<String>>, + pub card_token: Option<Secret<String>>, + pub card_holder_name: Option<Secret<String>>, + pub card_fingerprint: Option<Secret<String>>, +} + +//List Payment Method +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ListPaymentMethodRequest { + pub accepted_countries: Option<Vec<String>>, + pub accepted_currencies: Option<Vec<api_enums::Currency>>, + pub amount: Option<i32>, + pub recurring_enabled: Option<bool>, + pub installment_payment_enabled: Option<bool>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct ListPaymentMethodResponse { + pub payment_method: api_enums::PaymentMethodType, + pub payment_method_types: Option<Vec<api_enums::PaymentMethodSubType>>, + pub payment_method_issuers: Option<Vec<String>>, + pub payment_method_issuer_code: Option<Vec<api_enums::PaymentMethodIssuerCode>>, + pub payment_schemes: Option<Vec<String>>, + pub accepted_countries: Option<Vec<String>>, + pub accepted_currencies: Option<Vec<api_enums::Currency>>, + pub minimum_amount: Option<i32>, + pub maximum_amount: Option<i32>, + pub recurring_enabled: bool, + pub installment_payment_enabled: bool, + pub payment_experience: Option<Vec<String>>, //TODO change it to enum +} + +#[derive(Debug, Serialize)] +pub struct ListCustomerPaymentMethodsResponse { + pub enabled_payment_methods: Vec<ListPaymentMethodResponse>, + pub customer_payment_methods: Vec<CustomerPaymentMethod>, +} + +#[derive(Debug, Serialize)] +pub struct DeletePaymentMethodResponse { + pub payment_method_id: String, + pub deleted: bool, +} + +#[derive(Debug, Serialize)] +pub struct CustomerPaymentMethod { + pub payment_token: String, + pub customer_id: String, + pub payment_method: api_enums::PaymentMethodType, + pub payment_method_type: Option<api_enums::PaymentMethodSubType>, + pub payment_method_issuer: Option<String>, + pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, + //TODO: Populate this on request? + // pub accepted_country: Option<Vec<String>>, + // pub accepted_currency: Option<Vec<enums::Currency>>, + // pub minimum_amount: Option<i32>, + // pub maximum_amount: Option<i32>, + pub recurring_enabled: bool, + pub installment_payment_enabled: bool, + pub payment_experience: Option<Vec<String>>, //TODO change it to enum + pub card: Option<CardDetailFromLocker>, + pub metadata: Option<serde_json::Value>, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub created: Option<PrimitiveDateTime>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct PaymentMethodId { + pub payment_method_id: String, +} + +//------------------------------------------------TokenizeService------------------------------------------------ +#[derive(Debug, Serialize, Deserialize)] +pub struct TokenizePayloadEncrypted { + pub payload: String, + pub key_id: String, + pub version: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct TokenizePayloadRequest { + pub value1: String, + pub value2: String, + pub lookup_key: String, + pub service_name: String, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct GetTokenizePayloadRequest { + pub lookup_key: String, + pub get_value2: bool, +} + +#[derive(Debug, Serialize)] +pub struct DeleteTokenizeByTokenRequest { + pub lookup_key: String, +} + +#[derive(Debug, Serialize)] //FIXME yet to be implemented +pub struct DeleteTokenizeByDateRequest { + pub buffer_minutes: i32, + pub service_name: String, + pub max_rows: i32, +} + +#[derive(Debug, Deserialize)] +pub struct GetTokenizePayloadResponse { + pub lookup_key: String, + pub get_value2: Option<bool>, +} +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TokenizedCardValue1 { + pub card_number: String, + pub exp_year: String, + pub exp_month: String, + pub name_on_card: Option<String>, + pub nickname: Option<String>, + pub card_last_four: Option<String>, + pub card_token: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TokenizedCardValue2 { + pub card_security_code: Option<String>, + pub card_fingerprint: Option<String>, + pub external_id: Option<String>, + pub customer_id: Option<String>, +} diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs new file mode 100644 index 00000000000..2e6991baea0 --- /dev/null +++ b/crates/api_models/src/payments.rs @@ -0,0 +1,843 @@ +use common_utils::pii; +use masking::{PeekInterface, Secret}; +use router_derive::Setter; +use time::PrimitiveDateTime; + +use crate::{enums as api_enums, refunds}; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum PaymentOp { + Create, + Update, + Confirm, +} + +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct PaymentsRequest { + #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] + pub payment_id: Option<PaymentIdType>, + pub merchant_id: Option<String>, + #[serde(default, deserialize_with = "amount::deserialize_option")] + pub amount: Option<Amount>, + pub currency: Option<String>, + pub capture_method: Option<api_enums::CaptureMethod>, + pub amount_to_capture: Option<i32>, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub capture_on: Option<PrimitiveDateTime>, + pub confirm: Option<bool>, + pub customer_id: Option<String>, + pub email: Option<Secret<String, pii::Email>>, + pub name: Option<Secret<String>>, + pub phone: Option<Secret<String>>, + pub phone_country_code: Option<String>, + pub off_session: Option<bool>, + pub description: Option<String>, + pub return_url: Option<String>, + pub setup_future_usage: Option<api_enums::FutureUsage>, + pub authentication_type: Option<api_enums::AuthenticationType>, + pub payment_method_data: Option<PaymentMethod>, + pub payment_method: Option<api_enums::PaymentMethodType>, + pub payment_token: Option<String>, + pub shipping: Option<Address>, + pub billing: Option<Address>, + pub statement_descriptor_name: Option<String>, + pub statement_descriptor_suffix: Option<String>, + pub metadata: Option<serde_json::Value>, + pub client_secret: Option<String>, + pub mandate_data: Option<MandateData>, + pub mandate_id: Option<String>, + pub browser_info: Option<serde_json::Value>, +} + +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] +pub enum Amount { + Value(i32), + #[default] + Zero, +} + +impl From<Amount> for i32 { + fn from(amount: Amount) -> Self { + match amount { + Amount::Value(v) => v, + Amount::Zero => 0, + } + } +} +impl From<i32> for Amount { + fn from(val: i32) -> Self { + match val { + 0 => Amount::Zero, + amount => Amount::Value(amount), + } + } +} + +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct PaymentsRedirectRequest { + pub payment_id: String, + pub merchant_id: String, + pub connector: String, + pub param: String, +} + +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct VerifyRequest { + // The merchant_id is generated through api key + // and is later passed in the struct + pub merchant_id: Option<String>, + pub customer_id: Option<String>, + pub email: Option<Secret<String, pii::Email>>, + pub name: Option<Secret<String>>, + pub phone: Option<Secret<String>>, + pub phone_country_code: Option<String>, + pub payment_method: Option<api_enums::PaymentMethodType>, + pub payment_method_data: Option<PaymentMethod>, + pub payment_token: Option<String>, + pub mandate_data: Option<MandateData>, + pub setup_future_usage: Option<api_enums::FutureUsage>, + pub off_session: Option<bool>, + pub client_secret: Option<String>, +} + +impl From<PaymentsRequest> for VerifyRequest { + fn from(item: PaymentsRequest) -> Self { + Self { + client_secret: item.client_secret, + merchant_id: item.merchant_id, + customer_id: item.customer_id, + email: item.email, + name: item.name, + phone: item.phone, + phone_country_code: item.phone_country_code, + payment_method: item.payment_method, + payment_method_data: item.payment_method_data, + payment_token: item.payment_token, + mandate_data: item.mandate_data, + setup_future_usage: item.setup_future_usage, + off_session: item.off_session, + } + } +} + +pub enum MandateTxnType { + NewMandateTxn, + RecurringMandateTxn, +} + +#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct MandateData { + pub customer_acceptance: CustomerAcceptance, + pub mandate_type: MandateType, +} + +#[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] +pub struct SingleUseMandate { + pub amount: i32, + pub currency: api_enums::Currency, +} + +#[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] +pub struct MandateAmountData { + pub amount: i32, + pub currency: api_enums::Currency, +} + +#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] +pub enum MandateType { + SingleUse(MandateAmountData), + MultiUse(Option<MandateAmountData>), +} + +impl Default for MandateType { + fn default() -> Self { + Self::MultiUse(None) + } +} + +#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct CustomerAcceptance { + pub acceptance_type: AcceptanceType, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub accepted_at: Option<PrimitiveDateTime>, + pub online: Option<OnlineMandate>, +} + +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone)] +#[serde(rename_all = "lowercase")] +pub enum AcceptanceType { + Online, + #[default] + Offline, +} + +#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct OnlineMandate { + pub ip_address: Secret<String, pii::IpAddress>, + pub user_agent: String, +} + +#[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct CCard { + pub card_number: Secret<String, pii::CardNumber>, + pub card_exp_month: Secret<String>, + pub card_exp_year: Secret<String>, + pub card_holder_name: Secret<String>, + pub card_cvc: Secret<String>, +} + +#[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct PayLaterData { + pub billing_email: String, + pub country: String, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub enum PaymentMethod { + #[serde(rename(deserialize = "card"))] + Card(CCard), + #[serde(rename(deserialize = "bank_transfer"))] + BankTransfer, + #[serde(rename(deserialize = "wallet"))] + Wallet(WalletData), + #[serde(rename(deserialize = "pay_later"))] + PayLater(PayLaterData), + #[serde(rename(deserialize = "paypal"))] + Paypal, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct WalletData { + pub issuer_name: api_enums::WalletIssuer, + pub token: String, +} + +#[derive(Eq, PartialEq, Clone, Debug, serde::Serialize)] +pub struct CCardResponse { + last4: String, + exp_month: String, + exp_year: String, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize)] +pub enum PaymentMethodDataResponse { + #[serde(rename = "card")] + Card(CCardResponse), + #[serde(rename(deserialize = "bank_transfer"))] + BankTransfer, + Wallet(WalletData), + PayLater(PayLaterData), + Paypal, +} + +impl Default for PaymentMethod { + fn default() -> Self { + PaymentMethod::BankTransfer + } +} + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum PaymentIdType { + PaymentIntentId(String), + ConnectorTransactionId(String), + PaymentTxnId(String), +} + +impl Default for PaymentIdType { + fn default() -> Self { + Self::PaymentIntentId(Default::default()) + } +} + +//#[derive(Debug, serde::Deserialize, serde::Serialize)] +//#[serde(untagged)] +//pub enum enums::CaptureMethod { +//Automatic, +//Manual, +//} + +//impl Default for enums::CaptureMethod { +//fn default() -> Self { +//enums::CaptureMethod::Manual +//} +//} + +#[derive(Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +pub struct Address { + pub address: Option<AddressDetails>, + pub phone: Option<PhoneDetails>, +} + +// used by customers also, could be moved outside +#[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct AddressDetails { + pub city: Option<String>, + pub country: Option<String>, + pub line1: Option<Secret<String>>, + pub line2: Option<Secret<String>>, + pub line3: Option<Secret<String>>, + pub zip: Option<Secret<String>>, + pub state: Option<Secret<String>>, + pub first_name: Option<Secret<String>>, + pub last_name: Option<Secret<String>>, +} + +#[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct PhoneDetails { + pub number: Option<Secret<String>>, + pub country_code: Option<String>, +} + +#[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize)] +pub struct PaymentsCaptureRequest { + pub payment_id: Option<String>, + pub merchant_id: Option<String>, + pub amount_to_capture: Option<i32>, + pub refund_uncaptured_amount: Option<bool>, + pub statement_descriptor_suffix: Option<String>, + pub statement_descriptor_prefix: Option<String>, +} + +#[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] +pub struct UrlDetails { + pub url: String, + pub method: String, +} +#[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] +pub struct AuthenticationForStartResponse { + pub authentication: UrlDetails, +} +#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum NextActionType { + RedirectToUrl, + DisplayQrCode, + InvokeSdkClient, + TriggerApi, +} +#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] +pub struct NextAction { + #[serde(rename = "type")] + pub next_action_type: NextActionType, + pub redirect_to_url: Option<String>, +} + +#[derive(Setter, Clone, Default, Debug, Eq, PartialEq, serde::Serialize)] +pub struct PaymentsResponse { + pub payment_id: Option<String>, + pub merchant_id: Option<String>, + pub status: api_enums::IntentStatus, + pub amount: i32, + pub amount_capturable: Option<i32>, + pub amount_received: Option<i32>, + pub client_secret: Option<Secret<String>>, + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub created: Option<PrimitiveDateTime>, + pub currency: String, + pub customer_id: Option<String>, + pub description: Option<String>, + pub refunds: Option<Vec<refunds::RefundResponse>>, + pub mandate_id: Option<String>, + pub mandate_data: Option<MandateData>, + pub setup_future_usage: Option<api_enums::FutureUsage>, + pub off_session: Option<bool>, + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub capture_on: Option<PrimitiveDateTime>, + pub capture_method: Option<api_enums::CaptureMethod>, + #[auth_based] + pub payment_method: Option<api_enums::PaymentMethodType>, + #[auth_based] + pub payment_method_data: Option<PaymentMethodDataResponse>, + pub payment_token: Option<String>, + pub shipping: Option<Address>, + pub billing: Option<Address>, + pub metadata: Option<serde_json::Value>, + pub email: Option<Secret<String, pii::Email>>, + pub name: Option<Secret<String>>, + pub phone: Option<Secret<String>>, + pub return_url: Option<String>, + pub authentication_type: Option<api_enums::AuthenticationType>, + pub statement_descriptor_name: Option<String>, + pub statement_descriptor_suffix: Option<String>, + pub next_action: Option<NextAction>, + pub cancellation_reason: Option<String>, + pub error_code: Option<String>, //TODO: Add error code column to the database + pub error_message: Option<String>, +} + +#[derive(Clone, Debug, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PaymentListConstraints { + pub customer_id: Option<String>, + pub starting_after: Option<String>, + pub ending_before: Option<String>, + #[serde(default = "default_limit")] + pub limit: i64, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub created: Option<PrimitiveDateTime>, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + #[serde(rename = "created.lt")] + pub created_lt: Option<PrimitiveDateTime>, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + #[serde(rename = "created.gt")] + pub created_gt: Option<PrimitiveDateTime>, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + #[serde(rename = "created.lte")] + pub created_lte: Option<PrimitiveDateTime>, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + #[serde(rename = "created.gte")] + pub created_gte: Option<PrimitiveDateTime>, +} + +#[derive(Clone, Debug, serde::Serialize)] +pub struct PaymentListResponse { + pub size: usize, + pub data: Vec<PaymentsResponse>, +} + +#[derive(Setter, Clone, Default, Debug, Eq, PartialEq, serde::Serialize)] +pub struct VerifyResponse { + pub verify_id: Option<String>, + pub merchant_id: Option<String>, + // pub status: enums::VerifyStatus, + pub client_secret: Option<Secret<String>>, + pub customer_id: Option<String>, + pub email: Option<Secret<String, pii::Email>>, + pub name: Option<Secret<String>>, + pub phone: Option<Secret<String>>, + pub mandate_id: Option<String>, + #[auth_based] + pub payment_method: Option<api_enums::PaymentMethodType>, + #[auth_based] + pub payment_method_data: Option<PaymentMethodDataResponse>, + pub payment_token: Option<String>, + pub error_code: Option<String>, + pub error_message: Option<String>, +} + +fn default_limit() -> i64 { + 10 +} + +#[derive(Default, Debug, serde::Deserialize, serde::Serialize)] +pub struct PaymentsRedirectionResponse { + pub redirect_url: String, +} + +pub struct MandateValidationFields { + pub mandate_id: Option<String>, + pub confirm: Option<bool>, + pub customer_id: Option<String>, + pub mandate_data: Option<MandateData>, + pub setup_future_usage: Option<api_enums::FutureUsage>, + pub off_session: Option<bool>, +} + +impl From<&PaymentsRequest> for MandateValidationFields { + fn from(req: &PaymentsRequest) -> Self { + Self { + mandate_id: req.mandate_id.clone(), + confirm: req.confirm, + customer_id: req.customer_id.clone(), + mandate_data: req.mandate_data.clone(), + setup_future_usage: req.setup_future_usage, + off_session: req.off_session, + } + } +} + +impl From<&VerifyRequest> for MandateValidationFields { + fn from(req: &VerifyRequest) -> Self { + Self { + mandate_id: None, + confirm: Some(true), + customer_id: req.customer_id.clone(), + mandate_data: req.mandate_data.clone(), + off_session: req.off_session, + setup_future_usage: req.setup_future_usage, + } + } +} + +impl From<PaymentsRequest> for PaymentsResponse { + fn from(item: PaymentsRequest) -> Self { + let payment_id = match item.payment_id { + Some(PaymentIdType::PaymentIntentId(id)) => Some(id), + _ => None, + }; + + Self { + payment_id, + merchant_id: item.merchant_id, + setup_future_usage: item.setup_future_usage, + off_session: item.off_session, + shipping: item.shipping, + billing: item.billing, + metadata: item.metadata, + capture_method: item.capture_method, + payment_method: item.payment_method, + capture_on: item.capture_on, + payment_method_data: item + .payment_method_data + .map(PaymentMethodDataResponse::from), + email: item.email, + name: item.name, + phone: item.phone, + payment_token: item.payment_token, + return_url: item.return_url, + authentication_type: item.authentication_type, + statement_descriptor_name: item.statement_descriptor_name, + statement_descriptor_suffix: item.statement_descriptor_suffix, + mandate_data: item.mandate_data, + ..Default::default() + } + } +} + +impl From<VerifyRequest> for VerifyResponse { + fn from(item: VerifyRequest) -> Self { + Self { + merchant_id: item.merchant_id, + customer_id: item.customer_id, + email: item.email, + name: item.name, + phone: item.phone, + payment_method: item.payment_method, + payment_method_data: item + .payment_method_data + .map(PaymentMethodDataResponse::from), + payment_token: item.payment_token, + ..Default::default() + } + } +} + +impl From<PaymentsStartRequest> for PaymentsResponse { + fn from(item: PaymentsStartRequest) -> Self { + Self { + payment_id: Some(item.payment_id), + merchant_id: Some(item.merchant_id), + ..Default::default() + } + } +} + +impl From<PaymentsSessionRequest> for PaymentsResponse { + fn from(item: PaymentsSessionRequest) -> Self { + let payment_id = match item.payment_id { + PaymentIdType::PaymentIntentId(id) => Some(id), + _ => None, + }; + + Self { + payment_id, + ..Default::default() + } + } +} + +impl From<PaymentsSessionRequest> for PaymentsSessionResponse { + fn from(_item: PaymentsSessionRequest) -> Self { + Self { + session_token: vec![], + } + } +} + +impl From<PaymentsStartRequest> for PaymentsRequest { + fn from(item: PaymentsStartRequest) -> Self { + Self { + payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), + merchant_id: Some(item.merchant_id), + ..Default::default() + } + } +} + +impl From<PaymentsRetrieveRequest> for PaymentsResponse { + // After removing the request from the payments_to_payments_response this will no longer be needed + fn from(item: PaymentsRetrieveRequest) -> Self { + let payment_id = match item.resource_id { + PaymentIdType::PaymentIntentId(id) => Some(id), + _ => None, + }; + + Self { + payment_id, + merchant_id: item.merchant_id, + ..Default::default() + } + } +} + +impl From<PaymentsCancelRequest> for PaymentsResponse { + fn from(item: PaymentsCancelRequest) -> Self { + Self { + payment_id: Some(item.payment_id), + cancellation_reason: item.cancellation_reason, + ..Default::default() + } + } +} + +impl From<PaymentsCaptureRequest> for PaymentsResponse { + // After removing the request from the payments_to_payments_response this will no longer be needed + fn from(item: PaymentsCaptureRequest) -> Self { + Self { + payment_id: item.payment_id, + amount_received: item.amount_to_capture, + ..Self::default() + } + } +} + +impl From<CCard> for CCardResponse { + fn from(card: CCard) -> Self { + let card_number_length = card.card_number.peek().clone().len(); + Self { + last4: card.card_number.peek().clone()[card_number_length - 4..card_number_length] + .to_string(), + exp_month: card.card_exp_month.peek().clone(), + exp_year: card.card_exp_year.peek().clone(), + } + } +} + +impl From<PaymentMethod> for PaymentMethodDataResponse { + fn from(payment_method_data: PaymentMethod) -> Self { + match payment_method_data { + PaymentMethod::Card(card) => PaymentMethodDataResponse::Card(CCardResponse::from(card)), + PaymentMethod::BankTransfer => PaymentMethodDataResponse::BankTransfer, + PaymentMethod::PayLater(pay_later_data) => { + PaymentMethodDataResponse::PayLater(pay_later_data) + } + PaymentMethod::Wallet(wallet_data) => PaymentMethodDataResponse::Wallet(wallet_data), + PaymentMethod::Paypal => PaymentMethodDataResponse::Paypal, + } + } +} + +#[derive(Debug, Clone, serde::Serialize)] +pub struct PgRedirectResponse { + pub payment_id: String, + pub status: api_enums::IntentStatus, + pub gateway_id: String, + pub customer_id: Option<String>, + pub amount: Option<i32>, +} + +#[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] +pub struct RedirectionResponse { + pub return_url: String, + pub params: Vec<(String, String)>, + pub return_url_with_query_params: String, + pub http_method: String, + pub headers: Vec<(String, String)>, +} + +#[derive(Debug, serde::Deserialize)] +pub struct PaymentsResponseForm { + pub transaction_id: String, + // pub transaction_reference_id: String, + pub merchant_id: String, + pub order_id: String, +} + +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] +pub struct PaymentsRetrieveRequest { + pub resource_id: PaymentIdType, + pub merchant_id: Option<String>, + pub force_sync: bool, + pub param: Option<String>, + pub connector: Option<String>, +} + +#[derive(Debug, Clone, serde::Serialize)] +pub struct ConnectorSessionToken { + pub connector_name: String, + pub session_token: String, +} + +#[derive(Default, Debug, serde::Deserialize, Clone)] +pub struct PaymentsSessionRequest { + pub payment_id: PaymentIdType, + pub client_secret: String, +} + +#[derive(Default, Debug, serde::Serialize, Clone)] +pub struct PaymentsSessionResponse { + pub session_token: Vec<ConnectorSessionToken>, +} + +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] +pub struct PaymentRetrieveBody { + pub merchant_id: Option<String>, + pub force_sync: Option<bool>, +} +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] +pub struct PaymentsCancelRequest { + #[serde(skip)] + pub payment_id: String, + pub cancellation_reason: Option<String>, +} + +#[derive(Default, Debug, serde::Deserialize, serde::Serialize)] +pub struct PaymentsStartRequest { + pub payment_id: String, + pub merchant_id: String, + pub txn_id: String, +} + +mod payment_id_type { + use std::fmt; + + use serde::{ + de::{self, Visitor}, + Deserializer, + }; + + use super::PaymentIdType; + + struct PaymentIdVisitor; + struct OptionalPaymentIdVisitor; + + impl<'de> Visitor<'de> for PaymentIdVisitor { + type Value = PaymentIdType; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("payment id") + } + + fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> + where + E: de::Error, + { + Ok(PaymentIdType::PaymentIntentId(value.to_string())) + } + } + + impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { + type Value = Option<PaymentIdType>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("payment id") + } + + fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_any(PaymentIdVisitor).map(Some) + } + + fn visit_none<E>(self) -> Result<Self::Value, E> + where + E: de::Error, + { + Ok(None) + } + + fn visit_unit<E>(self) -> Result<Self::Value, E> + where + E: de::Error, + { + Ok(None) + } + } + + #[allow(dead_code)] + pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> + where + D: Deserializer<'a>, + { + deserializer.deserialize_any(PaymentIdVisitor) + } + + pub(crate) fn deserialize_option<'a, D>( + deserializer: D, + ) -> Result<Option<PaymentIdType>, D::Error> + where + D: Deserializer<'a>, + { + deserializer.deserialize_option(OptionalPaymentIdVisitor) + } +} + +mod amount { + use serde::de; + + use super::Amount; + struct AmountVisitor; + struct OptionalAmountVisitor; + + // This is defined to provide guarded deserialization of amount + // which itself handles zero and non-zero values internally + impl<'de> de::Visitor<'de> for AmountVisitor { + type Value = Amount; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(formatter, "amount as integer") + } + + fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> + where + E: de::Error, + { + self.visit_i64(v as i64) + } + + fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> + where + E: de::Error, + { + Ok(match v { + 0 => Amount::Zero, + amount => Amount::Value(amount as i32), + }) + } + } + + impl<'de> de::Visitor<'de> for OptionalAmountVisitor { + type Value = Option<Amount>; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(formatter, "option of amount (as integer)") + } + + fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: serde::Deserializer<'de>, + { + deserializer.deserialize_i64(AmountVisitor).map(Some) + } + + fn visit_none<E>(self) -> Result<Self::Value, E> + where + E: de::Error, + { + Ok(None) + } + } + + #[allow(dead_code)] + pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> + where + D: de::Deserializer<'de>, + { + deserializer.deserialize_any(AmountVisitor) + } + pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> + where + D: de::Deserializer<'de>, + { + deserializer.deserialize_option(OptionalAmountVisitor) + } +} diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/crates/api_models/src/payouts.rs @@ -0,0 +1 @@ + diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs new file mode 100644 index 00000000000..2586b1a576e --- /dev/null +++ b/crates/api_models/src/refunds.rs @@ -0,0 +1,56 @@ +use serde::{Deserialize, Serialize}; + +use crate::enums; + +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RefundRequest { + pub refund_id: Option<String>, + pub payment_id: String, + pub merchant_id: Option<String>, + pub amount: Option<i32>, + pub reason: Option<String>, + //FIXME: Make it refund_type instant or scheduled refund + pub force_process: Option<bool>, + pub metadata: Option<serde_json::Value>, +} + +#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)] +pub struct RefundResponse { + pub refund_id: String, + pub payment_id: String, + pub amount: i32, + pub currency: String, + pub reason: Option<String>, + pub status: RefundStatus, + pub metadata: Option<serde_json::Value>, + pub error_message: Option<String>, +} + +#[derive(Debug, Eq, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum RefundStatus { + Succeeded, + Failed, + Pending, + Review, +} + +impl Default for RefundStatus { + fn default() -> Self { + RefundStatus::Pending + } +} + +impl From<enums::RefundStatus> for RefundStatus { + fn from(status: enums::RefundStatus) -> Self { + match status { + enums::RefundStatus::Failure | enums::RefundStatus::TransactionFailure => { + RefundStatus::Failed + } + enums::RefundStatus::ManualReview => RefundStatus::Review, + enums::RefundStatus::Pending => RefundStatus::Pending, + enums::RefundStatus::Success => RefundStatus::Succeeded, + } + } +} diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs new file mode 100644 index 00000000000..ddc4ffa13a8 --- /dev/null +++ b/crates/api_models/src/webhooks.rs @@ -0,0 +1,48 @@ +use common_utils::custom_serde; +use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; + +use crate::{enums as api_enums, payments}; + +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum IncomingWebhookEvent { + PaymentIntentSuccess, +} + +pub enum WebhookFlow { + Payment, + Refund, + Subscription, +} + +impl From<IncomingWebhookEvent> for WebhookFlow { + fn from(evt: IncomingWebhookEvent) -> Self { + match evt { + IncomingWebhookEvent::PaymentIntentSuccess => Self::Payment, + } + } +} + +pub type MerchantWebhookConfig = std::collections::HashSet<IncomingWebhookEvent>; + +pub struct IncomingWebhookDetails { + pub object_reference_id: String, + pub resource_object: Vec<u8>, +} + +#[derive(Debug, Clone, Serialize)] +pub struct OutgoingWebhook { + pub merchant_id: String, + pub event_id: String, + pub event_type: api_enums::EventType, + pub content: OutgoingWebhookContent, + #[serde(default, with = "custom_serde::iso8601")] + pub timestamp: PrimitiveDateTime, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(tag = "type", content = "object", rename_all = "snake_case")] +pub enum OutgoingWebhookContent { + PaymentDetails(payments::PaymentsResponse), +} diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index 6080e6f33e8..569fdd39a53 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -10,6 +10,7 @@ license = "Apache-2.0" [dependencies] bytes = "1.3.0" error-stack = "0.2.4" +nanoid = "0.4.0" once_cell = "1.16.0" regex = "1.7.0" serde = { version = "1.0.149", features = ["derive"] } diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs new file mode 100644 index 00000000000..5ba50fb56ba --- /dev/null +++ b/crates/common_utils/src/consts.rs @@ -0,0 +1,12 @@ +//! Commonly used constants + +/// Number of characters in a generated ID +pub const ID_LENGTH: usize = 20; + +/// Characters to use for generating NanoID +pub(crate) const ALPHABETS: [char; 62] = [ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', + 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', + 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', + 'V', 'W', 'X', 'Y', 'Z', +]; diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs index d20570b28c4..85cdbfe8072 100644 --- a/crates/common_utils/src/lib.rs +++ b/crates/common_utils/src/lib.rs @@ -13,6 +13,7 @@ )] #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))] +pub mod consts; pub mod custom_serde; pub mod errors; pub mod ext_traits; @@ -29,3 +30,16 @@ pub mod date_time { PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time()) } } + +/// Generate a nanoid with the given prefix and length +#[inline] +pub fn generate_id(length: usize, prefix: &str) -> String { + format!("{}_{}", prefix, nanoid::nanoid!(length, &consts::ALPHABETS)) +} + +/// Generate a nanoid with the given prefix and a default length +#[inline] +pub fn generate_id_with_default_len(prefix: &str) -> String { + let len = consts::ID_LENGTH; + format!("{}_{}", prefix, nanoid::nanoid!(len, &consts::ALPHABETS)) +} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index bf151521417..f1c78431c50 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -63,6 +63,7 @@ url = { version = "2.3.1", features = ["serde"] } uuid = { version = "1.2.2", features = ["serde", "v4"] } # First party crates +api_models = { version = "0.1.0", path = "../api_models" } common_utils = { version = "0.1.0", path = "../common_utils" } masking = { version = "0.1.0", path = "../masking" } redis_interface = { version = "0.1.0", path = "../redis_interface" } diff --git a/crates/router/src/compatibility/stripe/customers/types.rs b/crates/router/src/compatibility/stripe/customers/types.rs index e5b5be732a0..8b1716d7e74 100644 --- a/crates/router/src/compatibility/stripe/customers/types.rs +++ b/crates/router/src/compatibility/stripe/customers/types.rs @@ -58,7 +58,7 @@ pub(crate) struct CustomerDeleteResponse { impl From<CreateCustomerRequest> for api::CustomerRequest { fn from(req: CreateCustomerRequest) -> Self { Self { - customer_id: api::generate_customer_id(), + customer_id: api_models::customers::generate_customer_id(), name: req.name, phone: req.phone, email: req.email, @@ -86,6 +86,7 @@ impl From<CustomerUpdateRequest> for api::CustomerRequest { impl From<api::CustomerResponse> for CreateCustomerResponse { fn from(cust: api::CustomerResponse) -> Self { + let cust = cust.into_inner(); Self { id: cust.customer_id, object: "customer".to_owned(), diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index c5d0acdd898..6a4617be6c8 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -5,7 +5,10 @@ use crate::{ core::errors::{self, RouterResponse, StorageErrorExt}, db::StorageInterface, services, - types::{api::customers, storage}, + types::{ + api::customers::{self, CustomerRequestExt}, + storage, + }, }; #[instrument(skip(db))] diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index 42a54646e69..6f78f869a32 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -7,7 +7,10 @@ use crate::{ routes::AppState, services, types::{ - api::{customers, mandates}, + api::{ + customers, + mandates::{self, MandateResponseExt}, + }, storage, }, }; diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index c94da51c1cd..d0bc34ba327 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -16,7 +16,7 @@ use crate::{ routes::AppState, services, types::{ - api, + api::{self, CreatePaymentMethodExt}, storage::{self, enums}, }, utils::{self, BytesExt, OptionExt, StringExt, ValueExt}, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 9b6da9716c8..61a47e4bc23 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -32,7 +32,7 @@ use crate::{ services, types::{ self, - api::{self, PaymentsResponse, PaymentsRetrieveRequest}, + api::{self, PaymentIdTypeExt, PaymentsResponse, PaymentsRetrieveRequest}, storage::{self, enums}, }, utils::{self, OptionExt}, @@ -406,7 +406,7 @@ where { payment_data .sessions_token - .push(types::ConnectorSessionToken { + .push(api::ConnectorSessionToken { connector_name, session_token, }); @@ -462,7 +462,7 @@ where pub force_sync: Option<bool>, pub payment_method_data: Option<api::PaymentMethod>, pub refunds: Vec<storage::Refund>, - pub sessions_token: Vec<types::ConnectorSessionToken>, + pub sessions_token: Vec<api::ConnectorSessionToken>, } #[derive(Debug)] diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 9e1c146db2b..b1805c5d1f0 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -22,7 +22,7 @@ use crate::{ services, types::{ self, - api::{self, enums as api_enums}, + api::{self, enums as api_enums, CustomerAcceptanceExt, MandateValidationFieldsExt}, storage::{self, enums as storage_enums, ephemeral_key}, }, utils::{ @@ -1092,9 +1092,9 @@ pub fn make_url_with_signature( params: parameters, return_url_with_query_params: url.to_string(), http_method: if merchant_account.redirect_to_merchant_with_http_post { - services::Method::Post + services::Method::Post.to_string() } else { - services::Method::Get + services::Method::Get.to_string() }, headers: Vec::new(), }) @@ -1160,14 +1160,14 @@ pub fn generate_mandate( Some(match data.mandate_type { api::MandateType::SingleUse(data) => new_mandate .set_mandate_amount(Some(data.amount)) - .set_mandate_currency(Some(data.currency)) + .set_mandate_currency(Some(data.currency.into())) .set_mandate_type(storage_enums::MandateType::SingleUse) .to_owned(), api::MandateType::MultiUse(op_data) => match op_data { Some(data) => new_mandate .set_mandate_amount(Some(data.amount)) - .set_mandate_currency(Some(data.currency)), + .set_mandate_currency(Some(data.currency.into())), None => &mut new_mandate, } .set_mandate_type(storage_enums::MandateType::MultiUse) diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index c99c92c054b..2bb11f5222c 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -14,7 +14,7 @@ use crate::{ db::StorageInterface, routes::AppState, types::{ - api, + api::{self, PaymentIdTypeExt}, storage::{self, enums, Customer}, }, utils::OptionExt, diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index bfad77e603f..95fe0858dc4 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -13,8 +13,7 @@ use crate::{ db::StorageInterface, routes::AppState, types::{ - api, - api::PaymentsCaptureRequest, + api::{self, PaymentIdTypeExt, PaymentsCaptureRequest}, storage::{self, enums}, }, utils::OptionExt, diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index b4a062806c1..0e0ada459c2 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -15,7 +15,8 @@ use crate::{ db::StorageInterface, routes::AppState, types::{ - self, api, + self, + api::{self, PaymentIdTypeExt}, storage::{self, enums}, }, utils::{self, OptionExt}, diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 3d1b1cde4c7..9233979645c 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -17,7 +17,8 @@ use crate::{ db::StorageInterface, routes::AppState, types::{ - self, api, + self, + api::{self, PaymentIdTypeExt}, storage::{ self, enums::{self, IntentStatus}, diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs index 76f7110e7ae..3c91337730c 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -19,7 +19,7 @@ use crate::{ routes::AppState, types::{ self, - api::{self, enums as api_enums}, + api::{self, enums as api_enums, PaymentIdTypeExt}, storage::{self, enums as storage_enums}, }, utils, diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 8b777a06bc7..c87b17b2058 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -14,7 +14,7 @@ use crate::{ db::StorageInterface, routes::AppState, types::{ - api, + api::{self, PaymentIdTypeExt}, storage::{self, enums}, }, utils::OptionExt, diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 17e66296a5f..c4dcaf29fcc 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -14,7 +14,7 @@ use crate::{ db::StorageInterface, routes::AppState, types::{ - api, + api::{self, PaymentIdTypeExt}, storage::{self, enums, Customer}, }, utils::OptionExt, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 09b8ed76e89..21e37d1907b 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -15,7 +15,7 @@ use crate::{ db::StorageInterface, routes::AppState, types::{ - api, + api::{self, PaymentIdTypeExt}, storage::{self, enums}, }, utils::{OptionExt, StringExt}, diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index c918af20f97..06afd4d62e9 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -27,6 +27,7 @@ pub mod core; pub mod cors; pub mod db; pub mod env; +pub(crate) mod macros; pub mod routes; pub mod scheduler; diff --git a/crates/router/src/macros.rs b/crates/router/src/macros.rs new file mode 100644 index 00000000000..3cf687099d5 --- /dev/null +++ b/crates/router/src/macros.rs @@ -0,0 +1,46 @@ +#[macro_export] +macro_rules! newtype_impl { + ($is_pub:vis, $name:ident, $ty_path:path) => { + impl std::ops::Deref for $name { + type Target = $ty_path; + + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + impl std::ops::DerefMut for $name { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } + } + + impl From<$ty_path> for $name { + fn from(ty: $ty_path) -> Self { + Self(ty) + } + } + + impl $name { + pub fn into_inner(self) -> $ty_path { + self.0 + } + } + }; +} + +#[macro_export] +macro_rules! newtype { + ($is_pub:vis $name:ident = $ty_path:path) => { + $is_pub struct $name(pub $ty_path); + + $crate::newtype_impl!($is_pub, $name, $ty_path); + }; + + ($is_pub:vis $name:ident = $ty_path:path, derives = ($($trt:path),*)) => { + #[derive($($trt),*)] + $is_pub struct $name(pub $ty_path); + + $crate::newtype_impl!($is_pub, $name, $ty_path); + }; +} diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 03e8cdcffa7..571a11b4232 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -121,12 +121,6 @@ pub struct PaymentsSessionData { //TODO: Add the fields here as required } -#[derive(Debug, Clone, serde::Serialize)] -pub struct ConnectorSessionToken { - pub connector_name: String, - pub session_token: String, -} - #[derive(serde::Serialize, Debug)] pub struct PaymentsSessionResponseData { pub client_token: Option<String>, diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 7dd16e9dc5c..3de3da61330 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -1,127 +1,62 @@ -use serde::{Deserialize, Serialize}; - -pub use self::CreateMerchantAccount as MerchantAccountResponse; -use super::payments::AddressDetails; -use crate::{ - pii::{self, Secret, StrongSecret}, - types::api::enums as api_enums, +pub use api_models::admin::{ + CreateMerchantAccount, CustomRoutingRules, DeleteMcaResponse, DeleteResponse, + MerchantConnectorId, MerchantDetails, MerchantId, PaymentConnectorCreate, PaymentMethods, + WebhookDetails, }; -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -pub struct CreateMerchantAccount { - pub merchant_id: String, - pub merchant_name: Option<String>, - pub api_key: Option<StrongSecret<String>>, - pub merchant_details: Option<MerchantDetails>, - pub return_url: Option<String>, - pub webhook_details: Option<WebhookDetails>, - pub routing_algorithm: Option<api_enums::RoutingAlgorithm>, - pub custom_routing_rules: Option<Vec<CustomRoutingRules>>, - pub sub_merchants_enabled: Option<bool>, - pub parent_merchant_id: Option<String>, - pub enable_payment_response_hash: Option<bool>, - pub payment_response_hash_key: Option<String>, - pub redirect_to_merchant_with_http_post: Option<bool>, - pub metadata: Option<serde_json::Value>, - pub publishable_key: Option<String>, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -pub struct MerchantDetails { - pub primary_contact_person: Option<Secret<String>>, - pub primary_phone: Option<Secret<String>>, - pub primary_email: Option<Secret<String, pii::Email>>, - pub secondary_contact_person: Option<Secret<String>>, - pub secondary_phone: Option<Secret<String>>, - pub secondary_email: Option<Secret<String, pii::Email>>, - pub website: Option<String>, - pub about_business: Option<String>, - pub address: Option<AddressDetails>, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -pub struct WebhookDetails { - pub webhook_version: Option<String>, - pub webhook_username: Option<String>, - pub webhook_password: Option<Secret<String>>, - pub webhook_url: Option<Secret<String>>, - pub payment_created_enabled: Option<bool>, - pub payment_succeeded_enabled: Option<bool>, - pub payment_failed_enabled: Option<bool>, -} - -#[derive(Default, Clone, Debug, Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -pub struct CustomRoutingRules { - pub payment_methods_incl: Option<Vec<api_enums::PaymentMethodType>>, //FIXME Add enums for all PM enums - pub payment_methods_excl: Option<Vec<api_enums::PaymentMethodType>>, - pub payment_method_types_incl: Option<Vec<api_enums::PaymentMethodSubType>>, - pub payment_method_types_excl: Option<Vec<api_enums::PaymentMethodSubType>>, - pub payment_method_issuers_incl: Option<Vec<String>>, - pub payment_method_issuers_excl: Option<Vec<String>>, - pub countries_incl: Option<Vec<String>>, - pub countries_excl: Option<Vec<String>>, - pub currencies_incl: Option<Vec<api_enums::Currency>>, - pub currencies_excl: Option<Vec<api_enums::Currency>>, - pub metadata_filters_keys: Option<Vec<String>>, - pub metadata_filters_values: Option<Vec<String>>, - pub connectors_pecking_order: Option<Vec<String>>, - pub connectors_traffic_weightage_key: Option<Vec<String>>, - pub connectors_traffic_weightage_value: Option<Vec<i32>>, -} - -#[derive(Debug, Serialize)] -pub struct DeleteResponse { - pub merchant_id: String, - pub deleted: bool, -} - -#[derive(Default, Debug, Deserialize, Serialize)] -pub struct MerchantId { - pub merchant_id: String, -} - -#[derive(Default, Debug, Deserialize, Serialize)] -pub struct MerchantConnectorId { - pub merchant_id: String, - pub merchant_connector_id: i32, -} -//Merchant Connector Account CRUD -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct PaymentConnectorCreate { - pub connector_type: api_enums::ConnectorType, - pub connector_name: String, - pub merchant_connector_id: Option<i32>, - pub connector_account_details: Option<Secret<serde_json::Value>>, - pub test_mode: Option<bool>, - pub disabled: Option<bool>, - pub payment_methods_enabled: Option<Vec<PaymentMethods>>, - pub metadata: Option<serde_json::Value>, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct PaymentMethods { - pub payment_method: api_enums::PaymentMethodType, - pub payment_method_types: Option<Vec<api_enums::PaymentMethodSubType>>, - pub payment_method_issuers: Option<Vec<String>>, - pub payment_schemes: Option<Vec<String>>, - pub accepted_currencies: Option<Vec<api_enums::Currency>>, - pub accepted_countries: Option<Vec<String>>, - pub minimum_amount: Option<i32>, - pub maximum_amount: Option<i32>, - pub recurring_enabled: bool, - pub installment_payment_enabled: bool, - pub payment_experience: Option<Vec<String>>, //TODO -} +//use serde::{Serialize, Deserialize}; +pub use self::CreateMerchantAccount as MerchantAccountResponse; -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct DeleteMcaResponse { - pub merchant_id: String, - pub merchant_connector_id: i32, - pub deleted: bool, -} +//use crate::newtype; + +//use api_models::admin; + +//newtype!( +//pub CreateMerchantAccount = admin::CreateMerchantAccount, +//derives = (Clone, Debug, Deserialize, Serialize) +//); + +//newtype!( +//pub MerchantDetails = admin::MerchantDetails, +//derives = (Clone, Debug, Deserialize, Serialize) +//); + +//newtype!( +//pub WebhookDetails = admin::WebhookDetails, +//derives = (Clone, Debug, Deserialize, Serialize) +//); + +//newtype!( +//pub CustomRoutingRules = admin::CustomRoutingRules, +//derives = (Default, Clone, Debug, Deserialize, Serialize) +//); + +//newtype!( +//pub DeleteResponse = admin::DeleteResponse, +//derives = (Debug, Serialize) +//); + +//newtype!( +//pub MerchantId = admin::MerchantId, +//derives = (Default, Debug, Deserialize, Serialize) +//); + +//newtype!( +//pub MerchantConnectorId = admin::MerchantConnectorId, +//derives = (Default, Debug, Deserialize, Serialize) +//); + +//newtype!( +//pub PaymentConnectorCreate = admin::PaymentConnectorCreate, +//derives = (Debug, Clone, Serialize, Deserialize) +//); + +//newtype!( +//pub PaymentMethods = admin::PaymentMethods, +//derives = (Debug, Clone, Serialize, Deserialize) +//); + +//newtype!( +//pub DeleteMcaResponse = admin::DeleteMcaResponse, +//derives = (Debug, Clone, Serialize, Deserialize) +//); diff --git a/crates/router/src/types/api/customers.rs b/crates/router/src/types/api/customers.rs index 18003073696..6cd0edd7e14 100644 --- a/crates/router/src/types/api/customers.rs +++ b/crates/router/src/types/api/customers.rs @@ -1,31 +1,27 @@ -use common_utils::custom_serde; +use api_models::customers; +pub use api_models::customers::{CustomerDeleteResponse, CustomerId, CustomerRequest}; use error_stack::ResultExt; -use serde::{Deserialize, Serialize}; +use serde::Serialize; use crate::{ - consts, core::errors::{self, RouterResult}, - pii::{self, PeekInterface, Secret}, + newtype, + pii::PeekInterface, types::storage, utils::{self, ValidateCall}, }; -#[derive(Debug, Default, Clone, Deserialize, Serialize)] -pub struct CustomerRequest { - #[serde(default = "generate_customer_id")] - pub customer_id: String, - #[serde(default = "unknown_merchant", skip)] - pub merchant_id: String, - pub name: Option<String>, - pub email: Option<Secret<String, pii::Email>>, - pub phone: Option<Secret<String>>, - pub description: Option<String>, - pub phone_country_code: Option<String>, - pub metadata: Option<serde_json::Value>, +newtype!( + pub CustomerResponse = customers::CustomerResponse, + derives = (Debug, Clone, Serialize) +); + +pub(crate) trait CustomerRequestExt: Sized { + fn validate(self) -> RouterResult<Self>; } -impl CustomerRequest { - pub(crate) fn validate(self) -> RouterResult<Self> { +impl CustomerRequestExt for CustomerRequest { + fn validate(self) -> RouterResult<Self> { self.email .as_ref() .validate_opt(|email| utils::validate_email(email.peek())) @@ -38,22 +34,9 @@ impl CustomerRequest { } } -#[derive(Debug, Clone, Serialize)] -pub struct CustomerResponse { - pub customer_id: String, - pub name: Option<String>, - pub email: Option<Secret<String, pii::Email>>, - pub phone: Option<Secret<String>>, - pub phone_country_code: Option<String>, - pub description: Option<String>, - #[serde(with = "custom_serde::iso8601")] - pub created_at: time::PrimitiveDateTime, - pub metadata: Option<serde_json::Value>, -} - impl From<storage::Customer> for CustomerResponse { fn from(cust: storage::Customer) -> Self { - Self { + customers::CustomerResponse { customer_id: cust.customer_id, name: cust.name, email: cust.email, @@ -62,25 +45,8 @@ impl From<storage::Customer> for CustomerResponse { description: cust.description, created_at: cust.created_at, metadata: cust.metadata, + address: None, } + .into() } } - -#[derive(Default, Debug, Deserialize, Serialize)] -pub struct CustomerId { - pub customer_id: String, -} - -#[derive(Default, Debug, Deserialize, Serialize)] -pub struct CustomerDeleteResponse { - pub customer_id: String, - pub deleted: bool, -} - -pub fn generate_customer_id() -> String { - utils::generate_id(consts::ID_LENGTH, "cus") -} - -fn unknown_merchant() -> String { - String::from("merchant_unknown") -} diff --git a/crates/router/src/types/api/enums.rs b/crates/router/src/types/api/enums.rs index 8db8250bb5f..f048bbea397 100644 --- a/crates/router/src/types/api/enums.rs +++ b/crates/router/src/types/api/enums.rs @@ -1,447 +1 @@ -#[derive( - Clone, - Copy, - Debug, - Default, - Eq, - PartialEq, - serde::Deserialize, - serde::Serialize, - strum::Display, - strum::EnumString, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum AttemptStatus { - Started, - AuthenticationFailed, - JuspayDeclined, - PendingVbv, - VbvSuccessful, - Authorized, - AuthorizationFailed, - Charged, - Authorizing, - CodInitiated, - Voided, - VoidInitiated, - CaptureInitiated, - CaptureFailed, - VoidFailed, - AutoRefunded, - PartialCharged, - #[default] - Pending, - Failure, - PaymentMethodAwaited, - ConfirmationAwaited, -} - -#[derive( - Clone, - Copy, - Debug, - Default, - Eq, - PartialEq, - serde::Deserialize, - serde::Serialize, - strum::Display, - strum::EnumString, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum AuthenticationType { - #[default] - ThreeDs, - NoThreeDs, -} - -#[derive( - Clone, - Copy, - Debug, - Default, - Eq, - PartialEq, - serde::Deserialize, - serde::Serialize, - strum::Display, - strum::EnumString, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum CaptureMethod { - #[default] - Automatic, - Manual, - ManualMultiple, - Scheduled, -} - -#[derive( - Clone, - Copy, - Debug, - Eq, - PartialEq, - strum::Display, - strum::EnumString, - serde::Deserialize, - serde::Serialize, -)] -#[strum(serialize_all = "snake_case")] -#[serde(rename_all = "snake_case")] -pub enum ConnectorType { - /// PayFacs, Acquirers, Gateways, BNPL etc - PaymentProcessor, - /// Fraud, Currency Conversion, Crypto etc - PaymentVas, - /// Accounting, Billing, Invoicing, Tax etc - FinOperations, - /// Inventory, ERP, CRM, KYC etc - FizOperations, - /// Payment Networks like Visa, MasterCard etc - Networks, - /// All types of banks including corporate / commercial / personal / neo banks - BankingEntities, - /// All types of non-banking financial institutions including Insurance, Credit / Lending etc - NonBankingFinance, -} - -#[allow(clippy::upper_case_acronyms)] -#[derive( - Clone, - Copy, - Debug, - Default, - Eq, - Hash, - PartialEq, - serde::Deserialize, - serde::Serialize, - strum::Display, - strum::EnumString, -)] -pub enum Currency { - AED, - ALL, - AMD, - ARS, - AUD, - AWG, - AZN, - BBD, - BDT, - BHD, - BMD, - BND, - BOB, - BRL, - BSD, - BWP, - BZD, - CAD, - CHF, - CNY, - COP, - CRC, - CUP, - CZK, - DKK, - DOP, - DZD, - EGP, - ETB, - EUR, - FJD, - GBP, - GHS, - GIP, - GMD, - GTQ, - GYD, - HKD, - HNL, - HRK, - HTG, - HUF, - IDR, - ILS, - INR, - JMD, - JOD, - JPY, - KES, - KGS, - KHR, - KRW, - KWD, - KYD, - KZT, - LAK, - LBP, - LKR, - LRD, - LSL, - MAD, - MDL, - MKD, - MMK, - MNT, - MOP, - MUR, - MVR, - MWK, - MXN, - MYR, - NAD, - NGN, - NIO, - NOK, - NPR, - NZD, - OMR, - PEN, - PGK, - PHP, - PKR, - PLN, - QAR, - RUB, - SAR, - SCR, - SEK, - SGD, - SLL, - SOS, - SSP, - SVC, - SZL, - THB, - TTD, - TWD, - TZS, - #[default] - USD, - UYU, - UZS, - YER, - ZAR, -} - -#[derive( - Clone, - Copy, - Debug, - Eq, - PartialEq, - serde::Deserialize, - serde::Serialize, - strum::Display, - strum::EnumString, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum EventType { - PaymentSucceeded, -} - -#[derive( - Clone, - Copy, - Debug, - Default, - Eq, - PartialEq, - serde::Deserialize, - serde::Serialize, - strum::Display, - strum::EnumString, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum IntentStatus { - Succeeded, - Failed, - Cancelled, - Processing, - RequiresCustomerAction, - RequiresPaymentMethod, - #[default] - RequiresConfirmation, - RequiresCapture, -} - -#[derive( - Clone, - Copy, - Debug, - Default, - Eq, - PartialEq, - serde::Deserialize, - serde::Serialize, - strum::Display, - strum::EnumString, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum FutureUsage { - #[default] - OffSession, - OnSession, -} - -#[derive( - Clone, - Copy, - Debug, - Eq, - Hash, - PartialEq, - serde::Deserialize, - serde::Serialize, - strum::Display, - strum::EnumString, -)] -#[strum(serialize_all = "snake_case")] -#[serde(rename_all = "snake_case")] -pub enum PaymentMethodIssuerCode { - JpHdfc, - JpIcici, - JpGooglepay, - JpApplepay, - JpPhonepay, - JpWechat, - JpSofort, - JpGiropay, - JpSepa, - JpBacs, -} - -#[derive( - Clone, - Copy, - Debug, - Eq, - Hash, - PartialEq, - serde::Deserialize, - serde::Serialize, - strum::Display, - strum::EnumString, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum PaymentMethodSubType { - Credit, - Debit, - UpiIntent, - UpiCollect, - CreditCardInstallments, - PayLaterInstallments, -} - -#[derive( - Clone, - Copy, - Debug, - Default, - Eq, - Hash, - PartialEq, - serde::Deserialize, - serde::Serialize, - strum::Display, - strum::EnumString, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum PaymentMethodType { - Card, - PaymentContainer, - #[default] - BankTransfer, - BankDebit, - PayLater, - Netbanking, - Upi, - OpenBanking, - ConsumerFinance, - Wallet, - Klarna, - Paypal, -} - -#[derive( - Clone, - Copy, - Debug, - Eq, - Hash, - PartialEq, - serde::Deserialize, - serde::Serialize, - strum::Display, - strum::EnumString, -)] -#[serde(rename_all = "lowercase")] -#[strum(serialize_all = "lowercase")] -pub enum WalletIssuer { - GooglePay, - ApplePay, -} - -#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, strum::Display, strum::EnumString)] -#[strum(serialize_all = "snake_case")] -pub enum RefundStatus { - Failure, - ManualReview, - #[default] - Pending, - Success, - TransactionFailure, -} - -#[derive( - Clone, - Copy, - Debug, - Eq, - PartialEq, - serde::Deserialize, - serde::Serialize, - strum::Display, - strum::EnumString, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum RoutingAlgorithm { - RoundRobin, - MaxConversion, - MinCost, - Custom, -} - -#[derive( - Clone, - Copy, - Debug, - Eq, - PartialEq, - Default, - serde::Deserialize, - serde::Serialize, - strum::Display, - strum::EnumString, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum MandateStatus { - #[default] - Active, - Inactive, - Pending, - Revoked, -} +pub use api_models::enums::*; diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs index 6b6f5934a58..d2b44126e22 100644 --- a/crates/router/src/types/api/mandates.rs +++ b/crates/router/src/types/api/mandates.rs @@ -1,3 +1,5 @@ +use api_models::mandates; +pub use api_models::mandates::{MandateId, MandateResponse, MandateRevokedResponse}; use error_stack::ResultExt; use serde::{Deserialize, Serialize}; @@ -6,40 +8,27 @@ use crate::{ errors::{self, RouterResult, StorageErrorExt}, payment_methods, }, - pii::Secret, + newtype, routes::AppState, types::{ - api::{self, enums as api_enums}, + api, storage::{self, enums as storage_enums}, }, }; -#[derive(Default, Debug, Deserialize, Serialize)] -pub struct MandateId { - pub mandate_id: String, -} - -#[derive(Default, Debug, Deserialize, Serialize)] -pub struct MandateRevokedResponse { - pub mandate_id: String, - pub status: api_enums::MandateStatus, -} +newtype!( + pub MandateCardDetails = mandates::MandateCardDetails, + derives = (Default, Debug, Deserialize, Serialize) +); -#[derive(Default, Debug, Deserialize, Serialize)] -pub struct MandateResponse { - pub mandate_id: String, - pub status: api_enums::MandateStatus, - pub payment_method_id: String, - pub payment_method: String, - pub card: Option<MandateCardDetails>, - pub customer_acceptance: Option<api::payments::CustomerAcceptance>, +#[async_trait::async_trait] +pub(crate) trait MandateResponseExt: Sized { + async fn from_db_mandate(state: &AppState, mandate: storage::Mandate) -> RouterResult<Self>; } -impl MandateResponse { - pub async fn from_db_mandate( - state: &AppState, - mandate: storage::Mandate, - ) -> RouterResult<Self> { +#[async_trait::async_trait] +impl MandateResponseExt for MandateResponse { + async fn from_db_mandate(state: &AppState, mandate: storage::Mandate) -> RouterResult<Self> { let db = &*state.store; let payment_method = db .find_payment_method(&mandate.payment_method_id) @@ -47,6 +36,7 @@ impl MandateResponse { .map_err(|error| { error.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) })?; + let card = if payment_method.payment_method == storage_enums::PaymentMethodType::Card { let get_card_resp = payment_methods::cards::get_card_from_legacy_locker( state, @@ -57,11 +47,12 @@ impl MandateResponse { let card_detail = payment_methods::transformers::get_card_detail(&payment_method, get_card_resp.card) .change_context(errors::ApiErrorResponse::InternalServerError)?; - Some(MandateCardDetails::from(card_detail)) + Some(MandateCardDetails::from(card_detail).into_inner()) } else { None }; - Ok(MandateResponse { + + Ok(Self { mandate_id: mandate.mandate_id, customer_acceptance: Some(api::payments::CustomerAcceptance { acceptance_type: if mandate.customer_ip_address.is_some() { @@ -83,21 +74,9 @@ impl MandateResponse { } } -#[derive(Default, Debug, Deserialize, Serialize)] -pub struct MandateCardDetails { - pub last4_digits: Option<String>, - pub card_exp_month: Option<Secret<String>>, - pub card_exp_year: Option<Secret<String>>, - pub card_holder_name: Option<Secret<String>>, - pub card_token: Option<Secret<String>>, - pub scheme: Option<String>, - pub issuer_country: Option<String>, - pub card_fingerprint: Option<Secret<String>>, -} - impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails { fn from(card_details_from_locker: api::payment_methods::CardDetailFromLocker) -> Self { - Self { + mandates::MandateCardDetails { last4_digits: card_details_from_locker.last4_digits, card_exp_month: card_details_from_locker.expiry_month.clone(), card_exp_year: card_details_from_locker.expiry_year.clone(), @@ -107,5 +86,6 @@ impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails { issuer_country: card_details_from_locker.issuer_country, card_fingerprint: card_details_from_locker.card_fingerprint, } + .into() } } diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index 4d591de01fc..3f4dc688668 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -1,14 +1,18 @@ use std::collections::HashMap; +pub use api_models::payment_methods::{ + CardDetail, CardDetailFromLocker, CreatePaymentMethod, CustomerPaymentMethod, + DeletePaymentMethodResponse, DeleteTokenizeByDateRequest, DeleteTokenizeByTokenRequest, + GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCustomerPaymentMethodsResponse, + ListPaymentMethodRequest, ListPaymentMethodResponse, PaymentMethodId, PaymentMethodResponse, + TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2, +}; use error_stack::report; use literally::hmap; use once_cell::sync::Lazy; -use serde::{Deserialize, Serialize}; -use time::PrimitiveDateTime; use crate::{ core::errors::{self, RouterResult}, - pii::{self, Secret}, types::api::enums as api_enums, }; @@ -68,21 +72,20 @@ static PAYMENT_METHOD_ISSUER_SET: Lazy< } }); -#[derive(Debug, Deserialize, Serialize, Clone)] -#[serde(deny_unknown_fields)] -pub struct CreatePaymentMethod { - pub merchant_id: Option<String>, - pub payment_method: api_enums::PaymentMethodType, - pub payment_method_type: Option<api_enums::PaymentMethodSubType>, - pub payment_method_issuer: Option<String>, - pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, - pub card: Option<CardDetail>, - pub metadata: Option<serde_json::Value>, - pub customer_id: Option<String>, +pub(crate) trait CreatePaymentMethodExt { + fn validate(&self) -> RouterResult<()>; + fn check_subtype_mapping<T, U>( + dict: &HashMap<T, Vec<U>>, + the_type: T, + the_subtype: Option<U>, + ) -> bool + where + T: std::cmp::Eq + std::hash::Hash, + U: std::cmp::PartialEq; } -impl CreatePaymentMethod { - pub fn validate(&self) -> RouterResult<()> { +impl CreatePaymentMethodExt for CreatePaymentMethod { + fn validate(&self) -> RouterResult<()> { let pm_subtype_map = Lazy::get(&PAYMENT_METHOD_TYPE_SET) .unwrap_or_else(|| Lazy::force(&PAYMENT_METHOD_TYPE_SET)); if !Self::check_subtype_mapping( @@ -131,174 +134,3 @@ impl CreatePaymentMethod { .unwrap_or(true) } } - -#[derive(Debug, Deserialize, Serialize, Clone)] -#[serde(deny_unknown_fields)] -pub struct CardDetail { - pub card_number: Secret<String, pii::CardNumber>, - pub card_exp_month: Secret<String>, - pub card_exp_year: Secret<String>, - pub card_holder_name: Option<Secret<String>>, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct PaymentMethodResponse { - pub payment_method_id: String, - pub payment_method: api_enums::PaymentMethodType, - pub payment_method_type: Option<api_enums::PaymentMethodSubType>, - pub payment_method_issuer: Option<String>, - pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, - pub card: Option<CardDetailFromLocker>, - //TODO: Populate this on request? - // pub accepted_country: Option<Vec<String>>, - // pub accepted_currency: Option<Vec<enums::Currency>>, - // pub minimum_amount: Option<i32>, - // pub maximum_amount: Option<i32>, - pub recurring_enabled: bool, - pub installment_payment_enabled: bool, - pub payment_experience: Option<Vec<String>>, //TODO change it to enum - pub metadata: Option<serde_json::Value>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub created: Option<PrimitiveDateTime>, -} - -#[derive(Debug, Deserialize, Serialize, Clone)] -pub struct CardDetailFromLocker { - pub scheme: Option<String>, - pub issuer_country: Option<String>, - pub last4_digits: Option<String>, - #[serde(skip)] - pub card_number: Option<Secret<String, pii::CardNumber>>, - pub expiry_month: Option<Secret<String>>, - pub expiry_year: Option<Secret<String>>, - pub card_token: Option<Secret<String>>, - pub card_holder_name: Option<Secret<String>>, - pub card_fingerprint: Option<Secret<String>>, -} - -//List Payment Method -#[derive(Debug, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct ListPaymentMethodRequest { - pub accepted_countries: Option<Vec<String>>, - pub accepted_currencies: Option<Vec<api_enums::Currency>>, - pub amount: Option<i32>, - pub recurring_enabled: Option<bool>, - pub installment_payment_enabled: Option<bool>, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct ListPaymentMethodResponse { - pub payment_method: api_enums::PaymentMethodType, - pub payment_method_types: Option<Vec<api_enums::PaymentMethodSubType>>, - pub payment_method_issuers: Option<Vec<String>>, - pub payment_method_issuer_code: Option<Vec<api_enums::PaymentMethodIssuerCode>>, - pub payment_schemes: Option<Vec<String>>, - pub accepted_countries: Option<Vec<String>>, - pub accepted_currencies: Option<Vec<api_enums::Currency>>, - pub minimum_amount: Option<i32>, - pub maximum_amount: Option<i32>, - pub recurring_enabled: bool, - pub installment_payment_enabled: bool, - pub payment_experience: Option<Vec<String>>, //TODO change it to enum -} - -#[derive(Debug, Serialize)] -pub struct ListCustomerPaymentMethodsResponse { - pub enabled_payment_methods: Vec<ListPaymentMethodResponse>, - pub customer_payment_methods: Vec<CustomerPaymentMethod>, -} - -#[derive(Debug, Serialize)] -pub struct DeletePaymentMethodResponse { - pub payment_method_id: String, - pub deleted: bool, -} - -#[derive(Debug, Serialize)] -pub struct CustomerPaymentMethod { - pub payment_token: String, - pub customer_id: String, - pub payment_method: api_enums::PaymentMethodType, - pub payment_method_type: Option<api_enums::PaymentMethodSubType>, - pub payment_method_issuer: Option<String>, - pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, - //TODO: Populate this on request? - // pub accepted_country: Option<Vec<String>>, - // pub accepted_currency: Option<Vec<enums::Currency>>, - // pub minimum_amount: Option<i32>, - // pub maximum_amount: Option<i32>, - pub recurring_enabled: bool, - pub installment_payment_enabled: bool, - pub payment_experience: Option<Vec<String>>, //TODO change it to enum - pub card: Option<CardDetailFromLocker>, - pub metadata: Option<serde_json::Value>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub created: Option<PrimitiveDateTime>, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct PaymentMethodId { - pub payment_method_id: String, -} - -//------------------------------------------------TokenizeService------------------------------------------------ -#[derive(Debug, Serialize, Deserialize)] -pub struct TokenizePayloadEncrypted { - pub payload: String, - pub key_id: String, - pub version: Option<String>, -} - -#[derive(Debug, Serialize, Deserialize, router_derive::DebugAsDisplay)] -pub struct TokenizePayloadRequest { - pub value1: String, - pub value2: String, - pub lookup_key: String, - pub service_name: String, -} - -#[derive(Debug, Serialize, Deserialize, router_derive::DebugAsDisplay)] -pub struct GetTokenizePayloadRequest { - pub lookup_key: String, - pub get_value2: bool, -} - -#[derive(Debug, Serialize, router_derive::DebugAsDisplay)] -pub struct DeleteTokenizeByTokenRequest { - pub lookup_key: String, -} - -#[derive(Debug, Serialize)] //FIXME yet to be implemented -pub struct DeleteTokenizeByDateRequest { - pub buffer_minutes: i32, - pub service_name: String, - pub max_rows: i32, -} - -#[derive(Debug, Deserialize, router_derive::DebugAsDisplay)] -pub struct GetTokenizePayloadResponse { - pub lookup_key: String, - pub get_value2: Option<bool>, -} -#[derive(Debug, Serialize, Deserialize, router_derive::DebugAsDisplay)] -#[serde(rename_all = "camelCase")] -pub struct TokenizedCardValue1 { - pub card_number: String, - pub exp_year: String, - pub exp_month: String, - pub name_on_card: Option<String>, - pub nickname: Option<String>, - pub card_last_four: Option<String>, - pub card_token: Option<String>, -} - -#[derive(Debug, Serialize, Deserialize, router_derive::DebugAsDisplay)] -#[serde(rename_all = "camelCase")] - -pub struct TokenizedCardValue2 { - pub card_security_code: Option<String>, - pub card_fingerprint: Option<String>, - pub external_id: Option<String>, - pub customer_id: Option<String>, -} diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index e2b3b723276..4ddc554acad 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -1,66 +1,31 @@ +use api_models::payments; +pub use api_models::payments::{ + AcceptanceType, Address, AddressDetails, Amount, AuthenticationForStartResponse, CCard, + ConnectorSessionToken, CustomerAcceptance, MandateData, MandateTxnType, MandateType, + MandateValidationFields, NextAction, NextActionType, OnlineMandate, PayLaterData, + PaymentIdType, PaymentListConstraints, PaymentListResponse, PaymentMethod, + PaymentMethodDataResponse, PaymentOp, PaymentRetrieveBody, PaymentsCancelRequest, + PaymentsCaptureRequest, PaymentsRedirectRequest, PaymentsRedirectionResponse, PaymentsRequest, + PaymentsResponse, PaymentsResponseForm, PaymentsRetrieveRequest, PaymentsSessionRequest, + PaymentsSessionResponse, PaymentsStartRequest, PgRedirectResponse, PhoneDetails, + RedirectionResponse, UrlDetails, VerifyRequest, VerifyResponse, WalletData, +}; use error_stack::{IntoReport, ResultExt}; -use masking::{PeekInterface, Secret}; -use router_derive::Setter; +use masking::PeekInterface; use time::PrimitiveDateTime; use crate::{ core::errors, - pii, services::api, - types::{self, api as api_types, api::enums as api_enums, storage}, - utils::custom_serde, + types::{self, api as api_types}, }; -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum PaymentOp { - Create, - Update, - Confirm, -} - -#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] -#[serde(deny_unknown_fields)] -pub struct PaymentsRequest { - #[serde( - default, - deserialize_with = "custom_serde::payment_id_type::deserialize_option" - )] - pub payment_id: Option<PaymentIdType>, - pub merchant_id: Option<String>, - #[serde(default, deserialize_with = "custom_serde::amount::deserialize_option")] - pub amount: Option<Amount>, - pub currency: Option<String>, - pub capture_method: Option<api_enums::CaptureMethod>, - pub amount_to_capture: Option<i32>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub capture_on: Option<PrimitiveDateTime>, - pub confirm: Option<bool>, - pub customer_id: Option<String>, - pub email: Option<Secret<String, pii::Email>>, - pub name: Option<Secret<String>>, - pub phone: Option<Secret<String>>, - pub phone_country_code: Option<String>, - pub off_session: Option<bool>, - pub description: Option<String>, - pub return_url: Option<String>, - pub setup_future_usage: Option<api_enums::FutureUsage>, - pub authentication_type: Option<api_enums::AuthenticationType>, - pub payment_method_data: Option<PaymentMethod>, - pub payment_method: Option<api_enums::PaymentMethodType>, - pub payment_token: Option<String>, - pub shipping: Option<Address>, - pub billing: Option<Address>, - pub statement_descriptor_name: Option<String>, - pub statement_descriptor_suffix: Option<String>, - pub metadata: Option<serde_json::Value>, - pub client_secret: Option<String>, - pub mandate_data: Option<MandateData>, - pub mandate_id: Option<String>, - pub browser_info: Option<serde_json::Value>, +pub(crate) trait PaymentsRequestExt { + fn is_mandate(&self) -> Option<MandateTxnType>; } -impl PaymentsRequest { - pub fn is_mandate(&self) -> Option<MandateTxnType> { +impl PaymentsRequestExt for PaymentsRequest { + fn is_mandate(&self) -> Option<MandateTxnType> { match (&self.mandate_data, &self.mandate_id) { (None, None) => None, (_, Some(_)) => Some(MandateTxnType::RecurringMandateTxn), @@ -69,231 +34,31 @@ impl PaymentsRequest { } } -#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] -pub enum Amount { - Value(i32), - #[default] - Zero, -} - -impl From<Amount> for i32 { - fn from(amount: Amount) -> Self { - match amount { - Amount::Value(v) => v, - Amount::Zero => 0, - } - } -} -impl From<i32> for Amount { - fn from(val: i32) -> Self { - match val { - 0 => Amount::Zero, - amount => Amount::Value(amount), - } - } -} - -#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] -#[serde(deny_unknown_fields)] -pub struct PaymentsRedirectRequest { - pub payment_id: String, - pub merchant_id: String, - pub connector: String, - pub param: String, +pub(crate) trait CustomerAcceptanceExt { + fn get_ip_address(&self) -> Option<String>; + fn get_user_agent(&self) -> Option<String>; + fn get_accepted_at(&self) -> PrimitiveDateTime; } -#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] -#[serde(deny_unknown_fields)] -pub struct VerifyRequest { - // The merchant_id is generated through api key - // and is later passed in the struct - pub merchant_id: Option<String>, - pub customer_id: Option<String>, - pub email: Option<Secret<String, pii::Email>>, - pub name: Option<Secret<String>>, - pub phone: Option<Secret<String>>, - pub phone_country_code: Option<String>, - pub payment_method: Option<api_enums::PaymentMethodType>, - pub payment_method_data: Option<PaymentMethod>, - pub payment_token: Option<String>, - pub mandate_data: Option<MandateData>, - pub setup_future_usage: Option<api_enums::FutureUsage>, - pub off_session: Option<bool>, - pub client_secret: Option<String>, -} - -impl From<PaymentsRequest> for VerifyRequest { - fn from(item: PaymentsRequest) -> Self { - Self { - client_secret: item.client_secret, - merchant_id: item.merchant_id, - customer_id: item.customer_id, - email: item.email, - name: item.name, - phone: item.phone, - phone_country_code: item.phone_country_code, - payment_method: item.payment_method, - payment_method_data: item.payment_method_data, - payment_token: item.payment_token, - mandate_data: item.mandate_data, - setup_future_usage: item.setup_future_usage, - off_session: item.off_session, - } - } -} - -pub enum MandateTxnType { - NewMandateTxn, - RecurringMandateTxn, -} - -#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] -#[serde(deny_unknown_fields)] -pub struct MandateData { - pub customer_acceptance: CustomerAcceptance, - pub mandate_type: MandateType, -} - -#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] -pub enum MandateType { - SingleUse(storage::MandateAmountData), - MultiUse(Option<storage::MandateAmountData>), -} - -impl Default for MandateType { - fn default() -> Self { - Self::MultiUse(None) - } -} - -#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] -#[serde(deny_unknown_fields)] -pub struct CustomerAcceptance { - pub acceptance_type: AcceptanceType, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub accepted_at: Option<PrimitiveDateTime>, - pub online: Option<OnlineMandate>, -} - -impl CustomerAcceptance { - pub fn get_ip_address(&self) -> Option<String> { +impl CustomerAcceptanceExt for CustomerAcceptance { + fn get_ip_address(&self) -> Option<String> { self.online .as_ref() .map(|data| data.ip_address.peek().to_owned()) } - pub fn get_user_agent(&self) -> Option<String> { + + fn get_user_agent(&self) -> Option<String> { self.online.as_ref().map(|data| data.user_agent.clone()) } - pub fn get_accepted_at(&self) -> PrimitiveDateTime { + + fn get_accepted_at(&self) -> PrimitiveDateTime { self.accepted_at .unwrap_or_else(common_utils::date_time::now) } } -#[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone)] -#[serde(rename_all = "lowercase")] -pub enum AcceptanceType { - Online, - #[default] - Offline, -} - -#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] -#[serde(deny_unknown_fields)] -pub struct OnlineMandate { - pub ip_address: Secret<String, pii::IpAddress>, - pub user_agent: String, -} - impl super::Router for PaymentsRequest {} -#[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] -pub struct CCard { - pub card_number: Secret<String, pii::CardNumber>, - pub card_exp_month: Secret<String>, - pub card_exp_year: Secret<String>, - pub card_holder_name: Secret<String>, - pub card_cvc: Secret<String>, -} - -#[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] -pub struct PayLaterData { - pub billing_email: String, - pub country: String, -} - -#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] -pub enum PaymentMethod { - #[serde(rename(deserialize = "card"))] - Card(CCard), - #[serde(rename(deserialize = "bank_transfer"))] - BankTransfer, - #[serde(rename(deserialize = "wallet"))] - Wallet(WalletData), - #[serde(rename(deserialize = "pay_later"))] - PayLater(PayLaterData), - #[serde(rename(deserialize = "paypal"))] - Paypal, -} - -#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] -pub struct WalletData { - pub issuer_name: api_enums::WalletIssuer, - pub token: String, -} - -#[derive(Eq, PartialEq, Clone, Debug, serde::Serialize)] -pub struct CCardResponse { - last4: String, - exp_month: String, - exp_year: String, -} - -#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize)] -pub enum PaymentMethodDataResponse { - #[serde(rename = "card")] - Card(CCardResponse), - #[serde(rename(deserialize = "bank_transfer"))] - BankTransfer, - Wallet(WalletData), - PayLater(PayLaterData), - Paypal, -} - -impl Default for PaymentMethod { - fn default() -> Self { - PaymentMethod::BankTransfer - } -} - -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -pub enum PaymentIdType { - PaymentIntentId(String), - ConnectorTransactionId(String), - PaymentTxnId(String), -} - -impl PaymentIdType { - pub fn get_payment_intent_id(&self) -> errors::CustomResult<String, errors::ValidationError> { - match self { - Self::PaymentIntentId(id) => Ok(id.clone()), - Self::ConnectorTransactionId(_) | Self::PaymentTxnId(_) => { - Err(errors::ValidationError::IncorrectValueProvided { - field_name: "payment_id", - }) - .into_report() - .attach_printable("Expected payment intent ID but got connector transaction ID") - } - } - } -} - -impl Default for PaymentIdType { - fn default() -> Self { - Self::PaymentIntentId(Default::default()) - } -} - // Core related api layer. #[derive(Debug, Clone)] pub struct Authorize; @@ -311,194 +76,31 @@ pub struct Session; #[derive(Debug, Clone)] pub struct Verify; -//#[derive(Debug, serde::Deserialize, serde::Serialize)] -//#[serde(untagged)] -//pub enum enums::CaptureMethod { -//Automatic, -//Manual, -//} - -//impl Default for enums::CaptureMethod { -//fn default() -> Self { -//enums::CaptureMethod::Manual -//} -//} - -#[derive(Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] -#[serde(deny_unknown_fields)] -pub struct Address { - pub address: Option<AddressDetails>, - pub phone: Option<PhoneDetails>, -} - -// used by customers also, could be moved outside -#[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq)] -#[serde(deny_unknown_fields)] -pub struct AddressDetails { - pub city: Option<String>, - pub country: Option<String>, - pub line1: Option<Secret<String>>, - pub line2: Option<Secret<String>>, - pub line3: Option<Secret<String>>, - pub zip: Option<Secret<String>>, - pub state: Option<Secret<String>>, - pub first_name: Option<Secret<String>>, - pub last_name: Option<Secret<String>>, -} - -#[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)] -pub struct PhoneDetails { - pub number: Option<Secret<String>>, - pub country_code: Option<String>, -} - -#[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize)] -pub(crate) struct PaymentsCaptureRequest { - pub payment_id: Option<String>, - pub merchant_id: Option<String>, - pub amount_to_capture: Option<i32>, - pub refund_uncaptured_amount: Option<bool>, - pub statement_descriptor_suffix: Option<String>, - pub statement_descriptor_prefix: Option<String>, -} - -#[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] -pub struct UrlDetails { - pub url: String, - pub method: String, -} -#[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] -pub struct AuthenticationForStartResponse { - pub authentication: UrlDetails, -} -#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] -#[serde(rename_all = "snake_case")] -pub enum NextActionType { - RedirectToUrl, - DisplayQrCode, - InvokeSdkClient, - TriggerApi, -} -#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] -pub struct NextAction { - #[serde(rename = "type")] - pub next_action_type: NextActionType, - pub redirect_to_url: Option<String>, +pub(crate) trait PaymentIdTypeExt { + fn get_payment_intent_id(&self) -> errors::CustomResult<String, errors::ValidationError>; } -#[derive(Setter, Clone, Default, Debug, Eq, PartialEq, serde::Serialize)] -pub struct PaymentsResponse { - pub payment_id: Option<String>, - pub merchant_id: Option<String>, - pub status: api_enums::IntentStatus, - pub amount: i32, - pub amount_capturable: Option<i32>, - pub amount_received: Option<i32>, - pub client_secret: Option<Secret<String>>, - #[serde(with = "common_utils::custom_serde::iso8601::option")] - pub created: Option<PrimitiveDateTime>, - pub currency: String, - pub customer_id: Option<String>, - pub description: Option<String>, - pub refunds: Option<Vec<api_types::RefundResponse>>, - pub mandate_id: Option<String>, - pub mandate_data: Option<MandateData>, - pub setup_future_usage: Option<api_enums::FutureUsage>, - pub off_session: Option<bool>, - #[serde(with = "common_utils::custom_serde::iso8601::option")] - pub capture_on: Option<PrimitiveDateTime>, - pub capture_method: Option<api_enums::CaptureMethod>, - #[auth_based] - pub payment_method: Option<api_enums::PaymentMethodType>, - #[auth_based] - pub payment_method_data: Option<PaymentMethodDataResponse>, - pub payment_token: Option<String>, - pub shipping: Option<Address>, - pub billing: Option<Address>, - pub metadata: Option<serde_json::Value>, - pub email: Option<Secret<String, pii::Email>>, - pub name: Option<Secret<String>>, - pub phone: Option<Secret<String>>, - pub return_url: Option<String>, - pub authentication_type: Option<api_enums::AuthenticationType>, - pub statement_descriptor_name: Option<String>, - pub statement_descriptor_suffix: Option<String>, - pub next_action: Option<NextAction>, - pub cancellation_reason: Option<String>, - pub error_code: Option<String>, //TODO: Add error code column to the database - pub error_message: Option<String>, -} - -#[derive(Clone, Debug, serde::Deserialize)] -#[serde(deny_unknown_fields)] -pub struct PaymentListConstraints { - pub customer_id: Option<String>, - pub starting_after: Option<String>, - pub ending_before: Option<String>, - #[serde(default = "default_limit")] - pub limit: i64, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub created: Option<PrimitiveDateTime>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - #[serde(rename = "created.lt")] - pub created_lt: Option<PrimitiveDateTime>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - #[serde(rename = "created.gt")] - pub created_gt: Option<PrimitiveDateTime>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - #[serde(rename = "created.lte")] - pub created_lte: Option<PrimitiveDateTime>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - #[serde(rename = "created.gte")] - pub created_gte: Option<PrimitiveDateTime>, -} - -#[derive(Clone, Debug, serde::Serialize)] -pub struct PaymentListResponse { - pub size: usize, - pub data: Vec<PaymentsResponse>, -} - -#[derive(Setter, Clone, Default, Debug, Eq, PartialEq, serde::Serialize)] -pub struct VerifyResponse { - pub verify_id: Option<String>, - pub merchant_id: Option<String>, - // pub status: enums::VerifyStatus, - pub client_secret: Option<Secret<String>>, - pub customer_id: Option<String>, - pub email: Option<Secret<String, pii::Email>>, - pub name: Option<Secret<String>>, - pub phone: Option<Secret<String>>, - pub mandate_id: Option<String>, - #[auth_based] - pub payment_method: Option<api_enums::PaymentMethodType>, - #[auth_based] - pub payment_method_data: Option<PaymentMethodDataResponse>, - pub payment_token: Option<String>, - pub error_code: Option<String>, - pub error_message: Option<String>, -} - -fn default_limit() -> i64 { - 10 -} - -#[derive(Default, Debug, serde::Deserialize, serde::Serialize)] -pub struct PaymentsRedirectionResponse { - pub redirect_url: String, +impl PaymentIdTypeExt for PaymentIdType { + fn get_payment_intent_id(&self) -> errors::CustomResult<String, errors::ValidationError> { + match self { + Self::PaymentIntentId(id) => Ok(id.clone()), + Self::ConnectorTransactionId(_) | Self::PaymentTxnId(_) => { + Err(errors::ValidationError::IncorrectValueProvided { + field_name: "payment_id", + }) + .into_report() + .attach_printable("Expected payment intent ID but got connector transaction ID") + } + } + } } -pub struct MandateValidationFields { - pub mandate_id: Option<String>, - pub confirm: Option<bool>, - pub customer_id: Option<String>, - pub mandate_data: Option<MandateData>, - pub setup_future_usage: Option<api_enums::FutureUsage>, - pub off_session: Option<bool>, +pub(crate) trait MandateValidationFieldsExt { + fn is_mandate(&self) -> Option<MandateTxnType>; } -impl MandateValidationFields { - pub fn is_mandate(&self) -> Option<MandateTxnType> { +impl MandateValidationFieldsExt for MandateValidationFields { + fn is_mandate(&self) -> Option<MandateTxnType> { match (&self.mandate_data, &self.mandate_id) { (None, None) => None, (_, Some(_)) => Some(MandateTxnType::RecurringMandateTxn), @@ -507,128 +109,9 @@ impl MandateValidationFields { } } -impl From<&PaymentsRequest> for MandateValidationFields { - fn from(req: &PaymentsRequest) -> Self { - Self { - mandate_id: req.mandate_id.clone(), - confirm: req.confirm, - customer_id: req.customer_id.clone(), - mandate_data: req.mandate_data.clone(), - setup_future_usage: req.setup_future_usage, - off_session: req.off_session, - } - } -} - -impl From<&VerifyRequest> for MandateValidationFields { - fn from(req: &VerifyRequest) -> Self { - Self { - mandate_id: None, - confirm: Some(true), - customer_id: req.customer_id.clone(), - mandate_data: req.mandate_data.clone(), - off_session: req.off_session, - setup_future_usage: req.setup_future_usage, - } - } -} - -impl PaymentsRedirectionResponse { - pub fn new(redirect_url: &str) -> Self { - Self { - redirect_url: redirect_url.to_owned(), - } - } -} - -impl From<PaymentsRequest> for PaymentsResponse { - fn from(item: PaymentsRequest) -> Self { - let payment_id = match item.payment_id { - Some(api_types::PaymentIdType::PaymentIntentId(id)) => Some(id), - _ => None, - }; - - Self { - payment_id, - merchant_id: item.merchant_id, - setup_future_usage: item.setup_future_usage, - off_session: item.off_session, - shipping: item.shipping, - billing: item.billing, - metadata: item.metadata, - capture_method: item.capture_method, - payment_method: item.payment_method, - capture_on: item.capture_on, - payment_method_data: item - .payment_method_data - .map(PaymentMethodDataResponse::from), - email: item.email, - name: item.name, - phone: item.phone, - payment_token: item.payment_token, - return_url: item.return_url, - authentication_type: item.authentication_type, - statement_descriptor_name: item.statement_descriptor_name, - statement_descriptor_suffix: item.statement_descriptor_suffix, - mandate_data: item.mandate_data, - ..Default::default() - } - } -} - -impl From<VerifyRequest> for VerifyResponse { - fn from(item: VerifyRequest) -> Self { - Self { - merchant_id: item.merchant_id, - customer_id: item.customer_id, - email: item.email, - name: item.name, - phone: item.phone, - payment_method: item.payment_method, - payment_method_data: item - .payment_method_data - .map(PaymentMethodDataResponse::from), - payment_token: item.payment_token, - ..Default::default() - } - } -} - -impl From<PaymentsStartRequest> for PaymentsResponse { - fn from(item: PaymentsStartRequest) -> Self { - Self { - payment_id: Some(item.payment_id), - merchant_id: Some(item.merchant_id), - ..Default::default() - } - } -} - -impl From<PaymentsSessionRequest> for PaymentsResponse { - fn from(item: PaymentsSessionRequest) -> Self { - let payment_id = match item.payment_id { - api_types::PaymentIdType::PaymentIntentId(id) => Some(id), - _ => None, - }; - - Self { - payment_id, - ..Default::default() - } - } -} - -impl From<PaymentsSessionRequest> for PaymentsSessionResponse { - fn from(_item: PaymentsSessionRequest) -> Self { - Self { - session_token: vec![], - } - } -} - impl From<types::storage::PaymentIntent> for PaymentsResponse { fn from(item: types::storage::PaymentIntent) -> Self { - Self { + payments::PaymentsResponse { payment_id: Some(item.payment_id), merchant_id: Some(item.merchant_id), status: item.status.into(), @@ -645,105 +128,7 @@ impl From<types::storage::PaymentIntent> for PaymentsResponse { } } -impl From<PaymentsStartRequest> for PaymentsRequest { - fn from(item: PaymentsStartRequest) -> Self { - Self { - payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), - merchant_id: Some(item.merchant_id), - ..Default::default() - } - } -} - -impl From<PaymentsRetrieveRequest> for PaymentsResponse { - // After removing the request from the payments_to_payments_response this will no longer be needed - fn from(item: PaymentsRetrieveRequest) -> Self { - let payment_id = match item.resource_id { - PaymentIdType::PaymentIntentId(id) => Some(id), - _ => None, - }; - - Self { - payment_id, - merchant_id: item.merchant_id, - ..Default::default() - } - } -} - -impl From<PaymentsCancelRequest> for PaymentsResponse { - fn from(item: PaymentsCancelRequest) -> Self { - Self { - payment_id: Some(item.payment_id), - cancellation_reason: item.cancellation_reason, - ..Default::default() - } - } -} - -impl From<PaymentsCaptureRequest> for PaymentsResponse { - // After removing the request from the payments_to_payments_response this will no longer be needed - fn from(item: PaymentsCaptureRequest) -> Self { - Self { - payment_id: item.payment_id, - amount_received: item.amount_to_capture, - ..Self::default() - } - } -} - -#[derive(Debug, Clone, serde::Serialize)] -pub struct PgRedirectResponse { - pub payment_id: String, - pub status: api_enums::IntentStatus, - pub gateway_id: String, - pub customer_id: Option<String>, - pub amount: Option<i32>, -} - -#[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] -pub struct RedirectionResponse { - pub return_url: String, - pub params: Vec<(String, String)>, - pub return_url_with_query_params: String, - pub http_method: api::Method, - pub headers: Vec<(String, String)>, -} - -#[derive(Debug, serde::Deserialize)] -pub struct PaymentsResponseForm { - pub transaction_id: String, - // pub transaction_reference_id: String, - pub merchant_id: String, - pub order_id: String, -} - // Extract only the last 4 digits of card -impl From<CCard> for CCardResponse { - fn from(card: CCard) -> Self { - let card_number_length = card.card_number.peek().clone().len(); - Self { - last4: card.card_number.peek().clone()[card_number_length - 4..card_number_length] - .to_string(), - exp_month: card.card_exp_month.peek().clone(), - exp_year: card.card_exp_year.peek().clone(), - } - } -} - -impl From<PaymentMethod> for PaymentMethodDataResponse { - fn from(payment_method_data: PaymentMethod) -> Self { - match payment_method_data { - PaymentMethod::Card(card) => PaymentMethodDataResponse::Card(CCardResponse::from(card)), - PaymentMethod::BankTransfer => PaymentMethodDataResponse::BankTransfer, - PaymentMethod::PayLater(pay_later_data) => { - PaymentMethodDataResponse::PayLater(pay_later_data) - } - PaymentMethod::Wallet(wallet_data) => PaymentMethodDataResponse::Wallet(wallet_data), - PaymentMethod::Paypal => PaymentMethodDataResponse::Paypal, - } - } -} pub trait PaymentAuthorize: api::ConnectorIntegration<Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> @@ -786,45 +171,6 @@ pub trait Payment: { } -#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] -pub struct PaymentsRetrieveRequest { - pub resource_id: PaymentIdType, - pub merchant_id: Option<String>, - pub force_sync: bool, - pub param: Option<String>, - pub connector: Option<String>, -} - -#[derive(Default, Debug, serde::Deserialize, Clone)] -pub struct PaymentsSessionRequest { - pub payment_id: PaymentIdType, - pub client_secret: String, -} - -#[derive(Default, Debug, serde::Serialize, Clone)] -pub struct PaymentsSessionResponse { - pub session_token: Vec<types::ConnectorSessionToken>, -} - -#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] -pub struct PaymentRetrieveBody { - pub merchant_id: Option<String>, - pub force_sync: Option<bool>, -} -#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] -pub struct PaymentsCancelRequest { - #[serde(skip)] - pub payment_id: String, - pub cancellation_reason: Option<String>, -} - -#[derive(Default, Debug, serde::Deserialize, serde::Serialize)] -pub struct PaymentsStartRequest { - pub payment_id: String, - pub merchant_id: String, - pub txn_id: String, -} - #[cfg(test)] mod payments_test { #![allow(clippy::expect_used)] diff --git a/crates/router/src/types/api/refunds.rs b/crates/router/src/types/api/refunds.rs index 8fc29dda0ad..11104cc96d5 100644 --- a/crates/router/src/types/api/refunds.rs +++ b/crates/router/src/types/api/refunds.rs @@ -1,66 +1,11 @@ -use serde::{Deserialize, Serialize}; +pub use api_models::refunds::{RefundRequest, RefundResponse, RefundStatus}; use super::ConnectorCommon; use crate::{ services::api, - types::{self, api::enums as api_enums, storage::enums as storage_enums}, + types::{self, storage::enums as storage_enums}, }; -#[derive(Default, Debug, Clone, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct RefundRequest { - pub refund_id: Option<String>, - pub payment_id: String, - pub merchant_id: Option<String>, - pub amount: Option<i32>, - pub reason: Option<String>, - //FIXME: Make it refund_type instant or scheduled refund - pub force_process: Option<bool>, - pub metadata: Option<serde_json::Value>, -} - -impl super::Router for RefundRequest {} - -#[derive(Debug, Default, Clone, Eq, PartialEq, Deserialize, Serialize)] -pub struct RefundResponse { - pub refund_id: String, - pub payment_id: String, - pub amount: i32, - pub currency: String, - pub reason: Option<String>, - pub status: RefundStatus, - pub metadata: Option<serde_json::Value>, - pub error_message: Option<String>, -} - -#[derive(Debug, Eq, Clone, PartialEq, Deserialize, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum RefundStatus { - Succeeded, - Failed, - Pending, - Review, -} - -impl Default for RefundStatus { - fn default() -> Self { - RefundStatus::Pending - } -} - -impl From<api_enums::RefundStatus> for RefundStatus { - fn from(status: api_enums::RefundStatus) -> Self { - match status { - api_enums::RefundStatus::Failure | api_enums::RefundStatus::TransactionFailure => { - RefundStatus::Failed - } - api_enums::RefundStatus::ManualReview => RefundStatus::Review, - api_enums::RefundStatus::Pending => RefundStatus::Pending, - api_enums::RefundStatus::Success => RefundStatus::Succeeded, - } - } -} - impl From<storage_enums::RefundStatus> for RefundStatus { fn from(status: storage_enums::RefundStatus) -> Self { match status { diff --git a/crates/router/src/types/api/webhooks.rs b/crates/router/src/types/api/webhooks.rs index 20263ee15a0..cc0718979f7 100644 --- a/crates/router/src/types/api/webhooks.rs +++ b/crates/router/src/types/api/webhooks.rs @@ -1,60 +1,17 @@ -use common_utils::custom_serde; +pub use api_models::webhooks::{ + IncomingWebhookDetails, IncomingWebhookEvent, MerchantWebhookConfig, OutgoingWebhook, + OutgoingWebhookContent, WebhookFlow, +}; use error_stack::ResultExt; -use serde::{Deserialize, Serialize}; -use time::PrimitiveDateTime; use super::ConnectorCommon; use crate::{ core::errors::{self, CustomResult}, db::StorageInterface, services, - types::{api, api::enums as api_enums}, utils::crypto, }; -#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum IncomingWebhookEvent { - PaymentIntentSuccess, -} - -pub enum WebhookFlow { - Payment, - Refund, - Subscription, -} - -impl From<IncomingWebhookEvent> for WebhookFlow { - fn from(evt: IncomingWebhookEvent) -> Self { - match evt { - IncomingWebhookEvent::PaymentIntentSuccess => Self::Payment, - } - } -} - -pub type MerchantWebhookConfig = std::collections::HashSet<IncomingWebhookEvent>; - -pub struct IncomingWebhookDetails { - pub object_reference_id: String, - pub resource_object: Vec<u8>, -} - -#[derive(Debug, Clone, Serialize)] -pub struct OutgoingWebhook { - pub merchant_id: String, - pub event_id: String, - pub event_type: api_enums::EventType, - pub content: OutgoingWebhookContent, - #[serde(default, with = "custom_serde::iso8601")] - pub timestamp: PrimitiveDateTime, -} - -#[derive(Debug, Clone, Serialize)] -#[serde(tag = "type", content = "object", rename_all = "snake_case")] -pub enum OutgoingWebhookContent { - PaymentDetails(api::PaymentsResponse), -} - #[async_trait::async_trait] pub trait IncomingWebhook: ConnectorCommon + Sync { fn get_webhook_body_decoding_algorithm( diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 7813d0123ef..60b62867c1d 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1,7 +1,6 @@ -use crate::{ - core::errors, - types::{api::enums as api_enums, storage::enums as storage_enums}, -}; +use api_models::enums as api_enums; + +use crate::{core::errors, types::storage::enums as storage_enums}; impl From<api_enums::RoutingAlgorithm> for storage_enums::RoutingAlgorithm { fn from(algo: api_enums::RoutingAlgorithm) -> Self { @@ -177,43 +176,6 @@ impl From<api_enums::IntentStatus> for storage_enums::IntentStatus { } } -impl From<api_enums::AttemptStatus> for api_enums::IntentStatus { - fn from(s: api_enums::AttemptStatus) -> Self { - match s { - api_enums::AttemptStatus::Charged | api_enums::AttemptStatus::AutoRefunded => { - api_enums::IntentStatus::Succeeded - } - - api_enums::AttemptStatus::ConfirmationAwaited => { - api_enums::IntentStatus::RequiresConfirmation - } - api_enums::AttemptStatus::PaymentMethodAwaited => { - api_enums::IntentStatus::RequiresPaymentMethod - } - - api_enums::AttemptStatus::Authorized => api_enums::IntentStatus::RequiresCapture, - api_enums::AttemptStatus::PendingVbv => api_enums::IntentStatus::RequiresCustomerAction, - - api_enums::AttemptStatus::PartialCharged - | api_enums::AttemptStatus::Started - | api_enums::AttemptStatus::VbvSuccessful - | api_enums::AttemptStatus::Authorizing - | api_enums::AttemptStatus::CodInitiated - | api_enums::AttemptStatus::VoidInitiated - | api_enums::AttemptStatus::CaptureInitiated - | api_enums::AttemptStatus::Pending => api_enums::IntentStatus::Processing, - - api_enums::AttemptStatus::AuthenticationFailed - | api_enums::AttemptStatus::AuthorizationFailed - | api_enums::AttemptStatus::VoidFailed - | api_enums::AttemptStatus::JuspayDeclined - | api_enums::AttemptStatus::CaptureFailed - | api_enums::AttemptStatus::Failure => api_enums::IntentStatus::Failed, - api_enums::AttemptStatus::Voided => api_enums::IntentStatus::Cancelled, - } - } -} - impl From<storage_enums::AttemptStatus> for storage_enums::IntentStatus { fn from(s: storage_enums::AttemptStatus) -> Self { match s { @@ -345,3 +307,113 @@ impl From<storage_enums::AuthenticationType> for api_enums::AuthenticationType { } } } + +impl From<api_enums::Currency> for storage_enums::Currency { + fn from(currency: api_enums::Currency) -> Self { + match currency { + api_enums::Currency::AED => Self::AED, + api_enums::Currency::ALL => Self::ALL, + api_enums::Currency::AMD => Self::AMD, + api_enums::Currency::ARS => Self::ARS, + api_enums::Currency::AUD => Self::AUD, + api_enums::Currency::AWG => Self::AWG, + api_enums::Currency::AZN => Self::AZN, + api_enums::Currency::BBD => Self::BBD, + api_enums::Currency::BDT => Self::BDT, + api_enums::Currency::BHD => Self::BHD, + api_enums::Currency::BMD => Self::BMD, + api_enums::Currency::BND => Self::BND, + api_enums::Currency::BOB => Self::BOB, + api_enums::Currency::BRL => Self::BRL, + api_enums::Currency::BSD => Self::BSD, + api_enums::Currency::BWP => Self::BWP, + api_enums::Currency::BZD => Self::BZD, + api_enums::Currency::CAD => Self::CAD, + api_enums::Currency::CHF => Self::CHF, + api_enums::Currency::CNY => Self::CNY, + api_enums::Currency::COP => Self::COP, + api_enums::Currency::CRC => Self::CRC, + api_enums::Currency::CUP => Self::CUP, + api_enums::Currency::CZK => Self::CZK, + api_enums::Currency::DKK => Self::DKK, + api_enums::Currency::DOP => Self::DOP, + api_enums::Currency::DZD => Self::DZD, + api_enums::Currency::EGP => Self::EGP, + api_enums::Currency::ETB => Self::ETB, + api_enums::Currency::EUR => Self::EUR, + api_enums::Currency::FJD => Self::FJD, + api_enums::Currency::GBP => Self::GBP, + api_enums::Currency::GHS => Self::GHS, + api_enums::Currency::GIP => Self::GIP, + api_enums::Currency::GMD => Self::GMD, + api_enums::Currency::GTQ => Self::GTQ, + api_enums::Currency::GYD => Self::GYD, + api_enums::Currency::HKD => Self::HKD, + api_enums::Currency::HNL => Self::HNL, + api_enums::Currency::HRK => Self::HRK, + api_enums::Currency::HTG => Self::HTG, + api_enums::Currency::HUF => Self::HUF, + api_enums::Currency::IDR => Self::IDR, + api_enums::Currency::ILS => Self::ILS, + api_enums::Currency::INR => Self::INR, + api_enums::Currency::JMD => Self::JMD, + api_enums::Currency::JOD => Self::JOD, + api_enums::Currency::JPY => Self::JPY, + api_enums::Currency::KES => Self::KES, + api_enums::Currency::KGS => Self::KGS, + api_enums::Currency::KHR => Self::KHR, + api_enums::Currency::KRW => Self::KRW, + api_enums::Currency::KWD => Self::KWD, + api_enums::Currency::KYD => Self::KYD, + api_enums::Currency::KZT => Self::KZT, + api_enums::Currency::LAK => Self::LAK, + api_enums::Currency::LBP => Self::LBP, + api_enums::Currency::LKR => Self::LKR, + api_enums::Currency::LRD => Self::LRD, + api_enums::Currency::LSL => Self::LSL, + api_enums::Currency::MAD => Self::MAD, + api_enums::Currency::MDL => Self::MDL, + api_enums::Currency::MKD => Self::MKD, + api_enums::Currency::MMK => Self::MMK, + api_enums::Currency::MNT => Self::MNT, + api_enums::Currency::MOP => Self::MOP, + api_enums::Currency::MUR => Self::MUR, + api_enums::Currency::MVR => Self::MVR, + api_enums::Currency::MWK => Self::MWK, + api_enums::Currency::MXN => Self::MXN, + api_enums::Currency::MYR => Self::MYR, + api_enums::Currency::NAD => Self::NAD, + api_enums::Currency::NGN => Self::NGN, + api_enums::Currency::NIO => Self::NIO, + api_enums::Currency::NOK => Self::NOK, + api_enums::Currency::NPR => Self::NPR, + api_enums::Currency::NZD => Self::NZD, + api_enums::Currency::OMR => Self::OMR, + api_enums::Currency::PEN => Self::PEN, + api_enums::Currency::PGK => Self::PGK, + api_enums::Currency::PHP => Self::PHP, + api_enums::Currency::PKR => Self::PKR, + api_enums::Currency::PLN => Self::PLN, + api_enums::Currency::QAR => Self::QAR, + api_enums::Currency::RUB => Self::RUB, + api_enums::Currency::SAR => Self::SAR, + api_enums::Currency::SCR => Self::SCR, + api_enums::Currency::SEK => Self::SEK, + api_enums::Currency::SGD => Self::SGD, + api_enums::Currency::SLL => Self::SLL, + api_enums::Currency::SOS => Self::SOS, + api_enums::Currency::SSP => Self::SSP, + api_enums::Currency::SVC => Self::SVC, + api_enums::Currency::SZL => Self::SZL, + api_enums::Currency::THB => Self::THB, + api_enums::Currency::TTD => Self::TTD, + api_enums::Currency::TWD => Self::TWD, + api_enums::Currency::TZS => Self::TZS, + api_enums::Currency::USD => Self::USD, + api_enums::Currency::UYU => Self::UYU, + api_enums::Currency::UZS => Self::UZS, + api_enums::Currency::YER => Self::YER, + api_enums::Currency::ZAR => Self::ZAR, + } + } +} diff --git a/crates/router/src/utils/custom_serde.rs b/crates/router/src/utils/custom_serde.rs index 1196c3af564..8b137891791 100644 --- a/crates/router/src/utils/custom_serde.rs +++ b/crates/router/src/utils/custom_serde.rs @@ -1,147 +1 @@ -pub(crate) mod payment_id_type { - use std::fmt; - use serde::{ - de::{self, Visitor}, - Deserializer, - }; - - use crate::types::api::PaymentIdType; - - struct PaymentIdVisitor; - struct OptionalPaymentIdVisitor; - - impl<'de> Visitor<'de> for PaymentIdVisitor { - type Value = PaymentIdType; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("payment id") - } - - fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> - where - E: de::Error, - { - Ok(PaymentIdType::PaymentIntentId(value.to_string())) - } - } - - impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { - type Value = Option<PaymentIdType>; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("payment id") - } - - fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_any(PaymentIdVisitor).map(Some) - } - - fn visit_none<E>(self) -> Result<Self::Value, E> - where - E: de::Error, - { - Ok(None) - } - - fn visit_unit<E>(self) -> Result<Self::Value, E> - where - E: de::Error, - { - Ok(None) - } - } - - #[allow(dead_code)] - pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> - where - D: Deserializer<'a>, - { - deserializer.deserialize_any(PaymentIdVisitor) - } - - pub(crate) fn deserialize_option<'a, D>( - deserializer: D, - ) -> Result<Option<PaymentIdType>, D::Error> - where - D: Deserializer<'a>, - { - deserializer.deserialize_option(OptionalPaymentIdVisitor) - } -} - -pub(crate) mod amount { - use serde::de; - - use crate::types::api; - struct AmountVisitor; - struct OptionalAmountVisitor; - - // This is defined to provide guarded deserialization of amount - // which itself handles zero and non-zero values internally - impl<'de> de::Visitor<'de> for AmountVisitor { - type Value = api::Amount; - - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(formatter, "amount as integer") - } - - fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> - where - E: de::Error, - { - self.visit_i64(v as i64) - } - - fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> - where - E: de::Error, - { - Ok(match v { - 0 => api::Amount::Zero, - amount => api::Amount::Value(amount as i32), - }) - } - } - - impl<'de> de::Visitor<'de> for OptionalAmountVisitor { - type Value = Option<api::Amount>; - - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(formatter, "option of amount (as integer)") - } - - fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where - D: serde::Deserializer<'de>, - { - deserialize(deserializer).map(Some) - } - - fn visit_none<E>(self) -> Result<Self::Value, E> - where - E: de::Error, - { - Ok(None) - } - } - - #[allow(dead_code)] - pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<api::Amount, D::Error> - where - D: de::Deserializer<'de>, - { - deserializer.deserialize_i64(AmountVisitor) - } - pub(crate) fn deserialize_option<'de, D>( - deserializer: D, - ) -> Result<Option<api::Amount>, D::Error> - where - D: de::Deserializer<'de>, - { - deserializer.deserialize_option(OptionalAmountVisitor) - } -} diff --git a/crates/storage_models/Cargo.toml b/crates/storage_models/Cargo.toml new file mode 100644 index 00000000000..89a7c3882c5 --- /dev/null +++ b/crates/storage_models/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "storage_models" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/crates/storage_models/src/lib.rs b/crates/storage_models/src/lib.rs new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/crates/storage_models/src/lib.rs @@ -0,0 +1 @@ +
refactor
move api models into separate crate (#103)
66d9c731f528cd33a1a94815485d6efceb493742
2025-02-13 13:10:28
Sakil Mostak
feat(core): add support to generate session token response from both `connector_wallets_details` and `metadata` (#7140)
false
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index a5dc3a83f2d..cadae4fa45c 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -9967,13 +9967,11 @@ }, "GpayTokenParameters": { "type": "object", - "required": [ - "gateway" - ], "properties": { "gateway": { "type": "string", - "description": "The name of the connector" + "description": "The name of the connector", + "nullable": true }, "gateway_merchant_id": { "type": "string", @@ -9987,6 +9985,16 @@ "stripe:publishableKey": { "type": "string", "nullable": true + }, + "protocol_version": { + "type": "string", + "description": "The protocol version for encryption", + "nullable": true + }, + "public_key": { + "type": "string", + "description": "The public key provided by the merchant", + "nullable": true } } }, diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 60be7f59d67..61892d1b29e 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -12654,13 +12654,11 @@ }, "GpayTokenParameters": { "type": "object", - "required": [ - "gateway" - ], "properties": { "gateway": { "type": "string", - "description": "The name of the connector" + "description": "The name of the connector", + "nullable": true }, "gateway_merchant_id": { "type": "string", @@ -12674,6 +12672,16 @@ "stripe:publishableKey": { "type": "string", "nullable": true + }, + "protocol_version": { + "type": "string", + "description": "The protocol version for encryption", + "nullable": true + }, + "public_key": { + "type": "string", + "description": "The public key provided by the merchant", + "nullable": true } } }, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index cc70520751a..bec25529af9 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -6085,7 +6085,8 @@ pub enum GpayBillingAddressFormat { #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector - pub gateway: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, @@ -6096,6 +6097,13 @@ pub struct GpayTokenParameters { rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, + /// The protocol version for encryption + #[serde(skip_serializing_if = "Option::is_none")] + pub protocol_version: Option<String>, + /// The public key provided by the merchant + #[serde(skip_serializing_if = "Option::is_none")] + #[schema(value_type = Option<String>)] + pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] @@ -6365,6 +6373,7 @@ pub struct GooglePayWalletDetails { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, + pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails @@ -6383,6 +6392,7 @@ pub struct GooglePayMerchantDetails { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, + pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } @@ -6393,8 +6403,9 @@ pub struct GooglePayTokenizationSpecification { pub parameters: GooglePayTokenizationParameters, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] +#[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, @@ -6402,10 +6413,13 @@ pub enum GooglePayTokenizationType { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { - pub gateway: String, - pub public_key: Secret<String>, - pub private_key: Secret<String>, + pub gateway: Option<String>, + pub public_key: Option<Secret<String>>, + pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, + pub gateway_merchant_id: Option<Secret<String>>, + pub stripe_publishable_key: Option<Secret<String>>, + pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index f51a785eaa8..65ac6adf5bc 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -199,24 +199,6 @@ impl SecretsHandler for settings::PazeDecryptConfig { } } -#[async_trait::async_trait] -impl SecretsHandler for settings::GooglePayDecryptConfig { - async fn convert_to_raw_secret( - value: SecretStateContainer<Self, SecuredSecret>, - secret_management_client: &dyn SecretManagementInterface, - ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { - let google_pay_decrypt_keys = value.get_inner(); - - let google_pay_root_signing_keys = secret_management_client - .get_secret(google_pay_decrypt_keys.google_pay_root_signing_keys.clone()) - .await?; - - Ok(value.transition_state(|_| Self { - google_pay_root_signing_keys, - })) - } -} - #[async_trait::async_trait] impl SecretsHandler for settings::ApplepayMerchantConfigs { async fn convert_to_raw_secret( @@ -438,20 +420,6 @@ pub(crate) async fn fetch_raw_secrets( None }; - #[allow(clippy::expect_used)] - let google_pay_decrypt_keys = if let Some(google_pay_keys) = conf.google_pay_decrypt_keys { - Some( - settings::GooglePayDecryptConfig::convert_to_raw_secret( - google_pay_keys, - secret_management_client, - ) - .await - .expect("Failed to decrypt google pay decrypt configs"), - ) - } else { - None - }; - #[allow(clippy::expect_used)] let applepay_merchant_configs = settings::ApplepayMerchantConfigs::convert_to_raw_secret( conf.applepay_merchant_configs, @@ -544,7 +512,7 @@ pub(crate) async fn fetch_raw_secrets( payouts: conf.payouts, applepay_decrypt_keys, paze_decrypt_keys, - google_pay_decrypt_keys, + google_pay_decrypt_keys: conf.google_pay_decrypt_keys, multiple_api_version_supported_connectors: conf.multiple_api_version_supported_connectors, applepay_merchant_configs, lock_settings: conf.lock_settings, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index d721a4db967..5445cb8697f 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -99,7 +99,7 @@ pub struct Settings<S: SecretState> { pub payout_method_filters: ConnectorFilters, pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConfig, S>, pub paze_decrypt_keys: Option<SecretStateContainer<PazeDecryptConfig, S>>, - pub google_pay_decrypt_keys: Option<SecretStateContainer<GooglePayDecryptConfig, S>>, + pub google_pay_decrypt_keys: Option<GooglePayDecryptConfig>, pub multiple_api_version_supported_connectors: MultipleApiVersionSupportedConnectors, pub applepay_merchant_configs: SecretStateContainer<ApplepayMerchantConfigs, S>, pub lock_settings: LockSettings, @@ -919,7 +919,7 @@ impl Settings<SecuredSecret> { self.google_pay_decrypt_keys .as_ref() - .map(|x| x.get_inner().validate()) + .map(|x| x.validate()) .transpose()?; self.key_manager.get_inner().validate()?; diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index 78641d7e33b..b7cb7a91f20 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -1364,10 +1364,12 @@ impl From<GpayTokenizationSpecification> for api_models::payments::GpayTokenizat impl From<GpayTokenParameters> for api_models::payments::GpayTokenParameters { fn from(value: GpayTokenParameters) -> Self { Self { - gateway: value.gateway, + gateway: Some(value.gateway), gateway_merchant_id: Some(value.gateway_merchant_id.expose()), stripe_version: None, stripe_publishable_key: None, + public_key: None, + protocol_version: None, } } } diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 05d08f37ddd..dc3c2d532e8 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -220,3 +220,9 @@ pub const DEFAULT_PAYMENT_METHOD_SESSION_EXPIRY: u32 = 15 * 60; // 15 minutes /// Authorize flow identifier used for performing GSM operations pub const AUTHORIZE_FLOW_STR: &str = "Authorize"; + +/// Protocol Version for encrypted Google Pay Token +pub(crate) const PROTOCOL: &str = "ECv2"; + +/// Sender ID for Google Pay Decryption +pub(crate) const SENDER_ID: &[u8] = b"Google"; diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 54cae42ceb3..506ce557192 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -246,8 +246,6 @@ pub enum PazeDecryptionError { #[derive(Debug, thiserror::Error)] pub enum GooglePayDecryptionError { - #[error("Recipient ID not found")] - RecipientIdNotFound, #[error("Invalid expiration time")] InvalidExpirationTime, #[error("Failed to base64 decode input data")] diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index c81a40216c6..fd2950f5069 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -4381,22 +4381,13 @@ fn get_google_pay_connector_wallet_details( state: &SessionState, merchant_connector_account: &helpers::MerchantConnectorAccountType, ) -> Option<GooglePayPaymentProcessingDetails> { - let google_pay_root_signing_keys = - state - .conf - .google_pay_decrypt_keys - .as_ref() - .map(|google_pay_keys| { - google_pay_keys - .get_inner() - .google_pay_root_signing_keys - .clone() - }); - match ( - google_pay_root_signing_keys, - merchant_connector_account.get_connector_wallets_details(), - ) { - (Some(google_pay_root_signing_keys), Some(wallet_details)) => { + let google_pay_root_signing_keys = state + .conf + .google_pay_decrypt_keys + .as_ref() + .map(|google_pay_keys| google_pay_keys.google_pay_root_signing_keys.clone()); + match merchant_connector_account.get_connector_wallets_details() { + Some(wallet_details) => { let google_pay_wallet_details = wallet_details .parse_value::<api_models::payments::GooglePayWalletDetails>( "GooglePayWalletDetails", @@ -4407,31 +4398,43 @@ fn get_google_pay_connector_wallet_details( google_pay_wallet_details .ok() - .map( + .and_then( |google_pay_wallet_details| { match google_pay_wallet_details .google_pay .provider_details { api_models::payments::GooglePayProviderDetails::GooglePayMerchantDetails(merchant_details) => { - GooglePayPaymentProcessingDetails { - google_pay_private_key: merchant_details + match ( + merchant_details .merchant_info .tokenization_specification .parameters .private_key, google_pay_root_signing_keys, - google_pay_recipient_id: merchant_details + merchant_details .merchant_info .tokenization_specification .parameters .recipient_id, - } + ) { + (Some(google_pay_private_key), Some(google_pay_root_signing_keys), Some(google_pay_recipient_id)) => { + Some(GooglePayPaymentProcessingDetails { + google_pay_private_key, + google_pay_root_signing_keys, + google_pay_recipient_id + }) + } + _ => { + logger::warn!("One or more of the following fields are missing in GooglePayMerchantDetails: google_pay_private_key, google_pay_root_signing_keys, google_pay_recipient_id"); + None + } + } } } } ) } - _ => None, + None => None, } } @@ -4557,7 +4560,7 @@ pub struct PazePaymentProcessingDetails { pub struct GooglePayPaymentProcessingDetails { pub google_pay_private_key: Secret<String>, pub google_pay_root_signing_keys: Secret<String>, - pub google_pay_recipient_id: Option<Secret<String>>, + pub google_pay_recipient_id: Secret<String>, } #[derive(Clone, Debug)] diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 65688c5d465..f6e5d1e7f05 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -1,4 +1,4 @@ -use api_models::payments as payment_types; +use api_models::{admin as admin_types, payments as payment_types}; use async_trait::async_trait; use common_utils::{ ext_traits::ByteSliceExt, @@ -8,10 +8,11 @@ use common_utils::{ use error_stack::{Report, ResultExt}; #[cfg(feature = "v2")] use hyperswitch_domain_models::payments::PaymentIntentData; -use masking::ExposeInterface; +use masking::{ExposeInterface, ExposeOptionInterface}; use super::{ConstructFlowSpecificData, Feature}; use crate::{ + consts::PROTOCOL, core::{ errors::{self, ConnectorErrorExt, RouterResult}, payments::{self, access_token, helpers, transformers, PaymentData}, @@ -828,6 +829,21 @@ fn create_gpay_session_token( connector: &api::ConnectorData, business_profile: &domain::Profile, ) -> RouterResult<types::PaymentsSessionRouterData> { + // connector_wallet_details is being parse into admin types to check specifically if google_pay field is present + // this is being done because apple_pay details from metadata is also being filled into connector_wallets_details + let connector_wallets_details = router_data + .connector_wallets_details + .clone() + .parse_value::<admin_types::ConnectorWalletDetails>("ConnectorWalletDetails") + .change_context(errors::ConnectorError::NoConnectorWalletDetails) + .attach_printable(format!( + "cannot parse connector_wallets_details from the given value {:?}", + router_data.connector_wallets_details + )) + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "connector_wallets_details".to_string(), + expected_format: "admin_types_connector_wallets_details_format".to_string(), + })?; let connector_metadata = router_data.connector_meta_data.clone(); let delayed_response = is_session_response_delayed(state, connector); @@ -849,18 +865,6 @@ fn create_gpay_session_token( ..router_data.clone() }) } else { - let gpay_data = connector_metadata - .clone() - .parse_value::<payment_types::GpaySessionTokenData>("GpaySessionTokenData") - .change_context(errors::ConnectorError::NoConnectorMetaData) - .attach_printable(format!( - "cannot parse gpay metadata from the given value {connector_metadata:?}" - )) - .change_context(errors::ApiErrorResponse::InvalidDataFormat { - field_name: "connector_metadata".to_string(), - expected_format: "gpay_metadata_format".to_string(), - })?; - let always_collect_billing_details_from_wallet_connector = business_profile .always_collect_billing_details_from_wallet_connector .unwrap_or(false); @@ -883,27 +887,6 @@ fn create_gpay_session_token( false }; - let billing_address_parameters = - is_billing_details_required.then_some(payment_types::GpayBillingAddressParameters { - phone_number_required: is_billing_details_required, - format: payment_types::GpayBillingAddressFormat::FULL, - }); - - let gpay_allowed_payment_methods = gpay_data - .data - .allowed_payment_methods - .into_iter() - .map( - |allowed_payment_methods| payment_types::GpayAllowedPaymentMethods { - parameters: payment_types::GpayAllowedMethodsParameters { - billing_address_required: Some(is_billing_details_required), - billing_address_parameters: billing_address_parameters.clone(), - ..allowed_payment_methods.parameters - }, - ..allowed_payment_methods - }, - ) - .collect(); let required_amount_type = StringMajorUnitForConnector; let google_pay_amount = required_amount_type .convert( @@ -945,39 +928,186 @@ fn create_gpay_session_token( false }; - Ok(types::PaymentsSessionRouterData { - response: Ok(types::PaymentsResponseData::SessionResponse { - session_token: payment_types::SessionToken::GooglePay(Box::new( - payment_types::GpaySessionTokenResponse::GooglePaySession( - payment_types::GooglePaySessionResponse { - merchant_info: gpay_data.data.merchant_info, - allowed_payment_methods: gpay_allowed_payment_methods, - transaction_info, - connector: connector.connector_name.to_string(), - sdk_next_action: payment_types::SdkNextAction { - next_action: payment_types::NextActionCall::Confirm, - }, - delayed_session_token: false, - secrets: None, - shipping_address_required: required_shipping_contact_fields, - // We pass Email as a required field irrespective of - // collect_billing_details_from_wallet_connector or - // collect_shipping_details_from_wallet_connector as it is common to both. - email_required: required_shipping_contact_fields - || is_billing_details_required, - shipping_address_parameters: - api_models::payments::GpayShippingAddressParameters { - phone_number_required: required_shipping_contact_fields, + if connector_wallets_details.google_pay.is_some() { + let gpay_data = router_data + .connector_wallets_details + .clone() + .parse_value::<payment_types::GooglePayWalletDetails>("GooglePayWalletDetails") + .change_context(errors::ConnectorError::NoConnectorWalletDetails) + .attach_printable(format!( + "cannot parse gpay connector_wallets_details from the given value {:?}", + router_data.connector_wallets_details + )) + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "connector_wallets_details".to_string(), + expected_format: "gpay_connector_wallets_details_format".to_string(), + })?; + + let payment_types::GooglePayProviderDetails::GooglePayMerchantDetails(gpay_info) = + gpay_data.google_pay.provider_details.clone(); + + let gpay_allowed_payment_methods = get_allowed_payment_methods_from_cards( + gpay_data, + &gpay_info.merchant_info.tokenization_specification, + is_billing_details_required, + )?; + + Ok(types::PaymentsSessionRouterData { + response: Ok(types::PaymentsResponseData::SessionResponse { + session_token: payment_types::SessionToken::GooglePay(Box::new( + payment_types::GpaySessionTokenResponse::GooglePaySession( + payment_types::GooglePaySessionResponse { + merchant_info: payment_types::GpayMerchantInfo { + merchant_name: gpay_info.merchant_info.merchant_name, + merchant_id: gpay_info.merchant_info.merchant_id, + }, + allowed_payment_methods: vec![gpay_allowed_payment_methods], + transaction_info, + connector: connector.connector_name.to_string(), + sdk_next_action: payment_types::SdkNextAction { + next_action: payment_types::NextActionCall::Confirm, }, + delayed_session_token: false, + secrets: None, + shipping_address_required: required_shipping_contact_fields, + // We pass Email as a required field irrespective of + // collect_billing_details_from_wallet_connector or + // collect_shipping_details_from_wallet_connector as it is common to both. + email_required: required_shipping_contact_fields + || is_billing_details_required, + shipping_address_parameters: + api_models::payments::GpayShippingAddressParameters { + phone_number_required: required_shipping_contact_fields, + }, + }, + ), + )), + }), + ..router_data.clone() + }) + } else { + let billing_address_parameters = is_billing_details_required.then_some( + payment_types::GpayBillingAddressParameters { + phone_number_required: is_billing_details_required, + format: payment_types::GpayBillingAddressFormat::FULL, + }, + ); + + let gpay_data = connector_metadata + .clone() + .parse_value::<payment_types::GpaySessionTokenData>("GpaySessionTokenData") + .change_context(errors::ConnectorError::NoConnectorMetaData) + .attach_printable(format!( + "cannot parse gpay metadata from the given value {connector_metadata:?}" + )) + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "connector_metadata".to_string(), + expected_format: "gpay_metadata_format".to_string(), + })?; + + let gpay_allowed_payment_methods = gpay_data + .data + .allowed_payment_methods + .into_iter() + .map( + |allowed_payment_methods| payment_types::GpayAllowedPaymentMethods { + parameters: payment_types::GpayAllowedMethodsParameters { + billing_address_required: Some(is_billing_details_required), + billing_address_parameters: billing_address_parameters.clone(), + ..allowed_payment_methods.parameters }, - ), - )), - }), - ..router_data.clone() - }) + ..allowed_payment_methods + }, + ) + .collect(); + + Ok(types::PaymentsSessionRouterData { + response: Ok(types::PaymentsResponseData::SessionResponse { + session_token: payment_types::SessionToken::GooglePay(Box::new( + payment_types::GpaySessionTokenResponse::GooglePaySession( + payment_types::GooglePaySessionResponse { + merchant_info: gpay_data.data.merchant_info, + allowed_payment_methods: gpay_allowed_payment_methods, + transaction_info, + connector: connector.connector_name.to_string(), + sdk_next_action: payment_types::SdkNextAction { + next_action: payment_types::NextActionCall::Confirm, + }, + delayed_session_token: false, + secrets: None, + shipping_address_required: required_shipping_contact_fields, + // We pass Email as a required field irrespective of + // collect_billing_details_from_wallet_connector or + // collect_shipping_details_from_wallet_connector as it is common to both. + email_required: required_shipping_contact_fields + || is_billing_details_required, + shipping_address_parameters: + api_models::payments::GpayShippingAddressParameters { + phone_number_required: required_shipping_contact_fields, + }, + }, + ), + )), + }), + ..router_data.clone() + }) + } } } +/// Card Type for Google Pay Allowerd Payment Methods +pub(crate) const CARD: &str = "CARD"; + +fn get_allowed_payment_methods_from_cards( + gpay_info: payment_types::GooglePayWalletDetails, + gpay_token_specific_data: &payment_types::GooglePayTokenizationSpecification, + is_billing_details_required: bool, +) -> RouterResult<payment_types::GpayAllowedPaymentMethods> { + let billing_address_parameters = + is_billing_details_required.then_some(payment_types::GpayBillingAddressParameters { + phone_number_required: is_billing_details_required, + format: payment_types::GpayBillingAddressFormat::FULL, + }); + + let protocol_version: Option<String> = gpay_token_specific_data + .parameters + .public_key + .as_ref() + .map(|_| PROTOCOL.to_string()); + + Ok(payment_types::GpayAllowedPaymentMethods { + parameters: payment_types::GpayAllowedMethodsParameters { + billing_address_required: Some(is_billing_details_required), + billing_address_parameters: billing_address_parameters.clone(), + ..gpay_info.google_pay.cards + }, + payment_method_type: CARD.to_string(), + tokenization_specification: payment_types::GpayTokenizationSpecification { + token_specification_type: gpay_token_specific_data.tokenization_type.to_string(), + parameters: payment_types::GpayTokenParameters { + protocol_version, + public_key: gpay_token_specific_data.parameters.public_key.clone(), + gateway: gpay_token_specific_data.parameters.gateway.clone(), + gateway_merchant_id: gpay_token_specific_data + .parameters + .gateway_merchant_id + .clone() + .expose_option(), + stripe_publishable_key: gpay_token_specific_data + .parameters + .stripe_publishable_key + .clone() + .expose_option(), + stripe_version: gpay_token_specific_data + .parameters + .stripe_version + .clone() + .expose_option(), + }, + }, + }) +} + fn is_session_response_delayed( state: &routes::SessionState, connector: &api::ConnectorData, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 28d843e2350..39bbef1f3d7 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -47,8 +47,8 @@ use openssl::{ }; #[cfg(feature = "v2")] use redis_interface::errors::RedisError; -use ring::hmac; use router_env::{instrument, logger, tracing}; +use serde::{Deserialize, Serialize}; use uuid::Uuid; use x509_parser::parse_x509_certificate; @@ -5267,7 +5267,7 @@ where Ok(connector_data_list) } -#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Serialize, Deserialize)] pub struct ApplePayData { version: masking::Secret<String>, data: masking::Secret<String>, @@ -5275,7 +5275,7 @@ pub struct ApplePayData { header: ApplePayHeader, } -#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayHeader { ephemeral_public_key: masking::Secret<String>, @@ -5430,13 +5430,10 @@ impl ApplePayData { } } -pub(crate) const SENDER_ID: &[u8] = b"Google"; -pub(crate) const PROTOCOL: &str = "ECv2"; - // Structs for keys and the main decryptor pub struct GooglePayTokenDecryptor { root_signing_keys: Vec<GooglePayRootSigningKey>, - recipient_id: Option<masking::Secret<String>>, + recipient_id: masking::Secret<String>, private_key: PKey<openssl::pkey::Private>, } @@ -5543,21 +5540,24 @@ fn filter_root_signing_keys( impl GooglePayTokenDecryptor { pub fn new( root_keys: masking::Secret<String>, - recipient_id: Option<masking::Secret<String>>, + recipient_id: masking::Secret<String>, private_key: masking::Secret<String>, ) -> CustomResult<Self, errors::GooglePayDecryptionError> { // base64 decode the private key let decoded_key = BASE64_ENGINE .decode(private_key.expose()) .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?; + // base64 decode the root signing keys + let decoded_root_signing_keys = BASE64_ENGINE + .decode(root_keys.expose()) + .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?; // create a private key from the decoded key let private_key = PKey::private_key_from_pkcs8(&decoded_key) .change_context(errors::GooglePayDecryptionError::KeyDeserializationFailed) .attach_printable("cannot convert private key from decode_key")?; // parse the root signing keys - let root_keys_vector: Vec<GooglePayRootSigningKey> = root_keys - .expose() + let root_keys_vector: Vec<GooglePayRootSigningKey> = decoded_root_signing_keys .parse_struct("GooglePayRootSigningKey") .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?; @@ -5663,13 +5663,13 @@ impl GooglePayTokenDecryptor { } // get the sender id i.e. Google - let sender_id = String::from_utf8(SENDER_ID.to_vec()) + let sender_id = String::from_utf8(consts::SENDER_ID.to_vec()) .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?; // construct the signed data let signed_data = self.construct_signed_data_for_intermediate_signing_key_verification( &sender_id, - PROTOCOL, + consts::PROTOCOL, encrypted_data.intermediate_signing_key.signed_key.peek(), )?; @@ -5770,7 +5770,7 @@ impl GooglePayTokenDecryptor { .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?; // get the sender id i.e. Google - let sender_id = String::from_utf8(SENDER_ID.to_vec()) + let sender_id = String::from_utf8(consts::SENDER_ID.to_vec()) .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?; // serialize the signed message to string @@ -5780,7 +5780,7 @@ impl GooglePayTokenDecryptor { // construct the signed data let signed_data = self.construct_signed_data_for_signature_verification( &sender_id, - PROTOCOL, + consts::PROTOCOL, &signed_message, )?; @@ -5827,11 +5827,7 @@ impl GooglePayTokenDecryptor { protocol_version: &str, signed_key: &str, ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> { - let recipient_id = self - .recipient_id - .clone() - .ok_or(errors::GooglePayDecryptionError::RecipientIdNotFound)? - .expose(); + let recipient_id = self.recipient_id.clone().expose(); let length_of_sender_id = u32::try_from(sender_id.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let length_of_recipient_id = u32::try_from(recipient_id.len()) @@ -5911,13 +5907,14 @@ impl GooglePayTokenDecryptor { // derive 64 bytes for the output key (symmetric encryption + MAC key) let mut output_key = vec![0u8; 64]; - hkdf.expand(SENDER_ID, &mut output_key).map_err(|err| { - logger::error!( + hkdf.expand(consts::SENDER_ID, &mut output_key) + .map_err(|err| { + logger::error!( "Failed to derive the shared ephemeral key for Google Pay decryption flow: {:?}", err ); - report!(errors::GooglePayDecryptionError::DerivingSharedEphemeralKeyFailed) - })?; + report!(errors::GooglePayDecryptionError::DerivingSharedEphemeralKeyFailed) + })?; Ok(output_key) } @@ -5930,8 +5927,8 @@ impl GooglePayTokenDecryptor { tag: &[u8], encrypted_message: &[u8], ) -> CustomResult<(), errors::GooglePayDecryptionError> { - let hmac_key = hmac::Key::new(hmac::HMAC_SHA256, mac_key); - hmac::verify(&hmac_key, encrypted_message, tag) + let hmac_key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, mac_key); + ring::hmac::verify(&hmac_key, encrypted_message, tag) .change_context(errors::GooglePayDecryptionError::HmacVerificationFailed) } @@ -6024,7 +6021,7 @@ pub fn decrypt_paze_token( Ok(parsed_decrypted) } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JwsBody { pub payload_id: String,
feat
add support to generate session token response from both `connector_wallets_details` and `metadata` (#7140)
c0f45771b0b4d7d60918ae03aca9f14162ff3218
2024-08-01 15:15:39
Pa1NarK
feat(cypress): add corner cases (#5481)
false
diff --git a/cypress-tests/cypress/e2e/PaymentTest/00020-Variations.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00020-Variations.cy.js new file mode 100644 index 00000000000..b413f0d0d0f --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentTest/00020-Variations.cy.js @@ -0,0 +1,325 @@ +import * as fixtures from "../../fixtures/imports"; +import State from "../../utils/State"; +import getConnectorDetails, * as utils from "../PaymentUtils/Utils"; + +let globalState; +let paymentIntentBody; +let paymentCreateConfirmBody; + +describe("Corner cases", () => { + // This is needed to get flush out old data + beforeEach("seed global state", () => { + paymentIntentBody = Cypress._.cloneDeep(fixtures.createPaymentBody); + paymentCreateConfirmBody = Cypress._.cloneDeep( + fixtures.createConfirmPaymentBody + ); + }); + + context("[Payment] [Payment create] Invalid Card Info", () => { + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + it("[Payment create] Invalid card number", () => { + let data = getConnectorDetails(globalState.get("commons"))["card_pm"][ + "invalidCardNumber" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + + cy.createConfirmPaymentTest( + paymentIntentBody, + req_data, + res_data, + "three_ds", + "automatic", + globalState + ); + }); + + it("[Payment create] Invalid expiry month", () => { + let data = getConnectorDetails(globalState.get("commons"))["card_pm"][ + "invalidExpiryMonth" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + + cy.createConfirmPaymentTest( + paymentIntentBody, + req_data, + res_data, + "three_ds", + "automatic", + globalState + ); + }); + + it("[Payment create] Invalid expiry year", () => { + let data = getConnectorDetails(globalState.get("commons"))["card_pm"][ + "invalidExpiryYear" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + + cy.createConfirmPaymentTest( + paymentIntentBody, + req_data, + res_data, + "three_ds", + "automatic", + globalState + ); + }); + + it("[Payment create] Invalid card CVV", () => { + let data = getConnectorDetails(globalState.get("commons"))["card_pm"][ + "invalidCardCvv" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + + cy.createConfirmPaymentTest( + paymentIntentBody, + req_data, + res_data, + "three_ds", + "automatic", + globalState + ); + }); + }); + + context("[Payment] Confirm w/o PMD", () => { + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + it("Create payment intent", () => { + let data = getConnectorDetails(globalState.get("commons"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + + cy.createPaymentIntentTest( + paymentIntentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState + ); + }); + + it("Confirm payment intent", () => { + let data = getConnectorDetails(globalState.get("commons"))["card_pm"][ + "PaymentIntentErrored" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + + cy.confirmCallTest( + fixtures.confirmBody, + req_data, + res_data, + true, + globalState + ); + }); + }); + + context("[Payment] Capture greater amount", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Create payment intent", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSManualCapture" + ]; + + let req_data = data["Request"]; + let res_data = data["Response"]; + + cy.createConfirmPaymentTest( + paymentCreateConfirmBody, + req_data, + res_data, + "no_three_ds", + "manual", + globalState + ); + + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Capture call", () => { + let data = getConnectorDetails(globalState.get("commons"))["card_pm"][ + "CaptureGreaterAmount" + ]; + + let req_data = data["Request"]; + let res_data = data["Response"]; + + cy.captureCallTest( + fixtures.captureBody, + req_data, + res_data, + 65000, + globalState + ); + + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }); + + context("[Payment] Capture successful payment", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Create payment intent", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSAutoCapture" + ]; + + let req_data = data["Request"]; + let res_data = data["Response"]; + + cy.createConfirmPaymentTest( + paymentCreateConfirmBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState + ); + + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Retrieve payment", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("Capture call", () => { + let data = getConnectorDetails(globalState.get("commons"))["card_pm"][ + "CaptureCapturedAmount" + ]; + + let req_data = data["Request"]; + let res_data = data["Response"]; + + cy.captureCallTest( + fixtures.captureBody, + req_data, + res_data, + 65000, + globalState + ); + + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }); + + context("[Payment] Void successful payment", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Create payment intent", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSAutoCapture" + ]; + + let req_data = data["Request"]; + let res_data = data["Response"]; + + cy.createConfirmPaymentTest( + paymentCreateConfirmBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState + ); + + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Retrieve payment", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("Void call", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "VoidErrored" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.voidCallTest(fixtures.voidBody, req_data, res_data, globalState); + + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }); +}); diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js b/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js index 1e2e7e0f3c3..92c21497b76 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js @@ -54,6 +54,7 @@ export const connectorDetails = { card_pm: { PaymentIntent: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -70,6 +71,7 @@ export const connectorDetails = { }, "3DSManualCapture": { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -86,6 +88,7 @@ export const connectorDetails = { }, "3DSAutoCapture": { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -102,6 +105,7 @@ export const connectorDetails = { }, No3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -118,6 +122,7 @@ export const connectorDetails = { }, No3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -134,6 +139,7 @@ export const connectorDetails = { }, Capture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -207,6 +213,7 @@ export const connectorDetails = { }, MandateSingleUse3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -222,6 +229,7 @@ export const connectorDetails = { }, MandateSingleUse3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -237,6 +245,7 @@ export const connectorDetails = { }, MandateSingleUseNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -252,6 +261,7 @@ export const connectorDetails = { }, MandateSingleUseNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -267,6 +277,7 @@ export const connectorDetails = { }, MandateMultiUseNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -282,6 +293,7 @@ export const connectorDetails = { }, MandateMultiUseNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -297,6 +309,7 @@ export const connectorDetails = { }, MandateMultiUse3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -312,6 +325,7 @@ export const connectorDetails = { }, MandateMultiUse3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -327,6 +341,7 @@ export const connectorDetails = { }, ZeroAuthMandate: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -342,6 +357,7 @@ export const connectorDetails = { }, SaveCardUseNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -365,6 +381,7 @@ export const connectorDetails = { }, SaveCardUseNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -388,6 +405,7 @@ export const connectorDetails = { }, PaymentMethodIdMandateNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -411,6 +429,7 @@ export const connectorDetails = { }, PaymentMethodIdMandateNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -434,6 +453,7 @@ export const connectorDetails = { }, PaymentMethodIdMandate3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -458,6 +478,7 @@ export const connectorDetails = { }, PaymentMethodIdMandate3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, diff --git a/cypress-tests/cypress/e2e/PaymentUtils/BankOfAmerica.js b/cypress-tests/cypress/e2e/PaymentUtils/BankOfAmerica.js index 544a0adec9b..675f17bbb09 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/BankOfAmerica.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/BankOfAmerica.js @@ -52,6 +52,7 @@ export const connectorDetails = { card_pm: { PaymentIntent: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -68,6 +69,7 @@ export const connectorDetails = { }, "3DSManualCapture": { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -84,6 +86,7 @@ export const connectorDetails = { }, "3DSAutoCapture": { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -100,6 +103,7 @@ export const connectorDetails = { }, No3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -116,6 +120,7 @@ export const connectorDetails = { }, No3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -132,6 +137,7 @@ export const connectorDetails = { }, Capture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -171,6 +177,7 @@ export const connectorDetails = { }, Refund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -186,6 +193,7 @@ export const connectorDetails = { }, PartialRefund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -201,6 +209,7 @@ export const connectorDetails = { }, SyncRefund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -216,6 +225,7 @@ export const connectorDetails = { }, MandateSingleUse3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -231,6 +241,7 @@ export const connectorDetails = { }, MandateSingleUse3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -246,6 +257,7 @@ export const connectorDetails = { }, MandateSingleUseNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -261,6 +273,7 @@ export const connectorDetails = { }, MandateSingleUseNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -276,6 +289,7 @@ export const connectorDetails = { }, MandateMultiUseNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -291,6 +305,7 @@ export const connectorDetails = { }, MandateMultiUseNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -306,6 +321,7 @@ export const connectorDetails = { }, MandateMultiUse3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -321,6 +337,7 @@ export const connectorDetails = { }, MandateMultiUse3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -336,6 +353,7 @@ export const connectorDetails = { }, ZeroAuthMandate: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -351,6 +369,7 @@ export const connectorDetails = { }, SaveCardUseNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -374,6 +393,7 @@ export const connectorDetails = { }, SaveCardUseNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -397,6 +417,7 @@ export const connectorDetails = { }, PaymentMethodIdMandateNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -420,6 +441,7 @@ export const connectorDetails = { }, PaymentMethodIdMandateNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -443,6 +465,7 @@ export const connectorDetails = { }, PaymentMethodIdMandate3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -467,6 +490,7 @@ export const connectorDetails = { }, PaymentMethodIdMandate3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Bluesnap.js b/cypress-tests/cypress/e2e/PaymentUtils/Bluesnap.js index 7a7e156b070..c019fb3c0be 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Bluesnap.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Bluesnap.js @@ -18,6 +18,7 @@ export const connectorDetails = { card_pm: { PaymentIntent: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -34,6 +35,7 @@ export const connectorDetails = { }, "3DSManualCapture": { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -51,6 +53,7 @@ export const connectorDetails = { }, "3DSAutoCapture": { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -68,6 +71,7 @@ export const connectorDetails = { }, No3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -84,6 +88,7 @@ export const connectorDetails = { }, No3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -100,6 +105,7 @@ export const connectorDetails = { }, Capture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -139,6 +145,7 @@ export const connectorDetails = { }, Refund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -154,6 +161,7 @@ export const connectorDetails = { }, PartialRefund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -169,6 +177,7 @@ export const connectorDetails = { }, SyncRefund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -196,6 +205,7 @@ export const connectorDetails = { }, SaveCardUseNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -219,6 +229,7 @@ export const connectorDetails = { }, SaveCardUseNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Commons.js b/cypress-tests/cypress/e2e/PaymentUtils/Commons.js index 9529665efb1..68c8fa61fc4 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Commons.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Commons.js @@ -784,6 +784,7 @@ export const connectorDetails = { }), PaymentMethodIdMandateNo3DSAutoCapture: getCustomExchange({ Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -801,6 +802,7 @@ export const connectorDetails = { }), PaymentMethodIdMandateNo3DSManualCapture: getCustomExchange({ Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -818,6 +820,7 @@ export const connectorDetails = { }), PaymentMethodIdMandate3DSAutoCapture: getCustomExchange({ Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -836,6 +839,7 @@ export const connectorDetails = { }), PaymentMethodIdMandate3DSManualCapture: getCustomExchange({ Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -851,6 +855,183 @@ export const connectorDetails = { }, }, }), + invalidCardNumber: { + Request: { + currency: "USD", + payment_method: "card", + payment_method_type: "debit", + setup_future_usage: "on_session", + payment_method_data: { + card: { + card_number: "123456", + card_exp_month: "10", + card_exp_year: "25", + card_holder_name: "joseph Doe", + card_cvc: "123", + }, + }, + }, + Response: { + status: 400, + body: { + error: "Json deserialize error: invalid card number length", + }, + }, + }, + invalidExpiryMonth: { + Request: { + currency: "USD", + payment_method: "card", + payment_method_type: "debit", + setup_future_usage: "on_session", + payment_method_data: { + card: { + card_number: "4242424242424242", + card_exp_month: "00", + card_exp_year: "2023", + card_holder_name: "joseph Doe", + card_cvc: "123", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Invalid Expiry Month", + code: "IR_16", + }, + }, + }, + }, + invalidExpiryYear: { + Request: { + currency: "USD", + payment_method: "card", + payment_method_type: "debit", + setup_future_usage: "on_session", + payment_method_data: { + card: { + card_number: "4242424242424242", + card_exp_month: "01", + card_exp_year: "2023", + card_holder_name: "joseph Doe", + card_cvc: "123", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Invalid Expiry Year", + code: "IR_16", + }, + }, + }, + }, + invalidCardCvv: { + Request: { + currency: "USD", + payment_method: "card", + payment_method_type: "debit", + setup_future_usage: "on_session", + payment_method_data: { + card: { + card_number: "4242424242424242", + card_exp_month: "01", + card_exp_year: "2023", + card_holder_name: "joseph Doe", + card_cvc: "123456", + }, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Invalid card_cvc length", + code: "IR_16", + }, + }, + }, + }, + PaymentIntentErrored: { + Request: { + currency: "USD", + }, + Response: { + status: 422, + body: { + error: { + type: "invalid_request", + message: "A payment token or payment method data is required", + code: "IR_06", + }, + }, + }, + }, + CaptureGreaterAmount: { + Request: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "USD", + customer_acceptance: null, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "amount_to_capture is greater than amount", + code: "IR_06", + }, + }, + }, + }, + CaptureCapturedAmount: { + Request: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "USD", + customer_acceptance: null, + }, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: + "This Payment could not be captured because it has a payment.status of succeeded. The expected state is requires_capture, partially_captured_and_capturable, processing", + code: "IR_14", + }, + }, + }, + }, + VoidErrored: getCustomExchange({ + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: + "You cannot cancel this payment because it has status succeeded", + code: "IR_16", + }, + }, + }, + }), }, upi_pm: { PaymentIntent: getCustomExchange({ diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js b/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js index 544a0adec9b..675f17bbb09 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js @@ -52,6 +52,7 @@ export const connectorDetails = { card_pm: { PaymentIntent: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -68,6 +69,7 @@ export const connectorDetails = { }, "3DSManualCapture": { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -84,6 +86,7 @@ export const connectorDetails = { }, "3DSAutoCapture": { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -100,6 +103,7 @@ export const connectorDetails = { }, No3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -116,6 +120,7 @@ export const connectorDetails = { }, No3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -132,6 +137,7 @@ export const connectorDetails = { }, Capture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -171,6 +177,7 @@ export const connectorDetails = { }, Refund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -186,6 +193,7 @@ export const connectorDetails = { }, PartialRefund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -201,6 +209,7 @@ export const connectorDetails = { }, SyncRefund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -216,6 +225,7 @@ export const connectorDetails = { }, MandateSingleUse3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -231,6 +241,7 @@ export const connectorDetails = { }, MandateSingleUse3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -246,6 +257,7 @@ export const connectorDetails = { }, MandateSingleUseNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -261,6 +273,7 @@ export const connectorDetails = { }, MandateSingleUseNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -276,6 +289,7 @@ export const connectorDetails = { }, MandateMultiUseNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -291,6 +305,7 @@ export const connectorDetails = { }, MandateMultiUseNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -306,6 +321,7 @@ export const connectorDetails = { }, MandateMultiUse3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -321,6 +337,7 @@ export const connectorDetails = { }, MandateMultiUse3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -336,6 +353,7 @@ export const connectorDetails = { }, ZeroAuthMandate: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -351,6 +369,7 @@ export const connectorDetails = { }, SaveCardUseNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -374,6 +393,7 @@ export const connectorDetails = { }, SaveCardUseNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -397,6 +417,7 @@ export const connectorDetails = { }, PaymentMethodIdMandateNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -420,6 +441,7 @@ export const connectorDetails = { }, PaymentMethodIdMandateNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -443,6 +465,7 @@ export const connectorDetails = { }, PaymentMethodIdMandate3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -467,6 +490,7 @@ export const connectorDetails = { }, PaymentMethodIdMandate3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Datatrans.js b/cypress-tests/cypress/e2e/PaymentUtils/Datatrans.js index bec505e55c3..ccca47c82af 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Datatrans.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Datatrans.js @@ -1,131 +1,151 @@ const successfulNo3DSCardDetails = { - card_number: "4444090101010103", - card_exp_month: "06", - card_exp_year: "25", - card_holder_name: "joseph Doe", - card_cvc: "123", - }; - - export const connectorDetails = { - card_pm: { - PaymentIntent: { - Request: { + card_number: "4444090101010103", + card_exp_month: "06", + card_exp_year: "25", + card_holder_name: "joseph Doe", + card_cvc: "123", +}; + +export const connectorDetails = { + card_pm: { + PaymentIntent: { + Request: { + payment_method: "card", + payment_method_data: { card: successfulNo3DSCardDetails, - currency: "USD", - customer_acceptance: null, - setup_future_usage: "on_session", }, - Response: { - status: 200, - body: { - status: "requires_payment_method", - }, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", }, }, - No3DSManualCapture: { - Request: { + }, + No3DSManualCapture: { + Request: { + payment_method: "card", + payment_method_data: { card: successfulNo3DSCardDetails, - currency: "USD", - customer_acceptance: null, - setup_future_usage: "on_session", }, - Response: { - status: 200, - body: { - status: "requires_capture", - }, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_capture", }, }, - No3DSAutoCapture: { - Request: { + }, + No3DSAutoCapture: { + Request: { + payment_method: "card", + payment_method_data: { card: successfulNo3DSCardDetails, - currency: "USD", - customer_acceptance: null, - setup_future_usage: "on_session", }, - Response: { - status: 200, - body: { - status: "succeeded", - }, + currency: "USD", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "succeeded", }, }, - Capture: { - Request: { + }, + Capture: { + Request: { + payment_method: "card", + payment_method_data: { card: successfulNo3DSCardDetails, - currency: "USD", - customer_acceptance: null, - }, - Response: { - status: 200, - body: { - status: "succeeded", - amount: 6500, - amount_capturable: 0, - amount_received: 6500, - }, - }, - }, - PartialCapture: { - Request: {}, - Response: { - status: 200, - body: { - status: "partially_captured", - amount: 6500, - amount_capturable: 0, - amount_received: 100, - }, - }, - }, - Void: { - Request: {}, - Response: { - status: 200, - body: { - status: "cancelled", - }, - }, - }, - Refund: { - Request: { + }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + amount: 6500, + amount_capturable: 0, + amount_received: 6500, + }, + }, + }, + PartialCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "partially_captured", + amount: 6500, + amount_capturable: 0, + amount_received: 100, + }, + }, + }, + Void: { + Request: {}, + Response: { + status: 200, + body: { + status: "cancelled", + }, + }, + }, + Refund: { + Request: { + payment_method: "card", + payment_method_data: { card: successfulNo3DSCardDetails, - currency: "USD", - customer_acceptance: null, }, - Response: { - status: 200, - body: { - status: "succeeded", - }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", }, }, - PartialRefund: { - Request: { + }, + PartialRefund: { + Request: { + payment_method: "card", + payment_method_data: { card: successfulNo3DSCardDetails, - currency: "USD", - customer_acceptance: null, }, - Response: { - status: 200, - body: { - status: "succeeded", - }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", }, }, - SyncRefund: { - Request: { + }, + SyncRefund: { + Request: { + payment_method: "card", + payment_method_data: { card: successfulNo3DSCardDetails, - currency: "USD", - customer_acceptance: null, }, - Response: { - status: 200, - body: { - status: "succeeded", - }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", }, }, }, + }, }; - \ No newline at end of file diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Nmi.js b/cypress-tests/cypress/e2e/PaymentUtils/Nmi.js index a5440c4ec88..e5f3304459a 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Nmi.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Nmi.js @@ -18,6 +18,7 @@ export const connectorDetails = { card_pm: { PaymentIntent: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -34,6 +35,7 @@ export const connectorDetails = { }, "3DSManualCapture": { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -50,6 +52,7 @@ export const connectorDetails = { }, "3DSAutoCapture": { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -66,6 +69,7 @@ export const connectorDetails = { }, No3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -82,6 +86,7 @@ export const connectorDetails = { }, No3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -98,6 +103,7 @@ export const connectorDetails = { }, Capture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -140,6 +146,7 @@ export const connectorDetails = { }, Refund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -155,6 +162,7 @@ export const connectorDetails = { }, PartialRefund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -170,6 +178,7 @@ export const connectorDetails = { }, SyncRefund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -197,6 +206,7 @@ export const connectorDetails = { }, SaveCardUseNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -220,6 +230,7 @@ export const connectorDetails = { }, SaveCardUseNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Paypal.js b/cypress-tests/cypress/e2e/PaymentUtils/Paypal.js index 256606c29c9..0471a742715 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Paypal.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Paypal.js @@ -20,6 +20,7 @@ export const connectorDetails = { card_pm: { PaymentIntent: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -36,6 +37,7 @@ export const connectorDetails = { }, "3DSManualCapture": { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -53,6 +55,7 @@ export const connectorDetails = { }, "3DSAutoCapture": { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -70,6 +73,7 @@ export const connectorDetails = { }, No3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -86,6 +90,7 @@ export const connectorDetails = { }, No3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -102,6 +107,7 @@ export const connectorDetails = { }, Capture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -141,6 +147,7 @@ export const connectorDetails = { }, Refund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -156,6 +163,7 @@ export const connectorDetails = { }, PartialRefund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -171,6 +179,7 @@ export const connectorDetails = { }, SyncRefund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -198,6 +207,7 @@ export const connectorDetails = { }, SaveCardUseNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -221,6 +231,7 @@ export const connectorDetails = { }, SaveCardUseNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js b/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js index f2cf89df243..ddbf47f2103 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js @@ -54,6 +54,7 @@ export const connectorDetails = { card_pm: { PaymentIntent: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -70,6 +71,7 @@ export const connectorDetails = { }, "3DSManualCapture": { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -86,6 +88,7 @@ export const connectorDetails = { }, "3DSAutoCapture": { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -102,6 +105,7 @@ export const connectorDetails = { }, No3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -118,6 +122,7 @@ export const connectorDetails = { }, No3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -134,6 +139,7 @@ export const connectorDetails = { }, Capture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -173,6 +179,7 @@ export const connectorDetails = { }, Refund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -188,6 +195,7 @@ export const connectorDetails = { }, PartialRefund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -203,6 +211,7 @@ export const connectorDetails = { }, SyncRefund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -218,6 +227,7 @@ export const connectorDetails = { }, MandateSingleUse3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -233,6 +243,7 @@ export const connectorDetails = { }, MandateSingleUse3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -248,6 +259,7 @@ export const connectorDetails = { }, MandateSingleUseNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -263,6 +275,7 @@ export const connectorDetails = { }, MandateSingleUseNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -278,6 +291,7 @@ export const connectorDetails = { }, MandateMultiUseNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -293,6 +307,7 @@ export const connectorDetails = { }, MandateMultiUseNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -308,6 +323,7 @@ export const connectorDetails = { }, MandateMultiUse3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -323,6 +339,7 @@ export const connectorDetails = { }, MandateMultiUse3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -338,6 +355,7 @@ export const connectorDetails = { }, ZeroAuthMandate: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -353,6 +371,7 @@ export const connectorDetails = { }, SaveCardUseNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -376,6 +395,7 @@ export const connectorDetails = { }, SaveCardUseNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -399,6 +419,7 @@ export const connectorDetails = { }, PaymentMethodIdMandateNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -422,6 +443,7 @@ export const connectorDetails = { }, PaymentMethodIdMandateNo3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -445,6 +467,7 @@ export const connectorDetails = { }, PaymentMethodIdMandate3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -469,6 +492,7 @@ export const connectorDetails = { }, PaymentMethodIdMandate3DSManualCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Trustpay.js b/cypress-tests/cypress/e2e/PaymentUtils/Trustpay.js index dae0b3a5dee..31a1d76a89c 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Trustpay.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Trustpay.js @@ -37,6 +37,7 @@ export const connectorDetails = { card_pm: { PaymentIntent: getCustomExchange({ Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -53,6 +54,7 @@ export const connectorDetails = { }), "3DSAutoCapture": { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -69,6 +71,7 @@ export const connectorDetails = { }, No3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -85,6 +88,7 @@ export const connectorDetails = { }, Capture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -105,6 +109,7 @@ export const connectorDetails = { }, PartialCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -138,6 +143,7 @@ export const connectorDetails = { }, Refund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -153,6 +159,7 @@ export const connectorDetails = { }, PartialRefund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -169,6 +176,7 @@ export const connectorDetails = { }, SyncRefund: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -184,6 +192,7 @@ export const connectorDetails = { }, MandateMultiUse3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulThreeDSTestCardDetails, }, @@ -211,6 +220,7 @@ export const connectorDetails = { }, SaveCardUseNo3DSAutoCapture: { Request: { + payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Utils.js b/cypress-tests/cypress/e2e/PaymentUtils/Utils.js index 27e0b2b937e..b22f5de535e 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Utils.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Utils.js @@ -6,13 +6,13 @@ import { updateDefaultStatusCode, } from "./Commons.js"; import { connectorDetails as cybersourceConnectorDetails } from "./Cybersource.js"; +import { connectorDetails as datatransConnectorDetails } from "./Datatrans.js"; import { connectorDetails as iatapayConnectorDetails } from "./Iatapay.js"; import { connectorDetails as itaubankConnectorDetails } from "./ItauBank.js"; import { connectorDetails as nmiConnectorDetails } from "./Nmi.js"; import { connectorDetails as paypalConnectorDetails } from "./Paypal.js"; import { connectorDetails as stripeConnectorDetails } from "./Stripe.js"; import { connectorDetails as trustpayConnectorDetails } from "./Trustpay.js"; -import { connectorDetails as datatransConnectorDetails } from "./Datatrans.js"; const connectorDetails = { adyen: adyenConnectorDetails, @@ -110,7 +110,12 @@ export function defaultErrorHandler(response, response_data) { } expect(response.body).to.have.property("error"); - for (const key in response_data.body.error) { - expect(response_data.body.error[key]).to.equal(response.body.error[key]); + + 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]); + } + } else if (typeof response.body.error === "string") { + expect(response.body.error).to.include(response_data.body.error); } } diff --git a/cypress-tests/cypress/fixtures/confirm-body.json b/cypress-tests/cypress/fixtures/confirm-body.json index fbf23a2016b..fa4769b627f 100644 --- a/cypress-tests/cypress/fixtures/confirm-body.json +++ b/cypress-tests/cypress/fixtures/confirm-body.json @@ -2,8 +2,6 @@ "client_secret": "", "return_url": "https://hyperswitch.io", "confirm": true, - "payment_method": "card", - "payment_method_data": {}, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z",
feat
add corner cases (#5481)
897612a64380778d7688269dd7227f4fbc5f8bc8
2024-04-16 05:33:06
github-actions
chore(version): 2024.04.16.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 738ae86f008..840019af383 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,21 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.04.16.0 + +### Features + +- **events:** Add payment cancel events ([#4166](https://github.com/juspay/hyperswitch/pull/4166)) ([`dea21c6`](https://github.com/juspay/hyperswitch/commit/dea21c65ffc872394caa39e29bcd6674d2e4f174)) +- **router:** Add `merchant_business_country` field in apple pay `session_token_data` ([#4236](https://github.com/juspay/hyperswitch/pull/4236)) ([`c3c8d09`](https://github.com/juspay/hyperswitch/commit/c3c8d094531df8092c1e9b772af75b22a7c2dccb)) + +### Miscellaneous Tasks + +- **configs:** [Zsl] Add configs for wasm ([#4346](https://github.com/juspay/hyperswitch/pull/4346)) ([`2f7faca`](https://github.com/juspay/hyperswitch/commit/2f7faca97e0ad47341e73a261fb9faff9043de13)) + +**Full Changelog:** [`2024.04.15.0...2024.04.16.0`](https://github.com/juspay/hyperswitch/compare/2024.04.15.0...2024.04.16.0) + +- - - + ## 2024.04.15.0 ### Bug Fixes
chore
2024.04.16.0
5be0c2bfd28e5a898842e1e24b51b41439aa92b3
2024-08-22 15:48:15
Sai Harsha Vardhan
refactor(router): add connector_transaction_id, send response body and use admin_api_auth_with_merchant_id for payments manual update flow (#5658)
false
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index 941cbb33309..c4459223a51 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -22,9 +22,9 @@ use crate::{ PaymentsApproveRequest, PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, PaymentsExternalAuthenticationRequest, PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest, - PaymentsManualUpdateRequest, PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, - PaymentsRetrieveRequest, PaymentsSessionResponse, PaymentsStartRequest, - RedirectionResponse, + PaymentsManualUpdateRequest, PaymentsManualUpdateResponse, PaymentsRejectRequest, + PaymentsRequest, PaymentsResponse, PaymentsRetrieveRequest, PaymentsSessionResponse, + PaymentsStartRequest, RedirectionResponse, }, }; impl ApiEventMetric for PaymentsRetrieveRequest { @@ -262,6 +262,14 @@ impl ApiEventMetric for PaymentsManualUpdateRequest { } } +impl ApiEventMetric for PaymentsManualUpdateResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Payment { + payment_id: self.payment_id.clone(), + }) + } +} + impl ApiEventMetric for PaymentsSessionResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index fcf884492ea..e303fbc9792 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -5054,6 +5054,29 @@ pub struct PaymentsManualUpdateRequest { pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, + /// A unique identifier for a payment provided by the connector + pub connector_transaction_id: Option<String>, +} + +#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] +pub struct PaymentsManualUpdateResponse { + /// The identifier for the payment + pub payment_id: String, + /// The identifier for the payment attempt + pub attempt_id: String, + /// Merchant ID + #[schema(value_type = String)] + pub merchant_id: id_type::MerchantId, + /// The status of the attempt + pub attempt_status: enums::AttemptStatus, + /// Error code of the connector + pub error_code: Option<String>, + /// Error message of the connector + pub error_message: Option<String>, + /// Error reason of the connector + pub error_reason: Option<String>, + /// A unique identifier for a payment provided by the connector + pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 525c681a1e5..84811f22624 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -436,6 +436,7 @@ pub enum PaymentAttemptUpdate { updated_by: String, unified_code: Option<String>, unified_message: Option<String>, + connector_transaction_id: Option<String>, }, } @@ -1645,6 +1646,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { updated_by, unified_code, unified_message, + connector_transaction_id, } => Self { status, error_code: error_code.map(Some), @@ -1657,7 +1659,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { amount: None, net_amount: None, currency: None, - connector_transaction_id: None, + connector_transaction_id, amount_to_capture: None, connector: None, authentication_type: None, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 54c86f3a4e1..5f2bc035f57 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -473,6 +473,7 @@ pub enum PaymentAttemptUpdate { updated_by: String, unified_code: Option<String>, unified_message: Option<String>, + connector_transaction_id: Option<String>, }, } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index db24b028800..287e144f396 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -4416,7 +4416,7 @@ pub async fn get_extended_card_info( pub async fn payments_manual_update( state: SessionState, req: api_models::payments::PaymentsManualUpdateRequest, -) -> RouterResponse<serde_json::Value> { +) -> RouterResponse<api_models::payments::PaymentsManualUpdateResponse> { let api_models::payments::PaymentsManualUpdateRequest { payment_id, attempt_id, @@ -4425,6 +4425,7 @@ pub async fn payments_manual_update( error_code, error_message, error_reason, + connector_transaction_id, } = req; let key_manager_state = &(&state).into(); let key_store = state @@ -4494,6 +4495,7 @@ pub async fn payments_manual_update( updated_by: merchant_account.storage_scheme.to_string(), unified_code: option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone()), unified_message: option_gsm.and_then(|gsm| gsm.unified_message), + connector_transaction_id, }; let updated_payment_attempt = state .store @@ -4525,5 +4527,16 @@ pub async fn payments_manual_update( .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Error while updating payment_intent")?; } - Ok(services::ApplicationResponse::StatusOk) + Ok(services::ApplicationResponse::Json( + api_models::payments::PaymentsManualUpdateResponse { + payment_id: updated_payment_attempt.payment_id, + attempt_id: updated_payment_attempt.attempt_id, + merchant_id: updated_payment_attempt.merchant_id, + attempt_status: updated_payment_attempt.status, + error_code: updated_payment_attempt.error_code, + error_message: updated_payment_attempt.error_message, + error_reason: updated_payment_attempt.error_reason, + connector_transaction_id: updated_payment_attempt.connector_transaction_id, + }, + )) } diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 38ab38925eb..d0c4cf42b7f 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -1486,7 +1486,7 @@ pub async fn payments_manual_update( &req, payload, |state, _auth, req, _req_state| payments::payments_manual_update(state, req), - &auth::AdminApiAuth, + &auth::AdminApiAuthWithMerchantId::default(), locking_action, )) .await diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 03a9ac6e454..a599618615f 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -1917,6 +1917,7 @@ impl DataModelExt for PaymentAttemptUpdate { updated_by, unified_code, unified_message, + connector_transaction_id, } => DieselPaymentAttemptUpdate::ManualUpdate { status, error_code, @@ -1925,6 +1926,7 @@ impl DataModelExt for PaymentAttemptUpdate { updated_by, unified_code, unified_message, + connector_transaction_id, }, } } @@ -2267,6 +2269,7 @@ impl DataModelExt for PaymentAttemptUpdate { updated_by, unified_code, unified_message, + connector_transaction_id, } => Self::ManualUpdate { status, error_code, @@ -2275,6 +2278,7 @@ impl DataModelExt for PaymentAttemptUpdate { updated_by, unified_code, unified_message, + connector_transaction_id, }, } }
refactor
add connector_transaction_id, send response body and use admin_api_auth_with_merchant_id for payments manual update flow (#5658)
7777c5ca84f21d3e5e6360af5a1d72df26402f03
2023-09-07 23:05:20
github-actions
chore(version): v1.36.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 78019766add..76a6b621d9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,29 @@ All notable changes to HyperSwitch will be documented here. - - - +## 1.36.0 (2023-09-07) + +### Features + +- **apple_pay:** Add support for pre decrypted apple pay token ([#2056](https://github.com/juspay/hyperswitch/pull/2056)) ([`75ee632`](https://github.com/juspay/hyperswitch/commit/75ee6327820fe31ff2c379250eae3e7974e6ae6c)) + +### Refactors + +- **connector:** + - [Payme] Rename types to follow naming conventions ([#2096](https://github.com/juspay/hyperswitch/pull/2096)) ([`98d7005`](https://github.com/juspay/hyperswitch/commit/98d70054e25ad8b2473110f7cde803f119b69d37)) + - [Payme] Response Handling for Preprocessing ([#2097](https://github.com/juspay/hyperswitch/pull/2097)) ([`bdf4832`](https://github.com/juspay/hyperswitch/commit/bdf48320f9d4f1dc8c13f42f6e1e06d1056acf33)) +- **router:** Changed auth of verify_apple_pay from mid to jwt ([#2094](https://github.com/juspay/hyperswitch/pull/2094)) ([`8246f4e`](https://github.com/juspay/hyperswitch/commit/8246f4e9c336152ca79e916375cd11618af4d90a)) + +### Miscellaneous Tasks + +- **deps:** Bump webpki from 0.22.0 to 0.22.1 ([#2104](https://github.com/juspay/hyperswitch/pull/2104)) ([`81c6480`](https://github.com/juspay/hyperswitch/commit/81c6480bdf2ab65b433ff2e89fcc299198019307)) +- Address Rust 1.72 clippy lints ([#2099](https://github.com/juspay/hyperswitch/pull/2099)) ([`cbbebe2`](https://github.com/juspay/hyperswitch/commit/cbbebe2408093d84a51b3916ea5a43d79404b4e9)) + +**Full Changelog:** [`v1.35.0...v1.36.0`](https://github.com/juspay/hyperswitch/compare/v1.35.0...v1.36.0) + +- - - + + ## 1.35.0 (2023-09-06) ### Features
chore
v1.36.0
5b89209b6f48691ee5ae2f9ede0d913abc9105f9
2024-04-08 17:21:41
Shankar Singh C
fix(psync): log the error if payment method retrieve fails in the `psync flow` (#4321)
false
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 7a8f487d73a..f25b89977f6 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -5,7 +5,7 @@ use async_trait::async_trait; use common_utils::ext_traits::AsyncExt; use error_stack::ResultExt; use router_derive::PaymentOperation; -use router_env::{instrument, tracing}; +use router_env::{instrument, logger, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ @@ -399,14 +399,22 @@ async fn get_tracker_for_sync< .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_id.to_string(), })?; + let payment_method_info = if let Some(ref payment_method_id) = payment_attempt.payment_method_id.clone() { - Some( - db.find_payment_method(payment_method_id) - .await - .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) - .attach_printable("error retrieving payment method from DB")?, - ) + match db.find_payment_method(payment_method_id).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")? + } + } + } } else { None };
fix
log the error if payment method retrieve fails in the `psync flow` (#4321)
08e9c079ce34219e9e2b09575fb6213c51f95ba4
2022-12-20 18:00:40
Sangamesh Kulkarni
refactor(compatibility): remove specific imports (#181)
false
diff --git a/crates/router/src/compatibility/stripe.rs b/crates/router/src/compatibility/stripe.rs index 9781f454526..e9a65cb6ca3 100644 --- a/crates/router/src/compatibility/stripe.rs +++ b/crates/router/src/compatibility/stripe.rs @@ -5,21 +5,19 @@ mod refunds; mod setup_intents; use actix_web::{web, Scope}; mod errors; -pub(crate) use errors::ErrorCode; -pub(crate) use self::app::{Customers, PaymentIntents, Refunds, SetupIntents}; -use crate::routes::AppState; +use crate::routes; pub struct StripeApis; impl StripeApis { - pub(crate) fn server(state: AppState) -> Scope { + pub(crate) fn server(state: routes::AppState) -> Scope { let max_depth = 10; let strict = false; web::scope("/vs/v1") .app_data(web::Data::new(serde_qs::Config::new(max_depth, strict))) - .service(SetupIntents::server(state.clone())) - .service(PaymentIntents::server(state.clone())) - .service(Refunds::server(state.clone())) - .service(Customers::server(state)) + .service(app::SetupIntents::server(state.clone())) + .service(app::PaymentIntents::server(state.clone())) + .service(app::Refunds::server(state.clone())) + .service(app::Customers::server(state)) } } diff --git a/crates/router/src/compatibility/stripe/app.rs b/crates/router/src/compatibility/stripe/app.rs index 4e3ddab4c17..dd40d56200c 100644 --- a/crates/router/src/compatibility/stripe/app.rs +++ b/crates/router/src/compatibility/stripe/app.rs @@ -1,12 +1,12 @@ use actix_web::{web, Scope}; use super::{customers::*, payment_intents::*, refunds::*, setup_intents::*}; -use crate::routes::AppState; +use crate::routes; pub struct PaymentIntents; impl PaymentIntents { - pub fn server(state: AppState) -> Scope { + pub fn server(state: routes::AppState) -> Scope { web::scope("/payment_intents") .app_data(web::Data::new(state)) .service(payment_intents_create) @@ -20,7 +20,7 @@ impl PaymentIntents { pub struct SetupIntents; impl SetupIntents { - pub fn server(state: AppState) -> Scope { + pub fn server(state: routes::AppState) -> Scope { web::scope("/setup_intents") .app_data(web::Data::new(state)) .service(setup_intents_create) @@ -33,7 +33,7 @@ impl SetupIntents { pub struct Refunds; impl Refunds { - pub fn server(config: AppState) -> Scope { + pub fn server(config: routes::AppState) -> Scope { web::scope("/refunds") .app_data(web::Data::new(config)) .service(refund_create) @@ -45,7 +45,7 @@ impl Refunds { pub struct Customers; impl Customers { - pub fn server(config: AppState) -> Scope { + pub fn server(config: routes::AppState) -> Scope { web::scope("/customers") .app_data(web::Data::new(config)) .service(customer_create) diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs index 2dec79707d4..63aa120b263 100644 --- a/crates/router/src/compatibility/stripe/customers.rs +++ b/crates/router/src/compatibility/stripe/customers.rs @@ -5,9 +5,9 @@ use error_stack::report; use router_env::{tracing, tracing::instrument}; use crate::{ - compatibility::{stripe, wrap}, + compatibility::{stripe::errors, wrap}, core::customers, - routes::AppState, + routes, services::api, types::api::customers as customer_types, }; @@ -15,7 +15,7 @@ use crate::{ #[instrument(skip_all)] #[post("")] pub async fn customer_create( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, @@ -23,13 +23,13 @@ pub async fn customer_create( let payload: types::CreateCustomerRequest = match qs_config.deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { - return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) + return api::log_and_return_error_response(report!(errors::ErrorCode::from(err))) } }; let create_cust_req: customer_types::CustomerRequest = payload.into(); - wrap::compatibility_api_wrap::<_, _, _, _, _, types::CreateCustomerResponse, stripe::ErrorCode>( + wrap::compatibility_api_wrap::<_, _, _, _, _, types::CreateCustomerResponse, errors::ErrorCode>( &state, &req, create_cust_req, @@ -44,7 +44,7 @@ pub async fn customer_create( #[instrument(skip_all)] #[get("/{customer_id}")] pub async fn customer_retrieve( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { @@ -52,7 +52,7 @@ pub async fn customer_retrieve( customer_id: path.into_inner(), }; - wrap::compatibility_api_wrap::<_, _, _, _, _, types::CustomerRetrieveResponse, stripe::ErrorCode>( + wrap::compatibility_api_wrap::<_, _, _, _, _, types::CustomerRetrieveResponse, errors::ErrorCode>( &state, &req, payload, @@ -67,7 +67,7 @@ pub async fn customer_retrieve( #[instrument(skip_all)] #[post("/{customer_id}")] pub async fn customer_update( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, path: web::Path<String>, @@ -76,7 +76,7 @@ pub async fn customer_update( let payload: types::CustomerUpdateRequest = match qs_config.deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { - return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) + return api::log_and_return_error_response(report!(errors::ErrorCode::from(err))) } }; @@ -84,7 +84,7 @@ pub async fn customer_update( let mut cust_update_req: customer_types::CustomerRequest = payload.into(); cust_update_req.customer_id = customer_id; - wrap::compatibility_api_wrap::<_, _, _, _, _, types::CustomerUpdateResponse, stripe::ErrorCode>( + wrap::compatibility_api_wrap::<_, _, _, _, _, types::CustomerUpdateResponse, errors::ErrorCode>( &state, &req, cust_update_req, @@ -99,7 +99,7 @@ pub async fn customer_update( #[instrument(skip_all)] #[delete("/{customer_id}")] pub async fn customer_delete( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { @@ -107,7 +107,7 @@ pub async fn customer_delete( customer_id: path.into_inner(), }; - wrap::compatibility_api_wrap::<_, _, _, _, _, types::CustomerDeleteResponse, stripe::ErrorCode>( + wrap::compatibility_api_wrap::<_, _, _, _, _, types::CustomerDeleteResponse, errors::ErrorCode>( &state, &req, payload, diff --git a/crates/router/src/compatibility/stripe/customers/types.rs b/crates/router/src/compatibility/stripe/customers/types.rs index 015bd516cb2..f2519a04ff4 100644 --- a/crates/router/src/compatibility/stripe/customers/types.rs +++ b/crates/router/src/compatibility/stripe/customers/types.rs @@ -1,9 +1,9 @@ use std::{convert::From, default::Default}; -use masking::{Secret, WithType}; +use masking; use serde::{Deserialize, Serialize}; -use crate::{pii::Email, types::api}; +use crate::{pii, types::api}; #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub(crate) struct CustomerAddress { @@ -17,10 +17,10 @@ pub(crate) struct CustomerAddress { #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub(crate) struct CreateCustomerRequest { - pub(crate) email: Option<Secret<String, Email>>, + pub(crate) email: Option<masking::Secret<String, pii::Email>>, pub(crate) invoice_prefix: Option<String>, pub(crate) name: Option<String>, - pub(crate) phone: Option<Secret<String, WithType>>, + pub(crate) phone: Option<masking::Secret<String, masking::WithType>>, pub(crate) address: Option<CustomerAddress>, } @@ -28,8 +28,8 @@ pub(crate) struct CreateCustomerRequest { pub(crate) struct CustomerUpdateRequest { pub(crate) metadata: Option<String>, pub(crate) description: Option<String>, - pub(crate) email: Option<Secret<String, Email>>, - pub(crate) phone: Option<Secret<String, WithType>>, + pub(crate) email: Option<masking::Secret<String, pii::Email>>, + pub(crate) phone: Option<masking::Secret<String, masking::WithType>>, pub(crate) name: Option<String>, pub(crate) address: Option<CustomerAddress>, } @@ -40,10 +40,10 @@ pub(crate) struct CreateCustomerResponse { object: String, created: u64, description: Option<String>, - email: Option<Secret<String, Email>>, + email: Option<masking::Secret<String, pii::Email>>, metadata: Option<serde_json::Value>, name: Option<String>, - phone: Option<Secret<String, WithType>>, + phone: Option<masking::Secret<String, masking::WithType>>, } pub(crate) type CustomerRetrieveResponse = CreateCustomerResponse; diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index 3790e6d95d0..6231809045b 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -1,5 +1,5 @@ #![allow(unused_variables)] -use crate::core::errors::ApiErrorResponse; +use crate::core::errors; #[derive(Debug, router_derive::ApiError)] #[error(error_type_enum = StripeErrorType)] @@ -310,90 +310,100 @@ pub(crate) enum StripeErrorType { InvalidRequestError, } -impl From<ApiErrorResponse> for ErrorCode { - fn from(value: ApiErrorResponse) -> Self { +impl From<errors::ApiErrorResponse> for ErrorCode { + fn from(value: errors::ApiErrorResponse) -> Self { match value { - ApiErrorResponse::Unauthorized | ApiErrorResponse::InvalidEphermeralKey => { - ErrorCode::Unauthorized - } - ApiErrorResponse::InvalidRequestUrl | ApiErrorResponse::InvalidHttpMethod => { - ErrorCode::InvalidRequestUrl + errors::ApiErrorResponse::Unauthorized + | errors::ApiErrorResponse::InvalidEphermeralKey => ErrorCode::Unauthorized, + errors::ApiErrorResponse::InvalidRequestUrl + | errors::ApiErrorResponse::InvalidHttpMethod => ErrorCode::InvalidRequestUrl, + errors::ApiErrorResponse::MissingRequiredField { field_name } => { + ErrorCode::ParameterMissing { + field_name: field_name.to_owned(), + param: field_name, + } } - ApiErrorResponse::MissingRequiredField { field_name } => ErrorCode::ParameterMissing { - field_name: field_name.to_owned(), - param: field_name, - }, // parameter unknown, invalid request error // actually if we type wrong values in address we get this error. Stripe throws parameter unknown. I don't know if stripe is validating email and stuff - ApiErrorResponse::InvalidDataFormat { + errors::ApiErrorResponse::InvalidDataFormat { field_name, expected_format, } => ErrorCode::ParameterUnknown { field_name, expected_format, }, - ApiErrorResponse::RefundAmountExceedsPaymentAmount => { + errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount => { ErrorCode::RefundAmountExceedsPaymentAmount { param: "amount".to_owned(), } } - ApiErrorResponse::PaymentAuthorizationFailed { data } - | ApiErrorResponse::PaymentAuthenticationFailed { data } => { + errors::ApiErrorResponse::PaymentAuthorizationFailed { data } + | errors::ApiErrorResponse::PaymentAuthenticationFailed { data } => { ErrorCode::PaymentIntentAuthenticationFailure { data } } - ApiErrorResponse::VerificationFailed { data } => ErrorCode::VerificationFailed { data }, - ApiErrorResponse::PaymentCaptureFailed { data } => { + errors::ApiErrorResponse::VerificationFailed { data } => { + ErrorCode::VerificationFailed { data } + } + errors::ApiErrorResponse::PaymentCaptureFailed { data } => { ErrorCode::PaymentIntentPaymentAttemptFailed { data } } - ApiErrorResponse::InvalidCardData { data } => ErrorCode::InvalidCardType, // Maybe it is better to de generalize this router error - ApiErrorResponse::CardExpired { data } => ErrorCode::ExpiredCard, - ApiErrorResponse::RefundFailed { data } => ErrorCode::RefundFailed, // Nothing at stripe to map - - ApiErrorResponse::InternalServerError => ErrorCode::InternalServerError, // not a stripe code - ApiErrorResponse::IncorrectConnectorNameGiven => ErrorCode::InternalServerError, - ApiErrorResponse::MandateActive => ErrorCode::MandateActive, //not a stripe code - ApiErrorResponse::CustomerRedacted => ErrorCode::CustomerRedacted, //not a stripe code - ApiErrorResponse::DuplicateRefundRequest => ErrorCode::DuplicateRefundRequest, - ApiErrorResponse::RefundNotFound => ErrorCode::RefundNotFound, - ApiErrorResponse::CustomerNotFound => ErrorCode::CustomerNotFound, - ApiErrorResponse::PaymentNotFound => ErrorCode::PaymentNotFound, - ApiErrorResponse::PaymentMethodNotFound => ErrorCode::PaymentMethodNotFound, - ApiErrorResponse::ClientSecretNotGiven => ErrorCode::ClientSecretNotFound, - ApiErrorResponse::MerchantAccountNotFound => ErrorCode::MerchantAccountNotFound, - ApiErrorResponse::ResourceIdNotFound => ErrorCode::ResourceIdNotFound, - ApiErrorResponse::MerchantConnectorAccountNotFound => { + errors::ApiErrorResponse::InvalidCardData { data } => ErrorCode::InvalidCardType, // Maybe it is better to de generalize this router error + errors::ApiErrorResponse::CardExpired { data } => ErrorCode::ExpiredCard, + errors::ApiErrorResponse::RefundFailed { data } => ErrorCode::RefundFailed, // Nothing at stripe to map + + errors::ApiErrorResponse::InternalServerError => ErrorCode::InternalServerError, // not a stripe code + errors::ApiErrorResponse::IncorrectConnectorNameGiven => ErrorCode::InternalServerError, + errors::ApiErrorResponse::MandateActive => ErrorCode::MandateActive, //not a stripe code + errors::ApiErrorResponse::CustomerRedacted => ErrorCode::CustomerRedacted, //not a stripe code + errors::ApiErrorResponse::DuplicateRefundRequest => ErrorCode::DuplicateRefundRequest, + errors::ApiErrorResponse::RefundNotFound => ErrorCode::RefundNotFound, + errors::ApiErrorResponse::CustomerNotFound => ErrorCode::CustomerNotFound, + errors::ApiErrorResponse::PaymentNotFound => ErrorCode::PaymentNotFound, + errors::ApiErrorResponse::PaymentMethodNotFound => ErrorCode::PaymentMethodNotFound, + errors::ApiErrorResponse::ClientSecretNotGiven => ErrorCode::ClientSecretNotFound, + errors::ApiErrorResponse::MerchantAccountNotFound => ErrorCode::MerchantAccountNotFound, + errors::ApiErrorResponse::ResourceIdNotFound => ErrorCode::ResourceIdNotFound, + errors::ApiErrorResponse::MerchantConnectorAccountNotFound => { ErrorCode::MerchantConnectorAccountNotFound } - ApiErrorResponse::MandateNotFound => ErrorCode::MandateNotFound, - ApiErrorResponse::MandateValidationFailed { reason } => { + errors::ApiErrorResponse::MandateNotFound => ErrorCode::MandateNotFound, + errors::ApiErrorResponse::MandateValidationFailed { reason } => { ErrorCode::PaymentIntentMandateInvalid { message: reason } } - ApiErrorResponse::ReturnUrlUnavailable => ErrorCode::ReturnUrlUnavailable, - ApiErrorResponse::DuplicateMerchantAccount => ErrorCode::DuplicateMerchantAccount, - ApiErrorResponse::DuplicateMerchantConnectorAccount => { + errors::ApiErrorResponse::ReturnUrlUnavailable => ErrorCode::ReturnUrlUnavailable, + errors::ApiErrorResponse::DuplicateMerchantAccount => { + ErrorCode::DuplicateMerchantAccount + } + errors::ApiErrorResponse::DuplicateMerchantConnectorAccount => { ErrorCode::DuplicateMerchantConnectorAccount } - ApiErrorResponse::DuplicatePaymentMethod => ErrorCode::DuplicatePaymentMethod, - ApiErrorResponse::ClientSecretInvalid => ErrorCode::PaymentIntentInvalidParameter { - param: "client_secret".to_owned(), - }, - ApiErrorResponse::InvalidRequestData { message } => { + errors::ApiErrorResponse::DuplicatePaymentMethod => ErrorCode::DuplicatePaymentMethod, + errors::ApiErrorResponse::ClientSecretInvalid => { + ErrorCode::PaymentIntentInvalidParameter { + param: "client_secret".to_owned(), + } + } + errors::ApiErrorResponse::InvalidRequestData { message } => { ErrorCode::InvalidRequestData { message } } - ApiErrorResponse::PreconditionFailed { message } => { + errors::ApiErrorResponse::PreconditionFailed { message } => { ErrorCode::PreconditionFailed { message } } - ApiErrorResponse::BadCredentials => ErrorCode::Unauthorized, - ApiErrorResponse::InvalidDataValue { field_name } => ErrorCode::ParameterMissing { - field_name: field_name.to_owned(), - param: field_name.to_owned(), - }, - ApiErrorResponse::MaximumRefundCount => ErrorCode::MaximumRefundCount, - ApiErrorResponse::PaymentNotSucceeded => ErrorCode::PaymentFailed, - ApiErrorResponse::DuplicateMandate => ErrorCode::DuplicateMandate, - ApiErrorResponse::SuccessfulPaymentNotFound => ErrorCode::SuccessfulPaymentNotFound, - ApiErrorResponse::AddressNotFound => ErrorCode::AddressNotFound, - ApiErrorResponse::NotImplemented => ErrorCode::Unauthorized, - ApiErrorResponse::PaymentUnexpectedState { + errors::ApiErrorResponse::BadCredentials => ErrorCode::Unauthorized, + errors::ApiErrorResponse::InvalidDataValue { field_name } => { + ErrorCode::ParameterMissing { + field_name: field_name.to_owned(), + param: field_name.to_owned(), + } + } + errors::ApiErrorResponse::MaximumRefundCount => ErrorCode::MaximumRefundCount, + errors::ApiErrorResponse::PaymentNotSucceeded => ErrorCode::PaymentFailed, + errors::ApiErrorResponse::DuplicateMandate => ErrorCode::DuplicateMandate, + errors::ApiErrorResponse::SuccessfulPaymentNotFound => { + ErrorCode::SuccessfulPaymentNotFound + } + errors::ApiErrorResponse::AddressNotFound => ErrorCode::AddressNotFound, + errors::ApiErrorResponse::NotImplemented => ErrorCode::Unauthorized, + errors::ApiErrorResponse::PaymentUnexpectedState { current_flow, field_name, current_value, diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs index 3cead5fd8ca..61c73d2d061 100644 --- a/crates/router/src/compatibility/stripe/payment_intents.rs +++ b/crates/router/src/compatibility/stripe/payment_intents.rs @@ -1,25 +1,22 @@ mod types; use actix_web::{get, post, web, HttpRequest, HttpResponse}; +use api_models::payments as payment_types; use error_stack::report; use router_env::{tracing, tracing::instrument}; use crate::{ - compatibility::{stripe, wrap}, + compatibility::{stripe::errors, wrap}, core::payments, - routes::AppState, + routes, services::api, - types::api::{ - self as api_types, payments::PaymentsCaptureRequest, Authorize, Capture, PSync, - PaymentListConstraints, PaymentsCancelRequest, PaymentsRequest, PaymentsRetrieveRequest, - Void, - }, + types::api::{self as api_types}, }; #[post("")] #[instrument(skip_all)] pub async fn payment_intents_create( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, @@ -28,11 +25,11 @@ pub async fn payment_intents_create( match qs_config.deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { - return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) + return api::log_and_return_error_response(report!(errors::ErrorCode::from(err))) } }; - let create_payment_req: PaymentsRequest = payload.into(); + let create_payment_req: payment_types::PaymentsRequest = payload.into(); wrap::compatibility_api_wrap::< _, @@ -41,14 +38,14 @@ pub async fn payment_intents_create( _, _, types::StripePaymentIntentResponse, - stripe::ErrorCode, + errors::ErrorCode, >( &state, &req, create_payment_req, |state, merchant_account, req| { let connector = req.connector; - payments::payments_core::<Authorize, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _>( state, merchant_account, payments::PaymentCreate, @@ -66,11 +63,11 @@ pub async fn payment_intents_create( #[instrument(skip_all)] #[get("/{payment_id}")] pub async fn payment_intents_retrieve( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { - let payload = PaymentsRetrieveRequest { + let payload = payment_types::PaymentsRetrieveRequest { resource_id: api_types::PaymentIdType::PaymentIntentId(path.to_string()), merchant_id: None, force_sync: true, @@ -91,13 +88,13 @@ pub async fn payment_intents_retrieve( _, _, types::StripePaymentIntentResponse, - stripe::ErrorCode, + errors::ErrorCode, >( &state, &req, payload, |state, merchant_account, payload| { - payments::payments_core::<PSync, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _>( state, merchant_account, payments::PaymentStatus, @@ -115,7 +112,7 @@ pub async fn payment_intents_retrieve( #[instrument(skip_all)] #[post("/{payment_id}")] pub async fn payment_intents_update( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, @@ -126,11 +123,11 @@ pub async fn payment_intents_update( match qs_config.deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { - return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) + return api::log_and_return_error_response(report!(errors::ErrorCode::from(err))) } }; - let mut payload: PaymentsRequest = stripe_payload.into(); + let mut payload: payment_types::PaymentsRequest = stripe_payload.into(); payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id)); let auth_type; @@ -146,14 +143,14 @@ pub async fn payment_intents_update( _, _, types::StripePaymentIntentResponse, - stripe::ErrorCode, + errors::ErrorCode, >( &state, &req, payload, |state, merchant_account, req| { let connector = req.connector; - payments::payments_core::<Authorize, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _>( state, merchant_account, payments::PaymentUpdate, @@ -171,7 +168,7 @@ pub async fn payment_intents_update( #[instrument(skip_all)] #[post("/{payment_id}/confirm")] pub async fn payment_intents_confirm( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, @@ -182,11 +179,11 @@ pub async fn payment_intents_confirm( match qs_config.deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { - return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) + return api::log_and_return_error_response(report!(errors::ErrorCode::from(err))) } }; - let mut payload: PaymentsRequest = stripe_payload.into(); + let mut payload: payment_types::PaymentsRequest = stripe_payload.into(); payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id)); payload.confirm = Some(true); @@ -203,14 +200,14 @@ pub async fn payment_intents_confirm( _, _, types::StripePaymentIntentResponse, - stripe::ErrorCode, + errors::ErrorCode, >( &state, &req, payload, |state, merchant_account, req| { let connector = req.connector; - payments::payments_core::<Authorize, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _>( state, merchant_account, payments::PaymentConfirm, @@ -227,20 +224,21 @@ pub async fn payment_intents_confirm( #[post("/{payment_id}/capture")] pub async fn payment_intents_capture( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<String>, ) -> HttpResponse { - let stripe_payload: PaymentsCaptureRequest = match qs_config.deserialize_bytes(&form_payload) { - Ok(p) => p, - Err(err) => { - return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) - } - }; + let stripe_payload: payment_types::PaymentsCaptureRequest = + match qs_config.deserialize_bytes(&form_payload) { + Ok(p) => p, + Err(err) => { + return api::log_and_return_error_response(report!(errors::ErrorCode::from(err))) + } + }; - let capture_payload = PaymentsCaptureRequest { + let capture_payload = payment_types::PaymentsCaptureRequest { payment_id: Some(path.into_inner()), ..stripe_payload }; @@ -252,13 +250,13 @@ pub async fn payment_intents_capture( _, _, types::StripePaymentIntentResponse, - stripe::ErrorCode, + errors::ErrorCode, >( &state, &req, capture_payload, |state, merchant_account, payload| { - payments::payments_core::<Capture, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::Capture, api_types::PaymentsResponse, _, _, _>( state, merchant_account, payments::PaymentCapture, @@ -276,7 +274,7 @@ pub async fn payment_intents_capture( #[instrument(skip_all)] #[post("/{payment_id}/cancel")] pub async fn payment_intents_cancel( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, @@ -287,11 +285,11 @@ pub async fn payment_intents_cancel( match qs_config.deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { - return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) + return api::log_and_return_error_response(report!(errors::ErrorCode::from(err))) } }; - let mut payload: PaymentsCancelRequest = stripe_payload.into(); + let mut payload: payment_types::PaymentsCancelRequest = stripe_payload.into(); payload.payment_id = payment_id; let auth_type = match api::get_auth_type(&req) { @@ -306,13 +304,13 @@ pub async fn payment_intents_cancel( _, _, types::StripePaymentIntentResponse, - stripe::ErrorCode, + errors::ErrorCode, >( &state, &req, payload, |state, merchant_account, req| { - payments::payments_core::<Void, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::Void, api_types::PaymentsResponse, _, _, _>( state, merchant_account, payments::PaymentCancel, @@ -330,11 +328,11 @@ pub async fn payment_intents_cancel( #[instrument(skip_all)] #[get("/list")] pub async fn payment_intent_list( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, req: HttpRequest, payload: web::Query<types::StripePaymentListConstraints>, ) -> HttpResponse { - let payload = match PaymentListConstraints::try_from(payload.into_inner()) { + let payload = match payment_types::PaymentListConstraints::try_from(payload.into_inner()) { Ok(p) => p, Err(err) => return api::log_and_return_error_response(err), }; @@ -345,7 +343,7 @@ pub async fn payment_intent_list( _, _, types::StripePaymentIntentListResponse, - stripe::ErrorCode, + errors::ErrorCode, >( &state, &req, diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 8738d66d717..0aa8bf0825b 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -1,30 +1,23 @@ +use api_models::{payments, refunds}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use crate::{ - core::errors, - pii::Secret, - types::api::{ - enums as api_enums, Address, AddressDetails, CCard, PaymentListConstraints, - PaymentListResponse, PaymentMethod, PaymentsCancelRequest, PaymentsRequest, - PaymentsResponse, PhoneDetails, RefundResponse, - }, -}; +use crate::{core::errors, types::api::enums as api_enums}; #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub(crate) struct StripeBillingDetails { - pub(crate) address: Option<AddressDetails>, + pub(crate) address: Option<payments::AddressDetails>, pub(crate) email: Option<String>, pub(crate) name: Option<String>, pub(crate) phone: Option<String>, } -impl From<StripeBillingDetails> for Address { +impl From<StripeBillingDetails> for payments::Address { fn from(details: StripeBillingDetails) -> Self { Self { address: details.address, - phone: Some(PhoneDetails { - number: details.phone.map(Secret::new), + phone: Some(payments::PhoneDetails { + number: details.phone.map(masking::Secret::new), country_code: None, }), } @@ -71,41 +64,43 @@ pub(crate) enum StripePaymentMethodDetails { BankTransfer, } -impl From<StripeCard> for CCard { +impl From<StripeCard> for payments::CCard { fn from(card: StripeCard) -> Self { Self { - card_number: Secret::new(card.number), - card_exp_month: Secret::new(card.exp_month), - card_exp_year: Secret::new(card.exp_year), - card_holder_name: Secret::new("stripe_cust".to_owned()), - card_cvc: Secret::new(card.cvc), + card_number: masking::Secret::new(card.number), + card_exp_month: masking::Secret::new(card.exp_month), + card_exp_year: masking::Secret::new(card.exp_year), + card_holder_name: masking::Secret::new("stripe_cust".to_owned()), + card_cvc: masking::Secret::new(card.cvc), } } } -impl From<StripePaymentMethodDetails> for PaymentMethod { +impl From<StripePaymentMethodDetails> for payments::PaymentMethod { fn from(item: StripePaymentMethodDetails) -> Self { match item { - StripePaymentMethodDetails::Card(card) => PaymentMethod::Card(CCard::from(card)), - StripePaymentMethodDetails::BankTransfer => PaymentMethod::BankTransfer, + StripePaymentMethodDetails::Card(card) => { + payments::PaymentMethod::Card(payments::CCard::from(card)) + } + StripePaymentMethodDetails::BankTransfer => payments::PaymentMethod::BankTransfer, } } } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub(crate) struct Shipping { - pub(crate) address: Option<AddressDetails>, + pub(crate) address: Option<payments::AddressDetails>, pub(crate) name: Option<String>, pub(crate) carrier: Option<String>, pub(crate) phone: Option<String>, pub(crate) tracking_number: Option<String>, } -impl From<Shipping> for Address { +impl From<Shipping> for payments::Address { fn from(details: Shipping) -> Self { Self { address: details.address, - phone: Some(PhoneDetails { - number: details.phone.map(Secret::new), + phone: Some(payments::PhoneDetails { + number: details.phone.map(masking::Secret::new), country_code: None, }), } @@ -134,9 +129,9 @@ pub(crate) struct StripePaymentIntentRequest { pub(crate) client_secret: Option<String>, } -impl From<StripePaymentIntentRequest> for PaymentsRequest { +impl From<StripePaymentIntentRequest> for payments::PaymentsRequest { fn from(item: StripePaymentIntentRequest) -> Self { - PaymentsRequest { + payments::PaymentsRequest { amount: item.amount.map(|amount| amount.into()), connector: item.connector, currency: item.currency.as_ref().map(|c| c.to_uppercase()), @@ -144,31 +139,34 @@ impl From<StripePaymentIntentRequest> for PaymentsRequest { amount_to_capture: item.amount_capturable, confirm: item.confirm, customer_id: item.customer, - email: item.receipt_email.map(Secret::new), + email: item.receipt_email.map(masking::Secret::new), name: item .billing_details .as_ref() - .and_then(|b| b.name.as_ref().map(|x| Secret::new(x.to_owned()))), + .and_then(|b| b.name.as_ref().map(|x| masking::Secret::new(x.to_owned()))), phone: item .shipping .as_ref() - .and_then(|s| s.phone.as_ref().map(|x| Secret::new(x.to_owned()))), + .and_then(|s| s.phone.as_ref().map(|x| masking::Secret::new(x.to_owned()))), description: item.description, return_url: item.return_url, payment_method_data: item.payment_method_data.as_ref().and_then(|pmd| { pmd.payment_method_details .as_ref() - .map(|spmd| PaymentMethod::from(spmd.to_owned())) + .map(|spmd| payments::PaymentMethod::from(spmd.to_owned())) }), payment_method: item .payment_method_data .as_ref() .map(|pmd| api_enums::PaymentMethodType::from(pmd.stype.to_owned())), - shipping: item.shipping.as_ref().map(|s| Address::from(s.to_owned())), + shipping: item + .shipping + .as_ref() + .map(|s| payments::Address::from(s.to_owned())), billing: item .billing_details .as_ref() - .map(|b| Address::from(b.to_owned())), + .map(|b| payments::Address::from(b.to_owned())), statement_descriptor_name: item.statement_descriptor, statement_descriptor_suffix: item.statement_descriptor_suffix, metadata: item.metadata, @@ -235,7 +233,7 @@ pub(crate) struct StripePaymentCancelRequest { cancellation_reason: Option<CancellationReason>, } -impl From<StripePaymentCancelRequest> for PaymentsCancelRequest { +impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest { fn from(item: StripePaymentCancelRequest) -> Self { Self { cancellation_reason: item.cancellation_reason.map(|c| c.to_string()), @@ -258,16 +256,16 @@ pub(crate) struct StripePaymentIntentResponse { pub(crate) amount_capturable: Option<i64>, pub(crate) currency: String, pub(crate) status: StripePaymentStatus, - pub(crate) client_secret: Option<Secret<String>>, + pub(crate) client_secret: Option<masking::Secret<String>>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub(crate) created: Option<time::PrimitiveDateTime>, pub(crate) customer: Option<String>, - pub(crate) refunds: Option<Vec<RefundResponse>>, + pub(crate) refunds: Option<Vec<refunds::RefundResponse>>, pub(crate) mandate_id: Option<String>, } -impl From<PaymentsResponse> for StripePaymentIntentResponse { - fn from(resp: PaymentsResponse) -> Self { +impl From<payments::PaymentsResponse> for StripePaymentIntentResponse { + fn from(resp: payments::PaymentsResponse) -> Self { Self { object: "payment_intent".to_owned(), amount: resp.amount, @@ -307,7 +305,7 @@ fn default_limit() -> i64 { 10 } -impl TryFrom<StripePaymentListConstraints> for PaymentListConstraints { +impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentListConstraints) -> Result<Self, Self::Error> { Ok(Self { @@ -349,8 +347,8 @@ pub(crate) struct StripePaymentIntentListResponse { pub(crate) data: Vec<StripePaymentIntentResponse>, } -impl From<PaymentListResponse> for StripePaymentIntentListResponse { - fn from(it: PaymentListResponse) -> Self { +impl From<payments::PaymentListResponse> for StripePaymentIntentListResponse { + fn from(it: payments::PaymentListResponse) -> Self { Self { object: "list".to_string(), url: "/v1/payment_intents".to_string(), diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rs index 516c0ee005b..f76a56ebf2f 100644 --- a/crates/router/src/compatibility/stripe/refunds.rs +++ b/crates/router/src/compatibility/stripe/refunds.rs @@ -4,22 +4,22 @@ use actix_web::{get, post, web, HttpRequest, HttpResponse}; use router_env::{tracing, tracing::instrument}; use crate::{ - compatibility::{stripe, wrap}, + compatibility::{stripe::errors, wrap}, core::refunds, - routes::AppState, + routes, services::api, - types::api::refunds::RefundRequest, + types::api::refunds as refund_types, }; #[instrument(skip_all)] #[post("")] pub(crate) async fn refund_create( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, req: HttpRequest, form_payload: web::Form<types::StripeCreateRefundRequest>, ) -> HttpResponse { let payload = form_payload.into_inner(); - let create_refund_req: RefundRequest = payload.into(); + let create_refund_req: refund_types::RefundRequest = payload.into(); wrap::compatibility_api_wrap::< _, @@ -28,7 +28,7 @@ pub(crate) async fn refund_create( _, _, types::StripeCreateRefundResponse, - stripe::ErrorCode, + errors::ErrorCode, >( &state, &req, @@ -42,7 +42,7 @@ pub(crate) async fn refund_create( #[instrument(skip_all)] #[get("/{refund_id}")] pub(crate) async fn refund_retrieve( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { @@ -54,7 +54,7 @@ pub(crate) async fn refund_retrieve( _, _, types::StripeCreateRefundResponse, - stripe::ErrorCode, + errors::ErrorCode, >( &state, &req, @@ -75,14 +75,14 @@ pub(crate) async fn refund_retrieve( #[instrument(skip_all)] #[post("/{refund_id}")] pub(crate) async fn refund_update( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<String>, form_payload: web::Form<types::StripeCreateRefundRequest>, ) -> HttpResponse { let refund_id = path.into_inner(); let payload = form_payload.into_inner(); - let create_refund_update_req: RefundRequest = payload.into(); + let create_refund_update_req: refund_types::RefundRequest = payload.into(); wrap::compatibility_api_wrap::< _, @@ -91,7 +91,7 @@ pub(crate) async fn refund_update( _, _, types::StripeCreateRefundResponse, - stripe::ErrorCode, + errors::ErrorCode, >( &state, &req, diff --git a/crates/router/src/compatibility/stripe/refunds/types.rs b/crates/router/src/compatibility/stripe/refunds/types.rs index 2cae9b80c03..4f571868541 100644 --- a/crates/router/src/compatibility/stripe/refunds/types.rs +++ b/crates/router/src/compatibility/stripe/refunds/types.rs @@ -2,7 +2,7 @@ use std::{convert::From, default::Default}; use serde::{Deserialize, Serialize}; -use crate::types::api::refunds::{RefundRequest, RefundResponse, RefundStatus}; +use crate::types::api::refunds; #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub(crate) struct StripeCreateRefundRequest { @@ -29,7 +29,7 @@ pub(crate) enum StripeRefundStatus { RequiresAction, } -impl From<StripeCreateRefundRequest> for RefundRequest { +impl From<StripeCreateRefundRequest> for refunds::RefundRequest { fn from(req: StripeCreateRefundRequest) -> Self { Self { amount: req.amount, @@ -40,19 +40,19 @@ impl From<StripeCreateRefundRequest> for RefundRequest { } } -impl From<RefundStatus> for StripeRefundStatus { - fn from(status: RefundStatus) -> Self { +impl From<refunds::RefundStatus> for StripeRefundStatus { + fn from(status: refunds::RefundStatus) -> Self { match status { - RefundStatus::Succeeded => Self::Succeeded, - RefundStatus::Failed => Self::Failed, - RefundStatus::Pending => Self::Pending, - RefundStatus::Review => Self::RequiresAction, + refunds::RefundStatus::Succeeded => Self::Succeeded, + refunds::RefundStatus::Failed => Self::Failed, + refunds::RefundStatus::Pending => Self::Pending, + refunds::RefundStatus::Review => Self::RequiresAction, } } } -impl From<RefundResponse> for StripeCreateRefundResponse { - fn from(res: RefundResponse) -> Self { +impl From<refunds::RefundResponse> for StripeCreateRefundResponse { + fn from(res: refunds::RefundResponse) -> Self { Self { id: res.refund_id, amount: res.amount, diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs index 6a0cec28bea..c5450e9e00b 100644 --- a/crates/router/src/compatibility/stripe/setup_intents.rs +++ b/crates/router/src/compatibility/stripe/setup_intents.rs @@ -1,21 +1,22 @@ mod types; use actix_web::{get, post, web, HttpRequest, HttpResponse}; +use api_models::payments as payment_types; use error_stack::report; use router_env::{tracing, tracing::instrument}; use crate::{ - compatibility::{stripe, wrap}, + compatibility::{stripe::errors, wrap}, core::payments, - routes::AppState, + routes, services::api, - types::api::{self as api_types, PSync, PaymentsRequest, PaymentsRetrieveRequest, Verify}, + types::api::{self as api_types}, }; #[post("")] #[instrument(skip_all)] pub async fn setup_intents_create( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, @@ -24,11 +25,11 @@ pub async fn setup_intents_create( { Ok(p) => p, Err(err) => { - return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) + return api::log_and_return_error_response(report!(errors::ErrorCode::from(err))) } }; - let create_payment_req: PaymentsRequest = payload.into(); + let create_payment_req: payment_types::PaymentsRequest = payload.into(); wrap::compatibility_api_wrap::< _, @@ -37,14 +38,14 @@ pub async fn setup_intents_create( _, _, types::StripeSetupIntentResponse, - stripe::ErrorCode, + errors::ErrorCode, >( &state, &req, create_payment_req, |state, merchant_account, req| { let connector = req.connector; - payments::payments_core::<Verify, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::Verify, api_types::PaymentsResponse, _, _, _>( state, merchant_account, payments::PaymentCreate, @@ -62,11 +63,11 @@ pub async fn setup_intents_create( #[instrument(skip_all)] #[get("/{setup_id}")] pub async fn setup_intents_retrieve( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { - let payload = PaymentsRetrieveRequest { + let payload = payment_types::PaymentsRetrieveRequest { resource_id: api_types::PaymentIdType::PaymentIntentId(path.to_string()), merchant_id: None, force_sync: true, @@ -87,13 +88,13 @@ pub async fn setup_intents_retrieve( _, _, types::StripeSetupIntentResponse, - stripe::ErrorCode, + errors::ErrorCode, >( &state, &req, payload, |state, merchant_account, payload| { - payments::payments_core::<PSync, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _>( state, merchant_account, payments::PaymentStatus, @@ -111,7 +112,7 @@ pub async fn setup_intents_retrieve( #[instrument(skip_all)] #[post("/{setup_id}")] pub async fn setup_intents_update( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, @@ -122,11 +123,11 @@ pub async fn setup_intents_update( match qs_config.deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { - return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) + return api::log_and_return_error_response(report!(errors::ErrorCode::from(err))) } }; - let mut payload: PaymentsRequest = stripe_payload.into(); + let mut payload: payment_types::PaymentsRequest = stripe_payload.into(); payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id)); let auth_type; @@ -142,14 +143,14 @@ pub async fn setup_intents_update( _, _, types::StripeSetupIntentResponse, - stripe::ErrorCode, + errors::ErrorCode, >( &state, &req, payload, |state, merchant_account, req| { let connector = req.connector; - payments::payments_core::<Verify, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::Verify, api_types::PaymentsResponse, _, _, _>( state, merchant_account, payments::PaymentUpdate, @@ -167,7 +168,7 @@ pub async fn setup_intents_update( #[instrument(skip_all)] #[post("/{setup_id}/confirm")] pub async fn setup_intents_confirm( - state: web::Data<AppState>, + state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, @@ -178,11 +179,11 @@ pub async fn setup_intents_confirm( match qs_config.deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { - return api::log_and_return_error_response(report!(stripe::ErrorCode::from(err))) + return api::log_and_return_error_response(report!(errors::ErrorCode::from(err))) } }; - let mut payload: PaymentsRequest = stripe_payload.into(); + let mut payload: payment_types::PaymentsRequest = stripe_payload.into(); payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id)); payload.confirm = Some(true); @@ -199,14 +200,14 @@ pub async fn setup_intents_confirm( _, _, types::StripeSetupIntentResponse, - stripe::ErrorCode, + errors::ErrorCode, >( &state, &req, payload, |state, merchant_account, req| { let connector = req.connector; - payments::payments_core::<Verify, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::Verify, api_types::PaymentsResponse, _, _, _>( state, merchant_account, payments::PaymentConfirm, diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 3a058696e29..71ecb7a1a75 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -1,31 +1,27 @@ +use api_models::{payments, refunds}; use router_env::logger; use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::{ core::errors, - pii::Secret, - types::api::{ - self as api_types, enums as api_enums, Address, AddressDetails, CCard, - PaymentListConstraints, PaymentMethod, PaymentsCancelRequest, PaymentsRequest, - PaymentsResponse, PhoneDetails, RefundResponse, - }, + types::api::{self as api_types, enums as api_enums}, }; #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub(crate) struct StripeBillingDetails { - pub(crate) address: Option<AddressDetails>, + pub(crate) address: Option<payments::AddressDetails>, pub(crate) email: Option<String>, pub(crate) name: Option<String>, pub(crate) phone: Option<String>, } -impl From<StripeBillingDetails> for Address { +impl From<StripeBillingDetails> for payments::Address { fn from(details: StripeBillingDetails) -> Self { Self { address: details.address, - phone: Some(PhoneDetails { - number: details.phone.map(Secret::new), + phone: Some(payments::PhoneDetails { + number: details.phone.map(masking::Secret::new), country_code: None, }), } @@ -72,41 +68,43 @@ pub(crate) enum StripePaymentMethodDetails { BankTransfer, } -impl From<StripeCard> for CCard { +impl From<StripeCard> for payments::CCard { fn from(card: StripeCard) -> Self { Self { - card_number: Secret::new(card.number), - card_exp_month: Secret::new(card.exp_month), - card_exp_year: Secret::new(card.exp_year), - card_holder_name: Secret::new("stripe_cust".to_owned()), - card_cvc: Secret::new(card.cvc), + card_number: masking::Secret::new(card.number), + card_exp_month: masking::Secret::new(card.exp_month), + card_exp_year: masking::Secret::new(card.exp_year), + card_holder_name: masking::Secret::new("stripe_cust".to_owned()), + card_cvc: masking::Secret::new(card.cvc), } } } -impl From<StripePaymentMethodDetails> for PaymentMethod { +impl From<StripePaymentMethodDetails> for payments::PaymentMethod { fn from(item: StripePaymentMethodDetails) -> Self { match item { - StripePaymentMethodDetails::Card(card) => PaymentMethod::Card(CCard::from(card)), - StripePaymentMethodDetails::BankTransfer => PaymentMethod::BankTransfer, + StripePaymentMethodDetails::Card(card) => { + payments::PaymentMethod::Card(payments::CCard::from(card)) + } + StripePaymentMethodDetails::BankTransfer => payments::PaymentMethod::BankTransfer, } } } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub(crate) struct Shipping { - pub(crate) address: Option<AddressDetails>, + pub(crate) address: Option<payments::AddressDetails>, pub(crate) name: Option<String>, pub(crate) carrier: Option<String>, pub(crate) phone: Option<String>, pub(crate) tracking_number: Option<String>, } -impl From<Shipping> for Address { +impl From<Shipping> for payments::Address { fn from(details: Shipping) -> Self { Self { address: details.address, - phone: Some(PhoneDetails { - number: details.phone.map(Secret::new), + phone: Some(payments::PhoneDetails { + number: details.phone.map(masking::Secret::new), country_code: None, }), } @@ -129,40 +127,43 @@ pub(crate) struct StripeSetupIntentRequest { pub(crate) client_secret: Option<String>, } -impl From<StripeSetupIntentRequest> for PaymentsRequest { +impl From<StripeSetupIntentRequest> for payments::PaymentsRequest { fn from(item: StripeSetupIntentRequest) -> Self { - PaymentsRequest { + payments::PaymentsRequest { amount: Some(api_types::Amount::Zero), currency: Some(api_enums::Currency::default().to_string()), capture_method: None, amount_to_capture: None, confirm: item.confirm, customer_id: item.customer, - email: item.receipt_email.map(Secret::new), + email: item.receipt_email.map(masking::Secret::new), name: item .billing_details .as_ref() - .and_then(|b| b.name.as_ref().map(|x| Secret::new(x.to_owned()))), + .and_then(|b| b.name.as_ref().map(|x| masking::Secret::new(x.to_owned()))), phone: item .shipping .as_ref() - .and_then(|s| s.phone.as_ref().map(|x| Secret::new(x.to_owned()))), + .and_then(|s| s.phone.as_ref().map(|x| masking::Secret::new(x.to_owned()))), description: item.description, return_url: item.return_url, payment_method_data: item.payment_method_data.as_ref().and_then(|pmd| { pmd.payment_method_details .as_ref() - .map(|spmd| PaymentMethod::from(spmd.to_owned())) + .map(|spmd| payments::PaymentMethod::from(spmd.to_owned())) }), payment_method: item .payment_method_data .as_ref() .map(|pmd| api_enums::PaymentMethodType::from(pmd.stype.to_owned())), - shipping: item.shipping.as_ref().map(|s| Address::from(s.to_owned())), + shipping: item + .shipping + .as_ref() + .map(|s| payments::Address::from(s.to_owned())), billing: item .billing_details .as_ref() - .map(|b| Address::from(b.to_owned())), + .map(|b| payments::Address::from(b.to_owned())), statement_descriptor_name: item.statement_descriptor, statement_descriptor_suffix: item.statement_descriptor_suffix, metadata: item.metadata, @@ -232,7 +233,7 @@ pub(crate) struct StripePaymentCancelRequest { cancellation_reason: Option<CancellationReason>, } -impl From<StripePaymentCancelRequest> for PaymentsCancelRequest { +impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest { fn from(item: StripePaymentCancelRequest) -> Self { Self { cancellation_reason: item.cancellation_reason.map(|c| c.to_string()), @@ -245,16 +246,16 @@ pub(crate) struct StripeSetupIntentResponse { pub(crate) id: Option<String>, pub(crate) object: String, pub(crate) status: StripeSetupStatus, - pub(crate) client_secret: Option<Secret<String>>, + pub(crate) client_secret: Option<masking::Secret<String>>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub(crate) created: Option<time::PrimitiveDateTime>, pub(crate) customer: Option<String>, - pub(crate) refunds: Option<Vec<RefundResponse>>, + pub(crate) refunds: Option<Vec<refunds::RefundResponse>>, pub(crate) mandate_id: Option<String>, } -impl From<PaymentsResponse> for StripeSetupIntentResponse { - fn from(resp: PaymentsResponse) -> Self { +impl From<payments::PaymentsResponse> for StripeSetupIntentResponse { + fn from(resp: payments::PaymentsResponse) -> Self { Self { object: "setup_intent".to_owned(), status: StripeSetupStatus::from(resp.status), @@ -290,7 +291,7 @@ fn default_limit() -> i64 { 10 } -impl TryFrom<StripePaymentListConstraints> for PaymentListConstraints { +impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentListConstraints) -> Result<Self, Self::Error> { Ok(Self { diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs index 454c732b715..a1ef4a9179d 100644 --- a/crates/router/src/compatibility/wrap.rs +++ b/crates/router/src/compatibility/wrap.rs @@ -8,7 +8,7 @@ use serde::Serialize; use crate::{ core::errors::{self, RouterResult}, routes, - services::{api, build_redirection_form, logger, BachResponse}, + services::{api, logger}, types::storage, }; @@ -23,7 +23,7 @@ pub(crate) async fn compatibility_api_wrap<'a, 'b, A, T, Q, F, Fut, S, E>( where A: Into<api::ApiAuthentication<'a>> + std::fmt::Debug, F: Fn(&'b routes::AppState, storage::MerchantAccount, T) -> Fut, - Fut: Future<Output = RouterResult<BachResponse<Q>>>, + Fut: Future<Output = RouterResult<api::BachResponse<Q>>>, Q: Serialize + std::fmt::Debug + 'a, S: From<Q> + Serialize, E: From<errors::ApiErrorResponse> + Serialize + error_stack::Context + actix_web::ResponseError, @@ -32,7 +32,7 @@ where let api_authentication = api_authentication.into(); let resp = api::server_wrap_util(state, request, payload, func, api_authentication).await; match resp { - Ok(BachResponse::Json(router_resp)) => { + Ok(api::BachResponse::Json(router_resp)) => { let pg_resp = S::try_from(router_resp); match pg_resp { Ok(pg_resp) => match serde_json::to_string(&pg_resp) { @@ -54,19 +54,21 @@ where ), } } - Ok(BachResponse::StatusOk) => api::http_response_ok(), - Ok(BachResponse::TextPlain(text)) => api::http_response_plaintext(text), - Ok(BachResponse::JsonForRedirection(response)) => match serde_json::to_string(&response) { - Ok(res) => api::http_redirect_response(res, response), - Err(_) => api::http_response_err( - r#"{ + Ok(api::BachResponse::StatusOk) => api::http_response_ok(), + Ok(api::BachResponse::TextPlain(text)) => api::http_response_plaintext(text), + Ok(api::BachResponse::JsonForRedirection(response)) => { + match serde_json::to_string(&response) { + Ok(res) => api::http_redirect_response(res, response), + Err(_) => api::http_response_err( + r#"{ "error": { "message": "Error serializing response from connector" } }"#, - ), - }, - Ok(BachResponse::Form(form_data)) => build_redirection_form(&form_data) + ), + } + } + Ok(api::BachResponse::Form(form_data)) => api::build_redirection_form(&form_data) .respond_to(request) .map_into_boxed_body(), Err(error) => {
refactor
remove specific imports (#181)
625f5ae289ca93a1a6d469d6a0f71d7492f22bc5
2024-08-01 15:09:20
Sandeep Kumar
feat(opensearch): Updated status filter field name to match index and added time-range based search (#5468)
false
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs index 1031c815448..11ea4e4f7ab 100644 --- a/crates/analytics/src/opensearch.rs +++ b/crates/analytics/src/opensearch.rs @@ -1,6 +1,7 @@ use api_models::{ analytics::search::SearchIndex, errors::types::{ApiError, ApiErrorResponse}, + payments::TimeRange, }; use aws_config::{self, meta::region::RegionProviderChain, Region}; use common_utils::errors::{CustomResult, ErrorSwitch}; @@ -18,8 +19,9 @@ use opensearch::{ }, MsearchParts, OpenSearch, SearchParts, }; -use serde_json::{json, Value}; +use serde_json::{json, Map, Value}; use storage_impl::errors::ApplicationError; +use time::PrimitiveDateTime; use super::{health_check::HealthCheck, query::QueryResult, types::QueryExecutionError}; use crate::query::QueryBuildingError; @@ -40,6 +42,23 @@ pub struct OpenSearchIndexes { pub disputes: String, } +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash)] +pub struct OpensearchTimeRange { + #[serde(with = "common_utils::custom_serde::iso8601")] + pub gte: PrimitiveDateTime, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub lte: Option<PrimitiveDateTime>, +} + +impl From<TimeRange> for OpensearchTimeRange { + fn from(time_range: TimeRange) -> Self { + Self { + gte: time_range.start_time, + lte: time_range.end_time, + } + } +} + #[derive(Clone, Debug, serde::Deserialize)] pub struct OpenSearchConfig { host: String, @@ -377,6 +396,7 @@ pub struct OpenSearchQueryBuilder { pub offset: Option<i64>, pub count: Option<i64>, pub filters: Vec<(String, Vec<String>)>, + pub time_range: Option<OpensearchTimeRange>, } impl OpenSearchQueryBuilder { @@ -387,6 +407,7 @@ impl OpenSearchQueryBuilder { offset: Default::default(), count: Default::default(), filters: Default::default(), + time_range: Default::default(), } } @@ -396,27 +417,110 @@ impl OpenSearchQueryBuilder { Ok(()) } + pub fn set_time_range(&mut self, time_range: OpensearchTimeRange) -> QueryResult<()> { + self.time_range = Some(time_range); + Ok(()) + } + pub fn add_filter_clause(&mut self, lhs: String, rhs: Vec<String>) -> QueryResult<()> { self.filters.push((lhs, rhs)); Ok(()) } + pub fn get_status_field(&self, index: &SearchIndex) -> &str { + match index { + SearchIndex::Refunds => "refund_status.keyword", + SearchIndex::Disputes => "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 = - vec![json!({"multi_match": {"type": "phrase", "query": self.query, "lenient": true}})]; + let mut query_obj = Map::new(); + let mut bool_obj = Map::new(); + let mut filter_array = Vec::new(); + + filter_array.push(json!({ + "multi_match": { + "type": "phrase", + "query": self.query, + "lenient": true + } + })); let mut filters = self .filters .iter() - .map(|(k, v)| json!({"terms" : {k : v}})) + .map(|(k, v)| json!({"terms": {k: v}})) .collect::<Vec<Value>>(); - query.append(&mut filters); + filter_array.append(&mut filters); + + if let Some(ref time_range) = self.time_range { + let range = json!(time_range); + filter_array.push(json!({ + "range": { + "timestamp": range + } + })); + } + + bool_obj.insert("filter".to_string(), Value::Array(filter_array)); + query_obj.insert("bool".to_string(), Value::Object(bool_obj)); + + let mut query = Map::new(); + query.insert("query".to_string(), Value::Object(query_obj)); - // TODO add index specific filters Ok(indexes .iter() - .map(|_index| json!({"query": {"bool": {"filter": query}}})) + .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_query = Map::new(); + final_query.insert("bool".to_string(), json!({ "filter": updated_query })); + + let payload = json!({ "query": Value::Object(final_query) }); + payload + }) .collect::<Vec<Value>>()) } } diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs index 12ef7fb8d96..95b7f204b97 100644 --- a/crates/analytics/src/search.rs +++ b/crates/analytics/src/search.rs @@ -97,6 +97,10 @@ pub async fn msearch_results( }; }; + if let Some(time_range) = req.time_range { + query_builder.set_time_range(time_range.into()).switch()?; + }; + let response_text: OpenMsearchOutput = client .execute(query_builder) .await @@ -221,6 +225,11 @@ pub async fn search_results( } }; }; + + if let Some(time_range) = search_req.time_range { + query_builder.set_time_range(time_range.into()).switch()?; + }; + query_builder .set_offset_n_count(search_req.offset, search_req.count) .switch()?; diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs index f27af75936d..b962f60cae0 100644 --- a/crates/api_models/src/analytics/search.rs +++ b/crates/api_models/src/analytics/search.rs @@ -2,6 +2,8 @@ use common_utils::hashing::HashedString; use masking::WithType; use serde_json::Value; +use crate::payments::TimeRange; + #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct SearchFilters { pub payment_method: Option<Vec<String>>, @@ -26,6 +28,8 @@ pub struct GetGlobalSearchRequest { pub query: String, #[serde(default)] pub filters: Option<SearchFilters>, + #[serde(default)] + pub time_range: Option<TimeRange>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] @@ -36,6 +40,8 @@ pub struct GetSearchRequest { pub query: String, #[serde(default)] pub filters: Option<SearchFilters>, + #[serde(default)] + pub time_range: Option<TimeRange>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
feat
Updated status filter field name to match index and added time-range based search (#5468)
af20344856ede858dce3d7dccd769f1e6bce637b
2022-11-17 13:04:47
Sanchith Hegde
chore: track .gitignore
false
diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000000..2d3af89fd6b --- /dev/null +++ b/.gitignore @@ -0,0 +1,253 @@ +# Created by https://www.toptal.com/developers/gitignore/api/rust,visualstudiocode,clion,dotenv,direnv,linux,macos,windows +# Edit at https://www.toptal.com/developers/gitignore?templates=rust,visualstudiocode,clion,dotenv,direnv,linux,macos,windows + +### CLion ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### CLion Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +### direnv ### +.direnv +.envrc + +### dotenv ### +.env + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud + +### Rust ### +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +!Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +# Support for Project snippet scope +.vscode/*.code-snippets + +# Ignore code-workspaces +*.code-workspace + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# End of https://www.toptal.com/developers/gitignore/api/rust,visualstudiocode,clion,dotenv,direnv,linux,macos,windows + +# Orca Project specific excludes +# code coverage report +*.profraw +html/ +coverage.json +# other +logs/ +**/tmp +**/*.log +**/*.log.* +monitoring/*.tmp/ +config/Sandbox.toml +config/Production.toml
chore
track .gitignore
f72abe4b979873b06d75553c7412f8072c29c8a9
2024-09-17 16:26:08
Sanchith Hegde
refactor: add encryption support to payment attempt domain model (#5882)
false
diff --git a/.github/workflows/CI-pr.yml b/.github/workflows/CI-pr.yml index a31d0450010..4ea196e1c22 100644 --- a/.github/workflows/CI-pr.yml +++ b/.github/workflows/CI-pr.yml @@ -309,12 +309,15 @@ jobs: - name: Run cargo check with v2 features enabled shell: bash - # env: - # # Not denying warnings for now. - # # We only want to ensure successful compilation for now. - # RUSTFLAGS: "-D warnings -A clippy::todo" + env: + RUSTFLAGS: "-A warnings" + # Not denying warnings for now. + # We only want to ensure successful compilation for now. + # RUSTFLAGS: "-D warnings -A clippy::todo" run: just check_v2 - name: Run cargo check enabling only the release and v2 features shell: bash + env: + RUSTFLAGS: "-A warnings" run: cargo check --no-default-features --features "release,v2" diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index 68809d8d2fa..77d167402ef 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -172,7 +172,7 @@ common_utils::impl_to_sql_from_sql_json!(MandateDataType); #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct MandateAmountData { - pub amount: i64, + pub amount: common_utils::types::MinorUnit, pub currency: Currency, pub start_date: Option<PrimitiveDateTime>, pub end_date: Option<PrimitiveDateTime>, diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs index c8940c4c6b2..1cf7fc9d81c 100644 --- a/crates/diesel_models/src/kv.rs +++ b/crates/diesel_models/src/kv.rs @@ -1,6 +1,8 @@ use error_stack::ResultExt; use serde::{Deserialize, Serialize}; +#[cfg(all(feature = "v2", feature = "payment_v2"))] +use crate::payment_attempt::PaymentAttemptUpdateInternal; use crate::{ address::{Address, AddressNew, AddressUpdateInternal}, customers::{Customer, CustomerNew, CustomerUpdateInternal}, @@ -109,9 +111,19 @@ impl DBOperation { Updateable::PaymentIntentUpdate(a) => { DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?)) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new( a.orig.update_with_attempt_id(conn, a.update_data).await?, )), + #[cfg(all(feature = "v2", feature = "payment_v2"))] + Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new( + a.orig + .update_with_attempt_id( + conn, + PaymentAttemptUpdateInternal::from(a.update_data), + ) + .await?, + )), Updateable::RefundUpdate(a) => { DBResult::Refund(Box::new(a.orig.update(conn, a.update_data).await?)) } diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 152037d55fe..63ce905f65f 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -19,14 +19,14 @@ pub struct PaymentAttempt { pub merchant_id: id_type::MerchantId, pub attempt_id: String, pub status: storage_enums::AttemptStatus, - pub amount: i64, + pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub save_to_locker: Option<bool>, pub connector: Option<String>, pub error_message: Option<String>, - pub offer_amount: Option<i64>, - pub surcharge_amount: Option<i64>, - pub tax_amount: Option<i64>, + pub offer_amount: Option<MinorUnit>, + pub surcharge_amount: Option<MinorUnit>, + pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<String>, pub payment_method: Option<storage_enums::PaymentMethod>, pub connector_transaction_id: Option<String>, @@ -42,7 +42,7 @@ pub struct PaymentAttempt { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, - pub amount_to_capture: Option<i64>, + pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<String>, pub browser_info: Option<serde_json::Value>, pub error_code: Option<String>, @@ -60,14 +60,14 @@ pub struct PaymentAttempt { pub multiple_capture_count: Option<i16>, // reference to the payment at connector side pub connector_response_reference_id: Option<String>, - pub amount_capturable: i64, + pub amount_capturable: MinorUnit, pub updated_by: String, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, pub unified_code: Option<String>, pub unified_message: Option<String>, - pub net_amount: Option<i64>, + pub net_amount: Option<MinorUnit>, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<String>, @@ -95,14 +95,14 @@ pub struct PaymentAttempt { pub merchant_id: id_type::MerchantId, pub attempt_id: String, pub status: storage_enums::AttemptStatus, - pub amount: i64, + pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub save_to_locker: Option<bool>, pub connector: Option<String>, pub error_message: Option<String>, - pub offer_amount: Option<i64>, - pub surcharge_amount: Option<i64>, - pub tax_amount: Option<i64>, + pub offer_amount: Option<MinorUnit>, + pub surcharge_amount: Option<MinorUnit>, + pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<String>, pub payment_method: Option<storage_enums::PaymentMethod>, pub connector_transaction_id: Option<String>, @@ -118,7 +118,7 @@ pub struct PaymentAttempt { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, - pub amount_to_capture: Option<i64>, + pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<String>, pub browser_info: Option<serde_json::Value>, pub error_code: Option<String>, @@ -136,14 +136,14 @@ pub struct PaymentAttempt { pub multiple_capture_count: Option<i16>, // reference to the payment at connector side pub connector_response_reference_id: Option<String>, - pub amount_capturable: i64, + pub amount_capturable: MinorUnit, pub updated_by: String, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, pub unified_code: Option<String>, pub unified_message: Option<String>, - pub net_amount: Option<i64>, + pub net_amount: Option<MinorUnit>, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<String>, @@ -162,22 +162,13 @@ pub struct PaymentAttempt { } impl PaymentAttempt { - pub fn get_or_calculate_net_amount(&self) -> i64 { - let shipping_cost = self - .shipping_cost - .unwrap_or(MinorUnit::new(0)) - .get_amount_as_i64(); - let order_tax_amount = self - .order_tax_amount - .unwrap_or(MinorUnit::new(0)) - .get_amount_as_i64(); - + pub fn get_or_calculate_net_amount(&self) -> MinorUnit { self.net_amount.unwrap_or( self.amount - + self.surcharge_amount.unwrap_or(0) - + self.tax_amount.unwrap_or(0) - + shipping_cost - + order_tax_amount, + + self.surcharge_amount.unwrap_or(MinorUnit::new(0)) + + self.tax_amount.unwrap_or(MinorUnit::new(0)) + + self.shipping_cost.unwrap_or(MinorUnit::new(0)) + + self.order_tax_amount.unwrap_or(MinorUnit::new(0)), ) } } @@ -197,15 +188,15 @@ pub struct PaymentAttemptNew { pub merchant_id: id_type::MerchantId, pub attempt_id: String, pub status: storage_enums::AttemptStatus, - pub amount: i64, + pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, // pub auto_capture: Option<bool>, pub save_to_locker: Option<bool>, pub connector: Option<String>, pub error_message: Option<String>, - pub offer_amount: Option<i64>, - pub surcharge_amount: Option<i64>, - pub tax_amount: Option<i64>, + pub offer_amount: Option<MinorUnit>, + pub surcharge_amount: Option<MinorUnit>, + pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<String>, pub payment_method: Option<storage_enums::PaymentMethod>, pub capture_method: Option<storage_enums::CaptureMethod>, @@ -220,7 +211,7 @@ pub struct PaymentAttemptNew { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, - pub amount_to_capture: Option<i64>, + pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<String>, pub browser_info: Option<serde_json::Value>, pub payment_token: Option<String>, @@ -236,14 +227,14 @@ pub struct PaymentAttemptNew { pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub multiple_capture_count: Option<i16>, - pub amount_capturable: i64, + pub amount_capturable: MinorUnit, pub updated_by: String, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, pub unified_code: Option<String>, pub unified_message: Option<String>, - pub net_amount: Option<i64>, + pub net_amount: Option<MinorUnit>, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<String>, @@ -263,19 +254,14 @@ pub struct PaymentAttemptNew { impl PaymentAttemptNew { /// returns amount + surcharge_amount + tax_amount (surcharge) + shipping_cost + order_tax_amount - pub fn calculate_net_amount(&self) -> i64 { - let shipping_cost = self - .shipping_cost - .unwrap_or(MinorUnit::new(0)) - .get_amount_as_i64(); - + pub fn calculate_net_amount(&self) -> MinorUnit { self.amount - + self.surcharge_amount.unwrap_or(0) - + self.tax_amount.unwrap_or(0) - + shipping_cost + + self.surcharge_amount.unwrap_or(MinorUnit::new(0)) + + self.tax_amount.unwrap_or(MinorUnit::new(0)) + + self.shipping_cost.unwrap_or(MinorUnit::new(0)) } - pub fn get_or_calculate_net_amount(&self) -> i64 { + pub fn get_or_calculate_net_amount(&self) -> MinorUnit { self.net_amount .unwrap_or_else(|| self.calculate_net_amount()) } @@ -290,7 +276,7 @@ impl PaymentAttemptNew { #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentAttemptUpdate { Update { - amount: i64, + amount: MinorUnit, currency: storage_enums::Currency, status: storage_enums::AttemptStatus, authentication_type: Option<storage_enums::AuthenticationType>, @@ -300,10 +286,10 @@ pub enum PaymentAttemptUpdate { payment_method_type: Option<storage_enums::PaymentMethodType>, payment_experience: Option<storage_enums::PaymentExperience>, business_sub_label: Option<String>, - amount_to_capture: Option<i64>, + amount_to_capture: Option<MinorUnit>, capture_method: Option<storage_enums::CaptureMethod>, - surcharge_amount: Option<i64>, - tax_amount: Option<i64>, + surcharge_amount: Option<MinorUnit>, + tax_amount: Option<MinorUnit>, fingerprint_id: Option<String>, payment_method_billing_address_id: Option<String>, updated_by: String, @@ -312,9 +298,9 @@ pub enum PaymentAttemptUpdate { payment_token: Option<String>, connector: Option<String>, straight_through_algorithm: Option<serde_json::Value>, - amount_capturable: Option<i64>, - surcharge_amount: Option<i64>, - tax_amount: Option<i64>, + amount_capturable: Option<MinorUnit>, + surcharge_amount: Option<MinorUnit>, + tax_amount: Option<MinorUnit>, updated_by: String, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, }, @@ -323,7 +309,7 @@ pub enum PaymentAttemptUpdate { updated_by: String, }, ConfirmUpdate { - amount: i64, + amount: MinorUnit, currency: storage_enums::Currency, status: storage_enums::AttemptStatus, authentication_type: Option<storage_enums::AuthenticationType>, @@ -339,9 +325,9 @@ pub enum PaymentAttemptUpdate { straight_through_algorithm: Option<serde_json::Value>, error_code: Option<Option<String>>, error_message: Option<Option<String>>, - amount_capturable: Option<i64>, - surcharge_amount: Option<i64>, - tax_amount: Option<i64>, + amount_capturable: Option<MinorUnit>, + surcharge_amount: Option<MinorUnit>, + tax_amount: Option<MinorUnit>, fingerprint_id: Option<String>, updated_by: String, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, @@ -390,7 +376,7 @@ pub enum PaymentAttemptUpdate { error_message: Option<Option<String>>, error_reason: Option<Option<String>>, connector_response_reference_id: Option<String>, - amount_capturable: Option<i64>, + amount_capturable: Option<MinorUnit>, updated_by: String, authentication_data: Option<serde_json::Value>, encoded_data: Option<String>, @@ -420,7 +406,7 @@ pub enum PaymentAttemptUpdate { error_code: Option<Option<String>>, error_message: Option<Option<String>>, error_reason: Option<Option<String>>, - amount_capturable: Option<i64>, + amount_capturable: Option<MinorUnit>, updated_by: String, unified_code: Option<Option<String>>, unified_message: Option<Option<String>>, @@ -429,13 +415,13 @@ pub enum PaymentAttemptUpdate { authentication_type: Option<storage_enums::AuthenticationType>, }, CaptureUpdate { - amount_to_capture: Option<i64>, + amount_to_capture: Option<MinorUnit>, multiple_capture_count: Option<i16>, updated_by: String, }, AmountToCaptureUpdate { status: storage_enums::AttemptStatus, - amount_capturable: i64, + amount_capturable: MinorUnit, updated_by: String, }, PreprocessingUpdate { @@ -456,8 +442,8 @@ pub enum PaymentAttemptUpdate { updated_by: String, }, IncrementalAuthorizationAmountUpdate { - amount: i64, - amount_capturable: i64, + amount: MinorUnit, + amount_capturable: MinorUnit, }, AuthenticationUpdate { status: storage_enums::AttemptStatus, @@ -481,82 +467,78 @@ pub enum PaymentAttemptUpdate { #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payment_attempt)] pub struct PaymentAttemptUpdateInternal { - amount: Option<i64>, - net_amount: Option<i64>, - currency: Option<storage_enums::Currency>, - status: Option<storage_enums::AttemptStatus>, - connector_transaction_id: Option<String>, - amount_to_capture: Option<i64>, - connector: Option<Option<String>>, - authentication_type: Option<storage_enums::AuthenticationType>, - payment_method: Option<storage_enums::PaymentMethod>, - error_message: Option<Option<String>>, - payment_method_id: Option<String>, - cancellation_reason: Option<String>, - modified_at: PrimitiveDateTime, - mandate_id: Option<String>, - browser_info: Option<serde_json::Value>, - payment_token: Option<String>, - error_code: Option<Option<String>>, - connector_metadata: Option<serde_json::Value>, - payment_method_data: Option<serde_json::Value>, - payment_method_type: Option<storage_enums::PaymentMethodType>, - payment_experience: Option<storage_enums::PaymentExperience>, - business_sub_label: Option<String>, - straight_through_algorithm: Option<serde_json::Value>, - preprocessing_step_id: Option<String>, - error_reason: Option<Option<String>>, - capture_method: Option<storage_enums::CaptureMethod>, - connector_response_reference_id: Option<String>, - multiple_capture_count: Option<i16>, - surcharge_amount: Option<i64>, - tax_amount: Option<i64>, - amount_capturable: Option<i64>, - updated_by: String, - merchant_connector_id: Option<Option<id_type::MerchantConnectorAccountId>>, - authentication_data: Option<serde_json::Value>, - encoded_data: Option<String>, - unified_code: Option<Option<String>>, - unified_message: Option<Option<String>>, - external_three_ds_authentication_attempted: Option<bool>, - authentication_connector: Option<String>, - authentication_id: Option<String>, - fingerprint_id: Option<String>, - payment_method_billing_address_id: Option<String>, - charge_id: Option<String>, - client_source: Option<String>, - client_version: Option<String>, - customer_acceptance: Option<pii::SecretSerdeValue>, - card_network: Option<String>, - shipping_cost: Option<MinorUnit>, - order_tax_amount: Option<MinorUnit>, + pub amount: Option<MinorUnit>, + pub net_amount: Option<MinorUnit>, + pub currency: Option<storage_enums::Currency>, + pub status: Option<storage_enums::AttemptStatus>, + pub connector_transaction_id: Option<String>, + pub amount_to_capture: Option<MinorUnit>, + pub connector: Option<Option<String>>, + pub authentication_type: Option<storage_enums::AuthenticationType>, + pub payment_method: Option<storage_enums::PaymentMethod>, + pub error_message: Option<Option<String>>, + pub payment_method_id: Option<String>, + pub cancellation_reason: Option<String>, + pub modified_at: PrimitiveDateTime, + pub mandate_id: Option<String>, + pub browser_info: Option<serde_json::Value>, + pub payment_token: Option<String>, + pub error_code: Option<Option<String>>, + pub connector_metadata: Option<serde_json::Value>, + pub payment_method_data: Option<serde_json::Value>, + pub payment_method_type: Option<storage_enums::PaymentMethodType>, + pub payment_experience: Option<storage_enums::PaymentExperience>, + pub business_sub_label: Option<String>, + pub straight_through_algorithm: Option<serde_json::Value>, + pub preprocessing_step_id: Option<String>, + pub error_reason: Option<Option<String>>, + pub capture_method: Option<storage_enums::CaptureMethod>, + pub connector_response_reference_id: Option<String>, + pub multiple_capture_count: Option<i16>, + pub surcharge_amount: Option<MinorUnit>, + pub tax_amount: Option<MinorUnit>, + pub amount_capturable: Option<MinorUnit>, + pub updated_by: String, + pub merchant_connector_id: Option<Option<id_type::MerchantConnectorAccountId>>, + pub authentication_data: Option<serde_json::Value>, + pub encoded_data: Option<String>, + pub unified_code: Option<Option<String>>, + pub unified_message: Option<Option<String>>, + pub external_three_ds_authentication_attempted: Option<bool>, + pub authentication_connector: Option<String>, + pub authentication_id: Option<String>, + pub fingerprint_id: Option<String>, + pub payment_method_billing_address_id: Option<String>, + pub charge_id: Option<String>, + pub client_source: Option<String>, + pub client_version: Option<String>, + pub customer_acceptance: Option<pii::SecretSerdeValue>, + pub card_network: Option<String>, + pub shipping_cost: Option<MinorUnit>, + pub order_tax_amount: Option<MinorUnit>, } impl PaymentAttemptUpdateInternal { pub fn populate_derived_fields(self, source: &PaymentAttempt) -> Self { let mut update_internal = self; - let shipping_cost = update_internal - .shipping_cost - .or(source.shipping_cost) - .unwrap_or(MinorUnit::new(0)) - .get_amount_as_i64(); - let order_tax_amount = update_internal - .order_tax_amount - .or(source.order_tax_amount) - .unwrap_or(MinorUnit::new(0)) - .get_amount_as_i64(); update_internal.net_amount = Some( update_internal.amount.unwrap_or(source.amount) + update_internal .surcharge_amount .or(source.surcharge_amount) - .unwrap_or(0) + .unwrap_or(MinorUnit::new(0)) + update_internal .tax_amount .or(source.tax_amount) - .unwrap_or(0) - + shipping_cost - + order_tax_amount, + .unwrap_or(MinorUnit::new(0)) + + update_internal + .shipping_cost + .or(source.shipping_cost) + .unwrap_or(MinorUnit::new(0)) + + update_internal + .order_tax_amount + .or(source.order_tax_amount) + .unwrap_or(MinorUnit::new(0)), ); update_internal.card_network = update_internal .payment_method_data diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs index a9d44bca88f..fa80b0990d1 100644 --- a/crates/diesel_models/src/query/payment_attempt.rs +++ b/crates/diesel_models/src/query/payment_attempt.rs @@ -29,6 +29,7 @@ impl PaymentAttemptNew { } impl PaymentAttempt { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] pub async fn update_with_attempt_id( self, conn: &PgPooledConn, @@ -56,6 +57,34 @@ impl PaymentAttempt { } } + #[cfg(all(feature = "v2", feature = "payment_v2"))] + pub async fn update_with_attempt_id( + self, + conn: &PgPooledConn, + payment_attempt: PaymentAttemptUpdateInternal, + ) -> StorageResult<Self> { + match generics::generic_update_with_unique_predicate_get_result::< + <Self as HasTable>::Table, + _, + _, + _, + >( + conn, + dsl::attempt_id + .eq(self.attempt_id.to_owned()) + .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), + payment_attempt.populate_derived_fields(&self), + ) + .await + { + Err(error) => match error.current_context() { + DatabaseError::NoFieldsToUpdate => Ok(self), + _ => Err(error), + }, + result => result, + } + } + pub async fn find_optional_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index f4c8cf30fab..ddcf6352c52 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -24,14 +24,14 @@ pub struct PaymentAttemptBatchNew { pub merchant_id: common_utils::id_type::MerchantId, pub attempt_id: String, pub status: AttemptStatus, - pub amount: i64, + pub amount: MinorUnit, pub currency: Option<Currency>, pub save_to_locker: Option<bool>, pub connector: Option<String>, pub error_message: Option<String>, - pub offer_amount: Option<i64>, - pub surcharge_amount: Option<i64>, - pub tax_amount: Option<i64>, + pub offer_amount: Option<MinorUnit>, + pub surcharge_amount: Option<MinorUnit>, + pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<String>, pub payment_method: Option<PaymentMethod>, pub capture_method: Option<CaptureMethod>, @@ -46,7 +46,7 @@ pub struct PaymentAttemptBatchNew { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, - pub amount_to_capture: Option<i64>, + pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<String>, pub browser_info: Option<serde_json::Value>, pub payment_token: Option<String>, @@ -63,14 +63,14 @@ pub struct PaymentAttemptBatchNew { pub connector_response_reference_id: Option<String>, pub connector_transaction_id: Option<String>, pub multiple_capture_count: Option<i16>, - pub amount_capturable: i64, + pub amount_capturable: MinorUnit, pub updated_by: String, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, pub unified_code: Option<String>, pub unified_message: Option<String>, - pub net_amount: Option<i64>, + pub net_amount: Option<MinorUnit>, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<String>, diff --git a/crates/hyperswitch_domain_models/src/mandates.rs b/crates/hyperswitch_domain_models/src/mandates.rs index c1380fe51ce..d12b041a8ab 100644 --- a/crates/hyperswitch_domain_models/src/mandates.rs +++ b/crates/hyperswitch_domain_models/src/mandates.rs @@ -15,6 +15,22 @@ pub struct MandateDetails { pub update_mandate_id: Option<String>, } +impl From<MandateDetails> for diesel_models::enums::MandateDetails { + fn from(value: MandateDetails) -> Self { + Self { + update_mandate_id: value.update_mandate_id, + } + } +} + +impl From<diesel_models::enums::MandateDetails> for MandateDetails { + fn from(value: diesel_models::enums::MandateDetails) -> Self { + Self { + update_mandate_id: value.update_mandate_id, + } + } +} + #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum MandateDataType { @@ -84,6 +100,28 @@ impl From<MandateType> for MandateDataType { } } +impl From<MandateDataType> for diesel_models::enums::MandateDataType { + fn from(value: MandateDataType) -> Self { + match value { + MandateDataType::SingleUse(data) => Self::SingleUse(data.into()), + MandateDataType::MultiUse(None) => Self::MultiUse(None), + MandateDataType::MultiUse(Some(data)) => Self::MultiUse(Some(data.into())), + } + } +} + +impl From<diesel_models::enums::MandateDataType> for MandateDataType { + fn from(value: diesel_models::enums::MandateDataType) -> Self { + use diesel_models::enums::MandateDataType as DieselMandateDataType; + + match value { + DieselMandateDataType::SingleUse(data) => Self::SingleUse(data.into()), + DieselMandateDataType::MultiUse(None) => Self::MultiUse(None), + DieselMandateDataType::MultiUse(Some(data)) => Self::MultiUse(Some(data.into())), + } + } +} + impl From<ApiMandateAmountData> for MandateAmountData { fn from(value: ApiMandateAmountData) -> Self { Self { @@ -96,6 +134,30 @@ impl From<ApiMandateAmountData> for MandateAmountData { } } +impl From<MandateAmountData> for diesel_models::enums::MandateAmountData { + fn from(value: MandateAmountData) -> Self { + Self { + amount: value.amount, + currency: value.currency, + start_date: value.start_date, + end_date: value.end_date, + metadata: value.metadata, + } + } +} + +impl From<diesel_models::enums::MandateAmountData> for MandateAmountData { + fn from(value: diesel_models::enums::MandateAmountData) -> Self { + Self { + amount: value.amount, + currency: value.currency, + start_date: value.start_date, + end_date: value.end_date, + metadata: value.metadata, + } + } +} + impl From<ApiMandateData> for MandateData { fn from(value: ApiMandateData) -> Self { Self { diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index b9cfba86d41..24a79e2905e 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -1,35 +1,49 @@ use api_models::enums::Connector; use common_enums as storage_enums; use common_utils::{ - encryption::Encryption, errors::{CustomResult, ValidationError}, - id_type, pii, type_name, + id_type, pii, types::{ keymanager::{self, KeyManagerState}, MinorUnit, }, }; +use diesel_models::{ + PaymentAttempt as DieselPaymentAttempt, PaymentAttemptNew as DieselPaymentAttemptNew, +}; use error_stack::ResultExt; -use masking::PeekInterface; +use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use super::PaymentIntent; +#[cfg(all(feature = "v2", feature = "payment_v2"))] +use crate::merchant_key_store::MerchantKeyStore; use crate::{ behaviour, errors, mandates::{MandateDataType, MandateDetails}, - type_encryption::{crypto_operation, AsyncLift, CryptoOperation}, - ForeignIDRef, RemoteStorageObject, + ForeignIDRef, }; #[async_trait::async_trait] pub trait PaymentAttemptInterface { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn insert_payment_attempt( &self, payment_attempt: PaymentAttemptNew, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; + #[cfg(all(feature = "v2", feature = "payment_v2"))] + async fn insert_payment_attempt( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &MerchantKeyStore, + payment_attempt: PaymentAttempt, + storage_scheme: storage_enums::MerchantStorageScheme, + ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn update_payment_attempt_with_attempt_id( &self, this: PaymentAttempt, @@ -37,6 +51,17 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; + #[cfg(all(feature = "v2", feature = "payment_v2"))] + async fn update_payment_attempt_with_attempt_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &MerchantKeyStore, + this: PaymentAttempt, + payment_attempt: PaymentAttemptUpdate, + storage_scheme: storage_enums::MerchantStorageScheme, + ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, connector_transaction_id: &str, @@ -45,6 +70,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, @@ -52,6 +78,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, @@ -59,6 +86,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, merchant_id: &id_type::MerchantId, @@ -66,6 +94,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, payment_id: &id_type::PaymentId, @@ -74,6 +103,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, attempt_id: &str, @@ -81,6 +111,17 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; + #[cfg(all(feature = "v2", feature = "payment_v2"))] + async fn find_payment_attempt_by_attempt_id_merchant_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &MerchantKeyStore, + attempt_id: &str, + merchant_id: &id_type::MerchantId, + storage_scheme: storage_enums::MerchantStorageScheme, + ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, preprocessing_id: &str, @@ -88,6 +129,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_attempts_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, @@ -95,6 +137,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentAttempt>, errors::StorageError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn get_filters_for_payments( &self, pi: &[PaymentIntent], @@ -102,6 +145,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentListFilters, errors::StorageError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[allow(clippy::too_many_arguments)] async fn get_total_count_of_filtered_payment_attempts( &self, @@ -490,434 +534,1634 @@ pub enum PaymentAttemptUpdate { }, } +#[cfg(all(feature = "v2", feature = "payment_v2"))] +impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal { + fn from(payment_attempt_update: PaymentAttemptUpdate) -> Self { + match payment_attempt_update { + PaymentAttemptUpdate::Update { + amount, + currency, + status, + authentication_type, + payment_method, + payment_token, + payment_method_data, + payment_method_type, + payment_experience, + business_sub_label, + amount_to_capture, + capture_method, + surcharge_amount, + tax_amount, + fingerprint_id, + updated_by, + payment_method_billing_address_id, + } => Self { + amount: Some(amount), + currency: Some(currency), + status: Some(status), + authentication_type, + payment_method, + payment_token, + modified_at: common_utils::date_time::now(), + payment_method_data, + payment_method_type, + payment_experience, + business_sub_label, + amount_to_capture, + capture_method, + surcharge_amount, + tax_amount, + fingerprint_id, + payment_method_billing_address_id, + updated_by, + net_amount: None, + connector_transaction_id: None, + connector: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + error_code: None, + connector_metadata: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + connector_response_reference_id: None, + multiple_capture_count: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::AuthenticationTypeUpdate { + authentication_type, + updated_by, + } => Self { + authentication_type: Some(authentication_type), + modified_at: common_utils::date_time::now(), + updated_by, + amount: None, + net_amount: None, + currency: None, + status: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + payment_method: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::ConfirmUpdate { + amount, + currency, + authentication_type, + capture_method, + status, + payment_method, + browser_info, + connector, + payment_token, + payment_method_data, + payment_method_type, + payment_experience, + business_sub_label, + straight_through_algorithm, + error_code, + error_message, + amount_capturable, + updated_by, + merchant_connector_id, + surcharge_amount, + tax_amount, + external_three_ds_authentication_attempted, + authentication_connector, + authentication_id, + payment_method_billing_address_id, + fingerprint_id, + payment_method_id, + client_source, + client_version, + customer_acceptance, + shipping_cost, + order_tax_amount, + } => Self { + amount: Some(amount), + currency: Some(currency), + authentication_type, + status: Some(status), + payment_method, + modified_at: common_utils::date_time::now(), + browser_info, + connector: connector.map(Some), + payment_token, + payment_method_data, + payment_method_type, + payment_experience, + business_sub_label, + straight_through_algorithm, + error_code, + error_message, + amount_capturable, + updated_by, + merchant_connector_id: merchant_connector_id.map(Some), + surcharge_amount, + tax_amount, + external_three_ds_authentication_attempted, + authentication_connector, + authentication_id, + payment_method_billing_address_id, + fingerprint_id, + payment_method_id, + capture_method, + client_source, + client_version, + customer_acceptance, + net_amount: None, + connector_transaction_id: None, + amount_to_capture: None, + cancellation_reason: None, + mandate_id: None, + connector_metadata: None, + preprocessing_step_id: None, + error_reason: None, + connector_response_reference_id: None, + multiple_capture_count: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + charge_id: None, + card_network: None, + shipping_cost, + order_tax_amount, + }, + PaymentAttemptUpdate::VoidUpdate { + status, + cancellation_reason, + updated_by, + } => Self { + status: Some(status), + cancellation_reason, + modified_at: common_utils::date_time::now(), + updated_by, + amount: None, + net_amount: None, + currency: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + error_message: None, + payment_method_id: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::RejectUpdate { + status, + error_code, + error_message, + updated_by, + } => Self { + status: Some(status), + modified_at: common_utils::date_time::now(), + error_code, + error_message, + updated_by, + amount: None, + net_amount: None, + currency: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::BlocklistUpdate { + status, + error_code, + error_message, + updated_by, + } => Self { + status: Some(status), + modified_at: common_utils::date_time::now(), + error_code, + connector: Some(None), + error_message, + updated_by, + merchant_connector_id: Some(None), + amount: None, + net_amount: None, + currency: None, + connector_transaction_id: None, + amount_to_capture: None, + authentication_type: None, + payment_method: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::PaymentMethodDetailsUpdate { + payment_method_id, + updated_by, + } => Self { + payment_method_id, + modified_at: common_utils::date_time::now(), + updated_by, + amount: None, + net_amount: None, + currency: None, + status: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + error_message: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::ResponseUpdate { + status, + connector, + connector_transaction_id, + authentication_type, + payment_method_id, + mandate_id, + connector_metadata, + payment_token, + error_code, + error_message, + error_reason, + connector_response_reference_id, + amount_capturable, + updated_by, + authentication_data, + encoded_data, + unified_code, + unified_message, + payment_method_data, + charge_id, + } => Self { + status: Some(status), + connector: connector.map(Some), + connector_transaction_id, + authentication_type, + payment_method_id, + modified_at: common_utils::date_time::now(), + mandate_id, + connector_metadata, + error_code, + error_message, + payment_token, + error_reason, + connector_response_reference_id, + amount_capturable, + updated_by, + authentication_data, + encoded_data, + unified_code, + unified_message, + payment_method_data, + charge_id, + amount: None, + net_amount: None, + currency: None, + amount_to_capture: None, + payment_method: None, + cancellation_reason: None, + browser_info: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + capture_method: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + merchant_connector_id: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::ErrorUpdate { + connector, + status, + error_code, + error_message, + error_reason, + amount_capturable, + updated_by, + unified_code, + unified_message, + connector_transaction_id, + payment_method_data, + authentication_type, + } => Self { + connector: connector.map(Some), + status: Some(status), + error_message, + error_code, + modified_at: common_utils::date_time::now(), + error_reason, + amount_capturable, + updated_by, + unified_code, + unified_message, + connector_transaction_id, + payment_method_data, + authentication_type, + amount: None, + net_amount: None, + currency: None, + amount_to_capture: None, + payment_method: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + connector_metadata: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self { + status: Some(status), + modified_at: common_utils::date_time::now(), + updated_by, + amount: None, + net_amount: None, + currency: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::UpdateTrackers { + payment_token, + connector, + straight_through_algorithm, + amount_capturable, + surcharge_amount, + tax_amount, + updated_by, + merchant_connector_id, + } => Self { + payment_token, + modified_at: common_utils::date_time::now(), + connector: connector.map(Some), + straight_through_algorithm, + amount_capturable, + surcharge_amount, + tax_amount, + updated_by, + merchant_connector_id: merchant_connector_id.map(Some), + amount: None, + net_amount: None, + currency: None, + status: None, + connector_transaction_id: None, + amount_to_capture: None, + authentication_type: None, + payment_method: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::UnresolvedResponseUpdate { + status, + connector, + connector_transaction_id, + payment_method_id, + error_code, + error_message, + error_reason, + connector_response_reference_id, + updated_by, + } => Self { + status: Some(status), + connector: connector.map(Some), + connector_transaction_id, + payment_method_id, + modified_at: common_utils::date_time::now(), + error_code, + error_message, + error_reason, + connector_response_reference_id, + updated_by, + amount: None, + net_amount: None, + currency: None, + amount_to_capture: None, + authentication_type: None, + payment_method: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + capture_method: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::PreprocessingUpdate { + status, + payment_method_id, + connector_metadata, + preprocessing_step_id, + connector_transaction_id, + connector_response_reference_id, + updated_by, + } => Self { + status: Some(status), + payment_method_id, + modified_at: common_utils::date_time::now(), + connector_metadata, + preprocessing_step_id, + connector_transaction_id, + connector_response_reference_id, + updated_by, + amount: None, + net_amount: None, + currency: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + error_message: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + error_reason: None, + capture_method: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::CaptureUpdate { + multiple_capture_count, + updated_by, + amount_to_capture, + } => Self { + multiple_capture_count, + modified_at: common_utils::date_time::now(), + updated_by, + amount_to_capture, + amount: None, + net_amount: None, + currency: None, + status: None, + connector_transaction_id: None, + connector: None, + authentication_type: None, + payment_method: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::AmountToCaptureUpdate { + status, + amount_capturable, + updated_by, + } => Self { + status: Some(status), + modified_at: common_utils::date_time::now(), + amount_capturable: Some(amount_capturable), + updated_by, + amount: None, + net_amount: None, + currency: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::ConnectorResponse { + authentication_data, + encoded_data, + connector_transaction_id, + connector, + updated_by, + charge_id, + } => Self { + authentication_data, + encoded_data, + connector_transaction_id, + connector: connector.map(Some), + modified_at: common_utils::date_time::now(), + updated_by, + charge_id, + amount: None, + net_amount: None, + currency: None, + status: None, + amount_to_capture: None, + authentication_type: None, + payment_method: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { + amount, + amount_capturable, + } => Self { + amount: Some(amount), + modified_at: common_utils::date_time::now(), + amount_capturable: Some(amount_capturable), + net_amount: None, + currency: None, + status: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + updated_by: String::default(), + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::AuthenticationUpdate { + status, + external_three_ds_authentication_attempted, + authentication_connector, + authentication_id, + updated_by, + } => Self { + status: Some(status), + modified_at: common_utils::date_time::now(), + external_three_ds_authentication_attempted, + authentication_connector, + authentication_id, + updated_by, + amount: None, + net_amount: None, + currency: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + error_message: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + error_code: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + error_reason: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + unified_code: None, + unified_message: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + PaymentAttemptUpdate::ManualUpdate { + status, + error_code, + error_message, + error_reason, + updated_by, + unified_code, + unified_message, + connector_transaction_id, + } => Self { + status, + error_code: error_code.map(Some), + modified_at: common_utils::date_time::now(), + error_message: error_message.map(Some), + error_reason: error_reason.map(Some), + updated_by, + unified_code: unified_code.map(Some), + unified_message: unified_message.map(Some), + amount: None, + net_amount: None, + currency: None, + connector_transaction_id, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + connector_metadata: None, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, + } + } +} + impl ForeignIDRef for PaymentAttempt { fn foreign_id(&self) -> String { self.attempt_id.clone() } } -use diesel_models::{ - PaymentIntent as DieselPaymentIntent, PaymentIntentNew as DieselPaymentIntentNew, -}; - -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[async_trait::async_trait] -impl behaviour::Conversion for PaymentIntent { - type DstType = DieselPaymentIntent; - type NewDstType = DieselPaymentIntentNew; +impl behaviour::Conversion for PaymentAttempt { + type DstType = DieselPaymentAttempt; + type NewDstType = DieselPaymentAttemptNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { - Ok(DieselPaymentIntent { + let card_network = self + .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()); + Ok(DieselPaymentAttempt { + payment_id: self.payment_id, merchant_id: self.merchant_id, + attempt_id: self.attempt_id, status: self.status, amount: self.amount, currency: self.currency, - amount_captured: self.amount_captured, - customer_id: self.customer_id, - description: self.description, - return_url: self.return_url, - metadata: self.metadata, - statement_descriptor_name: self.statement_descriptor_name, + save_to_locker: self.save_to_locker, + connector: self.connector, + error_message: self.error_message, + offer_amount: self.offer_amount, + surcharge_amount: self.surcharge_amount, + tax_amount: self.tax_amount, + payment_method_id: self.payment_method_id, + payment_method: self.payment_method, + connector_transaction_id: self.connector_transaction_id, + capture_method: self.capture_method, + capture_on: self.capture_on, + confirm: self.confirm, + authentication_type: self.authentication_type, created_at: self.created_at, modified_at: self.modified_at, last_synced: self.last_synced, - setup_future_usage: self.setup_future_usage, - off_session: self.off_session, - client_secret: self.client_secret, - active_attempt_id: self.active_attempt.get_id(), - order_details: self.order_details, - allowed_payment_method_types: self.allowed_payment_method_types, + cancellation_reason: self.cancellation_reason, + amount_to_capture: self.amount_to_capture, + mandate_id: self.mandate_id, + browser_info: self.browser_info, + error_code: self.error_code, + payment_token: self.payment_token, connector_metadata: self.connector_metadata, - feature_metadata: self.feature_metadata, - attempt_count: self.attempt_count, - profile_id: self.profile_id, - frm_merchant_decision: self.frm_merchant_decision, - payment_link_id: self.payment_link_id, - payment_confirm_source: self.payment_confirm_source, + payment_experience: self.payment_experience, + payment_method_type: self.payment_method_type, + payment_method_data: self.payment_method_data, + business_sub_label: self.business_sub_label, + straight_through_algorithm: self.straight_through_algorithm, + preprocessing_step_id: self.preprocessing_step_id, + mandate_details: self.mandate_details.map(Into::into), + error_reason: self.error_reason, + multiple_capture_count: self.multiple_capture_count, + connector_response_reference_id: self.connector_response_reference_id, + amount_capturable: self.amount_capturable, updated_by: self.updated_by, - surcharge_applicable: self.surcharge_applicable, - request_incremental_authorization: self.request_incremental_authorization, - authorization_count: self.authorization_count, - session_expiry: self.session_expiry, - request_external_three_ds_authentication: self.request_external_three_ds_authentication, - charges: self.charges, - frm_metadata: self.frm_metadata, - customer_details: self.customer_details.map(Encryption::from), - billing_address: self.billing_address.map(Encryption::from), - merchant_order_reference_id: self.merchant_order_reference_id, - shipping_address: self.shipping_address.map(Encryption::from), - is_payment_processor_token_flow: self.is_payment_processor_token_flow, - capture_method: self.capture_method, - id: self.id, - authentication_type: self.authentication_type, - amount_to_capture: self.amount_to_capture, - prerouting_algorithm: self.prerouting_algorithm, - merchant_reference_id: self.merchant_reference_id, - surcharge_amount: self.surcharge_amount, - tax_on_surcharge: self.tax_on_surcharge, + merchant_connector_id: self.merchant_connector_id, + authentication_data: self.authentication_data, + encoded_data: self.encoded_data, + unified_code: self.unified_code, + unified_message: self.unified_message, + net_amount: Some(self.net_amount), + external_three_ds_authentication_attempted: self + .external_three_ds_authentication_attempted, + authentication_connector: self.authentication_connector, + authentication_id: self.authentication_id, + mandate_data: self.mandate_data.map(Into::into), + fingerprint_id: self.fingerprint_id, + payment_method_billing_address_id: self.payment_method_billing_address_id, + charge_id: self.charge_id, + client_source: self.client_source, + client_version: self.client_version, + customer_acceptance: self.customer_acceptance, + profile_id: self.profile_id, organization_id: self.organization_id, + card_network, + order_tax_amount: self.order_tax_amount, shipping_cost: self.shipping_cost, - tax_details: self.tax_details, - skip_external_tax_calculation: self.skip_external_tax_calculation, }) } + async fn convert_back( - state: &KeyManagerState, + _state: &KeyManagerState, storage_model: Self::DstType, - key: &masking::Secret<Vec<u8>>, - key_manager_identifier: keymanager::Identifier, + _key: &Secret<Vec<u8>>, + _key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { async { - let inner_decrypt = |inner| async { - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::DecryptOptional(inner), - key_manager_identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }; + let net_amount = storage_model.get_or_calculate_net_amount(); Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { + payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id, + attempt_id: storage_model.attempt_id, status: storage_model.status, amount: storage_model.amount, + net_amount, currency: storage_model.currency, - amount_captured: storage_model.amount_captured, - customer_id: storage_model.customer_id, - description: storage_model.description, - return_url: storage_model.return_url, - metadata: storage_model.metadata, - statement_descriptor_name: storage_model.statement_descriptor_name, + save_to_locker: storage_model.save_to_locker, + connector: storage_model.connector, + error_message: storage_model.error_message, + offer_amount: storage_model.offer_amount, + surcharge_amount: storage_model.surcharge_amount, + tax_amount: storage_model.tax_amount, + payment_method_id: storage_model.payment_method_id, + payment_method: storage_model.payment_method, + connector_transaction_id: storage_model.connector_transaction_id, + capture_method: storage_model.capture_method, + capture_on: storage_model.capture_on, + confirm: storage_model.confirm, + authentication_type: storage_model.authentication_type, created_at: storage_model.created_at, modified_at: storage_model.modified_at, last_synced: storage_model.last_synced, - setup_future_usage: storage_model.setup_future_usage, - off_session: storage_model.off_session, - client_secret: storage_model.client_secret, - active_attempt: RemoteStorageObject::ForeignID(storage_model.active_attempt_id), - order_details: storage_model.order_details, - allowed_payment_method_types: storage_model.allowed_payment_method_types, + cancellation_reason: storage_model.cancellation_reason, + amount_to_capture: storage_model.amount_to_capture, + mandate_id: storage_model.mandate_id, + browser_info: storage_model.browser_info, + error_code: storage_model.error_code, + payment_token: storage_model.payment_token, connector_metadata: storage_model.connector_metadata, - feature_metadata: storage_model.feature_metadata, - attempt_count: storage_model.attempt_count, - profile_id: storage_model.profile_id, - frm_merchant_decision: storage_model.frm_merchant_decision, - payment_link_id: storage_model.payment_link_id, - payment_confirm_source: storage_model.payment_confirm_source, + payment_experience: storage_model.payment_experience, + payment_method_type: storage_model.payment_method_type, + payment_method_data: storage_model.payment_method_data, + business_sub_label: storage_model.business_sub_label, + straight_through_algorithm: storage_model.straight_through_algorithm, + preprocessing_step_id: storage_model.preprocessing_step_id, + mandate_details: storage_model.mandate_details.map(Into::into), + error_reason: storage_model.error_reason, + multiple_capture_count: storage_model.multiple_capture_count, + connector_response_reference_id: storage_model.connector_response_reference_id, + amount_capturable: storage_model.amount_capturable, updated_by: storage_model.updated_by, - surcharge_applicable: storage_model.surcharge_applicable, - request_incremental_authorization: storage_model.request_incremental_authorization, - authorization_count: storage_model.authorization_count, - session_expiry: storage_model.session_expiry, - request_external_three_ds_authentication: storage_model - .request_external_three_ds_authentication, - charges: storage_model.charges, - frm_metadata: storage_model.frm_metadata, - customer_details: storage_model - .customer_details - .async_lift(inner_decrypt) - .await?, - billing_address: storage_model - .billing_address - .async_lift(inner_decrypt) - .await?, - merchant_order_reference_id: storage_model.merchant_order_reference_id, - shipping_address: storage_model - .shipping_address - .async_lift(inner_decrypt) - .await?, - is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow, - capture_method: storage_model.capture_method, - id: storage_model.id, - merchant_reference_id: storage_model.merchant_reference_id, + authentication_data: storage_model.authentication_data, + encoded_data: storage_model.encoded_data, + merchant_connector_id: storage_model.merchant_connector_id, + unified_code: storage_model.unified_code, + unified_message: storage_model.unified_message, + external_three_ds_authentication_attempted: storage_model + .external_three_ds_authentication_attempted, + authentication_connector: storage_model.authentication_connector, + authentication_id: storage_model.authentication_id, + mandate_data: storage_model.mandate_data.map(Into::into), + payment_method_billing_address_id: storage_model.payment_method_billing_address_id, + fingerprint_id: storage_model.fingerprint_id, + charge_id: storage_model.charge_id, + client_source: storage_model.client_source, + client_version: storage_model.client_version, + customer_acceptance: storage_model.customer_acceptance, + profile_id: storage_model.profile_id, organization_id: storage_model.organization_id, - authentication_type: storage_model.authentication_type, - amount_to_capture: storage_model.amount_to_capture, - prerouting_algorithm: storage_model.prerouting_algorithm, - surcharge_amount: storage_model.surcharge_amount, - tax_on_surcharge: storage_model.tax_on_surcharge, + order_tax_amount: storage_model.order_tax_amount, shipping_cost: storage_model.shipping_cost, - tax_details: storage_model.tax_details, - skip_external_tax_calculation: storage_model.skip_external_tax_calculation, }) } .await .change_context(ValidationError::InvalidValue { - message: "Failed while decrypting payment intent".to_string(), + message: "Failed while decrypting payment attempt".to_string(), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { - Ok(DieselPaymentIntentNew { + let card_network = self + .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()); + Ok(DieselPaymentAttemptNew { + payment_id: self.payment_id, merchant_id: self.merchant_id, + attempt_id: self.attempt_id, status: self.status, amount: self.amount, currency: self.currency, - amount_captured: self.amount_captured, - customer_id: self.customer_id, - description: self.description, - return_url: self.return_url, - metadata: self.metadata, - statement_descriptor_name: self.statement_descriptor_name, + save_to_locker: self.save_to_locker, + connector: self.connector, + error_message: self.error_message, + offer_amount: self.offer_amount, + surcharge_amount: self.surcharge_amount, + tax_amount: self.tax_amount, + payment_method_id: self.payment_method_id, + payment_method: self.payment_method, + capture_method: self.capture_method, + capture_on: self.capture_on, + confirm: self.confirm, + authentication_type: self.authentication_type, created_at: self.created_at, modified_at: self.modified_at, last_synced: self.last_synced, - setup_future_usage: self.setup_future_usage, - off_session: self.off_session, - client_secret: self.client_secret, - active_attempt_id: self.active_attempt.get_id(), - order_details: self.order_details, - allowed_payment_method_types: self.allowed_payment_method_types, + cancellation_reason: self.cancellation_reason, + amount_to_capture: self.amount_to_capture, + mandate_id: self.mandate_id, + browser_info: self.browser_info, + payment_token: self.payment_token, + error_code: self.error_code, connector_metadata: self.connector_metadata, - feature_metadata: self.feature_metadata, - attempt_count: self.attempt_count, - profile_id: self.profile_id, - frm_merchant_decision: self.frm_merchant_decision, - payment_link_id: self.payment_link_id, - payment_confirm_source: self.payment_confirm_source, + payment_experience: self.payment_experience, + payment_method_type: self.payment_method_type, + payment_method_data: self.payment_method_data, + business_sub_label: self.business_sub_label, + straight_through_algorithm: self.straight_through_algorithm, + preprocessing_step_id: self.preprocessing_step_id, + mandate_details: self.mandate_details.map(Into::into), + error_reason: self.error_reason, + connector_response_reference_id: self.connector_response_reference_id, + multiple_capture_count: self.multiple_capture_count, + amount_capturable: self.amount_capturable, updated_by: self.updated_by, - surcharge_applicable: self.surcharge_applicable, - request_incremental_authorization: self.request_incremental_authorization, - authorization_count: self.authorization_count, - session_expiry: self.session_expiry, - request_external_three_ds_authentication: self.request_external_three_ds_authentication, - charges: self.charges, - frm_metadata: self.frm_metadata, - customer_details: self.customer_details.map(Encryption::from), - billing_address: self.billing_address.map(Encryption::from), - merchant_order_reference_id: self.merchant_order_reference_id, - shipping_address: self.shipping_address.map(Encryption::from), - is_payment_processor_token_flow: self.is_payment_processor_token_flow, - capture_method: self.capture_method, - id: self.id, - merchant_reference_id: self.merchant_reference_id, - authentication_type: self.authentication_type, - amount_to_capture: self.amount_to_capture, - prerouting_algorithm: self.prerouting_algorithm, - surcharge_amount: self.surcharge_amount, - tax_on_surcharge: self.tax_on_surcharge, + merchant_connector_id: self.merchant_connector_id, + authentication_data: self.authentication_data, + encoded_data: self.encoded_data, + unified_code: self.unified_code, + unified_message: self.unified_message, + net_amount: Some(self.net_amount), + external_three_ds_authentication_attempted: self + .external_three_ds_authentication_attempted, + authentication_connector: self.authentication_connector, + authentication_id: self.authentication_id, + mandate_data: self.mandate_data.map(Into::into), + fingerprint_id: self.fingerprint_id, + payment_method_billing_address_id: self.payment_method_billing_address_id, + charge_id: self.charge_id, + client_source: self.client_source, + client_version: self.client_version, + customer_acceptance: self.customer_acceptance, + profile_id: self.profile_id, organization_id: self.organization_id, + card_network, + order_tax_amount: self.order_tax_amount, shipping_cost: self.shipping_cost, - tax_details: self.tax_details, - skip_external_tax_calculation: self.skip_external_tax_calculation, }) } } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(all(feature = "v2", feature = "payment_v2"))] #[async_trait::async_trait] -impl behaviour::Conversion for PaymentIntent { - type DstType = DieselPaymentIntent; - type NewDstType = DieselPaymentIntentNew; +impl behaviour::Conversion for PaymentAttempt { + type DstType = DieselPaymentAttempt; + type NewDstType = DieselPaymentAttemptNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { - Ok(DieselPaymentIntent { + let card_network = self + .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()); + Ok(DieselPaymentAttempt { payment_id: self.payment_id, merchant_id: self.merchant_id, + attempt_id: self.attempt_id, status: self.status, amount: self.amount, currency: self.currency, - amount_captured: self.amount_captured, - customer_id: self.customer_id, - description: self.description, - return_url: self.return_url, - metadata: self.metadata, - connector_id: self.connector_id, - shipping_address_id: self.shipping_address_id, - billing_address_id: self.billing_address_id, - statement_descriptor_name: self.statement_descriptor_name, - statement_descriptor_suffix: self.statement_descriptor_suffix, + save_to_locker: self.save_to_locker, + connector: self.connector, + error_message: self.error_message, + offer_amount: self.offer_amount, + surcharge_amount: self.surcharge_amount, + tax_amount: self.tax_amount, + payment_method_id: self.payment_method_id, + payment_method: self.payment_method, + connector_transaction_id: self.connector_transaction_id, + capture_method: self.capture_method, + capture_on: self.capture_on, + confirm: self.confirm, + authentication_type: self.authentication_type, created_at: self.created_at, modified_at: self.modified_at, last_synced: self.last_synced, - setup_future_usage: self.setup_future_usage, - off_session: self.off_session, - client_secret: self.client_secret, - active_attempt_id: self.active_attempt.get_id(), - business_country: self.business_country, - business_label: self.business_label, - order_details: self.order_details, - allowed_payment_method_types: self.allowed_payment_method_types, + cancellation_reason: self.cancellation_reason, + amount_to_capture: self.amount_to_capture, + mandate_id: self.mandate_id, + browser_info: self.browser_info, + error_code: self.error_code, + payment_token: self.payment_token, connector_metadata: self.connector_metadata, - feature_metadata: self.feature_metadata, - attempt_count: self.attempt_count, - profile_id: self.profile_id, - merchant_decision: self.merchant_decision, - payment_link_id: self.payment_link_id, - payment_confirm_source: self.payment_confirm_source, + payment_experience: self.payment_experience, + payment_method_type: self.payment_method_type, + payment_method_data: self.payment_method_data, + business_sub_label: self.business_sub_label, + straight_through_algorithm: self.straight_through_algorithm, + preprocessing_step_id: self.preprocessing_step_id, + mandate_details: self.mandate_details.map(Into::into), + error_reason: self.error_reason, + multiple_capture_count: self.multiple_capture_count, + connector_response_reference_id: self.connector_response_reference_id, + amount_capturable: self.amount_capturable, updated_by: self.updated_by, - surcharge_applicable: self.surcharge_applicable, - request_incremental_authorization: self.request_incremental_authorization, - incremental_authorization_allowed: self.incremental_authorization_allowed, - authorization_count: self.authorization_count, + merchant_connector_id: self.merchant_connector_id, + authentication_data: self.authentication_data, + encoded_data: self.encoded_data, + unified_code: self.unified_code, + unified_message: self.unified_message, + net_amount: Some(self.net_amount), + external_three_ds_authentication_attempted: self + .external_three_ds_authentication_attempted, + authentication_connector: self.authentication_connector, + authentication_id: self.authentication_id, + mandate_data: self.mandate_data.map(Into::into), fingerprint_id: self.fingerprint_id, - session_expiry: self.session_expiry, - request_external_three_ds_authentication: self.request_external_three_ds_authentication, - charges: self.charges, - frm_metadata: self.frm_metadata, - customer_details: self.customer_details.map(Encryption::from), - billing_details: self.billing_details.map(Encryption::from), - merchant_order_reference_id: self.merchant_order_reference_id, - shipping_details: self.shipping_details.map(Encryption::from), - is_payment_processor_token_flow: self.is_payment_processor_token_flow, + payment_method_billing_address_id: self.payment_method_billing_address_id, + charge_id: self.charge_id, + client_source: self.client_source, + client_version: self.client_version, + customer_acceptance: self.customer_acceptance, + profile_id: self.profile_id, organization_id: self.organization_id, + card_network, + order_tax_amount: self.order_tax_amount, shipping_cost: self.shipping_cost, - tax_details: self.tax_details, - skip_external_tax_calculation: self.skip_external_tax_calculation, }) } async fn convert_back( - state: &KeyManagerState, + _state: &KeyManagerState, storage_model: Self::DstType, - key: &masking::Secret<Vec<u8>>, - key_manager_identifier: keymanager::Identifier, + _key: &Secret<Vec<u8>>, + _key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { async { - let inner_decrypt = |inner| async { - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::DecryptOptional(inner), - key_manager_identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }; + let net_amount = storage_model.get_or_calculate_net_amount(); Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id, + attempt_id: storage_model.attempt_id, status: storage_model.status, amount: storage_model.amount, + net_amount, currency: storage_model.currency, - amount_captured: storage_model.amount_captured, - customer_id: storage_model.customer_id, - description: storage_model.description, - return_url: storage_model.return_url, - metadata: storage_model.metadata, - connector_id: storage_model.connector_id, - shipping_address_id: storage_model.shipping_address_id, - billing_address_id: storage_model.billing_address_id, - statement_descriptor_name: storage_model.statement_descriptor_name, - statement_descriptor_suffix: storage_model.statement_descriptor_suffix, + save_to_locker: storage_model.save_to_locker, + connector: storage_model.connector, + error_message: storage_model.error_message, + offer_amount: storage_model.offer_amount, + surcharge_amount: storage_model.surcharge_amount, + tax_amount: storage_model.tax_amount, + payment_method_id: storage_model.payment_method_id, + payment_method: storage_model.payment_method, + connector_transaction_id: storage_model.connector_transaction_id, + capture_method: storage_model.capture_method, + capture_on: storage_model.capture_on, + confirm: storage_model.confirm, + authentication_type: storage_model.authentication_type, created_at: storage_model.created_at, modified_at: storage_model.modified_at, last_synced: storage_model.last_synced, - setup_future_usage: storage_model.setup_future_usage, - off_session: storage_model.off_session, - client_secret: storage_model.client_secret, - active_attempt: RemoteStorageObject::ForeignID(storage_model.active_attempt_id), - business_country: storage_model.business_country, - business_label: storage_model.business_label, - order_details: storage_model.order_details, - allowed_payment_method_types: storage_model.allowed_payment_method_types, + cancellation_reason: storage_model.cancellation_reason, + amount_to_capture: storage_model.amount_to_capture, + mandate_id: storage_model.mandate_id, + browser_info: storage_model.browser_info, + error_code: storage_model.error_code, + payment_token: storage_model.payment_token, connector_metadata: storage_model.connector_metadata, - feature_metadata: storage_model.feature_metadata, - attempt_count: storage_model.attempt_count, - profile_id: storage_model.profile_id, - merchant_decision: storage_model.merchant_decision, - payment_link_id: storage_model.payment_link_id, - payment_confirm_source: storage_model.payment_confirm_source, + payment_experience: storage_model.payment_experience, + payment_method_type: storage_model.payment_method_type, + payment_method_data: storage_model.payment_method_data, + business_sub_label: storage_model.business_sub_label, + straight_through_algorithm: storage_model.straight_through_algorithm, + preprocessing_step_id: storage_model.preprocessing_step_id, + mandate_details: storage_model.mandate_details.map(Into::into), + error_reason: storage_model.error_reason, + multiple_capture_count: storage_model.multiple_capture_count, + connector_response_reference_id: storage_model.connector_response_reference_id, + amount_capturable: storage_model.amount_capturable, updated_by: storage_model.updated_by, - surcharge_applicable: storage_model.surcharge_applicable, - request_incremental_authorization: storage_model.request_incremental_authorization, - incremental_authorization_allowed: storage_model.incremental_authorization_allowed, - authorization_count: storage_model.authorization_count, + authentication_data: storage_model.authentication_data, + encoded_data: storage_model.encoded_data, + merchant_connector_id: storage_model.merchant_connector_id, + unified_code: storage_model.unified_code, + unified_message: storage_model.unified_message, + external_three_ds_authentication_attempted: storage_model + .external_three_ds_authentication_attempted, + authentication_connector: storage_model.authentication_connector, + authentication_id: storage_model.authentication_id, + mandate_data: storage_model.mandate_data.map(Into::into), + payment_method_billing_address_id: storage_model.payment_method_billing_address_id, fingerprint_id: storage_model.fingerprint_id, - session_expiry: storage_model.session_expiry, - request_external_three_ds_authentication: storage_model - .request_external_three_ds_authentication, - charges: storage_model.charges, - frm_metadata: storage_model.frm_metadata, - shipping_cost: storage_model.shipping_cost, - tax_details: storage_model.tax_details, - customer_details: storage_model - .customer_details - .async_lift(inner_decrypt) - .await?, - billing_details: storage_model - .billing_details - .async_lift(inner_decrypt) - .await?, - merchant_order_reference_id: storage_model.merchant_order_reference_id, - shipping_details: storage_model - .shipping_details - .async_lift(inner_decrypt) - .await?, - is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow, + charge_id: storage_model.charge_id, + client_source: storage_model.client_source, + client_version: storage_model.client_version, + customer_acceptance: storage_model.customer_acceptance, + profile_id: storage_model.profile_id, organization_id: storage_model.organization_id, - skip_external_tax_calculation: storage_model.skip_external_tax_calculation, + order_tax_amount: storage_model.order_tax_amount, + shipping_cost: storage_model.shipping_cost, }) } .await .change_context(ValidationError::InvalidValue { - message: "Failed while decrypting payment intent".to_string(), + message: "Failed while decrypting payment attempt".to_string(), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { - Ok(DieselPaymentIntentNew { + let card_network = self + .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()); + Ok(DieselPaymentAttemptNew { payment_id: self.payment_id, merchant_id: self.merchant_id, + attempt_id: self.attempt_id, status: self.status, amount: self.amount, currency: self.currency, - amount_captured: self.amount_captured, - customer_id: self.customer_id, - description: self.description, - return_url: self.return_url, - metadata: self.metadata, - connector_id: self.connector_id, - shipping_address_id: self.shipping_address_id, - billing_address_id: self.billing_address_id, - statement_descriptor_name: self.statement_descriptor_name, - statement_descriptor_suffix: self.statement_descriptor_suffix, + save_to_locker: self.save_to_locker, + connector: self.connector, + error_message: self.error_message, + offer_amount: self.offer_amount, + surcharge_amount: self.surcharge_amount, + tax_amount: self.tax_amount, + payment_method_id: self.payment_method_id, + payment_method: self.payment_method, + capture_method: self.capture_method, + capture_on: self.capture_on, + confirm: self.confirm, + authentication_type: self.authentication_type, created_at: self.created_at, modified_at: self.modified_at, last_synced: self.last_synced, - setup_future_usage: self.setup_future_usage, - off_session: self.off_session, - client_secret: self.client_secret, - active_attempt_id: self.active_attempt.get_id(), - business_country: self.business_country, - business_label: self.business_label, - order_details: self.order_details, - allowed_payment_method_types: self.allowed_payment_method_types, + cancellation_reason: self.cancellation_reason, + amount_to_capture: self.amount_to_capture, + mandate_id: self.mandate_id, + browser_info: self.browser_info, + payment_token: self.payment_token, + error_code: self.error_code, connector_metadata: self.connector_metadata, - feature_metadata: self.feature_metadata, - attempt_count: self.attempt_count, - profile_id: self.profile_id, - merchant_decision: self.merchant_decision, - payment_link_id: self.payment_link_id, - payment_confirm_source: self.payment_confirm_source, + payment_experience: self.payment_experience, + payment_method_type: self.payment_method_type, + payment_method_data: self.payment_method_data, + business_sub_label: self.business_sub_label, + straight_through_algorithm: self.straight_through_algorithm, + preprocessing_step_id: self.preprocessing_step_id, + mandate_details: self.mandate_details.map(Into::into), + error_reason: self.error_reason, + connector_response_reference_id: self.connector_response_reference_id, + multiple_capture_count: self.multiple_capture_count, + amount_capturable: self.amount_capturable, updated_by: self.updated_by, - surcharge_applicable: self.surcharge_applicable, - request_incremental_authorization: self.request_incremental_authorization, - incremental_authorization_allowed: self.incremental_authorization_allowed, - authorization_count: self.authorization_count, + merchant_connector_id: self.merchant_connector_id, + authentication_data: self.authentication_data, + encoded_data: self.encoded_data, + unified_code: self.unified_code, + unified_message: self.unified_message, + net_amount: Some(self.net_amount), + external_three_ds_authentication_attempted: self + .external_three_ds_authentication_attempted, + authentication_connector: self.authentication_connector, + authentication_id: self.authentication_id, + mandate_data: self.mandate_data.map(Into::into), fingerprint_id: self.fingerprint_id, - session_expiry: self.session_expiry, - request_external_three_ds_authentication: self.request_external_three_ds_authentication, - charges: self.charges, - frm_metadata: self.frm_metadata, - customer_details: self.customer_details.map(Encryption::from), - billing_details: self.billing_details.map(Encryption::from), - merchant_order_reference_id: self.merchant_order_reference_id, - shipping_details: self.shipping_details.map(Encryption::from), - is_payment_processor_token_flow: self.is_payment_processor_token_flow, + payment_method_billing_address_id: self.payment_method_billing_address_id, + charge_id: self.charge_id, + client_source: self.client_source, + client_version: self.client_version, + customer_acceptance: self.customer_acceptance, + profile_id: self.profile_id, organization_id: self.organization_id, + card_network, + order_tax_amount: self.order_tax_amount, shipping_cost: self.shipping_cost, - tax_details: self.tax_details, - skip_external_tax_calculation: self.skip_external_tax_calculation, }) } } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index c4d19c83a39..f5b719fe370 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -3,16 +3,30 @@ use common_utils::{ consts::{PAYMENTS_LIST_MAX_LIMIT_V1, PAYMENTS_LIST_MAX_LIMIT_V2}, crypto::Encryptable, encryption::Encryption, + errors::{CustomResult, ValidationError}, id_type, pii::{self, Email}, - types::{keymanager::KeyManagerState, MinorUnit}, + type_name, + types::{ + keymanager::{self, KeyManagerState}, + MinorUnit, + }, +}; +use diesel_models::{ + PaymentIntent as DieselPaymentIntent, PaymentIntentNew as DieselPaymentIntentNew, }; -use masking::{Deserialize, Secret}; +use error_stack::ResultExt; +use masking::{Deserialize, PeekInterface, Secret}; use serde::Serialize; use time::PrimitiveDateTime; use super::{payment_attempt::PaymentAttempt, PaymentIntent}; -use crate::{errors, merchant_key_store::MerchantKeyStore, RemoteStorageObject}; +use crate::{ + behaviour, errors, + merchant_key_store::MerchantKeyStore, + type_encryption::{crypto_operation, AsyncLift, CryptoOperation}, + RemoteStorageObject, +}; #[async_trait::async_trait] pub trait PaymentIntentInterface { async fn update_payment_intent( @@ -1563,3 +1577,425 @@ where } } } + +#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[async_trait::async_trait] +impl behaviour::Conversion for PaymentIntent { + type DstType = DieselPaymentIntent; + type NewDstType = DieselPaymentIntentNew; + + async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { + Ok(DieselPaymentIntent { + merchant_id: self.merchant_id, + status: self.status, + amount: self.amount, + currency: self.currency, + amount_captured: self.amount_captured, + customer_id: self.customer_id, + description: self.description, + return_url: self.return_url, + metadata: self.metadata, + statement_descriptor_name: self.statement_descriptor_name, + created_at: self.created_at, + modified_at: self.modified_at, + last_synced: self.last_synced, + setup_future_usage: self.setup_future_usage, + off_session: self.off_session, + client_secret: self.client_secret, + active_attempt_id: self.active_attempt.get_id(), + order_details: self.order_details, + allowed_payment_method_types: self.allowed_payment_method_types, + connector_metadata: self.connector_metadata, + feature_metadata: self.feature_metadata, + attempt_count: self.attempt_count, + profile_id: self.profile_id, + frm_merchant_decision: self.frm_merchant_decision, + payment_link_id: self.payment_link_id, + payment_confirm_source: self.payment_confirm_source, + updated_by: self.updated_by, + surcharge_applicable: self.surcharge_applicable, + request_incremental_authorization: self.request_incremental_authorization, + authorization_count: self.authorization_count, + session_expiry: self.session_expiry, + request_external_three_ds_authentication: self.request_external_three_ds_authentication, + charges: self.charges, + frm_metadata: self.frm_metadata, + customer_details: self.customer_details.map(Encryption::from), + billing_address: self.billing_address.map(Encryption::from), + merchant_order_reference_id: self.merchant_order_reference_id, + shipping_address: self.shipping_address.map(Encryption::from), + is_payment_processor_token_flow: self.is_payment_processor_token_flow, + capture_method: self.capture_method, + id: self.id, + authentication_type: self.authentication_type, + amount_to_capture: self.amount_to_capture, + prerouting_algorithm: self.prerouting_algorithm, + merchant_reference_id: self.merchant_reference_id, + surcharge_amount: self.surcharge_amount, + tax_on_surcharge: self.tax_on_surcharge, + organization_id: self.organization_id, + shipping_cost: self.shipping_cost, + tax_details: self.tax_details, + skip_external_tax_calculation: self.skip_external_tax_calculation, + }) + } + async fn convert_back( + state: &KeyManagerState, + storage_model: Self::DstType, + key: &Secret<Vec<u8>>, + key_manager_identifier: keymanager::Identifier, + ) -> CustomResult<Self, ValidationError> + where + Self: Sized, + { + async { + let inner_decrypt = |inner| async { + crypto_operation( + state, + type_name!(Self::DstType), + CryptoOperation::DecryptOptional(inner), + key_manager_identifier.clone(), + key.peek(), + ) + .await + .and_then(|val| val.try_into_optionaloperation()) + }; + Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { + merchant_id: storage_model.merchant_id, + status: storage_model.status, + amount: storage_model.amount, + currency: storage_model.currency, + amount_captured: storage_model.amount_captured, + customer_id: storage_model.customer_id, + description: storage_model.description, + return_url: storage_model.return_url, + metadata: storage_model.metadata, + statement_descriptor_name: storage_model.statement_descriptor_name, + created_at: storage_model.created_at, + modified_at: storage_model.modified_at, + last_synced: storage_model.last_synced, + setup_future_usage: storage_model.setup_future_usage, + off_session: storage_model.off_session, + client_secret: storage_model.client_secret, + active_attempt: RemoteStorageObject::ForeignID(storage_model.active_attempt_id), + order_details: storage_model.order_details, + allowed_payment_method_types: storage_model.allowed_payment_method_types, + connector_metadata: storage_model.connector_metadata, + feature_metadata: storage_model.feature_metadata, + attempt_count: storage_model.attempt_count, + profile_id: storage_model.profile_id, + frm_merchant_decision: storage_model.frm_merchant_decision, + payment_link_id: storage_model.payment_link_id, + payment_confirm_source: storage_model.payment_confirm_source, + updated_by: storage_model.updated_by, + surcharge_applicable: storage_model.surcharge_applicable, + request_incremental_authorization: storage_model.request_incremental_authorization, + authorization_count: storage_model.authorization_count, + session_expiry: storage_model.session_expiry, + request_external_three_ds_authentication: storage_model + .request_external_three_ds_authentication, + charges: storage_model.charges, + frm_metadata: storage_model.frm_metadata, + customer_details: storage_model + .customer_details + .async_lift(inner_decrypt) + .await?, + billing_address: storage_model + .billing_address + .async_lift(inner_decrypt) + .await?, + merchant_order_reference_id: storage_model.merchant_order_reference_id, + shipping_address: storage_model + .shipping_address + .async_lift(inner_decrypt) + .await?, + is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow, + capture_method: storage_model.capture_method, + id: storage_model.id, + merchant_reference_id: storage_model.merchant_reference_id, + organization_id: storage_model.organization_id, + authentication_type: storage_model.authentication_type, + amount_to_capture: storage_model.amount_to_capture, + prerouting_algorithm: storage_model.prerouting_algorithm, + surcharge_amount: storage_model.surcharge_amount, + tax_on_surcharge: storage_model.tax_on_surcharge, + shipping_cost: storage_model.shipping_cost, + tax_details: storage_model.tax_details, + skip_external_tax_calculation: storage_model.skip_external_tax_calculation, + }) + } + .await + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting payment intent".to_string(), + }) + } + + async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + Ok(DieselPaymentIntentNew { + merchant_id: self.merchant_id, + status: self.status, + amount: self.amount, + currency: self.currency, + amount_captured: self.amount_captured, + customer_id: self.customer_id, + description: self.description, + return_url: self.return_url, + metadata: self.metadata, + statement_descriptor_name: self.statement_descriptor_name, + created_at: self.created_at, + modified_at: self.modified_at, + last_synced: self.last_synced, + setup_future_usage: self.setup_future_usage, + off_session: self.off_session, + client_secret: self.client_secret, + active_attempt_id: self.active_attempt.get_id(), + order_details: self.order_details, + allowed_payment_method_types: self.allowed_payment_method_types, + connector_metadata: self.connector_metadata, + feature_metadata: self.feature_metadata, + attempt_count: self.attempt_count, + profile_id: self.profile_id, + frm_merchant_decision: self.frm_merchant_decision, + payment_link_id: self.payment_link_id, + payment_confirm_source: self.payment_confirm_source, + updated_by: self.updated_by, + surcharge_applicable: self.surcharge_applicable, + request_incremental_authorization: self.request_incremental_authorization, + authorization_count: self.authorization_count, + session_expiry: self.session_expiry, + request_external_three_ds_authentication: self.request_external_three_ds_authentication, + charges: self.charges, + frm_metadata: self.frm_metadata, + customer_details: self.customer_details.map(Encryption::from), + billing_address: self.billing_address.map(Encryption::from), + merchant_order_reference_id: self.merchant_order_reference_id, + shipping_address: self.shipping_address.map(Encryption::from), + is_payment_processor_token_flow: self.is_payment_processor_token_flow, + capture_method: self.capture_method, + id: self.id, + merchant_reference_id: self.merchant_reference_id, + authentication_type: self.authentication_type, + amount_to_capture: self.amount_to_capture, + prerouting_algorithm: self.prerouting_algorithm, + surcharge_amount: self.surcharge_amount, + tax_on_surcharge: self.tax_on_surcharge, + organization_id: self.organization_id, + shipping_cost: self.shipping_cost, + tax_details: self.tax_details, + skip_external_tax_calculation: self.skip_external_tax_calculation, + }) + } +} + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[async_trait::async_trait] +impl behaviour::Conversion for PaymentIntent { + type DstType = DieselPaymentIntent; + type NewDstType = DieselPaymentIntentNew; + + async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { + Ok(DieselPaymentIntent { + payment_id: self.payment_id, + merchant_id: self.merchant_id, + status: self.status, + amount: self.amount, + currency: self.currency, + amount_captured: self.amount_captured, + customer_id: self.customer_id, + description: self.description, + return_url: self.return_url, + metadata: self.metadata, + connector_id: self.connector_id, + shipping_address_id: self.shipping_address_id, + billing_address_id: self.billing_address_id, + statement_descriptor_name: self.statement_descriptor_name, + statement_descriptor_suffix: self.statement_descriptor_suffix, + created_at: self.created_at, + modified_at: self.modified_at, + last_synced: self.last_synced, + setup_future_usage: self.setup_future_usage, + off_session: self.off_session, + client_secret: self.client_secret, + active_attempt_id: self.active_attempt.get_id(), + business_country: self.business_country, + business_label: self.business_label, + order_details: self.order_details, + allowed_payment_method_types: self.allowed_payment_method_types, + connector_metadata: self.connector_metadata, + feature_metadata: self.feature_metadata, + attempt_count: self.attempt_count, + profile_id: self.profile_id, + merchant_decision: self.merchant_decision, + payment_link_id: self.payment_link_id, + payment_confirm_source: self.payment_confirm_source, + updated_by: self.updated_by, + surcharge_applicable: self.surcharge_applicable, + request_incremental_authorization: self.request_incremental_authorization, + incremental_authorization_allowed: self.incremental_authorization_allowed, + authorization_count: self.authorization_count, + fingerprint_id: self.fingerprint_id, + session_expiry: self.session_expiry, + request_external_three_ds_authentication: self.request_external_three_ds_authentication, + charges: self.charges, + frm_metadata: self.frm_metadata, + customer_details: self.customer_details.map(Encryption::from), + billing_details: self.billing_details.map(Encryption::from), + merchant_order_reference_id: self.merchant_order_reference_id, + shipping_details: self.shipping_details.map(Encryption::from), + is_payment_processor_token_flow: self.is_payment_processor_token_flow, + organization_id: self.organization_id, + shipping_cost: self.shipping_cost, + tax_details: self.tax_details, + skip_external_tax_calculation: self.skip_external_tax_calculation, + }) + } + + async fn convert_back( + state: &KeyManagerState, + storage_model: Self::DstType, + key: &Secret<Vec<u8>>, + key_manager_identifier: keymanager::Identifier, + ) -> CustomResult<Self, ValidationError> + where + Self: Sized, + { + async { + let inner_decrypt = |inner| async { + crypto_operation( + state, + type_name!(Self::DstType), + CryptoOperation::DecryptOptional(inner), + key_manager_identifier.clone(), + key.peek(), + ) + .await + .and_then(|val| val.try_into_optionaloperation()) + }; + Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { + payment_id: storage_model.payment_id, + merchant_id: storage_model.merchant_id, + status: storage_model.status, + amount: storage_model.amount, + currency: storage_model.currency, + amount_captured: storage_model.amount_captured, + customer_id: storage_model.customer_id, + description: storage_model.description, + return_url: storage_model.return_url, + metadata: storage_model.metadata, + connector_id: storage_model.connector_id, + shipping_address_id: storage_model.shipping_address_id, + billing_address_id: storage_model.billing_address_id, + statement_descriptor_name: storage_model.statement_descriptor_name, + statement_descriptor_suffix: storage_model.statement_descriptor_suffix, + created_at: storage_model.created_at, + modified_at: storage_model.modified_at, + last_synced: storage_model.last_synced, + setup_future_usage: storage_model.setup_future_usage, + off_session: storage_model.off_session, + client_secret: storage_model.client_secret, + active_attempt: RemoteStorageObject::ForeignID(storage_model.active_attempt_id), + business_country: storage_model.business_country, + business_label: storage_model.business_label, + order_details: storage_model.order_details, + allowed_payment_method_types: storage_model.allowed_payment_method_types, + connector_metadata: storage_model.connector_metadata, + feature_metadata: storage_model.feature_metadata, + attempt_count: storage_model.attempt_count, + profile_id: storage_model.profile_id, + merchant_decision: storage_model.merchant_decision, + payment_link_id: storage_model.payment_link_id, + payment_confirm_source: storage_model.payment_confirm_source, + updated_by: storage_model.updated_by, + surcharge_applicable: storage_model.surcharge_applicable, + request_incremental_authorization: storage_model.request_incremental_authorization, + incremental_authorization_allowed: storage_model.incremental_authorization_allowed, + authorization_count: storage_model.authorization_count, + fingerprint_id: storage_model.fingerprint_id, + session_expiry: storage_model.session_expiry, + request_external_three_ds_authentication: storage_model + .request_external_three_ds_authentication, + charges: storage_model.charges, + frm_metadata: storage_model.frm_metadata, + shipping_cost: storage_model.shipping_cost, + tax_details: storage_model.tax_details, + customer_details: storage_model + .customer_details + .async_lift(inner_decrypt) + .await?, + billing_details: storage_model + .billing_details + .async_lift(inner_decrypt) + .await?, + merchant_order_reference_id: storage_model.merchant_order_reference_id, + shipping_details: storage_model + .shipping_details + .async_lift(inner_decrypt) + .await?, + 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, + }) + } + .await + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting payment intent".to_string(), + }) + } + + async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + Ok(DieselPaymentIntentNew { + payment_id: self.payment_id, + merchant_id: self.merchant_id, + status: self.status, + amount: self.amount, + currency: self.currency, + amount_captured: self.amount_captured, + customer_id: self.customer_id, + description: self.description, + return_url: self.return_url, + metadata: self.metadata, + connector_id: self.connector_id, + shipping_address_id: self.shipping_address_id, + billing_address_id: self.billing_address_id, + statement_descriptor_name: self.statement_descriptor_name, + statement_descriptor_suffix: self.statement_descriptor_suffix, + created_at: self.created_at, + modified_at: self.modified_at, + last_synced: self.last_synced, + setup_future_usage: self.setup_future_usage, + off_session: self.off_session, + client_secret: self.client_secret, + active_attempt_id: self.active_attempt.get_id(), + business_country: self.business_country, + business_label: self.business_label, + order_details: self.order_details, + allowed_payment_method_types: self.allowed_payment_method_types, + connector_metadata: self.connector_metadata, + feature_metadata: self.feature_metadata, + attempt_count: self.attempt_count, + profile_id: self.profile_id, + merchant_decision: self.merchant_decision, + payment_link_id: self.payment_link_id, + payment_confirm_source: self.payment_confirm_source, + updated_by: self.updated_by, + surcharge_applicable: self.surcharge_applicable, + request_incremental_authorization: self.request_incremental_authorization, + incremental_authorization_allowed: self.incremental_authorization_allowed, + authorization_count: self.authorization_count, + fingerprint_id: self.fingerprint_id, + session_expiry: self.session_expiry, + request_external_three_ds_authentication: self.request_external_three_ds_authentication, + charges: self.charges, + frm_metadata: self.frm_metadata, + customer_details: self.customer_details.map(Encryption::from), + billing_details: self.billing_details.map(Encryption::from), + merchant_order_reference_id: self.merchant_order_reference_id, + shipping_details: self.shipping_details.map(Encryption::from), + is_payment_processor_token_flow: self.is_payment_processor_token_flow, + organization_id: self.organization_id, + shipping_cost: self.shipping_cost, + tax_details: self.tax_details, + skip_external_tax_calculation: self.skip_external_tax_calculation, + }) + } +} diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index e4eb60982d4..a325f41404d 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -578,7 +578,7 @@ impl CustomerDeleteBridge for customers::GlobalId { key_manager_state, &self.id, merchant_account.get_id(), - &key_store, + key_store, merchant_account.storage_scheme, ) .await @@ -602,13 +602,9 @@ impl CustomerDeleteBridge for customers::GlobalId { Ok(customer_payment_methods) => { for pm in customer_payment_methods.into_iter() { if pm.payment_method == Some(enums::PaymentMethod::Card) { - cards::delete_card_by_locker_id( - &state, - &self.id, - merchant_account.get_id(), - ) - .await - .switch()?; + cards::delete_card_by_locker_id(state, &self.id, merchant_account.get_id()) + .await + .switch()?; } // No solution as of now, need to discuss this further with payment_method_v2 @@ -676,7 +672,7 @@ impl CustomerDeleteBridge for customers::GlobalId { customer_orig, merchant_account.get_id(), updated_customer, - &key_store, + key_store, merchant_account.storage_scheme, ) .await diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs index 90c36ba9aa8..7e184b318da 100644 --- a/crates/router/src/core/fraud_check.rs +++ b/crates/router/src/core/fraud_check.rs @@ -786,6 +786,7 @@ pub async fn frm_fulfillment_core( } } +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] pub async fn make_fulfillment_api_call( db: &dyn StorageInterface, diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs index bfb54c8f4e2..1a8bc1b5540 100644 --- a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs +++ b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs @@ -405,6 +405,7 @@ where frm_router_data: FrmRouterData, ) -> RouterResult<FrmData> { let db = &*state.store; + let key_manager_state = &state.into(); let frm_check_update = match frm_router_data.response { FrmResponse::Sale(response) => match response { Err(err) => Some(FraudCheckUpdate::ErrorUpdate { @@ -569,15 +570,30 @@ where ), }; + let payment_attempt_update = PaymentAttemptUpdate::RejectUpdate { + status: payment_attempt_status, + error_code: Some(Some(frm_data.fraud_check.frm_status.to_string())), + error_message, + updated_by: frm_data.merchant_account.storage_scheme.to_string(), + }; + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] let payment_attempt = db .update_payment_attempt_with_attempt_id( payment_data.get_payment_attempt().clone(), - PaymentAttemptUpdate::RejectUpdate { - status: payment_attempt_status, - error_code: Some(Some(frm_data.fraud_check.frm_status.to_string())), - error_message, - updated_by: frm_data.merchant_account.storage_scheme.to_string(), - }, + payment_attempt_update, + frm_data.merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + #[cfg(all(feature = "v2", feature = "payment_v2"))] + let payment_attempt = db + .update_payment_attempt_with_attempt_id( + key_manager_state, + key_store, + payment_data.get_payment_attempt().clone(), + payment_attempt_update, frm_data.merchant_account.storage_scheme, ) .await @@ -587,7 +603,7 @@ where let payment_intent = db .update_payment_intent( - &state.into(), + key_manager_state, payment_data.get_payment_intent().clone(), PaymentIntentUpdate::RejectUpdate { status: payment_intent_status, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 1b23dcab199..22350f77e69 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2046,7 +2046,7 @@ pub async fn delete_card_from_locker( #[cfg(all(feature = "v2", feature = "customer_v2"))] pub async fn delete_card_by_locker_id( state: &routes::SessionState, - id: &String, + id: &str, merchant_id: &id_type::MerchantId, ) -> errors::RouterResult<payment_methods::DeleteCardResp> { todo!() @@ -2472,7 +2472,7 @@ pub async fn delete_card_from_hs_locker<'a>( #[instrument(skip_all)] pub async fn delete_card_from_hs_locker_by_global_id<'a>( state: &routes::SessionState, - id: &String, + id: &str, merchant_id: &id_type::MerchantId, card_reference: &'a str, ) -> errors::RouterResult<payment_methods::DeleteCardResp> { @@ -4706,6 +4706,7 @@ async fn get_pm_list_context( Ok(payment_method_retrieval_context) } +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn perform_surcharge_ops( payment_intent: Option<storage::PaymentIntent>, state: &routes::SessionState, @@ -4750,6 +4751,18 @@ async fn perform_surcharge_ops( Ok(()) } +#[cfg(all(feature = "v2", feature = "payment_v2"))] +async fn perform_surcharge_ops( + _payment_intent: Option<storage::PaymentIntent>, + _state: &routes::SessionState, + _merchant_account: domain::MerchantAccount, + _key_store: domain::MerchantKeyStore, + _business_profile: Option<BusinessProfile>, + _response: &mut api::CustomerPaymentMethodsListResponse, +) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { + todo!() +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] struct SavedPMLPaymentsInfo { pub payment_intent: storage::PaymentIntent, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 2af3c52d758..a1d92d8a992 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3757,6 +3757,7 @@ pub enum AttemptType { } impl AttemptType { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] // The function creates a new payment_attempt from the previous payment attempt but doesn't populate fields like payment_method, error_code etc. // Logic to override the fields with data provided in the request should be done after this if required. // In case if fields are not overridden by the request then they contain the same data that was in the previous attempt provided it is populated in this function. @@ -3851,6 +3852,20 @@ impl AttemptType { } } + #[cfg(all(feature = "v2", feature = "payment_v2"))] + // The function creates a new payment_attempt from the previous payment attempt but doesn't populate fields like payment_method, error_code etc. + // Logic to override the fields with data provided in the request should be done after this if required. + // In case if fields are not overridden by the request then they contain the same data that was in the previous attempt provided it is populated in this function. + #[inline(always)] + fn make_new_payment_attempt( + _payment_method_data: Option<&api_models::payments::PaymentMethodData>, + _old_payment_attempt: PaymentAttempt, + _new_attempt_count: i16, + _storage_scheme: enums::MerchantStorageScheme, + ) -> PaymentAttempt { + todo!() + } + #[instrument(skip_all)] pub async fn modify_payment_intent_and_payment_attempt( &self, @@ -3865,19 +3880,34 @@ impl AttemptType { Self::SameOld => Ok((fetched_payment_intent, fetched_payment_attempt)), Self::New => { let db = &*state.store; + let key_manager_state = &state.into(); let new_attempt_count = fetched_payment_intent.attempt_count + 1; + let new_payment_attempt_to_insert = Self::make_new_payment_attempt( + request + .payment_method_data + .as_ref() + .and_then(|request_payment_method_data| { + request_payment_method_data.payment_method_data.as_ref() + }), + fetched_payment_attempt, + new_attempt_count, + storage_scheme, + ); + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + let new_payment_attempt = db + .insert_payment_attempt(new_payment_attempt_to_insert, storage_scheme) + .await + .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { + payment_id: fetched_payment_intent.get_id().to_owned(), + })?; + + #[cfg(all(feature = "v2", feature = "payment_v2"))] let new_payment_attempt = db .insert_payment_attempt( - Self::make_new_payment_attempt( - request.payment_method_data.as_ref().and_then( - |request_payment_method_data| { - request_payment_method_data.payment_method_data.as_ref() - }, - ), - fetched_payment_attempt, - new_attempt_count, - storage_scheme, - ), + key_manager_state, + key_store, + new_payment_attempt_to_insert, storage_scheme, ) .await @@ -3887,7 +3917,7 @@ impl AttemptType { let updated_payment_intent = db .update_payment_intent( - &state.into(), + key_manager_state, fetched_payment_intent, storage::PaymentIntentUpdate::StatusAndAttemptUpdate { status: payment_intent_status_fsm( diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index fb6bb044778..f397ecd8a2a 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -77,7 +77,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa let ephemeral_key = Self::get_ephemeral_key(request, state, merchant_account).await; let merchant_id = merchant_account.get_id(); let storage_scheme = merchant_account.storage_scheme; - let (payment_intent, payment_attempt); let money @ (amount, currency) = payments_create_request_validation(request)?; @@ -322,9 +321,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa ) .await?; - payment_intent = db + let payment_intent = db .insert_payment_intent( - &state.into(), + key_manager_state, payment_intent_new, merchant_key_store, storage_scheme, @@ -342,12 +341,27 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa )?; } - payment_attempt = db + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + let payment_attempt = db .insert_payment_attempt(payment_attempt_new, storage_scheme) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { payment_id: payment_id.clone(), })?; + + #[cfg(all(feature = "v2", feature = "payment_v2"))] + let payment_attempt = db + .insert_payment_attempt( + key_manager_state, + merchant_key_store, + payment_attempt_new, + storage_scheme, + ) + .await + .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { + payment_id: payment_id.clone(), + })?; + let mandate_details_present = payment_attempt.mandate_details.is_some(); helpers::validate_mandate_data_and_future_usage( diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 24ee0697ac3..fb09b4d8b60 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -246,6 +246,11 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor payment_method_id, updated_by: storage_scheme.clone().to_string(), }; + + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_v2") + ))] let respond = state .store .update_payment_attempt_with_attempt_id( @@ -254,6 +259,19 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor storage_scheme, ) .await; + + #[cfg(all(feature = "v2", feature = "payment_v2"))] + let respond = state + .store + .update_payment_attempt_with_attempt_id( + &(&state).into(), + &key_store, + payment_attempt, + payment_attempt_update, + storage_scheme, + ) + .await; + if let Err(err) = respond { logger::error!("Error updating payment attempt: {:?}", err); }; @@ -325,15 +343,33 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu }; //payment_attempt update if let Some(payment_attempt_update) = option_payment_attempt_update { - payment_data.payment_attempt = state - .store - .update_payment_attempt_with_attempt_id( - payment_data.payment_attempt.clone(), - payment_attempt_update, - storage_scheme, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + { + payment_data.payment_attempt = state + .store + .update_payment_attempt_with_attempt_id( + payment_data.payment_attempt.clone(), + payment_attempt_update, + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + } + + #[cfg(all(feature = "v2", feature = "payment_v2"))] + { + payment_data.payment_attempt = state + .store + .update_payment_attempt_with_attempt_id( + &state.into(), + key_store, + payment_data.payment_attempt.clone(), + payment_attempt_update, + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + } } // payment_intent update if let Some(payment_intent_update) = option_payment_intent_update { diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 75c0fb6d77f..ce2456e08c4 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -360,6 +360,7 @@ where ); let db = &*state.store; + let key_manager_state = &state.into(); let additional_payment_method_data = payments::helpers::update_additional_payment_data_with_connector_response_pm_data( payment_data @@ -389,43 +390,57 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not parse the connector response")?; + let payment_attempt_update = storage::PaymentAttemptUpdate::ResponseUpdate { + status: router_data.status, + connector: None, + connector_transaction_id: match resource_id { + types::ResponseId::NoResponseId => None, + types::ResponseId::ConnectorTransactionId(id) + | types::ResponseId::EncodedData(id) => Some(id), + }, + connector_response_reference_id: payment_data + .get_payment_attempt() + .connector_response_reference_id + .clone(), + authentication_type: None, + payment_method_id: payment_data.get_payment_attempt().payment_method_id.clone(), + mandate_id: payment_data + .get_mandate_id() + .and_then(|mandate| mandate.mandate_id.clone()), + connector_metadata, + payment_token: None, + error_code: None, + error_message: None, + error_reason: None, + amount_capturable: if router_data.status.is_terminal_status() { + Some(MinorUnit::new(0)) + } else { + None + }, + updated_by: storage_scheme.to_string(), + authentication_data, + encoded_data, + unified_code: None, + unified_message: None, + payment_method_data: additional_payment_method_data, + charge_id, + }; + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] db.update_payment_attempt_with_attempt_id( payment_data.get_payment_attempt().clone(), - storage::PaymentAttemptUpdate::ResponseUpdate { - status: router_data.status, - connector: None, - connector_transaction_id: match resource_id { - types::ResponseId::NoResponseId => None, - types::ResponseId::ConnectorTransactionId(id) - | types::ResponseId::EncodedData(id) => Some(id), - }, - connector_response_reference_id: payment_data - .get_payment_attempt() - .connector_response_reference_id - .clone(), - authentication_type: None, - payment_method_id: payment_data.get_payment_attempt().payment_method_id.clone(), - mandate_id: payment_data - .get_mandate_id() - .and_then(|mandate| mandate.mandate_id.clone()), - connector_metadata, - payment_token: None, - error_code: None, - error_message: None, - error_reason: None, - amount_capturable: if router_data.status.is_terminal_status() { - Some(MinorUnit::new(0)) - } else { - None - }, - updated_by: storage_scheme.to_string(), - authentication_data, - encoded_data, - unified_code: None, - unified_message: None, - payment_method_data: additional_payment_method_data, - charge_id, - }, + payment_attempt_update, + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + #[cfg(all(feature = "v2", feature = "payment_v2"))] + db.update_payment_attempt_with_attempt_id( + key_manager_state, + key_store, + payment_data.get_payment_attempt().clone(), + payment_attempt_update, storage_scheme, ) .await @@ -445,22 +460,36 @@ where None }; + let payment_attempt_update = storage::PaymentAttemptUpdate::ErrorUpdate { + connector: None, + error_code: Some(Some(error_response.code.clone())), + error_message: Some(Some(error_response.message.clone())), + status: storage_enums::AttemptStatus::Failure, + error_reason: Some(error_response.reason.clone()), + amount_capturable: Some(MinorUnit::new(0)), + updated_by: storage_scheme.to_string(), + unified_code: option_gsm.clone().map(|gsm| gsm.unified_code), + unified_message: option_gsm.map(|gsm| gsm.unified_message), + connector_transaction_id: error_response.connector_transaction_id.clone(), + payment_method_data: additional_payment_method_data, + authentication_type: auth_update, + }; + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] db.update_payment_attempt_with_attempt_id( payment_data.get_payment_attempt().clone(), - storage::PaymentAttemptUpdate::ErrorUpdate { - connector: None, - error_code: Some(Some(error_response.code.clone())), - error_message: Some(Some(error_response.message.clone())), - status: storage_enums::AttemptStatus::Failure, - error_reason: Some(error_response.reason.clone()), - amount_capturable: Some(MinorUnit::new(0)), - updated_by: storage_scheme.to_string(), - unified_code: option_gsm.clone().map(|gsm| gsm.unified_code), - unified_message: option_gsm.map(|gsm| gsm.unified_message), - connector_transaction_id: error_response.connector_transaction_id.clone(), - payment_method_data: additional_payment_method_data, - authentication_type: auth_update, - }, + payment_attempt_update, + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + #[cfg(all(feature = "v2", feature = "payment_v2"))] + db.update_payment_attempt_with_attempt_id( + key_manager_state, + key_store, + payment_data.get_payment_attempt().clone(), + payment_attempt_update, storage_scheme, ) .await @@ -468,6 +497,7 @@ where } } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] let payment_attempt = db .insert_payment_attempt(new_payment_attempt, storage_scheme) .await @@ -475,12 +505,25 @@ where payment_id: payment_data.get_payment_intent().get_id().to_owned(), })?; + #[cfg(all(feature = "v2", feature = "payment_v2"))] + let payment_attempt = db + .insert_payment_attempt( + key_manager_state, + key_store, + new_payment_attempt, + storage_scheme, + ) + .await + .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { + payment_id: payment_data.get_payment_intent().get_id().to_owned(), + })?; + // update payment_attempt, connector_response and payment_intent in payment_data payment_data.set_payment_attempt(payment_attempt); let payment_intent = db .update_payment_intent( - &state.into(), + key_manager_state, payment_data.get_payment_intent().clone(), storage::PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { active_attempt_id: payment_data.get_payment_attempt().attempt_id.clone(), @@ -498,6 +541,7 @@ where Ok(()) } +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] pub fn make_new_payment_attempt( connector: String, @@ -540,6 +584,9 @@ pub fn make_new_payment_attempt( created_at, modified_at, last_synced, + profile_id: old_payment_attempt.profile_id, + organization_id: old_payment_attempt.organization_id, + shipping_cost: old_payment_attempt.shipping_cost, net_amount: Default::default(), error_message: Default::default(), cancellation_reason: Default::default(), @@ -569,13 +616,21 @@ pub fn make_new_payment_attempt( fingerprint_id: Default::default(), charge_id: Default::default(), customer_acceptance: Default::default(), - profile_id: old_payment_attempt.profile_id, - organization_id: old_payment_attempt.organization_id, - shipping_cost: old_payment_attempt.shipping_cost, - order_tax_amount: None, + order_tax_amount: Default::default(), } } +#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[instrument(skip_all)] +pub fn make_new_payment_attempt( + _connector: String, + _old_payment_attempt: storage::PaymentAttempt, + _new_attempt_count: i16, + _is_step_up: bool, +) -> storage::PaymentAttempt { + todo!() +} + pub async fn config_should_call_gsm( db: &dyn StorageInterface, merchant_id: &common_utils::id_type::MerchantId, diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 7e703967a50..5143068db96 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1095,7 +1095,7 @@ async fn perform_session_routing_for_pm_type( &session_pm_input.state.clone(), merchant_id, algorithm_id, - &session_pm_input.profile_id, + session_pm_input.profile_id, transaction_type, ) .await?; @@ -1124,7 +1124,7 @@ async fn perform_session_routing_for_pm_type( chosen_connectors, session_pm_input.backend_input.clone(), None, - &session_pm_input.profile_id, + session_pm_input.profile_id, transaction_type, ) .await?; @@ -1140,7 +1140,7 @@ async fn perform_session_routing_for_pm_type( fallback, session_pm_input.backend_input.clone(), None, - &session_pm_input.profile_id, + session_pm_input.profile_id, transaction_type, ) .await?; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 4892e2552ec..4dc77211857 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -851,7 +851,7 @@ impl MandateInterface for KafkaStore { #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_mandate_by_global_id( &self, - id: &String, + id: &str, ) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> { self.diesel_store.find_mandate_by_global_id(id).await } @@ -1332,6 +1332,7 @@ impl QueueInterface for KafkaStore { #[async_trait::async_trait] impl PaymentAttemptInterface for KafkaStore { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn insert_payment_attempt( &self, payment_attempt: storage::PaymentAttemptNew, @@ -1353,6 +1354,36 @@ impl PaymentAttemptInterface for KafkaStore { Ok(attempt) } + #[cfg(all(feature = "v2", feature = "payment_v2"))] + async fn insert_payment_attempt( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &domain::MerchantKeyStore, + payment_attempt: storage::PaymentAttempt, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> { + let attempt = self + .diesel_store + .insert_payment_attempt( + key_manager_state, + merchant_key_store, + payment_attempt, + storage_scheme, + ) + .await?; + + if let Err(er) = self + .kafka_producer + .log_payment_attempt(&attempt, None, self.tenant_id.clone()) + .await + { + logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) + } + + Ok(attempt) + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn update_payment_attempt_with_attempt_id( &self, this: storage::PaymentAttempt, @@ -1375,6 +1406,38 @@ impl PaymentAttemptInterface for KafkaStore { Ok(attempt) } + #[cfg(all(feature = "v2", feature = "payment_v2"))] + async fn update_payment_attempt_with_attempt_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &domain::MerchantKeyStore, + this: storage::PaymentAttempt, + payment_attempt: storage::PaymentAttemptUpdate, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> { + let attempt = self + .diesel_store + .update_payment_attempt_with_attempt_id( + key_manager_state, + merchant_key_store, + this.clone(), + payment_attempt, + storage_scheme, + ) + .await?; + + if let Err(er) = self + .kafka_producer + .log_payment_attempt(&attempt, Some(this), self.tenant_id.clone()) + .await + { + logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) + } + + Ok(attempt) + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, connector_transaction_id: &str, @@ -1392,6 +1455,7 @@ impl PaymentAttemptInterface for KafkaStore { .await } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, merchant_id: &id_type::MerchantId, @@ -1407,6 +1471,7 @@ impl PaymentAttemptInterface for KafkaStore { .await } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, payment_id: &id_type::PaymentId, @@ -1424,6 +1489,7 @@ impl PaymentAttemptInterface for KafkaStore { .await } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, attempt_id: &str, @@ -1435,6 +1501,27 @@ impl PaymentAttemptInterface for KafkaStore { .await } + #[cfg(all(feature = "v2", feature = "payment_v2"))] + async fn find_payment_attempt_by_attempt_id_merchant_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &domain::MerchantKeyStore, + attempt_id: &str, + merchant_id: &id_type::MerchantId, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> { + self.diesel_store + .find_payment_attempt_by_attempt_id_merchant_id( + key_manager_state, + merchant_key_store, + attempt_id, + merchant_id, + storage_scheme, + ) + .await + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, @@ -1450,6 +1537,7 @@ impl PaymentAttemptInterface for KafkaStore { .await } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, @@ -1465,6 +1553,7 @@ impl PaymentAttemptInterface for KafkaStore { .await } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, preprocessing_id: &str, @@ -1480,6 +1569,7 @@ impl PaymentAttemptInterface for KafkaStore { .await } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn get_filters_for_payments( &self, pi: &[hyperswitch_domain_models::payments::PaymentIntent], @@ -1494,6 +1584,7 @@ impl PaymentAttemptInterface for KafkaStore { .await } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &id_type::MerchantId, @@ -1521,6 +1612,7 @@ impl PaymentAttemptInterface for KafkaStore { .await } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_attempts_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, @@ -1769,7 +1861,7 @@ impl PaymentMethodInterface for KafkaStore { &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, - id: &String, + id: &str, limit: Option<i64>, ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> { self.diesel_store diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs index 24356494471..40e5f88614d 100644 --- a/crates/router/src/db/mandate.rs +++ b/crates/router/src/db/mandate.rs @@ -32,7 +32,7 @@ pub trait MandateInterface { #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_mandate_by_global_id( &self, - id: &String, + id: &str, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError>; async fn update_mandate_by_merchant_id_mandate_id( @@ -203,7 +203,7 @@ mod storage { #[instrument(skip_all)] async fn find_mandate_by_global_id( &self, - id: &String, + id: &str, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_global_id(&conn, id) @@ -459,7 +459,7 @@ mod storage { #[instrument(skip_all)] async fn find_mandate_by_global_id( &self, - customer_id: &String, + customer_id: &str, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_global_id(&conn, customer_id) @@ -572,7 +572,7 @@ impl MandateInterface for MockDb { #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_mandate_by_global_id( &self, - id: &String, + id: &str, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { todo!() } diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs index 0541491ab98..cf263def41c 100644 --- a/crates/router/src/db/payment_method.rs +++ b/crates/router/src/db/payment_method.rs @@ -53,7 +53,7 @@ pub trait PaymentMethodInterface { &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, - id: &String, + id: &str, limit: Option<i64>, ) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError>; @@ -715,7 +715,7 @@ mod storage { &self, _state: &KeyManagerState, _key_store: &domain::MerchantKeyStore, - _id: &String, + _id: &str, _limit: Option<i64>, ) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> { todo!() @@ -1129,7 +1129,7 @@ mod storage { &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, - id: &String, + id: &str, limit: Option<i64>, ) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; @@ -1409,7 +1409,7 @@ impl PaymentMethodInterface for MockDb { &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, - _id: &String, + _id: &str, _limit: Option<i64>, ) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> { todo!() diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index d66dc8e51e2..2bafe504dd9 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1576,13 +1576,13 @@ impl BusinessProfile { pub fn server(state: AppState) -> Scope { web::scope("/v2/profiles") .app_data(web::Data::new(state)) - .service(web::resource("").route(web::post().to(super::admin::business_profile_create))) + .service(web::resource("").route(web::post().to(admin::business_profile_create))) .service( web::scope("/{profile_id}") .service( web::resource("") - .route(web::get().to(super::admin::business_profile_retrieve)) - .route(web::put().to(super::admin::business_profile_update)), + .route(web::get().to(admin::business_profile_retrieve)) + .route(web::put().to(admin::business_profile_update)), ) .service( web::resource("/connector_accounts") diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 549c544f30f..e30a6ccc1fd 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -189,7 +189,7 @@ impl ForeignTryFrom<domain::BusinessProfile> for BusinessProfileResponse { let order_fulfillment_time = item .order_fulfillment_time - .map(api_models::admin::OrderFulfillmentTime::new) + .map(api_models::admin::OrderFulfillmentTime::try_new) .transpose() .change_context(errors::ParsingError::IntegerOverflow)?; diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 8d6fb1a8ffb..725cefb8c41 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -401,7 +401,7 @@ impl NewUserMerchant { let merchant_name = if let Some(company_name) = self.company_name.clone() { MerchantName::try_from(company_name) } else { - MerchantName::new("merchant".to_string()) + MerchantName::try_new("merchant".to_string()) .change_context(UserErrors::InternalServerError) .attach_printable("merchant name validation failed") } diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs index 782d5ae76a0..18b6e8cc6f9 100644 --- a/crates/router/src/types/storage/payment_attempt.rs +++ b/crates/router/src/types/storage/payment_attempt.rs @@ -85,7 +85,11 @@ impl AttemptStatusExt for enums::AttemptStatus { } #[cfg(test)] -#[cfg(feature = "dummy_connector")] +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_v2"), // Ignoring tests for v2 since they aren't actively running + feature = "dummy_connector" +))] mod tests { #![allow(clippy::expect_used, clippy::unwrap_used, clippy::print_stderr)] use tokio::sync::oneshot; diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 46210d4dd09..1442f5b8d48 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -10,7 +10,6 @@ use common_utils::{ ext_traits::{Encode, StringExt, ValueExt}, fp_utils::when, pii, - types::MinorUnit, }; use diesel_models::enums as storage_enums; use error_stack::{report, ResultExt}; @@ -376,7 +375,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { impl ForeignFrom<storage_enums::MandateAmountData> for payments::MandateAmountData { fn foreign_from(from: storage_enums::MandateAmountData) -> Self { Self { - amount: MinorUnit::new(from.amount), + amount: from.amount, currency: from.currency, start_date: from.start_date, end_date: from.end_date, @@ -443,7 +442,7 @@ impl ForeignFrom<payments::MandateData> for hyperswitch_domain_models::mandates: impl ForeignFrom<payments::MandateAmountData> for storage_enums::MandateAmountData { fn foreign_from(from: payments::MandateAmountData) -> Self { Self { - amount: from.amount.get_amount_as_i64(), + amount: from.amount, currency: from.currency, start_date: from.start_date, end_date: from.end_date, diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index 12a26cf7c8b..b603b86a72c 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -378,6 +378,9 @@ pub async fn get_mca_from_payment_intent( connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; + let key_manager_state: &KeyManagerState = &state.into(); + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &payment_intent.active_attempt.get_id(), @@ -386,7 +389,19 @@ pub async fn get_mca_from_payment_intent( ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - let key_manager_state: &KeyManagerState = &state.into(); + + #[cfg(all(feature = "v2", feature = "payment_v2"))] + let payment_attempt = db + .find_payment_attempt_by_attempt_id_merchant_id( + key_manager_state, + key_store, + &payment_intent.active_attempt.get_id(), + merchant_account.get_id(), + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + match payment_attempt.merchant_connector_id { Some(merchant_connector_id) => { #[cfg(feature = "v1")] diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index 7147c5071c7..f030df01fc0 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -262,7 +262,7 @@ pub async fn generate_sample_data( true => common_enums::AttemptStatus::Failure, _ => common_enums::AttemptStatus::Charged, }, - amount: amount * 100, + amount: MinorUnit::new(amount * 100), currency: payment_intent.currency, connector: Some( (*connector_vec @@ -289,7 +289,7 @@ pub async fn generate_sample_data( created_at, modified_at, last_synced: Some(last_synced), - amount_to_capture: Some(amount * 100), + amount_to_capture: Some(MinorUnit::new(amount * 100)), connector_response_reference_id: Some(attempt_id.clone()), updated_by: merchant_from_db.storage_scheme.to_string(), save_to_locker: None, @@ -312,7 +312,7 @@ pub async fn generate_sample_data( mandate_details: None, error_reason: None, multiple_capture_count: None, - amount_capturable: i64::default(), + amount_capturable: MinorUnit::new(i64::default()), merchant_connector_id: None, authentication_data: None, encoded_data: None, diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 6558c14ace3..1a4595bdbbe 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -1,6 +1,10 @@ use api_models::enums::{AuthenticationType, Connector, PaymentMethod, PaymentMethodType}; use common_utils::errors::CustomResult; +#[cfg(all(feature = "v2", feature = "payment_v2"))] +use common_utils::types::keymanager::KeyManagerState; use diesel_models::enums as storage_enums; +#[cfg(all(feature = "v2", feature = "payment_v2"))] +use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; use hyperswitch_domain_models::{ errors::StorageError, payments::payment_attempt::{ @@ -13,6 +17,7 @@ use crate::DataModelExt; #[async_trait::async_trait] impl PaymentAttemptInterface for MockDb { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, _payment_id: &common_utils::id_type::PaymentId, @@ -24,6 +29,7 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn get_filters_for_payments( &self, _pi: &[hyperswitch_domain_models::payments::PaymentIntent], @@ -36,6 +42,7 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn get_total_count_of_filtered_payment_attempts( &self, _merchant_id: &common_utils::id_type::MerchantId, @@ -51,6 +58,7 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, _attempt_id: &str, @@ -61,6 +69,20 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } + #[cfg(all(feature = "v2", feature = "payment_v2"))] + async fn find_payment_attempt_by_attempt_id_merchant_id( + &self, + _key_manager_state: &KeyManagerState, + _merchant_key_store: &MerchantKeyStore, + _attempt_id: &str, + _merchant_id: &common_utils::id_type::MerchantId, + _storage_scheme: storage_enums::MerchantStorageScheme, + ) -> CustomResult<PaymentAttempt, StorageError> { + // [#172]: Implement function for `MockDb` + Err(StorageError::MockDbError)? + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, _preprocessing_id: &str, @@ -71,6 +93,7 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, _merchant_id: &common_utils::id_type::MerchantId, @@ -81,6 +104,7 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_attempts_by_merchant_id_payment_id( &self, _merchant_id: &common_utils::id_type::MerchantId, @@ -91,6 +115,7 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[allow(clippy::panic)] async fn insert_payment_attempt( &self, @@ -168,6 +193,20 @@ impl PaymentAttemptInterface for MockDb { Ok(payment_attempt) } + #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[allow(clippy::panic)] + async fn insert_payment_attempt( + &self, + _key_manager_state: &KeyManagerState, + _merchant_key_store: &MerchantKeyStore, + _payment_attempt: PaymentAttempt, + _storage_scheme: storage_enums::MerchantStorageScheme, + ) -> CustomResult<PaymentAttempt, StorageError> { + // [#172]: Implement function for `MockDb` + Err(StorageError::MockDbError)? + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] // safety: only used for testing #[allow(clippy::unwrap_used)] async fn update_payment_attempt_with_attempt_id( @@ -192,6 +231,20 @@ impl PaymentAttemptInterface for MockDb { Ok(item.clone()) } + #[cfg(all(feature = "v2", feature = "payment_v2"))] + async fn update_payment_attempt_with_attempt_id( + &self, + _key_manager_state: &KeyManagerState, + _merchant_key_store: &MerchantKeyStore, + _this: PaymentAttempt, + _payment_attempt: PaymentAttemptUpdate, + _storage_scheme: storage_enums::MerchantStorageScheme, + ) -> CustomResult<PaymentAttempt, StorageError> { + // [#172]: Implement function for `MockDb` + Err(StorageError::MockDbError)? + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, _connector_transaction_id: &str, @@ -203,6 +256,7 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] // safety: only used for testing #[allow(clippy::unwrap_used)] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( @@ -222,6 +276,8 @@ impl PaymentAttemptInterface for MockDb { .cloned() .unwrap()) } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[allow(clippy::unwrap_used)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 85fe2b22d3e..d1df6861657 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -1,5 +1,7 @@ use api_models::enums::{AuthenticationType, Connector, PaymentMethod, PaymentMethodType}; -use common_utils::{errors::CustomResult, fallback_reverse_lookup_not_found, types::MinorUnit}; +#[cfg(all(feature = "v2", feature = "payment_v2"))] +use common_utils::types::keymanager::KeyManagerState; +use common_utils::{errors::CustomResult, fallback_reverse_lookup_not_found}; use diesel_models::{ enums::{ MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType, @@ -25,6 +27,10 @@ use hyperswitch_domain_models::{ PaymentIntent, }, }; +#[cfg(all(feature = "v2", feature = "payment_v2"))] +use hyperswitch_domain_models::{ + behaviour::ReverseConversion, merchant_key_store::MerchantKeyStore, +}; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; @@ -39,6 +45,7 @@ use crate::{ #[async_trait::async_trait] impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn insert_payment_attempt( &self, @@ -57,6 +64,36 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } + #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[instrument(skip_all)] + async fn insert_payment_attempt( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &MerchantKeyStore, + payment_attempt: PaymentAttempt, + _storage_scheme: MerchantStorageScheme, + ) -> CustomResult<PaymentAttempt, errors::StorageError> { + let conn = pg_connection_write(self).await?; + payment_attempt + .construct_new() + .await + .change_context(errors::StorageError::EncryptionError)? + .insert(&conn) + .await + .map_err(|error| { + let new_error = diesel_error_to_data_error(error.current_context()); + error.change_context(new_error) + })? + .convert( + key_manager_state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone().into(), + ) + .await + .change_context(errors::StorageError::DecryptionError) + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn update_payment_attempt_with_attempt_id( &self, @@ -75,6 +112,40 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } + #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[instrument(skip_all)] + async fn update_payment_attempt_with_attempt_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &MerchantKeyStore, + this: PaymentAttempt, + payment_attempt: PaymentAttemptUpdate, + _storage_scheme: MerchantStorageScheme, + ) -> CustomResult<PaymentAttempt, errors::StorageError> { + let conn = pg_connection_write(self).await?; + + Conversion::convert(this) + .await + .change_context(errors::StorageError::EncryptionError)? + .update_with_attempt_id( + &conn, + diesel_models::PaymentAttemptUpdateInternal::from(payment_attempt), + ) + .await + .map_err(|error| { + let new_error = diesel_error_to_data_error(error.current_context()); + error.change_context(new_error) + })? + .convert( + key_manager_state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone().into(), + ) + .await + .change_context(errors::StorageError::DecryptionError) + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, @@ -98,6 +169,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, @@ -119,6 +191,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, @@ -140,6 +213,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, @@ -161,6 +235,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, @@ -185,6 +260,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn get_filters_for_payments( &self, @@ -194,7 +270,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { ) -> CustomResult<PaymentListFilters, errors::StorageError> { let conn = pg_connection_read(self).await?; let intents = futures::future::try_join_all(pi.iter().cloned().map(|pi| async { - pi.convert() + Conversion::convert(pi) .await .change_context(errors::StorageError::EncryptionError) })) @@ -225,6 +301,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { ) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, @@ -247,6 +324,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn find_attempts_by_merchant_id_payment_id( &self, @@ -268,6 +346,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { }) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, @@ -286,6 +365,34 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } + #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[instrument(skip_all)] + async fn find_payment_attempt_by_attempt_id_merchant_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &MerchantKeyStore, + attempt_id: &str, + merchant_id: &common_utils::id_type::MerchantId, + _storage_scheme: MerchantStorageScheme, + ) -> CustomResult<PaymentAttempt, errors::StorageError> { + let conn = pg_connection_read(self).await?; + + DieselPaymentAttempt::find_by_merchant_id_attempt_id(&conn, merchant_id, attempt_id) + .await + .map_err(|er| { + let new_err = diesel_error_to_data_error(er.current_context()); + er.change_context(new_err) + })? + .convert( + key_manager_state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone().into(), + ) + .await + .change_context(errors::StorageError::DecryptionError) + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn get_total_count_of_filtered_payment_attempts( &self, @@ -332,6 +439,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { #[async_trait::async_trait] impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn insert_payment_attempt( &self, @@ -480,6 +588,27 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } + #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[instrument(skip_all)] + async fn insert_payment_attempt( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &MerchantKeyStore, + payment_attempt: PaymentAttempt, + storage_scheme: MerchantStorageScheme, + ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { + // Ignoring storage scheme for v2 implementation + self.router_store + .insert_payment_attempt( + key_manager_state, + merchant_key_store, + payment_attempt, + storage_scheme, + ) + .await + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn update_payment_attempt_with_attempt_id( &self, @@ -603,6 +732,29 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } + #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[instrument(skip_all)] + async fn update_payment_attempt_with_attempt_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &MerchantKeyStore, + this: PaymentAttempt, + payment_attempt: PaymentAttemptUpdate, + storage_scheme: MerchantStorageScheme, + ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { + // Ignoring storage scheme for v2 implementation + self.router_store + .update_payment_attempt_with_attempt_id( + key_manager_state, + merchant_key_store, + this, + payment_attempt, + storage_scheme, + ) + .await + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, @@ -662,6 +814,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, @@ -720,6 +873,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, @@ -781,6 +935,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, @@ -849,6 +1004,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, @@ -902,6 +1058,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, @@ -967,6 +1124,29 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } + #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[instrument(skip_all)] + async fn find_payment_attempt_by_attempt_id_merchant_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &MerchantKeyStore, + attempt_id: &str, + merchant_id: &common_utils::id_type::MerchantId, + storage_scheme: MerchantStorageScheme, + ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { + // Ignoring storage scheme for v2 implementation + self.router_store + .find_payment_attempt_by_attempt_id_merchant_id( + key_manager_state, + merchant_key_store, + attempt_id, + merchant_id, + storage_scheme, + ) + .await + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, @@ -1035,6 +1215,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn find_attempts_by_merchant_id_payment_id( &self, @@ -1084,6 +1265,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn get_filters_for_payments( &self, @@ -1096,6 +1278,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { .await } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] #[instrument(skip_all)] async fn get_total_count_of_filtered_payment_attempts( &self, @@ -1130,7 +1313,7 @@ impl DataModelExt for MandateAmountData { fn to_storage_model(self) -> Self::StorageModel { DieselMandateAmountData { - amount: self.amount.get_amount_as_i64(), + amount: self.amount, currency: self.currency, start_date: self.start_date, end_date: self.end_date, @@ -1140,7 +1323,7 @@ impl DataModelExt for MandateAmountData { fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { - amount: MinorUnit::new(storage_model.amount), + amount: storage_model.amount, currency: storage_model.currency, start_date: storage_model.start_date, end_date: storage_model.end_date, @@ -1198,19 +1381,15 @@ impl DataModelExt for PaymentAttempt { merchant_id: self.merchant_id, attempt_id: self.attempt_id, status: self.status, - amount: self.amount.get_amount_as_i64(), - net_amount: Some(self.net_amount.get_amount_as_i64()), + amount: self.amount, + net_amount: Some(self.net_amount), currency: self.currency, save_to_locker: self.save_to_locker, connector: self.connector, error_message: self.error_message, - offer_amount: self - .offer_amount - .map(|offer_amt| offer_amt.get_amount_as_i64()), - surcharge_amount: self - .surcharge_amount - .map(|surcharge_amt| surcharge_amt.get_amount_as_i64()), - tax_amount: self.tax_amount.map(|tax_amt| tax_amt.get_amount_as_i64()), + offer_amount: self.offer_amount, + surcharge_amount: self.surcharge_amount, + tax_amount: self.tax_amount, payment_method_id: self.payment_method_id, payment_method: self.payment_method, connector_transaction_id: self.connector_transaction_id, @@ -1222,9 +1401,7 @@ impl DataModelExt for PaymentAttempt { modified_at: self.modified_at, last_synced: self.last_synced, cancellation_reason: self.cancellation_reason, - amount_to_capture: self - .amount_to_capture - .map(|capture_amt| capture_amt.get_amount_as_i64()), + amount_to_capture: self.amount_to_capture, mandate_id: self.mandate_id, browser_info: self.browser_info, error_code: self.error_code, @@ -1249,7 +1426,7 @@ impl DataModelExt for PaymentAttempt { error_reason: self.error_reason, multiple_capture_count: self.multiple_capture_count, connector_response_reference_id: self.connector_response_reference_id, - amount_capturable: self.amount_capturable.get_amount_as_i64(), + amount_capturable: self.amount_capturable, updated_by: self.updated_by, authentication_data: self.authentication_data, encoded_data: self.encoded_data, @@ -1276,19 +1453,19 @@ impl DataModelExt for PaymentAttempt { fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { - net_amount: MinorUnit::new(storage_model.get_or_calculate_net_amount()), + net_amount: storage_model.get_or_calculate_net_amount(), payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id, attempt_id: storage_model.attempt_id, status: storage_model.status, - amount: MinorUnit::new(storage_model.amount), + amount: storage_model.amount, currency: storage_model.currency, save_to_locker: storage_model.save_to_locker, connector: storage_model.connector, error_message: storage_model.error_message, - offer_amount: storage_model.offer_amount.map(MinorUnit::new), - surcharge_amount: storage_model.surcharge_amount.map(MinorUnit::new), - tax_amount: storage_model.tax_amount.map(MinorUnit::new), + offer_amount: storage_model.offer_amount, + surcharge_amount: storage_model.surcharge_amount, + tax_amount: storage_model.tax_amount, payment_method_id: storage_model.payment_method_id, payment_method: storage_model.payment_method, connector_transaction_id: storage_model.connector_transaction_id, @@ -1300,7 +1477,7 @@ impl DataModelExt for PaymentAttempt { modified_at: storage_model.modified_at, last_synced: storage_model.last_synced, cancellation_reason: storage_model.cancellation_reason, - amount_to_capture: storage_model.amount_to_capture.map(MinorUnit::new), + amount_to_capture: storage_model.amount_to_capture, mandate_id: storage_model.mandate_id, browser_info: storage_model.browser_info, error_code: storage_model.error_code, @@ -1318,7 +1495,7 @@ impl DataModelExt for PaymentAttempt { error_reason: storage_model.error_reason, multiple_capture_count: storage_model.multiple_capture_count, connector_response_reference_id: storage_model.connector_response_reference_id, - amount_capturable: MinorUnit::new(storage_model.amount_capturable), + amount_capturable: storage_model.amount_capturable, updated_by: storage_model.updated_by, authentication_data: storage_model.authentication_data, encoded_data: storage_model.encoded_data, @@ -1356,19 +1533,15 @@ impl DataModelExt for PaymentAttempt { merchant_id: self.merchant_id, attempt_id: self.attempt_id, status: self.status, - amount: self.amount.get_amount_as_i64(), - net_amount: Some(self.net_amount.get_amount_as_i64()), + amount: self.amount, + net_amount: Some(self.net_amount), currency: self.currency, save_to_locker: self.save_to_locker, connector: self.connector, error_message: self.error_message, - offer_amount: self - .offer_amount - .map(|offer_amt| offer_amt.get_amount_as_i64()), - surcharge_amount: self - .surcharge_amount - .map(|surcharge_amt| surcharge_amt.get_amount_as_i64()), - tax_amount: self.tax_amount.map(|tax_amt| tax_amt.get_amount_as_i64()), + offer_amount: self.offer_amount, + surcharge_amount: self.surcharge_amount, + tax_amount: self.tax_amount, payment_method_id: self.payment_method_id, payment_method: self.payment_method, connector_transaction_id: self.connector_transaction_id, @@ -1380,9 +1553,7 @@ impl DataModelExt for PaymentAttempt { modified_at: self.modified_at, last_synced: self.last_synced, cancellation_reason: self.cancellation_reason, - amount_to_capture: self - .amount_to_capture - .map(|capture_amt| capture_amt.get_amount_as_i64()), + amount_to_capture: self.amount_to_capture, mandate_id: self.mandate_id, browser_info: self.browser_info, error_code: self.error_code, @@ -1407,7 +1578,7 @@ impl DataModelExt for PaymentAttempt { error_reason: self.error_reason, multiple_capture_count: self.multiple_capture_count, connector_response_reference_id: self.connector_response_reference_id, - amount_capturable: self.amount_capturable.get_amount_as_i64(), + amount_capturable: self.amount_capturable, updated_by: self.updated_by, authentication_data: self.authentication_data, encoded_data: self.encoded_data, @@ -1434,19 +1605,19 @@ impl DataModelExt for PaymentAttempt { fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { - net_amount: MinorUnit::new(storage_model.get_or_calculate_net_amount()), + net_amount: storage_model.get_or_calculate_net_amount(), payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id, attempt_id: storage_model.attempt_id, status: storage_model.status, - amount: MinorUnit::new(storage_model.amount), + amount: storage_model.amount, currency: storage_model.currency, save_to_locker: storage_model.save_to_locker, connector: storage_model.connector, error_message: storage_model.error_message, - offer_amount: storage_model.offer_amount.map(MinorUnit::new), - surcharge_amount: storage_model.surcharge_amount.map(MinorUnit::new), - tax_amount: storage_model.tax_amount.map(MinorUnit::new), + offer_amount: storage_model.offer_amount, + surcharge_amount: storage_model.surcharge_amount, + tax_amount: storage_model.tax_amount, payment_method_id: storage_model.payment_method_id, payment_method: storage_model.payment_method, connector_transaction_id: storage_model.connector_transaction_id, @@ -1458,7 +1629,7 @@ impl DataModelExt for PaymentAttempt { modified_at: storage_model.modified_at, last_synced: storage_model.last_synced, cancellation_reason: storage_model.cancellation_reason, - amount_to_capture: storage_model.amount_to_capture.map(MinorUnit::new), + amount_to_capture: storage_model.amount_to_capture, mandate_id: storage_model.mandate_id, browser_info: storage_model.browser_info, error_code: storage_model.error_code, @@ -1476,7 +1647,7 @@ impl DataModelExt for PaymentAttempt { error_reason: storage_model.error_reason, multiple_capture_count: storage_model.multiple_capture_count, connector_response_reference_id: storage_model.connector_response_reference_id, - amount_capturable: MinorUnit::new(storage_model.amount_capturable), + amount_capturable: storage_model.amount_capturable, updated_by: storage_model.updated_by, authentication_data: storage_model.authentication_data, encoded_data: storage_model.encoded_data, @@ -1509,23 +1680,19 @@ impl DataModelExt for PaymentAttemptNew { fn to_storage_model(self) -> Self::StorageModel { DieselPaymentAttemptNew { - net_amount: Some(self.net_amount.get_amount_as_i64()), + net_amount: Some(self.net_amount), payment_id: self.payment_id, merchant_id: self.merchant_id, attempt_id: self.attempt_id, status: self.status, - amount: self.amount.get_amount_as_i64(), + amount: self.amount, currency: self.currency, save_to_locker: self.save_to_locker, connector: self.connector, error_message: self.error_message, - offer_amount: self - .offer_amount - .map(|offer_amt| offer_amt.get_amount_as_i64()), - surcharge_amount: self - .surcharge_amount - .map(|surcharge_amt| surcharge_amt.get_amount_as_i64()), - tax_amount: self.tax_amount.map(|tax_amt| tax_amt.get_amount_as_i64()), + offer_amount: self.offer_amount, + surcharge_amount: self.surcharge_amount, + tax_amount: self.tax_amount, payment_method_id: self.payment_method_id, payment_method: self.payment_method, capture_method: self.capture_method, @@ -1538,9 +1705,7 @@ impl DataModelExt for PaymentAttemptNew { .unwrap_or_else(common_utils::date_time::now), last_synced: self.last_synced, cancellation_reason: self.cancellation_reason, - amount_to_capture: self - .amount_to_capture - .map(|capture_amt| capture_amt.get_amount_as_i64()), + amount_to_capture: self.amount_to_capture, mandate_id: self.mandate_id, browser_info: self.browser_info, payment_token: self.payment_token, @@ -1565,7 +1730,7 @@ impl DataModelExt for PaymentAttemptNew { error_reason: self.error_reason, connector_response_reference_id: self.connector_response_reference_id, multiple_capture_count: self.multiple_capture_count, - amount_capturable: self.amount_capturable.get_amount_as_i64(), + amount_capturable: self.amount_capturable, updated_by: self.updated_by, authentication_data: self.authentication_data, encoded_data: self.encoded_data, @@ -1592,19 +1757,19 @@ impl DataModelExt for PaymentAttemptNew { fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { - net_amount: MinorUnit::new(storage_model.get_or_calculate_net_amount()), + net_amount: storage_model.get_or_calculate_net_amount(), payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id, attempt_id: storage_model.attempt_id, status: storage_model.status, - amount: MinorUnit::new(storage_model.amount), + amount: storage_model.amount, currency: storage_model.currency, save_to_locker: storage_model.save_to_locker, connector: storage_model.connector, error_message: storage_model.error_message, - offer_amount: storage_model.offer_amount.map(MinorUnit::new), - surcharge_amount: storage_model.surcharge_amount.map(MinorUnit::new), - tax_amount: storage_model.tax_amount.map(MinorUnit::new), + offer_amount: storage_model.offer_amount, + surcharge_amount: storage_model.surcharge_amount, + tax_amount: storage_model.tax_amount, payment_method_id: storage_model.payment_method_id, payment_method: storage_model.payment_method, capture_method: storage_model.capture_method, @@ -1615,7 +1780,7 @@ impl DataModelExt for PaymentAttemptNew { modified_at: Some(storage_model.modified_at), last_synced: storage_model.last_synced, cancellation_reason: storage_model.cancellation_reason, - amount_to_capture: storage_model.amount_to_capture.map(MinorUnit::new), + amount_to_capture: storage_model.amount_to_capture, mandate_id: storage_model.mandate_id, browser_info: storage_model.browser_info, payment_token: storage_model.payment_token, @@ -1633,7 +1798,7 @@ impl DataModelExt for PaymentAttemptNew { error_reason: storage_model.error_reason, connector_response_reference_id: storage_model.connector_response_reference_id, multiple_capture_count: storage_model.multiple_capture_count, - amount_capturable: MinorUnit::new(storage_model.amount_capturable), + amount_capturable: storage_model.amount_capturable, updated_by: storage_model.updated_by, authentication_data: storage_model.authentication_data, encoded_data: storage_model.encoded_data, @@ -1685,7 +1850,7 @@ impl DataModelExt for PaymentAttemptUpdate { payment_method_billing_address_id, updated_by, } => DieselPaymentAttemptUpdate::Update { - amount: amount.get_amount_as_i64(), + amount, currency, status, authentication_type, @@ -1695,12 +1860,10 @@ impl DataModelExt for PaymentAttemptUpdate { payment_method_type, payment_experience, business_sub_label, - amount_to_capture: amount_to_capture - .map(|capture_amt| capture_amt.get_amount_as_i64()), + amount_to_capture, capture_method, - surcharge_amount: surcharge_amount - .map(|surcharge_amt| surcharge_amt.get_amount_as_i64()), - tax_amount: tax_amount.map(|tax_amt| tax_amt.get_amount_as_i64()), + surcharge_amount, + tax_amount, fingerprint_id, payment_method_billing_address_id, updated_by, @@ -1718,11 +1881,9 @@ impl DataModelExt for PaymentAttemptUpdate { payment_token, connector, straight_through_algorithm, - amount_capturable: amount_capturable - .map(|amount_capturable| amount_capturable.get_amount_as_i64()), - surcharge_amount: surcharge_amount - .map(|surcharge_amt| surcharge_amt.get_amount_as_i64()), - tax_amount: tax_amount.map(|tax_amt| tax_amt.get_amount_as_i64()), + amount_capturable, + surcharge_amount, + tax_amount, updated_by, merchant_connector_id, }, @@ -1785,7 +1946,7 @@ impl DataModelExt for PaymentAttemptUpdate { shipping_cost, order_tax_amount, } => DieselPaymentAttemptUpdate::ConfirmUpdate { - amount: amount.get_amount_as_i64(), + amount, currency, status, authentication_type, @@ -1801,11 +1962,9 @@ impl DataModelExt for PaymentAttemptUpdate { straight_through_algorithm, error_code, error_message, - amount_capturable: amount_capturable - .map(|capture_amt| capture_amt.get_amount_as_i64()), - surcharge_amount: surcharge_amount - .map(|surcharge_amt| surcharge_amt.get_amount_as_i64()), - tax_amount: tax_amount.map(|tax_amt| tax_amt.get_amount_as_i64()), + amount_capturable, + surcharge_amount, + tax_amount, fingerprint_id, updated_by, merchant_connector_id: connector_id, @@ -1863,8 +2022,7 @@ impl DataModelExt for PaymentAttemptUpdate { error_message, error_reason, connector_response_reference_id, - amount_capturable: amount_capturable - .map(|capture_amt| capture_amt.get_amount_as_i64()), + amount_capturable, updated_by, authentication_data, encoded_data, @@ -1916,8 +2074,7 @@ impl DataModelExt for PaymentAttemptUpdate { error_code, error_message, error_reason, - amount_capturable: amount_capturable - .map(|capture_amt| capture_amt.get_amount_as_i64()), + amount_capturable, updated_by, unified_code, unified_message, @@ -1932,8 +2089,7 @@ impl DataModelExt for PaymentAttemptUpdate { } => DieselPaymentAttemptUpdate::CaptureUpdate { multiple_capture_count, updated_by, - amount_to_capture: amount_to_capture - .map(|capture_amt| capture_amt.get_amount_as_i64()), + amount_to_capture, }, Self::PreprocessingUpdate { status, @@ -1969,7 +2125,7 @@ impl DataModelExt for PaymentAttemptUpdate { updated_by, } => DieselPaymentAttemptUpdate::AmountToCaptureUpdate { status, - amount_capturable: amount_capturable.get_amount_as_i64(), + amount_capturable, updated_by, }, Self::ConnectorResponse { @@ -1991,8 +2147,8 @@ impl DataModelExt for PaymentAttemptUpdate { amount, amount_capturable, } => DieselPaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { - amount: amount.get_amount_as_i64(), - amount_capturable: amount_capturable.get_amount_as_i64(), + amount, + amount_capturable, }, Self::AuthenticationUpdate { status, @@ -2050,7 +2206,7 @@ impl DataModelExt for PaymentAttemptUpdate { updated_by, payment_method_billing_address_id, } => Self::Update { - amount: MinorUnit::new(amount), + amount, currency, status, authentication_type, @@ -2060,10 +2216,10 @@ impl DataModelExt for PaymentAttemptUpdate { payment_method_type, payment_experience, business_sub_label, - amount_to_capture: amount_to_capture.map(MinorUnit::new), + amount_to_capture, capture_method, - surcharge_amount: surcharge_amount.map(MinorUnit::new), - tax_amount: tax_amount.map(MinorUnit::new), + surcharge_amount, + tax_amount, fingerprint_id, payment_method_billing_address_id, updated_by, @@ -2081,9 +2237,9 @@ impl DataModelExt for PaymentAttemptUpdate { payment_token, connector, straight_through_algorithm, - amount_capturable: amount_capturable.map(MinorUnit::new), - surcharge_amount: surcharge_amount.map(MinorUnit::new), - tax_amount: tax_amount.map(MinorUnit::new), + amount_capturable, + surcharge_amount, + tax_amount, updated_by, merchant_connector_id: connector_id, }, @@ -2128,7 +2284,7 @@ impl DataModelExt for PaymentAttemptUpdate { shipping_cost, order_tax_amount, } => Self::ConfirmUpdate { - amount: MinorUnit::new(amount), + amount, currency, status, authentication_type, @@ -2144,9 +2300,9 @@ impl DataModelExt for PaymentAttemptUpdate { straight_through_algorithm, error_code, error_message, - amount_capturable: amount_capturable.map(MinorUnit::new), - surcharge_amount: surcharge_amount.map(MinorUnit::new), - tax_amount: tax_amount.map(MinorUnit::new), + amount_capturable, + surcharge_amount, + tax_amount, fingerprint_id, updated_by, merchant_connector_id: connector_id, @@ -2222,7 +2378,7 @@ impl DataModelExt for PaymentAttemptUpdate { error_message, error_reason, connector_response_reference_id, - amount_capturable: amount_capturable.map(MinorUnit::new), + amount_capturable, updated_by, authentication_data, encoded_data, @@ -2274,7 +2430,7 @@ impl DataModelExt for PaymentAttemptUpdate { error_code, error_message, error_reason, - amount_capturable: amount_capturable.map(MinorUnit::new), + amount_capturable, updated_by, unified_code, unified_message, @@ -2287,7 +2443,7 @@ impl DataModelExt for PaymentAttemptUpdate { multiple_capture_count, updated_by, } => Self::CaptureUpdate { - amount_to_capture: amount_to_capture.map(MinorUnit::new), + amount_to_capture, multiple_capture_count, updated_by, }, @@ -2325,7 +2481,7 @@ impl DataModelExt for PaymentAttemptUpdate { updated_by, } => Self::AmountToCaptureUpdate { status, - amount_capturable: MinorUnit::new(amount_capturable), + amount_capturable, updated_by, }, DieselPaymentAttemptUpdate::ConnectorResponse { @@ -2347,8 +2503,8 @@ impl DataModelExt for PaymentAttemptUpdate { amount, amount_capturable, } => Self::IncrementalAuthorizationAmountUpdate { - amount: MinorUnit::new(amount), - amount_capturable: MinorUnit::new(amount_capturable), + amount, + amount_capturable, }, DieselPaymentAttemptUpdate::AuthenticationUpdate { status,
refactor
add encryption support to payment attempt domain model (#5882)
70ba4ffe7bb9e685f3dc8afc26de241f2457e86c
2023-11-29 20:01:26
github-actions
chore(version): v1.92.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a63dcc2cae..f2966b238bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,22 @@ All notable changes to HyperSwitch will be documented here. - - - +## 1.92.0 (2023-11-29) + +### Features + +- **analytics:** Add Clickhouse based analytics ([#2988](https://github.com/juspay/hyperswitch/pull/2988)) ([`9df4e01`](https://github.com/juspay/hyperswitch/commit/9df4e0193ffeb6d1cc323bdebb7e2bdfb2a375e2)) +- **ses_email:** Add email services to hyperswitch ([#2977](https://github.com/juspay/hyperswitch/pull/2977)) ([`5f5e895`](https://github.com/juspay/hyperswitch/commit/5f5e895f638701a0e6ab3deea9101ef39033dd16)) + +### Bug Fixes + +- **router:** Make use of warning to log errors when apple pay metadata parsing fails ([#3010](https://github.com/juspay/hyperswitch/pull/3010)) ([`2e57745`](https://github.com/juspay/hyperswitch/commit/2e57745352c547323ac2df2554f6bc2dbd6da37f)) + +**Full Changelog:** [`v1.91.1...v1.92.0`](https://github.com/juspay/hyperswitch/compare/v1.91.1...v1.92.0) + +- - - + + ## 1.91.1 (2023-11-29) ### Bug Fixes
chore
v1.92.0
91f969a2908f4e7b0101a212567305888f51e236
2023-07-16 18:12:33
Swangi Kumari
feat(connector): [Mollie] Implement card 3ds (#1421)
false
diff --git a/Cargo.lock b/Cargo.lock index f93aa8d1dc8..d6310a82ea2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -297,12 +297,6 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" -[[package]] -name = "adler32" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234" - [[package]] name = "ahash" version = "0.7.6" @@ -385,14 +379,15 @@ dependencies = [ "cards", "common_enums", "common_utils", - "error-stack", + "frunk", + "frunk_core", "masking", "mime", "reqwest", "router_derive", "serde", "serde_json", - "strum 0.24.1", + "strum", "time 0.3.22", "url", "utoipa", @@ -1165,12 +1160,6 @@ version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c676a478f63e9fa2dd5368a42f28bba0d6c560b775f38583c8bbaa7fcd67c9c" -[[package]] -name = "bytemuck" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17febce684fd15d89027105661fec94afb475cb995fbc59d2865198446ba2eea" - [[package]] name = "byteorder" version = "1.4.3" @@ -1287,12 +1276,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" -[[package]] -name = "checked_int_cast" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17cc5e6b5ab06331c33589842070416baa137e8b0eb912b008cfd4a78ada7919" - [[package]] name = "chrono" version = "0.4.26" @@ -1329,7 +1312,6 @@ dependencies = [ "anstyle", "bitflags 1.3.2", "clap_lex", - "once_cell", ] [[package]] @@ -1350,23 +1332,15 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2da6da31387c7e4ef160ffab6d5e7f00c42626fe39aea70a7b0f1773f7dd6c1b" -[[package]] -name = "color_quant" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" - [[package]] name = "common_enums" version = "0.1.0" dependencies = [ - "common_utils", "diesel", "router_derive", "serde", "serde_json", - "strum 0.25.0", - "time 0.3.22", + "strum", "utoipa", ] @@ -1519,17 +1493,6 @@ dependencies = [ "crossbeam-utils", ] -[[package]] -name = "crossbeam-deque" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6fd6f855243022dcecf8702fef0c297d4338e226845fe067f6341ad9fa0cef" -dependencies = [ - "cfg-if", - "crossbeam-epoch", - "crossbeam-utils", -] - [[package]] name = "crossbeam-epoch" version = "0.9.15" @@ -1664,16 +1627,6 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaa37046cc0f6c3cc6090fbdbf73ef0b8ef4cfcc37f6befc0020f63e8cf121e1" -[[package]] -name = "deflate" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73770f8e1fe7d64df17ca66ad28994a0a623ea497fa69486e14984e715c5d174" -dependencies = [ - "adler32", - "byteorder", -] - [[package]] name = "derive_deref" version = "1.1.1" @@ -1726,27 +1679,6 @@ dependencies = [ "syn 2.0.18", ] -[[package]] -name = "diesel_models" -version = "0.1.0" -dependencies = [ - "async-bb8-diesel", - "common_enums", - "common_utils", - "diesel", - "error-stack", - "frunk", - "frunk_core", - "masking", - "router_derive", - "router_env", - "serde", - "serde_json", - "strum 0.24.1", - "thiserror", - "time 0.3.22", -] - [[package]] name = "diesel_table_macro_syntax" version = "0.1.0" @@ -1809,7 +1741,6 @@ dependencies = [ "common_utils", "config", "diesel", - "diesel_models", "error-stack", "external_services", "once_cell", @@ -1818,6 +1749,7 @@ dependencies = [ "serde", "serde_json", "serde_path_to_error", + "storage_models", "thiserror", "tokio", ] @@ -1858,9 +1790,9 @@ dependencies = [ [[package]] name = "equivalent" -version = "1.0.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" +checksum = "88bffebc5d80432c9b140ee17875ff173a8ab62faad5b257da912bd2f6c1c0a1" [[package]] name = "errno" @@ -1978,7 +1910,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b9429470923de8e8cbd4d2dc513535400b4b3fef0319fb5c4e1f520a7bef743" dependencies = [ "crc32fast", - "miniz_oxide 0.7.1", + "miniz_oxide", ] [[package]] @@ -2266,16 +2198,6 @@ dependencies = [ "wasi 0.11.0+wasi-snapshot-preview1", ] -[[package]] -name = "gif" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3edd93c6756b4dfaf2709eafcc345ba2636565295c198a9cfbf75fa5e3e00b06" -dependencies = [ - "color_quant", - "weezl", -] - [[package]] name = "git2" version = "0.17.2" @@ -2541,25 +2463,6 @@ dependencies = [ "unicode-normalization", ] -[[package]] -name = "image" -version = "0.23.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24ffcb7e7244a9bf19d35bf2883b9c080c4ced3c07a9895572178cdb8f13f6a1" -dependencies = [ - "bytemuck", - "byteorder", - "color_quant", - "gif", - "jpeg-decoder", - "num-iter", - "num-rational", - "num-traits", - "png", - "scoped_threadpool", - "tiff", -] - [[package]] name = "indexmap" version = "1.9.3" @@ -2664,15 +2567,6 @@ dependencies = [ "time 0.3.22", ] -[[package]] -name = "jpeg-decoder" -version = "0.1.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "229d53d58899083193af11e15917b5640cd40b29ff475a1fe4ef725deb02d0f2" -dependencies = [ - "rayon", -] - [[package]] name = "js-sys" version = "0.3.64" @@ -2956,25 +2850,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" -[[package]] -name = "miniz_oxide" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "791daaae1ed6889560f8c4359194f56648355540573244a5448a83ba1ecc7435" -dependencies = [ - "adler32", -] - -[[package]] -name = "miniz_oxide" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a92518e98c078586bc6c934028adcca4c92a53d6a958196de835170a01d84e4b" -dependencies = [ - "adler", - "autocfg", -] - [[package]] name = "miniz_oxide" version = "0.7.1" @@ -3089,28 +2964,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "num-iter" -version = "0.1.43" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d03e6c028c5dc5cac6e2dec0efda81fc887605bb3d884578bb6d6bf7514e252" -dependencies = [ - "autocfg", - "num-integer", - "num-traits", -] - -[[package]] -name = "num-rational" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12ac428b1cb17fce6f731001d307d351ec70a6d202fc2e60f7d4c5e42d8f4f07" -dependencies = [ - "autocfg", - "num-integer", - "num-traits", -] - [[package]] name = "num-traits" version = "0.2.15" @@ -3452,18 +3305,6 @@ version = "0.3.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" -[[package]] -name = "png" -version = "0.16.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c3287920cb847dee3de33d301c463fba14dda99db24214ddf93f83d3021f4c6" -dependencies = [ - "bitflags 1.3.2", - "crc32fast", - "deflate", - "miniz_oxide 0.3.7", -] - [[package]] name = "polling" version = "2.8.0" @@ -3598,16 +3439,6 @@ dependencies = [ "unicase", ] -[[package]] -name = "qrcode" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16d2f1455f3630c6e5107b4f2b94e74d76dea80736de0981fd27644216cff57f" -dependencies = [ - "checked_int_cast", - "image", -] - [[package]] name = "quanta" version = "0.11.1" @@ -3749,28 +3580,6 @@ dependencies = [ "bitflags 1.3.2", ] -[[package]] -name = "rayon" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d2df5196e37bcc87abebc0053e20787d73847bb33134a69841207dd0a47f03b" -dependencies = [ - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b8f95bd6966f5c87776639160a66bd8ab9895d9d4ab01ddba9fc60661aebe8d" -dependencies = [ - "crossbeam-channel", - "crossbeam-deque", - "crossbeam-utils", - "num_cpus", -] - [[package]] name = "redis-protocol" version = "4.1.0" @@ -3971,15 +3780,15 @@ dependencies = [ "crc32fast", "derive_deref", "diesel", - "diesel_models", "dyn-clone", "encoding_rs", "error-stack", "external_services", + "frunk", + "frunk_core", "futures", "hex", "http", - "image", "infer 0.13.0", "josekit", "jsonwebtoken", @@ -3992,7 +3801,6 @@ dependencies = [ "nanoid", "num_cpus", "once_cell", - "qrcode", "rand 0.8.5", "redis_interface", "regex", @@ -4009,8 +3817,8 @@ dependencies = [ "serial_test", "signal-hook", "signal-hook-tokio", - "strum 0.24.1", - "test_utils", + "storage_models", + "strum", "thirtyfour", "thiserror", "time 0.3.22", @@ -4034,7 +3842,7 @@ dependencies = [ "quote", "serde", "serde_json", - "strum 0.24.1", + "strum", "syn 1.0.109", ] @@ -4052,7 +3860,7 @@ dependencies = [ "serde", "serde_json", "serde_path_to_error", - "strum 0.24.1", + "strum", "time 0.3.22", "tokio", "tracing", @@ -4222,12 +4030,6 @@ dependencies = [ "parking_lot", ] -[[package]] -name = "scoped_threadpool" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d51f5df5af43ab3f1360b429fa5e0152ac5ce8c0bd6485cae490332e96846a8" - [[package]] name = "scopeguard" version = "1.1.0" @@ -4573,6 +4375,27 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" +[[package]] +name = "storage_models" +version = "0.1.0" +dependencies = [ + "async-bb8-diesel", + "common_enums", + "common_utils", + "diesel", + "error-stack", + "frunk", + "frunk_core", + "masking", + "router_derive", + "router_env", + "serde", + "serde_json", + "strum", + "thiserror", + "time 0.3.22", +] + [[package]] name = "stringmatch" version = "0.4.0" @@ -4594,16 +4417,7 @@ version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f" dependencies = [ - "strum_macros 0.24.3", -] - -[[package]] -name = "strum" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" -dependencies = [ - "strum_macros 0.25.1", + "strum_macros", ] [[package]] @@ -4619,19 +4433,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "strum_macros" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6069ca09d878a33f883cc06aaa9718ede171841d3832450354410b718b097232" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "rustversion", - "syn 2.0.18", -] - [[package]] name = "subtle" version = "2.4.1" @@ -4730,20 +4531,6 @@ dependencies = [ "test-case-core", ] -[[package]] -name = "test_utils" -version = "0.1.0" -dependencies = [ - "api_models", - "clap", - "masking", - "router", - "serde", - "serde_json", - "serde_path_to_error", - "toml 0.7.4", -] - [[package]] name = "thirtyfour" version = "0.31.0" @@ -4812,17 +4599,6 @@ dependencies = [ "once_cell", ] -[[package]] -name = "tiff" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a53f4706d65497df0c4349241deddf35f84cee19c87ed86ea8ca590f4464437" -dependencies = [ - "jpeg-decoder", - "miniz_oxide 0.4.4", - "weezl", -] - [[package]] name = "time" version = "0.1.45" @@ -5549,12 +5325,6 @@ dependencies = [ "webpki", ] -[[package]] -name = "weezl" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9193164d4de03a926d909d3bc7c30543cecb35400c02114792c2cae20d5e2dbb" - [[package]] name = "winapi" version = "0.3.9" diff --git a/config/config.example.toml b/config/config.example.toml index 61422f41e20..d8767517365 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -171,6 +171,7 @@ globepay.base_url = "https://pay.globepay.co/" iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1" klarna.base_url = "https://api-na.playground.klarna.com/" mollie.base_url = "https://api.mollie.com/v2/" +mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" multisafepay.base_url = "https://testapi.multisafepay.com/" nexinets.base_url = "https://apitest.payengine.de/v1" nmi.base_url = "https://secure.nmi.com/" @@ -278,6 +279,12 @@ from_email = "[email protected]" # Sender email aws_region = "" # AWS region used by AWS SES base_url = "" # Base url used when adding links that should redirect to self +#tokenization configuration which describe token lifetime and payment method for specific connector +[tokenization] +stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } } +checkout = { long_lived_token = false, payment_method = "wallet" } +mollie = {long_lived_token = false, payment_method = "card"} + [dummy_connector] payment_ttl = 172800 # Time to live for dummy connector payment in redis payment_duration = 1000 # Fake delay duration for dummy connector payment diff --git a/config/development.toml b/config/development.toml index 24a5540ba52..4db925ae82f 100644 --- a/config/development.toml +++ b/config/development.toml @@ -132,6 +132,7 @@ globepay.base_url = "https://pay.globepay.co/" iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1" klarna.base_url = "https://api-na.playground.klarna.com/" mollie.base_url = "https://api.mollie.com/v2/" +mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" multisafepay.base_url = "https://testapi.multisafepay.com/" nexinets.base_url = "https://apitest.payengine.de/v1" nmi.base_url = "https://secure.nmi.com/" @@ -290,6 +291,7 @@ debit = { currency = "USD" } [tokenization] stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } } checkout = { long_lived_token = false, payment_method = "wallet" } +mollie = {long_lived_token = false, payment_method = "card"} [connector_customer] connector_list = "bluesnap,stripe" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 583e534d003..e6de703794e 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -93,6 +93,7 @@ globepay.base_url = "https://pay.globepay.co/" iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1" klarna.base_url = "https://api-na.playground.klarna.com/" mollie.base_url = "https://api.mollie.com/v2/" +mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" multisafepay.base_url = "https://testapi.multisafepay.com/" nexinets.base_url = "https://apitest.payengine.de/v1" nmi.base_url = "https://secure.nmi.com/" @@ -173,6 +174,12 @@ stream = "SCHEDULER_STREAM" disabled = false consumer_group = "SCHEDULER_GROUP" +#tokenization configuration which describe token lifetime and payment method for specific connector +[tokenization] +stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } } +checkout = { long_lived_token = false, payment_method = "wallet" } +mollie = {long_lived_token = false, payment_method = "card"} + [dummy_connector] payment_ttl = 172800 payment_duration = 1000 diff --git a/crates/router/src/connector/mollie.rs b/crates/router/src/connector/mollie.rs index 9b75ac8702e..39be74a0c3c 100644 --- a/crates/router/src/connector/mollie.rs +++ b/crates/router/src/connector/mollie.rs @@ -3,6 +3,7 @@ mod transformers; use std::fmt::Debug; use error_stack::{IntoReport, ResultExt}; +use masking::ExposeInterface; use transformers as mollie; use crate::{ @@ -74,7 +75,7 @@ impl ConnectorCommon for Mollie { .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), - format!("Bearer {}", auth.api_key).into_masked(), + format!("Bearer {}", auth.api_key.expose()).into_masked(), )]) } @@ -114,7 +115,84 @@ impl types::PaymentsResponseData, > for Mollie { - // Not Implemented (R) + fn get_headers( + &self, + req: &types::TokenizationRouterData, + 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::TokenizationRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let base_url = connectors + .mollie + .secondary_base_url + .as_ref() + .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?; + Ok(format!("{base_url}card-tokens")) + } + + fn get_request_body( + &self, + req: &types::TokenizationRouterData, + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_req = mollie::MollieCardTokenRequest::try_from(req)?; + let mollie_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<mollie::MollieCardTokenRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(mollie_req)) + } + fn build_request( + &self, + req: &types::TokenizationRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::TokenizationType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::TokenizationType::get_headers(self, req, connectors)?) + .body(types::TokenizationType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::TokenizationRouterData, + res: Response, + ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError> + where + types::PaymentsResponseData: Clone, + { + let response: mollie::MollieCardTokenResponse = res + .response + .parse_struct("MollieTokenResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } } impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData> diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs index 8213b2729d0..a8ff89250c5 100644 --- a/crates/router/src/connector/mollie/transformers.rs +++ b/crates/router/src/connector/mollie/transformers.rs @@ -1,15 +1,20 @@ use api_models::payments; +use cards::CardNumber; use common_utils::pii::Email; use diesel_models::enums; use error_stack::IntoReport; -use masking::Secret; +use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; use crate::{ - connector::utils::{self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData}, + connector::utils::{ + self, AddressDetailsData, BrowserInformationData, CardData, PaymentsAuthorizeRequestData, + RouterData, + }, core::errors, services, types, + types::storage::enums as storage_enums, }; type Error = error_stack::Report<errors::ConnectorError>; @@ -28,7 +33,6 @@ pub struct MolliePaymentsRequest { metadata: Option<serde_json::Value>, sequence_type: SequenceType, mandate_id: Option<String>, - card_token: Option<String>, } #[derive(Default, Debug, Serialize, Deserialize)] @@ -49,6 +53,7 @@ pub enum PaymentMethodData { Sofort, Przelewy24(Box<Przelewy24MethodData>), Bancontact, + CreditCard(Box<CreditCardMethodData>), DirectDebit(Box<DirectDebitMethodData>), } @@ -84,6 +89,14 @@ pub struct DirectDebitMethodData { consumer_account: Secret<String>, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CreditCardMethodData { + billing_address: Option<Address>, + shipping_address: Option<Address>, + card_token: Option<Secret<String>>, +} + #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum SequenceType { @@ -103,6 +116,10 @@ pub struct Address { pub country: api_models::enums::CountryAlpha2, } +pub struct MollieBrowserInfo { + language: String, +} + impl TryFrom<&types::PaymentsAuthorizeRouterData> for MolliePaymentsRequest { type Error = Error; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { @@ -113,7 +130,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MolliePaymentsRequest { let description = item.get_description()?; let redirect_url = item.request.get_return_url()?; let payment_method_data = match item.request.capture_method.unwrap_or_default() { - enums::CaptureMethod::Automatic => match item.request.payment_method_data { + enums::CaptureMethod::Automatic => match &item.request.payment_method_data { + api_models::payments::PaymentMethodData::Card(_) => Ok( + PaymentMethodData::CreditCard(Box::new(CreditCardMethodData { + billing_address: get_billing_details(item)?, + shipping_address: get_shipping_details(item)?, + card_token: Some(Secret::new(item.get_payment_method_token()?)), + })), + ), api_models::payments::PaymentMethodData::BankRedirect(ref redirect_data) => { PaymentMethodData::try_from(redirect_data) } @@ -150,7 +174,6 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MolliePaymentsRequest { metadata: None, sequence_type: SequenceType::Oneoff, mandate_id: None, - card_token: None, }) } } @@ -196,6 +219,58 @@ impl TryFrom<&api_models::payments::BankDebitData> for PaymentMethodData { } } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MollieCardTokenRequest { + card_holder: Secret<String>, + card_number: CardNumber, + card_cvv: Secret<String>, + card_expiry_date: Secret<String>, + locale: String, + testmode: bool, + profile_token: Secret<String>, +} + +impl TryFrom<&types::TokenizationRouterData> for MollieCardTokenRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> { + match item.request.payment_method_data.clone() { + api_models::payments::PaymentMethodData::Card(ccard) => { + let auth = MollieAuthType::try_from(&item.connector_auth_type)?; + let card_holder = ccard.card_holder_name.clone(); + let card_number = ccard.card_number.clone(); + let card_expiry_date = + ccard.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned()); + let card_cvv = ccard.card_cvc; + let browser_info = get_browser_info(item)?; + let locale = browser_info + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "browser_info.language", + })? + .language; + let testmode = + item.test_mode + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "test_mode", + })?; + let profile_token = auth.key1; + Ok(Self { + card_holder, + card_number, + card_cvv, + card_expiry_date, + locale, + testmode, + profile_token, + }) + } + _ => Err(errors::ConnectorError::NotImplemented( + "Payment Method".to_string(), + ))?, + } + } +} + fn get_payment_method_for_wallet( item: &types::PaymentsAuthorizeRouterData, wallet_data: &api_models::payments::WalletData, @@ -264,6 +339,24 @@ fn get_address_details( Ok(address_details) } +fn get_browser_info( + item: &types::TokenizationRouterData, +) -> Result<Option<MollieBrowserInfo>, error_stack::Report<errors::ConnectorError>> { + if matches!(item.auth_type, enums::AuthenticationType::ThreeDs) { + item.request + .browser_info + .as_ref() + .map(|info| { + Ok(MollieBrowserInfo { + language: info.get_language()?, + }) + }) + .transpose() + } else { + Ok(None) + } +} + #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct MolliePaymentsResponse { @@ -340,15 +433,17 @@ pub struct BankDetails { } pub struct MollieAuthType { - pub(super) api_key: String, + pub(super) api_key: Secret<String>, + pub(super) key1: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for MollieAuthType { type Error = Error; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { - if let types::ConnectorAuthType::HeaderKey { api_key } = auth_type { + if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { Ok(Self { - api_key: api_key.to_string(), + api_key: Secret::new(api_key.to_owned()), + key1: Secret::new(key1.to_owned()), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) @@ -356,6 +451,31 @@ impl TryFrom<&types::ConnectorAuthType> for MollieAuthType { } } +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MollieCardTokenResponse { + card_token: Secret<String>, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, MollieCardTokenResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, MollieCardTokenResponse, T, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: storage_enums::AttemptStatus::Pending, + payment_method_token: Some(item.response.card_token.clone().expose()), + response: Ok(types::PaymentsResponseData::TokenizationResponse { + token: item.response.card_token.expose(), + }), + ..item.data + }) + } +} + impl<F, T> TryFrom<types::ResponseRouterData<F, MolliePaymentsResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 60935670e53..c556271a603 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -333,6 +333,7 @@ impl TryFrom<types::PaymentsAuthorizeData> for types::PaymentMethodTokenizationD fn try_from(data: types::PaymentsAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: data.payment_method_data, + browser_info: data.browser_info, }) } } diff --git a/crates/router/src/core/payments/flows/verify_flow.rs b/crates/router/src/core/payments/flows/verify_flow.rs index 5b4bb30a667..275df0792de 100644 --- a/crates/router/src/core/payments/flows/verify_flow.rs +++ b/crates/router/src/core/payments/flows/verify_flow.rs @@ -233,6 +233,7 @@ impl TryFrom<types::VerifyRequestData> for types::PaymentMethodTokenizationData fn try_from(data: types::VerifyRequestData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: data.payment_method_data, + browser_info: None, }) } } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index b74c8e35b04..ba3d0432b58 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2059,6 +2059,13 @@ impl MerchantConnectorAccountType { Self::CacheVal(_) => false, } } + + pub fn is_test_mode_on(&self) -> Option<bool> { + match self { + Self::DbVal(val) => val.test_mode, + Self::CacheVal(_) => None, + } + } } pub async fn get_merchant_connector_account( @@ -2154,6 +2161,7 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>( connector_customer: router_data.connector_customer, preprocessing_id: router_data.preprocessing_id, connector_request_reference_id: router_data.connector_request_reference_id, + test_mode: router_data.test_mode, } } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 407b6353645..4387fad2191 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -62,6 +62,8 @@ where Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) })?; + let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); + let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") @@ -130,6 +132,7 @@ where &payment_data.payment_attempt, ), preprocessing_id: payment_data.payment_attempt.preprocessing_step_id, + test_mode, }; Ok(router_data) diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 72706daad32..30179bdcb37 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -72,6 +72,7 @@ pub async fn construct_refund_router_data<'a, F>( &merchant_account.merchant_id, &connector_id.to_string(), )); + let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let router_data = types::RouterData { flow: PhantomData, @@ -118,6 +119,7 @@ pub async fn construct_refund_router_data<'a, F>( &merchant_account.merchant_id, payment_attempt, ), + test_mode, }; Ok(router_data) @@ -270,6 +272,7 @@ pub async fn construct_accept_dispute_router_data<'a>( key_store, ) .await?; + let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") @@ -310,6 +313,7 @@ pub async fn construct_accept_dispute_router_data<'a>( &merchant_account.merchant_id, payment_attempt, ), + test_mode, }; Ok(router_data) } @@ -339,6 +343,7 @@ pub async fn construct_submit_evidence_router_data<'a>( key_store, ) .await?; + let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") @@ -376,6 +381,7 @@ pub async fn construct_submit_evidence_router_data<'a>( &merchant_account.merchant_id, payment_attempt, ), + test_mode, }; Ok(router_data) } @@ -401,6 +407,7 @@ pub async fn construct_upload_file_router_data<'a>( key_store, ) .await?; + let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") @@ -443,6 +450,7 @@ pub async fn construct_upload_file_router_data<'a>( &merchant_account.merchant_id, payment_attempt, ), + test_mode, }; Ok(router_data) } @@ -472,6 +480,7 @@ pub async fn construct_defend_dispute_router_data<'a>( key_store, ) .await?; + let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") @@ -512,6 +521,7 @@ pub async fn construct_defend_dispute_router_data<'a>( &merchant_account.merchant_id, payment_attempt, ), + test_mode, }; Ok(router_data) } @@ -538,6 +548,7 @@ pub async fn construct_retrieve_file_router_data<'a>( key_store, ) .await?; + let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") @@ -576,6 +587,7 @@ pub async fn construct_retrieve_file_router_data<'a>( preprocessing_id: None, connector_request_reference_id: IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW .to_string(), + test_mode, }; Ok(router_data) } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index c4c29c95d1f..d75e72b40e3 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -207,6 +207,7 @@ pub struct RouterData<Flow, Request, Response> { /// Contains a reference ID that should be sent in the connector request pub connector_request_reference_id: String, + pub test_mode: Option<bool>, } #[derive(Debug, Clone)] @@ -267,6 +268,7 @@ pub struct ConnectorCustomerData { #[derive(Debug, Clone)] pub struct PaymentMethodTokenizationData { pub payment_method_data: payments::PaymentMethodData, + pub browser_info: Option<BrowserInformation>, } #[derive(Debug, Clone)] @@ -819,6 +821,7 @@ impl<F1, F2, T1, T2> From<(&RouterData<F1, T1, PaymentsResponseData>, T2)> preprocessing_id: None, connector_customer: data.connector_customer.clone(), connector_request_reference_id: data.connector_request_reference_id.clone(), + test_mode: data.test_mode, } } } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 17a3068f6ff..ea081a39e4c 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -81,6 +81,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { connector_customer: None, preprocessing_id: None, connector_request_reference_id: uuid::Uuid::new_v4().to_string(), + test_mode: None, } } @@ -126,6 +127,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { connector_customer: None, preprocessing_id: None, connector_request_reference_id: uuid::Uuid::new_v4().to_string(), + test_mode: None, } } diff --git a/crates/router/tests/connectors/mollie_ui.rs b/crates/router/tests/connectors/mollie_ui.rs index 15855b86810..0066a7b6e0e 100644 --- a/crates/router/tests/connectors/mollie_ui.rs +++ b/crates/router/tests/connectors/mollie_ui.rs @@ -11,10 +11,10 @@ impl SeleniumTest for MollieSeleniumTest { } } -async fn should_make_mollie_paypal_payment(c: WebDriver) -> Result<(), WebDriverError> { +async fn should_make_mollie_paypal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> { let conn = MollieSeleniumTest {}; conn.make_redirection_payment( - c, + web_driver, vec![ Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/32"))), Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), @@ -34,10 +34,10 @@ async fn should_make_mollie_paypal_payment(c: WebDriver) -> Result<(), WebDriver Ok(()) } -async fn should_make_mollie_sofort_payment(c: WebDriver) -> Result<(), WebDriverError> { +async fn should_make_mollie_sofort_payment(web_driver: WebDriver) -> Result<(), WebDriverError> { let conn = MollieSeleniumTest {}; conn.make_redirection_payment( - c, + web_driver, vec![ Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/29"))), Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), @@ -57,10 +57,10 @@ async fn should_make_mollie_sofort_payment(c: WebDriver) -> Result<(), WebDriver Ok(()) } -async fn should_make_mollie_ideal_payment(c: WebDriver) -> Result<(), WebDriverError> { +async fn should_make_mollie_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> { let conn: MollieSeleniumTest = MollieSeleniumTest {}; conn.make_redirection_payment( - c, + web_driver, vec![ Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/36"))), Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), @@ -84,10 +84,10 @@ async fn should_make_mollie_ideal_payment(c: WebDriver) -> Result<(), WebDriverE Ok(()) } -async fn should_make_mollie_eps_payment(c: WebDriver) -> Result<(), WebDriverError> { +async fn should_make_mollie_eps_payment(web_driver: WebDriver) -> Result<(), WebDriverError> { let conn = MollieSeleniumTest {}; conn.make_redirection_payment( - c, + web_driver, vec![ Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/38"))), Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), @@ -107,10 +107,10 @@ async fn should_make_mollie_eps_payment(c: WebDriver) -> Result<(), WebDriverErr Ok(()) } -async fn should_make_mollie_giropay_payment(c: WebDriver) -> Result<(), WebDriverError> { +async fn should_make_mollie_giropay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> { let conn = MollieSeleniumTest {}; conn.make_redirection_payment( - c, + web_driver, vec![ Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/41"))), Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), @@ -176,6 +176,25 @@ async fn should_make_mollie_przelewy24_payment(c: WebDriver) -> Result<(), WebDr Ok(()) } +async fn should_make_mollie_3ds_payment(web_driver: WebDriver) -> Result<(), WebDriverError> { + let conn = MollieSeleniumTest {}; + conn.make_redirection_payment( + web_driver, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/148"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Assert(Assert::IsPresent("Test profile")), + Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))), + Event::Trigger(Trigger::Click(By::Css( + "button[class='button form__button']", + ))), + Event::Assert(Assert::IsPresent("succeeded")), + ], + ) + .await?; + Ok(()) +} + #[test] #[serial] fn should_make_mollie_paypal_payment_test() { @@ -217,3 +236,9 @@ fn should_make_mollie_bancontact_card_payment_test() { fn should_make_mollie_przelewy24_payment_test() { tester!(should_make_mollie_przelewy24_payment); } + +#[test] +#[serial] +fn should_make_mollie_3ds_payment_test() { + tester!(should_make_mollie_3ds_payment); +} diff --git a/crates/router/tests/connectors/selenium.rs b/crates/router/tests/connectors/selenium.rs index f4408a67364..a77937abbc3 100644 --- a/crates/router/tests/connectors/selenium.rs +++ b/crates/router/tests/connectors/selenium.rs @@ -623,7 +623,7 @@ pub fn make_capabilities(browser: &str) -> Capabilities { "firefox" => { let mut caps = DesiredCapabilities::firefox(); let ignore_profile = env::var("IGNORE_BROWSER_PROFILE").ok(); - if ignore_profile.is_none() { + if ignore_profile.is_none() || ignore_profile.unwrap() == "false" { let profile_path = &format!("-profile={}", get_firefox_profile_path().unwrap()); caps.add_firefox_arg(profile_path).unwrap(); } else { diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 43b43e4ee48..971c857c383 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -404,6 +404,7 @@ pub trait ConnectorActions: Connector { connector_customer: None, preprocessing_id: None, connector_request_reference_id: uuid::Uuid::new_v4().to_string(), + test_mode: None, } } diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 17cd85e8d58..eab77e3790d 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -27,7 +27,7 @@ pub struct ConnectorAuthentication { pub globalpay: Option<BodyKey>, pub globepay: Option<BodyKey>, pub iatapay: Option<SignatureKey>, - pub mollie: Option<HeaderKey>, + pub mollie: Option<BodyKey>, pub multisafepay: Option<HeaderKey>, pub nexinets: Option<BodyKey>, pub noon: Option<SignatureKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 20daa5b813a..801c992fe11 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -80,6 +80,7 @@ globepay.base_url = "https://pay.globepay.co/" iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1" klarna.base_url = "https://api-na.playground.klarna.com/" mollie.base_url = "https://api.mollie.com/v2/" +mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" multisafepay.base_url = "https://testapi.multisafepay.com/" nexinets.base_url = "https://apitest.payengine.de/v1" nmi.base_url = "https://secure.nmi.com/" @@ -148,6 +149,12 @@ cards = [ "zen", ] +#tokenization configuration which describe token lifetime and payment method for specific connector +[tokenization] +stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } } +checkout = { long_lived_token = false, payment_method = "wallet" } +mollie = {long_lived_token = false, payment_method = "card"} + [dummy_connector] payment_ttl = 172800 payment_duration = 1000
feat
[Mollie] Implement card 3ds (#1421)
b9c29e7fd3bdc5e582a2dddbb98f3d2dbda72dd6
2024-02-09 17:28:17
Mani Chandra
feat(users): Add transfer org ownership API (#3603)
false
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs index 3ec30d6bd97..2b8d0221497 100644 --- a/crates/api_models/src/events/user_role.rs +++ b/crates/api_models/src/events/user_role.rs @@ -2,7 +2,7 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::user_role::{ AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest, GetRoleRequest, - ListRolesResponse, RoleInfoResponse, UpdateUserRoleRequest, + ListRolesResponse, RoleInfoResponse, TransferOrgOwnershipRequest, UpdateUserRoleRequest, }; common_utils::impl_misc_api_event_type!( @@ -12,5 +12,6 @@ common_utils::impl_misc_api_event_type!( AuthorizationInfoResponse, UpdateUserRoleRequest, AcceptInvitationRequest, - DeleteUserRoleRequest + DeleteUserRoleRequest, + TransferOrgOwnershipRequest ); diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index 2672293390e..78df1d6823e 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -108,3 +108,8 @@ pub type AcceptInvitationResponse = DashboardEntryResponse; pub struct DeleteUserRoleRequest { pub email: pii::Email, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct TransferOrgOwnershipRequest { + pub email: pii::Email, +} diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs index e67eba64c7c..5e759cf826b 100644 --- a/crates/diesel_models/src/query/user_role.rs +++ b/crates/diesel_models/src/query/user_role.rs @@ -54,6 +54,20 @@ impl UserRole { .await } + pub async fn update_by_user_id_org_id( + conn: &PgPooledConn, + user_id: String, + org_id: String, + update: UserRoleUpdate, + ) -> StorageResult<Vec<Self>> { + generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( + conn, + dsl::user_id.eq(user_id).and(dsl::org_id.eq(org_id)), + UserRoleUpdateInternal::from(update), + ) + .await + } + pub async fn delete_by_user_id_merchant_id( conn: &PgPooledConn, user_id: String, diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index b48b39eea14..14be9bb6991 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -1,10 +1,11 @@ -use api_models::user_role as user_role_api; +use api_models::{user as user_api, user_role as user_role_api}; use diesel_models::{enums::UserStatus, user_role::UserRoleUpdate}; use error_stack::ResultExt; use masking::ExposeInterface; use router_env::logger; use crate::{ + consts, core::errors::{StorageErrorExt, UserErrors, UserResponse}, routes::AppState, services::{ @@ -135,6 +136,55 @@ pub async fn update_user_role( Ok(ApplicationResponse::StatusOk) } +pub async fn transfer_org_ownership( + state: AppState, + user_from_token: auth::UserFromToken, + req: user_role_api::TransferOrgOwnershipRequest, +) -> UserResponse<user_api::DashboardEntryResponse> { + if user_from_token.role_id != consts::user_role::ROLE_ID_ORGANIZATION_ADMIN { + return Err(UserErrors::InvalidRoleOperation.into()).attach_printable(format!( + "role_id = {} is not org_admin", + user_from_token.role_id + )); + } + + let user_to_be_updated = + utils::user::get_user_from_db_by_email(&state, domain::UserEmail::try_from(req.email)?) + .await + .to_not_found_response(UserErrors::InvalidRoleOperation) + .attach_printable("User not found in our records".to_string())?; + + if user_from_token.user_id == user_to_be_updated.get_user_id() { + return Err(UserErrors::InvalidRoleOperation.into()) + .attach_printable("User transferring ownership to themselves".to_string()); + } + + state + .store + .transfer_org_ownership_between_users( + &user_from_token.user_id, + user_to_be_updated.get_user_id(), + &user_from_token.org_id, + ) + .await + .change_context(UserErrors::InternalServerError)?; + + auth::blacklist::insert_user_in_blacklist(&state, user_to_be_updated.get_user_id()).await?; + auth::blacklist::insert_user_in_blacklist(&state, &user_from_token.user_id).await?; + + let user_from_db = domain::UserFromStorage::from(user_from_token.get_user(&state).await?); + let user_role = user_from_db + .get_role_from_db_by_merchant_id(&state, &user_from_token.merchant_id) + .await + .to_not_found_response(UserErrors::InvalidRoleOperation)?; + + let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + + Ok(ApplicationResponse::Json( + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, + )) +} + pub async fn accept_invitation( state: AppState, user_token: auth::UserWithoutMerchantFromToken, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 029b1a57764..a5e5f216a8b 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1965,6 +1965,17 @@ impl UserRoleInterface for KafkaStore { .await } + async fn update_user_roles_by_user_id_org_id( + &self, + user_id: &str, + org_id: &str, + update: user_storage::UserRoleUpdate, + ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> { + self.diesel_store + .update_user_roles_by_user_id_org_id(user_id, org_id, update) + .await + } + async fn delete_user_role_by_user_id_merchant_id( &self, user_id: &str, @@ -1981,6 +1992,17 @@ impl UserRoleInterface for KafkaStore { ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> { self.diesel_store.list_user_roles_by_user_id(user_id).await } + + async fn transfer_org_ownership_between_users( + &self, + from_user_id: &str, + to_user_id: &str, + org_id: &str, + ) -> CustomResult<(), errors::StorageError> { + self.diesel_store + .transfer_org_ownership_between_users(from_user_id, to_user_id, org_id) + .await + } } #[async_trait::async_trait] diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index f02e6d60b3b..12816fa006b 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -1,9 +1,12 @@ -use diesel_models::user_role as storage; +use std::{collections::HashSet, ops::Not}; + +use async_bb8_diesel::AsyncConnection; +use diesel_models::{enums, user_role as storage}; use error_stack::{IntoReport, ResultExt}; use super::MockDb; use crate::{ - connection, + connection, consts, core::errors::{self, CustomResult}, services::Store, }; @@ -32,6 +35,14 @@ pub trait UserRoleInterface { merchant_id: &str, update: storage::UserRoleUpdate, ) -> CustomResult<storage::UserRole, errors::StorageError>; + + async fn update_user_roles_by_user_id_org_id( + &self, + user_id: &str, + org_id: &str, + update: storage::UserRoleUpdate, + ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; + async fn delete_user_role_by_user_id_merchant_id( &self, user_id: &str, @@ -42,6 +53,13 @@ pub trait UserRoleInterface { &self, user_id: &str, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; + + async fn transfer_org_ownership_between_users( + &self, + from_user_id: &str, + to_user_id: &str, + org_id: &str, + ) -> CustomResult<(), errors::StorageError>; } #[async_trait::async_trait] @@ -103,6 +121,24 @@ impl UserRoleInterface for Store { .into_report() } + async fn update_user_roles_by_user_id_org_id( + &self, + user_id: &str, + org_id: &str, + update: storage::UserRoleUpdate, + ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::UserRole::update_by_user_id_org_id( + &conn, + user_id.to_owned(), + org_id.to_owned(), + update, + ) + .await + .map_err(Into::into) + .into_report() + } + async fn delete_user_role_by_user_id_merchant_id( &self, user_id: &str, @@ -129,6 +165,86 @@ impl UserRoleInterface for Store { .map_err(Into::into) .into_report() } + + async fn transfer_org_ownership_between_users( + &self, + from_user_id: &str, + to_user_id: &str, + org_id: &str, + ) -> CustomResult<(), errors::StorageError> { + let conn = connection::pg_connection_write(self) + .await + .change_context(errors::StorageError::DatabaseConnectionError)?; + + conn.transaction_async(|conn| async move { + let old_org_admin_user_roles = storage::UserRole::update_by_user_id_org_id( + &conn, + from_user_id.to_owned(), + org_id.to_owned(), + storage::UserRoleUpdate::UpdateRole { + role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(), + modified_by: from_user_id.to_owned(), + }, + ) + .await + .map_err(|e| *e.current_context())?; + + let new_org_admin_user_roles = storage::UserRole::update_by_user_id_org_id( + &conn, + to_user_id.to_owned(), + org_id.to_owned(), + storage::UserRoleUpdate::UpdateRole { + role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), + modified_by: from_user_id.to_owned(), + }, + ) + .await + .map_err(|e| *e.current_context())?; + + let new_org_admin_merchant_ids = new_org_admin_user_roles + .iter() + .map(|user_role| user_role.merchant_id.to_owned()) + .collect::<HashSet<String>>(); + + let now = common_utils::date_time::now(); + + let missing_new_user_roles = + old_org_admin_user_roles.into_iter().filter_map(|old_role| { + new_org_admin_merchant_ids + .contains(&old_role.merchant_id) + .not() + .then_some({ + storage::UserRoleNew { + user_id: to_user_id.to_string(), + merchant_id: old_role.merchant_id, + role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), + org_id: org_id.to_string(), + status: enums::UserStatus::Active, + created_by: from_user_id.to_string(), + last_modified_by: from_user_id.to_string(), + created_at: now, + last_modified: now, + } + }) + }); + + futures::future::try_join_all(missing_new_user_roles.map(|user_role| async { + user_role + .insert(&conn) + .await + .map_err(|e| *e.current_context()) + })) + .await?; + + Ok::<_, errors::DatabaseError>(()) + }) + .await + .into_report() + .map_err(Into::into) + .into_report()?; + + Ok(()) + } } #[async_trait::async_trait] @@ -241,6 +357,107 @@ impl UserRoleInterface for MockDb { ) } + async fn update_user_roles_by_user_id_org_id( + &self, + user_id: &str, + org_id: &str, + update: storage::UserRoleUpdate, + ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { + let mut user_roles = self.user_roles.lock().await; + let mut updated_user_roles = Vec::new(); + for user_role in user_roles.iter_mut() { + if user_role.user_id == user_id && user_role.org_id == org_id { + match &update { + storage::UserRoleUpdate::UpdateRole { + role_id, + modified_by, + } => { + user_role.role_id = role_id.to_string(); + user_role.last_modified_by = modified_by.to_string(); + } + storage::UserRoleUpdate::UpdateStatus { + status, + modified_by, + } => { + user_role.status = status.to_owned(); + user_role.last_modified_by = modified_by.to_owned(); + } + } + updated_user_roles.push(user_role.to_owned()); + } + } + if updated_user_roles.is_empty() { + Err(errors::StorageError::ValueNotFound(format!( + "No user role available for user_id = {user_id} and org_id = {org_id}" + )) + .into()) + } else { + Ok(updated_user_roles) + } + } + + async fn transfer_org_ownership_between_users( + &self, + from_user_id: &str, + to_user_id: &str, + org_id: &str, + ) -> CustomResult<(), errors::StorageError> { + let old_org_admin_user_roles = self + .update_user_roles_by_user_id_org_id( + from_user_id, + org_id, + storage::UserRoleUpdate::UpdateRole { + role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(), + modified_by: from_user_id.to_string(), + }, + ) + .await?; + + let new_org_admin_user_roles = self + .update_user_roles_by_user_id_org_id( + to_user_id, + org_id, + storage::UserRoleUpdate::UpdateRole { + role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), + modified_by: from_user_id.to_string(), + }, + ) + .await?; + + let new_org_admin_merchant_ids = new_org_admin_user_roles + .iter() + .map(|user_role| user_role.merchant_id.to_owned()) + .collect::<HashSet<String>>(); + + let now = common_utils::date_time::now(); + + let missing_new_user_roles = old_org_admin_user_roles + .into_iter() + .filter_map(|old_roles| { + if !new_org_admin_merchant_ids.contains(&old_roles.merchant_id) { + Some(storage::UserRoleNew { + user_id: to_user_id.to_string(), + merchant_id: old_roles.merchant_id, + role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(), + org_id: org_id.to_string(), + status: enums::UserStatus::Active, + created_by: from_user_id.to_string(), + last_modified_by: from_user_id.to_string(), + created_at: now, + last_modified: now, + }) + } else { + None + } + }); + + for user_role in missing_new_user_roles { + self.insert_user_role(user_role).await?; + } + + Ok(()) + } + async fn delete_user_role_by_user_id_merchant_id( &self, user_id: &str, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 651d3c0026f..65caa2b5c04 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1026,6 +1026,10 @@ impl User { ) .service(web::resource("/invite/accept").route(web::post().to(accept_invitation))) .service(web::resource("/update_role").route(web::post().to(update_user_role))) + .service( + web::resource("/transfer_ownership") + .route(web::post().to(transfer_org_ownership)), + ) .service(web::resource("/delete").route(web::delete().to(delete_user_role))), ); diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 1636ed3a764..02a45408baf 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -196,7 +196,8 @@ impl From<Flow> for ApiIdentifier { | Flow::UpdateUserRole | Flow::GetAuthorizationInfo | Flow::AcceptInvitation - | Flow::DeleteUserRole => Self::UserRole, + | Flow::DeleteUserRole + | Flow::TransferOrgOwnership => Self::UserRole, Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => { Self::ConnectorOnboarding diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index ec05db1d615..f84c158332b 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -97,6 +97,25 @@ pub async fn update_user_role( .await } +pub async fn transfer_org_ownership( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_role_api::TransferOrgOwnershipRequest>, +) -> HttpResponse { + let flow = Flow::TransferOrgOwnership; + let payload = json_payload.into_inner(); + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + payload, + user_role_core::transfer_org_ownership, + &auth::JWTAuth(Permission::UsersWrite), + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn accept_invitation( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 4344acf89ff..2f4d48bea74 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -311,6 +311,8 @@ pub enum Flow { GetRoleFromToken, /// Update user role UpdateUserRole, + /// Transfer organization ownership + TransferOrgOwnership, /// Create merchant account for user in a org UserMerchantAccountCreate, /// Generate Sample Data
feat
Add transfer org ownership API (#3603)
be346e5d963925ecbe1bbb77aa024f7eed66019e
2024-09-11 12:57:22
GORAKHNATH YADAV
docs: Correction for JPY in API Ref (#5853)
false
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 31aa84e64a1..8e4112e80a1 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -12213,7 +12213,7 @@ "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 ¥100 since ¥ is a zero-decimal currency", + "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 @@ -12577,7 +12577,7 @@ "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 ¥100 since ¥ is a zero-decimal currency", + "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)", "minimum": 0 }, "currency": { @@ -13555,7 +13555,7 @@ "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 ¥100 since ¥ is a zero-decimal currency", + "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 @@ -14665,7 +14665,7 @@ "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 ¥100 since ¥ is a zero-decimal currency", + "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 diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 689b39cb4c2..1facbee5954 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -16211,7 +16211,7 @@ "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 ¥100 since ¥ is a zero-decimal currency", + "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 @@ -16575,7 +16575,7 @@ "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 ¥100 since ¥ is a zero-decimal currency", + "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)", "minimum": 0 }, "currency": { @@ -17573,7 +17573,7 @@ "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 ¥100 since ¥ is a zero-decimal currency", + "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 @@ -18683,7 +18683,7 @@ "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 ¥100 since ¥ is a zero-decimal currency", + "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 diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index be7b6ae456a..9514f6185ff 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -278,7 +278,7 @@ pub struct CustomerDetailsResponse { #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { - /// 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 ¥100 since ¥ is a zero-decimal currency + /// 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")] #[mandatory_in(PaymentsCreateRequest = u64)]
docs
Correction for JPY in API Ref (#5853)
289b20a82e5ee32aae6eb4e5766f9c757d26345d
2024-03-06 13:49:54
Kashif
fix(tests/postman/adyen): remove enabled payment methods for payouts processor (#3913)
false
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payout Connector - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payout Connector - Create/request.json index 4d3b41b7c0a..e4b52afd7ca 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payout Connector - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payout Connector - Create/request.json @@ -46,240 +46,13 @@ "key1": "{{connector_key1}}", "api_secret": "{{connector_api_secret}}" }, - "test_mode": false, + "test_mode": true, "disabled": false, "business_country": "GB", "business_label": "payouts", - "payment_methods_enabled": [ - { - "payment_method": "card", - "payment_method_types": [ - { - "payment_method_type": "credit", - "card_networks": ["Visa", "Mastercard"], - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "debit", - "card_networks": ["Visa", "Mastercard"], - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - } - ] - }, - { - "payment_method": "pay_later", - "payment_method_types": [ - { - "payment_method_type": "klarna", - "payment_experience": "redirect_to_url", - "card_networks": null, - "accepted_currencies": null, - "accepted_countries": null, - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "affirm", - "payment_experience": "redirect_to_url", - "card_networks": null, - "accepted_currencies": null, - "accepted_countries": null, - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "afterpay_clearpay", - "payment_experience": "redirect_to_url", - "card_networks": null, - "accepted_currencies": null, - "accepted_countries": null, - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "pay_bright", - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "walley", - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - } - ] - }, - { - "payment_method": "wallet", - "payment_method_types": [ - { - "payment_method_type": "paypal", - "payment_experience": "redirect_to_url", - "card_networks": null, - "accepted_currencies": null, - "accepted_countries": null, - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "google_pay", - "payment_experience": "invoke_sdk_client", - "card_networks": null, - "accepted_currencies": null, - "accepted_countries": null, - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "apple_pay", - "payment_experience": "invoke_sdk_client", - "card_networks": null, - "accepted_currencies": null, - "accepted_countries": null, - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "mobile_pay", - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "ali_pay", - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "we_chat_pay", - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "mb_way", - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - } - ] - }, - { - "payment_method": "bank_redirect", - "payment_method_types": [ - { - "payment_method_type": "giropay", - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "eps", - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "sofort", - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "blik", - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "trustly", - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "online_banking_czech_republic", - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "online_banking_finland", - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "online_banking_poland", - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "online_banking_slovakia", - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "bancontact_card", - "minimum_amount": 1, - "maximum_amount": 68607706, - "recurring_enabled": true, - "installment_payment_enabled": true - } - ] - }, - { - "payment_method": "bank_debit", - "payment_method_types": [ - { - "payment_method_type": "ach", - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "bacs", - "recurring_enabled": true, - "installment_payment_enabled": true - }, - { - "payment_method_type": "sepa", - "recurring_enabled": true, - "installment_payment_enabled": true - } - ] - } - ] + "metadata": { + "endpoint_prefix": "" + } } }, "url": {
fix
remove enabled payment methods for payouts processor (#3913)
eb6afd66f29ecbe17a8487d514b54ddaf1893af3
2024-06-26 21:51:40
Apoorv Dixit
feat(users): add endpoint for terminate auth select (#5135)
false
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 4f5651e0a3c..b357a3389d9 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -10,16 +10,17 @@ use crate::user::{ dashboard_metadata::{ GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest, }, - AcceptInviteFromEmailRequest, AuthorizeResponse, BeginTotpResponse, ChangePasswordRequest, - ConnectAccountRequest, CreateInternalUserRequest, CreateUserAuthenticationMethodRequest, - DashboardEntryResponse, ForgotPasswordRequest, GetSsoAuthUrlRequest, - GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest, - GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse, ReInviteUserRequest, - RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, - SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SsoSignInRequest, - SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse, TwoFactorAuthStatusResponse, - UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, - UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, + AcceptInviteFromEmailRequest, AuthSelectRequest, AuthorizeResponse, BeginTotpResponse, + ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest, + CreateUserAuthenticationMethodRequest, DashboardEntryResponse, ForgotPasswordRequest, + GetSsoAuthUrlRequest, GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, + GetUserRoleDetailsRequest, GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse, + ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, + SendVerifyEmailRequest, SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, + SsoSignInRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse, + TwoFactorAuthStatusResponse, UpdateUserAccountDetailsRequest, + UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantCreate, + VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -83,7 +84,8 @@ common_utils::impl_misc_api_event_type!( CreateUserAuthenticationMethodRequest, UpdateUserAuthenticationMethodRequest, GetSsoAuthUrlRequest, - SsoSignInRequest + SsoSignInRequest, + AuthSelectRequest ); #[cfg(feature = "dummy_connector")] diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index b2ed491b677..02a4a09dc94 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -372,3 +372,8 @@ pub struct SsoSignInRequest { pub struct AuthIdQueryParam { pub auth_id: Option<String>, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct AuthSelectRequest { + pub id: String, +} diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index c4260a92948..3e9145c2d33 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -2312,3 +2312,41 @@ pub async fn sso_sign( auth::cookies::set_cookie_response(response, token) } + +pub async fn terminate_auth_select( + state: SessionState, + user_token: auth::UserFromSinglePurposeToken, + req: user_api::AuthSelectRequest, +) -> UserResponse<user_api::TokenResponse> { + let user_from_db: domain::UserFromStorage = state + .global_store + .find_user_by_id(&user_token.user_id) + .await + .change_context(UserErrors::InternalServerError)? + .into(); + + let user_authentication_method = state + .store + .get_user_authentication_method_by_id(&req.id) + .await + .change_context(UserErrors::InternalServerError)?; + + let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::AuthSelect.into())?; + let mut next_flow = current_flow.next(user_from_db.clone(), &state).await?; + + // Skip SSO if continue with password(TOTP) + if next_flow.get_flow() == domain::UserFlow::SPTFlow(domain::SPTFlow::SSO) + && user_authentication_method.auth_type != common_enums::UserAuthType::OpenIdConnect + { + next_flow = next_flow.skip(user_from_db, &state).await?; + } + let token = next_flow.get_token(&state).await?; + + auth::cookies::set_cookie_response( + user_api::TokenResponse { + token: token.clone(), + token_type: next_flow.get_flow().into(), + }, + token, + ) +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 80157c476b3..0cf7de4d33c 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1417,7 +1417,8 @@ impl User { .service( web::resource("/list").route(web::get().to(list_user_authentication_methods)), ) - .service(web::resource("/url").route(web::get().to(get_sso_auth_url))), + .service(web::resource("/url").route(web::get().to(get_sso_auth_url))) + .service(web::resource("/select").route(web::post().to(terminate_auth_select))), ); #[cfg(feature = "email")] diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 115bcf6b9a0..03d12386918 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -232,7 +232,8 @@ impl From<Flow> for ApiIdentifier { | Flow::UpdateUserAuthenticationMethod | Flow::ListUserAuthenticationMethods | Flow::GetSsoAuthUrl - | Flow::SignInWithSso => Self::User, + | Flow::SignInWithSso + | Flow::AuthSelect => Self::User, Flow::ListRoles | Flow::GetRole diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index dae78d31bf0..7e55393cc57 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -876,3 +876,22 @@ pub async fn list_user_authentication_methods( )) .await } + +pub async fn terminate_auth_select( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_api::AuthSelectRequest>, +) -> HttpResponse { + let flow = Flow::AuthSelect; + + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, user, req, _| user_core::terminate_auth_select(state, user, req), + &auth::SinglePurposeJWTAuth(TokenPurpose::AuthSelect), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index ef73b88015f..97fb69074a6 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -51,9 +51,8 @@ impl SPTFlow { ) -> UserResult<bool> { match self { // Auth - // AuthSelect and SSO flow are not enabled, once the terminate SSO API is ready, we can enable these flows - Self::AuthSelect => Ok(false), - Self::SSO => Ok(false), + Self::AuthSelect => Ok(true), + Self::SSO => Ok(true), // TOTP Self::TOTP => Ok(!path.contains(&TokenPurpose::SSO)), // Main email APIs @@ -311,6 +310,26 @@ impl NextFlow { } } } + + pub async fn skip(self, user: UserFromStorage, state: &SessionState) -> UserResult<Self> { + let flows = self.origin.get_flows(); + let index = flows + .iter() + .position(|flow| flow == &self.get_flow()) + .ok_or(UserErrors::InternalServerError)?; + let remaining_flows = flows.iter().skip(index + 1); + for flow in remaining_flows { + if flow.is_required(&user, &self.path, state).await? { + return Ok(Self { + origin: self.origin.clone(), + next_flow: *flow, + user, + path: self.path, + }); + } + } + Err(UserErrors::InternalServerError.into()) + } } impl From<UserFlow> for TokenPurpose { diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 023cd2a7944..0b8f7f184da 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -155,7 +155,7 @@ pub enum Flow { PaymentsStart, /// Payments list flow. PaymentsList, - // Payments filters flow + /// Payments filters flow PaymentsFilters, #[cfg(feature = "payouts")] /// Payouts create flow @@ -412,7 +412,7 @@ pub enum Flow { UserFromEmail, /// Begin TOTP TotpBegin, - // Reset TOTP + /// Reset TOTP TotpReset, /// Verify TOTP TotpVerify, @@ -422,20 +422,22 @@ pub enum Flow { RecoveryCodeVerify, /// Generate or Regenerate recovery codes RecoveryCodesGenerate, - // Terminate two factor authentication + /// Terminate two factor authentication TerminateTwoFactorAuth, - // Check 2FA status + /// Check 2FA status TwoFactorAuthStatus, - // Create user authentication method + /// Create user authentication method CreateUserAuthenticationMethod, - // Update user authentication method + /// Update user authentication method UpdateUserAuthenticationMethod, - // List user authentication methods + /// List user authentication methods ListUserAuthenticationMethods, /// Get sso auth url GetSsoAuthUrl, /// Signin with SSO SignInWithSso, + /// Auth Select + AuthSelect, /// List initial webhook delivery attempts WebhookEventInitialDeliveryAttemptList, /// List delivery attempts for a webhook event
feat
add endpoint for terminate auth select (#5135)
c9fa94febe7a1fcd24e8d723d14b78f8a73da0e3
2024-05-28 13:06:53
AkshayaFoiger
feat(connector): [Iatapay] add upi qr support (#4728)
false
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 5f9618738b2..cd405e3ca98 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1664,7 +1664,10 @@ impl GetPaymentMethodType for CryptoData { impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { - api_enums::PaymentMethodType::UpiCollect + match self { + Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, + Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, + } } } impl GetPaymentMethodType for VoucherData { @@ -2119,11 +2122,21 @@ pub struct CryptoData { #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] -pub struct UpiData { +pub enum UpiData { + UpiCollect(UpiCollectData), + UpiIntent(UpiIntentData), +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct UpiIntentData {} + #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing @@ -2960,6 +2973,11 @@ pub enum NextActionData { /// The url for Qr code given by the connector qr_code_url: Option<Url>, }, + /// Contains url to fetch Qr code data + FetchQrCodeInformation { + #[schema(value_type = String)] + qr_code_fetch_url: Url, + }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] @@ -3045,6 +3063,11 @@ pub struct SdkNextActionData { pub next_action: NextActionCall, } +#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct FetchQrCodeInformation { + pub qr_code_fetch_url: Url, +} + #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index dc4ca6b2cb3..3df291d5681 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1430,6 +1430,7 @@ pub enum PaymentMethodType { Trustly, Twint, UpiCollect, + UpiIntent, Vipps, Venmo, Walley, diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index faca2579c0a..cb37180c987 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1854,6 +1854,7 @@ impl From<PaymentMethodType> for PaymentMethod { PaymentMethodType::Trustly => Self::BankRedirect, PaymentMethodType::Twint => Self::Wallet, PaymentMethodType::UpiCollect => Self::Upi, + PaymentMethodType::UpiIntent => Self::Upi, PaymentMethodType::Vipps => Self::Wallet, PaymentMethodType::Venmo => Self::Wallet, PaymentMethodType::Walley => Self::PayLater, diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs index c5f864bf770..133fee18c0d 100644 --- a/crates/euclid/src/frontend/dir/enums.rs +++ b/crates/euclid/src/frontend/dir/enums.rs @@ -268,6 +268,7 @@ pub enum CryptoType { #[strum(serialize_all = "snake_case")] pub enum UpiType { UpiCollect, + UpiIntent, } #[derive( diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs index f6b156bf909..cc4c9be2a2d 100644 --- a/crates/euclid/src/frontend/dir/lowering.rs +++ b/crates/euclid/src/frontend/dir/lowering.rs @@ -75,6 +75,7 @@ impl From<enums::UpiType> for global_enums::PaymentMethodType { fn from(value: enums::UpiType) -> Self { match value { enums::UpiType::UpiCollect => Self::UpiCollect, + enums::UpiType::UpiIntent => Self::UpiIntent, } } } diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs index bcc951b0057..052561b5aab 100644 --- a/crates/euclid/src/frontend/dir/transformers.rs +++ b/crates/euclid/src/frontend/dir/transformers.rs @@ -109,6 +109,7 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet } global_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)), global_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)), + global_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)), global_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)), global_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)), global_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)), diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 9dc85c103e9..7517918ed95 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -289,10 +289,20 @@ pub struct CryptoData { #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] -pub struct UpiData { +pub enum UpiData { + UpiCollect(UpiCollectData), + UpiIntent(UpiIntentData), +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub struct UpiCollectData { pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct UpiIntentData {} + #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum VoucherData { @@ -690,8 +700,12 @@ impl From<api_models::payments::CryptoData> for CryptoData { impl From<api_models::payments::UpiData> for UpiData { fn from(value: api_models::payments::UpiData) -> Self { - let api_models::payments::UpiData { vpa_id } = value; - Self { vpa_id } + match value { + api_models::payments::UpiData::UpiCollect(upi) => { + Self::UpiCollect(UpiCollectData { vpa_id: upi.vpa_id }) + } + api_models::payments::UpiData::UpiIntent(_) => Self::UpiIntent(UpiIntentData {}), + } } } diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index b32c8c23bd9..76c7381bf22 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -77,7 +77,6 @@ fn get_dir_value_payment_method( api_enums::PaymentMethodType::ClassicReward => Ok(dirval!(RewardType = ClassicReward)), api_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)), - api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)), api_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)), api_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)), api_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)), @@ -133,6 +132,8 @@ fn get_dir_value_payment_method( api_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)), api_enums::PaymentMethodType::CardRedirect => Ok(dirval!(CardRedirectType = CardRedirect)), api_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)), + api_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)), + api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)), } } diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 3e43a4324f9..1bff0eac0d7 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -230,6 +230,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { api_enums::PaymentMethodType::ClassicReward => Ok(dirval!(RewardType = ClassicReward)), api_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)), api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)), + api_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)), api_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)), api_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)), api_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)), diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index c67ea2d2746..fd0688ed293 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -291,6 +291,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::CryptoData, api_models::payments::RewardData, api_models::payments::UpiData, + api_models::payments::UpiCollectData, + api_models::payments::UpiIntentData, api_models::payments::VoucherData, api_models::payments::BoletoVoucherData, api_models::payments::AlfamartVoucherData, diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 5e8c9ea08c0..0526eacb2e8 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -141,10 +141,10 @@ impl From<StripeWallet> for payments::WalletData { } impl From<StripeUpi> for payments::UpiData { - fn from(upi: StripeUpi) -> Self { - Self { - vpa_id: Some(upi.vpa_id), - } + fn from(upi_data: StripeUpi) -> Self { + Self::UpiCollect(payments::UpiCollectData { + vpa_id: Some(upi_data.vpa_id), + }) } } @@ -315,6 +315,18 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { let amount = item.amount.map(|amount| MinorUnit::new(amount).into()); + let payment_method_data = item.payment_method_data.as_ref().map(|pmd| { + let payment_method_data = match pmd.payment_method_details.as_ref() { + Some(spmd) => Some(payments::PaymentMethodData::from(spmd.to_owned())), + None => get_pmd_based_on_payment_method_type(item.payment_method_types), + }; + + payments::PaymentMethodDataRequest { + payment_method_data, + billing: pmd.billing_details.clone().map(payments::Address::from), + } + }); + let request = Ok(Self { payment_id: item.id.map(payments::PaymentIdType::PaymentIntentId), amount, @@ -334,16 +346,7 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { phone: item.shipping.as_ref().and_then(|s| s.phone.clone()), description: item.description, return_url: item.return_url, - payment_method_data: item.payment_method_data.as_ref().and_then(|pmd| { - pmd.payment_method_details - .as_ref() - .map(|spmd| payments::PaymentMethodDataRequest { - payment_method_data: Some(payments::PaymentMethodData::from( - spmd.to_owned(), - )), - billing: pmd.billing_details.clone().map(payments::Address::from), - }) - }), + payment_method_data, payment_method: item .payment_method_data .as_ref() @@ -816,6 +819,9 @@ pub enum StripeNextAction { display_to_timestamp: Option<i64>, qr_code_url: Option<url::Url>, }, + FetchQrCodeInformation { + qr_code_fetch_url: url::Url, + }, DisplayVoucherInformation { voucher_details: payments::VoucherNextStepData, }, @@ -858,6 +864,9 @@ pub(crate) fn into_stripe_next_action( display_to_timestamp, qr_code_url, }, + payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url } => { + StripeNextAction::FetchQrCodeInformation { qr_code_fetch_url } + } payments::NextActionData::DisplayVoucherInformation { voucher_details } => { StripeNextAction::DisplayVoucherInformation { voucher_details } } @@ -884,3 +893,15 @@ pub(crate) fn into_stripe_next_action( pub struct StripePaymentRetrieveBody { pub client_secret: Option<String>, } + +//To handle payment types that have empty payment method data +fn get_pmd_based_on_payment_method_type( + payment_method_type: Option<api_enums::PaymentMethodType>, +) -> Option<payments::PaymentMethodData> { + match payment_method_type { + Some(api_enums::PaymentMethodType::UpiIntent) => Some(payments::PaymentMethodData::Upi( + payments::UpiData::UpiIntent(payments::UpiIntentData {}), + )), + _ => None, + } +} diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index bbcafb65e9f..9a1cf58f11b 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -382,6 +382,9 @@ pub enum StripeNextAction { display_to_timestamp: Option<i64>, qr_code_url: Option<url::Url>, }, + FetchQrCodeInformation { + qr_code_fetch_url: url::Url, + }, DisplayVoucherInformation { voucher_details: payments::VoucherNextStepData, }, @@ -424,6 +427,9 @@ pub(crate) fn into_stripe_next_action( display_to_timestamp, qr_code_url, }, + payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url } => { + StripeNextAction::FetchQrCodeInformation { qr_code_fetch_url } + } payments::NextActionData::DisplayVoucherInformation { voucher_details } => { StripeNextAction::DisplayVoucherInformation { voucher_details } } diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index e2effb2e325..1a63dc50c9e 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -214,7 +214,8 @@ impl ConnectorValidation for Adyen { | PaymentMethodType::SamsungPay | PaymentMethodType::Evoucher | PaymentMethodType::Cashapp - | PaymentMethodType::UpiCollect => { + | PaymentMethodType::UpiCollect + | PaymentMethodType::UpiIntent => { capture_method_not_supported!(connector, capture_method, payment_method_type) } }, diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index 5daa33ab944..b36792e90ca 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -1,7 +1,8 @@ use std::collections::HashMap; use api_models::enums::PaymentMethod; -use common_utils::errors::CustomResult; +use common_utils::{errors::CustomResult, ext_traits::Encode}; +use error_stack::ResultExt; use masking::{Secret, SwitchStrategy}; use serde::{Deserialize, Serialize}; @@ -84,6 +85,13 @@ pub struct PayerInfo { token_id: Secret<String>, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum PreferredCheckoutMethod { + Vpa, + Qr, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct IatapayPaymentsRequest { @@ -95,7 +103,9 @@ pub struct IatapayPaymentsRequest { locale: String, redirect_urls: RedirectUrls, notification_url: String, + #[serde(skip_serializing_if = "Option::is_none")] payer_info: Option<PayerInfo>, + preferred_checkout_method: Option<PreferredCheckoutMethod>, } impl @@ -136,24 +146,31 @@ impl | PaymentMethod::GiftCard => item.router_data.get_billing_country()?.to_string(), }; let return_url = item.router_data.get_return_url()?; - let payer_info = match item.router_data.request.payment_method_data.clone() { - domain::PaymentMethodData::Upi(upi_data) => upi_data.vpa_id.map(|id| PayerInfo { - token_id: id.switch_strategy(), - }), - domain::PaymentMethodData::Card(_) - | domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::Wallet(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::CardToken(_) => None, - }; + let (payer_info, preferred_checkout_method) = + match item.router_data.request.payment_method_data.clone() { + domain::PaymentMethodData::Upi(upi_type) => match upi_type { + domain::UpiData::UpiCollect(upi_data) => ( + upi_data.vpa_id.map(|id| PayerInfo { + token_id: id.switch_strategy(), + }), + Some(PreferredCheckoutMethod::Vpa), + ), + domain::UpiData::UpiIntent(_) => (None, Some(PreferredCheckoutMethod::Qr)), + }, + domain::PaymentMethodData::Card(_) + | domain::PaymentMethodData::CardRedirect(_) + | domain::PaymentMethodData::Wallet(_) + | domain::PaymentMethodData::PayLater(_) + | domain::PaymentMethodData::BankRedirect(_) + | domain::PaymentMethodData::BankDebit(_) + | domain::PaymentMethodData::BankTransfer(_) + | domain::PaymentMethodData::Crypto(_) + | domain::PaymentMethodData::MandatePayment + | domain::PaymentMethodData::Reward + | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::CardToken(_) => (None, None), + }; let payload = Self { merchant_id: IatapayAuthType::try_from(&item.router_data.connector_auth_type)? .merchant_id, @@ -165,6 +182,7 @@ impl redirect_urls: get_redirect_url(return_url), payer_info, notification_url: item.router_data.request.get_webhook_url()?, + preferred_checkout_method, }; Ok(payload) } @@ -291,8 +309,46 @@ fn get_iatpay_response( }; let connector_response_reference_id = response.merchant_payment_id.or(response.iata_payment_id); - let payment_response_data = response.checkout_methods.map_or( - types::PaymentsResponseData::TransactionResponse { + let payment_response_data = match response.checkout_methods { + Some(checkout_methods) => { + let (connector_metadata, redirection_data) = + match checkout_methods.redirect.redirect_url.ends_with("qr") { + true => { + let qr_code_info = api_models::payments::FetchQrCodeInformation { + qr_code_fetch_url: url::Url::parse( + &checkout_methods.redirect.redirect_url, + ) + .change_context(errors::ConnectorError::ResponseHandlingFailed)?, + }; + ( + Some(qr_code_info.encode_to_value()) + .transpose() + .change_context(errors::ConnectorError::ResponseHandlingFailed)?, + None, + ) + } + false => ( + None, + Some(services::RedirectForm::Form { + endpoint: checkout_methods.redirect.redirect_url, + method: services::Method::Get, + form_fields, + }), + ), + }; + + types::PaymentsResponseData::TransactionResponse { + resource_id: id, + redirection_data, + mandate_reference: None, + connector_metadata, + network_txn_id: None, + connector_response_reference_id: connector_response_reference_id.clone(), + incremental_authorization_allowed: None, + charge_id: None, + } + } + None => types::PaymentsResponseData::TransactionResponse { resource_id: id.clone(), redirection_data: None, mandate_reference: None, @@ -302,21 +358,8 @@ fn get_iatpay_response( incremental_authorization_allowed: None, charge_id: None, }, - |checkout_methods| types::PaymentsResponseData::TransactionResponse { - resource_id: id, - redirection_data: Some(services::RedirectForm::Form { - endpoint: checkout_methods.redirect.redirect_url, - method: services::Method::Get, - form_fields, - }), - mandate_reference: None, - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: connector_response_reference_id.clone(), - incremental_authorization_allowed: None, - charge_id: None, - }, - ); + }; + Ok((status, error, payment_response_data)) } diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 5c174c69e3b..48b6616a64e 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -398,6 +398,7 @@ impl | common_enums::PaymentMethodType::Trustly | common_enums::PaymentMethodType::Twint | common_enums::PaymentMethodType::UpiCollect + | common_enums::PaymentMethodType::UpiIntent | common_enums::PaymentMethodType::Venmo | common_enums::PaymentMethodType::Vipps | common_enums::PaymentMethodType::Walley diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 55b0d7f4675..83bca39626f 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -675,6 +675,7 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { | enums::PaymentMethodType::Paypal | enums::PaymentMethodType::Pix | enums::PaymentMethodType::UpiCollect + | enums::PaymentMethodType::UpiIntent | enums::PaymentMethodType::Cashapp | enums::PaymentMethodType::Oxxo => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index a39f0deb3ca..db99ff590cd 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1009,6 +1009,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { api_models::payments::NextActionData::DisplayBankTransferInformation { .. } => None, api_models::payments::NextActionData::ThirdPartySdkSessionToken { .. } => None, api_models::payments::NextActionData::QrCodeInformation{..} => None, + api_models::payments::NextActionData::FetchQrCodeInformation{..} => None, api_models::payments::NextActionData::DisplayVoucherInformation{ .. } => None, api_models::payments::NextActionData::WaitScreenInformation{..} => None, api_models::payments::NextActionData::ThreeDsInvoke{..} => None, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 973ca4b2266..6e3f6a9bf6e 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2338,7 +2338,7 @@ pub fn validate_payment_method_type_against_payment_method( ), api_enums::PaymentMethod::Upi => matches!( payment_method_type, - api_enums::PaymentMethodType::UpiCollect + api_enums::PaymentMethodType::UpiCollect | api_enums::PaymentMethodType::UpiIntent ), api_enums::PaymentMethod::Voucher => matches!( payment_method_type, @@ -4252,9 +4252,9 @@ pub fn get_key_params_for_surcharge_details( )), api_models::payments::PaymentMethodData::MandatePayment => None, api_models::payments::PaymentMethodData::Reward => None, - api_models::payments::PaymentMethodData::Upi(_) => Some(( + api_models::payments::PaymentMethodData::Upi(upi_data) => Some(( common_enums::PaymentMethod::Upi, - common_enums::PaymentMethodType::UpiCollect, + upi_data.get_payment_method_type(), None, )), api_models::payments::PaymentMethodData::Voucher(voucher) => Some(( diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 7f6b0cc1f61..8f6af2f89bc 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -541,6 +541,9 @@ where let papal_sdk_next_action = paypal_sdk_next_steps_check(payment_attempt.clone())?; + let next_action_containing_fetch_qr_code_url = + fetch_qr_code_url_next_steps_check(payment_attempt.clone())?; + let next_action_containing_wait_screen = wait_screen_next_steps_check(payment_attempt.clone())?; @@ -550,6 +553,7 @@ where || next_action_containing_qr_code_url.is_some() || next_action_containing_wait_screen.is_some() || papal_sdk_next_action.is_some() + || next_action_containing_fetch_qr_code_url.is_some() || payment_data.authentication.is_some() { next_action_response = bank_transfer_next_steps @@ -566,6 +570,11 @@ where .or(next_action_containing_qr_code_url.map(|qr_code_data| { api_models::payments::NextActionData::foreign_from(qr_code_data) })) + .or(next_action_containing_fetch_qr_code_url.map(|fetch_qr_code_data| { + api_models::payments::NextActionData::FetchQrCodeInformation { + qr_code_fetch_url: fetch_qr_code_data.qr_code_fetch_url + } + })) .or(papal_sdk_next_action.map(|paypal_next_action_data| { api_models::payments::NextActionData::InvokeSdkClient{ next_action_data: paypal_next_action_data @@ -899,6 +908,18 @@ pub fn paypal_sdk_next_steps_check( Ok(paypal_next_steps) } +pub fn fetch_qr_code_url_next_steps_check( + payment_attempt: storage::PaymentAttempt, +) -> RouterResult<Option<api_models::payments::FetchQrCodeInformation>> { + let qr_code_steps: Option<Result<api_models::payments::FetchQrCodeInformation, _>> = + payment_attempt + .connector_metadata + .map(|metadata| metadata.parse_value("FetchQrCodeInformation")); + + let qr_code_fetch_url = qr_code_steps.transpose().ok().flatten(); + Ok(qr_code_fetch_url) +} + pub fn wait_screen_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::WaitScreenInstructions>> { @@ -1108,8 +1129,8 @@ impl ForeignFrom<api_models::payments::QrCodeInformation> for api_models::paymen display_to_timestamp, } => Self::QrCodeInformation { qr_code_url: Some(qr_code_url), - display_to_timestamp, image_data_url: None, + display_to_timestamp, }, } } diff --git a/crates/router/src/types/domain/payments.rs b/crates/router/src/types/domain/payments.rs index 7b1f3365490..51d3210a70f 100644 --- a/crates/router/src/types/domain/payments.rs +++ b/crates/router/src/types/domain/payments.rs @@ -5,6 +5,6 @@ pub use hyperswitch_domain_models::payment_method_data::{ GooglePayPaymentMethodInfo, GooglePayRedirectData, GooglePayThirdPartySdkData, GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData, KakaoPayRedirection, MbWayRedirection, PayLaterData, PaymentMethodData, SamsungPayWalletData, - SepaAndBacsBillingDetails, SwishQrData, TouchNGoRedirection, VoucherData, WalletData, - WeChatPayQr, + SepaAndBacsBillingDetails, SwishQrData, TouchNGoRedirection, UpiCollectData, UpiData, + UpiIntentData, VoucherData, WalletData, WeChatPayQr, }; diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index da8e8c621b7..59ec42abfd2 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -461,7 +461,9 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { | api_enums::PaymentMethodType::Trustly | api_enums::PaymentMethodType::Bizum | api_enums::PaymentMethodType::Interac => Self::BankRedirect, - api_enums::PaymentMethodType::UpiCollect => Self::Upi, + api_enums::PaymentMethodType::UpiCollect | api_enums::PaymentMethodType::UpiIntent => { + Self::Upi + } api_enums::PaymentMethodType::CryptoCurrency => Self::Crypto, api_enums::PaymentMethodType::Ach | api_enums::PaymentMethodType::Sepa diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index b87b516de28..30bd356cd45 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -11757,6 +11757,25 @@ } } }, + { + "type": "object", + "description": "Contains url to fetch Qr code data", + "required": [ + "qr_code_fetch_url", + "type" + ], + "properties": { + "qr_code_fetch_url": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "fetch_qr_code_information" + ] + } + } + }, { "type": "object", "description": "Contains the download url and the reference number for transaction", @@ -13529,6 +13548,7 @@ "trustly", "twint", "upi_collect", + "upi_intent", "vipps", "venmo", "walley", @@ -18692,7 +18712,7 @@ }, "additionalProperties": false }, - "UpiData": { + "UpiCollectData": { "type": "object", "properties": { "vpa_id": { @@ -18702,6 +18722,35 @@ } } }, + "UpiData": { + "oneOf": [ + { + "type": "object", + "required": [ + "upi_collect" + ], + "properties": { + "upi_collect": { + "$ref": "#/components/schemas/UpiCollectData" + } + } + }, + { + "type": "object", + "required": [ + "upi_intent" + ], + "properties": { + "upi_intent": { + "$ref": "#/components/schemas/UpiIntentData" + } + } + } + ] + }, + "UpiIntentData": { + "type": "object" + }, "ValueType": { "oneOf": [ {
feat
[Iatapay] add upi qr support (#4728)
53ccde80467c6b6037b3a0c372aa879d9867571b
2023-07-20 08:21:45
github-actions
chore(version): v1.9.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index d012e379cc4..f448b3e88a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,37 @@ All notable changes to HyperSwitch will be documented here. - - - +## 1.9.0 (2023-07-20) + +### Features + +- **connector:** + - [Adyen] implement Momo for Adyen ([#1583](https://github.com/juspay/hyperswitch/pull/1583)) ([`96933f2`](https://github.com/juspay/hyperswitch/commit/96933f2636e39b96435cba8e59b96b8c59413f39)) + - [Adyen] Implement Alma BNPL and DANA Wallet ([#1566](https://github.com/juspay/hyperswitch/pull/1566)) ([`5dcf758`](https://github.com/juspay/hyperswitch/commit/5dcf758ac04716e194601c1571851f07a7d24fcc)) +- **metrics:** Add pod information in metrics pipeline ([#1710](https://github.com/juspay/hyperswitch/pull/1710)) ([`cf145a3`](https://github.com/juspay/hyperswitch/commit/cf145a321c4c797f0efa44f846f19048ea69e7ec)) +- Add payout service ([#1665](https://github.com/juspay/hyperswitch/pull/1665)) ([`763e2df`](https://github.com/juspay/hyperswitch/commit/763e2df3bdfb426214d94c56529d98f453452266)) + +### Bug Fixes + +- **adyen_ui:** Ignore tests failing from connector side ([#1751](https://github.com/juspay/hyperswitch/pull/1751)) ([`e0f4507`](https://github.com/juspay/hyperswitch/commit/e0f4507b1009c481ecd8216ccd41f44fbc0ccb36)) +- **connector:** + - [PowerTranz] error message from response_code in absence of errors object & comment billing and shipping as it is optional ([#1738](https://github.com/juspay/hyperswitch/pull/1738)) ([`54f7ab7`](https://github.com/juspay/hyperswitch/commit/54f7ab7ae14fa593fa9749c0d67807f68247e899)) + - Update amount captured after webhook call and parse error responses from connector properly ([#1680](https://github.com/juspay/hyperswitch/pull/1680)) ([`cac9f50`](https://github.com/juspay/hyperswitch/commit/cac9f5049e8abee78c260c523e871754cfc2b22c)) + - Deserialization error due to latest_charge stripe ([#1740](https://github.com/juspay/hyperswitch/pull/1740)) ([`c53631e`](https://github.com/juspay/hyperswitch/commit/c53631ef55645e45cb0c3165e79d389e0100b4ac)) + - Stripe mandate failure and other ui tests failures ([#1742](https://github.com/juspay/hyperswitch/pull/1742)) ([`ea119eb`](https://github.com/juspay/hyperswitch/commit/ea119eb856cf47c5e28117ba9ecfce722aff541f)) + +### Testing + +- **connector:** + - [Authorizedotnet] Add UI test for Authorizedotnet Payment methods ([#1736](https://github.com/juspay/hyperswitch/pull/1736)) ([`f44cc1e`](https://github.com/juspay/hyperswitch/commit/f44cc1e10705f167d332779a2dc0141566ac765e)) + - [Adyen] Add UI test for Adyen Payment methods ([#1648](https://github.com/juspay/hyperswitch/pull/1648)) ([`2e9b783`](https://github.com/juspay/hyperswitch/commit/2e9b78329a6bb6d400588578f7b83bc1201cc151)) + - [Noon] Add test for Noon Payment methods ([#1714](https://github.com/juspay/hyperswitch/pull/1714)) ([`f06e5dc`](https://github.com/juspay/hyperswitch/commit/f06e5dcd63affd9919d936884e055344bcd3e8ba)) + +**Full Changelog:** [`v1.8.0...v1.9.0`](https://github.com/juspay/hyperswitch/compare/v1.8.0...v1.9.0) + +- - - + + ## 1.8.0 (2023-07-19) ### Features
chore
v1.9.0
21a0a3d81dfb91f6e4a56c3343eff52f407aa8fa
2022-12-11 17:35:43
Nishant Joshi
feat(mandate): added amount based validation and database fields (#99)
false
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index 22dbcb1af18..f2f38ee997f 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -146,6 +146,8 @@ pub(crate) enum ErrorCode { current_value: String, states: String, }, + #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The mandate information is invalid. {message}")] + PaymentIntentMandateInvalid { message: String }, // TODO: Some day implement all stripe error codes https://stripe.com/docs/error-codes // AccountCountryInvalidAddress, // AccountErrorCountryChangeRequiresAdditionalSteps, @@ -227,7 +229,6 @@ pub(crate) enum ErrorCode { // PaymentIntentIncompatiblePaymentMethod, // PaymentIntentInvalidParameter, // PaymentIntentKonbiniRejectedConfirmationNumber, - // PaymentIntentMandateInvalid, // PaymentIntentPaymentAttemptExpired, // PaymentIntentUnexpectedState, // PaymentMethodBankAccountAlreadyVerified, @@ -350,6 +351,9 @@ impl From<ApiErrorResponse> for ErrorCode { ErrorCode::MerchantConnectorAccountNotFound } ApiErrorResponse::MandateNotFound => ErrorCode::MandateNotFound, + ApiErrorResponse::MandateValidationFailed { reason } => { + ErrorCode::PaymentIntentMandateInvalid { message: reason } + } ApiErrorResponse::ReturnUrlUnavailable => ErrorCode::ReturnUrlUnavailable, ApiErrorResponse::DuplicateMerchantAccount => ErrorCode::DuplicateMerchantAccount, ApiErrorResponse::DuplicateMerchantConnectorAccount => { @@ -427,6 +431,7 @@ impl actix_web::ResponseError for ErrorCode { | ErrorCode::SuccessfulPaymentNotFound | ErrorCode::AddressNotFound | ErrorCode::ResourceIdNotFound + | ErrorCode::PaymentIntentMandateInvalid { .. } | ErrorCode::PaymentIntentUnexpectedState { .. } => StatusCode::BAD_REQUEST, ErrorCode::RefundFailed | ErrorCode::InternalServerError => { StatusCode::INTERNAL_SERVER_ERROR diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index c79dcbe73aa..88dbb652cb7 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -120,6 +120,8 @@ pub enum ApiErrorResponse { SuccessfulPaymentNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "RE_05", message = "Address does not exist in our records.")] AddressNotFound, + #[error(error_type = ErrorType::ValidationError, code = "RE_03", message = "Mandate Validation Failed" )] + MandateValidationFailed { reason: String }, #[error(error_type = ErrorType::ServerNotAvailable, code = "IR_00", message = "This API is under development and will be made available soon.")] NotImplemented, } @@ -159,7 +161,8 @@ impl actix_web::ResponseError for ApiErrorResponse { | ApiErrorResponse::CardExpired { .. } | ApiErrorResponse::RefundFailed { .. } | ApiErrorResponse::VerificationFailed { .. } - | ApiErrorResponse::PaymentUnexpectedState { .. } => StatusCode::BAD_REQUEST, // 400 + | ApiErrorResponse::PaymentUnexpectedState { .. } + | ApiErrorResponse::MandateValidationFailed { .. } => StatusCode::BAD_REQUEST, // 400 ApiErrorResponse::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR, // 500 ApiErrorResponse::DuplicateRefundRequest => StatusCode::BAD_REQUEST, // 400 diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 6dfbe332326..b2cb17fd76c 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -1,10 +1,8 @@ use async_trait::async_trait; use error_stack::ResultExt; -use masking::Secret; use super::{ConstructFlowSpecificData, Feature}; use crate::{ - consts, core::{ errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt}, payments::{self, helpers, transformers, PaymentData}, @@ -17,7 +15,6 @@ use crate::{ storage::{self, enums as storage_enums}, PaymentsAuthorizeData, PaymentsAuthorizeRouterData, PaymentsResponseData, }, - utils, }; #[async_trait] @@ -124,7 +121,20 @@ impl PaymentsAuthorizeRouterData { ) .await .change_context(errors::ApiErrorResponse::MandateNotFound), - storage_enums::MandateType::MultiUse => Ok(mandate), + storage_enums::MandateType::MultiUse => state + .store + .update_mandate_by_merchant_id_mandate_id( + &resp.merchant_id, + mandate_id, + storage::MandateUpdate::CaptureAmountUpdate { + amount_captured: Some( + mandate.amount_captured.unwrap_or(0) + + self.request.amount, + ), + }, + ) + .await + .change_context(errors::ApiErrorResponse::MandateNotFound), }?; resp.payment_method_id = Some(mandate.payment_method_id); @@ -142,9 +152,13 @@ impl PaymentsAuthorizeRouterData { .payment_method_id; resp.payment_method_id = Some(payment_method_id.clone()); - if let Some(new_mandate_data) = - self.generate_mandate(maybe_customer, payment_method_id) - { + if let Some(new_mandate_data) = helpers::generate_mandate( + self.merchant_id.clone(), + self.connector.clone(), + None, + maybe_customer, + payment_method_id, + ) { resp.request.mandate_id = Some(new_mandate_data.mandate_id.clone()); state.store.insert_mandate(new_mandate_data).await.map_err( |err| { @@ -163,44 +177,4 @@ impl PaymentsAuthorizeRouterData { _ => Ok(self.clone()), } } - - fn generate_mandate( - &self, - customer: &Option<storage::Customer>, - payment_method_id: String, - ) -> Option<storage::MandateNew> { - match (self.request.setup_mandate_details.clone(), customer) { - (Some(data), Some(cus)) => { - let mandate_id = utils::generate_id(consts::ID_LENGTH, "man"); - - // The construction of the mandate new must be visible - let mut new_mandate = storage::MandateNew::default(); - - new_mandate - .set_mandate_id(mandate_id) - .set_customer_id(cus.customer_id.clone()) - .set_merchant_id(self.merchant_id.clone()) - .set_payment_method_id(payment_method_id) - .set_mandate_status(storage_enums::MandateStatus::Active) - .set_customer_ip_address( - data.customer_acceptance.get_ip_address().map(Secret::new), - ) - .set_customer_user_agent(data.customer_acceptance.get_user_agent()) - .set_customer_accepted_at(Some(data.customer_acceptance.get_accepted_at())); - - Some(match data.mandate_type { - api::MandateType::SingleUse(data) => new_mandate - .set_single_use_amount(Some(data.amount)) - .set_single_use_currency(Some(data.currency)) - .set_mandate_type(storage_enums::MandateType::SingleUse) - .to_owned(), - - api::MandateType::MultiUse => new_mandate - .set_mandate_type(storage_enums::MandateType::MultiUse) - .to_owned(), - }) - } - (_, _) => None, - } - } } diff --git a/crates/router/src/core/payments/flows/verfiy_flow.rs b/crates/router/src/core/payments/flows/verfiy_flow.rs index 41189e719bc..3ab253348d5 100644 --- a/crates/router/src/core/payments/flows/verfiy_flow.rs +++ b/crates/router/src/core/payments/flows/verfiy_flow.rs @@ -1,10 +1,8 @@ use async_trait::async_trait; use error_stack::ResultExt; -use masking::Secret; use super::{ConstructFlowSpecificData, Feature}; use crate::{ - consts, core::{ errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt}, payments::{self, helpers, transformers, PaymentData}, @@ -15,7 +13,6 @@ use crate::{ self, api, storage::{self, enums}, }, - utils, }; #[async_trait] @@ -108,8 +105,9 @@ impl types::VerifyRouterData { .payment_method_id; resp.payment_method_id = Some(payment_method_id.clone()); - if let Some(new_mandate_data) = generate_mandate( + if let Some(new_mandate_data) = helpers::generate_mandate( self.merchant_id.clone(), + self.connector.clone(), self.request.setup_mandate_details.clone(), maybe_customer, payment_method_id, @@ -132,29 +130,3 @@ impl types::VerifyRouterData { } } } - -fn generate_mandate( - merchant_id: String, - setup_mandate_details: Option<api::MandateData>, - customer: &Option<storage::Customer>, - payment_method_id: String, -) -> Option<storage::MandateNew> { - match (setup_mandate_details, customer) { - (Some(data), Some(cus)) => { - let mandate_id = utils::generate_id(consts::ID_LENGTH, "man"); - Some(storage::MandateNew { - mandate_id, - customer_id: cus.customer_id.clone(), - merchant_id, - payment_method_id, - mandate_status: enums::MandateStatus::Active, - mandate_type: enums::MandateType::MultiUse, - customer_ip_address: data.customer_acceptance.get_ip_address().map(Secret::new), - customer_user_agent: data.customer_acceptance.get_user_agent(), - customer_accepted_at: Some(data.customer_acceptance.get_accepted_at()), - ..Default::default() - }) - } - (_, _) => None, - } -} diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index f805a2e807b..2a7b2314692 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -141,10 +141,7 @@ pub async fn get_token_for_recurring_mandate( .await .map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::MandateNotFound))?; - utils::when( - mandate.mandate_status != storage_enums::MandateStatus::Active, - Err(errors::ApiErrorResponse::MandateNotFound), - )?; + // TODO: Make currency in payments request as Currency enum let customer = req.customer_id.clone().get_required_value("customer_id")?; @@ -159,8 +156,13 @@ pub async fn get_token_for_recurring_mandate( message: "mandate is not active".into() }))? }; - mandate.payment_method_id + mandate.payment_method_id.clone() }; + verify_mandate_details( + req.amount.get_required_value("amount")?.into(), + req.currency.clone().get_required_value("currency")?, + mandate.clone(), + )?; let payment_method = db .find_payment_method(payment_method_id.as_str()) @@ -346,6 +348,44 @@ fn validate_recurring_mandate(req: api::MandateValidationFields) -> RouterResult Ok(()) } +pub fn verify_mandate_details( + request_amount: i32, + request_currency: String, + mandate: storage::Mandate, +) -> RouterResult<()> { + match mandate.mandate_type { + storage_enums::MandateType::SingleUse => utils::when( + mandate + .mandate_amount + .map(|mandate_amount| request_amount > mandate_amount) + .unwrap_or(true), + Err(report!(errors::ApiErrorResponse::MandateValidationFailed { + reason: "request amount is greater than mandate amount".to_string() + })), + ), + storage::enums::MandateType::MultiUse => utils::when( + mandate + .mandate_amount + .map(|mandate_amount| { + (mandate.amount_captured.unwrap_or(0) + request_amount) > mandate_amount + }) + .unwrap_or(false), + Err(report!(errors::ApiErrorResponse::MandateValidationFailed { + reason: "request amount is greater than mandate amount".to_string() + })), + ), + }?; + utils::when( + mandate + .mandate_currency + .map(|mandate_currency| mandate_currency.to_string() != request_currency) + .unwrap_or(true), + Err(report!(errors::ApiErrorResponse::MandateValidationFailed { + reason: "cross currency mandates not supported".to_string() + })), + ) +} + #[instrument(skip_all)] pub fn payment_attempt_status_fsm( payment_method_data: &Option<api::PaymentMethod>, @@ -1077,3 +1117,53 @@ pub fn hmac_sha256_sorted_query_params<'a>( pub fn check_if_operation_confirm<Op: std::fmt::Debug>(operations: Op) -> bool { format!("{:?}", operations) == "PaymentConfirm" } + +pub fn generate_mandate( + merchant_id: String, + connector: String, + setup_mandate_details: Option<api::MandateData>, + customer: &Option<storage::Customer>, + payment_method_id: String, +) -> Option<storage::MandateNew> { + match (setup_mandate_details, customer) { + (Some(data), Some(cus)) => { + let mandate_id = utils::generate_id(consts::ID_LENGTH, "man"); + + // The construction of the mandate new must be visible + let mut new_mandate = storage::MandateNew::default(); + + new_mandate + .set_mandate_id(mandate_id) + .set_customer_id(cus.customer_id.clone()) + .set_merchant_id(merchant_id) + .set_payment_method_id(payment_method_id) + .set_connector(connector) + .set_mandate_status(storage_enums::MandateStatus::Active) + .set_customer_ip_address( + data.customer_acceptance + .get_ip_address() + .map(masking::Secret::new), + ) + .set_customer_user_agent(data.customer_acceptance.get_user_agent()) + .set_customer_accepted_at(Some(data.customer_acceptance.get_accepted_at())); + + Some(match data.mandate_type { + api::MandateType::SingleUse(data) => new_mandate + .set_mandate_amount(Some(data.amount)) + .set_mandate_currency(Some(data.currency)) + .set_mandate_type(storage_enums::MandateType::SingleUse) + .to_owned(), + + api::MandateType::MultiUse(op_data) => match op_data { + Some(data) => new_mandate + .set_mandate_amount(Some(data.amount)) + .set_mandate_currency(Some(data.currency)), + None => &mut new_mandate, + } + .set_mandate_type(storage_enums::MandateType::MultiUse) + .to_owned(), + }) + } + (_, _) => None, + } +} diff --git a/crates/router/src/schema.rs b/crates/router/src/schema.rs index dbb330e0a6f..c719ba473a9 100644 --- a/crates/router/src/schema.rs +++ b/crates/router/src/schema.rs @@ -127,8 +127,11 @@ diesel::table! { network_transaction_id -> Nullable<Varchar>, previous_transaction_id -> Nullable<Varchar>, created_at -> Timestamp, - single_use_amount -> Nullable<Int4>, - single_use_currency -> Nullable<Currency>, + mandate_amount -> Nullable<Int4>, + mandate_currency -> Nullable<Currency>, + amount_captured -> Nullable<Int4>, + connector -> Varchar, + connector_mandate_id -> Nullable<Varchar>, } } diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index e593afdfb5b..e2b3b723276 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -154,11 +154,16 @@ pub struct MandateData { pub mandate_type: MandateType, } -#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] +#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateType { - SingleUse(storage::SingleUseMandate), - #[default] - MultiUse, + SingleUse(storage::MandateAmountData), + MultiUse(Option<storage::MandateAmountData>), +} + +impl Default for MandateType { + fn default() -> Self { + Self::MultiUse(None) + } } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] diff --git a/crates/router/src/types/storage/mandate.rs b/crates/router/src/types/storage/mandate.rs index d9d251e4da0..7d00d1e5096 100644 --- a/crates/router/src/types/storage/mandate.rs +++ b/crates/router/src/types/storage/mandate.rs @@ -24,8 +24,11 @@ pub struct Mandate { pub network_transaction_id: Option<String>, pub previous_transaction_id: Option<String>, pub created_at: PrimitiveDateTime, - pub single_use_amount: Option<i32>, - pub single_use_currency: Option<storage_enums::Currency>, + pub mandate_amount: Option<i32>, + pub mandate_currency: Option<storage_enums::Currency>, + pub amount_captured: Option<i32>, + pub connector: String, + pub connector_mandate_id: Option<String>, } #[derive( @@ -45,8 +48,11 @@ pub struct MandateNew { pub network_transaction_id: Option<String>, pub previous_transaction_id: Option<String>, pub created_at: Option<PrimitiveDateTime>, - pub single_use_amount: Option<i32>, - pub single_use_currency: Option<storage_enums::Currency>, + pub mandate_amount: Option<i32>, + pub mandate_currency: Option<storage_enums::Currency>, + pub amount_captured: Option<i32>, + pub connector: String, + pub connector_mandate_id: String, } #[derive(Debug)] @@ -54,10 +60,13 @@ pub enum MandateUpdate { StatusUpdate { mandate_status: storage_enums::MandateStatus, }, + CaptureAmountUpdate { + amount_captured: Option<i32>, + }, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] -pub struct SingleUseMandate { +pub struct MandateAmountData { pub amount: i32, pub currency: storage_enums::Currency, } @@ -65,13 +74,21 @@ pub struct SingleUseMandate { #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = mandate)] pub(super) struct MandateUpdateInternal { - mandate_status: storage_enums::MandateStatus, + mandate_status: Option<storage_enums::MandateStatus>, + amount_captured: Option<i32>, } impl From<MandateUpdate> for MandateUpdateInternal { fn from(mandate_update: MandateUpdate) -> Self { match mandate_update { - MandateUpdate::StatusUpdate { mandate_status } => Self { mandate_status }, + MandateUpdate::StatusUpdate { mandate_status } => Self { + mandate_status: Some(mandate_status), + amount_captured: None, + }, + MandateUpdate::CaptureAmountUpdate { amount_captured } => Self { + mandate_status: None, + amount_captured, + }, } } } diff --git a/migrations/2022-12-09-102635_mandate-connector-and-amount/down.sql b/migrations/2022-12-09-102635_mandate-connector-and-amount/down.sql new file mode 100644 index 00000000000..f0ef5bd2a0e --- /dev/null +++ b/migrations/2022-12-09-102635_mandate-connector-and-amount/down.sql @@ -0,0 +1,9 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE mandate +RENAME COLUMN mandate_amount TO single_use_amount; +ALTER TABLE mandate +RENAME COLUMN mandate_currency TO single_use_currency; +ALTER TABLE mandate +DROP COLUMN IF EXISTS amount_captured, +DROP COLUMN IF EXISTS connector, +DROP COLUMN IF EXISTS connector_mandate_id; \ No newline at end of file diff --git a/migrations/2022-12-09-102635_mandate-connector-and-amount/up.sql b/migrations/2022-12-09-102635_mandate-connector-and-amount/up.sql new file mode 100644 index 00000000000..b0966183870 --- /dev/null +++ b/migrations/2022-12-09-102635_mandate-connector-and-amount/up.sql @@ -0,0 +1,9 @@ +-- Your SQL goes here +ALTER TABLE mandate +RENAME COLUMN single_use_amount TO mandate_amount; +ALTER TABLE mandate +RENAME COLUMN single_use_currency TO mandate_currency; +ALTER TABLE mandate +ADD IF NOT EXISTS amount_captured INTEGER DEFAULT NULL, +ADD IF NOT EXISTS connector VARCHAR(255) NOT NULL DEFAULT 'dummy', +ADD IF NOT EXISTS connector_mandate_id VARCHAR(255) DEFAULT NULL; \ No newline at end of file
feat
added amount based validation and database fields (#99)
f70f10aac58cce805b150badf634271c0f98d478
2023-05-11 16:36:47
Arvind Patel
feat(connector): [bitpay] Add new crypto connector bitpay & testcases for all crypto connectors (#919)
false
diff --git a/Cargo.lock b/Cargo.lock index a310cff5c1a..3ef85ac8f6a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2968,7 +2968,7 @@ dependencies = [ [[package]] name = "opentelemetry" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "opentelemetry_api", "opentelemetry_sdk", @@ -2977,7 +2977,7 @@ dependencies = [ [[package]] name = "opentelemetry-otlp" version = "0.11.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "async-trait", "futures", @@ -2994,7 +2994,7 @@ dependencies = [ [[package]] name = "opentelemetry-proto" version = "0.1.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "futures", "futures-util", @@ -3006,7 +3006,7 @@ dependencies = [ [[package]] name = "opentelemetry_api" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "fnv", "futures-channel", @@ -3021,7 +3021,7 @@ dependencies = [ [[package]] name = "opentelemetry_sdk" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "async-trait", "crossbeam-channel", diff --git a/config/config.example.toml b/config/config.example.toml index bda27142478..c0cf57015f4 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -150,6 +150,7 @@ airwallex.base_url = "https://api-demo.airwallex.com/" applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" +bitpay.base_url = "https://test.bitpay.com" bluesnap.base_url = "https://sandbox.bluesnap.com/" braintree.base_url = "https://api.sandbox.braintreegateway.com/" checkout.base_url = "https://api.sandbox.checkout.com/" diff --git a/config/development.toml b/config/development.toml index b537128d784..2aa9dc58d1d 100644 --- a/config/development.toml +++ b/config/development.toml @@ -57,6 +57,7 @@ cards = [ "airwallex", "authorizedotnet", "bambora", + "bitpay", "bluesnap", "braintree", "checkout", @@ -104,6 +105,7 @@ airwallex.base_url = "https://api-demo.airwallex.com/" applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" +bitpay.base_url = "https://test.bitpay.com" bluesnap.base_url = "https://sandbox.bluesnap.com/" braintree.base_url = "https://api.sandbox.braintreegateway.com/" checkout.base_url = "https://api.sandbox.checkout.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 10f5129c778..072dd4108a2 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -74,6 +74,7 @@ airwallex.base_url = "https://api-demo.airwallex.com/" applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" +bitpay.base_url = "https://test.bitpay.com" bluesnap.base_url = "https://sandbox.bluesnap.com/" braintree.base_url = "https://api.sandbox.braintreegateway.com/" checkout.base_url = "https://api.sandbox.checkout.com/" @@ -113,6 +114,7 @@ cards = [ "airwallex", "authorizedotnet", "bambora", + "bitpay", "bluesnap", "braintree", "checkout", diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 2deab45a86d..0f5b109da57 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -586,6 +586,7 @@ pub enum Connector { Airwallex, Applepay, Authorizedotnet, + Bitpay, Bluesnap, Braintree, Checkout, @@ -664,6 +665,7 @@ pub enum RoutableConnectors { Adyen, Airwallex, Authorizedotnet, + Bitpay, Bambora, Bluesnap, Braintree, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 7f81bfc6d0a..4e731193484 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -359,6 +359,7 @@ pub struct Connectors { pub applepay: ConnectorParams, pub authorizedotnet: ConnectorParams, pub bambora: ConnectorParams, + pub bitpay: ConnectorParams, pub bluesnap: ConnectorParams, pub braintree: ConnectorParams, pub checkout: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index a57ba2998fe..1b0298214e2 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -3,6 +3,7 @@ pub mod adyen; pub mod airwallex; pub mod authorizedotnet; pub mod bambora; +pub mod bitpay; pub mod bluesnap; pub mod braintree; pub mod checkout; @@ -38,7 +39,7 @@ pub mod mollie; pub use self::dummyconnector::DummyConnector; pub use self::{ aci::Aci, adyen::Adyen, airwallex::Airwallex, authorizedotnet::Authorizedotnet, - bambora::Bambora, bluesnap::Bluesnap, braintree::Braintree, checkout::Checkout, + bambora::Bambora, bitpay::Bitpay, bluesnap::Bluesnap, braintree::Braintree, checkout::Checkout, coinbase::Coinbase, cybersource::Cybersource, dlocal::Dlocal, fiserv::Fiserv, forte::Forte, globalpay::Globalpay, iatapay::Iatapay, klarna::Klarna, mollie::Mollie, multisafepay::Multisafepay, nexinets::Nexinets, nuvei::Nuvei, opennode::Opennode, diff --git a/crates/router/src/connector/bitpay.rs b/crates/router/src/connector/bitpay.rs new file mode 100644 index 00000000000..703302399f8 --- /dev/null +++ b/crates/router/src/connector/bitpay.rs @@ -0,0 +1,533 @@ +mod transformers; + +use std::fmt::Debug; + +use common_utils::{errors::ReportSwitchExt, ext_traits::ByteSliceExt}; +use error_stack::ResultExt; +use transformers as bitpay; + +use self::bitpay::BitpayWebhookDetails; +use crate::{ + configs::settings, + core::errors::{self, CustomResult}, + headers, + services::{self, ConnectorIntegration}, + types::{ + self, + api::{self, ConnectorCommon, ConnectorCommonExt}, + ErrorResponse, Response, + }, + utils::{self, BytesExt, Encode}, +}; + +#[derive(Debug, Clone)] +pub struct Bitpay; + +impl api::Payment for Bitpay {} +impl api::PaymentToken for Bitpay {} +impl api::PaymentSession for Bitpay {} +impl api::ConnectorAccessToken for Bitpay {} +impl api::PreVerify for Bitpay {} +impl api::PaymentAuthorize for Bitpay {} +impl api::PaymentSync for Bitpay {} +impl api::PaymentCapture for Bitpay {} +impl api::PaymentVoid for Bitpay {} +impl api::Refund for Bitpay {} +impl api::RefundExecute for Bitpay {} +impl api::RefundSync for Bitpay {} + +impl + ConnectorIntegration< + api::PaymentMethodToken, + types::PaymentMethodTokenizationData, + types::PaymentsResponseData, + > for Bitpay +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Bitpay +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + _req: &types::RouterData<Flow, Request, Response>, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let header = vec![ + ( + headers::CONTENT_TYPE.to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), + ), + (headers::X_ACCEPT_VERSION.to_string(), "2.0.0".to_string()), + ]; + Ok(header) + } +} + +impl ConnectorCommon for Bitpay { + fn id(&self) -> &'static str { + "bitpay" + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.bitpay.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let auth = bitpay::BitpayAuthType::try_from(auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![(headers::AUTHORIZATION.to_string(), auth.api_key)]) + } + + fn build_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: bitpay::BitpayErrorResponse = + res.response.parse_struct("BitpayErrorResponse").switch()?; + + Ok(ErrorResponse { + status_code: res.status_code, + code: response.code, + message: response.message, + reason: response.reason, + }) + } +} + +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Bitpay +{ + //TODO: implement sessions flow +} + +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Bitpay +{ +} + +impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData> + for Bitpay +{ +} + +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Bitpay +{ + fn get_headers( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}/invoices", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &types::PaymentsAuthorizeRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let req_obj = bitpay::BitpayPaymentsRequest::try_from(req)?; + let bitpay_req = + utils::Encode::<bitpay::BitpayPaymentsRequest>::encode_to_string_of_json(&req_obj) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(bitpay_req)) + } + + fn build_request( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + res: Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: bitpay::BitpayPaymentsResponse = res + .response + .parse_struct("Bitpay PaymentsAuthorizeResponse") + .switch()?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Bitpay +{ + fn get_headers( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let auth = bitpay::BitpayAuthType::try_from(&req.connector_auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let connector_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + Ok(format!( + "{}/invoices/{}?token={}", + self.base_url(connectors), + connector_id, + auth.api_key + )) + } + + fn build_request( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::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: &types::PaymentsSyncRouterData, + res: Response, + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + let response: bitpay::BitpayPaymentsResponse = res + .response + .parse_struct("bitpay PaymentsSyncResponse") + .switch()?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for Bitpay +{ + fn get_headers( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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::PaymentsCaptureRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + _req: &types::PaymentsCaptureRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + } + + fn build_request( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCaptureRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + let response: bitpay::BitpayPaymentsResponse = res + .response + .parse_struct("Bitpay PaymentsCaptureResponse") + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for Bitpay +{ +} + +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Bitpay { + fn get_headers( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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::RefundsRouterData<api::Execute>, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &types::RefundsRouterData<api::Execute>, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let req_obj = bitpay::BitpayRefundRequest::try_from(req)?; + let bitpay_req = + utils::Encode::<bitpay::BitpayRefundRequest>::encode_to_string_of_json(&req_obj) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(bitpay_req)) + } + + fn build_request( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .body(types::RefundExecuteType::get_request_body(self, req)?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::RefundsRouterData<api::Execute>, + res: Response, + ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + let response: bitpay::RefundResponse = + res.response + .parse_struct("bitpay RefundResponse") + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Bitpay { + fn get_headers( + &self, + req: &types::RefundSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, 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::RefundSyncRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &types::RefundSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .body(types::RefundSyncType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::RefundSyncRouterData, + res: Response, + ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + let response: bitpay::RefundResponse = res + .response + .parse_struct("bitpay RefundSyncResponse") + .switch()?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Bitpay { + fn get_webhook_object_reference_id( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { + let notif: BitpayWebhookDetails = request + .body + .parse_struct("BitpayWebhookDetails") + .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId(notif.data.id), + )) + } + + fn get_webhook_event_type( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + let notif: BitpayWebhookDetails = request + .body + .parse_struct("BitpayWebhookDetails") + .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; + match notif.event.name { + bitpay::WebhookEventType::Confirmed | bitpay::WebhookEventType::Completed => { + Ok(api::IncomingWebhookEvent::PaymentIntentSuccess) + } + bitpay::WebhookEventType::Paid => { + Ok(api::IncomingWebhookEvent::PaymentIntentProcessing) + } + bitpay::WebhookEventType::Declined => { + Ok(api::IncomingWebhookEvent::PaymentIntentFailure) + } + _ => Ok(api::IncomingWebhookEvent::EventNotSupported), + } + } + + fn get_webhook_resource_object( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<serde_json::Value, errors::ConnectorError> { + let notif: BitpayWebhookDetails = request + .body + .parse_struct("BitpayWebhookDetails") + .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; + Encode::<BitpayWebhookDetails>::encode_to_value(&notif) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed) + } +} diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs new file mode 100644 index 00000000000..92626abd7d0 --- /dev/null +++ b/crates/router/src/connector/bitpay/transformers.rs @@ -0,0 +1,287 @@ +use reqwest::Url; +use serde::{Deserialize, Serialize}; + +use crate::{ + connector::utils::PaymentsAuthorizeRequestData, + core::errors, + services, + types::{self, api, storage::enums, ConnectorAuthType}, +}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum TransactionSpeed { + Low, + #[default] + Medium, + High, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct BitpayPaymentsRequest { + price: i64, + currency: String, + #[serde(rename = "redirectURL")] + redirect_url: String, + #[serde(rename = "notificationURL")] + notification_url: String, + transaction_speed: TransactionSpeed, + token: String, +} + +impl TryFrom<&types::PaymentsAuthorizeRouterData> for BitpayPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + get_crypto_specific_payment_data(item) + } +} + +// Auth Struct +pub struct BitpayAuthType { + pub(super) api_key: String, +} + +impl TryFrom<&ConnectorAuthType> for BitpayAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + api_key: api_key.to_string(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} +// PaymentsResponse +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum BitpayPaymentStatus { + #[default] + New, + Paid, + Confirmed, + Complete, + Expired, + Invalid, +} + +impl From<BitpayPaymentStatus> for enums::AttemptStatus { + fn from(item: BitpayPaymentStatus) -> Self { + match item { + BitpayPaymentStatus::New => Self::AuthenticationPending, + BitpayPaymentStatus::Complete | BitpayPaymentStatus::Confirmed => Self::Charged, + BitpayPaymentStatus::Expired => Self::Failure, + _ => Self::Pending, + } + } +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ExceptionStatus { + #[default] + Unit, + Bool(bool), + String(String), +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BitpayPaymentResponseData { + pub url: Option<Url>, + pub status: BitpayPaymentStatus, + pub price: i64, + pub currency: String, + pub amount_paid: i64, + pub invoice_time: Option<i64>, + pub rate_refresh_time: Option<i64>, + pub expiration_time: Option<i64>, + pub current_time: Option<i64>, + pub id: String, + pub low_fee_detected: Option<bool>, + pub display_amount_paid: Option<String>, + pub exception_status: ExceptionStatus, + pub redirect_url: Option<String>, + pub refund_address_request_pending: Option<bool>, + pub merchant_name: Option<String>, + pub token: Option<String>, +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct BitpayPaymentsResponse { + data: BitpayPaymentResponseData, + facade: Option<String>, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, BitpayPaymentsResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, BitpayPaymentsResponse, T, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let redirection_data = item + .response + .data + .url + .map(|x| services::RedirectForm::from((x, services::Method::Get))); + let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id); + let attempt_status = item.response.data.status; + Ok(Self { + status: enums::AttemptStatus::from(attempt_status), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: connector_id, + redirection_data, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + }), + ..item.data + }) + } +} + +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct BitpayRefundRequest { + pub amount: i64, +} + +impl<F> TryFrom<&types::RefundsRouterData<F>> for BitpayRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.request.amount, + }) + } +} + +// 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<types::RefundsResponseRouterData<api::Execute, RefundResponse>> + for types::RefundsRouterData<api::Execute> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> + for types::RefundsRouterData<api::RSync> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct BitpayErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, +} + +fn get_crypto_specific_payment_data( + item: &types::PaymentsAuthorizeRouterData, +) -> Result<BitpayPaymentsRequest, error_stack::Report<errors::ConnectorError>> { + let price = item.request.amount; + let currency = item.request.currency.to_string(); + let redirect_url = item.request.get_return_url()?; + let notification_url = item.request.get_webhook_url()?; + let transaction_speed = TransactionSpeed::Medium; + let auth_type = item.connector_auth_type.clone(); + let token = match auth_type { + ConnectorAuthType::HeaderKey { api_key } => api_key, + _ => String::default(), + }; + + Ok(BitpayPaymentsRequest { + price, + currency, + redirect_url, + notification_url, + transaction_speed, + token, + }) +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct BitpayWebhookDetails { + pub event: Event, + pub data: BitpayPaymentResponseData, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Event { + pub code: i64, + pub name: WebhookEventType, +} + +#[derive(Debug, Serialize, Deserialize)] +pub enum WebhookEventType { + #[serde(rename = "invoice_paidInFull")] + Paid, + #[serde(rename = "invoice_confirmed")] + Confirmed, + #[serde(rename = "invoice_completed")] + Completed, + #[serde(rename = "invoice_expired")] + Expired, + #[serde(rename = "invoice_failedToConfirm")] + Invalid, + #[serde(rename = "invoice_declined")] + Declined, + #[serde(rename = "invoice_refundComplete")] + Refunded, + #[serde(rename = "invoice_manuallyNotified")] + Resent, +} diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 278a1dd24e2..6e8fe22685d 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -107,6 +107,7 @@ default_imp_for_complete_authorize!( connector::Aci, connector::Adyen, connector::Authorizedotnet, + connector::Bitpay, connector::Braintree, connector::Checkout, connector::Coinbase, @@ -153,6 +154,7 @@ default_imp_for_create_customer!( connector::Airwallex, connector::Authorizedotnet, connector::Bambora, + connector::Bitpay, connector::Braintree, connector::Checkout, connector::Coinbase, @@ -203,6 +205,7 @@ default_imp_for_connector_redirect_response!( connector::Aci, connector::Adyen, connector::Authorizedotnet, + connector::Bitpay, connector::Braintree, connector::Coinbase, connector::Cybersource, @@ -239,6 +242,7 @@ default_imp_for_connector_request_id!( connector::Airwallex, connector::Authorizedotnet, connector::Bambora, + connector::Bitpay, connector::Bluesnap, connector::Braintree, connector::Checkout, @@ -290,6 +294,7 @@ default_imp_for_accept_dispute!( connector::Airwallex, connector::Authorizedotnet, connector::Bambora, + connector::Bitpay, connector::Bluesnap, connector::Braintree, connector::Coinbase, @@ -350,6 +355,7 @@ default_imp_for_file_upload!( connector::Airwallex, connector::Authorizedotnet, connector::Bambora, + connector::Bitpay, connector::Bluesnap, connector::Braintree, connector::Coinbase, @@ -400,6 +406,7 @@ default_imp_for_submit_evidence!( connector::Airwallex, connector::Authorizedotnet, connector::Bambora, + connector::Bitpay, connector::Bluesnap, connector::Braintree, connector::Cybersource, @@ -450,6 +457,7 @@ default_imp_for_defend_dispute!( connector::Airwallex, connector::Authorizedotnet, connector::Bambora, + connector::Bitpay, connector::Bluesnap, connector::Braintree, connector::Cybersource, diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index fb2ea5b073b..6a1524dc998 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -61,6 +61,7 @@ pub mod headers { pub const X_TRANS_KEY: &str = "X-Trans-Key"; pub const X_VERSION: &str = "X-Version"; pub const X_CC_VERSION: &str = "X-CC-Version"; + pub const X_ACCEPT_VERSION: &str = "X-Accept-Version"; pub const X_DATE: &str = "X-Date"; } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 7af5f624299..d4d7807273c 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -203,6 +203,7 @@ impl ConnectorData { "airwallex" => Ok(Box::new(&connector::Airwallex)), "authorizedotnet" => Ok(Box::new(&connector::Authorizedotnet)), "bambora" => Ok(Box::new(&connector::Bambora)), + "bitpay" => Ok(Box::new(&connector::Bitpay)), "bluesnap" => Ok(Box::new(&connector::Bluesnap)), "braintree" => Ok(Box::new(&connector::Braintree)), "checkout" => Ok(Box::new(&connector::Checkout)), diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs new file mode 100644 index 00000000000..ebba241de1a --- /dev/null +++ b/crates/router/tests/connectors/bitpay.rs @@ -0,0 +1,145 @@ +use api_models::payments::CryptoData; +use masking::Secret; +use router::types::{self, api, storage::enums, PaymentAddress}; + +use crate::{ + connector_auth, + utils::{self, ConnectorActions}, +}; + +#[derive(Clone, Copy)] +struct BitpayTest; +impl ConnectorActions for BitpayTest {} +impl utils::Connector for BitpayTest { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Bitpay; + types::api::ConnectorData { + connector: Box::new(&Bitpay), + connector_name: types::Connector::Bitpay, + get_token: types::api::GetToken::Connector, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + connector_auth::ConnectorAuthentication::new() + .bitpay + .expect("Missing connector authentication configuration"), + ) + } + + fn get_name(&self) -> String { + "bitpay".to_string() + } +} + +static CONNECTOR: BitpayTest = BitpayTest {}; + +fn get_default_payment_info() -> Option<utils::PaymentInfo> { + Some(utils::PaymentInfo { + address: Some(PaymentAddress { + billing: Some(api::Address { + address: Some(api::AddressDetails { + first_name: Some(Secret::new("first".to_string())), + last_name: Some(Secret::new("last".to_string())), + line1: Some(Secret::new("line1".to_string())), + line2: Some(Secret::new("line2".to_string())), + city: Some("city".to_string()), + zip: Some(Secret::new("zip".to_string())), + country: Some(api_models::enums::CountryAlpha2::IN), + ..Default::default() + }), + phone: Some(api::PhoneDetails { + number: Some(Secret::new("1234567890".to_string())), + country_code: Some("+91".to_string()), + }), + }), + ..Default::default() + }), + ..Default::default() + }) +} + +fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { + Some(types::PaymentsAuthorizeData { + amount: 1, + currency: enums::Currency::USD, + payment_method_data: types::api::PaymentMethodData::Crypto(CryptoData {}), + confirm: true, + statement_descriptor_suffix: None, + statement_descriptor: None, + setup_future_usage: None, + mandate_id: None, + off_session: None, + setup_mandate_details: None, + // capture_method: Some(capture_method), + browser_info: None, + order_details: None, + email: None, + payment_experience: None, + payment_method_type: None, + session_token: None, + enrolled_for_3ds: false, + related_transaction_id: None, + router_return_url: Some(String::from("https://google.com/")), + webhook_url: Some(String::from("https://google.com/")), + complete_authorize_url: None, + capture_method: None, + }) +} + +// Creates a payment using the manual capture flow +#[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"); + let resp = response.clone().response.ok().unwrap(); + assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending); + let endpoint = match resp { + types::PaymentsResponseData::TransactionResponse { + redirection_data, .. + } => Some(redirection_data), + _ => None, + }; + assert!(endpoint.is_some()) +} + +// Synchronizes a successful transaction. +#[actix_web::test] +async fn should_sync_authorized_payment() { + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + "NPf27TDfyU5mhcTCw2oaq4".to_string(), + ), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a expired transaction. +#[actix_web::test] +async fn should_sync_expired_payment() { + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + "bUsFf4RjQEahjbjGcETRS".to_string(), + ), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Failure); +} diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs index 2a01ed7c621..9ad2a4dd056 100644 --- a/crates/router/tests/connectors/coinbase.rs +++ b/crates/router/tests/connectors/coinbase.rs @@ -1,7 +1,7 @@ -use std::str::FromStr; - +use api_models::payments::CryptoData; use masking::Secret; -use router::types::{self, api, storage::enums}; +use router::types::{self, api, storage::enums, PaymentAddress}; +use serde_json::json; use crate::{ connector_auth, @@ -37,65 +37,86 @@ impl utils::Connector for CoinbaseTest { static CONNECTOR: CoinbaseTest = CoinbaseTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { - None + Some(utils::PaymentInfo { + address: Some(PaymentAddress { + billing: Some(api::Address { + address: Some(api::AddressDetails { + first_name: Some(Secret::new("first".to_string())), + last_name: Some(Secret::new("last".to_string())), + line1: Some(Secret::new("line1".to_string())), + line2: Some(Secret::new("line2".to_string())), + city: Some("city".to_string()), + zip: Some(Secret::new("zip".to_string())), + country: Some(api_models::enums::CountryAlpha2::IN), + ..Default::default() + }), + phone: Some(api::PhoneDetails { + number: Some(Secret::new("1234567890".to_string())), + country_code: Some("+91".to_string()), + }), + }), + ..Default::default() + }), + connector_meta_data: Some(json!({"pricing_type": "fixed_price"})), + ..Default::default() + }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { - None -} - -// Cards Positive Tests -// Creates a payment using the manual capture flow (Non 3DS). + Some(types::PaymentsAuthorizeData { + amount: 1, + currency: enums::Currency::USD, + payment_method_data: types::api::PaymentMethodData::Crypto(CryptoData {}), + confirm: true, + statement_descriptor_suffix: None, + statement_descriptor: None, + setup_future_usage: None, + mandate_id: None, + off_session: None, + setup_mandate_details: None, + // capture_method: Some(capture_method), + browser_info: None, + order_details: None, + email: None, + payment_experience: None, + payment_method_type: None, + session_token: None, + enrolled_for_3ds: false, + related_transaction_id: None, + router_return_url: Some(String::from("https://google.com/")), + webhook_url: None, + complete_authorize_url: None, + capture_method: None, + }) +} + +// Creates a payment using the manual capture flow #[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); + assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending); + let resp = response.response.ok().unwrap(); + let endpoint = match resp { + types::PaymentsResponseData::TransactionResponse { + redirection_data, .. + } => Some(redirection_data), + _ => None, + }; + assert!(endpoint.is_some()) } -// 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). +// Synchronizes a successful transaction. #[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: router::types::ResponseId::ConnectorTransactionId( - txn_id.unwrap(), + "ADFY3789".to_string(), ), ..Default::default() }), @@ -103,342 +124,62 @@ async fn should_sync_authorized_payment() { ) .await .expect("PSync response"); - assert_eq!(response.status, enums::AttemptStatus::Authorized,); + assert_eq!(response.status, enums::AttemptStatus::Charged); } -// Voids a payment using the manual capture flow (Non 3DS). +// Synchronizes a unresovled(underpaid) transaction. #[actix_web::test] -async fn should_void_authorized_payment() { +async fn should_sync_unresolved_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()), + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + "YJ6RFZXZ".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); + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Unresolved); } -// Synchronizes a payment using the automatic capture flow (Non 3DS). +// Synchronizes a expired transaction. #[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"); +async fn should_sync_expired_payment() { let response = CONNECTOR .psync_retry_till_status_matches( - enums::AttemptStatus::Charged, + enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( - txn_id.unwrap(), + "FZ89KDDB".to_string(), ), - 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 scenerios -// Creates a payment with incorrect card number. -#[actix_web::test] -async fn should_fail_payment_for_incorrect_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: cards::CardNumber::from_str("1234567891011").unwrap(), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - get_default_payment_info(), - ) - .await - .unwrap(); - assert_eq!( - response.response.unwrap_err().message, - "Your card number is incorrect.".to_string(), - ); -} - -// 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: types::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: types::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'") - ); + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Failure); } -// Refunds a payment with refund amount higher than payment amount. +// Synchronizes a cancelled transaction. #[actix_web::test] -async fn should_fail_for_refund_amount_higher_than_payment_amount() { +async fn should_sync_cancelled_payment() { let response = CONNECTOR - .make_payment_and_refund( - payment_method_details(), - Some(types::RefundsData { - refund_amount: 150, - ..utils::PaymentRefundType::default().0 + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + "C35AAXKF".to_string(), + ), + ..Default::default() }), get_default_payment_info(), ) .await - .unwrap(); - assert_eq!( - response.response.unwrap_err().message, - "Refund amount (₹1.50) is greater than charge amount (₹1.00)", - ); + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Voided); } - -// Connector dependent test cases goes here - -// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index 0613f1a84a7..e42b579b542 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -10,6 +10,7 @@ pub(crate) struct ConnectorAuthentication { pub airwallex: Option<BodyKey>, pub authorizedotnet: Option<BodyKey>, pub bambora: Option<BodyKey>, + pub bitpay: Option<HeaderKey>, pub bluesnap: Option<BodyKey>, pub checkout: Option<SignatureKey>, pub coinbase: Option<HeaderKey>, diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 766a67029bb..ba31db4cb10 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -11,6 +11,7 @@ mod adyen_ui; mod airwallex; mod authorizedotnet; mod bambora; +mod bitpay; mod bluesnap; mod checkout; mod coinbase; diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs index 8d568789131..06aeb5c4c23 100644 --- a/crates/router/tests/connectors/opennode.rs +++ b/crates/router/tests/connectors/opennode.rs @@ -1,7 +1,6 @@ -use std::str::FromStr; - +use api_models::payments::CryptoData; use masking::Secret; -use router::types::{self, api, storage::enums}; +use router::types::{self, api, storage::enums, PaymentAddress}; use crate::{ connector_auth, @@ -37,65 +36,86 @@ impl utils::Connector for OpennodeTest { static CONNECTOR: OpennodeTest = OpennodeTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { - None + Some(utils::PaymentInfo { + address: Some(PaymentAddress { + billing: Some(api::Address { + address: Some(api::AddressDetails { + first_name: Some(Secret::new("first".to_string())), + last_name: Some(Secret::new("last".to_string())), + line1: Some(Secret::new("line1".to_string())), + line2: Some(Secret::new("line2".to_string())), + city: Some("city".to_string()), + zip: Some(Secret::new("zip".to_string())), + country: Some(api_models::enums::CountryAlpha2::IN), + ..Default::default() + }), + phone: Some(api::PhoneDetails { + number: Some(Secret::new("1234567890".to_string())), + country_code: Some("+91".to_string()), + }), + }), + ..Default::default() + }), + return_url: Some(String::from("https://google.com")), + ..Default::default() + }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { - None -} - -// Cards Positive Tests -// Creates a payment using the manual capture flow (Non 3DS). + Some(types::PaymentsAuthorizeData { + amount: 1, + currency: enums::Currency::USD, + payment_method_data: types::api::PaymentMethodData::Crypto(CryptoData {}), + confirm: true, + statement_descriptor_suffix: None, + statement_descriptor: None, + setup_future_usage: None, + mandate_id: None, + off_session: None, + setup_mandate_details: None, + // capture_method: Some(capture_method), + browser_info: None, + order_details: None, + email: None, + payment_experience: None, + payment_method_type: None, + session_token: None, + enrolled_for_3ds: false, + related_transaction_id: None, + router_return_url: Some(String::from("https://google.com/")), + webhook_url: Some(String::from("https://google.com/")), + complete_authorize_url: None, + capture_method: None, + }) +} + +// Creates a payment using the manual capture flow #[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); + assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending); + let resp = response.response.ok().unwrap(); + let endpoint = match resp { + types::PaymentsResponseData::TransactionResponse { + redirection_data, .. + } => Some(redirection_data), + _ => None, + }; + assert!(endpoint.is_some()) } -// Synchronizes a payment using the manual capture flow (Non 3DS). +// Synchronizes a successful transaction. #[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: router::types::ResponseId::ConnectorTransactionId( - txn_id.unwrap(), + "5adebfb1-802e-432b-8b42-5db4b754b2eb".to_string(), ), ..Default::default() }), @@ -103,342 +123,43 @@ async fn should_sync_authorized_payment() { ) .await .expect("PSync response"); - assert_eq!(response.status, enums::AttemptStatus::Authorized,); + assert_eq!(response.status, enums::AttemptStatus::Charged); } -// Voids a payment using the manual capture flow (Non 3DS). +// Synchronizes a unresovled(underpaid) transaction. #[actix_web::test] -async fn should_void_authorized_payment() { +async fn should_sync_unresolved_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()), + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + "4cf63e6b-5135-49cb-997f-6e0b30fecebc".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); + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Unresolved); } -// Synchronizes a payment using the automatic capture flow (Non 3DS). +// Synchronizes a expired transaction. #[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"); +async fn should_sync_expired_payment() { let response = CONNECTOR .psync_retry_till_status_matches( - enums::AttemptStatus::Charged, + enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( - txn_id.unwrap(), + "c36a097a-5091-4317-8749-80343a71c1c4".to_string(), ), - 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 scenerios -// Creates a payment with incorrect card number. -#[actix_web::test] -async fn should_fail_payment_for_incorrect_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: cards::CardNumber::from_str("1234567891011").unwrap(), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - get_default_payment_info(), - ) - .await - .unwrap(); - assert_eq!( - response.response.unwrap_err().message, - "Your card number is incorrect.".to_string(), - ); -} - -// 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: types::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: types::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)", - ); + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Failure); } - -// Connector dependent test cases goes here - -// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 262ab819dda..0448e782eb1 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -97,6 +97,9 @@ api_key = "api_key" key1 = "key1" api_secret = "secret" +[bitpay] +api_key="API Key" + [iatapay] key1 = "key1" api_key = "api_key" diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 86571a26b50..5c5653fdc70 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -63,6 +63,7 @@ airwallex.base_url = "https://api-demo.airwallex.com/" applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" +bitpay.base_url = "https://test.bitpay.com" bluesnap.base_url = "https://sandbox.bluesnap.com/" braintree.base_url = "https://api.sandbox.braintreegateway.com/" checkout.base_url = "https://api.sandbox.checkout.com/" @@ -101,6 +102,7 @@ cards = [ "airwallex", "authorizedotnet", "bambora", + "bitpay", "bluesnap", "braintree", "checkout", diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 261513e1287..4430f7808ba 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -4,7 +4,7 @@ function find_prev_connector() { git checkout $self cp $self $self.tmp # add new connector to existing list and sort it - connectors=(aci adyen airwallex applepay authorizedotnet bambora bluesnap braintree checkout coinbase cybersource dlocal dummyconnector fiserv forte globalpay iatapay klarna mollie multisafepay nexinets nuvei opennode payeezy paypal payu rapyd shift4 stripe trustpay worldline worldpay "$1") + connectors=(aci adyen airwallex applepay authorizedotnet bambora bitpay bluesnap braintree checkout coinbase cybersource dlocal dummyconnector fiserv forte globalpay iatapay klarna mollie multisafepay nexinets nuvei opennode payeezy paypal payu rapyd shift4 stripe trustpay worldline worldpay "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res=`echo ${sorted[@]}` sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
feat
[bitpay] Add new crypto connector bitpay & testcases for all crypto connectors (#919)
46b40ecce540b61eced7156555c0fcdcec170405
2023-05-13 14:58:41
Sakil Mostak
feat(connector): [ACI] Implement Trustly Bank Redirect (#1130)
false
diff --git a/Cargo.lock b/Cargo.lock index 6cb3e124104..b504c3db426 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2970,7 +2970,7 @@ dependencies = [ [[package]] name = "opentelemetry" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "opentelemetry_api", "opentelemetry_sdk", @@ -2979,7 +2979,7 @@ dependencies = [ [[package]] name = "opentelemetry-otlp" version = "0.11.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "async-trait", "futures", @@ -2996,7 +2996,7 @@ dependencies = [ [[package]] name = "opentelemetry-proto" version = "0.1.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "futures", "futures-util", @@ -3008,7 +3008,7 @@ dependencies = [ [[package]] name = "opentelemetry_api" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "fnv", "futures-channel", @@ -3023,7 +3023,7 @@ dependencies = [ [[package]] name = "opentelemetry_sdk" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "async-trait", "crossbeam-channel", diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 59671836aeb..52e72fd2f3a 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -670,7 +670,11 @@ pub enum BankRedirectData { preferred_language: String, }, Swish {}, - Trustly {}, + Trustly { + /// The country for bank payment + #[schema(value_type = CountryAlpha2, example = "US")] + country: api_enums::CountryAlpha2, + }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 62b25c343e1..760dfa38091 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -74,8 +74,13 @@ pub struct BankRedirectionPMData { bank_account_bic: Option<Secret<String>>, #[serde(rename = "bankAccount.iban")] bank_account_iban: Option<Secret<String>>, + #[serde(rename = "billing.country")] + billing_country: Option<api_models::enums::CountryAlpha2>, #[serde(rename = "customer.email")] customer_email: Option<Email>, + #[serde(rename = "customer.merchantCustomerId")] + merchant_customer_id: Option<Secret<String>>, + merchant_transaction_id: Option<Secret<String>>, shopper_result_url: Option<String>, } @@ -151,6 +156,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { bank_account_bank_name: None, bank_account_bic: None, bank_account_iban: None, + billing_country: None, + merchant_customer_id: None, + merchant_transaction_id: None, customer_email: None, shopper_result_url: item.request.router_return_url.clone(), })) @@ -165,6 +173,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { bank_account_bank_name: None, bank_account_bic: bank_account_bic.clone(), bank_account_iban: bank_account_iban.clone(), + billing_country: None, + merchant_customer_id: None, + merchant_transaction_id: None, customer_email: None, shopper_result_url: item.request.router_return_url.clone(), })), @@ -175,6 +186,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { bank_account_bank_name: Some(bank_name.to_string()), bank_account_bic: None, bank_account_iban: None, + billing_country: None, + merchant_customer_id: None, + merchant_transaction_id: None, customer_email: None, shopper_result_url: item.request.router_return_url.clone(), })) @@ -186,6 +200,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { bank_account_bank_name: None, bank_account_bic: None, bank_account_iban: None, + billing_country: None, + merchant_customer_id: None, + merchant_transaction_id: None, customer_email: None, shopper_result_url: item.request.router_return_url.clone(), })) @@ -197,6 +214,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { bank_account_bank_name: None, bank_account_bic: None, bank_account_iban: None, + billing_country: None, + merchant_customer_id: None, + merchant_transaction_id: None, customer_email: Some(email.to_owned()), shopper_result_url: item.request.router_return_url.clone(), @@ -209,10 +229,33 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { bank_account_bank_name: None, bank_account_bic: None, bank_account_iban: None, + billing_country: None, + merchant_customer_id: None, + merchant_transaction_id: None, customer_email: Some(email.to_owned()), shopper_result_url: item.request.router_return_url.clone(), })) } + api_models::payments::BankRedirectData::Trustly { country } => { + PaymentDetails::BankRedirect(Box::new(BankRedirectionPMData { + payment_brand: PaymentBrand::Trustly, + bank_account_country: None, + bank_account_bank_name: None, + bank_account_bic: None, + bank_account_iban: None, + billing_country: Some(*country), + merchant_customer_id: Some(Secret::new( + item.customer_id.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "customer_id", + }, + )?, + )), + merchant_transaction_id: Some(Secret::new(item.payment_id.clone())), + customer_email: None, + shopper_result_url: item.request.router_return_url.clone(), + })) + } _ => Err(errors::ConnectorError::NotImplemented( "Payment method".to_string(), ))?, diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index d1d5b3ef359..57dfe7f3fcd 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1165,11 +1165,11 @@ impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod payment_type: PaymentType::Sofort, })), ), - api_models::payments::BankRedirectData::Trustly {} => Ok(AdyenPaymentMethod::Trustly( - Box::new(BankRedirectionPMData { + api_models::payments::BankRedirectData::Trustly { .. } => Ok( + AdyenPaymentMethod::Trustly(Box::new(BankRedirectionPMData { payment_type: PaymentType::Trustly, - }), - )), + })), + ), _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } }
feat
[ACI] Implement Trustly Bank Redirect (#1130)
54c0b218d9f20c6388dde0f30ea525011cdad573
2024-02-21 05:48:27
github-actions
chore(version): 2024.02.21.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 379079b0fe1..68013d44278 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,35 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.02.21.0 + +### Features + +- **analytics:** Added filter api for dispute analytics ([#3724](https://github.com/juspay/hyperswitch/pull/3724)) ([`6aeb440`](https://github.com/juspay/hyperswitch/commit/6aeb44091b34f202b60868028979b3720e3507ce)) +- **connector:** Accept connector_transaction_id in 2xx and 4xx error_response of connector flows for Adyen ([#3703](https://github.com/juspay/hyperswitch/pull/3703)) ([`236c5ba`](https://github.com/juspay/hyperswitch/commit/236c5baeda69721513c91682edca54facb947536)) + +### Bug Fixes + +- **config:** Add update mandate config in docker_compose ([#3732](https://github.com/juspay/hyperswitch/pull/3732)) ([`d541953`](https://github.com/juspay/hyperswitch/commit/d541953693ef7292fce2f4b2c39fe2cd5cddccbf)) +- Remove status_code being printed in EndRequest log ([#3722](https://github.com/juspay/hyperswitch/pull/3722)) ([`cf3c666`](https://github.com/juspay/hyperswitch/commit/cf3c66636ffee30cdd4353b276a89a8f9fc2d9d0)) + +### Refactors + +- **connector:** [ADYEN] Capture error reason in case of 2xx and 4xx failure ([#3708](https://github.com/juspay/hyperswitch/pull/3708)) ([`1c933a0`](https://github.com/juspay/hyperswitch/commit/1c933a08a9cad0980a4d14dd9b641995d0f4e659)) +- **connectors:** + - [Bitpay] PII data masking ([#3704](https://github.com/juspay/hyperswitch/pull/3704)) ([`1c92328`](https://github.com/juspay/hyperswitch/commit/1c9232820e4821652112b21863e1910b3dd6be3b)) + - [Bambora] data masking ([#3695](https://github.com/juspay/hyperswitch/pull/3695)) ([`e5e4485`](https://github.com/juspay/hyperswitch/commit/e5e44857d21af9db8dee580e276028de76c7d278)) + - [BOA] PII data masking ([#3702](https://github.com/juspay/hyperswitch/pull/3702)) ([`49c71d0`](https://github.com/juspay/hyperswitch/commit/49c71d093e7e01b241ab29e3bb7b0c724b399aaf)) +- **merchant_connector_account:** Change unique constraint to connector label ([#3091](https://github.com/juspay/hyperswitch/pull/3091)) ([`073310c`](https://github.com/juspay/hyperswitch/commit/073310c1f671ccbb71cc5c8725eca9771e511589)) + +### Miscellaneous Tasks + +- **postman:** Update Postman collection files ([`421b9e8`](https://github.com/juspay/hyperswitch/commit/421b9e8f463949aca82e74e4259c88950f2bf15a)) + +**Full Changelog:** [`2024.02.20.0...2024.02.21.0`](https://github.com/juspay/hyperswitch/compare/2024.02.20.0...2024.02.21.0) + +- - - + ## 2024.02.20.0 ### Features
chore
2024.02.21.0
2d9df53491b1ef662736efec60ec5e5368466bb4
2025-02-20 01:50:45
Suman Maji
fix(connector): [SCRIPT] Update template generating script and updated connector doc (#7301)
false
diff --git a/add_connector_updated.md b/add_connector_updated.md new file mode 100644 index 00000000000..4ee8c895656 --- /dev/null +++ b/add_connector_updated.md @@ -0,0 +1,720 @@ +# Guide to Integrating a Connector + +## Table of Contents + +1. [Introduction](#introduction) +2. [Prerequisites](#prerequisites) +3. [Understanding Connectors and Payment Methods](#understanding-connectors-and-payment-methods) +4. [Integration Steps](#integration-steps) + - [Generate Template](#generate-template) + - [Implement Request & Response Types](#implement-request--response-types) + - [Implement transformers.rs](#implementing-transformersrs) + - [Handle Response Mapping](#handle-response-mapping) + - [Recommended Fields for Connector Request and Response](#recommended-fields-for-connector-request-and-response) + - [Error Handling](#error-handling) +5. [Implementing the Traits](#implementing-the-traits) + - [ConnectorCommon](#connectorcommon) + - [ConnectorIntegration](#connectorintegration) + - [ConnectorCommonExt](#connectorcommonext) + - [Other Traits](#othertraits) +6. [Set the Currency Unit](#set-the-currency-unit) +7. [Connector utility functions](#connector-utility-functions) +8. [Connector configs for control center](#connector-configs-for-control-center) +9. [Update `ConnectorTypes.res` and `ConnectorUtils.res`](#update-connectortypesres-and-connectorutilsres) +10. [Add Connector Icon](#add-connector-icon) +11. [Test the Connector](#test-the-connector) +12. [Build Payment Request and Response from JSON Schema](#build-payment-request-and-response-from-json-schema) + +## Introduction + +This guide provides instructions on integrating a new connector with Router, from setting up the environment to implementing API interactions. + +## Prerequisites + +- Familiarity with the Connector API you’re integrating +- A locally set up and running Router repository +- API credentials for testing (sign up for sandbox/UAT credentials on the connector’s website). +- Rust nightly toolchain installed for code formatting: + ```bash + rustup toolchain install nightly + ``` + +## Understanding Connectors and Payment Methods + +A **Connector** processes payments (e.g., Stripe, Adyen) or manages fraud risk (e.g., Signifyd). A **Payment Method** is a specific way to transact (e.g., credit card, PayPal). See the [Hyperswitch Payment Matrix](https://hyperswitch.io/pm-list) for details. + +## Integration Steps + +Integrating a connector is mainly an API integration task. You'll define request and response types and implement required traits. + +This tutorial covers card payments via [Billwerk](https://optimize-docs.billwerk.com/). Review the API reference and test APIs before starting. + +Follow these steps to integrate a new connector. + +### Generate Template + +Run the following script to create the connector structure: + +```bash +sh scripts/add_connector.sh <connector-name> <connector-base-url> +``` + +Example folder structure: + +``` +hyperswitch_connectors/src/connectors +├── billwerk +│ └── transformers.rs +└── billwerk.rs +crates/router/tests/connectors +└── billwerk.rs +``` + +**Note:** move the file `crates/hyperswitch_connectors/src/connectors/connector_name/test.rs` to `crates/router/tests/connectors/connector_name.rs` + + +Define API request/response types and conversions in `hyperswitch_connectors/src/connector/billwerk/transformers.rs` + +Implement connector traits in `hyperswitch_connectors/src/connector/billwerk.rs` + +Write basic payment flow tests in `crates/router/tests/connectors/billwerk.rs` + +Boilerplate code with todo!() is provided—follow the guide and complete the necessary implementations. + +### Implement Request & Response Types + +Integrating a new connector involves transforming Router's core data into the connector's API format. Since the Connector module is stateless, Router handles data persistence. + +#### Implementing transformers.rs + +Design request/response structures based on the connector's API spec. + +Define request format in `transformers.rs`: + +```rust +#[derive(Debug, Serialize)] +pub struct BillwerkCustomerObject { + handle: Option<id_type::CustomerId>, + email: Option<Email>, + address: Option<Secret<String>>, + address2: Option<Secret<String>>, + city: Option<String>, + country: Option<common_enums::CountryAlpha2>, + first_name: Option<Secret<String>>, + last_name: Option<Secret<String>>, +} + +#[derive(Debug, Serialize)] +pub struct BillwerkPaymentsRequest { + handle: String, + amount: MinorUnit, + source: Secret<String>, + currency: common_enums::Currency, + customer: BillwerkCustomerObject, + metadata: Option<SecretSerdeValue>, + settle: bool, +} +``` + +Since Router is connector agnostic, only minimal data is sent to connector and optional fields may be ignored. + +We transform our `PaymentsAuthorizeRouterData` into Billwerk's `PaymentsRequest` structure by employing the `try_from` function. + +```rust +impl TryFrom<&BillwerkRouterData<&types::PaymentsAuthorizeRouterData>> for BillwerkPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &BillwerkRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + if item.router_data.is_three_ds() { + return Err(errors::ConnectorError::NotImplemented( + "Three_ds payments through Billwerk".to_string(), + ) + .into()); + }; + let source = match item.router_data.get_payment_method_token()? { + PaymentMethodToken::Token(pm_token) => Ok(pm_token), + _ => Err(errors::ConnectorError::MissingRequiredField { + field_name: "payment_method_token", + }), + }?; + Ok(Self { + handle: item.router_data.connector_request_reference_id.clone(), + amount: item.amount, + source, + currency: item.router_data.request.currency, + customer: BillwerkCustomerObject { + handle: item.router_data.customer_id.clone(), + email: item.router_data.request.email.clone(), + address: item.router_data.get_optional_billing_line1(), + address2: item.router_data.get_optional_billing_line2(), + city: item.router_data.get_optional_billing_city(), + country: item.router_data.get_optional_billing_country(), + first_name: item.router_data.get_optional_billing_first_name(), + last_name: item.router_data.get_optional_billing_last_name(), + }, + metadata: item.router_data.request.metadata.clone().map(Into::into), + settle: item.router_data.request.is_auto_capture()?, + }) + } +} +``` + +### Handle Response Mapping + +When implementing the response type, the key enum to define for each connector is `PaymentStatus`. It represents the different status types returned by the connector, as specified in its API spec. Below is the definition for Billwerk. + +```rust +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum BillwerkPaymentState { + Created, + Authorized, + Pending, + Settled, + Failed, + Cancelled, +} + +impl From<BillwerkPaymentState> for enums::AttemptStatus { + fn from(item: BillwerkPaymentState) -> Self { + match item { + BillwerkPaymentState::Created | BillwerkPaymentState::Pending => Self::Pending, + BillwerkPaymentState::Authorized => Self::Authorized, + BillwerkPaymentState::Settled => Self::Charged, + BillwerkPaymentState::Failed => Self::Failure, + BillwerkPaymentState::Cancelled => Self::Voided, + } + } +} +``` + +Here are common payment attempt statuses: + +- **Charged:** Payment succeeded. +- **Pending:** Payment is processing. +- **Failure:** Payment failed. +- **Authorized:** Payment authorized; can be voided, captured, or partially captured. +- **AuthenticationPending:** Customer action required. +- **Voided:** Payment voided, funds returned to the customer. + +**Note:** Default status should be `Pending`. Only explicit success or failure from the connector should mark the payment as `Charged` or `Failure`. + +Define response format in `transformers.rs`: + +```rust +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct BillwerkPaymentsResponse { + state: BillwerkPaymentState, + handle: String, + error: Option<String>, + error_state: Option<String>, +} +``` + +We transform our `ResponseRouterData` into `PaymentsResponseData` by employing the `try_from` function. + +```rust +impl<F, T> TryFrom<ResponseRouterData<F, BillwerkPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, BillwerkPaymentsResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let error_response = if item.response.error.is_some() || item.response.error_state.is_some() + { + Some(ErrorResponse { + code: item + .response + .error_state + .clone() + .unwrap_or(NO_ERROR_CODE.to_string()), + message: item + .response + .error_state + .unwrap_or(NO_ERROR_MESSAGE.to_string()), + reason: item.response.error, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(item.response.handle.clone()), + }) + } else { + None + }; + let payments_response = PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.handle.clone()), + 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), + incremental_authorization_allowed: None, + charges: None, + }; + Ok(Self { + status: enums::AttemptStatus::from(item.response.state), + response: error_response.map_or_else(|| Ok(payments_response), Err), + ..item.data + }) + } +} +``` + +### Recommended Fields for Connector Request and Response + +- **connector_request_reference_id:** Merchant's reference ID in the payment request (e.g., `reference` in Checkout). + +```rust + reference: item.router_data.connector_request_reference_id.clone(), +``` +- **connector_response_reference_id:** ID used for transaction identification in the connector dashboard, linked to merchant_reference or connector_transaction_id. + +```rust + connector_response_reference_id: item.response.reference.or(Some(item.response.id)), +``` + +- **resource_id:** The connector's connector_transaction_id is used as the resource_id. If unavailable, set to NoResponseId. + +```rust + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), +``` + +- **redirection_data:** For redirection flows (e.g., 3D Secure), assign the redirection link. + +```rust + let redirection_data = item.response.links.redirect.map(|href| { + services::RedirectForm::from((href.redirection_url, services::Method::Get)) + }); +``` + +### Error Handling + +Define error responses: + +```rust +#[derive(Debug, Serialize, Deserialize)] +pub struct BillwerkErrorResponse { + pub code: Option<i32>, + pub error: String, + pub message: Option<String>, +} +``` + +By following these steps, you can integrate a new connector efficiently while ensuring compatibility with Router's architecture. + +## Implementing the Traits + +The `mod.rs` file contains trait implementations using connector types in transformers. A struct with the connector name holds these implementations. Below are the mandatory traits: + +### ConnectorCommon +Contains common description of the connector, like the base endpoint, content-type, error response handling, id, currency unit. + +Within the `ConnectorCommon` trait, you'll find the following methods : + +- `id` method corresponds directly to the connector name. + +```rust + fn id(&self) -> &'static str { + "Billwerk" + } +``` + +- `get_currency_unit` method anticipates you to [specify the accepted currency unit](#set-the-currency-unit) for the connector. + +```rust + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + } +``` + +- `common_get_content_type` method requires you to provide the accepted content type for the connector API. + +```rust + fn common_get_content_type(&self) -> &'static str { + "application/json" + } +``` + +- `get_auth_header` method accepts common HTTP Authorization headers that are accepted in all `ConnectorIntegration` flows. + +```rust + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = BillwerkAuthType::try_from(auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let encoded_api_key = BASE64_ENGINE.encode(format!("{}:", auth.api_key.peek())); + Ok(vec![( + headers::AUTHORIZATION.to_string(), + format!("Basic {encoded_api_key}").into_masked(), + )]) + } +``` + +- `base_url` method is for fetching the base URL of connector's API. Base url needs to be consumed from configs. + +```rust + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.billwerk.base_url.as_ref() + } +``` + +- `build_error_response` method is common error response handling for a connector if it is same in all cases + +```rust + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: BillwerkErrorResponse = res + .response + .parse_struct("BillwerkErrorResponse") + .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 + .map_or(NO_ERROR_CODE.to_string(), |code| code.to_string()), + message: response.message.unwrap_or(NO_ERROR_MESSAGE.to_string()), + reason: Some(response.error), + attempt_status: None, + connector_transaction_id: None, + }) + } +``` + +### ConnectorIntegration +For every api endpoint contains the url, using request transform and response transform and headers. +Within the `ConnectorIntegration` trait, you'll find the following methods implemented(below mentioned is example for authorized flow): + +- `get_url` method defines endpoint for authorize flow, base url is consumed from `ConnectorCommon` trait. + +```rust + fn get_url( + &self, + _req: &TokenizationRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let base_url = connectors + .billwerk + .secondary_base_url + .as_ref() + .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?; + Ok(format!("{base_url}v1/token")) + } +``` + +- `get_headers` method accepts HTTP headers that are accepted for authorize flow. In this context, it is utilized from the `ConnectorCommonExt` trait, as the connector adheres to common headers across various flows. + +```rust + fn get_headers( + &self, + req: &TokenizationRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } +``` + +- `get_request_body` method uses transformers to convert the Hyperswitch payment request to the connector's format. If successful, it returns the request as `RequestContent::Json`, supporting formats like JSON, form-urlencoded, XML, and raw bytes. + +```rust + fn get_request_body( + &self, + req: &TokenizationRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = BillwerkTokenRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } +``` + +- `build_request` method assembles the API request by providing the method, URL, headers, and request body as parameters. + +```rust + fn build_request( + &self, + req: &TokenizationRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::TokenizationType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::TokenizationType::get_headers(self, req, connectors)?) + .set_body(types::TokenizationType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } +``` + +- `handle_response` method calls transformers where connector response data is transformed into hyperswitch response. + +```rust + fn handle_response( + &self, + data: &TokenizationRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<TokenizationRouterData, errors::ConnectorError> + where + PaymentsResponseData: Clone, + { + let response: BillwerkTokenResponse = res + .response + .parse_struct("BillwerkTokenResponse") + .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, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } +``` + +- `get_error_response` method to manage error responses. As the handling of checkout errors remains consistent across various flows, we've incorporated it from the `build_error_response` method within the `ConnectorCommon` trait. + +```rust + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +``` + +### ConnectorCommonExt +Adds functions with a generic type, including the `build_headers` method. This method constructs both common headers and Authorization headers (from `get_auth_header`), returning them as a vector. + +```rust + impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Billwerk + 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) + } + } +``` + +### OtherTraits +**Payment :** This trait includes several other traits and is meant to represent the functionality related to payments. + +**PaymentAuthorize :** This trait extends the `api::ConnectorIntegration `trait with specific types related to payment authorization. + +**PaymentCapture :** This trait extends the `api::ConnectorIntegration `trait with specific types related to manual payment capture. + +**PaymentSync :** This trait extends the `api::ConnectorIntegration `trait with specific types related to payment retrieve. + +**Refund :** This trait includes several other traits and is meant to represent the functionality related to Refunds. + +**RefundExecute :** This trait extends the `api::ConnectorIntegration `trait with specific types related to refunds create. + +**RefundSync :** This trait extends the `api::ConnectorIntegration `trait with specific types related to refunds retrieve. + +And the below derive traits + +- **Debug** +- **Clone** +- **Copy** + +### **Set the currency Unit** + +Part of the `ConnectorCommon` trait, it allows connectors to specify their accepted currency unit as either `Base` or `Minor`. For example, PayPal uses the base unit (e.g., USD), while Hyperswitch uses the minor unit (e.g., cents). Conversion is required if the connector uses the base unit. + +```rust +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for PaypalRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (currency_unit, currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; + Ok(Self { + amount, + router_data: item, + }) + } +} +``` + +### **Connector utility functions** + +Contains utility functions for constructing connector requests and responses. Use these helpers for retrieving fields like `get_billing_country`, `get_browser_info`, and `get_expiry_date_as_yyyymm`, as well as for validations like `is_three_ds` and `is_auto_capture`. + +```rust + let json_wallet_data: CheckoutGooglePayData = wallet_data.get_wallet_token_as_json()?; +``` + +### **Connector configs for control center** + +This section is for developers using the [Hyperswitch Control Center](https://github.com/juspay/hyperswitch-control-center). Update the connector configuration in development.toml and run the wasm-pack build command. Replace placeholders with actual paths. + +1. Install wasm-pack: + +```bash +cargo install wasm-pack +``` + +2. Add connector configuration: + + Open the development.toml file located at crates/connector_configs/toml/development.toml in your Hyperswitch project. + Find the [stripe] section and add the configuration for example_connector. Example: + + ```toml + # crates/connector_configs/toml/development.toml + + # Other connector configurations... + + [stripe] + [stripe.connector_auth.HeaderKey] + api_key="Secret Key" + + # Add any other Stripe-specific configuration here + + [example_connector] + # Your specific connector configuration for reference + # ... + + ``` + +3. Update paths: + Replace /absolute/path/to/hyperswitch-control-center and /absolute/path/to/hyperswitch with actual paths. + +4. Run `wasm-pack` build: + wasm-pack build --target web --out-dir /absolute/path/to/hyperswitch-control-center/public/hyperswitch/wasm --out-name euclid /absolute/path/to/hyperswitch/crates/euclid_wasm -- --features dummy_connector + +By following these steps, you should be able to update the connector configuration and build the WebAssembly files successfully. + +### Update `ConnectorTypes.res` and `ConnectorUtils.res` + +1. **Update `ConnectorTypes.res`**: + - Open `src/screens/HyperSwitch/Connectors/ConnectorTypes.res`. + - Add your connector to the `connectorName` enum: + ```reason + type connectorName = + | Stripe + | DummyConnector + | YourNewConnector + ``` + - Save the file. + +2. **Update `ConnectorUtils.res`**: + - Open `src/screens/HyperSwitch/Connectors/ConnectorUtils.res`. + - Update functions with your connector: + ```reason + let connectorList : array<connectorName> = [Stripe, YourNewConnector] + + let getConnectorNameString = (connectorName: connectorName) => + switch connectorName { + | Stripe => "Stripe" + | YourNewConnector => "Your New Connector" + }; + + let getConnectorInfo = (connectorName: connectorName) => + switch connectorName { + | Stripe => "Stripe description." + | YourNewConnector => "Your New Connector description." + }; + ``` + - Save the file. + +### Add Connector Icon + +1. **Prepare the Icon**: + Name your connector icon in uppercase (e.g., `YOURCONNECTOR.SVG`). + +2. **Add the Icon**: + Navigate to `public/hyperswitch/Gateway` and copy your SVG icon file there. + +3. **Verify Structure**: + Ensure the file is correctly placed in `public/hyperswitch/Gateway`: + + ``` + public + └── hyperswitch + └── Gateway + └── YOURCONNECTOR.SVG + ``` + Save the changes made to the `Gateway` folder. + +### **Test the Connector** + +1. **Template Code** + + The template script generates a test file with 20 sanity tests. Implement these tests when adding a new connector. + + Example test: + ```rust + #[serial_test::serial] + #[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); + } + ``` + +2. **Utility Functions** + + Helper functions for tests are available in `tests/connector/utils`, making test writing easier. + +3. **Set API Keys** + + Before running tests, configure API keys in sample_auth.toml and set the environment variable: + + ```bash + export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml" + cargo test --package router --test connectors -- checkout --test-threads=1 + ``` + +### **Build Payment Request and Response from JSON Schema** + +1. **Install OpenAPI Generator:** + ```bash + brew install openapi-generator + ``` + +2. **Generate Rust Code:** + ```bash + export CONNECTOR_NAME="<CONNECTOR-NAME>" + export SCHEMA_PATH="<PATH-TO-SCHEMA>" + openapi-generator generate -g rust -i ${SCHEMA_PATH} -o temp && cat temp/src/models/* > crates/router/src/connector/${CONNECTOR_NAME}/temp.rs && rm -rf temp && sed -i'' -r "s/^pub use.*//;s/^pub mod.*//;s/^\/.*//;s/^.\*.*//;s/crate::models:://g;" crates/router/src/connector/${CONNECTOR_NAME}/temp.rs && cargo +nightly fmt + ``` \ No newline at end of file diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index a2bf5872c07..021854ab3f1 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -52,12 +52,12 @@ previous_connector='' find_prev_connector $payment_gateway previous_connector previous_connector_camelcase="$(tr '[:lower:]' '[:upper:]' <<< ${previous_connector:0:1})${previous_connector:1}" sed -i'' -e "s|pub mod $previous_connector;|pub mod $previous_connector;\npub mod ${payment_gateway};|" $conn.rs -sed -i'' -e "s/};/, ${payment_gateway}::${payment_gateway_camelcase},\n};/" $conn.rs -sed -i'' -e "0,/};/s/};/, ${payment_gateway}, ${payment_gateway}::${payment_gateway_camelcase},\n};/" $src/connector.rs +sed -i'' -e "s/};/ ${payment_gateway}::${payment_gateway_camelcase},\n};/" $conn.rs +sed -i'' -e "/pub use hyperswitch_connectors::connectors::{/ s/{/{\n ${payment_gateway}, ${payment_gateway}::${payment_gateway_camelcase},/" $src/connector.rs sed -i'' -e "s|$previous_connector_camelcase \(.*\)|$previous_connector_camelcase \1\n\t\t\tenums::Connector::${payment_gateway_camelcase} => Ok(ConnectorEnum::Old(\Box::new(\connector::${payment_gateway_camelcase}))),|" $src/types/api.rs sed -i'' -e "s|$previous_connector_camelcase \(.*\)|$previous_connector_camelcase \1\n\t\t\tRoutableConnectors::${payment_gateway_camelcase} => euclid_enums::Connector::${payment_gateway_camelcase},|" crates/api_models/src/routing.rs sed -i'' -e "s/pub $previous_connector: \(.*\)/pub $previous_connector: \1\n\tpub ${payment_gateway}: ConnectorParams,/" crates/hyperswitch_interfaces/src/configs.rs -sed -i'' -e "s|$previous_connector.base_url \(.*\)|$previous_connector.base_url \1\n${payment_gateway}.base_url = \"$base_url\"|" config/development.toml config/docker_compose.toml config/config.example.toml loadtest/config/development.toml +sed -i'' -e "s|$previous_connector.base_url \(.*\)|$previous_connector.base_url \1\n${payment_gateway}.base_url = \"$base_url\"|" config/development.toml config/docker_compose.toml config/config.example.toml loadtest/config/development.toml config/deployments/integration_test.toml config/deployments/production.toml config/deployments/sandbox.toml sed -r -i'' -e "s/\"$previous_connector\",/\"$previous_connector\",\n \"${payment_gateway}\",/" config/development.toml config/docker_compose.toml config/config.example.toml loadtest/config/development.toml sed -i '' -e "s/\(pub enum Connector {\)/\1\n\t${payment_gateway_camelcase},/" crates/api_models/src/connector_enums.rs sed -i '' -e "/\/\/ Add Separate authentication support for connectors/{N;s/\(.*\)\n/\1\n\t\t\t| Self::${payment_gateway_camelcase}\n/;}" crates/api_models/src/connector_enums.rs @@ -67,9 +67,27 @@ sed -i '' -e "s/\(pub enum Connector {\)/\1\n\t${payment_gateway_camelcase},/" c sed -i'' -e "s|$previous_connector_camelcase \(.*\)|$previous_connector_camelcase \1\n\t\t\tapi_enums::Connector::${payment_gateway_camelcase} => Self::${payment_gateway_camelcase},|" $src/types/transformers.rs sed -i'' -e "s/^default_imp_for_\(.*\)/default_imp_for_\1\n\tconnectors::${payment_gateway_camelcase},/" crates/hyperswitch_connectors/src/default_implementations.rs sed -i'' -e "s/^default_imp_for_\(.*\)/default_imp_for_\1\n\tconnectors::${payment_gateway_camelcase},/" crates/hyperswitch_connectors/src/default_implementations_v2.rs +sed -i'' -e "s/^default_imp_for_connector_request_id!(/default_imp_for_connector_request_id!(\n connectors::${payment_gateway_camelcase},/" $src/core/payments/flows.rs +sed -i'' -e "s/^default_imp_for_fraud_check!(/default_imp_for_fraud_check!(\n connectors::${payment_gateway_camelcase},/" $src/core/payments/flows.rs +sed -i'' -e "s/^default_imp_for_connector_authentication!(/default_imp_for_connector_authentication!(\n connectors::${payment_gateway_camelcase},/" $src/core/payments/flows.rs +sed -i'' -e "/pub struct ConnectorConfig {/ s/{/{\n pub ${payment_gateway}: Option<ConnectorTomlConfig>,/" crates/connector_configs/src/connector.rs +sed -i'' -e "/mod utils;/ s/mod utils;/mod ${payment_gateway};\nmod utils;/" crates/router/tests/connectors/main.rs +sed -i'' -e "s/^default_imp_for_new_connector_integration_payouts!(/default_imp_for_new_connector_integration_payouts!(\n connector::${payment_gateway_camelcase},/" crates/router/src/core/payments/connector_integration_v2_impls.rs +sed -i'' -e "s/^default_imp_for_new_connector_integration_frm!(/default_imp_for_new_connector_integration_frm!(\n connector::${payment_gateway_camelcase},/" crates/router/src/core/payments/connector_integration_v2_impls.rs +sed -i'' -e "s/^default_imp_for_new_connector_integration_connector_authentication!(/default_imp_for_new_connector_integration_connector_authentication!(\n connector::${payment_gateway_camelcase},/" crates/router/src/core/payments/connector_integration_v2_impls.rs +sed -i'' -e "s/\(pub enum Connector {\)/\1\n\t${payment_gateway_camelcase},/" crates/common_enums/src/connector_enums.rs +sed -i'' -e "/match self {/ s/match self {/match self {\n | Self::${payment_gateway_camelcase}/" crates/common_enums/src/connector_enums.rs +sed -i'' -e "/match routable_connector {/ s/match routable_connector {/match routable_connector {\n RoutableConnectors::${payment_gateway_camelcase} => Self::${payment_gateway_camelcase},/" crates/common_enums/src/connector_enums.rs +sed -i'' -e "/match self.connector_name {/a\\ + api_enums::Connector::${payment_gateway_camelcase} => {\\ + ${payment_gateway}::transformers::${payment_gateway_camelcase}AuthType::try_from(self.auth_type)?;\\ + Ok(())\\ + },\\ +" crates/router/src/core/admin.rs + # Remove temporary files created in above step -rm $conn.rs-e $src/types/api.rs-e $src/configs/settings.rs-e config/development.toml-e config/docker_compose.toml-e config/config.example.toml-e loadtest/config/development.toml-e crates/api_models/src/connector_enums.rs-e crates/euclid/src/enums.rs-e crates/api_models/src/routing.rs-e $src/core/payments/flows.rs-e crates/common_enums/src/connector_enums.rs-e $src/types/transformers.rs-e $src/core/admin.rs-e crates/hyperswitch_connectors/src/default_implementations.rs-e crates/hyperswitch_connectors/src/default_implementations_v2.rs-e crates/hyperswitch_interfaces/src/configs.rs-e $src/connector.rs-e +rm $conn.rs-e $src/types/api.rs-e $src/configs/settings.rs-e config/development.toml-e config/docker_compose.toml-e config/config.example.toml-e loadtest/config/development.toml-e crates/api_models/src/connector_enums.rs-e crates/euclid/src/enums.rs-e crates/api_models/src/routing.rs-e $src/core/payments/flows.rs-e crates/common_enums/src/connector_enums.rs-e $src/types/transformers.rs-e $src/core/admin.rs-e crates/hyperswitch_connectors/src/default_implementations.rs-e crates/hyperswitch_connectors/src/default_implementations_v2.rs-e crates/hyperswitch_interfaces/src/configs.rs-e $src/connector.rs-e config/deployments/integration_test.toml-e config/deployments/production.toml-e config/deployments/sandbox.toml-e temp crates/connector_configs/src/connector.rs-e crates/router/tests/connectors/main.rs-e crates/router/src/core/payments/connector_integration_v2_impls.rs-e cd $conn/ # Generate template files for the connector
fix
[SCRIPT] Update template generating script and updated connector doc (#7301)
5eb033336321b5deb197f4416c8409abf99a8421
2023-06-19 14:19:40
Sanchith Hegde
build(docker): use `debian:bookworm-slim` as base image for builder and runner stages (#1473)
false
diff --git a/Dockerfile b/Dockerfile index fb92bd3acb5..8eb321dd2af 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM rust:slim as builder +FROM rust:slim-bookworm as builder ARG EXTRA_FEATURES="" @@ -36,7 +36,7 @@ RUN cargo build --release --features release ${EXTRA_FEATURES} -FROM debian +FROM debian:bookworm-slim # Placing config and binary executable in different directories ARG CONFIG_DIR=/local/config
build
use `debian:bookworm-slim` as base image for builder and runner stages (#1473)
6a4706323c61f3722dc543993c55084dc9ff9850
2024-01-11 17:26:31
Rachit Naithani
feat(users): invite user without email (#3328)
false
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 07909a35782..f5af31c8e7f 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -86,6 +86,7 @@ pub struct InviteUserRequest { #[derive(Debug, serde::Serialize)] pub struct InviteUserResponse { pub is_email_sent: bool, + pub password: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 532f8208ecf..b1a582cedec 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1,7 +1,5 @@ use api_models::user as user_api; -#[cfg(feature = "email")] -use diesel_models::user_role::UserRoleNew; -use diesel_models::{enums::UserStatus, user as storage_user}; +use diesel_models::{enums::UserStatus, user as storage_user, user_role::UserRoleNew}; #[cfg(feature = "email")] use error_stack::IntoReport; use error_stack::ResultExt; @@ -342,7 +340,6 @@ pub async fn reset_password( Ok(ApplicationResponse::StatusOk) } -#[cfg(feature = "email")] pub async fn invite_user( state: AppState, request: user_api::InviteUserRequest, @@ -395,6 +392,7 @@ pub async fn invite_user( Ok(ApplicationResponse::Json(user_api::InviteUserResponse { is_email_sent: false, + password: None, })) } else if invitee_user .as_ref() @@ -432,25 +430,37 @@ pub async fn invite_user( } })?; - let email_contents = email_types::InviteUser { - recipient_email: invitee_email, - user_name: domain::UserName::new(new_user.get_name())?, - settings: state.conf.clone(), - subject: "You have been invited to join Hyperswitch Community!", - }; - - let send_email_result = state - .email_client - .compose_and_send_email( - Box::new(email_contents), - state.conf.proxy.https_url.as_ref(), - ) - .await; - - logger::info!(?send_email_result); + let is_email_sent; + #[cfg(feature = "email")] + { + let email_contents = email_types::InviteUser { + recipient_email: invitee_email, + user_name: domain::UserName::new(new_user.get_name())?, + settings: state.conf.clone(), + subject: "You have been invited to join Hyperswitch Community!", + }; + let send_email_result = state + .email_client + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), + ) + .await; + logger::info!(?send_email_result); + is_email_sent = send_email_result.is_ok(); + } + #[cfg(not(feature = "email"))] + { + is_email_sent = false; + } Ok(ApplicationResponse::Json(user_api::InviteUserResponse { - is_email_sent: send_email_result.is_ok(), + is_email_sent, + password: if cfg!(not(feature = "email")) { + Some(new_user.get_password().get_secret()) + } else { + None + }, })) } else { Err(UserErrors::InternalServerError.into()) diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 6625a206be2..015e3305de1 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -879,6 +879,7 @@ impl User { .service(web::resource("/user/update_role").route(web::post().to(update_user_role))) .service(web::resource("/role/list").route(web::get().to(list_roles))) .service(web::resource("/role/{role_id}").route(web::get().to(get_role))) + .service(web::resource("/user/invite").route(web::post().to(invite_user))) .service( web::resource("/data") .route(web::get().to(get_multiple_dashboard_metadata)) @@ -901,7 +902,6 @@ impl User { ) .service(web::resource("/forgot_password").route(web::post().to(forgot_password))) .service(web::resource("/reset_password").route(web::post().to(reset_password))) - .service(web::resource("/user/invite").route(web::post().to(invite_user))) .service( web::resource("/signup_with_merchant_id") .route(web::post().to(user_signup_with_merchant_id)), diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 7f0f0db3b69..a77b82c550e 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -333,7 +333,6 @@ pub async fn reset_password( .await } -#[cfg(feature = "email")] pub async fn invite_user( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 8f204814ec4..d271ed5e29d 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -489,6 +489,10 @@ impl NewUser { self.new_merchant.clone() } + pub fn get_password(&self) -> UserPassword { + self.password.clone() + } + pub async fn insert_user_in_db( &self, db: &dyn StorageInterface, @@ -683,8 +687,7 @@ 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 = password::generate_password_hash(uuid::Uuid::new_v4().to_string().into())?; - let password = UserPassword::new(password)?; + let password = UserPassword::new(uuid::Uuid::new_v4().to_string().into())?; let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self {
feat
invite user without email (#3328)
a72f040d9281744bceb928ef2e8d3a26783aae9e
2024-05-07 12:48:22
Sakil Mostak
feat(connector): [Cybersource] Add payout flows for Card (#4511)
false
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 02fac0fbfa5..b48e6bce573 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -348,6 +348,7 @@ pub enum PayoutConnectors { Wise, Paypal, Ebanx, + Cybersource, } #[cfg(feature = "payouts")] @@ -359,6 +360,7 @@ impl From<PayoutConnectors> for RoutableConnectors { PayoutConnectors::Wise => Self::Wise, PayoutConnectors::Paypal => Self::Paypal, PayoutConnectors::Ebanx => Self::Ebanx, + PayoutConnectors::Cybersource => Self::Cybersource, } } } @@ -372,6 +374,7 @@ impl From<PayoutConnectors> for Connector { PayoutConnectors::Wise => Self::Wise, PayoutConnectors::Paypal => Self::Paypal, PayoutConnectors::Ebanx => Self::Ebanx, + PayoutConnectors::Cybersource => Self::Cybersource, } } } @@ -386,6 +389,7 @@ impl TryFrom<Connector> for PayoutConnectors { Connector::Wise => Ok(Self::Wise), Connector::Paypal => Ok(Self::Paypal), Connector::Ebanx => Ok(Self::Ebanx), + Connector::Cybersource => Ok(Self::Cybersource), _ => Err(format!("Invalid payout connector {}", value)), } } diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index b9fbed28158..691d52b4fbb 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -133,6 +133,8 @@ pub struct ConnectorConfig { pub coinbase: Option<ConnectorTomlConfig>, pub cryptopay: Option<ConnectorTomlConfig>, pub cybersource: Option<ConnectorTomlConfig>, + #[cfg(feature = "payouts")] + pub cybersource_payout: Option<ConnectorTomlConfig>, pub iatapay: Option<ConnectorTomlConfig>, pub opennode: Option<ConnectorTomlConfig>, pub bambora: Option<ConnectorTomlConfig>, @@ -223,6 +225,7 @@ impl ConnectorConfig { PayoutConnectors::Wise => Ok(connector_data.wise_payout), PayoutConnectors::Paypal => Ok(connector_data.paypal_payout), PayoutConnectors::Ebanx => Ok(connector_data.ebanx_payout), + PayoutConnectors::Cybersource => Ok(connector_data.cybersource_payout), } } diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 39079fe9f99..d93a9405ae3 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -304,6 +304,10 @@ impl api::PaymentsPreProcessing for Cybersource {} impl api::PaymentsCompleteAuthorize for Cybersource {} impl api::ConnectorMandateRevoke for Cybersource {} +impl api::Payouts for Cybersource {} +#[cfg(feature = "payouts")] +impl api::PayoutFulfill for Cybersource {} + impl ConnectorIntegration< api::PaymentMethodToken, @@ -965,6 +969,124 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P } } +#[cfg(feature = "payouts")] +impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData> + for Cybersource +{ + fn get_url( + &self, + _req: &types::PayoutsRouterData<api::PoFulfill>, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}pts/v2/payouts", self.base_url(connectors))) + } + + fn get_headers( + &self, + req: &types::PayoutsRouterData<api::PoFulfill>, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_request_body( + &self, + req: &types::PayoutsRouterData<api::PoFulfill>, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = cybersource::CybersourceRouterData::try_from(( + &self.get_currency_unit(), + req.request.destination_currency, + req.request.amount, + req, + ))?; + let connector_req = + cybersource::CybersourcePayoutFulfillRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &types::PayoutsRouterData<api::PoFulfill>, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PayoutFulfillType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PayoutFulfillType::get_headers( + self, req, connectors, + )?) + .set_body(types::PayoutFulfillType::get_request_body( + self, req, connectors, + )?) + .build(); + + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::PayoutsRouterData<api::PoFulfill>, + event_builder: Option<&mut ConnectorEvent>, + res: types::Response, + ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> { + let response: cybersource::CybersourceFulfillResponse = res + .response + .parse_struct("CybersourceFulfillResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } + + fn get_5xx_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + let response: cybersource::CybersourceServerErrorResponse = res + .response + .parse_struct("CybersourceServerErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|event| event.set_response_body(&response)); + router_env::logger::info!(error_response=?response); + + let attempt_status = match response.reason { + Some(reason) => match reason { + transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure), + transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None, + }, + None => None, + }; + Ok(types::ErrorResponse { + status_code: res.status_code, + reason: response.status.clone(), + code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: response + .message + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + attempt_status, + connector_transaction_id: None, + }) + } +} + impl ConnectorIntegration< api::CompleteAuthorize, diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 4c8e06b28ef..8251de8ca31 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1,4 +1,9 @@ use api_models::payments; +#[cfg(feature = "payouts")] +use api_models::{ + payments::{AddressDetails, PhoneDetails}, + payouts::PayoutMethodData, +}; use base64::Engine; use common_enums::FutureUsage; use common_utils::{ext_traits::ValueExt, pii}; @@ -111,7 +116,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, - security_code: ccard.card_cvc, + security_code: Some(ccard.card_cvc), card_type, }, }), @@ -404,7 +409,7 @@ pub struct Card { number: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, - security_code: Secret<String>, + security_code: Option<Secret<String>>, #[serde(rename = "type")] card_type: Option<String>, } @@ -849,7 +854,7 @@ impl number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, - security_code: ccard.card_cvc, + security_code: Some(ccard.card_cvc), card_type: card_type.clone(), }, }); @@ -900,7 +905,7 @@ impl number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, - security_code: ccard.card_cvc, + security_code: Some(ccard.card_cvc), card_type, }, }); @@ -1278,7 +1283,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, - security_code: ccard.card_cvc, + security_code: Some(ccard.card_cvc), card_type, }, }); @@ -1982,7 +1987,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsPreProcessingRouterData>> number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, - security_code: ccard.card_cvc, + security_code: Some(ccard.card_cvc), card_type, }, })) @@ -2775,6 +2780,223 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, CybersourceRsyncRespon } } +#[cfg(feature = "payouts")] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourcePayoutFulfillRequest { + client_reference_information: ClientReferenceInformation, + order_information: OrderInformation, + recipient_information: CybersourceRecipientInfo, + sender_information: CybersourceSenderInfo, + processing_information: CybersourceProcessingInfo, + payment_information: PaymentInformation, +} + +#[cfg(feature = "payouts")] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceRecipientInfo { + first_name: Secret<String>, + last_name: Secret<String>, + address1: Secret<String>, + locality: String, + administrative_area: Secret<String>, + postal_code: Secret<String>, + country: api_enums::CountryAlpha2, + phone_number: Option<Secret<String>>, +} + +#[cfg(feature = "payouts")] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceSenderInfo { + reference_number: String, + account: CybersourceAccountInfo, +} + +#[cfg(feature = "payouts")] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceAccountInfo { + funds_source: CybersourcePayoutFundSourceType, +} + +#[cfg(feature = "payouts")] +#[derive(Debug, Serialize)] +pub enum CybersourcePayoutFundSourceType { + #[serde(rename = "05")] + Disbursement, +} + +#[cfg(feature = "payouts")] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceProcessingInfo { + business_application_id: CybersourcePayoutBusinessType, +} + +#[cfg(feature = "payouts")] +#[derive(Debug, Serialize)] +pub enum CybersourcePayoutBusinessType { + #[serde(rename = "PP")] + PersonToPerson, + #[serde(rename = "AA")] + AccountToAccount, +} + +#[cfg(feature = "payouts")] +impl TryFrom<&CybersourceRouterData<&types::PayoutsRouterData<api::PoFulfill>>> + for CybersourcePayoutFulfillRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &CybersourceRouterData<&types::PayoutsRouterData<api::PoFulfill>>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payout_type { + enums::PayoutType::Card => { + let client_reference_information = ClientReferenceInformation { + code: Some(item.router_data.request.payout_id.clone()), + }; + + let order_information = OrderInformation { + amount_details: Amount { + total_amount: item.amount.to_owned(), + currency: item.router_data.request.destination_currency, + }, + }; + + let billing_address = item.router_data.get_billing_address()?; + let phone_address = item.router_data.get_billing_phone()?; + let recipient_information = + CybersourceRecipientInfo::try_from((billing_address, phone_address))?; + + let sender_information = CybersourceSenderInfo { + reference_number: item.router_data.request.payout_id.clone(), + account: CybersourceAccountInfo { + funds_source: CybersourcePayoutFundSourceType::Disbursement, + }, + }; + + let processing_information = CybersourceProcessingInfo { + business_application_id: CybersourcePayoutBusinessType::PersonToPerson, // this means sender and receiver are different + }; + + let payout_method_data = item.router_data.get_payout_method_data()?; + let payment_information = PaymentInformation::try_from(payout_method_data)?; + + Ok(Self { + client_reference_information, + order_information, + recipient_information, + sender_information, + processing_information, + payment_information, + }) + } + enums::PayoutType::Bank | enums::PayoutType::Wallet => { + Err(errors::ConnectorError::NotSupported { + message: "PayoutType is not supported".to_string(), + connector: "Cybersource", + })? + } + } + } +} + +#[cfg(feature = "payouts")] +impl TryFrom<(&AddressDetails, &PhoneDetails)> for CybersourceRecipientInfo { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: (&AddressDetails, &PhoneDetails)) -> Result<Self, Self::Error> { + let (billing_address, phone_address) = item; + Ok(Self { + first_name: billing_address.get_first_name()?.to_owned(), + last_name: billing_address.get_last_name()?.to_owned(), + address1: billing_address.get_line1()?.to_owned(), + locality: billing_address.get_city()?.to_owned(), + administrative_area: billing_address.get_state()?.to_owned(), + postal_code: billing_address.get_zip()?.to_owned(), + country: billing_address.get_country()?.to_owned(), + phone_number: phone_address.number.clone(), + }) + } +} + +#[cfg(feature = "payouts")] +impl TryFrom<PayoutMethodData> for PaymentInformation { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: PayoutMethodData) -> Result<Self, Self::Error> { + match item { + PayoutMethodData::Card(card_details) => { + let card_issuer = card_details.get_card_issuer().ok(); + let card_type = card_issuer.map(String::from); + let card = Card { + number: card_details.card_number, + expiration_month: card_details.expiry_month, + expiration_year: card_details.expiry_year, + security_code: None, + card_type, + }; + Ok(Self::Cards(CardPaymentInformation { card })) + } + PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => { + Err(errors::ConnectorError::NotSupported { + message: "PayoutMethod is not supported".to_string(), + connector: "Cybersource", + })? + } + } + } +} + +#[cfg(feature = "payouts")] +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceFulfillResponse { + id: String, + status: CybersourcePayoutStatus, +} + +#[cfg(feature = "payouts")] +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum CybersourcePayoutStatus { + Accepted, + Declined, + InvalidRequest, +} + +#[cfg(feature = "payouts")] +impl ForeignFrom<CybersourcePayoutStatus> for enums::PayoutStatus { + fn foreign_from(status: CybersourcePayoutStatus) -> Self { + match status { + CybersourcePayoutStatus::Accepted => Self::Success, + CybersourcePayoutStatus::Declined | CybersourcePayoutStatus::InvalidRequest => { + Self::Failed + } + } + } +} + +#[cfg(feature = "payouts")] +impl<F> TryFrom<types::PayoutsResponseRouterData<F, CybersourceFulfillResponse>> + for types::PayoutsRouterData<F> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::PayoutsResponseRouterData<F, CybersourceFulfillResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::PayoutsResponseData { + status: Some(enums::PayoutStatus::foreign_from(item.response.status)), + connector_payout_id: item.response.id, + payout_eligible: None, + should_add_next_step_to_process_tracker: false, + }), + ..item.data + }) + } +} + #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceStandardErrorResponse { diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 2cb3aa436e4..bb52d4885fb 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; #[cfg(feature = "payouts")] -use api_models::payouts::PayoutVendorAccountDetails; +use api_models::payouts::{self, PayoutVendorAccountDetails}; use api_models::{ enums::{CanadaStatesAbbreviation, UsStatesAbbreviation}, payments::{self, OrderDetailsWithAmount}, @@ -1078,6 +1078,80 @@ pub trait CardData { fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error>; } +#[cfg(feature = "payouts")] +impl CardData for payouts::Card { + fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { + let binding = self.expiry_year.clone(); + let year = binding.peek(); + Ok(Secret::new( + year.get(year.len() - 2..) + .ok_or(errors::ConnectorError::RequestEncodingFailed)? + .to_string(), + )) + } + fn get_card_issuer(&self) -> Result<CardIssuer, Error> { + get_card_issuer(self.card_number.peek()) + } + fn get_card_expiry_month_year_2_digit_with_delimiter( + &self, + delimiter: String, + ) -> Result<Secret<String>, errors::ConnectorError> { + let year = self.get_card_expiry_year_2_digit()?; + Ok(Secret::new(format!( + "{}{}{}", + self.expiry_month.peek(), + delimiter, + year.peek() + ))) + } + fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> { + let year = self.get_expiry_year_4_digit(); + Secret::new(format!( + "{}{}{}", + year.peek(), + delimiter, + self.expiry_month.peek() + )) + } + fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> { + let year = self.get_expiry_year_4_digit(); + Secret::new(format!( + "{}{}{}", + self.expiry_month.peek(), + delimiter, + year.peek() + )) + } + fn get_expiry_year_4_digit(&self) -> Secret<String> { + let mut year = self.expiry_year.peek().clone(); + if year.len() == 2 { + year = format!("20{}", year); + } + Secret::new(year) + } + fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> { + let year = self.get_card_expiry_year_2_digit()?.expose(); + let month = self.expiry_month.clone().expose(); + Ok(Secret::new(format!("{year}{month}"))) + } + fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> { + self.expiry_month + .peek() + .clone() + .parse::<i8>() + .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .map(Secret::new) + } + fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> { + self.expiry_year + .peek() + .clone() + .parse::<i32>() + .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .map(Secret::new) + } +} + impl CardData for domain::Card { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let binding = self.card_exp_year.clone(); diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index c7ec86ac5e6..0687f5986ba 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -975,7 +975,6 @@ default_imp_for_payouts!( connector::Cashtocode, connector::Checkout, connector::Cryptopay, - connector::Cybersource, connector::Coinbase, connector::Dlocal, connector::Fiserv, @@ -1232,7 +1231,6 @@ default_imp_for_payouts_fulfill!( connector::Cashtocode, connector::Checkout, connector::Cryptopay, - connector::Cybersource, connector::Coinbase, connector::Dlocal, connector::Fiserv, diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 70e4715183f..c45a4aaaa10 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -15721,7 +15721,8 @@ "stripe", "wise", "paypal", - "ebanx" + "ebanx", + "cybersource" ] }, "PayoutCreateRequest": {
feat
[Cybersource] Add payout flows for Card (#4511)
f8f69728b3303663942722acc1514249d98912d4
2024-07-11 00:33:08
Apoorv Dixit
refactor(user_auth_method): populate default user auth method (#5257)
false
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 49993f3873a..2abcb5ea78b 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -27,6 +27,7 @@ use super::errors::{StorageErrorExt, UserErrors, UserResponse, UserResult}; use crate::services::email::types as email_types; use crate::{ consts, + db::domain::user_authentication_method::DEFAULT_USER_AUTH_METHOD, routes::{app::ReqState, SessionState}, services::{authentication as auth, authorization::roles, openidconnect, ApplicationResponse}, types::{domain, transformers::ForeignInto}, @@ -2306,38 +2307,25 @@ pub async fn terminate_auth_select( .change_context(UserErrors::InternalServerError)? .into(); - if let Some(id) = &req.id { - let user_authentication_method = state + let user_authentication_method = if let Some(id) = &req.id { + state .store .get_user_authentication_method_by_id(id) .await - .to_not_found_response(UserErrors::InvalidUserAuthMethodOperation)?; - - let current_flow = - domain::CurrentFlow::new(user_token, domain::SPTFlow::AuthSelect.into())?; - let mut next_flow = current_flow.next(user_from_db.clone(), &state).await?; - - // Skip SSO if continue with password(TOTP) - if next_flow.get_flow() == domain::UserFlow::SPTFlow(domain::SPTFlow::SSO) - && !utils::user::is_sso_auth_type(&user_authentication_method.auth_type) - { - next_flow = next_flow.skip(user_from_db, &state).await?; - } - let token = next_flow.get_token(&state).await?; - - return auth::cookies::set_cookie_response( - user_api::TokenResponse { - token: token.clone(), - token_type: next_flow.get_flow().into(), - }, - token, - ); - } + .to_not_found_response(UserErrors::InvalidUserAuthMethodOperation)? + } else { + DEFAULT_USER_AUTH_METHOD.clone() + }; - // Giving totp token for hyperswtich users when no id is present in the request body let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::AuthSelect.into())?; let mut next_flow = current_flow.next(user_from_db.clone(), &state).await?; - next_flow = next_flow.skip(user_from_db, &state).await?; + + // Skip SSO if continue with password(TOTP) + if next_flow.get_flow() == domain::UserFlow::SPTFlow(domain::SPTFlow::SSO) + && !utils::user::is_sso_auth_type(&user_authentication_method.auth_type) + { + next_flow = next_flow.skip(user_from_db, &state).await?; + } let token = next_flow.get_token(&state).await?; auth::cookies::set_cookie_response( diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 4c48c21204b..d5100c89c19 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -37,6 +37,7 @@ use crate::{ pub mod dashboard_metadata; pub mod decision_manager; pub use decision_manager::*; +pub mod user_authentication_method; use super::{types as domain_types, UserKeyStore}; diff --git a/crates/router/src/types/domain/user/user_authentication_method.rs b/crates/router/src/types/domain/user/user_authentication_method.rs new file mode 100644 index 00000000000..570e144961a --- /dev/null +++ b/crates/router/src/types/domain/user/user_authentication_method.rs @@ -0,0 +1,17 @@ +use common_enums::{Owner, UserAuthType}; +use diesel_models::UserAuthenticationMethod; +use once_cell::sync::Lazy; + +pub static DEFAULT_USER_AUTH_METHOD: Lazy<UserAuthenticationMethod> = + Lazy::new(|| UserAuthenticationMethod { + id: String::from("hyperswitch_default"), + auth_id: String::from("hyperswitch"), + owner_id: String::from("hyperswitch"), + owner_type: Owner::Tenant, + auth_type: UserAuthType::Password, + private_config: None, + public_config: None, + allow_signup: true, + created_at: common_utils::date_time::now(), + last_modified_at: common_utils::date_time::now(), + });
refactor
populate default user auth method (#5257)
c81d8e9a180da8f71d156d39c9f85847f6d7a572
2023-10-01 12:54:29
Vedant Khairnar
docs(README): fixed TOC links (#2402)
false
diff --git a/README.md b/README.md index 3306de28704..cc19670a8fc 100644 --- a/README.md +++ b/README.md @@ -10,17 +10,17 @@ The single API to access payment ecosystems across 130+ countries</div> <p align="center"> - <a href="#quick-start-guide">Quick Start Guide</a> • - <a href="#fast-integration-for-stripe-users">Fast Integration for Stripe Users</a> • - <a href="#supported-features">Supported Features</a> • - <a href="#faqs">FAQs</a> + <a href="#%EF%B8%8F-quick-start-guide">Quick Start Guide</a> • + <a href="#-fast-integration-for-stripe-users">Fast Integration for Stripe Users</a> • + <a href="#-supported-features">Supported Features</a> • + <a href="#-FAQs">FAQs</a> <br> <a href="#whats-included">What's Included</a> • - <a href="#join-us-in-building-hyperswitch">Join us in building HyperSwitch</a> • - <a href="#community">Community</a> • - <a href="#bugs-and-feature-requests">Bugs and feature requests</a> • - <a href="#versioning">Versioning</a> • - <a href="#copyright-and-license">Copyright and License</a> + <a href="#-join-us-in-building-hyperswitch">Join us in building HyperSwitch</a> • + <a href="#-community">Community</a> • + <a href="#-bugs-and-feature-requests">Bugs and feature requests</a> • + <a href="#-versioning">Versioning</a> • + <a href="#%EF%B8%8F-copyright-and-license">Copyright and License</a> </p> <p align="center"> @@ -63,7 +63,9 @@ Using Hyperswitch, you can: <br> <img src="./docs/imgs/hyperswitch-product.png" alt="Hyperswitch-Product" width="50%"/> -## ⚡️ Quick Start Guide +<a href="#Quick Start Guide"> + <h2 id="Quick Start Guide">⚡️ Quick Start Guide</h2> +</a> <a href="https://app.hyperswitch.io/register"><img src="./docs/imgs/signup-to-hs.svg" height="35"></a> @@ -84,7 +86,9 @@ Ways to get started with Hyperswitch: setup required in your system. Suitable if you like to customise the core offering, [setup guide](/docs/try_local_system.md) -## 🔌 Fast Integration for Stripe Users +<a href="#Fast-Integration-for-Stripe-Users"> + <h2 id="Fast Integration for Stripe Users">🔌 Fast Integration for Stripe Users</h2> +</a> If you are already using Stripe, integrating with Hyperswitch is fun, fast & easy. @@ -97,7 +101,9 @@ Try the steps below to get a feel for how quick the setup is: [dashboard]: https://app.hyperswitch.io/register [migrate-from-stripe]: https://hyperswitch.io/docs/migrateFromStripe -## ✅ Supported Features +<a href="#Supported-Features"> + <h2 id="Supported Features">✅ Supported Features</h2> +</a> ### 🌟 Supported Payment Processors and Methods @@ -141,7 +147,9 @@ analytics, and operations end-to-end: You can [try the hosted version in our sandbox][dashboard]. -## 🤔 FAQs +<a href="#FAQs"> + <h2 id="FAQs">🤔 FAQs</h2> +</a> Got more questions? Please refer to our [FAQs page][faqs]. @@ -160,7 +168,9 @@ Please refer to the following documentation pages: - Router Architecture [Link] --> -## What's Included❓ +<a href="#what's-Included❓"> + <h2 id="what's-Included❓">What's Included❓</h2> +</a> Within the repositories, you'll find the following directories and files, logically grouping common assets and providing both compiled and minified @@ -208,7 +218,9 @@ should be introduced, checking it agrees with the actual structure --> └── scripts : automation, testing, and other utility scripts ``` -## 💪 Join us in building Hyperswitch +<a href="#Join-us-in-building-Hyperswitch"> + <h2 id="Join-us-in-building-Hyperswitch">💪 Join us in building Hyperswitch</h2> +</a> ### 🤝 Our Belief @@ -260,7 +272,9 @@ readability over purely idiomatic code. For example, some of the code in core functions (e.g., `payments_core`) is written to be more readable than pure-idiomatic. -## 👥 Community +<a href="#Community"> + <h2 id="Community">👥 Community</h2> +</a> Get updates on Hyperswitch development and chat with the community: @@ -292,7 +306,9 @@ Get updates on Hyperswitch development and chat with the community: </div> </div> -## 🐞 Bugs and feature requests +<a href="#Bugs and feature requests"> + <h2 id="Bugs and feature requests">🐞 Bugs and feature requests</h2> +</a> Please read the issue guidelines and search for [existing and closed issues]. If your problem or idea is not addressed yet, please [open a new issue]. @@ -300,16 +316,22 @@ If your problem or idea is not addressed yet, please [open a new issue]. [existing and closed issues]: https://github.com/juspay/hyperswitch/issues [open a new issue]: https://github.com/juspay/hyperswitch/issues/new/choose -## 🔖 Versioning +<a href="#Versioning"> + <h2 id="Versioning">🔖 Versioning</h2> +</a> Check the [CHANGELOG.md](./CHANGELOG.md) file for details. -## ©️ Copyright and License +<a href="#©Copyright and License"> + <h2 id="©Copyright and License">©️ Copyright and License</h2> +</a> This product is licensed under the [Apache 2.0 License](LICENSE). -## ✨ Thanks to all contributors +<a href="#Thanks to all contributors"> + <h2 id="Thanks to all contributors">✨ Thanks to all contributors</h2> +</a> Thank you for your support in hyperswitch's growth. Keep up the great work! 🥂
docs
fixed TOC links (#2402)
6df1578922b7bdc3d0b20ef1bc0b8714f43cc4bf
2025-03-05 19:32:06
Sagnik Mitra
feat(connector): [EFT] Add EFT as a payment method (#7304)
false
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 1301d130cba..e3804320976 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -5578,6 +5578,27 @@ "type": "object" } } + }, + { + "type": "object", + "required": [ + "eft" + ], + "properties": { + "eft": { + "type": "object", + "required": [ + "provider" + ], + "properties": { + "provider": { + "type": "string", + "description": "The preferred eft provider", + "example": "ozow" + } + } + } + } } ] }, @@ -15458,6 +15479,7 @@ "debit", "duit_now", "efecty", + "eft", "eps", "fps", "evoucher", diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 116e79383a9..8476ed3df33 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -7733,6 +7733,27 @@ "type": "object" } } + }, + { + "type": "object", + "required": [ + "eft" + ], + "properties": { + "eft": { + "type": "object", + "required": [ + "provider" + ], + "properties": { + "provider": { + "type": "string", + "description": "The preferred eft provider", + "example": "ozow" + } + } + } + } } ] }, @@ -17792,6 +17813,7 @@ "debit", "duit_now", "efecty", + "eft", "eps", "fps", "evoucher", diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index b8b60481361..7e69728da41 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -2639,6 +2639,7 @@ impl GetPaymentMethodType for BankRedirectData { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, + Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, @@ -3015,6 +3016,11 @@ pub enum BankRedirectData { issuer: common_enums::BankNames, }, LocalBankRedirect {}, + Eft { + /// The preferred eft provider + #[schema(example = "ozow")] + provider: String, + }, } impl GetAddressFromPaymentMethodData for BankRedirectData { @@ -3130,7 +3136,8 @@ impl GetAddressFromPaymentMethodData for BankRedirectData { | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } - | Self::Blik { .. } => None, + | Self::Blik { .. } + | Self::Eft { .. } => None, } } } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 26b56be1f07..208fb7dedb5 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1587,6 +1587,7 @@ pub enum PaymentMethodType { Debit, DuitNow, Efecty, + Eft, Eps, Fps, Evoucher, diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index d351f5c927e..6fcc33a97f0 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1821,6 +1821,7 @@ impl From<PaymentMethodType> for PaymentMethod { PaymentMethodType::Debit => Self::Card, PaymentMethodType::Fps => Self::RealTimePayment, PaymentMethodType::DuitNow => Self::RealTimePayment, + PaymentMethodType::Eft => Self::BankRedirect, PaymentMethodType::Eps => Self::BankRedirect, PaymentMethodType::Evoucher => Self::Reward, PaymentMethodType::Giropay => Self::BankRedirect, diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs index 6fb302641db..58e9f6fca31 100644 --- a/crates/euclid/src/frontend/dir/enums.rs +++ b/crates/euclid/src/frontend/dir/enums.rs @@ -147,6 +147,7 @@ pub enum BankRedirectType { Giropay, Ideal, Sofort, + Eft, Eps, BancontactCard, Blik, diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs index 04a029bd109..c5cb54378b0 100644 --- a/crates/euclid/src/frontend/dir/lowering.rs +++ b/crates/euclid/src/frontend/dir/lowering.rs @@ -160,6 +160,7 @@ impl From<enums::BankRedirectType> for global_enums::PaymentMethodType { enums::BankRedirectType::Giropay => Self::Giropay, enums::BankRedirectType::Ideal => Self::Ideal, enums::BankRedirectType::Sofort => Self::Sofort, + enums::BankRedirectType::Eft => Self::Eft, enums::BankRedirectType::Eps => Self::Eps, enums::BankRedirectType::BancontactCard => Self::BancontactCard, enums::BankRedirectType::Blik => Self::Blik, diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs index 1a3bb52e0fa..762f3a857b2 100644 --- a/crates/euclid/src/frontend/dir/transformers.rs +++ b/crates/euclid/src/frontend/dir/transformers.rs @@ -196,6 +196,7 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet global_enums::PaymentMethodType::DirectCarrierBilling => { Ok(dirval!(MobilePaymentType = DirectCarrierBilling)) } + global_enums::PaymentMethodType::Eft => Ok(dirval!(BankRedirectType = Eft)), } } } diff --git a/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs b/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs index 9fe45cef21e..3e4ac8d80a8 100644 --- a/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs @@ -174,6 +174,17 @@ impl merchant_transaction_id: None, customer_email: None, })), + BankRedirectData::Eft { .. } => Self::BankRedirect(Box::new(BankRedirectionPMData { + payment_brand: PaymentBrand::Eft, + bank_account_country: Some(item.router_data.get_billing_country()?), + bank_account_bank_name: None, + bank_account_bic: None, + bank_account_iban: None, + billing_country: None, + merchant_customer_id: None, + merchant_transaction_id: None, + customer_email: None, + })), BankRedirectData::Giropay { bank_account_bic, bank_account_iban, @@ -326,6 +337,7 @@ pub struct WalletPMData { #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaymentBrand { Eps, + Eft, Ideal, Giropay, Sofortueberweisung, diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index 5c38a55dc0f..8b1296a0159 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -465,6 +465,7 @@ impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentReque BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum {} | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Giropay { .. } | BankRedirectData::Ideal { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs index 6450839fac3..e41057fb8e6 100644 --- a/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs @@ -164,6 +164,7 @@ impl BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum {} | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Giropay { .. } | BankRedirectData::Interac { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/klarna.rs b/crates/hyperswitch_connectors/src/connectors/klarna.rs index dd0110d9593..86ad19d7dc2 100644 --- a/crates/hyperswitch_connectors/src/connectors/klarna.rs +++ b/crates/hyperswitch_connectors/src/connectors/klarna.rs @@ -581,6 +581,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData | common_enums::PaymentMethodType::Debit | common_enums::PaymentMethodType::DirectCarrierBilling | common_enums::PaymentMethodType::Efecty + | common_enums::PaymentMethodType::Eft | common_enums::PaymentMethodType::Eps | common_enums::PaymentMethodType::Evoucher | common_enums::PaymentMethodType::Giropay @@ -698,6 +699,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData | common_enums::PaymentMethodType::Debit | common_enums::PaymentMethodType::DirectCarrierBilling | common_enums::PaymentMethodType::Efecty + | common_enums::PaymentMethodType::Eft | common_enums::PaymentMethodType::Eps | common_enums::PaymentMethodType::Evoucher | common_enums::PaymentMethodType::Giropay diff --git a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs index 61732e5c751..3e632e048a2 100644 --- a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs @@ -525,6 +525,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum { .. } | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } @@ -590,6 +591,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum { .. } | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } @@ -777,6 +779,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum { .. } | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Giropay { .. } | BankRedirectData::Interac { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs index 88cea9c8edf..8e4b9995040 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs @@ -593,6 +593,7 @@ fn get_payment_details_and_product( BankRedirectData::BancontactCard { .. } | BankRedirectData::Blik { .. } | BankRedirectData::Bizum { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index 3bc06aa6e19..0bfd3af7e99 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -977,6 +977,7 @@ where BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum {} | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs b/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs index b2fd0ed0b49..cfa5c28e7ba 100644 --- a/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs @@ -505,6 +505,7 @@ impl TryFrom<&BankRedirectData> for PaymentMethodType { BankRedirectData::Sofort { .. } => Ok(Self::Sofort), BankRedirectData::BancontactCard { .. } | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Trustly { .. } | BankRedirectData::Przelewy24 { .. } | BankRedirectData::Bizum {} diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs index 52181738579..e8da94fae34 100644 --- a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs @@ -238,6 +238,7 @@ impl TryFrom<&BankRedirectData> for TrustpayPaymentMethod { BankRedirectData::Blik { .. } => Ok(Self::Blik), BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum {} + | BankRedirectData::Eft { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs index 86816195276..3841b7e33b4 100644 --- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs @@ -113,6 +113,7 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum {} | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Giropay { .. } | BankRedirectData::Ideal { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs index f9d7da5d1ec..d716bfd088f 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs @@ -390,6 +390,7 @@ fn make_bank_redirect_request( BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum {} | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs index abe528eff29..305c8518c8e 100644 --- a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs @@ -724,6 +724,7 @@ impl TryFrom<&BankRedirectData> for ZenPaymentsRequest { | BankRedirectData::BancontactCard { .. } | BankRedirectData::Blik { .. } | BankRedirectData::Trustly { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Giropay { .. } | BankRedirectData::Przelewy24 { .. } diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index ac5a7714b54..ce40e373462 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -5199,6 +5199,7 @@ pub enum PaymentMethodDataType { BancontactCard, Bizum, Blik, + Eft, Eps, Giropay, Ideal, @@ -5330,6 +5331,7 @@ impl From<PaymentMethodData> for PaymentMethodDataType { } payment_method_data::BankRedirectData::Bizum {} => Self::Bizum, payment_method_data::BankRedirectData::Blik { .. } => Self::Blik, + payment_method_data::BankRedirectData::Eft { .. } => Self::Eft, payment_method_data::BankRedirectData::Eps { .. } => Self::Eps, payment_method_data::BankRedirectData::Giropay { .. } => Self::Giropay, payment_method_data::BankRedirectData::Ideal { .. } => Self::Ideal, diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 78b2144f3ed..9b73fe45f65 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -437,6 +437,9 @@ pub enum BankRedirectData { issuer: common_enums::BankNames, }, LocalBankRedirect {}, + Eft { + provider: String, + }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] @@ -1029,6 +1032,7 @@ impl From<api_models::payments::BankRedirectData> for BankRedirectData { api_models::payments::BankRedirectData::LocalBankRedirect { .. } => { Self::LocalBankRedirect {} } + api_models::payments::BankRedirectData::Eft { provider } => Self::Eft { provider }, } } } @@ -1613,6 +1617,7 @@ impl GetPaymentMethodType for BankRedirectData { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, + Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index e224078493f..88c32a48187 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -28,6 +28,7 @@ fn get_dir_value_payment_method( api_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)), api_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)), api_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)), + api_enums::PaymentMethodType::Eft => Ok(dirval!(BankRedirectType = Eft)), api_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)), api_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)), api_enums::PaymentMethodType::AfterpayClearpay => { diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index adfe5820866..0479753d8d0 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -136,6 +136,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)), api_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)), api_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)), + api_enums::PaymentMethodType::Eft => Ok(dirval!(BankRedirectType = Eft)), api_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)), api_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)), api_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)), diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 7067592771f..7cefdda657e 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -222,6 +222,7 @@ impl ConnectorValidation for Adyen { | PaymentMethodType::Multibanco | PaymentMethodType::Przelewy24 | PaymentMethodType::Becs + | PaymentMethodType::Eft | PaymentMethodType::ClassicReward | PaymentMethodType::Pse | PaymentMethodType::LocalBankTransfer diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 93a43f25b8a..0920887962a 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2404,6 +2404,7 @@ impl ), domain::BankRedirectData::Trustly { .. } => Ok(AdyenPaymentMethod::Trustly), domain::BankRedirectData::Giropay { .. } + | domain::BankRedirectData::Eft { .. } | domain::BankRedirectData::Interac { .. } | domain::BankRedirectData::LocalBankRedirect {} | domain::BankRedirectData::Przelewy24 { .. } diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 5989706bf5b..80a702512c0 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -762,6 +762,7 @@ fn get_payment_source( .into()) } domain::BankRedirectData::Bizum {} + | domain::BankRedirectData::Eft { .. } | domain::BankRedirectData::Interac { .. } | domain::BankRedirectData::OnlineBankingCzechRepublic { .. } | domain::BankRedirectData::OnlineBankingFinland { .. } @@ -1158,6 +1159,7 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP | enums::PaymentMethodType::DirectCarrierBilling | enums::PaymentMethodType::DuitNow | enums::PaymentMethodType::Efecty + | enums::PaymentMethodType::Eft | enums::PaymentMethodType::Eps | enums::PaymentMethodType::Fps | enums::PaymentMethodType::Evoucher diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index cdcf7b4c7b2..41fb23e7e9e 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -711,6 +711,7 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { | enums::PaymentMethodType::Dana | enums::PaymentMethodType::DirectCarrierBilling | enums::PaymentMethodType::Efecty + | enums::PaymentMethodType::Eft | enums::PaymentMethodType::Evoucher | enums::PaymentMethodType::GoPay | enums::PaymentMethodType::Gcash @@ -1032,6 +1033,7 @@ impl TryFrom<&domain::BankRedirectData> for StripePaymentMethodType { } domain::BankRedirectData::Bizum {} | domain::BankRedirectData::Interac { .. } + | domain::BankRedirectData::Eft { .. } | domain::BankRedirectData::OnlineBankingCzechRepublic { .. } | domain::BankRedirectData::OnlineBankingFinland { .. } | domain::BankRedirectData::OnlineBankingPoland { .. } @@ -1600,6 +1602,7 @@ impl TryFrom<(&domain::BankRedirectData, Option<StripeBillingAddress>)> .into()) } domain::BankRedirectData::Bizum {} + | domain::BankRedirectData::Eft { .. } | domain::BankRedirectData::Interac { .. } | domain::BankRedirectData::OnlineBankingCzechRepublic { .. } | domain::BankRedirectData::OnlineBankingFinland { .. } diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 2d7e3cc6d52..8a186e0291a 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -2789,6 +2789,7 @@ pub enum PaymentMethodDataType { BancontactCard, Bizum, Blik, + Eft, Eps, Giropay, Ideal, @@ -2920,6 +2921,7 @@ impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType { } domain::payments::BankRedirectData::Bizum {} => Self::Bizum, domain::payments::BankRedirectData::Blik { .. } => Self::Blik, + domain::payments::BankRedirectData::Eft { .. } => Self::Eft, domain::payments::BankRedirectData::Eps { .. } => Self::Eps, domain::payments::BankRedirectData::Giropay { .. } => Self::Giropay, domain::payments::BankRedirectData::Ideal { .. } => Self::Ideal, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 05b4d592c23..cdbda13997b 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2997,6 +2997,7 @@ pub fn validate_payment_method_type_against_payment_method( api_enums::PaymentMethodType::Giropay | api_enums::PaymentMethodType::Ideal | api_enums::PaymentMethodType::Sofort + | api_enums::PaymentMethodType::Eft | api_enums::PaymentMethodType::Eps | api_enums::PaymentMethodType::BancontactCard | api_enums::PaymentMethodType::Blik @@ -4828,6 +4829,12 @@ pub async fn get_additional_payment_data( details: None, }, )), + domain::BankRedirectData::Eft { .. } => Ok(Some( + api_models::payments::AdditionalPaymentData::BankRedirect { + bank_name: None, + details: None, + }, + )), domain::BankRedirectData::Ideal { bank_name, .. } => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: bank_name.to_owned(), diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 6ab4111f4b7..b89e70e5703 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -492,6 +492,7 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { api_enums::PaymentMethodType::Giropay | api_enums::PaymentMethodType::Ideal | api_enums::PaymentMethodType::Sofort + | api_enums::PaymentMethodType::Eft | api_enums::PaymentMethodType::Eps | api_enums::PaymentMethodType::BancontactCard | api_enums::PaymentMethodType::Blik
feat
[EFT] Add EFT as a payment method (#7304)
6001fb08b2cc1074e1cd0467da89446a4d168300
2022-12-16 17:59:20
Sanchith Hegde
ci: remove explicitly provided cache key (#164)
false
diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index bab4f6e860a..d6d97f8b50f 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -98,8 +98,6 @@ jobs: toolchain: 1.64 - uses: Swatinem/[email protected] - with: - key: cargo-cache-${{ hashFiles('**/Cargo.lock', '**/Cargo.toml') }}-${{ matrix.os }}-msrv - name: Install cargo-hack uses: baptiste0928/[email protected] @@ -169,8 +167,6 @@ jobs: # crate: cargo-nextest - uses: Swatinem/[email protected] - with: - key: cargo-cache-${{ hashFiles('**/Cargo.lock', '**/Cargo.toml') }}-${{ matrix.os }}-stable # - name: Setup Embark Studios lint rules # shell: bash
ci
remove explicitly provided cache key (#164)
3cdf50c9421f64a7b53d2485090706985354fa75
2023-01-10 18:07:32
Kartikeya Hegde
refactor: Replace Bach with Application on every naming (#292)
false
diff --git a/config/Development.toml b/config/Development.toml index 456311468b3..833c5989995 100644 --- a/config/Development.toml +++ b/config/Development.toml @@ -40,6 +40,10 @@ locker_decryption_key2 = "" wallets = ["klarna", "braintree", "applepay"] cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree", "aci", "shift4", "cybersource", "worldpay"] +[refund] +max_attempts = 10 +max_age = 365 + [eph_key] validity = 1 diff --git a/config/config.example.toml b/config/config.example.toml index 99e6dc0ac8a..f21b49ca4ae 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -89,6 +89,11 @@ locker_decryption_key1 = "" # private key 1 in pem format, corresponding public locker_decryption_key2 = "" # private key 2 in pem format, corresponding public key in basilisk +# Refund configuration +[refund] +max_attempts = 10 # Number of refund attempts allowed +max_age = 365 # Max age of a refund in days. + # Validity of an Ephemeral Key in Hours [eph_key] validity = 1 diff --git a/config/docker_compose.toml b/config/docker_compose.toml index dbd3caaac0a..c7c4bc84d68 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -52,6 +52,10 @@ port = 6379 cluster_enabled = true cluster_urls = ["redis-queue:6379"] +[refund] +max_attempts = 10 +max_age = 365 + [connectors.aci] base_url = "https://eu-test.oppwa.com/" diff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rs index 91452aa4ee3..31ed18bcac2 100644 --- a/crates/router/src/bin/router.rs +++ b/crates/router/src/bin/router.rs @@ -1,12 +1,12 @@ use router::{ configs::settings::{CmdLineConf, Settings, Subcommand}, - core::errors::{BachError, BachResult}, + core::errors::{ApplicationError, ApplicationResult}, logger, }; use structopt::StructOpt; #[actix_web::main] -async fn main() -> BachResult<()> { +async fn main() -> ApplicationResult<()> { // get commandline config before initializing config let cmd_line = CmdLineConf::from_args(); @@ -41,7 +41,7 @@ async fn main() -> BachResult<()> { state.store.close().await; - Err(BachError::from(std::io::Error::new( + Err(ApplicationError::from(std::io::Error::new( std::io::ErrorKind::Other, "Server shut down", ))) diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs index 4064304d248..84348839aef 100644 --- a/crates/router/src/compatibility/wrap.rs +++ b/crates/router/src/compatibility/wrap.rs @@ -21,7 +21,7 @@ pub async fn compatibility_api_wrap<'a, 'b, U, T, Q, F, Fut, S, E>( ) -> HttpResponse where F: Fn(&'b routes::AppState, U, T) -> Fut, - Fut: Future<Output = RouterResult<api::BachResponse<Q>>>, + Fut: Future<Output = RouterResult<api::ApplicationResponse<Q>>>, Q: Serialize + std::fmt::Debug + 'a, S: From<Q> + Serialize, E: From<errors::ApiErrorResponse> + Serialize + error_stack::Context + actix_web::ResponseError, @@ -29,7 +29,7 @@ where { let resp = api::server_wrap_util(state, request, payload, func, api_authentication).await; match resp { - Ok(api::BachResponse::Json(router_resp)) => { + Ok(api::ApplicationResponse::Json(router_resp)) => { let pg_resp = S::try_from(router_resp); match pg_resp { Ok(pg_resp) => match serde_json::to_string(&pg_resp) { @@ -51,9 +51,9 @@ where ), } } - Ok(api::BachResponse::StatusOk) => api::http_response_ok(), - Ok(api::BachResponse::TextPlain(text)) => api::http_response_plaintext(text), - Ok(api::BachResponse::JsonForRedirection(response)) => { + Ok(api::ApplicationResponse::StatusOk) => api::http_response_ok(), + Ok(api::ApplicationResponse::TextPlain(text)) => api::http_response_plaintext(text), + Ok(api::ApplicationResponse::JsonForRedirection(response)) => { match serde_json::to_string(&response) { Ok(res) => api::http_redirect_response(res, response), Err(_) => api::http_response_err( @@ -65,7 +65,7 @@ where ), } } - Ok(api::BachResponse::Form(form_data)) => api::build_redirection_form(&form_data) + Ok(api::ApplicationResponse::Form(form_data)) => api::build_redirection_form(&form_data) .respond_to(request) .map_into_boxed_body(), Err(error) => { diff --git a/crates/router/src/configs/defaults.toml b/crates/router/src/configs/defaults.toml index 53766d1c5bc..62200dace25 100644 --- a/crates/router/src/configs/defaults.toml +++ b/crates/router/src/configs/defaults.toml @@ -42,6 +42,10 @@ jwt_secret="secret" [eph_key] validity = 1 +[refund] +max_attempts = 10 +max_age = 365 + [scheduler] stream = "SCHEDULER_STREAM" consumer_group = "SCHEDULER_GROUP" diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 7dc34ed90e2..3e70f3a5985 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -7,7 +7,7 @@ use serde::Deserialize; use structopt::StructOpt; use crate::{ - core::errors::{BachError, BachResult}, + core::errors::{ApplicationError, ApplicationResult}, env::{self, logger, Env}, }; @@ -42,6 +42,7 @@ pub struct Settings { pub keys: Keys, //remove this during refactoring pub locker: Locker, pub connectors: Connectors, + pub refund: Refund, pub eph_key: EphemeralConfig, pub scheduler: Option<SchedulerSettings>, #[cfg(feature = "kv_store")] @@ -67,6 +68,12 @@ pub struct Locker { pub basilisk_host: String, } +#[derive(Debug, Deserialize, Clone)] +pub struct Refund { + pub max_attempts: usize, + pub max_age: i64, +} + #[derive(Debug, Deserialize, Clone)] pub struct EphemeralConfig { pub validity: i64, @@ -163,11 +170,11 @@ pub struct DrainerSettings { } impl Settings { - pub fn new() -> BachResult<Self> { + pub fn new() -> ApplicationResult<Self> { Self::with_config_path(None) } - pub fn with_config_path(config_path: Option<PathBuf>) -> BachResult<Self> { + pub fn with_config_path(config_path: Option<PathBuf>) -> ApplicationResult<Self> { let environment = env::which(); let config_path = router_env::Config::config_path(&environment.to_string(), config_path); @@ -199,7 +206,7 @@ impl Settings { serde_path_to_error::deserialize(config).map_err(|error| { logger::error!(%error, "Unable to deserialize application configuration"); eprintln!("Unable to deserialize application configuration: {error}"); - BachError::from(error.into_inner()) + ApplicationError::from(error.into_inner()) }) } } diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 0c3f0a93366..b2a4240fa95 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -720,8 +720,9 @@ impl api::IncomingWebhook for Adyen { fn get_webhook_api_response( &self, - ) -> CustomResult<services::api::BachResponse<serde_json::Value>, errors::ConnectorError> { - Ok(services::api::BachResponse::TextPlain( + ) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ConnectorError> + { + Ok(services::api::ApplicationResponse::TextPlain( "[accepted]".to_string(), )) } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index fdbb9b90d35..eed32e0558d 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -78,7 +78,7 @@ pub async fn create_merchant_account( .map_err(|error| { error.to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount) })?; - Ok(service_api::BachResponse::Json(response)) + Ok(service_api::ApplicationResponse::Json(response)) } pub async fn get_merchant_account( @@ -128,7 +128,7 @@ pub async fn get_merchant_account( publishable_key: merchant_account.publishable_key, locker_id: merchant_account.locker_id, }; - Ok(service_api::BachResponse::Json(response)) + Ok(service_api::ApplicationResponse::Json(response)) } pub async fn merchant_account_update( @@ -226,7 +226,7 @@ pub async fn merchant_account_update( db.update_merchant(merchant_account, updated_merchant_account) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; - Ok(service_api::BachResponse::Json(response)) + Ok(service_api::ApplicationResponse::Json(response)) } pub async fn merchant_account_delete( @@ -243,7 +243,7 @@ pub async fn merchant_account_delete( merchant_id, deleted: is_deleted, }; - Ok(service_api::BachResponse::Json(response)) + Ok(service_api::ApplicationResponse::Json(response)) } async fn get_parent_merchant( @@ -340,7 +340,7 @@ pub async fn create_payment_connector( })?; response.merchant_connector_id = Some(mca.merchant_connector_id); - Ok(service_api::BachResponse::Json(response)) + Ok(service_api::ApplicationResponse::Json(response)) } pub async fn retrieve_payment_connector( @@ -365,7 +365,9 @@ pub async fn retrieve_payment_connector( error.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound) })?; - Ok(service_api::BachResponse::Json(mca.foreign_try_into()?)) + Ok(service_api::ApplicationResponse::Json( + mca.foreign_try_into()?, + )) } pub async fn list_payment_connectors( @@ -393,7 +395,7 @@ pub async fn list_payment_connectors( response.push(mca.foreign_try_into()?); } - Ok(service_api::BachResponse::Json(response)) + Ok(service_api::ApplicationResponse::Json(response)) } pub async fn update_payment_connector( @@ -460,7 +462,7 @@ pub async fn update_payment_connector( payment_methods_enabled: req.payment_methods_enabled, metadata: req.metadata, }; - Ok(service_api::BachResponse::Json(response)) + Ok(service_api::ApplicationResponse::Json(response)) } pub async fn delete_payment_connector( @@ -489,5 +491,5 @@ pub async fn delete_payment_connector( merchant_connector_id, deleted: is_deleted, }; - Ok(service_api::BachResponse::Json(response)) + Ok(service_api::ApplicationResponse::Json(response)) } diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 30c91c95f0f..cc4e6dda40d 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -80,7 +80,7 @@ pub async fn create_customer( let mut customer_response: customers::CustomerResponse = customer.into(); customer_response.address = customer_data.address; - Ok(services::BachResponse::Json(customer_response)) + Ok(services::ApplicationResponse::Json(customer_response)) } #[instrument(skip(db))] @@ -94,7 +94,7 @@ pub async fn retrieve_customer( .await .map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound))?; - Ok(services::BachResponse::Json(response.into())) + Ok(services::ApplicationResponse::Json(response.into())) } #[instrument(skip_all)] @@ -190,7 +190,7 @@ pub async fn delete_customer( address_deleted: true, payment_methods_deleted: true, }; - Ok(services::BachResponse::Json(response)) + Ok(services::ApplicationResponse::Json(response)) } #[instrument(skip(db))] @@ -247,5 +247,7 @@ pub async fn update_customer( let mut customer_update_response: customers::CustomerResponse = response.into(); customer_update_response.address = update_customer.address; - Ok(services::BachResponse::Json(customer_update_response)) + Ok(services::ApplicationResponse::Json( + customer_update_response, + )) } diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index fa9688f4de0..c4ff5aac2bf 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -16,11 +16,10 @@ pub use self::api_error_response::ApiErrorResponse; pub(crate) use self::utils::{ConnectorErrorExt, StorageErrorExt}; use crate::services; pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; -pub type RouterResponse<T> = CustomResult<services::BachResponse<T>, ApiErrorResponse>; +pub type RouterResponse<T> = CustomResult<services::ApplicationResponse<T>, ApiErrorResponse>; -// FIXME: Phase out BachResult and BachResponse -pub type BachResult<T> = Result<T, BachError>; -pub type BachResponse<T> = BachResult<services::BachResponse<T>>; +pub type ApplicationResult<T> = Result<T, ApplicationError>; +pub type ApplicationResponse<T> = ApplicationResult<services::ApplicationResponse<T>>; macro_rules! impl_error_display { ($st: ident, $arg: tt) => { @@ -50,7 +49,7 @@ macro_rules! impl_error_type { // FIXME: Make this a derive macro instead macro_rules! router_error_error_stack_specific { ($($path: ident)::+ < $st: ident >, $($path2:ident)::* ($($inner_path2:ident)::+ <$st2:ident>) ) => { - impl From<$($path)::+ <$st>> for BachError { + impl From<$($path)::+ <$st>> for ApplicationError { fn from(err: $($path)::+ <$st> ) -> Self { $($path2)::*(err) } @@ -58,7 +57,7 @@ macro_rules! router_error_error_stack_specific { }; ($($path: ident)::+ <$($inner_path:ident)::+>, $($path2:ident)::* ($($inner_path2:ident)::+ <$st2:ident>) ) => { - impl<'a> From< $($path)::+ <$($inner_path)::+> > for BachError { + impl<'a> From< $($path)::+ <$($inner_path)::+> > for ApplicationError { fn from(err: $($path)::+ <$($inner_path)::+> ) -> Self { $($path2)::*(err) } @@ -114,7 +113,7 @@ impl_error_type!(EncryptionError, "Encryption error"); impl_error_type!(UnexpectedError, "Unexpected error"); #[derive(Debug, thiserror::Error)] -pub enum BachError { +pub enum ApplicationError { // Display's impl can be overridden by the attribute error marco. // Don't use Debug here, Debug gives error stack in response. #[error("{{ error_description: Error while Authenticating, error_message: {0} }}")] @@ -150,32 +149,32 @@ pub enum BachError { router_error_error_stack_specific!( error_stack::Report<storage_errors::DatabaseError>, - BachError::EDatabaseError(error_stack::Report<DatabaseError>) + ApplicationError::EDatabaseError(error_stack::Report<DatabaseError>) ); router_error_error_stack_specific!( error_stack::Report<AuthenticationError>, - BachError::EAuthenticationError(error_stack::Report<AuthenticationError>) + ApplicationError::EAuthenticationError(error_stack::Report<AuthenticationError>) ); router_error_error_stack_specific!( error_stack::Report<UnexpectedError>, - BachError::EUnexpectedError(error_stack::Report<UnexpectedError>) + ApplicationError::EUnexpectedError(error_stack::Report<UnexpectedError>) ); router_error_error_stack_specific!( error_stack::Report<ParsingError>, - BachError::EParsingError(error_stack::Report<ParsingError>) + ApplicationError::EParsingError(error_stack::Report<ParsingError>) ); router_error_error_stack_specific!( error_stack::Report<EncryptionError>, - BachError::EEncryptionError(error_stack::Report<EncryptionError>) + ApplicationError::EEncryptionError(error_stack::Report<EncryptionError>) ); -impl From<MetricsError> for BachError { +impl From<MetricsError> for ApplicationError { fn from(err: MetricsError) -> Self { Self::EMetrics(err) } } -impl From<std::io::Error> for BachError { +impl From<std::io::Error> for ApplicationError { fn from(err: std::io::Error) -> Self { Self::EIo(err) } @@ -187,7 +186,7 @@ impl From<ring::error::Unspecified> for EncryptionError { } } -impl From<ConfigError> for BachError { +impl From<ConfigError> for ApplicationError { fn from(err: ConfigError) -> Self { Self::ConfigurationError(err) } @@ -202,7 +201,7 @@ fn error_response<T: Display>(err: &T) -> actix_web::HttpResponse { )) } -impl ResponseError for BachError { +impl ResponseError for ApplicationError { fn status_code(&self) -> StatusCode { match self { Self::EParsingError(_) diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index 501b99fb073..139f1511ceb 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -30,7 +30,7 @@ pub async fn get_mandate( .find_mandate_by_merchant_id_mandate_id(&merchant_account.merchant_id, &req.mandate_id) .await .map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::MandateNotFound))?; - Ok(services::BachResponse::Json( + Ok(services::ApplicationResponse::Json( mandates::MandateResponse::from_db_mandate(state, mandate, &merchant_account).await?, )) } @@ -52,7 +52,7 @@ pub async fn revoke_mandate( .await .map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::MandateNotFound))?; - Ok(services::BachResponse::Json( + Ok(services::ApplicationResponse::Json( mandates::MandateRevokedResponse { mandate_id: mandate.mandate_id, status: mandate.mandate_status.foreign_into(), @@ -82,7 +82,7 @@ pub async fn get_customer_mandates( .await?, ); } - Ok(services::BachResponse::Json(response_vec)) + Ok(services::ApplicationResponse::Json(response_vec)) } } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 873d64c771a..06ba52964df 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -92,7 +92,7 @@ pub async fn add_payment_method( }) } } - .map(services::BachResponse::Json) + .map(services::ApplicationResponse::Json) } #[instrument(skip_all)] @@ -383,7 +383,7 @@ pub async fn list_payment_methods( response .is_empty() .then(|| Err(report!(errors::ApiErrorResponse::PaymentMethodNotFound))) - .unwrap_or(Ok(services::BachResponse::Json(response))) + .unwrap_or(Ok(services::ApplicationResponse::Json(response))) } fn filter_payment_methods( @@ -568,7 +568,7 @@ pub async fn list_customer_payment_method( customer_payment_methods: vec, }; - Ok(services::BachResponse::Json(response)) + Ok(services::ApplicationResponse::Json(response)) } pub async fn get_lookup_key_from_locker( @@ -751,23 +751,27 @@ pub async fn retrieve_payment_method( } else { None }; - Ok(services::BachResponse::Json(api::PaymentMethodResponse { - merchant_id: pm.merchant_id, - customer_id: Some(pm.customer_id), - payment_method_id: pm.payment_method_id, - payment_method: pm.payment_method.foreign_into(), - payment_method_type: pm.payment_method_type.map(ForeignInto::foreign_into), - payment_method_issuer: pm.payment_method_issuer, - card, - metadata: pm.metadata, - created: Some(pm.created_at), - payment_method_issuer_code: pm.payment_method_issuer_code.map(ForeignInto::foreign_into), - recurring_enabled: false, //TODO - installment_payment_enabled: false, //TODO - payment_experience: Some(vec![ - api_models::payment_methods::PaymentExperience::RedirectToUrl, - ]), //TODO, - })) + Ok(services::ApplicationResponse::Json( + api::PaymentMethodResponse { + merchant_id: pm.merchant_id, + customer_id: Some(pm.customer_id), + payment_method_id: pm.payment_method_id, + payment_method: pm.payment_method.foreign_into(), + payment_method_type: pm.payment_method_type.map(ForeignInto::foreign_into), + payment_method_issuer: pm.payment_method_issuer, + card, + metadata: pm.metadata, + created: Some(pm.created_at), + payment_method_issuer_code: pm + .payment_method_issuer_code + .map(ForeignInto::foreign_into), + recurring_enabled: false, //TODO + installment_payment_enabled: false, //TODO + payment_experience: Some(vec![ + api_models::payment_methods::PaymentExperience::RedirectToUrl, + ]), //TODO, + }, + )) } #[instrument(skip_all)] @@ -801,7 +805,7 @@ pub async fn delete_payment_method( } }; - Ok(services::BachResponse::Json( + Ok(services::ApplicationResponse::Json( api::DeletePaymentMethodResponse { payment_method_id: pm.payment_method_id, deleted: true, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 2f510fc0215..566b5b8b69e 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -247,7 +247,7 @@ where let payments_response = match response.change_context(errors::ApiErrorResponse::NotImplemented)? { - services::BachResponse::Json(response) => Ok(response), + services::ApplicationResponse::Json(response) => Ok(response), _ => Err(errors::ApiErrorResponse::InternalServerError) .into_report() .attach_printable("Failed to get the response in json"), @@ -261,7 +261,7 @@ where ) .attach_printable("No redirection response")?; - Ok(services::BachResponse::JsonForRedirection(result)) + Ok(services::ApplicationResponse::JsonForRedirection(result)) } pub async fn payments_response_for_redirection_flows<'a>( @@ -562,10 +562,12 @@ pub async fn list_payments( .into_iter() .map(ForeignInto::foreign_into) .collect(); - Ok(services::BachResponse::Json(api::PaymentListResponse { - size: data.len(), - data, - })) + Ok(services::ApplicationResponse::Json( + api::PaymentListResponse { + size: data.len(), + data, + }, + )) } pub async fn add_process_sync_task( diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 1a9ffaae862..0b8f13656ff 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -547,7 +547,7 @@ pub(crate) async fn call_payment_method( .await .attach_printable("Error on adding payment method")?; match resp { - crate::services::BachResponse::Json(payment_method) => { + crate::services::ApplicationResponse::Json(payment_method) => { Ok(payment_method) } _ => Err(report!(errors::ApiErrorResponse::InternalServerError) @@ -575,7 +575,9 @@ pub(crate) async fn call_payment_method( .await .attach_printable("Error on adding payment method")?; match resp { - crate::services::BachResponse::Json(payment_method) => Ok(payment_method), + crate::services::ApplicationResponse::Json(payment_method) => { + Ok(payment_method) + } _ => Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error on adding payment method")), } @@ -1156,7 +1158,7 @@ pub async fn make_ephemeral_key( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to create ephemeral key")?; - Ok(services::BachResponse::Json(ek)) + Ok(services::ApplicationResponse::Json(ek)) } pub async fn delete_ephemeral_key( @@ -1168,7 +1170,7 @@ pub async fn delete_ephemeral_key( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to delete ephemeral key")?; - Ok(services::BachResponse::Json(ek)) + Ok(services::ApplicationResponse::Json(ek)) } pub fn make_pg_redirect_response( diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 4aba347d326..f24fa8da540 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -160,7 +160,7 @@ where _server: &Server, _operation: Op, ) -> RouterResponse<Self> { - Ok(services::BachResponse::Json(Self { + Ok(services::ApplicationResponse::Json(Self { session_token: payment_data.sessions_token, payment_id: payment_data.payment_attempt.payment_id, client_secret: payment_data @@ -186,7 +186,7 @@ where _server: &Server, _operation: Op, ) -> RouterResponse<Self> { - Ok(services::BachResponse::Json(Self { + Ok(services::ApplicationResponse::Json(Self { verify_id: Some(data.payment_intent.payment_id), merchant_id: Some(data.payment_intent.merchant_id), client_secret: data.payment_intent.client_secret.map(masking::Secret::new), @@ -254,7 +254,7 @@ where let redirection_data = redirection_data.get_required_value("redirection_data")?; let form: RedirectForm = serde_json::from_value(redirection_data) .map_err(|_| errors::ApiErrorResponse::InternalServerError)?; - services::BachResponse::Form(form) + services::ApplicationResponse::Form(form) } else { let mut response: api::PaymentsResponse = request .try_into() @@ -271,7 +271,7 @@ where }) } - services::BachResponse::Json( + services::ApplicationResponse::Json( response .set_payment_id(Some(payment_attempt.payment_id)) .set_merchant_id(Some(payment_attempt.merchant_id)) @@ -341,7 +341,7 @@ where ) } } - None => services::BachResponse::Json(api::PaymentsResponse { + None => services::ApplicationResponse::Json(api::PaymentsResponse { payment_id: Some(payment_attempt.payment_id), merchant_id: Some(payment_attempt.merchant_id), status: payment_intent.status.foreign_into(), diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 8f33b253b97..d021f49bd0d 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -2,9 +2,9 @@ pub mod validator; use error_stack::{report, IntoReport, ResultExt}; use router_env::{instrument, tracing}; -use uuid::Uuid; use crate::{ + consts, core::{ errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt}, payments, utils as core_utils, @@ -45,9 +45,9 @@ pub async fn refund_create_core( .change_context(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?; // Amount is not passed in request refer from payment attempt. - amount = req.amount.unwrap_or(payment_attempt.amount); // FIXME: Need to that capture amount + amount = req.amount.unwrap_or(payment_attempt.amount); // [#298]: Need to that capture amount - //TODO: Can we change the flow based on some workflow idea + //[#299]: Can we change the flow based on some workflow idea utils::when(amount <= 0, || { Err(report!(errors::ApiErrorResponse::InvalidDataFormat { field_name: "amount".to_string(), @@ -82,7 +82,7 @@ pub async fn refund_create_core( req, ) .await - .map(services::BachResponse::Json) + .map(services::ApplicationResponse::Json) } #[instrument(skip_all)] @@ -180,7 +180,7 @@ where Fut: futures::Future<Output = RouterResult<T>>, T: ForeignInto<refunds::RefundResponse>, { - Ok(services::BachResponse::Json( + Ok(services::ApplicationResponse::Json( f(state, merchant_account, refund_id).await?.foreign_into(), )) } @@ -337,7 +337,7 @@ pub async fn refund_update_core( .await .change_context(errors::ApiErrorResponse::InternalServerError)?; - Ok(services::BachResponse::Json(response.foreign_into())) + Ok(services::ApplicationResponse::Json(response.foreign_into())) } // ********************************************** VALIDATIONS ********************************************** @@ -402,37 +402,52 @@ pub async fn validate_and_create_refund( .attach_printable("Failed to fetch refund")?; currency = payment_attempt.currency.get_required_value("currency")?; - // TODO: Add Connector Based Validation here. - validator::validate_payment_order_age(&payment_intent.created_at).change_context( - errors::ApiErrorResponse::InvalidDataFormat { - field_name: "created_at".to_string(), - expected_format: format!( - "created_at not older than {} days", - validator::REFUND_MAX_AGE - ), - }, - )?; + //[#249]: Add Connector Based Validation here. + validator::validate_payment_order_age( + &payment_intent.created_at, + state.conf.refund.max_age, + ) + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "created_at".to_string(), + expected_format: format!( + "created_at not older than {} days", + state.conf.refund.max_age, + ), + })?; validator::validate_refund_amount(payment_attempt.amount, &all_refunds, refund_amount) .change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?; - validator::validate_maximum_refund_against_payment_attempt(&all_refunds) - .change_context(errors::ApiErrorResponse::MaximumRefundCount)?; + validator::validate_maximum_refund_against_payment_attempt( + &all_refunds, + state.conf.refund.max_attempts, + ) + .change_context(errors::ApiErrorResponse::MaximumRefundCount)?; let connector = payment_attempt.connector.clone().ok_or_else(|| { report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("connector not populated in payment attempt.") })?; - refund_create_req = mk_new_refund( - req, - connector, - payment_attempt, - currency, - &refund_id, - &merchant_account.merchant_id, - refund_amount, - ); + refund_create_req = storage::RefundNew::default() + .set_refund_id(refund_id.to_string()) + .set_internal_reference_id(utils::generate_id(consts::ID_LENGTH, "refid")) + .set_external_reference_id(Some(refund_id)) + .set_payment_id(req.payment_id) + .set_merchant_id(merchant_account.merchant_id.clone()) + .set_connector_transaction_id(connecter_transaction_id.to_string()) + .set_connector(connector) + .set_refund_type(enums::RefundType::RegularRefund) + .set_total_amount(refund_amount) + .set_currency(currency) + .set_created_at(Some(common_utils::date_time::now())) + .set_modified_at(Some(common_utils::date_time::now())) + .set_refund_status(enums::RefundStatus::Pending) + .set_metadata(req.metadata) + .set_description(req.reason.clone()) + .set_attempt_id(payment_attempt.attempt_id.clone()) + .set_refund_reason(req.reason) + .to_owned(); refund = db .insert_refund(refund_create_req, merchant_account.storage_scheme) @@ -484,53 +499,11 @@ pub async fn refund_list( utils::when(data.is_empty(), || { Err(errors::ApiErrorResponse::RefundNotFound) })?; - Ok(services::BachResponse::Json( + Ok(services::ApplicationResponse::Json( api_models::refunds::RefundListResponse { data }, )) } -// ********************************************** UTILS ********************************************** - -// FIXME: function should not have more than 3 arguments. -// Consider to use builder pattern. -#[instrument] -fn mk_new_refund( - request: refunds::RefundRequest, - connector: String, - payment_attempt: &storage::PaymentAttempt, - currency: enums::Currency, - refund_id: &str, - merchant_id: &str, - refund_amount: i64, -) -> storage::RefundNew { - let current_time = common_utils::date_time::now(); - let connecter_transaction_id = match &payment_attempt.connector_transaction_id { - Some(id) => id, - None => "", - }; - storage::RefundNew { - refund_id: refund_id.to_string(), - internal_reference_id: Uuid::new_v4().to_string(), - external_reference_id: Some(refund_id.to_string()), - payment_id: request.payment_id, - merchant_id: merchant_id.to_string(), - // FIXME: remove the default. - connector_transaction_id: connecter_transaction_id.to_string(), - connector, - refund_type: enums::RefundType::RegularRefund, - total_amount: refund_amount, - currency, - refund_amount, - created_at: Some(current_time), - modified_at: Some(current_time), - refund_status: enums::RefundStatus::Pending, - metadata: request.metadata, - description: request.reason, - attempt_id: payment_attempt.attempt_id.clone(), - ..storage::RefundNew::default() - } -} - impl<F> TryFrom<types::RefundsRouterData<F>> for refunds::RefundResponse { type Error = error_stack::Report<errors::ApiErrorResponse>; @@ -548,7 +521,7 @@ impl<F> TryFrom<types::RefundsRouterData<F>> for refunds::RefundResponse { refund_id, amount: data.request.amount / 100, currency: data.request.currency.to_string(), - reason: Some("TODO: Not propagated".to_string()), // TODO: Not propagated + reason: data.request.reason, status, metadata: None, error_message, @@ -622,7 +595,7 @@ pub async fn schedule_refund_execution( } _ => { // Sync the refund for status check - //TODO: return refund status response + //[#300]: return refund status response match refund_type { api_models::refunds::RefundType::Scheduled => { add_refund_sync_task(db, &refund, runner) @@ -661,25 +634,6 @@ pub async fn sync_refund_with_gateway_workflow( ) })?; - let merchant_account = state - .store - .find_merchant_account_by_merchant_id(&refund_core.merchant_id) - .await - .map_err(|error| { - error.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) - })?; - - // FIXME we actually don't use this? - let _refund = state - .store - .find_refund_by_internal_reference_id_merchant_id( - &refund_core.refund_internal_reference_id, - &refund_core.merchant_id, - merchant_account.storage_scheme, - ) - .await - .map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::RefundNotFound))?; - let merchant_account = state .store .find_merchant_account_by_merchant_id(&refund_core.merchant_id) @@ -763,7 +717,6 @@ pub async fn trigger_refund_execute_workflow( .await .map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::RefundNotFound))?; match (&refund.sent_to_gateway, &refund.refund_status) { - //FIXME: Conversion should come from trait (false, enums::RefundStatus::Pending) => { let merchant_account = db .find_merchant_account_by_merchant_id(&refund.merchant_id) diff --git a/crates/router/src/core/refunds/validator.rs b/crates/router/src/core/refunds/validator.rs index 71e698a012f..3b80cff0e3c 100644 --- a/crates/router/src/core/refunds/validator.rs +++ b/crates/router/src/core/refunds/validator.rs @@ -10,9 +10,6 @@ use crate::{ utils, }; -pub(super) const REFUND_MAX_AGE: i64 = 365; -pub(super) const REFUND_MAX_ATTEMPTS: usize = 10; - #[derive(Debug, thiserror::Error)] pub enum RefundValidationError { #[error("The payment attempt was not successful")] @@ -38,7 +35,6 @@ pub fn validate_success_transaction( Ok(()) } -//todo: max refund request count #[instrument(skip_all)] pub fn validate_refund_amount( payment_attempt_amount: i64, // &storage::PaymentAttempt, @@ -71,11 +67,12 @@ pub fn validate_refund_amount( #[instrument(skip_all)] pub fn validate_payment_order_age( created_at: &PrimitiveDateTime, + refund_max_age: i64, ) -> CustomResult<(), RefundValidationError> { let current_time = common_utils::date_time::now(); utils::when( - (current_time - *created_at).whole_days() > REFUND_MAX_AGE, + (current_time - *created_at).whole_days() > refund_max_age, || Err(report!(RefundValidationError::OrderExpired)), ) } @@ -83,9 +80,9 @@ pub fn validate_payment_order_age( #[instrument(skip_all)] pub fn validate_maximum_refund_against_payment_attempt( all_refunds: &[storage::Refund], + refund_max_attempts: usize, ) -> CustomResult<(), RefundValidationError> { - // TODO: Make this configurable - utils::when(all_refunds.len() > REFUND_MAX_ATTEMPTS, || { + utils::when(all_refunds.len() > refund_max_attempts, || { Err(report!(RefundValidationError::MaxRefundCountReached)) }) } diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index a839d1d4b6f..86fa3fbfc79 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -28,7 +28,6 @@ pub async fn construct_refund_router_data<'a, F>( refund: &'a storage::Refund, ) -> RouterResult<types::RefundsRouterData<F>> { let db = &*state.store; - //TODO: everytime parsing the json may have impact? let merchant_connector_account = db .find_merchant_connector_account_by_merchant_id_connector( &merchant_account.merchant_id, @@ -86,6 +85,7 @@ pub async fn construct_refund_router_data<'a, F>( refund_amount: refund.refund_amount, currency, amount, + reason: refund.refund_reason.clone(), }, response: Ok(types::RefundsResponseData { diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 86d1e7348ac..81c70624d48 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -59,7 +59,7 @@ async fn payments_incoming_webhook_flow( .change_context(errors::WebhooksFlowError::PaymentsCoreFailed)?; match payments_response { - services::BachResponse::Json(payments_response) => { + services::ApplicationResponse::Json(payments_response) => { let payment_id = payments_response .payment_id .clone() diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index aec81c37069..6d15da921f2 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -290,6 +290,7 @@ mod storage { created_at: new.created_at.unwrap_or_else(date_time::now), updated_at: new.created_at.unwrap_or_else(date_time::now), description: new.description.clone(), + refund_reason: new.refund_reason.clone(), }; let field = format!( @@ -640,6 +641,7 @@ impl RefundInterface for MockDb { created_at: new.created_at.unwrap_or(current_time), updated_at: current_time, description: new.description, + refund_reason: new.refund_reason.clone(), }; refunds.push(refund.clone()); Ok(refund) diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 055896bec31..074f06597ce 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -32,7 +32,7 @@ use routes::AppState; pub use self::env::logger; use crate::{ configs::settings::Settings, - core::errors::{self, BachResult}, + core::errors::{self, ApplicationResult}, }; #[cfg(feature = "mimalloc")] @@ -110,7 +110,7 @@ pub fn mk_app( /// # Panics /// /// Unwrap used because without the value we can't start the server -pub async fn start_server(conf: Settings) -> BachResult<(Server, AppState)> { +pub async fn start_server(conf: Settings) -> ApplicationResult<(Server, AppState)> { logger::debug!(startup_config=?conf); let server = conf.server.clone(); let state = routes::AppState::new(conf).await; diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index ce07e4bedb0..8cfc61670d6 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -320,7 +320,7 @@ async fn handle_response( } #[derive(Debug, Eq, PartialEq)] -pub enum BachResponse<R> { +pub enum ApplicationResponse<R> { Json(R), StatusOk, TextPlain(String), @@ -329,11 +329,11 @@ pub enum BachResponse<R> { } #[derive(Debug, Eq, PartialEq, Serialize)] -pub struct BachRedirectResponse { +pub struct ApplicationRedirectResponse { pub url: String, } -impl From<&storage::PaymentAttempt> for BachRedirectResponse { +impl From<&storage::PaymentAttempt> for ApplicationRedirectResponse { fn from(payment_attempt: &storage::PaymentAttempt) -> Self { Self { url: format!( @@ -376,7 +376,7 @@ pub async fn server_wrap_util<'a, 'b, U, T, Q, F, Fut>( payload: T, func: F, api_auth: &dyn auth::AuthenticateAndFetch<U>, -) -> RouterResult<BachResponse<Q>> +) -> RouterResult<ApplicationResponse<Q>> where F: Fn(&'b AppState, U, T) -> Fut, Fut: Future<Output = RouterResponse<Q>>, @@ -402,7 +402,7 @@ pub async fn server_wrap<'a, 'b, T, U, Q, F, Fut>( ) -> HttpResponse where F: Fn(&'b AppState, U, T) -> Fut, - Fut: Future<Output = RouterResult<BachResponse<Q>>>, + Fut: Future<Output = RouterResult<ApplicationResponse<Q>>>, Q: Serialize + Debug + 'a, T: Debug, { @@ -415,7 +415,7 @@ where logger::info!(tag = ?Tag::BeginRequest); let res = match server_wrap_util(state, request, payload, func, api_auth).await { - Ok(BachResponse::Json(response)) => match serde_json::to_string(&response) { + Ok(ApplicationResponse::Json(response)) => match serde_json::to_string(&response) { Ok(res) => http_response_json(res), Err(_) => http_response_err( r#"{ @@ -425,19 +425,21 @@ where }"#, ), }, - Ok(BachResponse::StatusOk) => http_response_ok(), - Ok(BachResponse::TextPlain(text)) => http_response_plaintext(text), - Ok(BachResponse::JsonForRedirection(response)) => match serde_json::to_string(&response) { - Ok(res) => http_redirect_response(res, response), - Err(_) => http_response_err( - r#"{ + Ok(ApplicationResponse::StatusOk) => http_response_ok(), + Ok(ApplicationResponse::TextPlain(text)) => http_response_plaintext(text), + Ok(ApplicationResponse::JsonForRedirection(response)) => { + match serde_json::to_string(&response) { + Ok(res) => http_redirect_response(res, response), + Err(_) => http_response_err( + r#"{ "error": { "message": "Error serializing response from connector" } }"#, - ), - }, - Ok(BachResponse::Form(response)) => build_redirection_form(&response) + ), + } + } + Ok(ApplicationResponse::Form(response)) => build_redirection_form(&response) .respond_to(request) .map_into_boxed_body(), diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 2492fe6b16f..5cb34ad48fa 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -200,6 +200,7 @@ pub struct RefundsData { pub currency: storage_enums::Currency, /// Amount for the payment against which this refund is issued pub amount: i64, + pub reason: Option<String>, /// Amount to be refunded pub refund_amount: i64, } diff --git a/crates/router/src/types/api/webhooks.rs b/crates/router/src/types/api/webhooks.rs index cc0718979f7..813b380fcaf 100644 --- a/crates/router/src/types/api/webhooks.rs +++ b/crates/router/src/types/api/webhooks.rs @@ -136,7 +136,8 @@ pub trait IncomingWebhook: ConnectorCommon + Sync { fn get_webhook_api_response( &self, - ) -> CustomResult<services::api::BachResponse<serde_json::Value>, errors::ConnectorError> { - Ok(services::api::BachResponse::StatusOk) + ) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ConnectorError> + { + Ok(services::api::ApplicationResponse::StatusOk) } } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 170e86d6643..6922ffc3649 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -91,6 +91,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { }), connector_transaction_id: String::new(), refund_amount: 100, + reason: None, }, payment_method_id: None, response: Err(types::ErrorResponse::default()), diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs index b8bd87e325d..28dec76dfeb 100644 --- a/crates/router/tests/connectors/authorizedotnet.rs +++ b/crates/router/tests/connectors/authorizedotnet.rs @@ -91,6 +91,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { }), connector_transaction_id: String::new(), refund_amount: 1, + reason: None, }, response: Err(types::ErrorResponse::default()), payment_method_id: None, diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs index 7e3adddf155..34cd565a476 100644 --- a/crates/router/tests/connectors/checkout.rs +++ b/crates/router/tests/connectors/checkout.rs @@ -88,6 +88,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { }), connector_transaction_id: String::new(), refund_amount: 10, + reason: None, }, response: Err(types::ErrorResponse::default()), payment_method_id: None, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 5ae3ccb8865..b4266f7b43c 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -117,6 +117,7 @@ pub trait ConnectorActions: Connector { payment_method_data: types::api::PaymentMethod::Card(CCardType::default().0), connector_transaction_id: transaction_id, refund_amount: 100, + reason: None, }), ); call_connector(request, integration).await @@ -139,6 +140,7 @@ pub trait ConnectorActions: Connector { payment_method_data: types::api::PaymentMethod::Card(CCardType::default().0), connector_transaction_id: transaction_id, refund_amount: 100, + reason: None, }), ); call_connector(request, integration).await @@ -249,6 +251,7 @@ impl Default for PaymentRefundType { payment_method_data: types::api::PaymentMethod::Card(CCardType::default().0), connector_transaction_id: String::new(), refund_amount: 100, + reason: None, }; Self(data) } diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index f2561a3f0d1..5927d7ae80c 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -347,7 +347,7 @@ async fn payments_create_core() { mandate_id: None, ..Default::default() }; - let expected_response = services::BachResponse::Json(expected_response); + let expected_response = services::ApplicationResponse::Json(expected_response); let actual_response = payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>( &state, @@ -406,7 +406,7 @@ async fn payments_create_core() { // .update(&state.pg_conn, payment_intent_update) // .unwrap(); -// let expected_response = services::BachResponse::Form(services::RedirectForm { +// let expected_response = services::ApplicationResponse::Form(services::RedirectForm { // url: "http://example.com/payments".to_string(), // method: services::Method::Post, // form_fields: HashMap::from([("payment_id".to_string(), payment_id.clone())]), @@ -491,7 +491,7 @@ async fn payments_create_core_adyen_no_redirect() { browser_info: None, }; - let expected_response = services::BachResponse::Json(api::PaymentsResponse { + let expected_response = services::ApplicationResponse::Json(api::PaymentsResponse { payment_id: Some(payment_id.clone()), status: api_enums::IntentStatus::Processing, amount: 6540, diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index 171359299fe..618433ff9e1 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -98,7 +98,7 @@ async fn payments_create_core() { mandate_id: None, ..Default::default() }; - let expected_response = services::BachResponse::Json(expected_response); + let expected_response = services::ApplicationResponse::Json(expected_response); let actual_response = router::core::payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>( &state, @@ -162,7 +162,7 @@ async fn payments_create_core() { // .await // .unwrap(); // -// let expected_response = services::BachResponse::Form(services::RedirectForm { +// let expected_response = services::ApplicationResponse::Form(services::RedirectForm { // url: "http://example.com/payments".to_string(), // method: services::Method::Post, // form_fields: HashMap::from([("payment_id".to_string(), payment_id.clone())]), @@ -245,7 +245,7 @@ async fn payments_create_core_adyen_no_redirect() { browser_info: None, }; - let expected_response = services::BachResponse::Json(api::PaymentsResponse { + let expected_response = services::ApplicationResponse::Json(api::PaymentsResponse { payment_id: Some(payment_id.clone()), status: api_enums::IntentStatus::Processing, amount: 6540, diff --git a/crates/storage_models/src/refund.rs b/crates/storage_models/src/refund.rs index 1aa3e215055..e74935fdf5a 100644 --- a/crates/storage_models/src/refund.rs +++ b/crates/storage_models/src/refund.rs @@ -31,6 +31,7 @@ pub struct Refund { pub updated_at: PrimitiveDateTime, pub description: Option<String>, pub attempt_id: String, + pub refund_reason: Option<String>, } #[derive( @@ -43,6 +44,7 @@ pub struct Refund { router_derive::DebugAsDisplay, serde::Serialize, serde::Deserialize, + router_derive::Setter, )] #[diesel(table_name = refund)] pub struct RefundNew { @@ -67,6 +69,7 @@ pub struct RefundNew { pub modified_at: Option<PrimitiveDateTime>, pub description: Option<String>, pub attempt_id: String, + pub refund_reason: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs index 298a995614c..d70ad30733f 100644 --- a/crates/storage_models/src/schema.rs +++ b/crates/storage_models/src/schema.rs @@ -327,6 +327,7 @@ diesel::table! { modified_at -> Timestamp, description -> Nullable<Varchar>, attempt_id -> Varchar, + refund_reason -> Nullable<Varchar>, } } diff --git a/loadtest/config/Development.toml b/loadtest/config/Development.toml index f3f12cb77fe..3fbc108dd20 100644 --- a/loadtest/config/Development.toml +++ b/loadtest/config/Development.toml @@ -34,6 +34,10 @@ basilisk_host = "" [eph_key] validity = 1 +[refund] +max_attempts = 10 +max_age = 365 + [jwekey] locker_key_identifier1 = "" locker_key_identifier2 = "" diff --git a/migrations/2022-12-21-071825_add_refund_reason/down.sql b/migrations/2022-12-21-071825_add_refund_reason/down.sql new file mode 100644 index 00000000000..bd2eb6f82ec --- /dev/null +++ b/migrations/2022-12-21-071825_add_refund_reason/down.sql @@ -0,0 +1,2 @@ +ALTER TABLE REFUND +DROP COLUMN refund_reason; diff --git a/migrations/2022-12-21-071825_add_refund_reason/up.sql b/migrations/2022-12-21-071825_add_refund_reason/up.sql new file mode 100644 index 00000000000..bc921194c5f --- /dev/null +++ b/migrations/2022-12-21-071825_add_refund_reason/up.sql @@ -0,0 +1 @@ +ALTER TABLE REFUND ADD COLUMN refund_reason VARCHAR(255) DEFAULT NULL;
refactor
Replace Bach with Application on every naming (#292)
7c63c76011cec5fb398cff90b6237578c132b87d
2024-02-21 17:51:59
Sanchith Hegde
refactor(scheduler): improve code reusability and consumer logs (#3712)
false
diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs index 9e649279f24..76e280d6bc0 100644 --- a/crates/diesel_models/src/process_tracker.rs +++ b/crates/diesel_models/src/process_tracker.rs @@ -1,8 +1,10 @@ +use common_utils::ext_traits::Encode; use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; +use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{enums as storage_enums, schema::process_tracker}; +use crate::{enums as storage_enums, errors, schema::process_tracker, StorageResult}; #[derive( Clone, @@ -37,6 +39,13 @@ pub struct ProcessTracker { pub updated_at: PrimitiveDateTime, } +impl ProcessTracker { + #[inline(always)] + pub fn is_valid_business_status(&self, valid_statuses: &[&str]) -> bool { + valid_statuses.iter().any(|&x| x == self.business_status) + } +} + #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = process_tracker)] pub struct ProcessTrackerNew { @@ -55,6 +64,42 @@ pub struct ProcessTrackerNew { pub updated_at: PrimitiveDateTime, } +impl ProcessTrackerNew { + pub fn new<T>( + process_tracker_id: impl Into<String>, + task: impl Into<String>, + runner: ProcessTrackerRunner, + tag: impl IntoIterator<Item = impl Into<String>>, + tracking_data: T, + schedule_time: PrimitiveDateTime, + ) -> StorageResult<Self> + where + T: Serialize + std::fmt::Debug, + { + const BUSINESS_STATUS_PENDING: &str = "Pending"; + + let current_time = common_utils::date_time::now(); + Ok(Self { + id: process_tracker_id.into(), + name: Some(task.into()), + tag: tag.into_iter().map(Into::into).collect(), + runner: Some(runner.to_string()), + retry_count: 0, + schedule_time: Some(schedule_time), + rule: String::new(), + tracking_data: tracking_data + .encode_to_value() + .change_context(errors::DatabaseError::Others) + .attach_printable("Failed to serialize process tracker tracking data")?, + business_status: String::from(BUSINESS_STATUS_PENDING), + status: storage_enums::ProcessTrackerStatus::New, + event: vec![], + created_at: current_time, + updated_at: current_time, + }) + } +} + #[derive(Debug)] pub enum ProcessTrackerUpdate { Update { @@ -165,3 +210,39 @@ pub struct ProcessData { cache_name: String, process_tracker: ProcessTracker, } + +#[derive( + serde::Serialize, + serde::Deserialize, + Clone, + Copy, + Debug, + PartialEq, + Eq, + strum::EnumString, + strum::Display, +)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +#[strum(serialize_all = "SCREAMING_SNAKE_CASE")] +pub enum ProcessTrackerRunner { + PaymentsSyncWorkflow, + RefundWorkflowRouter, + DeleteTokenizeDataWorkflow, + ApiKeyExpiryWorkflow, +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use common_utils::ext_traits::StringExt; + + use super::ProcessTrackerRunner; + + #[test] + fn test_enum_to_string() { + let string_format = "PAYMENTS_SYNC_WORKFLOW".to_string(); + let enum_format: ProcessTrackerRunner = + string_format.parse_enum("ProcessTrackerRunner").unwrap(); + assert_eq!(enum_format, ProcessTrackerRunner::PaymentsSyncWorkflow); + } +} diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs index 5d376a4d7b1..70d24f0493c 100644 --- a/crates/redis_interface/src/commands.rs +++ b/crates/redis_interface/src/commands.rs @@ -596,7 +596,12 @@ impl super::RedisConnectionPool { None => self.pool.xread_map(count, block, streams, ids).await, } .into_report() - .change_context(errors::RedisError::StreamReadFailed) + .map_err(|err| match err.current_context().kind() { + RedisErrorKind::NotFound | RedisErrorKind::Parse => { + err.change_context(errors::RedisError::StreamEmptyOrNotAvailable) + } + _ => err.change_context(errors::RedisError::StreamReadFailed), + }) } // Consumer Group API diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index caa69ea1394..c2877535daa 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -14,7 +14,6 @@ use router::{ }, logger, routes, services::{self, api}, - types::storage::ProcessTrackerExt, workflows, }; use router_env::{instrument, tracing}; @@ -22,9 +21,7 @@ use scheduler::{ consumer::workflows::ProcessTrackerWorkflow, errors::ProcessTrackerError, workflows::ProcessTrackerWorkflows, SchedulerAppState, }; -use serde::{Deserialize, Serialize}; use storage_impl::errors::ApplicationError; -use strum::EnumString; use tokio::sync::{mpsc, oneshot}; const SCHEDULER_FLOW: &str = "SCHEDULER_FLOW"; @@ -209,17 +206,6 @@ pub async fn deep_health_check_func( Ok(response) } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, EnumString)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -#[strum(serialize_all = "SCREAMING_SNAKE_CASE")] -pub enum PTRunner { - PaymentsSyncWorkflow, - RefundWorkflowRouter, - DeleteTokenizeDataWorkflow, - #[cfg(feature = "email")] - ApiKeyExpiryWorkflow, -} - #[derive(Debug, Copy, Clone)] pub struct WorkflowRunner; @@ -229,25 +215,51 @@ impl ProcessTrackerWorkflows<routes::AppState> for WorkflowRunner { &'a self, state: &'a routes::AppState, process: storage::ProcessTracker, - ) -> Result<(), ProcessTrackerError> { - let runner = process.runner.clone().get_required_value("runner")?; - let runner: Option<PTRunner> = runner.parse_enum("PTRunner").ok(); - let operation: Box<dyn ProcessTrackerWorkflow<routes::AppState>> = match runner { - Some(PTRunner::PaymentsSyncWorkflow) => { - Box::new(workflows::payment_sync::PaymentsSyncWorkflow) - } - Some(PTRunner::RefundWorkflowRouter) => { - Box::new(workflows::refund_router::RefundWorkflowRouter) - } - Some(PTRunner::DeleteTokenizeDataWorkflow) => { - Box::new(workflows::tokenized_data::DeleteTokenizeDataWorkflow) - } - #[cfg(feature = "email")] - Some(PTRunner::ApiKeyExpiryWorkflow) => { - Box::new(workflows::api_key_expiry::ApiKeyExpiryWorkflow) + ) -> CustomResult<(), ProcessTrackerError> { + let runner = process + .runner + .clone() + .get_required_value("runner") + .change_context(ProcessTrackerError::MissingRequiredField) + .attach_printable("Missing runner field in process information")?; + let runner: storage::ProcessTrackerRunner = runner + .parse_enum("ProcessTrackerRunner") + .change_context(ProcessTrackerError::UnexpectedFlow) + .attach_printable("Failed to parse workflow runner name")?; + + let get_operation = |runner: storage::ProcessTrackerRunner| -> CustomResult< + Box<dyn ProcessTrackerWorkflow<routes::AppState>>, + ProcessTrackerError, + > { + match runner { + storage::ProcessTrackerRunner::PaymentsSyncWorkflow => { + Ok(Box::new(workflows::payment_sync::PaymentsSyncWorkflow)) + } + storage::ProcessTrackerRunner::RefundWorkflowRouter => { + Ok(Box::new(workflows::refund_router::RefundWorkflowRouter)) + } + storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow => Ok(Box::new( + workflows::tokenized_data::DeleteTokenizeDataWorkflow, + )), + storage::ProcessTrackerRunner::ApiKeyExpiryWorkflow => { + #[cfg(feature = "email")] + { + Ok(Box::new(workflows::api_key_expiry::ApiKeyExpiryWorkflow)) + } + + #[cfg(not(feature = "email"))] + { + Err(error_stack::report!(ProcessTrackerError::UnexpectedFlow)) + .attach_printable( + "Cannot run API key expiry workflow when email feature is disabled", + ) + } + } } - _ => Err(ProcessTrackerError::UnexpectedFlow)?, }; + + let operation = get_operation(runner)?; + let app_state = &state.clone(); let output = operation.execute_workflow(app_state, process.clone()).await; match output { @@ -259,11 +271,10 @@ impl ProcessTrackerWorkflows<routes::AppState> for WorkflowRunner { Ok(_) => (), Err(error) => { logger::error!(%error, "Failed while handling error"); - let status = process - .finish_with_status( - state.get_db().as_scheduler(), - "GLOBAL_FAILURE".to_string(), - ) + let status = state + .get_db() + .as_scheduler() + .finish_process_with_business_status(process, "GLOBAL_FAILURE".to_string()) .await; if let Err(err) = status { logger::error!(%err, "Failed while performing database operation: GLOBAL_FAILURE"); @@ -294,18 +305,3 @@ async fn start_scheduler( ) .await } - -#[cfg(test)] -mod workflow_tests { - #![allow(clippy::unwrap_used)] - use common_utils::ext_traits::StringExt; - - use super::PTRunner; - - #[test] - fn test_enum_to_string() { - let string_format = "PAYMENTS_SYNC_WORKFLOW".to_string(); - let enum_format: PTRunner = string_format.parse_enum("PTRunner").unwrap(); - assert_eq!(enum_format, PTRunner::PaymentsSyncWorkflow) - } -} diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index 21ef4037d81..851b7ba7571 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -156,18 +156,27 @@ impl super::settings::ApiKeys { use common_utils::fp_utils::when; #[cfg(feature = "aws_kms")] - return when(self.kms_encrypted_hash_key.is_default_or_empty(), || { + when(self.kms_encrypted_hash_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "API key hashing key must not be empty when KMS feature is enabled".into(), )) - }); + })?; #[cfg(not(feature = "aws_kms"))] when(self.hash_key.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "API key hashing key must not be empty".into(), )) - }) + })?; + + #[cfg(feature = "email")] + when(self.expiry_reminder_days.is_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "API key expiry reminder days must not be empty".into(), + )) + })?; + + Ok(()) } } diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index 39212ab3814..b3f8931cde5 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -11,8 +11,6 @@ use masking::ExposeInterface; use masking::{PeekInterface, StrongSecret}; use router_env::{instrument, tracing}; -#[cfg(feature = "email")] -use crate::types::storage::enums; use crate::{ configs::settings, consts, @@ -28,7 +26,8 @@ const API_KEY_EXPIRY_TAG: &str = "API_KEY"; #[cfg(feature = "email")] const API_KEY_EXPIRY_NAME: &str = "API_KEY_EXPIRY"; #[cfg(feature = "email")] -const API_KEY_EXPIRY_RUNNER: &str = "API_KEY_EXPIRY_WORKFLOW"; +const API_KEY_EXPIRY_RUNNER: diesel_models::ProcessTrackerRunner = + diesel_models::ProcessTrackerRunner::ApiKeyExpiryWorkflow; #[cfg(feature = "aws_kms")] use external_services::aws_kms::decrypt::AwsKmsDecrypt; @@ -245,15 +244,16 @@ pub async fn add_api_key_expiry_task( api_key.expires_at.map(|expires_at| { expires_at.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day))) }) - }); + }) + .ok_or(errors::ApiErrorResponse::InternalServerError) + .into_report() + .attach_printable("Failed to obtain initial process tracker schedule time")?; - if let Some(schedule_time) = schedule_time { - if schedule_time <= current_time { - return Ok(()); - } + if schedule_time <= current_time { + return Ok(()); } - let api_key_expiry_tracker = &storage::ApiKeyExpiryTrackingData { + let api_key_expiry_tracker = storage::ApiKeyExpiryTrackingData { key_id: api_key.key_id.clone(), merchant_id: api_key.merchant_id.clone(), // We need API key expiry too, because we need to decide on the schedule_time in @@ -261,30 +261,18 @@ pub async fn add_api_key_expiry_task( api_key_expiry: api_key.expires_at, expiry_reminder_days: expiry_reminder_days.clone(), }; - let api_key_expiry_workflow_model = serde_json::to_value(api_key_expiry_tracker) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable_lazy(|| { - format!("unable to serialize API key expiry tracker: {api_key_expiry_tracker:?}") - })?; - let process_tracker_entry = storage::ProcessTrackerNew { - id: generate_task_id_for_api_key_expiry_workflow(api_key.key_id.as_str()), - name: Some(String::from(API_KEY_EXPIRY_NAME)), - tag: vec![String::from(API_KEY_EXPIRY_TAG)], - runner: Some(String::from(API_KEY_EXPIRY_RUNNER)), - // Retry count specifies, number of times the current process (email) has been retried. - // It also acts as an index of expiry_reminder_days vector - retry_count: 0, + let process_tracker_id = generate_task_id_for_api_key_expiry_workflow(api_key.key_id.as_str()); + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + API_KEY_EXPIRY_NAME, + API_KEY_EXPIRY_RUNNER, + [API_KEY_EXPIRY_TAG], + api_key_expiry_tracker, schedule_time, - rule: String::new(), - tracking_data: api_key_expiry_workflow_model, - business_status: String::from("Pending"), - status: enums::ProcessTrackerStatus::New, - event: vec![], - created_at: current_time, - updated_at: current_time, - }; + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct API key expiry process tracker task")?; store .insert_process(process_tracker_entry) @@ -293,7 +281,7 @@ pub async fn add_api_key_expiry_task( .attach_printable_lazy(|| { format!( "Failed while inserting API key expiry reminder to process_tracker: api_key_id: {}", - api_key_expiry_tracker.key_id + api_key.key_id ) })?; metrics::TASKS_ADDED_COUNT.add( diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index b547027a1c7..622fed0738a 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -17,7 +17,7 @@ use crate::{ routes::metrics, types::{ api, domain, - storage::{self, enums, ProcessTrackerExt}, + storage::{self, enums}, }, utils::StringExt, }; @@ -998,33 +998,31 @@ pub async fn add_delete_tokenized_data_task( lookup_key: &str, pm: enums::PaymentMethod, ) -> RouterResult<()> { - let runner = "DELETE_TOKENIZE_DATA_WORKFLOW"; - let current_time = common_utils::date_time::now(); - let tracking_data = serde_json::to_value(storage::TokenizeCoreWorkflow { + let runner = storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow; + let process_tracker_id = format!("{runner}_{lookup_key}"); + let task = runner.to_string(); + let tag = ["BASILISK-V3"]; + let tracking_data = storage::TokenizeCoreWorkflow { lookup_key: lookup_key.to_owned(), pm, - }) - .into_report() + }; + let schedule_time = get_delete_tokenize_schedule_time(db, &pm, 0) + .await + .ok_or(errors::ApiErrorResponse::InternalServerError) + .into_report() + .attach_printable("Failed to obtain initial process tracker schedule time")?; + + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + &task, + runner, + tag, + tracking_data, + schedule_time, + ) .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable_lazy(|| format!("unable to convert into value {lookup_key:?}"))?; - - let schedule_time = get_delete_tokenize_schedule_time(db, &pm, 0).await; + .attach_printable("Failed to construct delete tokenized data process tracker task")?; - let process_tracker_entry = storage::ProcessTrackerNew { - id: format!("{runner}_{lookup_key}"), - name: Some(String::from(runner)), - tag: vec![String::from("BASILISK-V3")], - runner: Some(String::from(runner)), - retry_count: 0, - schedule_time, - rule: String::new(), - tracking_data, - business_status: String::from("Pending"), - status: enums::ProcessTrackerStatus::New, - event: vec![], - created_at: current_time, - updated_at: current_time, - }; let response = db.insert_process(process_tracker_entry).await; response.map(|_| ()).or_else(|err| { if err.current_context().is_db_unique_violation() { @@ -1056,10 +1054,11 @@ pub async fn start_tokenize_data_workflow( Ok(()) => { logger::info!("Card From locker deleted Successfully"); //mark task as finished - let id = tokenize_tracker.id.clone(); - tokenize_tracker - .clone() - .finish_with_status(db.as_scheduler(), format!("COMPLETED_BY_PT_{id}")) + db.as_scheduler() + .finish_process_with_business_status( + tokenize_tracker.clone(), + "COMPLETED_BY_PT".to_string(), + ) .await?; } Err(err) => { @@ -1104,7 +1103,11 @@ pub async fn retry_delete_tokenize( match schedule_time { Some(s_time) => { - let retry_schedule = pt.retry(db.as_scheduler(), s_time).await; + let retry_schedule = db + .as_scheduler() + .retry_process(pt, s_time) + .await + .map_err(Into::into); metrics::TASKS_RESET_COUNT.add( &metrics::CONTEXT, 1, @@ -1115,10 +1118,11 @@ pub async fn retry_delete_tokenize( ); retry_schedule } - None => { - pt.finish_with_status(db.as_scheduler(), "RETRIES_EXCEEDED".to_string()) - .await - } + None => db + .as_scheduler() + .finish_process_with_business_status(pt, "RETRIES_EXCEEDED".to_string()) + .await + .map_err(Into::into), } } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 7348a2b8f0c..050b0dd4b7b 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -25,7 +25,7 @@ use redis_interface::errors::RedisError; use router_env::{instrument, tracing}; #[cfg(feature = "olap")] use router_types::transformers::ForeignFrom; -use scheduler::{db::process_tracker::ProcessTrackerExt, errors as sch_errors, utils as pt_utils}; +use scheduler::utils as pt_utils; use time; pub use self::operations::{ @@ -2356,28 +2356,32 @@ pub async fn add_process_sync_task( db: &dyn StorageInterface, payment_attempt: &storage::PaymentAttempt, schedule_time: time::PrimitiveDateTime, -) -> Result<(), sch_errors::ProcessTrackerError> { +) -> CustomResult<(), errors::StorageError> { let tracking_data = api::PaymentsRetrieveRequest { force_sync: true, merchant_id: Some(payment_attempt.merchant_id.clone()), resource_id: api::PaymentIdType::PaymentAttemptId(payment_attempt.attempt_id.clone()), ..Default::default() }; - let runner = "PAYMENTS_SYNC_WORKFLOW"; + let runner = storage::ProcessTrackerRunner::PaymentsSyncWorkflow; let task = "PAYMENTS_SYNC"; + let tag = ["SYNC", "PAYMENT"]; let process_tracker_id = pt_utils::get_process_tracker_id( runner, task, &payment_attempt.attempt_id, &payment_attempt.merchant_id, ); - let process_tracker_entry = <storage::ProcessTracker>::make_process_tracker_new( + let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, + tag, tracking_data, schedule_time, - )?; + ) + .map_err(errors::StorageError::from) + .into_report()?; db.insert_process(process_tracker_entry).await?; Ok(()) @@ -2388,7 +2392,7 @@ pub async fn reset_process_sync_task( payment_attempt: &storage::PaymentAttempt, schedule_time: time::PrimitiveDateTime, ) -> Result<(), errors::ProcessTrackerError> { - let runner = "PAYMENTS_SYNC_WORKFLOW"; + let runner = storage::ProcessTrackerRunner::PaymentsSyncWorkflow; let task = "PAYMENTS_SYNC"; let process_tracker_id = pt_utils::get_process_tracker_id( runner, @@ -2400,8 +2404,8 @@ pub async fn reset_process_sync_task( .find_process_by_id(&process_tracker_id) .await? .ok_or(errors::ProcessTrackerError::ProcessFetchingFailed)?; - psync_process - .reset(db.as_scheduler(), schedule_time) + db.as_scheduler() + .reset_process(psync_process, schedule_time) .await?; Ok(()) } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 764752ba903..b3330f82f74 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1032,7 +1032,6 @@ where ); super::add_process_sync_task(&*state.store, payment_attempt, stime) .await - .into_report() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while adding task to process tracker") } else { diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 4b1c33296e6..06030262fbc 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -19,7 +19,7 @@ use crate::{ self, api::{self, refunds}, domain, - storage::{self, enums, ProcessTrackerExt}, + storage::{self, enums}, transformers::{ForeignFrom, ForeignInto}, }, utils::{self, OptionExt}, @@ -798,9 +798,9 @@ pub async fn schedule_refund_execution( ) -> RouterResult<storage::Refund> { // refunds::RefundResponse> { let db = &*state.store; - let runner = "REFUND_WORKFLOW_ROUTER"; + let runner = storage::ProcessTrackerRunner::RefundWorkflowRouter; let task = "EXECUTE_REFUND"; - let task_id = format!("{}_{}_{}", runner, task, refund.internal_reference_id); + let task_id = format!("{runner}_{task}_{}", refund.internal_reference_id); let refund_process = db .find_process_by_id(&task_id) @@ -909,10 +909,13 @@ pub async fn sync_refund_with_gateway_workflow( ]; match response.refund_status { status if terminal_status.contains(&status) => { - let id = refund_tracker.id.clone(); - refund_tracker - .clone() - .finish_with_status(state.store.as_scheduler(), format!("COMPLETED_BY_PT_{id}")) + state + .store + .as_scheduler() + .finish_process_with_business_status( + refund_tracker.clone(), + "COMPLETED_BY_PT".to_string(), + ) .await? } _ => { @@ -1020,18 +1023,29 @@ pub async fn trigger_refund_execute_workflow( None, ) .await?; - add_refund_sync_task(db, &updated_refund, "REFUND_WORKFLOW_ROUTER").await?; + add_refund_sync_task( + db, + &updated_refund, + storage::ProcessTrackerRunner::RefundWorkflowRouter, + ) + .await?; } (true, enums::RefundStatus::Pending) => { // create sync task - add_refund_sync_task(db, &refund, "REFUND_WORKFLOW_ROUTER").await?; + add_refund_sync_task( + db, + &refund, + storage::ProcessTrackerRunner::RefundWorkflowRouter, + ) + .await?; } (_, _) => { //mark task as finished - let id = refund_tracker.id.clone(); - refund_tracker - .clone() - .finish_with_status(db.as_scheduler(), format!("COMPLETED_BY_PT_{id}")) + db.as_scheduler() + .finish_process_with_business_status( + refund_tracker.clone(), + "COMPLETED_BY_PT".to_string(), + ) .await?; } }; @@ -1054,29 +1068,23 @@ pub fn refund_to_refund_core_workflow_model( pub async fn add_refund_sync_task( db: &dyn db::StorageInterface, refund: &storage::Refund, - runner: &str, + runner: storage::ProcessTrackerRunner, ) -> RouterResult<storage::ProcessTracker> { - let current_time = common_utils::date_time::now(); - let refund_workflow_model = serde_json::to_value(refund_to_refund_core_workflow_model(refund)) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable_lazy(|| format!("unable to convert into value {:?}", &refund))?; let task = "SYNC_REFUND"; - let process_tracker_entry = storage::ProcessTrackerNew { - id: format!("{}_{}_{}", runner, task, refund.internal_reference_id), - name: Some(String::from(task)), - tag: vec![String::from("REFUND")], - runner: Some(String::from(runner)), - retry_count: 0, - schedule_time: Some(common_utils::date_time::now()), - rule: String::new(), - tracking_data: refund_workflow_model, - business_status: String::from("Pending"), - status: enums::ProcessTrackerStatus::New, - event: vec![], - created_at: current_time, - updated_at: current_time, - }; + let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id); + let schedule_time = common_utils::date_time::now(); + let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); + let tag = ["REFUND"]; + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + task, + runner, + tag, + refund_workflow_tracking_data, + schedule_time, + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct refund sync process tracker task")?; let response = db .insert_process(process_tracker_entry) @@ -1101,29 +1109,23 @@ pub async fn add_refund_sync_task( pub async fn add_refund_execute_task( db: &dyn db::StorageInterface, refund: &storage::Refund, - runner: &str, + runner: storage::ProcessTrackerRunner, ) -> RouterResult<storage::ProcessTracker> { let task = "EXECUTE_REFUND"; - let current_time = common_utils::date_time::now(); - let refund_workflow_model = serde_json::to_value(refund_to_refund_core_workflow_model(refund)) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable_lazy(|| format!("unable to convert into value {:?}", &refund))?; - let process_tracker_entry = storage::ProcessTrackerNew { - id: format!("{}_{}_{}", runner, task, refund.internal_reference_id), - name: Some(String::from(task)), - tag: vec![String::from("REFUND")], - runner: Some(String::from(runner)), - retry_count: 0, - schedule_time: Some(common_utils::date_time::now()), - rule: String::new(), - tracking_data: refund_workflow_model, - business_status: String::from("Pending"), - status: enums::ProcessTrackerStatus::New, - event: vec![], - created_at: current_time, - updated_at: current_time, - }; + let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id); + let tag = ["REFUND"]; + let schedule_time = common_utils::date_time::now(); + let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + task, + runner, + tag, + refund_workflow_tracking_data, + schedule_time, + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct refund execute process tracker task")?; let response = db .insert_process(process_tracker_entry) @@ -1177,7 +1179,11 @@ pub async fn retry_refund_sync_task( match schedule_time { Some(s_time) => { - let retry_schedule = pt.retry(db.as_scheduler(), s_time).await; + let retry_schedule = db + .as_scheduler() + .retry_process(pt, s_time) + .await + .map_err(Into::into); metrics::TASKS_RESET_COUNT.add( &metrics::CONTEXT, 1, @@ -1185,9 +1191,10 @@ pub async fn retry_refund_sync_task( ); retry_schedule } - None => { - pt.finish_with_status(db.as_scheduler(), "RETRIES_EXCEEDED".to_string()) - .await - } + None => db + .as_scheduler() + .finish_process_with_business_status(pt, "RETRIES_EXCEEDED".to_string()) + .await + .map_err(Into::into), } } diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 213417b1318..78b95544ca1 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1396,15 +1396,6 @@ impl ProcessTrackerInterface for KafkaStore { .process_tracker_update_process_status_by_ids(task_ids, task_update) .await } - async fn update_process_tracker( - &self, - this: storage::ProcessTracker, - process: storage::ProcessTrackerUpdate, - ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { - self.diesel_store - .update_process_tracker(this, process) - .await - } async fn insert_process( &self, @@ -1413,6 +1404,32 @@ impl ProcessTrackerInterface for KafkaStore { self.diesel_store.insert_process(new).await } + async fn reset_process( + &self, + this: storage::ProcessTracker, + schedule_time: PrimitiveDateTime, + ) -> CustomResult<(), errors::StorageError> { + self.diesel_store.reset_process(this, schedule_time).await + } + + async fn retry_process( + &self, + this: storage::ProcessTracker, + schedule_time: PrimitiveDateTime, + ) -> CustomResult<(), errors::StorageError> { + self.diesel_store.retry_process(this, schedule_time).await + } + + async fn finish_process_with_business_status( + &self, + this: storage::ProcessTracker, + business_status: String, + ) -> CustomResult<(), errors::StorageError> { + self.diesel_store + .finish_process_with_business_status(this, business_status) + .await + } + async fn find_processes_by_time_status( &self, time_lower_limit: PrimitiveDateTime, diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 01decc89c4c..27fd6db8e7e 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -43,7 +43,9 @@ pub use data_models::payments::{ payment_intent::{PaymentIntentNew, PaymentIntentUpdate}, PaymentIntent, }; -pub use diesel_models::{ProcessTracker, ProcessTrackerNew, ProcessTrackerUpdate}; +pub use diesel_models::{ + ProcessTracker, ProcessTrackerNew, ProcessTrackerRunner, ProcessTrackerUpdate, +}; pub use scheduler::db::process_tracker; pub use self::{ diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index b9830c4ebc5..e9e1f323708 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -8,11 +8,7 @@ use crate::{ logger::error, routes::{metrics, AppState}, services::email::types::ApiKeyExpiryReminder, - types::{ - api, - domain::UserEmail, - storage::{self, ProcessTrackerExt}, - }, + types::{api, domain::UserEmail, storage}, utils::OptionExt, }; @@ -90,8 +86,10 @@ impl ProcessTrackerWorkflow<AppState> for ApiKeyExpiryWorkflow { == i32::try_from(tracking_data.expiry_reminder_days.len() - 1) .map_err(|_| errors::ProcessTrackerError::TypeConversionError)? { - process - .finish_with_status(state.get_db().as_scheduler(), "COMPLETED_BY_PT".to_string()) + state + .get_db() + .as_scheduler() + .finish_process_with_business_status(process, "COMPLETED_BY_PT".to_string()) .await? } // If tasks are remaining that has to be scheduled diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index b2296e17f70..92057b08899 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -3,7 +3,6 @@ use error_stack::ResultExt; use router_env::logger; use scheduler::{ consumer::{self, types::process_data, workflows::ProcessTrackerWorkflow}, - db::process_tracker::ProcessTrackerExt, errors as sch_errors, utils as scheduler_utils, SchedulerAppState, }; @@ -91,12 +90,10 @@ impl ProcessTrackerWorkflow<AppState> for PaymentsSyncWorkflow { ]; match &payment_data.payment_attempt.status { status if terminal_status.contains(status) => { - let id = process.id.clone(); - process - .finish_with_status( - state.get_db().as_scheduler(), - format!("COMPLETED_BY_PT_{id}"), - ) + state + .get_db() + .as_scheduler() + .finish_process_with_business_status(process, "COMPLETED_BY_PT".to_string()) .await? } _ => { @@ -274,11 +271,12 @@ pub async fn retry_sync_task( match schedule_time { Some(s_time) => { - pt.retry(db.as_scheduler(), s_time).await?; + db.as_scheduler().retry_process(pt, s_time).await?; Ok(false) } None => { - pt.finish_with_status(db.as_scheduler(), "RETRIES_EXCEEDED".to_string()) + db.as_scheduler() + .finish_process_with_business_status(pt, "RETRIES_EXCEEDED".to_string()) .await?; Ok(true) } diff --git a/crates/scheduler/src/consumer.rs b/crates/scheduler/src/consumer.rs index ccc943afba3..e069db28da7 100644 --- a/crates/scheduler/src/consumer.rs +++ b/crates/scheduler/src/consumer.rs @@ -18,9 +18,8 @@ use uuid::Uuid; use super::env::logger; pub use super::workflows::ProcessTrackerWorkflow; use crate::{ - configs::settings::SchedulerSettings, - db::process_tracker::{ProcessTrackerExt, ProcessTrackerInterface}, - errors, metrics, utils as pt_utils, SchedulerAppState, SchedulerInterface, + configs::settings::SchedulerSettings, db::process_tracker::ProcessTrackerInterface, errors, + metrics, utils as pt_utils, SchedulerAppState, SchedulerInterface, }; // Valid consumer business statuses @@ -59,7 +58,7 @@ pub async fn start_consumer<T: SchedulerAppState + 'static>( let consumer_operation_counter = sync::Arc::new(atomic::AtomicU64::new(0)); let signal = get_allowed_signals() .map_err(|error| { - logger::error!("Signal Handler Error: {:?}", error); + logger::error!(?error, "Signal Handler Error"); errors::ProcessTrackerError::ConfigurationError }) .into_report() @@ -80,8 +79,8 @@ pub async fn start_consumer<T: SchedulerAppState + 'static>( pt_utils::consumer_operation_handler( state.clone(), settings.clone(), - |err| { - logger::error!(%err); + |error| { + logger::error!(?error, "Failed to perform consumer operation"); }, sync::Arc::clone(&consumer_operation_counter), workflow_selector, @@ -94,7 +93,7 @@ pub async fn start_consumer<T: SchedulerAppState + 'static>( loop { shutdown_interval.tick().await; let active_tasks = consumer_operation_counter.load(atomic::Ordering::Acquire); - logger::error!("{}", active_tasks); + logger::info!("Active tasks: {active_tasks}"); match active_tasks { 0 => { logger::info!("Terminating consumer"); @@ -130,7 +129,7 @@ pub async fn consumer_operations<T: SchedulerAppState + 'static>( .consumer_group_create(&stream_name, &group_name, &RedisEntryId::AfterLastID) .await; if group_created.is_err() { - logger::info!("Consumer group already exists"); + logger::info!("Consumer group {group_name} already exists"); } let mut tasks = state @@ -148,7 +147,7 @@ pub async fn consumer_operations<T: SchedulerAppState + 'static>( pt_utils::add_histogram_metrics(&pickup_time, task, &stream_name); metrics::TASK_CONSUMED.add(&metrics::CONTEXT, 1, &[]); - // let runner = workflow_selector(task)?.ok_or(errors::ProcessTrackerError::UnexpectedFlow)?; + handler.push(tokio::task::spawn(start_workflow( state.clone(), task.clone(), @@ -171,6 +170,11 @@ pub async fn fetch_consumer_tasks( ) -> CustomResult<Vec<storage::ProcessTracker>, errors::ProcessTrackerError> { let batches = pt_utils::get_batches(redis_conn, stream_name, group_name, consumer_name).await?; + // Returning early to avoid execution of database queries when `batches` is empty + if batches.is_empty() { + return Ok(Vec::new()); + } + let mut tasks = batches.into_iter().fold(Vec::new(), |mut acc, batch| { acc.extend_from_slice( batch @@ -209,15 +213,20 @@ pub async fn start_workflow<T>( process: storage::ProcessTracker, _pickup_time: PrimitiveDateTime, workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + std::fmt::Debug, -) -> Result<(), errors::ProcessTrackerError> +) -> CustomResult<(), errors::ProcessTrackerError> where T: SchedulerAppState, { tracing::Span::current().record("workflow_id", Uuid::new_v4().to_string()); - logger::info!("{:?}", process.name.as_ref()); + logger::info!(pt.name=?process.name, pt.id=%process.id); + let res = workflow_selector .trigger_workflow(&state.clone(), process.clone()) - .await; + .await + .map_err(|error| { + logger::error!(?error, "Failed to trigger workflow"); + error + }); metrics::TASK_PROCESSED.add(&metrics::CONTEXT, 1, &[]); res } @@ -228,7 +237,7 @@ pub async fn consumer_error_handler( process: storage::ProcessTracker, error: errors::ProcessTrackerError, ) -> CustomResult<(), errors::ProcessTrackerError> { - logger::error!(pt.name = ?process.name, pt.id = %process.id, ?error, "ERROR: Failed while executing workflow"); + logger::error!(pt.name=?process.name, pt.id=%process.id, ?error, "Failed to execute workflow"); state .process_tracker_update_process_status_by_ids( diff --git a/crates/scheduler/src/consumer/workflows.rs b/crates/scheduler/src/consumer/workflows.rs index 3b897347bed..3e8a4c8e502 100644 --- a/crates/scheduler/src/consumer/workflows.rs +++ b/crates/scheduler/src/consumer/workflows.rs @@ -1,8 +1,9 @@ use async_trait::async_trait; use common_utils::errors::CustomResult; pub use diesel_models::process_tracker as storage; +use router_env::logger; -use crate::{db::process_tracker::ProcessTrackerExt, errors, SchedulerAppState}; +use crate::{errors, SchedulerAppState}; pub type WorkflowSelectorFn = fn(&storage::ProcessTracker) -> Result<(), errors::ProcessTrackerError>; @@ -14,15 +15,16 @@ pub trait ProcessTrackerWorkflows<T>: Send + Sync { &'a self, _state: &'a T, _process: storage::ProcessTracker, - ) -> Result<(), errors::ProcessTrackerError> { + ) -> CustomResult<(), errors::ProcessTrackerError> { Err(errors::ProcessTrackerError::NotImplemented)? } + async fn execute_workflow<'a>( &'a self, operation: Box<dyn ProcessTrackerWorkflow<T>>, state: &'a T, process: storage::ProcessTracker, - ) -> Result<(), errors::ProcessTrackerError> + ) -> CustomResult<(), errors::ProcessTrackerError> where T: SchedulerAppState, { @@ -35,16 +37,18 @@ pub trait ProcessTrackerWorkflows<T>: Send + Sync { .await { Ok(_) => (), - Err(_error) => { - // logger::error!(%error, "Failed while handling error"); - let status = process - .finish_with_status( - state.get_db().as_scheduler(), - "GLOBAL_FAILURE".to_string(), - ) + Err(error) => { + logger::error!( + ?error, + "Failed to handle process tracker workflow execution error" + ); + let status = app_state + .get_db() + .as_scheduler() + .finish_process_with_business_status(process, "GLOBAL_FAILURE".to_string()) .await; - if let Err(_err) = status { - // logger::error!(%err, "Failed while performing database operation: GLOBAL_FAILURE"); + if let Err(error) = status { + logger::error!(?error, "Failed to update process business status"); } } }, @@ -55,7 +59,7 @@ pub trait ProcessTrackerWorkflows<T>: Send + Sync { #[async_trait] pub trait ProcessTrackerWorkflow<T>: Send + Sync { - // The core execution of the workflow + /// The core execution of the workflow async fn execute_workflow<'a>( &'a self, _state: &'a T, @@ -63,9 +67,11 @@ pub trait ProcessTrackerWorkflow<T>: Send + Sync { ) -> Result<(), errors::ProcessTrackerError> { Err(errors::ProcessTrackerError::NotImplemented)? } - // Callback function after successful execution of the `execute_workflow` + + /// Callback function after successful execution of the `execute_workflow` async fn success_handler<'a>(&'a self, _state: &'a T, _process: storage::ProcessTracker) {} - // Callback function after error received from `execute_workflow` + + /// Callback function after error received from `execute_workflow` async fn error_handler<'a>( &'a self, _state: &'a T, @@ -75,18 +81,3 @@ pub trait ProcessTrackerWorkflow<T>: Send + Sync { Err(errors::ProcessTrackerError::NotImplemented)? } } - -// #[cfg(test)] -// mod workflow_tests { -// #![allow(clippy::unwrap_used)] -// use common_utils::ext_traits::StringExt; - -// use super::PTRunner; - -// #[test] -// fn test_enum_to_string() { -// let string_format = "PAYMENTS_SYNC_WORKFLOW".to_string(); -// let enum_format: PTRunner = string_format.parse_enum("PTRunner").unwrap(); -// assert_eq!(enum_format, PTRunner::PaymentsSyncWorkflow) -// } -// } diff --git a/crates/scheduler/src/db/process_tracker.rs b/crates/scheduler/src/db/process_tracker.rs index 728c146a64e..ac20d4b293f 100644 --- a/crates/scheduler/src/db/process_tracker.rs +++ b/crates/scheduler/src/db/process_tracker.rs @@ -2,11 +2,10 @@ use common_utils::errors::CustomResult; pub use diesel_models as storage; use diesel_models::enums as storage_enums; use error_stack::{IntoReport, ResultExt}; -use serde::Serialize; use storage_impl::{connection, errors, mock_db::MockDb}; use time::PrimitiveDateTime; -use crate::{errors as sch_errors, metrics, scheduler::Store, SchedulerInterface}; +use crate::{metrics, scheduler::Store}; #[async_trait::async_trait] pub trait ProcessTrackerInterface: Send + Sync + 'static { @@ -32,17 +31,30 @@ pub trait ProcessTrackerInterface: Send + Sync + 'static { task_ids: Vec<String>, task_update: storage::ProcessTrackerUpdate, ) -> CustomResult<usize, errors::StorageError>; - async fn update_process_tracker( - &self, - this: storage::ProcessTracker, - process: storage::ProcessTrackerUpdate, - ) -> CustomResult<storage::ProcessTracker, errors::StorageError>; async fn insert_process( &self, new: storage::ProcessTrackerNew, ) -> CustomResult<storage::ProcessTracker, errors::StorageError>; + async fn reset_process( + &self, + this: storage::ProcessTracker, + schedule_time: PrimitiveDateTime, + ) -> CustomResult<(), errors::StorageError>; + + async fn retry_process( + &self, + this: storage::ProcessTracker, + schedule_time: PrimitiveDateTime, + ) -> CustomResult<(), errors::StorageError>; + + async fn finish_process_with_business_status( + &self, + this: storage::ProcessTracker, + business_status: String, + ) -> CustomResult<(), errors::StorageError>; + async fn find_processes_by_time_status( &self, time_lower_limit: PrimitiveDateTime, @@ -120,16 +132,58 @@ impl ProcessTrackerInterface for Store { .into_report() } - async fn update_process_tracker( + async fn reset_process( &self, this: storage::ProcessTracker, - process: storage::ProcessTrackerUpdate, - ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; - this.update(&conn, process) - .await - .map_err(Into::into) - .into_report() + schedule_time: PrimitiveDateTime, + ) -> CustomResult<(), errors::StorageError> { + self.update_process( + this, + storage::ProcessTrackerUpdate::StatusRetryUpdate { + status: storage_enums::ProcessTrackerStatus::New, + retry_count: 0, + schedule_time, + }, + ) + .await?; + Ok(()) + } + + async fn retry_process( + &self, + this: storage::ProcessTracker, + schedule_time: PrimitiveDateTime, + ) -> CustomResult<(), errors::StorageError> { + metrics::TASK_RETRIED.add(&metrics::CONTEXT, 1, &[]); + let retry_count = this.retry_count + 1; + self.update_process( + this, + storage::ProcessTrackerUpdate::StatusRetryUpdate { + status: storage_enums::ProcessTrackerStatus::Pending, + retry_count, + schedule_time, + }, + ) + .await?; + Ok(()) + } + + async fn finish_process_with_business_status( + &self, + this: storage::ProcessTracker, + business_status: String, + ) -> CustomResult<(), errors::StorageError> { + self.update_process( + this, + storage::ProcessTrackerUpdate::StatusUpdate { + status: storage_enums::ProcessTrackerStatus::Finish, + business_status: Some(business_status), + }, + ) + .await + .attach_printable("Failed to update business status of process")?; + metrics::TASK_FINISHED.add(&metrics::CONTEXT, 1, &[]); + Ok(()) } async fn process_tracker_update_process_status_by_ids( @@ -215,143 +269,39 @@ impl ProcessTrackerInterface for MockDb { Err(errors::StorageError::MockDbError)? } - async fn update_process_tracker( + async fn reset_process( &self, _this: storage::ProcessTracker, - _process: storage::ProcessTrackerUpdate, - ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { + _schedule_time: PrimitiveDateTime, + ) -> CustomResult<(), errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } - async fn process_tracker_update_process_status_by_ids( + async fn retry_process( &self, - _task_ids: Vec<String>, - _task_update: storage::ProcessTrackerUpdate, - ) -> CustomResult<usize, errors::StorageError> { + _this: storage::ProcessTracker, + _schedule_time: PrimitiveDateTime, + ) -> CustomResult<(), errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } -} - -#[async_trait::async_trait] -pub trait ProcessTrackerExt { - fn is_valid_business_status(&self, valid_statuses: &[&str]) -> bool; - - fn make_process_tracker_new<'a, T>( - process_tracker_id: String, - task: &'a str, - runner: &'a str, - tracking_data: T, - schedule_time: PrimitiveDateTime, - ) -> Result<storage::ProcessTrackerNew, sch_errors::ProcessTrackerError> - where - T: Serialize; - - async fn reset( - self, - db: &dyn SchedulerInterface, - schedule_time: PrimitiveDateTime, - ) -> Result<(), sch_errors::ProcessTrackerError>; - - async fn retry( - self, - db: &dyn SchedulerInterface, - schedule_time: PrimitiveDateTime, - ) -> Result<(), sch_errors::ProcessTrackerError>; - - async fn finish_with_status( - self, - db: &dyn SchedulerInterface, - status: String, - ) -> Result<(), sch_errors::ProcessTrackerError>; -} - -#[async_trait::async_trait] -impl ProcessTrackerExt for storage::ProcessTracker { - fn is_valid_business_status(&self, valid_statuses: &[&str]) -> bool { - valid_statuses.iter().any(|x| x == &self.business_status) - } - - fn make_process_tracker_new<'a, T>( - process_tracker_id: String, - task: &'a str, - runner: &'a str, - tracking_data: T, - schedule_time: PrimitiveDateTime, - ) -> Result<storage::ProcessTrackerNew, sch_errors::ProcessTrackerError> - where - T: Serialize, - { - let current_time = common_utils::date_time::now(); - Ok(storage::ProcessTrackerNew { - id: process_tracker_id, - name: Some(String::from(task)), - tag: vec![String::from("SYNC"), String::from("PAYMENT")], - runner: Some(String::from(runner)), - retry_count: 0, - schedule_time: Some(schedule_time), - rule: String::new(), - tracking_data: serde_json::to_value(tracking_data) - .map_err(|_| sch_errors::ProcessTrackerError::SerializationFailed)?, - business_status: String::from("Pending"), - status: storage_enums::ProcessTrackerStatus::New, - event: vec![], - created_at: current_time, - updated_at: current_time, - }) - } - async fn reset( - self, - db: &dyn SchedulerInterface, - schedule_time: PrimitiveDateTime, - ) -> Result<(), sch_errors::ProcessTrackerError> { - db.update_process_tracker( - self.clone(), - storage::ProcessTrackerUpdate::StatusRetryUpdate { - status: storage_enums::ProcessTrackerStatus::New, - retry_count: 0, - schedule_time, - }, - ) - .await?; - Ok(()) - } - - async fn retry( - self, - db: &dyn SchedulerInterface, - schedule_time: PrimitiveDateTime, - ) -> Result<(), sch_errors::ProcessTrackerError> { - metrics::TASK_RETRIED.add(&metrics::CONTEXT, 1, &[]); - db.update_process_tracker( - self.clone(), - storage::ProcessTrackerUpdate::StatusRetryUpdate { - status: storage_enums::ProcessTrackerStatus::Pending, - retry_count: self.retry_count + 1, - schedule_time, - }, - ) - .await?; - Ok(()) + async fn finish_process_with_business_status( + &self, + _this: storage::ProcessTracker, + _business_status: String, + ) -> CustomResult<(), errors::StorageError> { + // [#172]: Implement function for `MockDb` + Err(errors::StorageError::MockDbError)? } - async fn finish_with_status( - self, - db: &dyn SchedulerInterface, - status: String, - ) -> Result<(), sch_errors::ProcessTrackerError> { - db.update_process( - self, - storage::ProcessTrackerUpdate::StatusUpdate { - status: storage_enums::ProcessTrackerStatus::Finish, - business_status: Some(status), - }, - ) - .await - .attach_printable("Failed while updating status of the process")?; - metrics::TASK_FINISHED.add(&metrics::CONTEXT, 1, &[]); - Ok(()) + async fn process_tracker_update_process_status_by_ids( + &self, + _task_ids: Vec<String>, + _task_update: storage::ProcessTrackerUpdate, + ) -> CustomResult<usize, errors::StorageError> { + // [#172]: Implement function for `MockDb` + Err(errors::StorageError::MockDbError)? } } diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs index f6a340e9d59..174efd637e9 100644 --- a/crates/scheduler/src/utils.rs +++ b/crates/scheduler/src/utils.rs @@ -8,7 +8,7 @@ use diesel_models::enums::{self, ProcessTrackerStatus}; pub use diesel_models::process_tracker as storage; use error_stack::{report, ResultExt}; use redis_interface::{RedisConnectionPool, RedisEntryId}; -use router_env::opentelemetry; +use router_env::{instrument, opentelemetry, tracing}; use uuid::Uuid; use super::{ @@ -178,7 +178,7 @@ pub async fn get_batches( group_name: &str, consumer_name: &str, ) -> CustomResult<Vec<ProcessTrackerBatch>, errors::ProcessTrackerError> { - let response = conn + let response = match conn .stream_read_with_options( stream_name, RedisEntryId::UndeliveredEntryID, @@ -188,10 +188,20 @@ pub async fn get_batches( Some((group_name, consumer_name)), ) .await - .map_err(|error| { - logger::warn!(%error, "Warning: finding batch in stream"); - error.change_context(errors::ProcessTrackerError::BatchNotFound) - })?; + { + Ok(response) => response, + Err(error) => { + if let redis_interface::errors::RedisError::StreamEmptyOrNotAvailable = + error.current_context() + { + logger::debug!("No batches processed as stream is empty"); + return Ok(Vec::new()); + } else { + return Err(error.change_context(errors::ProcessTrackerError::BatchNotFound)); + } + } + }; + metrics::BATCHES_CONSUMED.add(&metrics::CONTEXT, 1, &[]); let (batches, entry_ids): (Vec<Vec<ProcessTrackerBatch>>, Vec<Vec<String>>) = response.into_values().map(|entries| { @@ -217,13 +227,13 @@ pub async fn get_batches( conn.stream_acknowledge_entries(stream_name, group_name, entry_ids.clone()) .await .map_err(|error| { - logger::error!(%error, "Error acknowledging batch in stream"); + logger::error!(?error, "Error acknowledging batch in stream"); error.change_context(errors::ProcessTrackerError::BatchUpdateFailed) })?; conn.stream_delete_entries(stream_name, entry_ids.clone()) .await .map_err(|error| { - logger::error!(%error, "Error deleting batch from stream"); + logger::error!(?error, "Error deleting batch from stream"); error.change_context(errors::ProcessTrackerError::BatchDeleteFailed) })?; @@ -231,7 +241,7 @@ pub async fn get_batches( } pub fn get_process_tracker_id<'a>( - runner: &'a str, + runner: storage::ProcessTrackerRunner, task_name: &'a str, txn_id: &'a str, merchant_id: &'a str, @@ -243,6 +253,7 @@ pub fn get_time_from_delta(delta: Option<i32>) -> Option<time::PrimitiveDateTime delta.map(|t| common_utils::date_time::now().saturating_add(time::Duration::seconds(t.into()))) } +#[instrument(skip_all)] pub async fn consumer_operation_handler<E, T: Send + Sync + 'static>( state: T, settings: sync::Arc<SchedulerSettings>,
refactor
improve code reusability and consumer logs (#3712)
13fe58450bad094fb2b4745ecf76bc2df8b96798
2024-03-22 16:21:18
chikke srujan
feat(payouts): Add user roles for payouts (#4167)
false
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index 2e3d60024d3..31da8386ab6 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -32,6 +32,8 @@ pub enum Permission { UsersWrite, MerchantAccountCreate, WebhookEventRead, + PayoutWrite, + PayoutRead, } #[derive(Debug, serde::Serialize)] @@ -48,6 +50,7 @@ pub enum PermissionModule { ThreeDsDecisionManager, SurchargeDecisionManager, AccountCreate, + Payouts, } #[derive(Debug, serde::Serialize)] diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs index c8d1c05bb37..0eeb0f27f07 100644 --- a/crates/router/src/routes/payouts.rs +++ b/crates/router/src/routes/payouts.rs @@ -9,7 +9,7 @@ use super::app::AppState; use crate::types::api::payments as payment_types; use crate::{ core::{api_locking, payouts::*}, - services::{api, authentication as auth}, + services::{api, authentication as auth, authorization::permissions::Permission}, types::api::payouts as payout_types, }; @@ -77,7 +77,11 @@ pub async fn payouts_retrieve( &req, payout_retrieve_request, |state, auth, req| payouts_retrieve_core(state, auth.merchant_account, auth.key_store, req), - &auth::ApiKeyAuth, + auth::auth_type( + &auth::ApiKeyAuth, + &auth::JWTAuth(Permission::PayoutRead), + req.headers(), + ), api_locking::LockAction::NotApplicable, )) .await @@ -225,7 +229,11 @@ pub async fn payouts_list( &req, payload, |state, auth, req| payouts_list_core(state, auth.merchant_account, req), - &auth::ApiKeyAuth, + auth::auth_type( + &auth::ApiKeyAuth, + &auth::JWTAuth(Permission::PayoutRead), + req.headers(), + ), api_locking::LockAction::NotApplicable, )) .await @@ -259,7 +267,11 @@ pub async fn payouts_list_by_filter( &req, payload, |state, auth, req| payouts_filtered_list_core(state, auth.merchant_account, req), - &auth::ApiKeyAuth, + auth::auth_type( + &auth::ApiKeyAuth, + &auth::JWTAuth(Permission::PayoutRead), + req.headers(), + ), api_locking::LockAction::NotApplicable, )) .await @@ -293,7 +305,11 @@ pub async fn payouts_list_available_filters( &req, payload, |state, auth, req| payouts_list_available_filters_core(state, auth.merchant_account, req), - &auth::ApiKeyAuth, + auth::auth_type( + &auth::ApiKeyAuth, + &auth::JWTAuth(Permission::PayoutRead), + req.headers(), + ), api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs index 7b82e84d64c..371087cc303 100644 --- a/crates/router/src/services/authorization/info.rs +++ b/crates/router/src/services/authorization/info.rs @@ -41,6 +41,7 @@ pub enum PermissionModule { ThreeDsDecisionManager, SurchargeDecisionManager, AccountCreate, + Payouts, } impl PermissionModule { @@ -57,7 +58,8 @@ impl PermissionModule { Self::Disputes => "Everything related to disputes - like creating and viewing dispute related information are within this module", Self::ThreeDsDecisionManager => "View and configure 3DS decision rules configured for a merchant", Self::SurchargeDecisionManager =>"View and configure surcharge decision rules configured for a merchant", - Self::AccountCreate => "Create new account within your organization" + Self::AccountCreate => "Create new account within your organization", + Self::Payouts => "Everything related to payouts - like creating and viewing payout related information are within this module" } } } @@ -168,6 +170,14 @@ impl ModuleInfo { Permission::MerchantAccountCreate, ]), }, + PermissionModule::Payouts => Self { + module: module_name, + description, + permissions: get_permission_info_from_permissions(&[ + Permission::PayoutRead, + Permission::PayoutWrite, + ]), + }, } } } @@ -184,10 +194,10 @@ fn get_group_info_from_permission_group(group: PermissionGroup) -> GroupInfo { fn get_group_description(group: PermissionGroup) -> &'static str { match group { PermissionGroup::OperationsView => { - "View Payments, Refunds, Mandates, Disputes and Customers" + "View Payments, Refunds, Payouts, Mandates, Disputes and Customers" } PermissionGroup::OperationsManage => { - "Create, modify and delete Payments, Refunds, Mandates, Disputes and Customers" + "Create, modify and delete Payments, Refunds, Payouts, Mandates, Disputes and Customers" } PermissionGroup::ConnectorsView => { "View connected Payment Processors, Payout Processors and Fraud & Risk Manager details" diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs index 33647eb9a39..b68bef213cd 100644 --- a/crates/router/src/services/authorization/permission_groups.rs +++ b/crates/router/src/services/authorization/permission_groups.rs @@ -19,22 +19,24 @@ pub fn get_permissions_vec(permission_group: &PermissionGroup) -> &[Permission] } } -pub static OPERATIONS_VIEW: [Permission; 6] = [ +pub static OPERATIONS_VIEW: [Permission; 7] = [ Permission::PaymentRead, Permission::RefundRead, Permission::MandateRead, Permission::DisputeRead, Permission::CustomerRead, Permission::MerchantAccountRead, + Permission::PayoutRead, ]; -pub static OPERATIONS_MANAGE: [Permission; 6] = [ +pub static OPERATIONS_MANAGE: [Permission; 7] = [ Permission::PaymentWrite, Permission::RefundWrite, Permission::MandateWrite, Permission::DisputeWrite, Permission::CustomerWrite, Permission::MerchantAccountRead, + Permission::PayoutWrite, ]; pub static CONNECTORS_VIEW: [Permission; 2] = [ diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs index b5ba72df05e..997eff8274e 100644 --- a/crates/router/src/services/authorization/permissions.rs +++ b/crates/router/src/services/authorization/permissions.rs @@ -31,6 +31,8 @@ pub enum Permission { UsersWrite, MerchantAccountCreate, WebhookEventRead, + PayoutRead, + PayoutWrite, } impl Permission { @@ -69,6 +71,8 @@ impl Permission { Self::UsersWrite => "Invite users, assign and update roles", Self::MerchantAccountCreate => "Create merchant account", Self::WebhookEventRead => "View webhook events", + Self::PayoutRead => "View all payouts", + Self::PayoutWrite => "Create payout, download payout data", } } } diff --git a/crates/router/src/services/authorization/predefined_permissions.rs b/crates/router/src/services/authorization/predefined_permissions.rs index bd0f37e2a0d..50f9a7196b8 100644 --- a/crates/router/src/services/authorization/predefined_permissions.rs +++ b/crates/router/src/services/authorization/predefined_permissions.rs @@ -64,6 +64,8 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::UsersRead, Permission::UsersWrite, Permission::MerchantAccountCreate, + Permission::PayoutRead, + Permission::PayoutWrite, ], name: None, is_invitable: false, @@ -88,6 +90,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::MandateRead, Permission::CustomerRead, Permission::UsersRead, + Permission::PayoutRead, ], name: None, is_invitable: false, @@ -126,6 +129,8 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::UsersRead, Permission::UsersWrite, Permission::MerchantAccountCreate, + Permission::PayoutRead, + Permission::PayoutWrite, ], name: Some("Organization Admin"), is_invitable: false, @@ -164,6 +169,8 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::Analytics, Permission::UsersRead, Permission::UsersWrite, + Permission::PayoutRead, + Permission::PayoutWrite, ], name: Some("Admin"), is_invitable: true, @@ -188,6 +195,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::CustomerRead, Permission::Analytics, Permission::UsersRead, + Permission::PayoutRead, ], name: Some("View Only"), is_invitable: true, @@ -213,6 +221,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::Analytics, Permission::UsersRead, Permission::UsersWrite, + Permission::PayoutRead, ], name: Some("IAM"), is_invitable: true, @@ -238,6 +247,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::CustomerRead, Permission::Analytics, Permission::UsersRead, + Permission::PayoutRead, ], name: Some("Developer"), is_invitable: true, @@ -268,6 +278,8 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::CustomerRead, Permission::Analytics, Permission::UsersRead, + Permission::PayoutRead, + Permission::PayoutWrite, ], name: Some("Operator"), is_invitable: true, @@ -289,6 +301,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: Permission::MandateRead, Permission::CustomerRead, Permission::Analytics, + Permission::PayoutRead, ], name: Some("Customer Support"), is_invitable: true, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 63272732e63..176b5810158 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -808,6 +808,7 @@ impl From<info::PermissionModule> for user_role_api::PermissionModule { info::PermissionModule::ThreeDsDecisionManager => Self::ThreeDsDecisionManager, info::PermissionModule::SurchargeDecisionManager => Self::SurchargeDecisionManager, info::PermissionModule::AccountCreate => Self::AccountCreate, + info::PermissionModule::Payouts => Self::Payouts, } } } diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index fa9eba8c27f..23b5bcf0f38 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -44,6 +44,8 @@ impl From<Permission> for user_role_api::Permission { Permission::UsersWrite => Self::UsersWrite, Permission::MerchantAccountCreate => Self::MerchantAccountCreate, Permission::WebhookEventRead => Self::WebhookEventRead, + Permission::PayoutRead => Self::PayoutRead, + Permission::PayoutWrite => Self::PayoutWrite, } } } diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 28b8f9ef796..1868eb9b4d9 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -3866,64 +3866,6 @@ ] } }, - "/payouts/list": { - "get": { - "tags": [ - "Payouts" - ], - "summary": "Payouts - List", - "description": "Payouts - List", - "operationId": "List payouts", - "responses": { - "200": { - "description": "Payouts listed", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PayoutListResponse" - } - } - } - }, - "404": { - "description": "Payout not found" - } - }, - "security": [ - { - "api_key": [] - } - ] - }, - "post": { - "tags": [ - "Payouts" - ], - "summary": "Payouts - Filter", - "description": "Payouts - Filter", - "operationId": "Filter payouts", - "responses": { - "200": { - "description": "Payouts filtered", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PayoutListResponse" - } - } - } - }, - "404": { - "description": "Payout not found" - } - }, - "security": [ - { - "api_key": [] - } - ] - } - }, "/payouts/{payout_id}": { "get": { "tags": [ @@ -4116,6 +4058,64 @@ ] } }, + "/payouts/list": { + "get": { + "tags": [ + "Payouts" + ], + "summary": "Payouts - List", + "description": "Payouts - List", + "operationId": "List payouts", + "responses": { + "200": { + "description": "Payouts listed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PayoutListResponse" + } + } + } + }, + "404": { + "description": "Payout not found" + } + }, + "security": [ + { + "api_key": [] + } + ] + }, + "post": { + "tags": [ + "Payouts" + ], + "summary": "Payouts - Filter", + "description": "Payouts - Filter", + "operationId": "Filter payouts", + "responses": { + "200": { + "description": "Payouts filtered", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PayoutListResponse" + } + } + } + }, + "404": { + "description": "Payout not found" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, "/api_keys/{merchant_id)": { "post": { "tags": [
feat
Add user roles for payouts (#4167)
15ad6da0793be4bc149ae2e92f4805735be8712a
2025-03-07 13:18:27
Sahkal Poddar
fix(dashboard): Added auth key to juspay threeds server (#7457)
false
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 7404fcf18f2..2708fe11af5 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -4668,4 +4668,6 @@ name="acquirer_merchant_id" label="Acquirer Merchant Id" placeholder="Enter Acquirer Merchant Id" required=true -type="Text" \ No newline at end of file +type="Text" +[juspaythreedsserver.connector_auth.HeaderKey] +api_key="API Key" \ No newline at end of file diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index a816ed42777..da8f9ba62e5 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -4610,3 +4610,5 @@ label="Acquirer Merchant Id" placeholder="Enter Acquirer Merchant Id" required=true type="Text" +[juspaythreedsserver.connector_auth.HeaderKey] +api_key="API Key" \ No newline at end of file
fix
Added auth key to juspay threeds server (#7457)
7885b2a213f474da3e018ddeb56bc6e407c48471
2024-01-24 05:48:36
github-actions
chore(postman): update Postman collection files
false
diff --git a/postman/collection-json/adyen_uk.postman_collection.json b/postman/collection-json/adyen_uk.postman_collection.json index 26963aa8abb..91a03afa47c 100644 --- a/postman/collection-json/adyen_uk.postman_collection.json +++ b/postman/collection-json/adyen_uk.postman_collection.json @@ -472,7 +472,7 @@ "language": "json" } }, - "raw": "{\"connector_type\":\"fiz_operations\",\"connector_name\":\"adyen\",\"connector_account_details\":{\"auth_type\":\"BodyKey\",\"api_key\":\"{{connector_api_key}}\",\"key1\":\"{{connector_key1}}\",\"api_secret\":\"{{connector_api_secret}}\"},\"test_mode\":false,\"disabled\":false,\"business_country\":\"US\",\"business_label\":\"default\",\"payment_methods_enabled\":[{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"card_networks\":[\"AmericanExpress\",\"Discover\",\"Interac\",\"JCB\",\"Mastercard\",\"Visa\",\"DinersClub\",\"UnionPay\",\"RuPay\"],\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"debit\",\"card_networks\":[\"AmericanExpress\",\"Discover\",\"Interac\",\"JCB\",\"Mastercard\",\"Visa\",\"DinersClub\",\"UnionPay\",\"RuPay\"],\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"payment_method_type\":\"klarna\",\"payment_experience\":\"redirect_to_url\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"affirm\",\"payment_experience\":\"redirect_to_url\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"afterpay_clearpay\",\"payment_experience\":\"redirect_to_url\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"pay_bright\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"walley\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"paypal\",\"payment_experience\":\"redirect_to_url\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"google_pay\",\"payment_experience\":\"invoke_sdk_client\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"apple_pay\",\"payment_experience\":\"invoke_sdk_client\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"mobile_pay\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"ali_pay\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"we_chat_pay\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"mb_way\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"gift_card\",\"payment_method_types\":[{\"payment_method_type\":\"givex\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_redirect\",\"payment_method_types\":[{\"payment_method_type\":\"giropay\",\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"eps\",\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sofort\",\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"blik\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"trustly\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"online_banking_czech_republic\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"online_banking_finland\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"online_banking_poland\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"online_banking_slovakia\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bancontact_card\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_debit\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bacs\",\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"google_pay\":{\"allowed_payment_methods\":[{\"type\":\"CARD\",\"parameters\":{\"allowed_auth_methods\":[\"PAN_ONLY\",\"CRYPTOGRAM_3DS\"],\"allowed_card_networks\":[\"AMEX\",\"DISCOVER\",\"INTERAC\",\"JCB\",\"MASTERCARD\",\"VISA\"]},\"tokenization_specification\":{\"type\":\"PAYMENT_GATEWAY\"}}],\"merchant_info\":{\"merchant_name\":\"Narayan Bhat\"}},\"apple_pay\":{\"session_token_data\":{\"initiative\":\"web\",\"certificate\":\"LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUdKakNDQlE2Z0F3SUJBZ0lRRENzRmFrVkNLU01uc2JacTc1YTI0ekFOQmdrcWhraUc5dzBCQVFzRkFEQjEKTVVRd1FnWURWUVFERER0QmNIQnNaU0JYYjNKc1pIZHBaR1VnUkdWMlpXeHZjR1Z5SUZKbGJHRjBhVzl1Y3lCRApaWEowYVdacFkyRjBhVzl1SUVGMWRHaHZjbWwwZVRFTE1Ba0dBMVVFQ3d3Q1J6TXhFekFSQmdOVkJBb01Da0Z3CmNHeGxJRWx1WXk0eEN6QUpCZ05WQkFZVEFsVlRNQjRYRFRJeU1USXdPREE1TVRJeE1Wb1hEVEkxTURFd05qQTUKTVRJeE1Gb3dnYWd4SmpBa0Jnb0praWFKay9Jc1pBRUJEQlp0WlhKamFHRnVkQzVqYjIwdVlXUjVaVzR1YzJGdQpNVHN3T1FZRFZRUUREREpCY0hCc1pTQlFZWGtnVFdWeVkyaGhiblFnU1dSbGJuUnBkSGs2YldWeVkyaGhiblF1ClkyOXRMbUZrZVdWdUxuTmhiakVUTUJFR0ExVUVDd3dLV1UwNVZUY3pXakpLVFRFc01Db0dBMVVFQ2d3alNsVlQKVUVGWklGUkZRMGhPVDB4UFIwbEZVeUJRVWtsV1FWUkZJRXhKVFVsVVJVUXdnZ0VpTUEwR0NTcUdTSWIzRFFFQgpBUVVBQTRJQkR3QXdnZ0VLQW9JQkFRRDhIUy81ZmJZNVJLaElYU3pySEpoeTVrNmY0YUdMaEltYklLaXFYRUlUCnVSQ2RHcGcyMExZM1VhTlBlYXZXTVRIUTBpK3d1RzlZWFVhYzV5eGE0cHg5eHlmQlVIejhzeU9pMjdYNVZaVG8KTlFhd2F6dGM5aGpZc1B2K0s2UW9oaWRTQWZ3cDhMdThkQ0lVZlhQWHBjdjFqVVRyRCtlc1RJTFZUb1FUTmhDcwplQlJtUS9nK05WdTB5c3BqeUYxU2l6VG9BK1BML3NrMlJEYWNaWC9vWTB1R040VWd4c0JYWHdZM0dKbTFSQ3B1CjM0Y2d0UC9kaHNBM1Ixb1VOb0gyQkZBSm9xK3pyUnl3U1RCSEhNMGpEQ2lncVU1RktwL1pBbHdzYmg1WVZOU00KWksrQ0pTK1BPTzlVNGVkeHJmTGlBVkhnQTgzRG43Z2U4K29nV1Y0Z0hUNmhBZ01CQUFHamdnSjhNSUlDZURBTQpCZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZBbit3QldRK2E5a0NwSVN1U1lvWXd5WDdLZXlNSEFHCkNDc0dBUVVGQndFQkJHUXdZakF0QmdnckJnRUZCUWN3QW9ZaGFIUjBjRG92TDJObGNuUnpMbUZ3Y0d4bExtTnYKYlM5M2QyUnlaek11WkdWeU1ERUdDQ3NHQVFVRkJ6QUJoaVZvZEhSd09pOHZiMk56Y0M1aGNIQnNaUzVqYjIwdgpiMk56Y0RBekxYZDNaSEpuTXpBNU1JSUJMUVlEVlIwZ0JJSUJKRENDQVNBd2dnRWNCZ2txaGtpRzkyTmtCUUV3CmdnRU5NSUhSQmdnckJnRUZCUWNDQWpDQnhBeUJ3VkpsYkdsaGJtTmxJRzl1SUhSb2FYTWdRMlZ5ZEdsbWFXTmgKZEdVZ1lua2dZVzU1SUhCaGNuUjVJRzkwYUdWeUlIUm9ZVzRnUVhCd2JHVWdhWE1nY0hKdmFHbGlhWFJsWkM0ZwpVbVZtWlhJZ2RHOGdkR2hsSUdGd2NHeHBZMkZpYkdVZ2MzUmhibVJoY21RZ2RHVnliWE1nWVc1a0lHTnZibVJwCmRHbHZibk1nYjJZZ2RYTmxMQ0JqWlhKMGFXWnBZMkYwWlNCd2IyeHBZM2tnWVc1a0lHTmxjblJwWm1sallYUnAKYjI0Z2NISmhZM1JwWTJVZ2MzUmhkR1Z0Wlc1MGN5NHdOd1lJS3dZQkJRVUhBZ0VXSzJoMGRIQnpPaTh2ZDNkMwpMbUZ3Y0d4bExtTnZiUzlqWlhKMGFXWnBZMkYwWldGMWRHaHZjbWwwZVM4d0V3WURWUjBsQkF3d0NnWUlLd1lCCkJRVUhBd0l3SFFZRFZSME9CQllFRk5RSysxcUNHbDRTQ1p6SzFSUmpnb05nM0hmdk1BNEdBMVVkRHdFQi93UUUKQXdJSGdEQlBCZ2txaGtpRzkyTmtCaUFFUWd4QVFVUkNRemxDTmtGRE5USkVRems0TnpCRk5qYzJNVFpFUkRJdwpPVUkwTWtReE1UVXlSVVpFTURVeFFVRXhRekV6T0ROR00wUkROa1V5TkVNelFqRkVSVEFQQmdrcWhraUc5Mk5rCkJpNEVBZ1VBTUEwR0NTcUdTSWIzRFFFQkN3VUFBNElCQVFBSFR6NTU2RUs5VVp6R0RVd2cvcmFibmYrUXFSYkgKcllVS0ZNcWQwUDhFTHZGMmYrTzN0ZXlDWHNBckF4TmVMY2hRSGVTNUFJOHd2azdMQ0xLUmJCdWJQQy9NVmtBKwpCZ3h5STg2ejJOVUNDWml4QVM1d2JFQWJYOStVMFp2RHp5Y01BbUNrdVVHZjNwWXR5TDNDaEplSGRvOEwwdmdvCnJQWElUSzc4ZjQzenNzYjBTNE5xbTE0eS9LNCs1ZkUzcFUxdEJqME5tUmdKUVJLRnB6MENpV2RPd1BRTk5BYUMKYUNNU2NiYXdwUTBjWEhaZDJWVjNtem4xdUlITEVtaU5GTWVxeEprbjZhUXFFQnNndDUzaUFxcmZMNjEzWStScAppd0tENXVmeU0wYzBweTYyZmkvWEwwS2c4ajEwWU1VdWJpd2dHajAzZThQWTB6bWUvcGZCZ3p6VQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg==\",\"display_name\":\"applepay\",\"certificate_keys\":\"LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JSUV2Z0lCQURBTkJna3Foa2lHOXcwQkFRRUZBQVNDQktnd2dnU2tBZ0VBQW9JQkFRRDhIUy81ZmJZNVJLaEkKWFN6ckhKaHk1azZmNGFHTGhJbWJJS2lxWEVJVHVSQ2RHcGcyMExZM1VhTlBlYXZXTVRIUTBpK3d1RzlZWFVhYwo1eXhhNHB4OXh5ZkJVSHo4c3lPaTI3WDVWWlRvTlFhd2F6dGM5aGpZc1B2K0s2UW9oaWRTQWZ3cDhMdThkQ0lVCmZYUFhwY3YxalVUckQrZXNUSUxWVG9RVE5oQ3NlQlJtUS9nK05WdTB5c3BqeUYxU2l6VG9BK1BML3NrMlJEYWMKWlgvb1kwdUdONFVneHNCWFh3WTNHSm0xUkNwdTM0Y2d0UC9kaHNBM1Ixb1VOb0gyQkZBSm9xK3pyUnl3U1RCSApITTBqRENpZ3FVNUZLcC9aQWx3c2JoNVlWTlNNWksrQ0pTK1BPTzlVNGVkeHJmTGlBVkhnQTgzRG43Z2U4K29nCldWNGdIVDZoQWdNQkFBRUNnZ0VBZFNaRzVhTFJxdmpKVFo3bVFYWHZMT3p4dWY5SlpxQTJwUHZmQkJLTXJjZC8KL2RDZXpGSGRhZ1VvWXNUQjRXekluaVVjL2Z3bDJTUzJyREFMZjB2dnRjNTJIYkQ5OHhwMnc3VmVjTGFnMCtuWAo2dUJaSEZCS3FWNU1LZ1l6YUpVMTdqaDM2VEV3dTFnbmdlZnRqVlpBV1NERTFvbDBlSzZ3Mk5kOExjVWdxRkxUCjVHYUlBV01nd0NKL3pzQmwydUV1Y0Q4S21WL1Z2MkVCQVJLWGZtci92UU1NelZrNkhhalprVGZqbWY2cWFVQVMKQWlFblROcHBic2ZrdTk2VGdIa2owWm10VWc0SFkzSU9qWFlpaGJsSjJzQ1JjS3p6cXkxa3B3WlpHcHo1NXEzbgphSXEwenJ3RjlpTUZubEhCa04yK3FjSnhzcDNTalhRdFRLTTY4WHRrVlFLQmdRRC8wemtCVlExR2Q1U0Mzb2czCnM3QWRCZ243dnVMdUZHZFFZY3c0OUppRGw1a1BZRXlKdGQvTVpNOEpFdk1nbVVTeUZmczNZcGtmQ2VGbUp0S3QKMnNNNEdCRWxqTVBQNjI3Q0QrV3c4L3JpWmlOZEg3OUhPRjRneTRGbjBycDNqanlLSWF1OHJISDQwRUUvSkVyOQpxWFQ1SGdWMmJQOGhMcW5sSjFmSDhpY2Zkd0tCZ1FEOFNWQ3ZDV2txQkh2SzE5ZDVTNlArdm5hcXhnTWo0U0srCnJ6L1I1c3pTaW5lS045VEhyeVkxYUZJbVFJZjJYOUdaQXBocUhrckxtQ3BIcURHOWQ3WDVQdUxxQzhmc09kVTYKRzhWaFRXeXdaSVNjdGRSYkk5S2xKUFk2V2ZDQjk0ODNVaDJGbW1xV2JuNWcwZUJxZWZzamVVdEtHekNRaGJDYworR1dBREVRSXB3S0JnUURmaWYvN3pBZm5sVUh1QU9saVV0OEczV29IMGtxVTRydE1IOGpGMCtVWXgzVDFYSjVFCmp1blp2aFN5eHg0dlUvNFU1dVEzQnk3cFVrYmtiZlFWK2x3dlBjaHQyVXlZK0E0MkFKSWlSMjdvT1h1Wk9jNTQKT3liMDNSNWNUR1NuWjJBN0N5VDNubStRak5rV2hXNEpyUE1MWTFJK293dGtRVlF2YW10bnlZNnFEUUtCZ0ZYWgpLT0IzSmxjSzhZa0R5Nm5WeUhkZUhvbGNHaU55YjkxTlN6MUUrWHZIYklnWEdZdmRtUFhoaXRyRGFNQzR1RjBGCjJoRjZQMTlxWnpDOUZqZnY3WGRrSTlrYXF5eENQY0dwUTVBcHhZdDhtUGV1bEJWemFqR1NFMHVsNFVhSWxDNXgKL2VQQnVQVjVvZjJXVFhST0Q5eHhZT0pWd0QvZGprekw1ZFlkMW1UUEFvR0JBTWVwY3diVEphZ3BoZk5zOHY0WAprclNoWXplbVpxY2EwQzRFc2QwNGYwTUxHSlVNS3Zpck4zN0g1OUFjT2IvNWtZcTU5WFRwRmJPWjdmYlpHdDZnCkxnM2hWSHRacElOVGJ5Ni9GOTBUZ09Za3RxUnhNVmc3UFBxbjFqdEFiVU15eVpVZFdHcFNNMmI0bXQ5dGhlUDEKblhMR09NWUtnS2JYbjZXWWN5K2U5eW9ICi0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0KCg==\",\"initiative_context\":\"hyperswitch-sdk-test.netlify.app\",\"merchant_identifier\":\"merchant.com.adyen.san\"},\"payment_request_data\":{\"label\":\"applepay pvt.ltd\",\"supported_networks\":[\"visa\",\"masterCard\",\"amex\",\"discover\"],\"merchant_capabilities\":[\"supports3DS\"]}}}}" + "raw": "{\"connector_type\":\"fiz_operations\",\"connector_name\":\"adyen\",\"connector_account_details\":{\"auth_type\":\"BodyKey\",\"api_key\":\"{{connector_api_key}}\",\"key1\":\"{{connector_key1}}\",\"api_secret\":\"{{connector_api_secret}}\"},\"test_mode\":false,\"disabled\":false,\"business_country\":\"US\",\"business_label\":\"default\",\"payment_methods_enabled\":[{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"card_networks\":[\"AmericanExpress\",\"Discover\",\"Interac\",\"JCB\",\"Mastercard\",\"Visa\",\"DinersClub\",\"UnionPay\",\"RuPay\"],\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"debit\",\"card_networks\":[\"AmericanExpress\",\"Discover\",\"Interac\",\"JCB\",\"Mastercard\",\"Visa\",\"DinersClub\",\"UnionPay\",\"RuPay\"],\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"payment_method_type\":\"klarna\",\"payment_experience\":\"redirect_to_url\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"affirm\",\"payment_experience\":\"redirect_to_url\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"afterpay_clearpay\",\"payment_experience\":\"redirect_to_url\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"pay_bright\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"walley\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"paypal\",\"payment_experience\":\"redirect_to_url\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"google_pay\",\"payment_experience\":\"invoke_sdk_client\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"apple_pay\",\"payment_experience\":\"invoke_sdk_client\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"mobile_pay\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"ali_pay\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"we_chat_pay\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"mb_way\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"gift_card\",\"payment_method_types\":[{\"payment_method_type\":\"givex\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_redirect\",\"payment_method_types\":[{\"payment_method_type\":\"giropay\",\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"eps\",\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sofort\",\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"blik\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"trustly\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"online_banking_czech_republic\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"online_banking_finland\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"online_banking_poland\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"online_banking_slovakia\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bancontact_card\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_debit\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bacs\",\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"google_pay\":{\"allowed_payment_methods\":[{\"type\":\"CARD\",\"parameters\":{\"allowed_auth_methods\":[\"PAN_ONLY\",\"CRYPTOGRAM_3DS\"],\"allowed_card_networks\":[\"AMEX\",\"DISCOVER\",\"INTERAC\",\"JCB\",\"MASTERCARD\",\"VISA\"]},\"tokenization_specification\":{\"type\":\"PAYMENT_GATEWAY\"}}],\"merchant_info\":{\"merchant_name\":\"Narayan Bhat\"}}}}" }, "url": { "raw": "{{baseUrl}}/account/:account_id/connectors", diff --git a/postman/collection-json/hyperswitch.postman_collection.json b/postman/collection-json/hyperswitch.postman_collection.json index ab710ca4316..0acf2ee2b3f 100644 --- a/postman/collection-json/hyperswitch.postman_collection.json +++ b/postman/collection-json/hyperswitch.postman_collection.json @@ -1915,7 +1915,7 @@ "language": "json" } }, - "raw": "{\"connector_type\":\"fiz_operations\",\"connector_name\":\"stripe\",\"connector_account_details\":{\"auth_type\":\"HeaderKey\",\"api_key\":\"{{connector_api_key}}\"},\"test_mode\":false,\"disabled\":false,\"payment_methods_enabled\":[{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"affirm\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"afterpay_clearpay\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"invoke_sdk_client\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"bank_redirect\",\"payment_method_types\":[{\"payment_method_type\":\"ideal\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"giropay\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sofort\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"eps\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_debit\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"becs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_transfer\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bacs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"debit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"apple_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"google_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"google_pay\":{\"allowed_payment_methods\":[{\"type\":\"CARD\",\"parameters\":{\"allowed_auth_methods\":[\"PAN_ONLY\",\"CRYPTOGRAM_3DS\"],\"allowed_card_networks\":[\"AMEX\",\"DISCOVER\",\"INTERAC\",\"JCB\",\"MASTERCARD\",\"VISA\"]},\"tokenization_specification\":{\"type\":\"PAYMENT_GATEWAY\",\"parameters\":{\"gateway\":\"example\",\"gateway_merchant_id\":\"{{gateway_merchant_id}}\"}}}],\"merchant_info\":{\"merchant_name\":\"Narayan Bhat\"}},\"apple_pay\":{\"session_token_data\":{\"initiative\":\"web\",\"certificate\":\"{{certificate}}\",\"display_name\":\"applepay\",\"certificate_keys\":\"{{certificate_keys}}\",\"initiative_context\":\"hyperswitch-sdk-test.netlify.app\",\"merchant_identifier\":\"merchant.com.stripe.sang\"},\"payment_request_data\":{\"label\":\"applepay pvt.ltd\",\"supported_networks\":[\"visa\",\"masterCard\",\"amex\",\"discover\"],\"merchant_capabilities\":[\"supports3DS\"]}}}}" + "raw": "{\"connector_type\":\"fiz_operations\",\"connector_name\":\"stripe\",\"connector_account_details\":{\"auth_type\":\"HeaderKey\",\"api_key\":\"{{connector_api_key}}\"},\"test_mode\":false,\"disabled\":false,\"payment_methods_enabled\":[{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"affirm\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"afterpay_clearpay\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"invoke_sdk_client\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"bank_redirect\",\"payment_method_types\":[{\"payment_method_type\":\"ideal\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"giropay\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sofort\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"eps\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_debit\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"becs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_transfer\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bacs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"debit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"apple_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"google_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"google_pay\":{\"allowed_payment_methods\":[{\"type\":\"CARD\",\"parameters\":{\"allowed_auth_methods\":[\"PAN_ONLY\",\"CRYPTOGRAM_3DS\"],\"allowed_card_networks\":[\"AMEX\",\"DISCOVER\",\"INTERAC\",\"JCB\",\"MASTERCARD\",\"VISA\"]},\"tokenization_specification\":{\"type\":\"PAYMENT_GATEWAY\",\"parameters\":{\"gateway\":\"example\",\"gateway_merchant_id\":\"{{gateway_merchant_id}}\"}}}],\"merchant_info\":{\"merchant_name\":\"Narayan Bhat\"}},\"apple_pay\":{\"session_token_data\":{\"initiative\":\"web\",\"certificate\":\"{{certificate}}\",\"display_name\":\"applepay\",\"certificate_keys\":\"{{certificate_keys}}\",\"initiative_context\":\"sdk-test-app.netlify.app\",\"merchant_identifier\":\"merchant.com.stripe.sang\"},\"payment_request_data\":{\"label\":\"applepay pvt.ltd\",\"supported_networks\":[\"visa\",\"masterCard\",\"amex\",\"discover\"],\"merchant_capabilities\":[\"supports3DS\"]}}}}" }, "url": { "raw": "{{baseUrl}}/account/:account_id/connectors", @@ -4798,7 +4798,7 @@ "language": "json" } }, - "raw": "{\"connector_type\":\"fiz_operations\",\"connector_name\":\"stripe\",\"connector_account_details\":{\"auth_type\":\"HeaderKey\",\"api_key\":\"{{connector_api_key}}\"},\"test_mode\":false,\"disabled\":false,\"payment_methods_enabled\":[{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"affirm\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"afterpay_clearpay\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"invoke_sdk_client\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"bank_redirect\",\"payment_method_types\":[{\"payment_method_type\":\"ideal\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"giropay\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sofort\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"eps\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_debit\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"becs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_transfer\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bacs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"debit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"apple_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"google_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"google_pay\":{\"allowed_payment_methods\":[{\"type\":\"CARD\",\"parameters\":{\"allowed_auth_methods\":[\"PAN_ONLY\",\"CRYPTOGRAM_3DS\"],\"allowed_card_networks\":[\"AMEX\",\"DISCOVER\",\"INTERAC\",\"JCB\",\"MASTERCARD\",\"VISA\"]},\"tokenization_specification\":{\"type\":\"PAYMENT_GATEWAY\",\"parameters\":{\"gateway\":\"example\",\"gateway_merchant_id\":\"{{gateway_merchant_id}}\"}}}],\"merchant_info\":{\"merchant_name\":\"Narayan Bhat\"}},\"apple_pay\":{\"session_token_data\":{\"initiative\":\"web\",\"certificate\":\"{{certificate}}\",\"display_name\":\"applepay\",\"certificate_keys\":\"{{certificate_keys}}\",\"initiative_context\":\"hyperswitch-sdk-test.netlify.app\",\"merchant_identifier\":\"merchant.com.stripe.sang\"},\"payment_request_data\":{\"label\":\"applepay pvt.ltd\",\"supported_networks\":[\"visa\",\"masterCard\",\"amex\",\"discover\"],\"merchant_capabilities\":[\"supports3DS\"]}}}}" + "raw": "{\"connector_type\":\"fiz_operations\",\"connector_name\":\"stripe\",\"connector_account_details\":{\"auth_type\":\"HeaderKey\",\"api_key\":\"{{connector_api_key}}\"},\"test_mode\":false,\"disabled\":false,\"payment_methods_enabled\":[{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"affirm\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"afterpay_clearpay\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"invoke_sdk_client\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"bank_redirect\",\"payment_method_types\":[{\"payment_method_type\":\"ideal\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"giropay\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sofort\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"eps\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_debit\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"becs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_transfer\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bacs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"debit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"apple_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"google_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"google_pay\":{\"allowed_payment_methods\":[{\"type\":\"CARD\",\"parameters\":{\"allowed_auth_methods\":[\"PAN_ONLY\",\"CRYPTOGRAM_3DS\"],\"allowed_card_networks\":[\"AMEX\",\"DISCOVER\",\"INTERAC\",\"JCB\",\"MASTERCARD\",\"VISA\"]},\"tokenization_specification\":{\"type\":\"PAYMENT_GATEWAY\",\"parameters\":{\"gateway\":\"example\",\"gateway_merchant_id\":\"{{gateway_merchant_id}}\"}}}],\"merchant_info\":{\"merchant_name\":\"Narayan Bhat\"}},\"apple_pay\":{\"session_token_data\":{\"initiative\":\"web\",\"certificate\":\"{{certificate}}\",\"display_name\":\"applepay\",\"certificate_keys\":\"{{certificate_keys}}\",\"initiative_context\":\"sdk-test-app.netlify.app\",\"merchant_identifier\":\"merchant.com.stripe.sang\"},\"payment_request_data\":{\"label\":\"applepay pvt.ltd\",\"supported_networks\":[\"visa\",\"masterCard\",\"amex\",\"discover\"],\"merchant_capabilities\":[\"supports3DS\"]}}}}" }, "url": { "raw": "{{baseUrl}}/account/:account_id/connectors", diff --git a/postman/collection-json/stripe.postman_collection.json b/postman/collection-json/stripe.postman_collection.json index e158ccd1a5e..0638ff734c4 100644 --- a/postman/collection-json/stripe.postman_collection.json +++ b/postman/collection-json/stripe.postman_collection.json @@ -2079,7 +2079,7 @@ "language": "json" } }, - "raw": "{\"connector_type\":\"fiz_operations\",\"connector_name\":\"stripe\",\"business_country\":\"US\",\"business_label\":\"default\",\"connector_account_details\":{\"auth_type\":\"HeaderKey\",\"api_key\":\"{{connector_api_key}}_invalid_values\"},\"test_mode\":false,\"disabled\":false,\"payment_methods_enabled\":[{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"affirm\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"afterpay_clearpay\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"invoke_sdk_client\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"bank_redirect\",\"payment_method_types\":[{\"payment_method_type\":\"ideal\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"giropay\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sofort\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"eps\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_debit\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"becs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_transfer\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bacs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"debit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"apple_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"google_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"google_pay\":{\"allowed_payment_methods\":[{\"type\":\"CARD\",\"parameters\":{\"allowed_auth_methods\":[\"PAN_ONLY\",\"CRYPTOGRAM_3DS\"],\"allowed_card_networks\":[\"AMEX\",\"DISCOVER\",\"INTERAC\",\"JCB\",\"MASTERCARD\",\"VISA\"]},\"tokenization_specification\":{\"type\":\"PAYMENT_GATEWAY\",\"parameters\":{\"gateway\":\"example\",\"gateway_merchant_id\":\"{{gateway_merchant_id}}\"}}}],\"merchant_info\":{\"merchant_name\":\"Narayan Bhat\"}},\"apple_pay\":{\"session_token_data\":{\"initiative\":\"web\",\"certificate\":\"{{certificate}}\",\"display_name\":\"applepay\",\"certificate_keys\":\"{{certificate_keys}}\",\"initiative_context\":\"hyperswitch-sdk-test.netlify.app\",\"merchant_identifier\":\"merchant.com.stripe.sang\"},\"payment_request_data\":{\"label\":\"applepay pvt.ltd\",\"supported_networks\":[\"visa\",\"masterCard\",\"amex\",\"discover\"],\"merchant_capabilities\":[\"supports3DS\"]}}}}" + "raw": "{\"connector_type\":\"fiz_operations\",\"connector_name\":\"stripe\",\"business_country\":\"US\",\"business_label\":\"default\",\"connector_account_details\":{\"auth_type\":\"HeaderKey\",\"api_key\":\"{{connector_api_key}}_invalid_values\"},\"test_mode\":false,\"disabled\":false,\"payment_methods_enabled\":[{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"affirm\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"afterpay_clearpay\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"invoke_sdk_client\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"bank_redirect\",\"payment_method_types\":[{\"payment_method_type\":\"ideal\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"giropay\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sofort\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"eps\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_debit\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"becs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_transfer\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bacs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"debit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"apple_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"google_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"google_pay\":{\"allowed_payment_methods\":[{\"type\":\"CARD\",\"parameters\":{\"allowed_auth_methods\":[\"PAN_ONLY\",\"CRYPTOGRAM_3DS\"],\"allowed_card_networks\":[\"AMEX\",\"DISCOVER\",\"INTERAC\",\"JCB\",\"MASTERCARD\",\"VISA\"]},\"tokenization_specification\":{\"type\":\"PAYMENT_GATEWAY\",\"parameters\":{\"gateway\":\"example\",\"gateway_merchant_id\":\"{{gateway_merchant_id}}\"}}}],\"merchant_info\":{\"merchant_name\":\"Narayan Bhat\"}},\"apple_pay\":{\"session_token_data\":{\"initiative\":\"web\",\"certificate\":\"{{certificate}}\",\"display_name\":\"applepay\",\"certificate_keys\":\"{{certificate_keys}}\",\"initiative_context\":\"sdk-test-app.netlify.app\",\"merchant_identifier\":\"merchant.com.stripe.sang\"},\"payment_request_data\":{\"label\":\"applepay pvt.ltd\",\"supported_networks\":[\"visa\",\"masterCard\",\"amex\",\"discover\"],\"merchant_capabilities\":[\"supports3DS\"]}}}}" }, "url": { "raw": "{{baseUrl}}/account/:account_id/connectors", @@ -2349,7 +2349,7 @@ "language": "json" } }, - "raw": "{\"connector_type\":\"fiz_operations\",\"connector_account_details\":{\"auth_type\":\"HeaderKey\",\"api_key\":\"{{connector_api_key}}\"},\"test_mode\":false,\"disabled\":false,\"payment_methods_enabled\":[{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"affirm\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"afterpay_clearpay\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"invoke_sdk_client\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"bank_redirect\",\"payment_method_types\":[{\"payment_method_type\":\"ideal\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"giropay\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sofort\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"eps\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_debit\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"becs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_transfer\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bacs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"debit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"apple_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"google_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"google_pay\":{\"allowed_payment_methods\":[{\"type\":\"CARD\",\"parameters\":{\"allowed_auth_methods\":[\"PAN_ONLY\",\"CRYPTOGRAM_3DS\"],\"allowed_card_networks\":[\"AMEX\",\"DISCOVER\",\"INTERAC\",\"JCB\",\"MASTERCARD\",\"VISA\"]},\"tokenization_specification\":{\"type\":\"PAYMENT_GATEWAY\",\"parameters\":{\"gateway\":\"example\",\"gateway_merchant_id\":\"{{gateway_merchant_id}}\"}}}],\"merchant_info\":{\"merchant_name\":\"Narayan Bhat\"}},\"apple_pay\":{\"session_token_data\":{\"initiative\":\"web\",\"certificate\":\"{{certificate}}\",\"display_name\":\"applepay\",\"certificate_keys\":\"{{certificate_keys}}\",\"initiative_context\":\"hyperswitch-sdk-test.netlify.app\",\"merchant_identifier\":\"merchant.com.stripe.sang\"},\"payment_request_data\":{\"label\":\"applepay pvt.ltd\",\"supported_networks\":[\"visa\",\"masterCard\",\"amex\",\"discover\"],\"merchant_capabilities\":[\"supports3DS\"]}}}}" + "raw": "{\"connector_type\":\"fiz_operations\",\"connector_account_details\":{\"auth_type\":\"HeaderKey\",\"api_key\":\"{{connector_api_key}}\"},\"test_mode\":false,\"disabled\":false,\"payment_methods_enabled\":[{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"affirm\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"afterpay_clearpay\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"invoke_sdk_client\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"bank_redirect\",\"payment_method_types\":[{\"payment_method_type\":\"ideal\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"giropay\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sofort\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"eps\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_debit\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"becs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_transfer\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bacs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"debit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"apple_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"google_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"google_pay\":{\"allowed_payment_methods\":[{\"type\":\"CARD\",\"parameters\":{\"allowed_auth_methods\":[\"PAN_ONLY\",\"CRYPTOGRAM_3DS\"],\"allowed_card_networks\":[\"AMEX\",\"DISCOVER\",\"INTERAC\",\"JCB\",\"MASTERCARD\",\"VISA\"]},\"tokenization_specification\":{\"type\":\"PAYMENT_GATEWAY\",\"parameters\":{\"gateway\":\"example\",\"gateway_merchant_id\":\"{{gateway_merchant_id}}\"}}}],\"merchant_info\":{\"merchant_name\":\"Narayan Bhat\"}},\"apple_pay\":{\"session_token_data\":{\"initiative\":\"web\",\"certificate\":\"{{certificate}}\",\"display_name\":\"applepay\",\"certificate_keys\":\"{{certificate_keys}}\",\"initiative_context\":\"sdk-test-app.netlify.app\",\"merchant_identifier\":\"merchant.com.stripe.sang\"},\"payment_request_data\":{\"label\":\"applepay pvt.ltd\",\"supported_networks\":[\"visa\",\"masterCard\",\"amex\",\"discover\"],\"merchant_capabilities\":[\"supports3DS\"]}}}}" }, "url": { "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id", @@ -5664,7 +5664,7 @@ "language": "json" } }, - "raw": "{\"connector_type\":\"fiz_operations\",\"connector_name\":\"stripe\",\"business_country\":\"US\",\"business_label\":\"default\",\"connector_account_details\":{\"auth_type\":\"HeaderKey\",\"api_key\":\"{{connector_api_key}}\"},\"test_mode\":false,\"disabled\":false,\"payment_methods_enabled\":[{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"affirm\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"afterpay_clearpay\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"invoke_sdk_client\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"bank_redirect\",\"payment_method_types\":[{\"payment_method_type\":\"ideal\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"giropay\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sofort\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"eps\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_debit\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"becs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_transfer\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bacs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"card_networks\":[\"AmericanExpress\",\"Discover\",\"Interac\",\"JCB\",\"Mastercard\",\"Visa\",\"DinersClub\",\"UnionPay\",\"RuPay\"]}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"debit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"card_networks\":[\"AmericanExpress\",\"Discover\",\"Interac\",\"JCB\",\"Mastercard\",\"Visa\",\"DinersClub\",\"UnionPay\",\"RuPay\"]}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"apple_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"google_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"we_chat_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"google_pay\":{\"allowed_payment_methods\":[{\"type\":\"CARD\",\"parameters\":{\"allowed_auth_methods\":[\"PAN_ONLY\",\"CRYPTOGRAM_3DS\"],\"allowed_card_networks\":[\"AMEX\",\"DISCOVER\",\"INTERAC\",\"JCB\",\"MASTERCARD\",\"VISA\"]},\"tokenization_specification\":{\"type\":\"PAYMENT_GATEWAY\",\"parameters\":{\"gateway\":\"example\",\"gateway_merchant_id\":\"{{gateway_merchant_id}}\"}}}],\"merchant_info\":{\"merchant_name\":\"Narayan Bhat\"}},\"apple_pay\":{\"session_token_data\":{\"initiative\":\"web\",\"certificate\":\"{{certificate}}\",\"display_name\":\"applepay\",\"certificate_keys\":\"{{certificate_keys}}\",\"initiative_context\":\"hyperswitch-sdk-test.netlify.app\",\"merchant_identifier\":\"merchant.com.stripe.sang\"},\"payment_request_data\":{\"label\":\"applepay pvt.ltd\",\"supported_networks\":[\"visa\",\"masterCard\",\"amex\",\"discover\"],\"merchant_capabilities\":[\"supports3DS\"]}}}}" + "raw": "{\"connector_type\":\"fiz_operations\",\"connector_name\":\"stripe\",\"business_country\":\"US\",\"business_label\":\"default\",\"connector_account_details\":{\"auth_type\":\"HeaderKey\",\"api_key\":\"{{connector_api_key}}\"},\"test_mode\":false,\"disabled\":false,\"payment_methods_enabled\":[{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"affirm\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"afterpay_clearpay\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"redirect_to_url\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"payment_experience\":\"invoke_sdk_client\",\"payment_method_type\":\"klarna\"}]},{\"payment_method\":\"bank_redirect\",\"payment_method_types\":[{\"payment_method_type\":\"ideal\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"giropay\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sofort\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"eps\",\"payment_experience\":null,\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_debit\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"becs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_transfer\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bacs\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sepa\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"card_networks\":[\"AmericanExpress\",\"Discover\",\"Interac\",\"JCB\",\"Mastercard\",\"Visa\",\"DinersClub\",\"UnionPay\",\"RuPay\"]}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"debit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true,\"card_networks\":[\"AmericanExpress\",\"Discover\",\"Interac\",\"JCB\",\"Mastercard\",\"Visa\",\"DinersClub\",\"UnionPay\",\"RuPay\"]}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"apple_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"google_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"we_chat_pay\",\"payment_experience\":\"invoke_sdk_client\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"google_pay\":{\"allowed_payment_methods\":[{\"type\":\"CARD\",\"parameters\":{\"allowed_auth_methods\":[\"PAN_ONLY\",\"CRYPTOGRAM_3DS\"],\"allowed_card_networks\":[\"AMEX\",\"DISCOVER\",\"INTERAC\",\"JCB\",\"MASTERCARD\",\"VISA\"]},\"tokenization_specification\":{\"type\":\"PAYMENT_GATEWAY\",\"parameters\":{\"gateway\":\"example\",\"gateway_merchant_id\":\"{{gateway_merchant_id}}\"}}}],\"merchant_info\":{\"merchant_name\":\"Narayan Bhat\"}},\"apple_pay\":{\"session_token_data\":{\"initiative\":\"web\",\"certificate\":\"{{certificate}}\",\"display_name\":\"applepay\",\"certificate_keys\":\"{{certificate_keys}}\",\"initiative_context\":\"sdk-test-app.netlify.app\",\"merchant_identifier\":\"merchant.com.stripe.sang\"},\"payment_request_data\":{\"label\":\"applepay pvt.ltd\",\"supported_networks\":[\"visa\",\"masterCard\",\"amex\",\"discover\"],\"merchant_capabilities\":[\"supports3DS\"]}}}}" }, "url": { "raw": "{{baseUrl}}/account/:account_id/connectors", diff --git a/postman/collection-json/wise.postman_collection.json b/postman/collection-json/wise.postman_collection.json index dc4d9395d3a..410f066ff6f 100644 --- a/postman/collection-json/wise.postman_collection.json +++ b/postman/collection-json/wise.postman_collection.json @@ -424,7 +424,7 @@ "language": "json" } }, - "raw": "{\"connector_type\":\"payout_processor\",\"connector_name\":\"wise\",\"connector_account_details\":{\"auth_type\":\"BodyKey\",\"api_key\":\"{{connector_api_key}}\",\"key1\":\"{{connector_key1}}\"},\"test_mode\":false,\"disabled\":false,\"business_country\":\"US\",\"business_label\":\"default\",\"payment_methods_enabled\":[{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"card_networks\":[\"Visa\",\"Mastercard\"],\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"debit\",\"card_networks\":[\"Visa\",\"Mastercard\"],\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"payment_method_type\":\"klarna\",\"payment_experience\":\"redirect_to_url\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"affirm\",\"payment_experience\":\"redirect_to_url\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"afterpay_clearpay\",\"payment_experience\":\"redirect_to_url\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"pay_bright\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"walley\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"paypal\",\"payment_experience\":\"redirect_to_url\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"google_pay\",\"payment_experience\":\"invoke_sdk_client\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"apple_pay\",\"payment_experience\":\"invoke_sdk_client\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"mobile_pay\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"ali_pay\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"we_chat_pay\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"mb_way\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_redirect\",\"payment_method_types\":[{\"payment_method_type\":\"giropay\",\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"eps\",\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sofort\",\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"blik\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"trustly\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"online_banking_czech_republic\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"online_banking_finland\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"online_banking_poland\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"online_banking_slovakia\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bancontact_card\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_debit\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bacs\",\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"google_pay\":{\"allowed_payment_methods\":[{\"type\":\"CARD\",\"parameters\":{\"allowed_auth_methods\":[\"PAN_ONLY\",\"CRYPTOGRAM_3DS\"],\"allowed_card_networks\":[\"AMEX\",\"DISCOVER\",\"INTERAC\",\"JCB\",\"MASTERCARD\",\"VISA\"]},\"tokenization_specification\":{\"type\":\"PAYMENT_GATEWAY\"}}],\"merchant_info\":{\"merchant_name\":\"Narayan Bhat\"}},\"apple_pay\":{\"session_token_data\":{\"initiative\":\"web\",\"certificate\":\"{{certificate}}\",\"display_name\":\"applepay\",\"certificate_keys\":\"{{certificate_keys}}\",\"initiative_context\":\"hyperswitch-sdk-test.netlify.app\",\"merchant_identifier\":\"merchant.com.stripe.sang\"},\"payment_request_data\":{\"label\":\"applepay pvt.ltd\",\"supported_networks\":[\"visa\",\"masterCard\",\"amex\",\"discover\"],\"merchant_capabilities\":[\"supports3DS\"]}}}}" + "raw": "{\"connector_type\":\"payout_processor\",\"connector_name\":\"wise\",\"connector_account_details\":{\"auth_type\":\"BodyKey\",\"api_key\":\"{{connector_api_key}}\",\"key1\":\"{{connector_key1}}\"},\"test_mode\":false,\"disabled\":false,\"business_country\":\"US\",\"business_label\":\"default\",\"payment_methods_enabled\":[{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"card_networks\":[\"Visa\",\"Mastercard\"],\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"debit\",\"card_networks\":[\"Visa\",\"Mastercard\"],\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"pay_later\",\"payment_method_types\":[{\"payment_method_type\":\"klarna\",\"payment_experience\":\"redirect_to_url\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"affirm\",\"payment_experience\":\"redirect_to_url\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"afterpay_clearpay\",\"payment_experience\":\"redirect_to_url\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"pay_bright\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"walley\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"wallet\",\"payment_method_types\":[{\"payment_method_type\":\"paypal\",\"payment_experience\":\"redirect_to_url\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"google_pay\",\"payment_experience\":\"invoke_sdk_client\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"apple_pay\",\"payment_experience\":\"invoke_sdk_client\",\"card_networks\":null,\"accepted_currencies\":null,\"accepted_countries\":null,\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"mobile_pay\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"ali_pay\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"we_chat_pay\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"mb_way\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_redirect\",\"payment_method_types\":[{\"payment_method_type\":\"giropay\",\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"eps\",\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"sofort\",\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"blik\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"trustly\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"online_banking_czech_republic\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"online_banking_finland\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"online_banking_poland\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"online_banking_slovakia\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bancontact_card\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"bank_debit\",\"payment_method_types\":[{\"payment_method_type\":\"ach\",\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"bacs\",\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}],\"metadata\":{\"google_pay\":{\"allowed_payment_methods\":[{\"type\":\"CARD\",\"parameters\":{\"allowed_auth_methods\":[\"PAN_ONLY\",\"CRYPTOGRAM_3DS\"],\"allowed_card_networks\":[\"AMEX\",\"DISCOVER\",\"INTERAC\",\"JCB\",\"MASTERCARD\",\"VISA\"]},\"tokenization_specification\":{\"type\":\"PAYMENT_GATEWAY\"}}],\"merchant_info\":{\"merchant_name\":\"Narayan Bhat\"}},\"apple_pay\":{\"session_token_data\":{\"initiative\":\"web\",\"certificate\":\"{{certificate}}\",\"display_name\":\"applepay\",\"certificate_keys\":\"{{certificate_keys}}\",\"initiative_context\":\"sdk-test-app.netlify.app\",\"merchant_identifier\":\"merchant.com.stripe.sang\"},\"payment_request_data\":{\"label\":\"applepay pvt.ltd\",\"supported_networks\":[\"visa\",\"masterCard\",\"amex\",\"discover\"],\"merchant_capabilities\":[\"supports3DS\"]}}}}" }, "url": { "raw": "{{baseUrl}}/account/:account_id/connectors",
chore
update Postman collection files
5c2a9da6f8e8d96d508dd890bb80b2fabb63185d
2023-07-18 19:12:26
Sanchith Hegde
ci(release-new-version): update schedule to run workflow at 8 AM IST every weekday (#1733)
false
diff --git a/.github/workflows/release-new-version.yml b/.github/workflows/release-new-version.yml index da6fc536d85..6df64abb275 100644 --- a/.github/workflows/release-new-version.yml +++ b/.github/workflows/release-new-version.yml @@ -2,7 +2,7 @@ name: Release a new version on: schedule: - - cron: "30 12 * * 2-4" # Run workflow at 6 PM IST every Tuesday, Wednesday, Thursday + - cron: "30 2 * * 1-5" # Run workflow at 8 AM IST every Monday-Friday workflow_dispatch:
ci
update schedule to run workflow at 8 AM IST every weekday (#1733)
7f22c22cf4c3e9f68ca3d639d98330446e2c7db1
2023-02-27 23:19:42
Abhishek
fix(compatibility): change next_action type and customer request type (#675)
false
diff --git a/crates/router/src/compatibility/stripe/customers/types.rs b/crates/router/src/compatibility/stripe/customers/types.rs index 4d07fb20513..5822c5ed7e1 100644 --- a/crates/router/src/compatibility/stripe/customers/types.rs +++ b/crates/router/src/compatibility/stripe/customers/types.rs @@ -2,38 +2,29 @@ use std::{convert::From, default::Default}; use api_models::payment_methods as api_types; use common_utils::date_time; -use masking; use serde::{Deserialize, Serialize}; use crate::{logger, pii, types::api}; -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] -pub struct CustomerAddress { - pub city: Option<pii::Secret<String>>, - pub country: Option<pii::Secret<String>>, - pub line1: Option<pii::Secret<String>>, - pub line2: Option<pii::Secret<String>>, - pub postal_code: Option<pii::Secret<String>>, - pub state: Option<pii::Secret<String>>, -} - #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct CreateCustomerRequest { pub email: Option<masking::Secret<String, pii::Email>>, pub invoice_prefix: Option<String>, pub name: Option<String>, pub phone: Option<masking::Secret<String>>, - pub address: Option<CustomerAddress>, + pub address: Option<masking::Secret<serde_json::Value>>, + pub metadata: Option<serde_json::Value>, + pub description: Option<String>, } #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct CustomerUpdateRequest { - pub metadata: Option<String>, pub description: Option<String>, pub email: Option<masking::Secret<String, pii::Email>>, pub phone: Option<masking::Secret<String, masking::WithType>>, pub name: Option<String>, - pub address: Option<CustomerAddress>, + pub address: Option<masking::Secret<serde_json::Value>>, + pub metadata: Option<serde_json::Value>, } #[derive(Default, Serialize, PartialEq, Eq)] @@ -64,7 +55,9 @@ impl From<CreateCustomerRequest> for api::CustomerRequest { name: req.name, phone: req.phone, email: req.email, - description: req.invoice_prefix, + description: req.description, + metadata: req.metadata, + address: req.address, ..Default::default() } } @@ -77,10 +70,7 @@ impl From<CustomerUpdateRequest> for api::CustomerRequest { phone: req.phone, email: req.email, description: req.description, - metadata: req - .metadata - .map(|v| serde_json::from_str(&v).ok()) - .unwrap_or(None), + metadata: req.metadata, ..Default::default() } } diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 4202bfcd32c..66cddde8bf8 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -85,6 +85,7 @@ impl From<StripeCard> for payments::Card { } } } + impl From<StripePaymentMethodDetails> for payments::PaymentMethodData { fn from(item: StripePaymentMethodDetails) -> Self { match item { @@ -283,9 +284,9 @@ pub struct StripePaymentIntentResponse { pub mandate_data: Option<payments::MandateData>, pub setup_future_usage: Option<api_models::enums::FutureUsage>, pub off_session: Option<bool>, - pub return_url: Option<String>, + pub authentication_type: Option<api_models::enums::AuthenticationType>, - pub next_action: Option<payments::NextAction>, + pub next_action: Option<StripeNextAction>, pub cancellation_reason: Option<String>, pub payment_method: Option<api_models::enums::PaymentMethod>, pub payment_method_data: Option<payments::PaymentMethodDataResponse>, @@ -334,11 +335,10 @@ impl From<payments::PaymentsResponse> for StripePaymentIntentResponse { email: resp.email, name: resp.name, phone: resp.phone, - return_url: resp.return_url, authentication_type: resp.authentication_type, statement_descriptor_name: resp.statement_descriptor_name, statement_descriptor_suffix: resp.statement_descriptor_suffix, - next_action: resp.next_action, + next_action: into_stripe_next_action(resp.next_action, resp.return_url), cancellation_reason: resp.cancellation_reason, error_code: resp.error_code, error_message: resp.error_message, @@ -469,3 +469,29 @@ impl From<Foreign<Option<Request3DS>>> for Foreign<api_models::enums::Authentica }) } } + +#[derive(Default, Eq, PartialEq, Serialize)] +pub struct RedirectUrl { + pub return_url: Option<String>, + pub url: Option<String>, +} + +#[derive(Eq, PartialEq, Serialize)] +pub struct StripeNextAction { + #[serde(rename = "type")] + stype: payments::NextActionType, + redirect_to_url: RedirectUrl, +} + +fn into_stripe_next_action( + next_action: Option<payments::NextAction>, + return_url: Option<String>, +) -> Option<StripeNextAction> { + next_action.map(|n| StripeNextAction { + stype: n.next_action_type, + redirect_to_url: RedirectUrl { + return_url, + url: n.redirect_to_url, + }, + }) +}
fix
change next_action type and customer request type (#675)
15026977461c46249c7ff1e3f6373f3f074949cf
2023-11-03 16:49:57
github-actions
chore(version): v1.70.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index aaf1cc629d8..a6f88af7c8b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,28 @@ All notable changes to HyperSwitch will be documented here. - - - +## 1.70.0 (2023-11-03) + +### Features + +- **analytics:** Analytics APIs ([#2676](https://github.com/juspay/hyperswitch/pull/2676)) ([`c0a5e7b`](https://github.com/juspay/hyperswitch/commit/c0a5e7b7d945095053606e35c9bb23a06090c4e3)) +- **connector:** [Multisafepay] add error handling ([#2595](https://github.com/juspay/hyperswitch/pull/2595)) ([`b3c846d`](https://github.com/juspay/hyperswitch/commit/b3c846d637dd32a2d6d7044c118abbb2616642f0)) +- **events:** Add api auth type details to events ([#2760](https://github.com/juspay/hyperswitch/pull/2760)) ([`1094493`](https://github.com/juspay/hyperswitch/commit/10944937a02502e0727f16368d8d055e575dd518)) + +### Bug Fixes + +- **router:** Make customer_id optional when billing and shipping address is passed in payments create, update ([#2762](https://github.com/juspay/hyperswitch/pull/2762)) ([`e40a293`](https://github.com/juspay/hyperswitch/commit/e40a29351c7aa7b86a5684959a84f0236104cafd)) +- Null fields in payments respose ([#2745](https://github.com/juspay/hyperswitch/pull/2745)) ([`42261a5`](https://github.com/juspay/hyperswitch/commit/42261a5306bb99d3e20eb3aa734a895e589b1d94)) + +### Testing + +- **postman:** Update postman collection files ([`772f03e`](https://github.com/juspay/hyperswitch/commit/772f03ee3836ce86de3874f6a5e7f636718e6034)) + +**Full Changelog:** [`v1.69.0...v1.70.0`](https://github.com/juspay/hyperswitch/compare/v1.69.0...v1.70.0) + +- - - + + ## 1.69.0 (2023-10-31) ### Features
chore
v1.70.0
9bc8fd4d8c4be1b54050398dfb3b574e924e4b5f
2025-02-22 13:25:37
Shankar Singh C
feat(connector): add Samsung pay mandate support for Cybersource (#7298)
false
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 265f06ee749..db440656fba 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -1215,6 +1215,8 @@ merchant_secret="Source verification key" payment_method_type = "google_pay" [[cybersource.wallet]] payment_method_type = "paze" +[[cybersource.wallet]] + payment_method_type = "samsung_pay" [cybersource.connector_auth.SignatureKey] api_key="Key" key1="Merchant ID" diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource.rs b/crates/hyperswitch_connectors/src/connectors/cybersource.rs index 5a60f6d705a..812d0391dec 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource.rs @@ -312,6 +312,7 @@ impl ConnectorValidation for Cybersource { PaymentMethodDataType::Card, PaymentMethodDataType::ApplePay, PaymentMethodDataType::GooglePay, + PaymentMethodDataType::SamsungPay, ]); utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs index 20db1648e96..4c65218c5a3 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs @@ -251,6 +251,11 @@ impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest { )), Some(PaymentSolution::GooglePay), ), + WalletData::SamsungPay(samsung_pay_data) => ( + (get_samsung_pay_payment_information(&samsung_pay_data) + .attach_printable("Failed to get samsung pay payment information")?), + Some(PaymentSolution::SamsungPay), + ), WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) @@ -269,7 +274,6 @@ impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest { | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) - | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) @@ -1859,25 +1863,8 @@ impl let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); - let samsung_pay_fluid_data_value = - get_samsung_pay_fluid_data_value(&samsung_pay_data.payment_credential.token_data)?; - - let samsung_pay_fluid_data_str = serde_json::to_string(&samsung_pay_fluid_data_value) - .change_context(errors::ConnectorError::RequestEncodingFailed) - .attach_printable("Failed to serialize samsung pay fluid data")?; - - let payment_information = - PaymentInformation::SamsungPay(Box::new(SamsungPayPaymentInformation { - fluid_data: FluidData { - value: Secret::new(consts::BASE64_ENGINE.encode(samsung_pay_fluid_data_str)), - descriptor: Some( - consts::BASE64_ENGINE.encode(FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY), - ), - }, - tokenized_card: SamsungPayTokenizedCard { - transaction_type: TransactionType::SamsungPay, - }, - })); + let payment_information = get_samsung_pay_payment_information(&samsung_pay_data) + .attach_printable("Failed to get samsung pay payment information")?; let processing_information = ProcessingInformation::try_from(( item, @@ -1903,6 +1890,32 @@ impl } } +fn get_samsung_pay_payment_information( + samsung_pay_data: &SamsungPayWalletData, +) -> Result<PaymentInformation, error_stack::Report<errors::ConnectorError>> { + let samsung_pay_fluid_data_value = + get_samsung_pay_fluid_data_value(&samsung_pay_data.payment_credential.token_data)?; + + let samsung_pay_fluid_data_str = serde_json::to_string(&samsung_pay_fluid_data_value) + .change_context(errors::ConnectorError::RequestEncodingFailed) + .attach_printable("Failed to serialize samsung pay fluid data")?; + + let payment_information = + PaymentInformation::SamsungPay(Box::new(SamsungPayPaymentInformation { + fluid_data: FluidData { + value: Secret::new(consts::BASE64_ENGINE.encode(samsung_pay_fluid_data_str)), + descriptor: Some( + consts::BASE64_ENGINE.encode(FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY), + ), + }, + tokenized_card: SamsungPayTokenizedCard { + transaction_type: TransactionType::SamsungPay, + }, + })); + + Ok(payment_information) +} + fn get_samsung_pay_fluid_data_value( samsung_pay_token_data: &hyperswitch_domain_models::payment_method_data::SamsungPayTokenData, ) -> Result<SamsungPayFluidDataValue, error_stack::Report<errors::ConnectorError>> { diff --git a/crates/router/src/configs/defaults/payment_connector_required_fields.rs b/crates/router/src/configs/defaults/payment_connector_required_fields.rs index 27cc485188b..3849054045c 100644 --- a/crates/router/src/configs/defaults/payment_connector_required_fields.rs +++ b/crates/router/src/configs/defaults/payment_connector_required_fields.rs @@ -9128,7 +9128,86 @@ impl Default for settings::RequiredFields { RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), - common: HashMap::new(), + common: HashMap::from( + [ + ( + "billing.email".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::UserEmailAddress, + value: None, + } + ), + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.first_name".to_string(), + display_name: "billing_first_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + ), + ( + "billing.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.last_name".to_string(), + display_name: "billing_last_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + ), + ( + "billing.address.city".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::UserAddressCity, + value: None, + } + ), + ( + "billing.address.state".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.state".to_string(), + display_name: "state".to_string(), + field_type: enums::FieldType::UserAddressState, + value: None, + } + ), + ( + "billing.address.zip".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::UserAddressPincode, + value: None, + } + ), + ( + "billing.address.country".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserAddressCountry{ + options: vec![ + "ALL".to_string(), + ] + }, + value: None, + } + ), + ( + "billing.address.line1".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::UserAddressLine1, + value: None, + } + ) + ] + ), } ), ]),
feat
add Samsung pay mandate support for Cybersource (#7298)
2ff76f254964e299a21fd9e13effd51c6d58d3f0
2023-01-20 01:24:28
Manoj Ghorela
feat(rapyd): ApplePay and GooglePay integration (#425)
false
diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index 3eb8926f219..a34a345b57b 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -11,6 +11,7 @@ use crate::{ storage::enums, transformers::{self, ForeignFrom}, }, + utils::OptionExt, }; #[derive(Default, Debug, Serialize)] @@ -18,8 +19,9 @@ pub struct RapydPaymentsRequest { pub amount: i64, pub currency: enums::Currency, pub payment_method: PaymentMethod, - pub payment_method_options: PaymentMethodOptions, - pub capture: bool, + pub payment_method_options: Option<PaymentMethodOptions>, + pub capture: Option<bool>, + pub description: Option<String>, } #[derive(Default, Debug, Serialize)] @@ -31,7 +33,9 @@ pub struct PaymentMethodOptions { pub struct PaymentMethod { #[serde(rename = "type")] pub pm_type: String, - pub fields: PaymentFields, + pub fields: Option<PaymentFields>, + pub address: Option<Address>, + pub digital_wallet: Option<RapydWallet>, } #[derive(Default, Debug, Serialize)] @@ -43,38 +47,94 @@ pub struct PaymentFields { pub cvv: Secret<String>, } +#[derive(Default, Debug, Serialize)] +pub struct Address { + name: String, + line_1: String, + line_2: Option<String>, + line_3: Option<String>, + city: Option<String>, + state: Option<String>, + country: Option<String>, + zip: Option<String>, + phone_number: Option<String>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RapydWallet { + #[serde(rename = "type")] + payment_type: String, + #[serde(rename = "details")] + apple_pay_token: Option<String>, +} + impl TryFrom<&types::PaymentsAuthorizeRouterData> for RapydPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - match item.request.payment_method_data { + let (capture, payment_method_options) = match item.payment_method { + storage_models::enums::PaymentMethodType::Card => { + let three_ds_enabled = matches!(item.auth_type, enums::AuthenticationType::ThreeDs); + let payment_method_options = PaymentMethodOptions { + three_ds: three_ds_enabled, + }; + ( + Some(matches!( + item.request.capture_method, + Some(enums::CaptureMethod::Automatic) | None + )), + Some(payment_method_options), + ) + } + _ => (None, None), + }; + let payment_method = match item.request.payment_method_data { api_models::payments::PaymentMethod::Card(ref ccard) => { - let payment_method = PaymentMethod { + Some(PaymentMethod { pm_type: "in_amex_card".to_owned(), //[#369] Map payment method type based on country - fields: PaymentFields { + fields: Some(PaymentFields { number: ccard.card_number.to_owned(), expiration_month: ccard.card_exp_month.to_owned(), expiration_year: ccard.card_exp_year.to_owned(), name: ccard.card_holder_name.to_owned(), cvv: ccard.card_cvc.to_owned(), - }, - }; - let three_ds_enabled = matches!(item.auth_type, enums::AuthenticationType::ThreeDs); - let payment_method_options = PaymentMethodOptions { - three_ds: three_ds_enabled, + }), + address: None, + digital_wallet: None, + }) + } + api_models::payments::PaymentMethod::Wallet(ref wallet_data) => { + let digital_wallet = match wallet_data.issuer_name { + api_models::enums::WalletIssuer::GooglePay => Some(RapydWallet { + payment_type: "google_pay".to_string(), + apple_pay_token: wallet_data.token.to_owned(), + }), + api_models::enums::WalletIssuer::ApplePay => Some(RapydWallet { + payment_type: "apple_pay".to_string(), + apple_pay_token: wallet_data.token.to_owned(), + }), + _ => None, }; - Ok(Self { - amount: item.request.amount, - currency: item.request.currency, - payment_method, - capture: matches!( - item.request.capture_method, - Some(enums::CaptureMethod::Automatic) | None - ), - payment_method_options, + Some(PaymentMethod { + pm_type: "by_visa_card".to_string(), //[#369] + fields: None, + address: None, + digital_wallet, }) } - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + _ => None, } + .get_required_value("payment_method not implemnted") + .change_context(errors::ConnectorError::NotImplemented( + "payment_method".to_owned(), + ))?; + Ok(Self { + amount: item.request.amount, + currency: item.request.currency, + payment_method, + capture, + payment_method_options, + description: None, + }) } }
feat
ApplePay and GooglePay integration (#425)
de12ba779a229966c292caa05976883dafb4996e
2024-02-14 19:11:08
ShivanshMathurJuspay
refactor: Adding connector_name into logs ( Logging Changes ) (#3581)
false
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 391a081a290..0157f741d97 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -266,7 +266,7 @@ pub enum CaptureSyncMethod { /// Handle the flow by interacting with connector module /// `connector_request` is applicable only in case if the `CallConnectorAction` is `Trigger` /// In other cases, It will be created if required, even if it is not passed -#[instrument(skip_all, fields(payment_method))] +#[instrument(skip_all, fields(connector_name, payment_method))] pub async fn execute_connector_processing_step< 'b, 'a, @@ -286,6 +286,7 @@ where { // If needed add an error stack as follows // connector_integration.build_request(req).attach_printable("Failed to build request"); + tracing::Span::current().record("connector_name", &req.connector); tracing::Span::current().record("payment_method", &req.payment_method.to_string()); logger::debug!(connector_request=?connector_request); let mut router_data = req.clone();
refactor
Adding connector_name into logs ( Logging Changes ) (#3581)
e69a7bda52784a7d7166f19e745bab6df72c7430
2024-06-26 14:44:48
Sahkal Poddar
refactor(connector): add amount framework to payme & Trustpay with googlePay, ApplePay for bluesnap, Noon & Trustpay (#4833)
false
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 7c965506d73..d40c6d4e5c2 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -5052,7 +5052,8 @@ }, "amount": { "type": "string", - "description": "The total amount for the payment" + "description": "The total amount for the payment in majot unit string (Ex: 38.02)", + "example": "38.02" } } }, @@ -10203,7 +10204,8 @@ }, "total_price": { "type": "string", - "description": "The total price" + "description": "The total price", + "example": "38.02" } } }, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 3b526c58ec7..573c977db27 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -11,7 +11,7 @@ use common_utils::{ ext_traits::{ConfigExt, Encode}, id_type, pii::{self, Email}, - types::MinorUnit, + types::{MinorUnit, StringMajorUnit}, }; use masking::{PeekInterface, Secret}; use router_derive::Setter; @@ -4175,7 +4175,8 @@ pub struct GpayTransactionInfo { /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price - pub total_price: String, + #[schema(value_type = String, example = "38.02")] + pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] @@ -4547,8 +4548,9 @@ pub struct AmountInfo { /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, - /// The total amount for the payment - pub amount: String, + /// The total amount for the payment in majot unit string (Ex: 38.02) + #[schema(value_type = String, example = "38.02")] + pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index f91bd9d890a..bcf84e560e3 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -685,6 +685,9 @@ pub struct PaymentsSessionData { pub country: Option<common_enums::CountryAlpha2>, pub surcharge_details: Option<SurchargeDetails>, pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>, + + // Minor Unit amount for amount frame work + pub minor_amount: MinorUnit, } #[derive(Debug, Clone)] diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs index b7da3d0da18..7fb4869dc83 100644 --- a/crates/router/src/connector/bluesnap.rs +++ b/crates/router/src/connector/bluesnap.rs @@ -33,6 +33,7 @@ use crate::{ types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, + transformers::ForeignTryFrom, ErrorResponse, Response, }, utils::BytesExt, @@ -603,11 +604,20 @@ impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::Payme .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) + let req_amount = data.request.minor_amount; + let req_currency = data.request.currency; + + let apple_pay_amount = + connector_utils::convert_amount(self.amount_converter, req_amount, req_currency)?; + + types::RouterData::foreign_try_from(( + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + apple_pay_amount, + )) } fn get_error_response( diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index 281dad58945..909e8120c6e 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -470,12 +470,18 @@ impl TryFrom<&types::PaymentsSessionRouterData> for BluesnapCreateWalletToken { } } -impl TryFrom<types::PaymentsSessionResponseRouterData<BluesnapWalletTokenResponse>> - for types::PaymentsSessionRouterData +impl + ForeignTryFrom<( + types::PaymentsSessionResponseRouterData<BluesnapWalletTokenResponse>, + StringMajorUnit, + )> for types::PaymentsSessionRouterData { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: types::PaymentsSessionResponseRouterData<BluesnapWalletTokenResponse>, + fn foreign_try_from( + (item, apple_pay_amount): ( + types::PaymentsSessionResponseRouterData<BluesnapWalletTokenResponse>, + StringMajorUnit, + ), ) -> Result<Self, Self::Error> { let response = &item.response; @@ -532,7 +538,7 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<BluesnapWalletTokenRespons total: payments::AmountInfo { label: payment_request_data.label, total_type: Some("final".to_string()), - amount: item.data.request.amount.to_string(), + amount: apple_pay_amount, }, merchant_capabilities: Some(payment_request_data.merchant_capabilities), supported_networks: Some(payment_request_data.supported_networks), diff --git a/crates/router/src/connector/payme.rs b/crates/router/src/connector/payme.rs index 88b2ec67595..c7039c25d49 100644 --- a/crates/router/src/connector/payme.rs +++ b/crates/router/src/connector/payme.rs @@ -1,9 +1,14 @@ pub mod transformers; -use std::fmt::Debug; - use api_models::enums::AuthenticationType; -use common_utils::{crypto, request::RequestContent}; +use common_utils::{ + crypto, + request::RequestContent, + types::{ + AmountConvertor, MinorUnit, MinorUnitForConnector, StringMajorUnit, + StringMajorUnitForConnector, + }, +}; use diesel_models::enums; use error_stack::{Report, ResultExt}; use masking::ExposeInterface; @@ -22,14 +27,30 @@ use crate::{ types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, - domain, ErrorResponse, Response, + domain, + transformers::ForeignTryFrom, + ErrorResponse, Response, }, + // transformers::{ForeignFrom, ForeignTryFrom}, utils::{handle_json_response_deserialization_failure, BytesExt}, }; -#[derive(Debug, Clone)] -pub struct Payme; +#[derive(Clone)] +pub struct Payme { + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), + apple_pay_google_pay_amount_converter: + &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), +} +impl Payme { + pub const fn new() -> &'static Self { + &Self { + amount_converter: &MinorUnitForConnector, + apple_pay_google_pay_amount_converter: &StringMajorUnitForConnector, + } + } +} +// dummy commit impl api::Payment for Payme {} impl api::PaymentSession for Payme {} impl api::PaymentsCompleteAuthorize for Payme {} @@ -287,10 +308,11 @@ impl req: &types::PaymentsPreProcessingRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = req.request.get_amount()?; - let currency = req.request.get_currency()?; - let connector_router_data = - payme::PaymeRouterData::try_from((&self.get_currency_unit(), currency, amount, req))?; + let req_amount = req.request.get_minor_amount()?; + let req_currency = req.request.get_currency()?; + let amount = + connector_utils::convert_amount(self.amount_converter, req_amount, req_currency)?; + let connector_router_data = payme::PaymeRouterData::try_from((amount, req))?; let connector_req = payme::GenerateSaleRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -329,14 +351,26 @@ impl .parse_struct("Payme GenerateSaleResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let req_amount = data.request.get_minor_amount()?; + let req_currency = data.request.get_currency()?; + + let apple_pay_amount = connector_utils::convert_amount( + self.apple_pay_google_pay_amount_converter, + req_amount, + req_currency, + )?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) + types::RouterData::foreign_try_from(( + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + apple_pay_amount, + )) } fn get_error_response( @@ -536,12 +570,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = payme::PaymeRouterData::try_from(( - &self.get_currency_unit(), + let amount = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_amount, req.request.currency, - req.request.amount, - req, - ))?; + )?; + let connector_router_data = payme::PaymeRouterData::try_from((amount, req))?; let connector_req = payme::PaymePaymentRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -724,12 +758,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme req: &types::PaymentsCaptureRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = payme::PaymeRouterData::try_from(( - &self.get_currency_unit(), + let amount = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_amount_to_capture, req.request.currency, - req.request.amount_to_capture, - req, - ))?; + )?; + let connector_router_data = payme::PaymeRouterData::try_from((amount, req))?; let connector_req = payme::PaymentCaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -822,20 +856,21 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR req: &types::PaymentsCancelRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = req - .request - .amount - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "amount", - })?; - let currency = + let req_amount = + req.request + .minor_amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "amount", + })?; + let req_currency = req.request .currency .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "currency", })?; - let connector_router_data = - payme::PaymeRouterData::try_from((&self.get_currency_unit(), currency, amount, req))?; + let amount = + connector_utils::convert_amount(self.amount_converter, req_amount, req_currency)?; + let connector_router_data = payme::PaymeRouterData::try_from((amount, req))?; let connector_req = payme::PaymeVoidRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -922,12 +957,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = payme::PaymeRouterData::try_from(( - &self.get_currency_unit(), + let amount = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_refund_amount, req.request.currency, - req.request.refund_amount, - req, - ))?; + )?; + let connector_router_data = payme::PaymeRouterData::try_from((amount, req))?; let connector_req = payme::PaymeRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index 7c6f426d38b..5cb025816d6 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -1,7 +1,10 @@ use std::collections::HashMap; use api_models::enums::{AuthenticationType, PaymentMethod}; -use common_utils::pii; +use common_utils::{ + pii, + types::{MinorUnit, StringMajorUnit}, +}; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; @@ -18,7 +21,10 @@ use crate::{ core::errors, services, types::{ - self, api, domain, domain::PaymentMethodData, storage::enums, transformers::ForeignFrom, + self, api, domain, + domain::PaymentMethodData, + storage::enums, + transformers::{ForeignFrom, ForeignTryFrom}, MandateReference, }, unimplemented_payment_method, @@ -28,15 +34,13 @@ const LANGUAGE: &str = "en"; #[derive(Debug, Serialize)] pub struct PaymeRouterData<T> { - pub amount: i64, + pub amount: MinorUnit, pub router_data: T, } -impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for PaymeRouterData<T> { +impl<T> TryFrom<(MinorUnit, T)> for PaymeRouterData<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> { + fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, @@ -57,7 +61,7 @@ pub struct PayRequest { #[derive(Debug, Serialize)] pub struct MandateRequest { currency: enums::Currency, - sale_price: i64, + sale_price: MinorUnit, transaction_id: String, product_name: String, sale_return_url: String, @@ -118,7 +122,7 @@ pub struct CaptureBuyerResponse { pub struct GenerateSaleRequest { currency: enums::Currency, sale_type: SaleType, - sale_price: i64, + sale_price: MinorUnit, transaction_id: String, product_name: String, sale_return_url: String, @@ -473,23 +477,27 @@ impl TryFrom<&types::RefundSyncRouterData> for PaymeQueryTransactionRequest { } impl<F> - TryFrom< + ForeignTryFrom<( types::ResponseRouterData< F, GenerateSaleResponse, types::PaymentsPreProcessingData, types::PaymentsResponseData, >, - > for types::RouterData<F, types::PaymentsPreProcessingData, types::PaymentsResponseData> + StringMajorUnit, + )> for types::RouterData<F, types::PaymentsPreProcessingData, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: types::ResponseRouterData< - F, - GenerateSaleResponse, - types::PaymentsPreProcessingData, - types::PaymentsResponseData, - >, + fn foreign_try_from( + (item, apple_pay_amount): ( + types::ResponseRouterData< + F, + GenerateSaleResponse, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + >, + StringMajorUnit, + ), ) -> Result<Self, Self::Error> { match item.data.payment_method { PaymentMethod::Card => { @@ -537,8 +545,6 @@ impl<F> } _ => { let currency_code = item.data.request.get_currency()?; - let amount = item.data.request.get_amount()?; - let amount_in_base_unit = utils::to_currency_base_unit(amount, currency_code)?; let pmd = item.data.request.payment_method_data.to_owned(); let payme_auth_type = PaymeAuthType::try_from(&item.data.connector_auth_type)?; @@ -556,7 +562,7 @@ impl<F> total: api_models::payments::AmountInfo { label: "Apple Pay".to_string(), total_type: None, - amount: amount_in_base_unit, + amount: apple_pay_amount, }, merchant_capabilities: None, supported_networks: None, @@ -907,7 +913,7 @@ impl<F, T> #[derive(Debug, Serialize)] pub struct PaymentCaptureRequest { payme_sale_id: String, - sale_price: i64, + sale_price: MinorUnit, } impl TryFrom<&PaymeRouterData<&types::PaymentsCaptureRouterData>> for PaymentCaptureRequest { @@ -915,7 +921,9 @@ impl TryFrom<&PaymeRouterData<&types::PaymentsCaptureRouterData>> for PaymentCap fn try_from( item: &PaymeRouterData<&types::PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { - if item.router_data.request.amount_to_capture != item.router_data.request.payment_amount { + if item.router_data.request.minor_amount_to_capture + != item.router_data.request.minor_payment_amount + { Err(errors::ConnectorError::NotSupported { message: "Partial Capture".to_string(), connector: "Payme", @@ -932,7 +940,7 @@ impl TryFrom<&PaymeRouterData<&types::PaymentsCaptureRouterData>> for PaymentCap // Type definition for RefundRequest #[derive(Debug, Serialize)] pub struct PaymeRefundRequest { - sale_refund_amount: i64, + sale_refund_amount: MinorUnit, payme_sale_id: String, seller_payme_id: Secret<String>, language: String, diff --git a/crates/router/src/connector/trustpay.rs b/crates/router/src/connector/trustpay.rs index e2904221e59..6ec8b37982a 100644 --- a/crates/router/src/connector/trustpay.rs +++ b/crates/router/src/connector/trustpay.rs @@ -1,18 +1,21 @@ pub mod transformers; -use std::fmt::Debug; - use base64::Engine; use common_utils::{ - crypto, errors::ReportSwitchExt, ext_traits::ByteSliceExt, request::RequestContent, + crypto, + errors::ReportSwitchExt, + ext_traits::ByteSliceExt, + request::RequestContent, + types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::{Report, ResultExt}; use masking::PeekInterface; use transformers as trustpay; use super::utils::{ - collect_and_sort_values_by_removing_signature, get_error_code_error_message_based_on_priority, - ConnectorErrorType, ConnectorErrorTypeMapping, PaymentsPreProcessingData, + self as connector_utils, collect_and_sort_values_by_removing_signature, + get_error_code_error_message_based_on_priority, ConnectorErrorType, ConnectorErrorTypeMapping, + PaymentsPreProcessingData, }; use crate::{ configs::settings, @@ -36,8 +39,18 @@ use crate::{ utils::{self, BytesExt}, }; -#[derive(Debug, Clone)] -pub struct Trustpay; +#[derive(Clone)] +pub struct Trustpay { + amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), +} + +impl Trustpay { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMajorUnitForConnector, + } + } +} impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Trustpay where @@ -462,14 +475,13 @@ impl req: &types::PaymentsPreProcessingRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let currency = req.request.get_currency()?; - let amount = req.request.get_amount()?; - let connector_router_data = trustpay::TrustpayRouterData::try_from(( - &self.get_currency_unit(), - currency, - amount, - req, - ))?; + let req_currency = req.request.get_currency()?; + let req_amount = req.request.get_minor_amount()?; + + let amount = + connector_utils::convert_amount(self.amount_converter, req_amount, req_currency)?; + + let connector_router_data = trustpay::TrustpayRouterData::try_from((amount, req))?; let connector_req = trustpay::TrustpayCreateIntentRequest::try_from(&connector_router_data)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) @@ -576,13 +588,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = req.request.amount; - let connector_router_data = trustpay::TrustpayRouterData::try_from(( - &self.get_currency_unit(), + let amount = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_amount, req.request.currency, - amount, - req, - ))?; + )?; + let connector_router_data = trustpay::TrustpayRouterData::try_from((amount, req))?; let connector_req = trustpay::TrustpayPaymentsRequest::try_from(&connector_router_data)?; match req.payment_method { diesel_models::enums::PaymentMethod::BankRedirect => { @@ -686,12 +697,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = trustpay::TrustpayRouterData::try_from(( - &self.get_currency_unit(), + let amount = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_refund_amount, req.request.currency, - req.request.refund_amount, - req, - ))?; + )?; + + let connector_router_data = trustpay::TrustpayRouterData::try_from((amount, req))?; let connector_req = trustpay::TrustpayRefundRequest::try_from(&connector_router_data)?; match req.payment_method { diesel_models::enums::PaymentMethod::BankRedirect => { diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index b07b819f37d..b48c52c76ff 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -3,6 +3,7 @@ use std::collections::HashMap; use common_utils::{ errors::CustomResult, pii::{self, Email}, + types::StringMajorUnit, }; use error_stack::{report, ResultExt}; use masking::{ExposeInterface, PeekInterface, Secret}; @@ -24,21 +25,13 @@ type Error = error_stack::Report<errors::ConnectorError>; #[derive(Debug, Serialize)] pub struct TrustpayRouterData<T> { - pub amount: String, + pub amount: StringMajorUnit, pub router_data: T, } -impl<T> TryFrom<(&types::api::CurrencyUnit, enums::Currency, i64, T)> for TrustpayRouterData<T> { +impl<T> TryFrom<(StringMajorUnit, T)> for TrustpayRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - (currency_unit, currency, amount, item): ( - &types::api::CurrencyUnit, - enums::Currency, - i64, - T, - ), - ) -> Result<Self, Self::Error> { - let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; + fn try_from((amount, item): (StringMajorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, @@ -97,7 +90,7 @@ pub struct References { #[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] #[serde(rename_all = "PascalCase")] pub struct Amount { - pub amount: String, + pub amount: StringMajorUnit, pub currency: String, } @@ -147,7 +140,7 @@ pub struct CallbackURLs { #[derive(Debug, Serialize, PartialEq)] pub struct PaymentRequestCards { - pub amount: String, + pub amount: StringMajorUnit, pub currency: String, pub pan: cards::CardNumber, pub cvv: Secret<String>, @@ -273,7 +266,7 @@ fn get_card_request_data( item: &types::PaymentsAuthorizeRouterData, browser_info: &BrowserInformation, params: TrustpayMandatoryParams, - amount: String, + amount: StringMajorUnit, ccard: &domain::payments::Card, return_url: String, ) -> Result<TrustpayPaymentsRequest, Error> { @@ -353,7 +346,7 @@ fn get_bank_redirection_request_data( item: &types::PaymentsAuthorizeRouterData, bank_redirection_data: &domain::BankRedirectData, params: TrustpayMandatoryParams, - amount: String, + amount: StringMajorUnit, auth: TrustpayAuthType, ) -> Result<TrustpayPaymentsRequest, error_stack::Report<errors::ConnectorError>> { let pm = TrustpayPaymentMethod::try_from(bank_redirection_data)?; @@ -1016,7 +1009,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, TrustpayAuthUpdateResponse, T, t #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayCreateIntentRequest { - pub amount: String, + pub amount: StringMajorUnit, pub currency: String, // If true, Apple Pay will be initialized pub init_apple_pay: Option<bool>, @@ -1084,7 +1077,7 @@ pub struct GooglePayTransactionInfo { pub country_code: api_models::enums::CountryAlpha2, pub currency_code: api_models::enums::Currency, pub total_price_status: String, - pub total_price: String, + pub total_price: StringMajorUnit, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] @@ -1155,7 +1148,7 @@ pub struct TrustpayApplePayResponse { #[serde(rename_all = "camelCase")] pub struct ApplePayTotalInfo { pub label: String, - pub amount: String, + pub amount: StringMajorUnit, } impl<F> @@ -1392,7 +1385,7 @@ impl From<ApplePayTotalInfo> for api_models::payments::AmountInfo { #[serde(rename_all = "camelCase")] pub struct TrustpayRefundRequestCards { instance_id: String, - amount: String, + amount: StringMajorUnit, currency: String, reference: String, } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 6cae31c3038..0774f0a8593 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -1,6 +1,10 @@ use api_models::payments as payment_types; use async_trait::async_trait; -use common_utils::{ext_traits::ByteSliceExt, request::RequestContent}; +use common_utils::{ + ext_traits::ByteSliceExt, + request::RequestContent, + types::{AmountConvertor, StringMajorUnitForConnector}, +}; use error_stack::{Report, ResultExt}; use masking::ExposeInterface; use router_env::metrics::add_attributes; @@ -403,15 +407,16 @@ fn get_apple_pay_amount_info( label: &str, session_data: types::PaymentsSessionData, ) -> RouterResult<payment_types::AmountInfo> { + let required_amount_type = StringMajorUnitForConnector; + let apple_pay_amount = required_amount_type + .convert(session_data.minor_amount, session_data.currency) + .change_context(errors::ApiErrorResponse::PreconditionFailed { + message: "Failed to convert amount to string major unit for applePay".to_string(), + })?; let amount_info = payment_types::AmountInfo { label: label.to_string(), total_type: Some("final".to_string()), - amount: session_data - .currency - .to_currency_base_unit(session_data.amount) - .change_context(errors::ApiErrorResponse::PreconditionFailed { - message: "Failed to convert currency to base unit".to_string(), - })?, + amount: apple_pay_amount, }; Ok(amount_info) @@ -548,22 +553,21 @@ fn create_gpay_session_token( }, ) .collect(); - + let required_amount_type = StringMajorUnitForConnector; + let google_pay_amount = required_amount_type + .convert( + router_data.request.minor_amount, + router_data.request.currency, + ) + .change_context(errors::ApiErrorResponse::PreconditionFailed { + message: "Failed to convert amount to string major unit for googlePay".to_string(), + })?; let session_data = router_data.request.clone(); let transaction_info = payment_types::GpayTransactionInfo { country_code: session_data.country.unwrap_or_default(), currency_code: router_data.request.currency, total_price_status: "Final".to_string(), - total_price: router_data - .request - .currency - .to_currency_base_unit(router_data.request.amount) - .attach_printable( - "Cannot convert given amount to base currency denomination".to_string(), - ) - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "amount", - })?, + total_price: google_pay_amount, }; let required_shipping_contact_fields = diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 3488bb917e1..0dbbbbf674a 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1556,6 +1556,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionD Ok(Self { amount: amount.get_amount_as_i64(), //need to change once we move to connector module + minor_amount: amount, currency: payment_data.currency, country: payment_data.address.get_payment_method_billing().and_then( |billing_address| { diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 883693ff63a..5dcb8db05a5 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -437,7 +437,9 @@ impl ConnectorData { Ok(ConnectorEnum::Old(Box::new(&connector::Opennode))) } // "payeezy" => Ok(ConnectorIntegrationEnum::Old(Box::new(&connector::Payeezy)), As psync and rsync are not supported by this connector, it is added as template code for future usage - enums::Connector::Payme => Ok(ConnectorEnum::Old(Box::new(&connector::Payme))), + enums::Connector::Payme => { + Ok(ConnectorEnum::Old(Box::new(connector::Payme::new()))) + } enums::Connector::Payone => Ok(ConnectorEnum::Old(Box::new(&connector::Payone))), enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(&connector::Payu))), enums::Connector::Placetopay => { @@ -477,7 +479,7 @@ impl ConnectorData { } enums::Connector::Paypal => Ok(ConnectorEnum::Old(Box::new(&connector::Paypal))), enums::Connector::Trustpay => { - Ok(ConnectorEnum::Old(Box::new(&connector::Trustpay))) + Ok(ConnectorEnum::Old(Box::new(connector::Trustpay::new()))) } enums::Connector::Tsys => Ok(ConnectorEnum::Old(Box::new(&connector::Tsys))), enums::Connector::Volt => Ok(ConnectorEnum::Old(Box::new(&connector::Volt))), diff --git a/crates/router/tests/connectors/payme.rs b/crates/router/tests/connectors/payme.rs index 7c8a7720cd0..590ad15d7f6 100644 --- a/crates/router/tests/connectors/payme.rs +++ b/crates/router/tests/connectors/payme.rs @@ -17,7 +17,7 @@ impl utils::Connector for PaymeTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Payme; utils::construct_connector_data_old( - Box::new(&Payme), + Box::new(Payme::new()), types::Connector::Payme, types::api::GetToken::Connector, None, diff --git a/crates/router/tests/connectors/trustpay.rs b/crates/router/tests/connectors/trustpay.rs index 848797ebf15..bae62913a9a 100644 --- a/crates/router/tests/connectors/trustpay.rs +++ b/crates/router/tests/connectors/trustpay.rs @@ -15,7 +15,7 @@ impl utils::Connector for TrustpayTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Trustpay; utils::construct_connector_data_old( - Box::new(&Trustpay), + Box::new(Trustpay::new()), types::Connector::Trustpay, api::GetToken::Connector, None,
refactor
add amount framework to payme & Trustpay with googlePay, ApplePay for bluesnap, Noon & Trustpay (#4833)
535f2f12f825be384a17fba8628d8517027bb6c6
2024-10-08 18:47:59
DEEPANSHU BANSAL
feat(connector): Integrate PAZE Wallet (#6030)
false
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 388ccb79a66..44ac1d3e08d 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -5592,6 +5592,11 @@ "type": "object", "description": "This field contains the Samsung Pay certificates and credentials", "nullable": true + }, + "paze": { + "type": "object", + "description": "This field contains the Paze certificates and credentials", + "nullable": true } }, "additionalProperties": false @@ -12548,6 +12553,7 @@ "open_banking_uk", "pay_bright", "paypal", + "paze", "pix", "pay_safe_card", "przelewy24", @@ -17138,6 +17144,39 @@ } } }, + "PazeSessionTokenResponse": { + "type": "object", + "required": [ + "client_id", + "client_name", + "client_profile_id" + ], + "properties": { + "client_id": { + "type": "string", + "description": "Paze Client ID" + }, + "client_name": { + "type": "string", + "description": "Client Name to be displayed on the Paze screen" + }, + "client_profile_id": { + "type": "string", + "description": "Paze Client Profile ID" + } + } + }, + "PazeWalletData": { + "type": "object", + "required": [ + "complete_response" + ], + "properties": { + "complete_response": { + "type": "string" + } + } + }, "PhoneDetails": { "type": "object", "properties": { @@ -19377,6 +19416,27 @@ } ] }, + { + "allOf": [ + { + "$ref": "#/components/schemas/PazeSessionTokenResponse" + }, + { + "type": "object", + "required": [ + "wallet_name" + ], + "properties": { + "wallet_name": { + "type": "string", + "enum": [ + "paze" + ] + } + } + } + ] + }, { "type": "object", "required": [ @@ -20551,6 +20611,17 @@ } } }, + { + "type": "object", + "required": [ + "paze" + ], + "properties": { + "paze": { + "$ref": "#/components/schemas/PazeWalletData" + } + } + }, { "type": "object", "required": [ diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index d0e6c6ad0aa..90239bb8a0a 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -8884,6 +8884,11 @@ "type": "object", "description": "This field contains the Samsung Pay certificates and credentials", "nullable": true + }, + "paze": { + "type": "object", + "description": "This field contains the Paze certificates and credentials", + "nullable": true } }, "additionalProperties": false @@ -16185,6 +16190,7 @@ "open_banking_uk", "pay_bright", "paypal", + "paze", "pix", "pay_safe_card", "przelewy24", @@ -20883,6 +20889,39 @@ } } }, + "PazeSessionTokenResponse": { + "type": "object", + "required": [ + "client_id", + "client_name", + "client_profile_id" + ], + "properties": { + "client_id": { + "type": "string", + "description": "Paze Client ID" + }, + "client_name": { + "type": "string", + "description": "Client Name to be displayed on the Paze screen" + }, + "client_profile_id": { + "type": "string", + "description": "Paze Client Profile ID" + } + } + }, + "PazeWalletData": { + "type": "object", + "required": [ + "complete_response" + ], + "properties": { + "complete_response": { + "type": "string" + } + } + }, "PhoneDetails": { "type": "object", "properties": { @@ -23139,6 +23178,27 @@ } ] }, + { + "allOf": [ + { + "$ref": "#/components/schemas/PazeSessionTokenResponse" + }, + { + "type": "object", + "required": [ + "wallet_name" + ], + "properties": { + "wallet_name": { + "type": "string", + "enum": [ + "paze" + ] + } + } + } + ] + }, { "type": "object", "required": [ @@ -24395,6 +24455,17 @@ } } }, + { + "type": "object", + "required": [ + "paze" + ], + "properties": { + "paze": { + "$ref": "#/components/schemas/PazeWalletData" + } + } + }, { "type": "object", "required": [ diff --git a/config/config.example.toml b/config/config.example.toml index 54f0d1a27a4..c0358d91a26 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -540,6 +540,7 @@ debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } samsung_pay = { currency = "USD,GBP,EUR" } +paze = { currency = "USD" } [pm_filters.stax] credit = { currency = "USD" } @@ -581,6 +582,10 @@ apple_pay_ppc_key = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY" # Private key apple_pay_merchant_cert = "APPLE_PAY_MERCHNAT_CERTIFICATE" # Merchant Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Merchant Identity Certificate apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY" # Private key generated by RSA:2048 algorithm. Refer Hyperswitch Docs (https://docs.hyperswitch.io/hyperswitch-cloud/payment-methods-setup/wallets/apple-pay/ios-application/) to generate the private key +[paze_decrypt_keys] +paze_private_key = "PAZE_PRIVATE_KEY" # Base 64 Encoded Private Key File cakey.pem generated for Paze -> Command to create private key: openssl req -newkey rsa:2048 -x509 -keyout cakey.pem -out cacert.pem -days 365 +paze_private_key_passphrase = "PAZE_PRIVATE_KEY_PASSPHRASE" # PEM Passphrase used for generating Private Key File cakey.pem + [applepay_merchant_configs] # Run below command to get common merchant identifier for applepay in shell # diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index db43cac979b..5dce5be9c96 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -29,6 +29,10 @@ apple_pay_ppc_key = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY" # Private key apple_pay_merchant_cert = "APPLE_PAY_MERCHNAT_CERTIFICATE" # Merchant Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Merchant Identity Certificate apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY" # Private key generated by RSA:2048 algorithm. Refer Hyperswitch Docs (https://docs.hyperswitch.io/hyperswitch-cloud/payment-methods-setup/wallets/apple-pay/ios-application/) to generate the private key +[paze_decrypt_keys] +paze_private_key = "PAZE_PRIVATE_KEY" # Base 64 Encoded Private Key File cakey.pem generated for Paze -> Command to create private key: openssl req -newkey rsa:2048 -x509 -keyout cakey.pem -out cacert.pem -days 365 +paze_private_key_passphrase = "PAZE_PRIVATE_KEY_PASSPHRASE" # PEM Passphrase used for generating Private Key File cakey.pem + [applepay_merchant_configs] common_merchant_identifier = "APPLE_PAY_COMMON_MERCHANT_IDENTIFIER" # Refer to config.example.toml to learn how you can generate this value merchant_cert = "APPLE_PAY_MERCHANT_CERTIFICATE" # Merchant Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Merchant Identity Certificate diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index dbb4161ec5d..4f742a61698 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -307,6 +307,7 @@ debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } samsung_pay = { currency = "USD,GBP,EUR" } +paze = { currency = "USD" } [pm_filters.nexixpay] credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index c100ccf46de..c25b70d6ba0 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -281,6 +281,7 @@ debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } samsung_pay = { currency = "USD,GBP,EUR" } +paze = { currency = "USD" } [pm_filters.nexixpay] credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 89aea282764..28f5a4e0575 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -284,6 +284,7 @@ debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } samsung_pay = { currency = "USD,GBP,EUR" } +paze = { currency = "USD" } [pm_filters.nexixpay] credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } diff --git a/config/development.toml b/config/development.toml index f0e26172514..0153c6ef102 100644 --- a/config/development.toml +++ b/config/development.toml @@ -453,6 +453,7 @@ debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } samsung_pay = { currency = "USD,GBP,EUR" } +paze = { currency = "USD" } [pm_filters.nexixpay] credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } @@ -617,6 +618,10 @@ apple_pay_ppc_key = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY" apple_pay_merchant_cert = "APPLE_PAY_MERCHNAT_CERTIFICATE" apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY" +[paze_decrypt_keys] +paze_private_key = "PAZE_PRIVATE_KEY" +paze_private_key_passphrase = "PAZE_PRIVATE_KEY_PASSPHRASE" + [generic_link] [generic_link.payment_method_collect] sdk_url = "http://localhost:9050/HyperLoader.js" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 1b9ef294dc0..5ffe5df138f 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -420,6 +420,7 @@ debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } samsung_pay = { currency = "USD,GBP,EUR" } +paze = { currency = "USD" } [pm_filters.nexixpay] credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 6e7f4f29d03..8f24bdf65bc 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -1558,6 +1558,10 @@ pub struct ConnectorWalletDetails { #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub samsung_pay: Option<pii::SecretSerdeValue>, + /// This field contains the Paze certificates and credentials + #[serde(skip_serializing_if = "Option::is_none")] + #[schema(value_type = Option<Object>)] + pub paze: Option<pii::SecretSerdeValue>, } /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 9cafc37af54..a758d457858 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1930,6 +1930,7 @@ impl GetPaymentMethodType for WalletData { Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, + Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, @@ -2819,6 +2820,8 @@ pub enum WalletData { PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), + /// The wallet data for Paze + Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection @@ -2879,6 +2882,7 @@ impl GetAddressFromPaymentMethodData for WalletData { | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) + | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} @@ -2891,6 +2895,13 @@ impl GetAddressFromPaymentMethodData for WalletData { } } +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub struct PazeWalletData { + #[schema(value_type = String)] + pub complete_response: Secret<String>, +} + #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { @@ -4932,6 +4943,19 @@ pub struct GpaySessionTokenData { pub data: GpayMetaData, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PazeSessionTokenData { + #[serde(rename = "paze")] + pub data: PazeMetadata, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PazeMetadata { + pub client_id: String, + pub client_name: String, + pub client_profile_id: String, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { @@ -5138,10 +5162,23 @@ pub enum SessionToken { ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), + /// The session response structure for Paze + Paze(Box<PazeSessionTokenResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[serde(rename_all = "lowercase")] +pub struct PazeSessionTokenResponse { + /// Paze Client ID + pub client_id: String, + /// Client Name to be displayed on the Paze screen + pub client_name: String, + /// Paze Client Profile ID + pub client_profile_id: String, +} + #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 528f38ac61a..5ab05c9a688 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1593,6 +1593,7 @@ pub enum PaymentMethodType { OpenBankingUk, PayBright, Paypal, + Paze, Pix, PaySafeCard, Przelewy24, diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index db4162a8bb1..4fba749ef63 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1843,6 +1843,7 @@ impl From<PaymentMethodType> for PaymentMethod { PaymentMethodType::OnlineBankingThailand => Self::BankRedirect, PaymentMethodType::OnlineBankingPoland => Self::BankRedirect, PaymentMethodType::OnlineBankingSlovakia => Self::BankRedirect, + PaymentMethodType::Paze => Self::Wallet, PaymentMethodType::PermataBankTransfer => Self::BankTransfer, PaymentMethodType::Pix => Self::BankTransfer, PaymentMethodType::Pse => Self::BankTransfer, diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs index 68ade2909b4..88997691eb6 100644 --- a/crates/connector_configs/src/transformer.rs +++ b/crates/connector_configs/src/transformer.rs @@ -56,7 +56,10 @@ impl DashboardRequestPayload { | (Connector::Stripe, WeChatPay) => { Some(api_models::enums::PaymentExperience::DisplayQrCode) } - (_, GooglePay) | (_, ApplePay) | (_, PaymentMethodType::SamsungPay) => { + (_, GooglePay) + | (_, ApplePay) + | (_, PaymentMethodType::SamsungPay) + | (_, PaymentMethodType::Paze) => { Some(api_models::enums::PaymentExperience::InvokeSdkClient) } _ => Some(api_models::enums::PaymentExperience::RedirectToUrl), diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs index 0d2f959c702..136cdf4d981 100644 --- a/crates/euclid/src/frontend/dir/enums.rs +++ b/crates/euclid/src/frontend/dir/enums.rs @@ -91,6 +91,7 @@ pub enum WalletType { Cashapp, Venmo, Mifinity, + Paze, } #[derive( diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs index 33d368e9696..da589ec3748 100644 --- a/crates/euclid/src/frontend/dir/lowering.rs +++ b/crates/euclid/src/frontend/dir/lowering.rs @@ -58,6 +58,7 @@ impl From<enums::WalletType> for global_enums::PaymentMethodType { enums::WalletType::Cashapp => Self::Cashapp, enums::WalletType::Venmo => Self::Venmo, enums::WalletType::Mifinity => Self::Mifinity, + enums::WalletType::Paze => Self::Paze, } } } diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs index 3e35bcd391c..de0b619b120 100644 --- a/crates/euclid/src/frontend/dir/transformers.rs +++ b/crates/euclid/src/frontend/dir/transformers.rs @@ -188,6 +188,7 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet global_enums::PaymentMethodType::OpenBankingPIS => { Ok(dirval!(OpenBankingType = OpenBankingPIS)) } + global_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)), } } } diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index eab8d878f05..c4ca017cec7 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -366,6 +366,9 @@ impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentReque PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { FiuuPaymentMethodData::try_from(decrypt_data) } + PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Fiuu"))? + } } } WalletData::AliPayQr(_) @@ -384,6 +387,7 @@ impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentReque | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) + | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} diff --git a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs index 4986e8d5f32..772f2af209e 100644 --- a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs @@ -74,6 +74,7 @@ impl TryFrom<&GlobepayRouterData<&types::PaymentsAuthorizeRouterData>> for Globe | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) + | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} diff --git a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs index d0525921632..a12434a460a 100644 --- a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs @@ -182,6 +182,9 @@ impl TryFrom<&MollieRouterData<&types::PaymentsAuthorizeRouterData>> for MollieP "Mollie" ))? } + PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Mollie"))? + } }), }, ))) diff --git a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs index 4e2b30a574b..ad09e7445d4 100644 --- a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs @@ -119,6 +119,7 @@ impl TryFrom<(&types::TokenizationRouterData, WalletData)> for SquareTokenReques | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) + | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} @@ -263,6 +264,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest { PaymentMethodToken::ApplePayDecrypt(_) => Err( unimplemented_payment_method!("Apple Pay", "Simplified", "Square"), )?, + PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Square"))? + } }, amount_money: SquarePaymentsAmountData { amount: item.request.amount, diff --git a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs index f7b2016a370..686178e9621 100644 --- a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs @@ -82,6 +82,9 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme PaymentMethodToken::ApplePayDecrypt(_) => Err( unimplemented_payment_method!("Apple Pay", "Simplified", "Stax"), )?, + PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Stax"))? + } }, idempotency_id: Some(item.router_data.connector_request_reference_id.clone()), }) @@ -99,6 +102,9 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme PaymentMethodToken::ApplePayDecrypt(_) => Err( unimplemented_payment_method!("Apple Pay", "Simplified", "Stax"), )?, + PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Stax"))? + } }, idempotency_id: Some(item.router_data.connector_request_reference_id.clone()), }) diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 4c7c9adaf8e..66b8081b0f2 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -1781,6 +1781,7 @@ pub enum PaymentMethodDataType { MobilePayRedirect, PaypalRedirect, PaypalSdk, + Paze, SamsungPay, TwintRedirect, VippsRedirect, @@ -1898,6 +1899,7 @@ impl From<PaymentMethodData> for PaymentMethodDataType { hyperswitch_domain_models::payment_method_data::WalletData::MobilePayRedirect(_) => Self::MobilePayRedirect, hyperswitch_domain_models::payment_method_data::WalletData::PaypalRedirect(_) => Self::PaypalRedirect, hyperswitch_domain_models::payment_method_data::WalletData::PaypalSdk(_) => Self::PaypalSdk, + hyperswitch_domain_models::payment_method_data::WalletData::Paze(_) => Self::Paze, hyperswitch_domain_models::payment_method_data::WalletData::SamsungPay(_) => Self::SamsungPay, hyperswitch_domain_models::payment_method_data::WalletData::TwintRedirect {} => Self::TwintRedirect, hyperswitch_domain_models::payment_method_data::WalletData::VippsRedirect {} => Self::VippsRedirect, diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 9f505f26712..3ccfabf021c 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -117,6 +117,7 @@ pub enum WalletData { MobilePayRedirect(Box<MobilePayRedirection>), PaypalRedirect(PaypalRedirection), PaypalSdk(PayPalWalletData), + Paze(PazeWalletData), SamsungPay(Box<SamsungPayWalletData>), TwintRedirect {}, VippsRedirect {}, @@ -134,6 +135,12 @@ pub struct MifinityData { pub language_preference: Option<String>, } +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub struct PazeWalletData { + pub complete_response: Secret<String>, +} + #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { @@ -689,6 +696,9 @@ impl From<api_models::payments::WalletData> for WalletData { token: paypal_sdk_data.token, }) } + api_models::payments::WalletData::Paze(paze_data) => { + Self::Paze(PazeWalletData::from(paze_data)) + } api_models::payments::WalletData::SamsungPay(samsung_pay_data) => { Self::SamsungPay(Box::new(SamsungPayWalletData::from(samsung_pay_data))) } @@ -754,6 +764,14 @@ impl From<api_models::payments::ApplePayWalletData> for ApplePayWalletData { } } +impl From<api_models::payments::PazeWalletData> for PazeWalletData { + fn from(value: api_models::payments::PazeWalletData) -> Self { + Self { + complete_response: value.complete_response, + } + } +} + impl From<Box<api_models::payments::SamsungPayWalletData>> for SamsungPayWalletData { fn from(value: Box<api_models::payments::SamsungPayWalletData>) -> Self { Self { @@ -1388,6 +1406,7 @@ impl GetPaymentMethodType for WalletData { Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, + Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index cd8ac85594e..b41b42eaa2d 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -220,6 +220,7 @@ pub struct AccessToken { pub enum PaymentMethodToken { Token(Secret<String>), ApplePayDecrypt(Box<ApplePayPredecryptData>), + PazeDecrypt(Box<PazeDecryptedData>), } #[derive(Debug, Clone, serde::Deserialize)] @@ -241,6 +242,69 @@ pub struct ApplePayCryptogramData { pub eci_indicator: Option<String>, } +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PazeDecryptedData { + pub client_id: Secret<String>, + pub profile_id: String, + pub token: PazeToken, + pub payment_card_network: common_enums::enums::CardNetwork, + pub dynamic_data: Vec<PazeDynamicData>, + pub billing_address: PazeAddress, + pub consumer: PazeConsumer, + pub eci: Option<String>, +} + +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PazeToken { + pub payment_token: cards::CardNumber, + pub token_expiration_month: Secret<String>, + pub token_expiration_year: Secret<String>, + pub payment_account_reference: Secret<String>, +} + +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PazeDynamicData { + pub dynamic_data_value: Option<Secret<String>>, + pub dynamic_data_type: Option<String>, + pub dynamic_data_expiration: Option<String>, +} + +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PazeAddress { + pub name: Option<Secret<String>>, + pub line1: Option<Secret<String>>, + pub line2: Option<Secret<String>>, + pub line3: Option<Secret<String>>, + pub city: Option<Secret<String>>, + pub state: Option<Secret<String>>, + pub zip: Option<Secret<String>>, + pub country_code: Option<common_enums::enums::CountryAlpha2>, +} + +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PazeConsumer { + // This is consumer data not customer data. + pub first_name: Option<Secret<String>>, + pub last_name: Option<Secret<String>>, + pub full_name: Secret<String>, + pub email_address: common_utils::pii::Email, + pub mobile_number: Option<PazePhoneNumber>, + pub country_code: Option<common_enums::enums::CountryAlpha2>, + pub language_code: Option<String>, +} + +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PazePhoneNumber { + pub country_code: Secret<String>, + pub phone_number: Secret<String>, +} + #[derive(Debug, Default, Clone)] pub struct RecurringMandatePaymentData { pub payment_method_type: Option<common_enums::enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index 2ec0cbe8031..e897292d6ff 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -146,6 +146,7 @@ fn get_dir_value_payment_method( api_enums::PaymentMethodType::OpenBankingPIS => { Ok(dirval!(OpenBankingType = OpenBankingPIS)) } + api_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)), } } diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 758a0dd3de0..1a340aa91d3 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -307,6 +307,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { api_enums::PaymentMethodType::OpenBankingPIS => { Ok(dirval!(OpenBankingType = OpenBankingPIS)) } + api_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)), } } } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index a76726eb8ac..24fbadc0a59 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -389,6 +389,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentsCaptureRequest, api_models::payments::PaymentsSessionRequest, api_models::payments::PaymentsSessionResponse, + api_models::payments::PazeWalletData, api_models::payments::SessionToken, api_models::payments::ApplePaySessionResponse, api_models::payments::ThirdPartySdkSessionResponse, @@ -445,6 +446,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::GooglePayRedirectData, api_models::payments::GooglePayThirdPartySdk, api_models::payments::GooglePaySessionResponse, + api_models::payments::PazeSessionTokenResponse, api_models::payments::SamsungPaySessionTokenResponse, api_models::payments::SamsungPayMerchantPaymentInformation, api_models::payments::SamsungPayAmountDetails, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 05a2c72ba94..bc44068030b 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -323,6 +323,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentsSessionResponse, api_models::payments::PaymentsCreateIntentRequest, api_models::payments::PaymentsCreateIntentResponse, + api_models::payments::PazeWalletData, api_models::payments::AmountDetails, api_models::payments::SessionToken, api_models::payments::ApplePaySessionResponse, @@ -358,6 +359,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::GooglePayPaymentMethodInfo, api_models::payments::ApplePayWalletData, api_models::payments::ApplepayPaymentMethod, + api_models::payments::PazeSessionTokenResponse, api_models::payments::SamsungPaySessionTokenResponse, api_models::payments::SamsungPayMerchantPaymentInformation, api_models::payments::SamsungPayAmountDetails, diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 0f25477802c..dbdba189ed1 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -178,6 +178,27 @@ impl SecretsHandler for settings::ApplePayDecryptConfig { } } +#[async_trait::async_trait] +impl SecretsHandler for settings::PazeDecryptConfig { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let paze_decrypt_keys = value.get_inner(); + + let (paze_private_key, paze_private_key_passphrase) = tokio::try_join!( + secret_management_client.get_secret(paze_decrypt_keys.paze_private_key.clone()), + secret_management_client + .get_secret(paze_decrypt_keys.paze_private_key_passphrase.clone()), + )?; + + Ok(value.transition_state(|_| Self { + paze_private_key, + paze_private_key_passphrase, + })) + } +} + #[async_trait::async_trait] impl SecretsHandler for settings::ApplepayMerchantConfigs { async fn convert_to_raw_secret( @@ -388,6 +409,17 @@ pub(crate) async fn fetch_raw_secrets( .await .expect("Failed to decrypt applepay decrypt configs"); + #[allow(clippy::expect_used)] + let paze_decrypt_keys = if let Some(paze_keys) = conf.paze_decrypt_keys { + Some( + settings::PazeDecryptConfig::convert_to_raw_secret(paze_keys, secret_management_client) + .await + .expect("Failed to decrypt paze decrypt configs"), + ) + } else { + None + }; + #[allow(clippy::expect_used)] let applepay_merchant_configs = settings::ApplepayMerchantConfigs::convert_to_raw_secret( conf.applepay_merchant_configs, @@ -479,6 +511,7 @@ pub(crate) async fn fetch_raw_secrets( #[cfg(feature = "payouts")] payouts: conf.payouts, applepay_decrypt_keys, + paze_decrypt_keys, multiple_api_version_supported_connectors: conf.multiple_api_version_supported_connectors, applepay_merchant_configs, lock_settings: conf.lock_settings, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 1124423714b..149ee2b8456 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -96,6 +96,7 @@ pub struct Settings<S: SecretState> { pub payouts: Payouts, pub payout_method_filters: ConnectorFilters, pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConfig, S>, + pub paze_decrypt_keys: Option<SecretStateContainer<PazeDecryptConfig, S>>, pub multiple_api_version_supported_connectors: MultipleApiVersionSupportedConnectors, pub applepay_merchant_configs: SecretStateContainer<ApplepayMerchantConfigs, S>, pub lock_settings: LockSettings, @@ -723,6 +724,12 @@ pub struct ApplePayDecryptConfig { pub apple_pay_merchant_cert_key: Secret<String>, } +#[derive(Debug, Deserialize, Clone, Default)] +pub struct PazeDecryptConfig { + pub paze_private_key: Secret<String>, + pub paze_private_key_passphrase: Secret<String>, +} + #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct LockerBasedRecipientConnectorList { @@ -864,6 +871,11 @@ impl Settings<SecuredSecret> { .map(|x| x.get_inner().validate()) .transpose()?; + self.paze_decrypt_keys + .as_ref() + .map(|x| x.get_inner().validate()) + .transpose()?; + self.key_manager.get_inner().validate()?; Ok(()) diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index f109fe3f773..7040998ccf0 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -236,6 +236,27 @@ impl super::settings::NetworkTokenizationService { } } +impl super::settings::PazeDecryptConfig { + pub fn validate(&self) -> Result<(), ApplicationError> { + use common_utils::fp_utils::when; + + when(self.paze_private_key.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "paze_private_key must not be empty".into(), + )) + })?; + + when( + self.paze_private_key_passphrase.is_default_or_empty(), + || { + Err(ApplicationError::InvalidConfigurationValueError( + "paze_private_key_passphrase must not be empty".into(), + )) + }, + ) + } +} + impl super::settings::KeyManagerConfig { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 46f312b38f2..abd99fae18c 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -120,6 +120,7 @@ impl TryFrom<(&domain::WalletData, &types::PaymentsAuthorizeRouterData)> for Pay | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect { .. } | domain::WalletData::VippsRedirect { .. } diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 810551e0cb7..e5215022e94 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -218,6 +218,7 @@ impl ConnectorValidation for Adyen { | PaymentMethodType::Pse | PaymentMethodType::LocalBankTransfer | PaymentMethodType::Efecty + | PaymentMethodType::Paze | PaymentMethodType::PagoEfectivo | PaymentMethodType::PromptPay | PaymentMethodType::RedCompra diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 50ce6aea0f4..4cc392c57bc 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2149,6 +2149,7 @@ impl<'a> TryFrom<(&domain::WalletData, &types::PaymentsAuthorizeRouterData)> | domain::WalletData::GooglePayRedirect(_) | domain::WalletData::GooglePayThirdPartySdk(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::WeChatPayQr(_) | domain::WalletData::CashappQr(_) | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index 4d84f64534e..868a4767c31 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -254,6 +254,7 @@ fn get_wallet_details( | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 868409dafc7..e352d8b79bc 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -1747,6 +1747,7 @@ fn get_wallet_data( | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index b987a6717a1..ab6367eeb6e 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -297,6 +297,7 @@ impl TryFrom<&types::SetupMandateRouterData> for BankOfAmericaPaymentsRequest { | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -977,6 +978,9 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> "Bank Of America" ))? } + types::PaymentMethodToken::PazeDecrypt(_) => Err( + unimplemented_payment_method!("Paze", "Bank Of America"), + )?, }, None => { let email = item.router_data.request.get_email()?; @@ -1051,6 +1055,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -2328,6 +2333,9 @@ impl TryFrom<(&types::SetupMandateRouterData, domain::ApplePayWalletData)> "Manual", "Bank Of America" ))?, + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Bank Of America"))? + } }, None => PaymentInformation::from(&apple_pay_data), }; diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index 6ebcdf0e765..b156aafb6ef 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -369,6 +369,7 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs index 5fd6b0e6a2e..a48e49a10cc 100644 --- a/crates/router/src/connector/boku/transformers.rs +++ b/crates/router/src/connector/boku/transformers.rs @@ -180,6 +180,7 @@ fn get_wallet_type(wallet_data: &domain::WalletData) -> Result<String, errors::C | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 05d8c1c559d..29f741d8bdc 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -1591,6 +1591,9 @@ impl types::PaymentMethodToken::ApplePayDecrypt(_) => Err( unimplemented_payment_method!("Apple Pay", "Simplified", "Braintree"), )?, + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Braintree"))? + } }, transaction: transaction_body, }, @@ -1689,6 +1692,9 @@ fn get_braintree_redirect_form( "Simplified", "Braintree" ))?, + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Braintree"))? + } }, bin: match card_details { domain::PaymentMethodData::Card(card_details) => { diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index 223256155cf..2950fdb6bd1 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -106,6 +106,7 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest { | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -301,6 +302,9 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme types::PaymentMethodToken::ApplePayDecrypt(_) => Err( unimplemented_payment_method!("Apple Pay", "Simplified", "Checkout"), )?, + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Checkout"))? + } }, })), domain::WalletData::ApplePay(_) => { @@ -327,6 +331,9 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme }, ))) } + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Checkout"))? + } } } domain::WalletData::AliPayQr(_) @@ -345,6 +352,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 38bb016ff25..8a6c3c075ff 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -176,6 +176,9 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { types::PaymentMethodToken::Token(_) => Err( unimplemented_payment_method!("Apple Pay", "Manual", "Cybersource"), )?, + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Cybersource"))? + } }, None => ( PaymentInformation::ApplePayToken(Box::new( @@ -221,6 +224,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -1322,6 +1326,92 @@ impl } } +impl + TryFrom<( + &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, + Box<hyperswitch_domain_models::router_data::PazeDecryptedData>, + )> for CybersourcePaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, paze_data): ( + &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, + Box<hyperswitch_domain_models::router_data::PazeDecryptedData>, + ), + ) -> Result<Self, Self::Error> { + let email = item.router_data.request.get_email()?; + let (first_name, last_name) = match paze_data.billing_address.name { + Some(name) => { + let (first_name, last_name) = name + .peek() + .split_once(' ') + .map(|(first, last)| (first.to_string(), last.to_string())) + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "billing_address.name", + })?; + (Secret::from(first_name), Secret::from(last_name)) + } + None => ( + item.router_data.get_billing_first_name()?, + item.router_data.get_billing_last_name()?, + ), + }; + let bill_to = BillTo { + first_name: Some(first_name), + last_name: Some(last_name), + address1: paze_data.billing_address.line1, + locality: paze_data.billing_address.city.map(|city| city.expose()), + administrative_area: Some(Secret::from( + //Paze wallet is currently supported in US only + common_enums::UsStatesAbbreviation::foreign_try_from( + paze_data + .billing_address + .state + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "billing_address.state", + })? + .peek() + .to_owned(), + )? + .to_string(), + )), + postal_code: paze_data.billing_address.zip, + country: paze_data.billing_address.country_code, + email, + }; + let order_information = OrderInformationWithBill::from((item, Some(bill_to))); + + let payment_information = + PaymentInformation::NetworkToken(Box::new(NetworkTokenPaymentInformation { + tokenized_card: NetworkTokenizedCard { + number: paze_data.token.payment_token, + expiration_month: paze_data.token.token_expiration_month, + expiration_year: paze_data.token.token_expiration_year, + cryptogram: Some(paze_data.token.payment_account_reference), + transaction_type: "1".to_string(), + }, + })); + + let processing_information = ProcessingInformation::try_from((item, None, None))?; + let client_reference_information = ClientReferenceInformation::from(item); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); + + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + consumer_authentication_information: None, + merchant_defined_information, + }) + } +} + impl TryFrom<( &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, @@ -1645,6 +1735,9 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> "Cybersource" ))? } + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Cybersource"))? + } }, None => { let email = item @@ -1719,6 +1812,19 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> domain::WalletData::SamsungPay(samsung_pay_data) => { Self::try_from((item, samsung_pay_data)) } + domain::WalletData::Paze(_) => { + match item.router_data.payment_method_token.clone() { + Some(types::PaymentMethodToken::PazeDecrypt( + paze_decrypted_data, + )) => Self::try_from((item, paze_decrypted_data)), + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message( + "Cybersource", + ), + ) + .into()), + } + } domain::WalletData::AliPayQr(_) | domain::WalletData::AliPayRedirect(_) | domain::WalletData::AliPayHkRedirect(_) diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs index ff2f9d95026..4982aaf4d88 100644 --- a/crates/router/src/connector/gocardless/transformers.rs +++ b/crates/router/src/connector/gocardless/transformers.rs @@ -429,7 +429,8 @@ impl TryFrom<&types::SetupMandateRouterData> for GocardlessMandateRequest { let payment_method_token = item.get_payment_method_token()?; let customer_bank_account = match payment_method_token { types::PaymentMethodToken::Token(token) => Ok(token), - types::PaymentMethodToken::ApplePayDecrypt(_) => { + types::PaymentMethodToken::ApplePayDecrypt(_) + | types::PaymentMethodToken::PazeDecrypt(_) => { Err(errors::ConnectorError::NotImplemented( "Setup Mandate flow for selected payment method through Gocardless".to_string(), )) diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 0e6fab80584..2c3d3651284 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -598,6 +598,7 @@ impl | common_enums::PaymentMethodType::OpenBankingUk | common_enums::PaymentMethodType::PayBright | common_enums::PaymentMethodType::Paypal + | common_enums::PaymentMethodType::Paze | common_enums::PaymentMethodType::Pix | common_enums::PaymentMethodType::PaySafeCard | common_enums::PaymentMethodType::Przelewy24 diff --git a/crates/router/src/connector/mifinity/transformers.rs b/crates/router/src/connector/mifinity/transformers.rs index 0af3826c877..92b6b45785d 100644 --- a/crates/router/src/connector/mifinity/transformers.rs +++ b/crates/router/src/connector/mifinity/transformers.rs @@ -169,6 +169,7 @@ impl TryFrom<&MifinityRouterData<&types::PaymentsAuthorizeRouterData>> for Mifin | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index 547a38ad849..e0146bf2eda 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -493,6 +493,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -556,6 +557,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -714,6 +716,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 55b2fbe4176..5bf72133384 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -722,6 +722,7 @@ fn get_wallet_details( | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect { .. } | domain::WalletData::VippsRedirect { .. } diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index 069a51ae52e..57b04cdca17 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -558,6 +558,7 @@ impl | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 5d987174273..99e04018632 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -326,6 +326,7 @@ impl TryFrom<&NoonRouterData<&types::PaymentsAuthorizeRouterData>> for NoonPayme | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index f280d3a42a2..d9728174f84 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -914,6 +914,7 @@ where | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index e0ab598d76d..b4aa66a1c49 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -403,6 +403,7 @@ impl TryFrom<&PaymentMethodData> for SalePaymentMethod { | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -715,6 +716,9 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest { types::PaymentMethodToken::ApplePayDecrypt(_) => Err( unimplemented_payment_method!("Apple Pay", "Simplified", "Payme"), )?, + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Payme"))? + } }; Ok(Self { buyer_email, diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 4f5ab133735..41fd533309e 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -490,6 +490,7 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP | domain::WalletData::GooglePayThirdPartySdk(_) | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 13c0395cf9f..e206fe0e0ae 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -282,6 +282,7 @@ impl TryFrom<&domain::WalletData> for Shift4PaymentMethod { | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index f9fd519241a..68bab815d65 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -737,6 +737,7 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { | enums::PaymentMethodType::MandiriVa | enums::PaymentMethodType::PermataBankTransfer | enums::PaymentMethodType::PaySafeCard + | enums::PaymentMethodType::Paze | enums::PaymentMethodType::Givex | enums::PaymentMethodType::Benefit | enums::PaymentMethodType::Knet @@ -1062,6 +1063,7 @@ impl ForeignTryFrom<&domain::WalletData> for Option<StripePaymentMethodType> { | domain::WalletData::GooglePayThirdPartySdk(_) | domain::WalletData::MbWayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -1478,6 +1480,7 @@ impl TryFrom<(&domain::WalletData, Option<types::PaymentMethodToken>)> for Strip | domain::WalletData::GooglePayThirdPartySdk(_) | domain::WalletData::MbWayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -1809,6 +1812,9 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent wallet_name: "Apple Pay".to_string(), })? } + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(crate::unimplemented_payment_method!("Paze", "Stripe"))? + } }; Some(StripePaymentMethodData::Wallet( StripeWallet::ApplepayPayment(ApplepayPayment { diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index c66e1f2f65c..31afb0adf11 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -2638,6 +2638,7 @@ pub enum PaymentMethodDataType { MobilePayRedirect, PaypalRedirect, PaypalSdk, + Paze, SamsungPay, TwintRedirect, VippsRedirect, @@ -2755,6 +2756,7 @@ impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType { domain::payments::WalletData::MobilePayRedirect(_) => Self::MobilePayRedirect, domain::payments::WalletData::PaypalRedirect(_) => Self::PaypalRedirect, domain::payments::WalletData::PaypalSdk(_) => Self::PaypalSdk, + domain::payments::WalletData::Paze(_) => Self::Paze, domain::payments::WalletData::SamsungPay(_) => Self::SamsungPay, domain::payments::WalletData::TwintRedirect {} => Self::TwintRedirect, domain::payments::WalletData::VippsRedirect {} => Self::VippsRedirect, diff --git a/crates/router/src/connector/wellsfargo/transformers.rs b/crates/router/src/connector/wellsfargo/transformers.rs index be3cf4a1cef..ee34c26d670 100644 --- a/crates/router/src/connector/wellsfargo/transformers.rs +++ b/crates/router/src/connector/wellsfargo/transformers.rs @@ -135,6 +135,9 @@ impl TryFrom<&types::SetupMandateRouterData> for WellsfargoZeroMandateRequest { types::PaymentMethodToken::Token(_) => Err( unimplemented_payment_method!("Apple Pay", "Manual", "Wellsfargo"), )?, + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Wellsfargo"))? + } }, None => ( PaymentInformation::ApplePayToken(Box::new( @@ -180,6 +183,7 @@ impl TryFrom<&types::SetupMandateRouterData> for WellsfargoZeroMandateRequest { | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -1158,6 +1162,9 @@ impl TryFrom<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>> "Wellsfargo" ))? } + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Wellsfargo"))? + } }, None => { let email = item.router_data.request.get_email()?; @@ -1242,6 +1249,7 @@ impl TryFrom<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>> | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index de82e11548c..467a1cba902 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -83,6 +83,7 @@ fn fetch_payment_instrument( | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index d2e8ce40283..2b2e7e889e2 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -486,6 +486,7 @@ impl | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index c56bfaca913..aa4ff406a2c 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -234,6 +234,16 @@ pub enum ApplePayDecryptionError { DerivingSharedSecretKeyFailed, } +#[derive(Debug, thiserror::Error)] +pub enum PazeDecryptionError { + #[error("Failed to base64 decode input data")] + Base64DecodingFailed, + #[error("Failed to decrypt input data")] + DecryptionFailed, + #[error("Certificate parsing failed")] + CertificateParsingFailed, +} + #[cfg(feature = "detailed_errors")] pub mod error_stack_parsing { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 9f904116171..363d52cd8bf 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -34,13 +34,13 @@ use diesel_models::{ephemeral_key, fraud_check::FraudCheck}; use error_stack::{report, ResultExt}; use events::EventInfo; use futures::future::join_all; -use helpers::ApplePayData; +use helpers::{decrypt_paze_token, ApplePayData}; #[cfg(feature = "v2")] use hyperswitch_domain_models::payments::PaymentIntentData; pub use hyperswitch_domain_models::{ mandates::{CustomerAcceptance, MandateData}, payment_address::PaymentAddress, - router_data::RouterData, + router_data::{PaymentMethodToken, RouterData}, router_request_types::CustomerDetails, }; use masking::{ExposeInterface, PeekInterface, Secret}; @@ -1710,42 +1710,12 @@ where &call_connector_action, ); - // Tokenization Action will be DecryptApplePayToken, only when payment method type is Apple Pay - // and the connector supports Apple Pay predecrypt - match &tokenization_action { - TokenizationAction::DecryptApplePayToken(payment_processing_details) - | TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( - payment_processing_details, - ) => { - let apple_pay_data = match payment_data.get_payment_method_data() { - Some(domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay( - wallet_data, - ))) => Some( - ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data.clone())) - .change_context(errors::ApiErrorResponse::InternalServerError)? - .decrypt( - &payment_processing_details.payment_processing_certificate, - &payment_processing_details.payment_processing_certificate_key, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?, - ), - _ => None, - }; - - let apple_pay_predecrypt = apple_pay_data - .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>( - "ApplePayPredecryptData", - ) - .change_context(errors::ApiErrorResponse::InternalServerError)?; - - router_data.payment_method_token = Some( - hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt( - Box::new(apple_pay_predecrypt), - ), - ); - } - _ => (), + router_data.payment_method_token = if let Some(decrypted_token) = + add_decrypted_payment_method_token(tokenization_action.clone(), payment_data).await? + { + Some(decrypted_token) + } else { + router_data.payment_method_token }; let payment_method_token_response = router_data @@ -1853,6 +1823,83 @@ where Ok((router_data, merchant_connector_account)) } +pub async fn add_decrypted_payment_method_token<F, D>( + tokenization_action: TokenizationAction, + payment_data: &D, +) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse> +where + F: Send + Clone + Sync, + D: OperationSessionGetters<F> + Send + Sync + Clone, +{ + // Tokenization Action will be DecryptApplePayToken, only when payment method type is Apple Pay + // and the connector supports Apple Pay predecrypt + match &tokenization_action { + TokenizationAction::DecryptApplePayToken(payment_processing_details) + | TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( + payment_processing_details, + ) => { + let apple_pay_data = match payment_data.get_payment_method_data() { + Some(domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay( + wallet_data, + ))) => Some( + ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data.clone())) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to parse apple pay token to json")? + .decrypt( + &payment_processing_details.payment_processing_certificate, + &payment_processing_details.payment_processing_certificate_key, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to decrypt apple pay token")?, + ), + _ => None, + }; + + let apple_pay_predecrypt = apple_pay_data + .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>( + "ApplePayPredecryptData", + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "failed to parse decrypted apple pay response to ApplePayPredecryptData", + )?; + + Ok(Some(PaymentMethodToken::ApplePayDecrypt(Box::new( + apple_pay_predecrypt, + )))) + } + TokenizationAction::DecryptPazeToken(payment_processing_details) => { + let paze_data = match payment_data.get_payment_method_data() { + Some(domain::PaymentMethodData::Wallet(domain::WalletData::Paze(wallet_data))) => { + Some( + decrypt_paze_token( + wallet_data.clone(), + payment_processing_details.paze_private_key.clone(), + payment_processing_details + .paze_private_key_passphrase + .clone(), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to decrypt paze token")?, + ) + } + _ => None, + }; + let paze_decrypted_data = paze_data + .parse_value::<hyperswitch_domain_models::router_data::PazeDecryptedData>( + "PazeDecryptedData", + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to parse PazeDecryptedData")?; + Ok(Some(PaymentMethodToken::PazeDecrypt(Box::new( + paze_decrypted_data, + )))) + } + _ => Ok(None), + } +} + pub async fn get_merchant_bank_data_for_open_banking_connectors( merchant_connector_account: &helpers::MerchantConnectorAccountType, key_store: &domain::MerchantKeyStore, @@ -2642,59 +2689,87 @@ async fn decide_payment_method_tokenize_action( pm_parent_token: Option<&str>, is_connector_tokenization_enabled: bool, apple_pay_flow: Option<domain::ApplePayFlow>, + payment_method_type: Option<storage_enums::PaymentMethodType>, ) -> RouterResult<TokenizationAction> { - match pm_parent_token { - None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) { - (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { - TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( - payment_processing_details, - ) - } - (true, _) => TokenizationAction::TokenizeInConnectorAndRouter, - (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { - TokenizationAction::DecryptApplePayToken(payment_processing_details) - } - (false, _) => TokenizationAction::TokenizeInRouter, - }), - Some(token) => { - let redis_conn = state - .store - .get_redis_conn() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to get redis connection")?; - - let key = format!( - "pm_token_{}_{}_{}", - token.to_owned(), - payment_method, - connector_name - ); + if let Some(storage_enums::PaymentMethodType::Paze) = payment_method_type { + // Paze generates a one time use network token which should not be tokenized in the connector or router. + match &state.conf.paze_decrypt_keys { + Some(paze_keys) => Ok(TokenizationAction::DecryptPazeToken( + PazePaymentProcessingDetails { + paze_private_key: paze_keys.get_inner().paze_private_key.clone(), + paze_private_key_passphrase: paze_keys + .get_inner() + .paze_private_key_passphrase + .clone(), + }, + )), + None => Err(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch Paze configs"), + } + } else { + match pm_parent_token { + None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) { + (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { + TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( + payment_processing_details, + ) + } + (true, _) => TokenizationAction::TokenizeInConnectorAndRouter, + (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { + TokenizationAction::DecryptApplePayToken(payment_processing_details) + } + (false, _) => TokenizationAction::TokenizeInRouter, + }), + Some(token) => { + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection")?; + + let key = format!( + "pm_token_{}_{}_{}", + token.to_owned(), + payment_method, + connector_name + ); - let connector_token_option = redis_conn - .get_key::<Option<String>>(&key) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to fetch the token from redis")?; + let connector_token_option = redis_conn + .get_key::<Option<String>>(&key) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch the token from redis")?; - match connector_token_option { - Some(connector_token) => Ok(TokenizationAction::ConnectorToken(connector_token)), - None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) { - (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { - TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( - payment_processing_details, - ) - } - (true, _) => TokenizationAction::TokenizeInConnectorAndRouter, - (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { - TokenizationAction::DecryptApplePayToken(payment_processing_details) + match connector_token_option { + Some(connector_token) => { + Ok(TokenizationAction::ConnectorToken(connector_token)) } - (false, _) => TokenizationAction::TokenizeInRouter, - }), + None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) { + ( + true, + Some(domain::ApplePayFlow::Simplified(payment_processing_details)), + ) => TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( + payment_processing_details, + ), + (true, _) => TokenizationAction::TokenizeInConnectorAndRouter, + ( + false, + Some(domain::ApplePayFlow::Simplified(payment_processing_details)), + ) => TokenizationAction::DecryptApplePayToken(payment_processing_details), + (false, _) => TokenizationAction::TokenizeInRouter, + }), + } } } } } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +pub struct PazePaymentProcessingDetails { + pub paze_private_key: Secret<String>, + pub paze_private_key_passphrase: Secret<String>, +} + #[derive(Clone, Debug)] pub enum TokenizationAction { TokenizeInRouter, @@ -2704,6 +2779,7 @@ pub enum TokenizationAction { SkipConnectorTokenization, DecryptApplePayToken(payments_api::PaymentProcessingDetails), TokenizeInConnectorAndApplepayPreDecrypt(payments_api::PaymentProcessingDetails), + DecryptPazeToken(PazePaymentProcessingDetails), } #[cfg(feature = "v2")] @@ -2791,6 +2867,7 @@ where payment_data.get_token(), is_connector_tokenization_enabled, apple_pay_flow, + *payment_method_type, ) .await?; @@ -2846,6 +2923,9 @@ where ) => TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( payment_processing_details, ), + TokenizationAction::DecryptPazeToken(paze_payment_processing_details) => { + TokenizationAction::DecryptPazeToken(paze_payment_processing_details) + } }; (payment_data.to_owned(), connector_tokenization_action) } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index ee657bc3949..1785eee87c5 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -498,6 +498,34 @@ async fn create_applepay_session_token( } } +fn create_paze_session_token( + router_data: &types::PaymentsSessionRouterData, + _header_payload: api_models::payments::HeaderPayload, +) -> RouterResult<types::PaymentsSessionRouterData> { + let paze_wallet_details = router_data + .connector_wallets_details + .clone() + .parse_value::<payment_types::PazeSessionTokenData>("PazeSessionTokenData") + .change_context(errors::ConnectorError::NoConnectorWalletDetails) + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "connector_wallets_details".to_string(), + expected_format: "paze_metadata_format".to_string(), + })?; + + Ok(types::PaymentsSessionRouterData { + response: Ok(types::PaymentsResponseData::SessionResponse { + session_token: payment_types::SessionToken::Paze(Box::new( + payment_types::PazeSessionTokenResponse { + 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, + }, + )), + }), + ..router_data.clone() + }) +} + fn create_samsung_pay_session_token( router_data: &types::PaymentsSessionRouterData, header_payload: api_models::payments::HeaderPayload, @@ -967,6 +995,7 @@ impl RouterDataSession for types::PaymentsSessionRouterData { api::GetToken::PaypalSdkMetadata => { create_paypal_sdk_session_token(state, self, connector, business_profile) } + api::GetToken::PazeMetadata => create_paze_session_token(self, header_payload), api::GetToken::Connector => { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::Session, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index fbd1170ebad..a39b151bd27 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -30,7 +30,7 @@ use futures::future::Either; use hyperswitch_domain_models::payments::payment_intent::CustomerData; use hyperswitch_domain_models::{ mandates::MandateData, - payment_method_data::GetPaymentMethodType, + payment_method_data::{GetPaymentMethodType, PazeWalletData}, payments::{ payment_attempt::PaymentAttempt, payment_intent::PaymentIntentFetchConstraints, PaymentIntent, @@ -2545,6 +2545,7 @@ pub fn validate_payment_method_type_against_payment_method( | api_enums::PaymentMethodType::KakaoPay | api_enums::PaymentMethodType::Cashapp | api_enums::PaymentMethodType::Mifinity + | api_enums::PaymentMethodType::Paze ), api_enums::PaymentMethod::BankRedirect => matches!( payment_method_type, @@ -4624,6 +4625,9 @@ async fn get_and_merge_apple_pay_metadata( samsung_pay: connector_wallets_details_optional .as_ref() .and_then(|d| d.samsung_pay.clone()), + paze: connector_wallets_details_optional + .as_ref() + .and_then(|d| d.paze.clone()), } } api_models::payments::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => { @@ -4639,6 +4643,9 @@ async fn get_and_merge_apple_pay_metadata( samsung_pay: connector_wallets_details_optional .as_ref() .and_then(|d| d.samsung_pay.clone()), + paze: connector_wallets_details_optional + .as_ref() + .and_then(|d| d.paze.clone()), } } }; @@ -4980,6 +4987,71 @@ impl ApplePayData { } } +pub fn decrypt_paze_token( + paze_wallet_data: PazeWalletData, + paze_private_key: masking::Secret<String>, + paze_private_key_passphrase: masking::Secret<String>, +) -> CustomResult<serde_json::Value, errors::PazeDecryptionError> { + let decoded_paze_private_key = BASE64_ENGINE + .decode(paze_private_key.expose().as_bytes()) + .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?; + let decrypted_private_key = openssl::rsa::Rsa::private_key_from_pem_passphrase( + decoded_paze_private_key.as_slice(), + paze_private_key_passphrase.expose().as_bytes(), + ) + .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?; + let decrypted_private_key_pem = String::from_utf8( + decrypted_private_key + .private_key_to_pem() + .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?, + ) + .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?; + let decrypter = jwe::RSA_OAEP_256 + .decrypter_from_pem(decrypted_private_key_pem) + .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?; + + let paze_complete_response: Vec<&str> = paze_wallet_data + .complete_response + .peek() + .split('.') + .collect(); + let encrypted_jwe_key = paze_complete_response + .get(1) + .ok_or(errors::PazeDecryptionError::DecryptionFailed)? + .to_string(); + let decoded_jwe_key = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(encrypted_jwe_key) + .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?; + let jws_body: JwsBody = serde_json::from_slice(&decoded_jwe_key) + .change_context(errors::PazeDecryptionError::DecryptionFailed)?; + + let (deserialized_payload, _deserialized_header) = + jwe::deserialize_compact(jws_body.secured_payload.peek(), &decrypter) + .change_context(errors::PazeDecryptionError::DecryptionFailed)?; + let encoded_secured_payload_element = String::from_utf8(deserialized_payload) + .change_context(errors::PazeDecryptionError::DecryptionFailed)? + .split('.') + .collect::<Vec<&str>>() + .get(1) + .ok_or(errors::PazeDecryptionError::DecryptionFailed)? + .to_string(); + let decoded_secured_payload_element = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(encoded_secured_payload_element) + .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?; + let parsed_decrypted: serde_json::Value = + serde_json::from_slice(&decoded_secured_payload_element) + .change_context(errors::PazeDecryptionError::DecryptionFailed)?; + Ok(parsed_decrypted) +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct JwsBody { + pub payload_id: String, + pub session_id: String, + pub secured_payload: masking::Secret<String>, +} + pub fn get_key_params_for_surcharge_details( payment_method_data: &domain::PaymentMethodData, ) -> Option<( diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index cc8b839cc80..2e37d26cdec 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -492,6 +492,7 @@ impl From<api_models::enums::PaymentMethodType> for api::GetToken { api_models::enums::PaymentMethodType::ApplePay => Self::ApplePayMetadata, api_models::enums::PaymentMethodType::SamsungPay => Self::SamsungPayMetadata, api_models::enums::PaymentMethodType::Paypal => Self::PaypalSdkMetadata, + api_models::enums::PaymentMethodType::Paze => Self::PazeMetadata, _ => Self::Connector, } } diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 6815d2dfc4f..ee75536e7c9 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -133,6 +133,11 @@ where message: "Apple Pay Decrypt token is not supported".to_string(), })? } + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(errors::ApiErrorResponse::NotSupported { + message: "Paze Decrypt token is not supported".to_string(), + })? + } }; Some((connector_name, token)) } else { diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index c2ed06d9bad..e115558995d 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -177,6 +177,7 @@ pub enum GetToken { SamsungPayMetadata, ApplePayMetadata, PaypalSdkMetadata, + PazeMetadata, Connector, } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index a75ef879daf..49d8d50442e 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -476,6 +476,7 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { | api_enums::PaymentMethodType::Dana | api_enums::PaymentMethodType::MbWay | api_enums::PaymentMethodType::MobilePay + | api_enums::PaymentMethodType::Paze | api_enums::PaymentMethodType::SamsungPay | api_enums::PaymentMethodType::Twint | api_enums::PaymentMethodType::Vipps
feat
Integrate PAZE Wallet (#6030)
a3ad0d92d71f654b3843bff550322f665d26223f
2024-08-05 05:48:29
github-actions
chore(version): 2024.08.05.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b9b3ca974a..34af7055950 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,25 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.08.05.0 + +### Bug Fixes + +- **pm_auth:** Added mca status check in pml ([#5421](https://github.com/juspay/hyperswitch/pull/5421)) ([`e9bd345`](https://github.com/juspay/hyperswitch/commit/e9bd345464f28133aeaab638c33b77f31dd1fcb5)) +- **router:** [Iatapay] make error status and error message optional ([#5382](https://github.com/juspay/hyperswitch/pull/5382)) ([`37e34e3`](https://github.com/juspay/hyperswitch/commit/37e34e3bfde9281b3a69b0769c901a887dcf400f)) + +### Refactors + +- **payment_methods:** List the Payment Methods for Merchant , based on the connector type ([#4909](https://github.com/juspay/hyperswitch/pull/4909)) ([`f3677f2`](https://github.com/juspay/hyperswitch/commit/f3677f268ca18879bc8a9e4c7ab8c96011eb56c3)) + +### Miscellaneous Tasks + +- **postman:** Update Postman collection files ([`1737d74`](https://github.com/juspay/hyperswitch/commit/1737d74183a77910ea764c8cf2cdb148ba77ab74)) + +**Full Changelog:** [`2024.08.02.0...2024.08.05.0`](https://github.com/juspay/hyperswitch/compare/2024.08.02.0...2024.08.05.0) + +- - - + ## 2024.08.02.0 ### Features
chore
2024.08.05.0
2d11bf5b3ac94b207978ef7a67d3ab70bd77a139
2023-06-30 19:54:35
Arvind Patel
feat(payment_method): [upi] add new payment method and use in iatapay (#1528)
false
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 09eba6e810b..60c45f22e87 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -447,6 +447,7 @@ pub enum PaymentMethodType { Sofort, Swish, Trustly, + UpiCollect, Walley, WeChatPay, } @@ -478,6 +479,7 @@ pub enum PaymentMethod { Crypto, BankDebit, Reward, + Upi, } #[derive( diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 12796c982f4..bbdbe3c76f8 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -590,6 +590,7 @@ pub enum PaymentMethodData { Crypto(CryptoData), MandatePayment, Reward(RewardData), + Upi(UpiData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] @@ -609,6 +610,7 @@ pub enum AdditionalPaymentData { BankDebit {}, MandatePayment {}, Reward {}, + Upi {}, } impl From<&PaymentMethodData> for AdditionalPaymentData { @@ -637,6 +639,7 @@ impl From<&PaymentMethodData> for AdditionalPaymentData { PaymentMethodData::BankDebit(_) => Self::BankDebit {}, PaymentMethodData::MandatePayment => Self::MandatePayment {}, PaymentMethodData::Reward(_) => Self::Reward {}, + PaymentMethodData::Upi(_) => Self::Upi {}, } } } @@ -775,6 +778,13 @@ pub struct CryptoData { pub pay_currency: Option<String>, } +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub struct UpiData { + #[schema(value_type = Option<String>, example = "successtest@iata")] + pub vpa_id: Option<Secret<String>>, +} + #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing @@ -976,6 +986,7 @@ pub enum PaymentMethodDataResponse { BankDebit(BankDebitData), MandatePayment, Reward(RewardData), + Upi(UpiData), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] @@ -1606,6 +1617,7 @@ impl From<PaymentMethodData> for PaymentMethodDataResponse { PaymentMethodData::BankDebit(bank_debit_data) => Self::BankDebit(bank_debit_data), PaymentMethodData::MandatePayment => Self::MandatePayment, PaymentMethodData::Reward(reward_data) => Self::Reward(reward_data), + PaymentMethodData::Upi(upi_data) => Self::Upi(upi_data), } } } diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 2666b5c7b37..c88fc2b83a4 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -370,7 +370,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { api::PaymentMethodData::Crypto(_) | api::PaymentMethodData::BankDebit(_) | api::PaymentMethodData::BankTransfer(_) - | api::PaymentMethodData::Reward(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::Reward(_) + | api::PaymentMethodData::Upi(_) => Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.payment_method), connector: "Aci", payment_experience: api_models::enums::PaymentExperience::RedirectToUrl.to_string(), diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index d0b46998b3f..9655c5ae430 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -140,7 +140,8 @@ fn get_pm_and_subsequent_auth_detail( | api::PaymentMethodData::BankDebit(_) | api::PaymentMethodData::MandatePayment | api::PaymentMethodData::BankTransfer(_) - | api::PaymentMethodData::Reward(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::Reward(_) + | api::PaymentMethodData::Upi(_) => Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.request.payment_method_data), connector: "AuthorizeDotNet", payment_experience: api_models::enums::PaymentExperience::RedirectToUrl.to_string(), diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index 7b9ef7bfcba..2a9361e5797 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -1,5 +1,6 @@ use std::collections::HashMap; +use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ @@ -58,6 +59,12 @@ pub struct RedirectUrls { failure_url: String, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PayerInfo { + token_id: Secret<String>, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct IatapayPaymentsRequest { @@ -68,6 +75,7 @@ pub struct IatapayPaymentsRequest { locale: String, redirect_urls: RedirectUrls, notification_url: String, + payer_info: Option<PayerInfo>, } impl TryFrom<&types::PaymentsAuthorizeRouterData> for IatapayPaymentsRequest { @@ -75,6 +83,12 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for IatapayPaymentsRequest { fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let country = item.get_billing_country()?.to_string(); let return_url = item.get_return_url()?; + let payer_info = match item.request.payment_method_data.clone() { + api::PaymentMethodData::Upi(upi_data) => { + upi_data.vpa_id.map(|id| PayerInfo { token_id: id }) + } + _ => None, + }; let payload = Self { merchant_id: IatapayAuthType::try_from(&item.connector_auth_type)?.merchant_id, amount: item.request.amount, @@ -82,6 +96,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for IatapayPaymentsRequest { country: country.clone(), locale: format!("en-{}", country), redirect_urls: get_redirect_url(return_url), + payer_info, notification_url: item.request.get_webhook_url()?, }; Ok(payload) diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 9c734d2e0bd..1ce506fbeca 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -2574,7 +2574,8 @@ impl } api::PaymentMethodData::MandatePayment | api::PaymentMethodData::Crypto(_) - | api::PaymentMethodData::Reward(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::Reward(_) + | api::PaymentMethodData::Upi(_) => Err(errors::ConnectorError::NotSupported { message: format!("{pm_type:?}"), connector: "Stripe", payment_experience: api_models::enums::PaymentExperience::RedirectToUrl.to_string(), diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 1a52a681cdd..9752aa44fa4 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1271,6 +1271,7 @@ pub async fn make_pm_data<'a, F: Clone, R>( (pm @ Some(api::PaymentMethodData::BankRedirect(_)), _) => Ok(pm.to_owned()), (pm @ Some(api::PaymentMethodData::Crypto(_)), _) => Ok(pm.to_owned()), (pm @ Some(api::PaymentMethodData::BankDebit(_)), _) => Ok(pm.to_owned()), + (pm @ Some(api::PaymentMethodData::Upi(_)), _) => Ok(pm.to_owned()), (pm @ Some(api::PaymentMethodData::Reward(_)), _) => Ok(pm.to_owned()), (pm_opt @ Some(pm @ api::PaymentMethodData::BankTransfer(_)), _) => { let token = vault::Vault::store_payment_method_data_in_locker( diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index d6024964158..e4a4b43986b 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -170,6 +170,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::BankDebitBilling, api_models::payments::CryptoData, api_models::payments::RewardData, + api_models::payments::UpiData, api_models::payments::Address, api_models::payments::BankRedirectData, api_models::payments::BankRedirectBilling, diff --git a/crates/storage_models/src/enums.rs b/crates/storage_models/src/enums.rs index 4578c72959e..cc6acc4d957 100644 --- a/crates/storage_models/src/enums.rs +++ b/crates/storage_models/src/enums.rs @@ -465,6 +465,7 @@ pub enum PaymentMethod { Crypto, BankDebit, Reward, + Upi, } #[derive( @@ -706,6 +707,7 @@ pub enum PaymentMethodType { Sofort, Swish, Trustly, + UpiCollect, Walley, WeChatPay, } diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index cd1cf109ba0..1aa078e9346 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -2896,14 +2896,15 @@ "bitpay", "bluesnap", "braintree", + "cashtocode", "checkout", "coinbase", + "cryptopay", "cybersource", "iatapay", "phonypay", "fauxpay", "pretendpay", - "opennode", "bambora", "dlocal", "fiserv", @@ -2916,6 +2917,7 @@ "nmi", "noon", "nuvei", + "opennode", "paypal", "payu", "rapyd", @@ -3273,7 +3275,13 @@ } }, "CryptoData": { - "type": "object" + "type": "object", + "properties": { + "pay_currency": { + "type": "string", + "nullable": true + } + } }, "Currency": { "type": "string", @@ -5822,7 +5830,9 @@ "bank_redirect", "bank_transfer", "crypto", - "bank_debit" + "bank_debit", + "reward", + "upi" ] }, "PaymentMethodCreate": { @@ -5967,6 +5977,28 @@ "enum": [ "mandate_payment" ] + }, + { + "type": "object", + "required": [ + "reward" + ], + "properties": { + "reward": { + "$ref": "#/components/schemas/RewardData" + } + } + }, + { + "type": "object", + "required": [ + "upi" + ], + "properties": { + "upi": { + "$ref": "#/components/schemas/UpiData" + } + } } ] }, @@ -6153,10 +6185,12 @@ "bancontact_card", "becs", "blik", + "classic", "credit", "crypto_currency", "debit", "eps", + "evoucher", "giropay", "google_pay", "ideal", @@ -6176,6 +6210,7 @@ "sofort", "swish", "trustly", + "upi_collect", "walley", "we_chat_pay" ] @@ -6307,73 +6342,38 @@ "PaymentsCreateRequest": { "type": "object", "required": [ - "currency", + "amount", "manual_retry", - "amount" + "currency" ], "properties": { - "name": { - "type": "string", - "description": "description: The customer's name\nThis field will be deprecated soon, use the customer object instead", - "example": "John Test", - "nullable": true, - "maxLength": 255 + "browser_info": { + "type": "object", + "description": "Additional details required by 3DS 2.0", + "nullable": true }, - "payment_experience": { + "billing": { "allOf": [ { - "$ref": "#/components/schemas/PaymentExperience" + "$ref": "#/components/schemas/Address" } ], "nullable": true }, - "business_label": { - "type": "string", - "description": "Business label of the merchant for this payment", - "example": "food", - "nullable": true - }, - "phone": { - "type": "string", - "description": "The customer's phone number\nThis field will be deprecated soon, use the customer object instead", - "example": "3141592653", - "nullable": true, - "maxLength": 255 - }, - "statement_descriptor_suffix": { - "type": "string", - "description": "Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.", - "example": "Payment for shoes purchase", - "nullable": true, - "maxLength": 255 - }, - "statement_descriptor_name": { - "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": 255 - }, - "currency": { + "merchant_connector_details": { "allOf": [ { - "$ref": "#/components/schemas/Currency" + "$ref": "#/components/schemas/MerchantConnectorDetailsWrap" } ], "nullable": true }, - "card_cvc": { - "type": "string", - "description": "This is used when payment is to be confirmed and the card is not saved", - "nullable": true - }, - "order_details": { - "type": "array", - "items": { - "$ref": "#/components/schemas/OrderDetailsWithAmount" - }, - "description": "Information about the product , quantity and amount for connectors. (e.g. Klarna)", - "example": "[{\n \"product_name\": \"gillete creme\",\n \"quantity\": 15,\n \"amount\" : 900\n }]", + "capture_method": { + "allOf": [ + { + "$ref": "#/components/schemas/CaptureMethod" + } + ], "nullable": true }, "shipping": { @@ -6384,21 +6384,48 @@ ], "nullable": true }, - "business_sub_label": { + "routing": { + "allOf": [ + { + "$ref": "#/components/schemas/RoutingAlgorithm" + } + ], + "nullable": true + }, + "off_session": { + "type": "boolean", + "description": "Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with `confirm: true`.", + "example": true, + "nullable": true + }, + "return_url": { "type": "string", - "description": "Business sub label for the payment", + "description": "The URL to redirect after the completion of the operation", + "example": "https://hyperswitch.io", "nullable": true }, - "capture_on": { + "statement_descriptor_name": { "type": "string", - "format": "date-time", - "description": "A timestamp (ISO 8601 code) that determines when the payment should be captured.\nProviding this field will automatically set `capture` to true", - "example": "2022-09-10T10:11:12Z", + "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": 255 + }, + "setup_future_usage": { + "allOf": [ + { + "$ref": "#/components/schemas/FutureUsage" + } + ], "nullable": true }, - "manual_retry": { - "type": "boolean", - "description": "If enabled payment can be retried from the client side until the payment is successful or payment expires or the attempts(configured by the merchant) for payment are exhausted." + "amount": { + "type": "integer", + "format": "int64", + "description": "The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,", + "example": 6540, + "nullable": true, + "minimum": 0.0 }, "merchant_id": { "type": "string", @@ -6407,46 +6434,64 @@ "nullable": true, "maxLength": 255 }, - "capture_method": { + "amount_to_capture": { + "type": "integer", + "format": "int64", + "description": "The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\nIf not provided, the default amount_to_capture will be the payment amount.", + "example": 6540, + "nullable": true + }, + "customer": { "allOf": [ { - "$ref": "#/components/schemas/CaptureMethod" + "$ref": "#/components/schemas/CustomerDetails" } ], "nullable": true }, - "mandate_data": { + "payment_id": { + "type": "string", + "description": "Unique identifier for the payment. This ensures idempotency for multiple payments\nthat have been done by a single merchant. This field is auto generated and is returned in the API response.", + "example": "pay_mbabizu24mvu3mela5njyhpit4", + "nullable": true, + "maxLength": 30, + "minLength": 30 + }, + "confirm": { + "type": "boolean", + "description": "Whether to confirm the payment (if applicable)", + "default": false, + "example": true, + "nullable": true + }, + "authentication_type": { "allOf": [ { - "$ref": "#/components/schemas/MandateData" + "$ref": "#/components/schemas/AuthenticationType" } ], "nullable": true }, - "udf": { - "type": "object", - "description": "Any user defined fields can be passed here.", - "nullable": true - }, - "amount_to_capture": { - "type": "integer", - "format": "int64", - "description": "The Amount to be captured/ debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,\nIf not provided, the default amount_to_capture will be the payment amount.", - "example": 6540, + "metadata": { + "allOf": [ + { + "$ref": "#/components/schemas/Metadata" + } + ], "nullable": true }, - "payment_method": { + "mandate_data": { "allOf": [ { - "$ref": "#/components/schemas/PaymentMethod" + "$ref": "#/components/schemas/MandateData" } ], "nullable": true }, - "customer": { + "payment_experience": { "allOf": [ { - "$ref": "#/components/schemas/CustomerDetails" + "$ref": "#/components/schemas/PaymentExperience" } ], "nullable": true @@ -6457,67 +6502,38 @@ "example": "187282ab-40ef-47a9-9206-5099ba31e432", "nullable": true }, - "connector": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Connector" - }, - "description": "This allows the merchant to manually select a connector with which the payment can go through", - "example": [ - "stripe", - "adyen" - ], - "nullable": true - }, - "client_secret": { - "type": "string", - "description": "It's a token used for client side verification.", - "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo", - "nullable": true - }, - "phone_country_code": { + "phone": { "type": "string", - "description": "The country code for the customer phone number\nThis field will be deprecated soon, use the customer object instead", - "example": "+1", + "description": "The customer's phone number\nThis field will be deprecated soon, use the customer object instead", + "example": "3141592653", "nullable": true, "maxLength": 255 }, - "payment_method_type": { - "allOf": [ - { - "$ref": "#/components/schemas/PaymentMethodType" - } - ], - "nullable": true - }, - "off_session": { - "type": "boolean", - "description": "Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with `confirm: true`.", - "example": true, - "nullable": true - }, - "merchant_connector_details": { + "business_country": { "allOf": [ { - "$ref": "#/components/schemas/MerchantConnectorDetailsWrap" + "$ref": "#/components/schemas/CountryAlpha2" } ], "nullable": true }, - "email": { + "phone_country_code": { "type": "string", - "description": "The customer's email address\nThis field will be deprecated soon, use the customer object instead", - "example": "[email protected]", + "description": "The country code for the customer phone number\nThis field will be deprecated soon, use the customer object instead", + "example": "+1", "nullable": true, "maxLength": 255 }, - "payment_id": { + "client_secret": { "type": "string", - "description": "Unique identifier for the payment. This ensures idempotency for multiple payments\nthat have been done by a single merchant. This field is auto generated and is returned in the API response.", - "example": "pay_mbabizu24mvu3mela5njyhpit4", - "nullable": true, - "maxLength": 30, - "minLength": 30 + "description": "It's a token used for client side verification.", + "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo", + "nullable": true + }, + "udf": { + "type": "object", + "description": "Any user defined fields can be passed here.", + "nullable": true }, "customer_id": { "type": "string", @@ -6526,20 +6542,24 @@ "nullable": true, "maxLength": 255 }, - "routing": { - "allOf": [ - { - "$ref": "#/components/schemas/RoutingAlgorithm" - } - ], + "card_cvc": { + "type": "string", + "description": "This is used when payment is to be confirmed and the card is not saved", "nullable": true }, - "setup_future_usage": { - "allOf": [ - { - "$ref": "#/components/schemas/FutureUsage" - } - ], + "name": { + "type": "string", + "description": "description: The customer's name\nThis field will be deprecated soon, use the customer object instead", + "example": "John Test", + "nullable": true, + "maxLength": 255 + }, + "allowed_payment_method_types": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentMethodType" + }, + "description": "Allowed Payment Method Types for a given PaymentIntent", "nullable": true }, "payment_method_data": { @@ -6550,84 +6570,99 @@ ], "nullable": true }, - "metadata": { - "allOf": [ - { - "$ref": "#/components/schemas/Metadata" - } - ], - "nullable": true + "manual_retry": { + "type": "boolean", + "description": "If enabled payment can be retried from the client side until the payment is successful or payment expires or the attempts(configured by the merchant) for payment are exhausted." }, - "amount": { - "type": "integer", - "format": "int64", - "description": "The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,", - "example": 6540, - "nullable": true, - "minimum": 0.0 + "order_details": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OrderDetailsWithAmount" + }, + "description": "Information about the product , quantity and amount for connectors. (e.g. Klarna)", + "example": "[{\n \"product_name\": \"gillete creme\",\n \"quantity\": 15,\n \"amount\" : 900\n }]", + "nullable": true }, - "allowed_payment_method_types": { + "connector": { "type": "array", "items": { - "$ref": "#/components/schemas/PaymentMethodType" + "$ref": "#/components/schemas/Connector" }, - "description": "Allowed Payment Method Types for a given PaymentIntent", + "description": "This allows the merchant to manually select a connector with which the payment can go through", + "example": [ + "stripe", + "adyen" + ], "nullable": true }, - "description": { + "capture_on": { "type": "string", - "description": "A description of the payment", - "example": "It's my first payment request", + "format": "date-time", + "description": "A timestamp (ISO 8601 code) that determines when the payment should be captured.\nProviding this field will automatically set `capture` to true", + "example": "2022-09-10T10:11:12Z", "nullable": true }, - "browser_info": { - "type": "object", - "description": "Additional details required by 3DS 2.0", - "nullable": true + "mandate_id": { + "type": "string", + "description": "A unique identifier to link the payment to a mandate, can be use instead of payment_method_data", + "example": "mandate_iwer89rnjef349dni3", + "nullable": true, + "maxLength": 255 }, - "business_country": { + "payment_method_type": { "allOf": [ { - "$ref": "#/components/schemas/CountryAlpha2" + "$ref": "#/components/schemas/PaymentMethodType" } ], "nullable": true }, - "mandate_id": { + "business_label": { "type": "string", - "description": "A unique identifier to link the payment to a mandate, can be use instead of payment_method_data", - "example": "mandate_iwer89rnjef349dni3", + "description": "Business label of the merchant for this payment", + "example": "food", + "nullable": true + }, + "statement_descriptor_suffix": { + "type": "string", + "description": "Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.", + "example": "Payment for shoes purchase", "nullable": true, "maxLength": 255 }, - "return_url": { + "business_sub_label": { "type": "string", - "description": "The URL to redirect after the completion of the operation", - "example": "https://hyperswitch.io", + "description": "Business sub label for the payment", "nullable": true }, - "billing": { + "currency": { "allOf": [ { - "$ref": "#/components/schemas/Address" + "$ref": "#/components/schemas/Currency" } ], "nullable": true }, - "authentication_type": { + "payment_method": { "allOf": [ { - "$ref": "#/components/schemas/AuthenticationType" + "$ref": "#/components/schemas/PaymentMethod" } ], "nullable": true }, - "confirm": { - "type": "boolean", - "description": "Whether to confirm the payment (if applicable)", - "default": false, - "example": true, + "description": { + "type": "string", + "description": "A description of the payment", + "example": "It's my first payment request", "nullable": true + }, + "email": { + "type": "string", + "description": "The customer's email address\nThis field will be deprecated soon, use the customer object instead", + "example": "[email protected]", + "nullable": true, + "maxLength": 255 } } }, @@ -7274,6 +7309,12 @@ "type": "object", "description": "Any user defined fields can be passed here.", "nullable": true + }, + "connector_transaction_id": { + "type": "string", + "description": "A unique identifier for a payment provided by the connector", + "example": "993672945374576J", + "nullable": true } } }, @@ -7800,6 +7841,18 @@ } } }, + "RewardData": { + "type": "object", + "required": [ + "merchant_id" + ], + "properties": { + "merchant_id": { + "type": "string", + "description": "The merchant ID with which we have to call the connector" + } + } + }, "RoutingAlgorithm": { "type": "string", "description": "The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom'", @@ -8038,6 +8091,16 @@ } } }, + "UpiData": { + "type": "object", + "properties": { + "vpa_id": { + "type": "string", + "example": "successtest@iata", + "nullable": true + } + } + }, "WalletData": { "oneOf": [ {
feat
[upi] add new payment method and use in iatapay (#1528)
369939a37385fe85fd3430d9be0b7b0698962625
2024-10-03 12:16:28
Kartikeya Hegde
fix(payment_intent): batch encrypt and decrypt payment intent (#6164)
false
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index bd4707243ce..562e5d205c0 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1,14 +1,14 @@ use common_enums as storage_enums; use common_utils::{ consts::{PAYMENTS_LIST_MAX_LIMIT_V1, PAYMENTS_LIST_MAX_LIMIT_V2}, - crypto::Encryptable, + crypto::{self, Encryptable}, encryption::Encryption, errors::{CustomResult, ValidationError}, id_type, pii::{self, Email}, type_name, types::{ - keymanager::{self, KeyManagerState}, + keymanager::{self, KeyManagerState, ToEncryptable}, MinorUnit, }, }; @@ -17,6 +17,7 @@ use diesel_models::{ }; use error_stack::ResultExt; use masking::{Deserialize, PeekInterface, Secret}; +use rustc_hash::FxHashMap; use serde::Serialize; use time::PrimitiveDateTime; @@ -26,7 +27,7 @@ use super::PaymentIntent; use crate::{ behaviour, errors, merchant_key_store::MerchantKeyStore, - type_encryption::{crypto_operation, AsyncLift, CryptoOperation}, + type_encryption::{crypto_operation, CryptoOperation}, RemoteStorageObject, }; #[async_trait::async_trait] @@ -1568,17 +1569,25 @@ impl behaviour::Conversion for PaymentIntent { Self: Sized, { async { - let inner_decrypt = |inner| async { - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::DecryptOptional(inner), - key_manager_identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }; + 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, + customer_details: storage_model.customer_details, + }, + )), + key_manager_identifier, + key.peek(), + ) + .await + .and_then(|val| val.try_into_batchoperation())?; + + let data = EncryptedPaymentIntentAddress::from_encryptable(decrypted_data) + .change_context(common_utils::errors::CryptoError::DecodingFailed) + .attach_printable("Invalid batch operation data")?; let amount_details = super::AmountDetails { order_amount: storage_model.amount, @@ -1628,18 +1637,9 @@ impl behaviour::Conversion for PaymentIntent { storage_model.request_external_three_ds_authentication, ), frm_metadata: storage_model.frm_metadata, - customer_details: storage_model - .customer_details - .async_lift(inner_decrypt) - .await?, - billing_address: storage_model - .billing_address - .async_lift(inner_decrypt) - .await?, - shipping_address: storage_model - .shipping_address - .async_lift(inner_decrypt) - .await?, + customer_details: data.customer_details, + billing_address: data.billing, + shipping_address: data.shipping, capture_method: storage_model.capture_method, id: storage_model.id, merchant_reference_id: storage_model.merchant_reference_id, @@ -1796,17 +1796,26 @@ impl behaviour::Conversion for PaymentIntent { Self: Sized, { async { - let inner_decrypt = |inner| async { - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::DecryptOptional(inner), - key_manager_identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }; + 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, + customer_details: storage_model.customer_details, + }, + )), + key_manager_identifier, + key.peek(), + ) + .await + .and_then(|val| val.try_into_batchoperation())?; + + let data = EncryptedPaymentIntentAddress::from_encryptable(decrypted_data) + .change_context(common_utils::errors::CryptoError::DecodingFailed) + .attach_printable("Invalid batch operation data")?; + Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id, @@ -1854,19 +1863,10 @@ impl behaviour::Conversion for PaymentIntent { frm_metadata: storage_model.frm_metadata, shipping_cost: storage_model.shipping_cost, tax_details: storage_model.tax_details, - customer_details: storage_model - .customer_details - .async_lift(inner_decrypt) - .await?, - billing_details: storage_model - .billing_details - .async_lift(inner_decrypt) - .await?, + customer_details: data.customer_details, + billing_details: data.billing, merchant_order_reference_id: storage_model.merchant_order_reference_id, - shipping_details: storage_model - .shipping_details - .async_lift(inner_decrypt) - .await?, + shipping_details: data.shipping, 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, @@ -1935,3 +1935,73 @@ 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/Cargo.toml b/crates/router/Cargo.toml index 31cfae49875..5becef839d5 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -17,7 +17,7 @@ email = ["external_services/email", "scheduler/email", "olap"] # keymanager_create, keymanager_mtls, encryption_service should not be removed or added to default feature. Once this features were enabled it can't be disabled as these are breaking changes. keymanager_create = [] keymanager_mtls = ["reqwest/rustls-tls", "common_utils/keymanager_mtls"] -encryption_service = ["hyperswitch_domain_models/encryption_service", "common_utils/encryption_service"] +encryption_service = ["keymanager_create","hyperswitch_domain_models/encryption_service", "common_utils/encryption_service"] km_forward_x_request_id = ["common_utils/km_forward_x_request_id"] frm = ["api_models/frm", "hyperswitch_domain_models/frm", "hyperswitch_connectors/frm", "hyperswitch_interfaces/frm"] stripe = [] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 0803106cc28..684c1777521 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -194,7 +194,7 @@ pub async fn create_merchant_account( let master_key = db.get_master_key(); - let key_manager_state = &(&state).into(); + let key_manager_state: &KeyManagerState = &(&state).into(); let merchant_id = req.get_merchant_reference_id(); let identifier = km_types::Identifier::Merchant(merchant_id.clone()); #[cfg(feature = "keymanager_create")] @@ -203,16 +203,18 @@ pub async fn create_merchant_account( use crate::consts::BASE64_ENGINE; - keymanager::transfer_key_to_key_manager( - key_manager_state, - EncryptionTransferRequest { - identifier: identifier.clone(), - key: BASE64_ENGINE.encode(key), - }, - ) - .await - .change_context(errors::ApiErrorResponse::DuplicateMerchantAccount) - .attach_printable("Failed to insert key to KeyManager")?; + if key_manager_state.enabled { + keymanager::transfer_key_to_key_manager( + key_manager_state, + EncryptionTransferRequest { + identifier: identifier.clone(), + key: BASE64_ENGINE.encode(key), + }, + ) + .await + .change_context(errors::ApiErrorResponse::DuplicateMerchantAccount) + .attach_printable("Failed to insert key to KeyManager")?; + } } let key_store = domain::MerchantKeyStore { diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 51f2de51f26..0921e38317a 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -7,13 +7,20 @@ use api_models::{ use async_trait::async_trait; use common_utils::{ ext_traits::{AsyncExt, Encode, ValueExt}, - types::{keymanager::KeyManagerState, MinorUnit}, + type_name, + types::{ + keymanager::{Identifier, KeyManagerState, ToEncryptable}, + MinorUnit, + }, }; use diesel_models::ephemeral_key; use error_stack::{self, ResultExt}; use hyperswitch_domain_models::{ mandates::{MandateData, MandateDetails}, - payments::{payment_attempt::PaymentAttempt, payment_intent::CustomerData}, + payments::{ + payment_attempt::PaymentAttempt, + payment_intent::{CustomerData, PaymentAddressFromRequest}, + }, }; use masking::{ExposeInterface, PeekInterface, Secret}; use router_derive::PaymentOperation; @@ -1280,28 +1287,6 @@ impl PaymentCreate { .change_context(errors::ApiErrorResponse::InternalServerError)? .map(Secret::new); - // Derivation of directly supplied Billing Address data in our Payment Create Request - // Encrypting our Billing Address Details to be stored in Payment Intent - let billing_details = request - .billing - .clone() - .async_map(|billing_details| create_encrypted_data(state, key_store, billing_details)) - .await - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt billing details")?; - - // Derivation of directly supplied Shipping Address data in our Payment Create Request - // Encrypting our Shipping Address Details to be stored in Payment Intent - let shipping_details = request - .shipping - .clone() - .async_map(|shipping_details| create_encrypted_data(state, key_store, shipping_details)) - .await - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt shipping details")?; - // Derivation of directly supplied Customer data in our Payment Create Request let raw_customer_details = if request.customer_id.is_none() && (request.name.is_some() @@ -1325,13 +1310,53 @@ impl PaymentCreate { }, ); - // Encrypting our Customer Details to be stored in Payment Intent - let customer_details = raw_customer_details - .async_map(|customer_details| create_encrypted_data(state, key_store, customer_details)) - .await + let key = key_store.key.get_inner().peek(); + let identifier = Identifier::Merchant(key_store.merchant_id.clone()); + let key_manager_state: KeyManagerState = state.into(); + + let shipping_details_encoded = request + .shipping + .clone() + .map(|shipping| Encode::encode_to_value(&shipping).map(Secret::new)) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt customer details")?; + .attach_printable("Unable to encode billing details to serde_json::Value")?; + + let billing_details_encoded = request + .billing + .clone() + .map(|billing| Encode::encode_to_value(&billing).map(Secret::new)) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encode billing details to serde_json::Value")?; + + let customer_details_encoded = raw_customer_details + .map(|customer| Encode::encode_to_value(&customer).map(Secret::new)) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encode shipping details to serde_json::Value")?; + + let encrypted_data = domain::types::crypto_operation( + &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, + }), + ), + identifier.clone(), + key, + ) + .await + .and_then(|val| val.try_into_batchoperation()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt data")?; + + let encrypted_data = PaymentAddressFromRequest::from_encryptable(encrypted_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt the payment intent data")?; let skip_external_tax_calculation = request.skip_external_tax_calculation; @@ -1382,10 +1407,10 @@ impl PaymentCreate { .request_external_three_ds_authentication, charges, frm_metadata: request.frm_metadata.clone(), - billing_details, - customer_details, + billing_details: encrypted_data.billing, + customer_details: encrypted_data.customer_details, merchant_order_reference_id: request.merchant_order_reference_id.clone(), - shipping_details, + shipping_details: encrypted_data.shipping, is_payment_processor_token_flow, organization_id: merchant_account.organization_id.clone(), shipping_cost: request.shipping_cost,
fix
batch encrypt and decrypt payment intent (#6164)
9852dac1fe5b223edaa7357c273dcc791c133928
2023-12-21 12:57:07
github-actions
chore(version): v1.103.1
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 6784fd3fdeb..8010277b565 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,19 @@ All notable changes to HyperSwitch will be documented here. - - - +## 1.103.1 (2023-12-21) + +### Bug Fixes + +- **connector:** + - Remove set_body method for connectors implementing default get_request_body ([#3182](https://github.com/juspay/hyperswitch/pull/3182)) ([`a5e141b`](https://github.com/juspay/hyperswitch/commit/a5e141b542622e7065f0e0070a3cddacde78fd8a)) + - [Paypal] remove shipping address as mandatory field for paypal wallet ([#3181](https://github.com/juspay/hyperswitch/pull/3181)) ([`680ed60`](https://github.com/juspay/hyperswitch/commit/680ed603c5113ec29fbd13c4c633e18ad4ad10ee)) + +**Full Changelog:** [`v1.103.0...v1.103.1`](https://github.com/juspay/hyperswitch/compare/v1.103.0...v1.103.1) + +- - - + + ## 1.103.0 (2023-12-20) ### Features
chore
v1.103.1
7e90031c68c7b93db996ee03e11c56b56a87402b
2024-10-15 23:38:44
Swangi Kumari
feat(router): implement post_update_tracker for SessionUpdate Flow and add support for session_update_flow for Paypal (#6299)
false
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 9ecfe9cf644..e16a206b118 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -14572,6 +14572,11 @@ }, "payment_method_type": { "$ref": "#/components/schemas/PaymentMethodType" + }, + "session_id": { + "type": "string", + "description": "Session Id", + "nullable": true } } }, diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 49fe3b6b95d..355daf66c90 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -17837,6 +17837,11 @@ }, "payment_method_type": { "$ref": "#/components/schemas/PaymentMethodType" + }, + "session_id": { + "type": "string", + "description": "Session Id", + "nullable": true } } }, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 265865b973a..674a19f3ef8 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4916,6 +4916,8 @@ pub struct PaymentsDynamicTaxCalculationRequest { /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, + /// Session Id + pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 4601a818fb3..0a87e6c19aa 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -404,25 +404,25 @@ pub enum AuthorizationStatus { Unresolved, } -// #[derive( -// Clone, -// Debug, -// Eq, -// PartialEq, -// serde::Deserialize, -// serde::Serialize, -// strum::Display, -// strum::EnumString, -// ToSchema, -// Hash, -// )] -// #[router_derive::diesel_enum(storage_type = "text")] -// #[serde(rename_all = "snake_case")] -// #[strum(serialize_all = "snake_case")] -// pub enum SessionUpdateStatus { -// Success, -// Failure, -// } +#[derive( + Clone, + Debug, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + ToSchema, + Hash, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum SessionUpdateStatus { + Success, + Failure, +} #[derive( Clone, diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index f03ab75af19..d599a2caa74 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -841,6 +841,9 @@ pub struct PaymentsTaxCalculationData { pub struct SdkPaymentsSessionUpdateData { pub order_tax_amount: MinorUnit, pub net_amount: MinorUnit, + pub amount: MinorUnit, + pub currency: storage_enums::Currency, + pub session_id: Option<String>, } #[derive(Debug, Clone)] diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs index 79a78efb538..eca56b8c866 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types.rs @@ -68,9 +68,9 @@ pub enum PaymentsResponseData { PostProcessingResponse { session_token: Option<api_models::payments::OpenBankingSessionToken>, }, - // SessionUpdateResponse { - // status: common_enums::SessionUpdateStatus, - // }, + SessionUpdateResponse { + status: common_enums::SessionUpdateStatus, + }, } #[derive(Debug, Clone)] diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs index 81e2086f972..41a1b1ba83c 100644 --- a/crates/hyperswitch_interfaces/src/types.rs +++ b/crates/hyperswitch_interfaces/src/types.rs @@ -9,8 +9,8 @@ use hyperswitch_domain_models::{ payments::{ Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync, - PaymentMethodToken, PostProcessing, PostSessionTokens, PreProcessing, Session, - SetupMandate, Void, + PaymentMethodToken, PostProcessing, PostSessionTokens, PreProcessing, SdkSessionUpdate, + Session, SetupMandate, Void, }, refunds::{Execute, RSync}, webhooks::VerifyWebhookSource, @@ -22,8 +22,8 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, RefundsData, - RetrieveFileRequestData, SetupMandateRequestData, SubmitEvidenceRequestData, - UploadFileRequestData, VerifyWebhookSourceRequestData, + RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, + SubmitEvidenceRequestData, UploadFileRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ AcceptDisputeResponse, DefendDisputeResponse, MandateRevokeResponseData, @@ -65,6 +65,9 @@ pub type PaymentsPostSessionTokensType = dyn ConnectorIntegration< PaymentsPostSessionTokensData, PaymentsResponseData, >; +/// Type alias for `ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>` +pub type SdkSessionUpdateType = + dyn ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>` pub type SetupMandateType = dyn ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>; diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs index 254278944e7..274aab8e504 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -10,6 +10,7 @@ use common_utils::{ use diesel_models::enums; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret}; +use router_env::logger; #[cfg(feature = "payouts")] use router_env::{instrument, tracing}; use transformers as paypal; @@ -74,6 +75,7 @@ impl api::RefundExecute for Paypal {} impl api::RefundSync for Paypal {} impl api::ConnectorVerifyWebhookSource for Paypal {} impl api::PaymentPostSessionTokens for Paypal {} +impl api::PaymentSessionUpdate for Paypal {} impl api::Payouts for Paypal {} #[cfg(feature = "payouts")] @@ -482,7 +484,7 @@ impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResp req.request.minor_amount, req.request.destination_currency, )?; - let connector_router_data = paypal::PaypalRouterData::try_from((amount, req))?; + let connector_router_data = paypal::PaypalRouterData::try_from((amount, None, None, req))?; let connector_req = paypal::PaypalFulfillRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -687,6 +689,7 @@ impl .url(&types::PaymentsPostSessionTokensType::get_url( self, req, connectors, )?) + .attach_default_headers() .headers(types::PaymentsPostSessionTokensType::get_headers( self, req, connectors, )?) @@ -707,7 +710,7 @@ impl req.request.amount, req.request.currency, )?; - let connector_router_data = paypal::PaypalRouterData::try_from((amount, req))?; + let connector_router_data = paypal::PaypalRouterData::try_from((amount, None, None, req))?; let connector_req = paypal::PaypalPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -740,6 +743,129 @@ impl } } +impl + ConnectorIntegration< + api::SdkSessionUpdate, + types::SdkPaymentsSessionUpdateData, + types::PaymentsResponseData, + > for Paypal +{ + fn get_headers( + &self, + req: &types::SdkSessionUpdateRouterData, + 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::SdkSessionUpdateRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let session_id = + req.request + .session_id + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "session_id", + })?; + Ok(format!( + "{}v2/checkout/orders/{}", + self.base_url(connectors), + session_id + )) + } + + fn build_request( + &self, + req: &types::SdkSessionUpdateRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Patch) + .url(&types::SdkSessionUpdateType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::SdkSessionUpdateType::get_headers( + self, req, connectors, + )?) + .set_body(types::SdkSessionUpdateType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn get_request_body( + &self, + req: &types::SdkSessionUpdateRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let order_amount = connector_utils::convert_amount( + self.amount_converter, + req.request.amount, + req.request.currency, + )?; + let amount = connector_utils::convert_amount( + self.amount_converter, + req.request.net_amount, + req.request.currency, + )?; + let order_tax_amount = connector_utils::convert_amount( + self.amount_converter, + req.request.order_tax_amount, + req.request.currency, + )?; + let connector_router_data = paypal::PaypalRouterData::try_from(( + amount, + Some(order_tax_amount), + Some(order_amount), + req, + ))?; + + let connector_req = paypal::PaypalUpdateOrderRequest::try_from(&connector_router_data)?; + // encode only for for urlencoded things. + Ok(RequestContent::Json(Box::new( + connector_req.get_inner_value(), + ))) + } + + fn handle_response( + &self, + data: &types::SdkSessionUpdateRouterData, + _event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::SdkSessionUpdateRouterData, errors::ConnectorError> { + logger::debug!("Expected zero bytes response, skipped parsing of the response"); + // https://developer.paypal.com/docs/api/orders/v2/#orders_patch + // If 204 status code, then the session was updated successfully. + let status = if res.status_code == 204 { + enums::SessionUpdateStatus::Success + } else { + enums::SessionUpdateStatus::Failure + }; + Ok(types::SdkSessionUpdateRouterData { + response: Ok(types::PaymentsResponseData::SessionUpdateResponse { status }), + ..data.clone() + }) + } + + 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<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Paypal { @@ -789,7 +915,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req.request.minor_amount, req.request.currency, )?; - let connector_router_data = paypal::PaypalRouterData::try_from((amount, req))?; + let connector_router_data = paypal::PaypalRouterData::try_from((amount, None, None, req))?; let connector_req = paypal::PaypalPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -817,6 +943,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) + .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) @@ -1304,7 +1431,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme req.request.minor_amount_to_capture, req.request.currency, )?; - let connector_router_data = paypal::PaypalRouterData::try_from((amount_to_capture, req))?; + let connector_router_data = + paypal::PaypalRouterData::try_from((amount_to_capture, None, None, req))?; let connector_req = paypal::PaypalPaymentsCaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -1471,7 +1599,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon req.request.minor_refund_amount, req.request.currency, )?; - let connector_router_data = paypal::PaypalRouterData::try_from((amount, req))?; + let connector_router_data = paypal::PaypalRouterData::try_from((amount, None, None, req))?; let connector_req = paypal::PaypalRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index eafc86343b3..30aaf5a84a8 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -28,14 +28,32 @@ use crate::{ #[derive(Debug, Serialize)] pub struct PaypalRouterData<T> { pub amount: StringMajorUnit, + pub order_tax_amount: Option<StringMajorUnit>, + pub order_amount: Option<StringMajorUnit>, pub router_data: T, } -impl<T> TryFrom<(StringMajorUnit, T)> for PaypalRouterData<T> { +impl<T> + TryFrom<( + StringMajorUnit, + Option<StringMajorUnit>, + Option<StringMajorUnit>, + T, + )> for PaypalRouterData<T> +{ type Error = error_stack::Report<errors::ConnectorError>; - fn try_from((amount, item): (StringMajorUnit, T)) -> Result<Self, Self::Error> { + fn try_from( + (amount, order_tax_amount, order_amount, item): ( + StringMajorUnit, + Option<StringMajorUnit>, + Option<StringMajorUnit>, + T, + ), + ) -> Result<Self, Self::Error> { Ok(Self { amount, + order_tax_amount, + order_amount, router_data: item, }) } @@ -55,6 +73,8 @@ pub mod auth_headers { pub const PAYPAL_AUTH_ASSERTION: &str = "PayPal-Auth-Assertion"; } +const ORDER_QUANTITY: u16 = 1; + #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum PaypalPaymentIntent { @@ -86,6 +106,7 @@ impl From<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for OrderReque currency_code: item.router_data.request.currency, value: item.amount.clone(), }, + tax_total: None, }, } } @@ -101,14 +122,46 @@ impl From<&PaypalRouterData<&types::PaymentsPostSessionTokensRouterData>> for Or currency_code: item.router_data.request.currency, value: item.amount.clone(), }, + tax_total: None, }, } } } +impl TryFrom<&PaypalRouterData<&types::SdkSessionUpdateRouterData>> for OrderRequestAmount { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &PaypalRouterData<&types::SdkSessionUpdateRouterData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + currency_code: item.router_data.request.currency, + value: item.amount.clone(), + breakdown: AmountBreakdown { + item_total: OrderAmount { + currency_code: item.router_data.request.currency, + value: item.order_amount.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "order_amount", + }, + )?, + }, + tax_total: Some(OrderAmount { + currency_code: item.router_data.request.currency, + value: item.order_tax_amount.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "order_tax_amount", + }, + )?, + }), + }, + }) + } +} + #[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq)] pub struct AmountBreakdown { item_total: OrderAmount, + tax_total: Option<OrderAmount>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] @@ -133,6 +186,7 @@ pub struct ItemDetails { name: String, quantity: u16, unit_amount: OrderAmount, + tax: Option<OrderAmount>, } impl From<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for ItemDetails { @@ -142,11 +196,12 @@ impl From<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for ItemDetail "Payment for invoice {}", item.router_data.connector_request_reference_id ), - quantity: 1, + quantity: ORDER_QUANTITY, unit_amount: OrderAmount { currency_code: item.router_data.request.currency, value: item.amount.clone(), }, + tax: None, } } } @@ -158,15 +213,47 @@ impl From<&PaypalRouterData<&types::PaymentsPostSessionTokensRouterData>> for It "Payment for invoice {}", item.router_data.connector_request_reference_id ), - quantity: 1, + quantity: ORDER_QUANTITY, unit_amount: OrderAmount { currency_code: item.router_data.request.currency, value: item.amount.clone(), }, + tax: None, } } } +impl TryFrom<&PaypalRouterData<&types::SdkSessionUpdateRouterData>> for ItemDetails { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &PaypalRouterData<&types::SdkSessionUpdateRouterData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + name: format!( + "Payment for invoice {}", + item.router_data.connector_request_reference_id + ), + quantity: ORDER_QUANTITY, + unit_amount: OrderAmount { + currency_code: item.router_data.request.currency, + value: item.order_amount.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "order_amount", + }, + )?, + }, + tax: Some(OrderAmount { + currency_code: item.router_data.request.currency, + value: item.order_tax_amount.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "order_tax_amount", + }, + )?, + }), + }) + } +} + #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct Address { address_line_1: Option<Secret<String>>, @@ -211,6 +298,40 @@ impl From<&PaypalRouterData<&types::PaymentsPostSessionTokensRouterData>> for Sh } } +#[derive(Debug, Serialize, PartialEq, Eq)] +pub struct PaypalUpdateOrderRequest(Vec<Operation>); + +impl PaypalUpdateOrderRequest { + pub fn get_inner_value(self) -> Vec<Operation> { + self.0 + } +} + +#[derive(Debug, Serialize, PartialEq, Eq)] +pub struct Operation { + pub op: PaypalOperationType, + pub path: String, + pub value: Value, +} + +#[derive(Debug, Serialize, PartialEq, Eq, Clone)] +#[serde(rename_all = "lowercase")] +pub enum PaypalOperationType { + Add, + Remove, + Replace, + Move, + Copy, + Test, +} + +#[derive(Debug, Serialize, PartialEq, Eq)] +#[serde(untagged)] +pub enum Value { + Amount(OrderRequestAmount), + Items(Vec<ItemDetails>), +} + #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct ShippingName { full_name: Option<Secret<String>>, @@ -461,6 +582,39 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsPostSessionTokensRouterData>> } } +impl TryFrom<&PaypalRouterData<&types::SdkSessionUpdateRouterData>> for PaypalUpdateOrderRequest { + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + item: &PaypalRouterData<&types::SdkSessionUpdateRouterData>, + ) -> Result<Self, Self::Error> { + let op = PaypalOperationType::Replace; + + // Create separate paths for amount and items + let reference_id = &item.router_data.connector_request_reference_id; + + let amount_path = format!("/purchase_units/@reference_id=='{}'/amount", reference_id); + let items_path = format!("/purchase_units/@reference_id=='{}'/items", reference_id); + + let amount_value = Value::Amount(OrderRequestAmount::try_from(item)?); + + let items_value = Value::Items(vec![ItemDetails::try_from(item)?]); + + Ok(Self(vec![ + Operation { + op: op.clone(), + path: amount_path, + value: amount_value, + }, + Operation { + op, + path: items_path, + value: items_value, + }, + ])) + } +} + impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( @@ -585,7 +739,6 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP | domain::WalletData::GooglePayThirdPartySdk(_) | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) - | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -594,7 +747,8 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP | domain::WalletData::WeChatPayQr(_) | domain::WalletData::CashappQr(_) | domain::WalletData::SwishQr(_) - | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | domain::WalletData::Mifinity(_) + | domain::WalletData::Paze(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), ))?, }, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index aa38b142b7c..68f318958a2 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3488,6 +3488,7 @@ where pub recurring_details: Option<RecurringDetails>, pub poll_config: Option<router_types::PollConfig>, pub tax_data: Option<TaxData>, + pub session_id: Option<String>, } #[derive(Clone, serde::Serialize, Debug)] @@ -5720,6 +5721,41 @@ pub async fn payments_manual_update( )) } +pub trait PaymentMethodChecker<F> { + fn should_update_in_post_update_tracker(&self) -> bool; + fn should_update_in_update_tracker(&self) -> bool; +} + +#[cfg(feature = "v1")] +impl<F: Clone> PaymentMethodChecker<F> for PaymentData<F> { + fn should_update_in_post_update_tracker(&self) -> bool { + let payment_method_type = self + .payment_intent + .tax_details + .as_ref() + .and_then(|tax_details| tax_details.payment_method_type.as_ref().map(|pmt| pmt.pmt)); + + matches!( + payment_method_type, + Some(storage_enums::PaymentMethodType::Paypal) + ) + } + + fn should_update_in_update_tracker(&self) -> bool { + let payment_method_type = self + .payment_intent + .tax_details + .as_ref() + .and_then(|tax_details| tax_details.payment_method_type.as_ref().map(|pmt| pmt.pmt)); + + matches!( + payment_method_type, + Some(storage_enums::PaymentMethodType::ApplePay) + | Some(storage_enums::PaymentMethodType::GooglePay) + ) + } +} + pub trait OperationSessionGetters<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt; fn get_payment_intent(&self) -> &storage::PaymentIntent; diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index c888dc74ce0..eae41c91e4e 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -3041,7 +3041,6 @@ default_imp_for_session_update!( connector::Payeezy, connector::Payme, connector::Payone, - connector::Paypal, connector::Payu, connector::Placetopay, connector::Plaid, diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index c57f4c34458..e8814c7e56e 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -192,6 +192,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> recurring_details: None, poll_config: None, tax_data: None, + session_id: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index f21ccb2c5e1..c84dcc50e6d 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -202,6 +202,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> recurring_details: None, poll_config: None, tax_data: None, + session_id: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index 710d6dd7cec..93a79e2d2e3 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -253,6 +253,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu recurring_details: None, poll_config: None, tax_data: None, + session_id: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 92e462c78bc..e705c64d6e0 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -344,6 +344,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co recurring_details, poll_config: None, tax_data: None, + session_id: None, }; let customer_details = Some(CustomerDetails { diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 81451d1aff9..5dccea54f52 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -754,6 +754,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa recurring_details, poll_config: None, tax_data: None, + session_id: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 267eeaa040b..a715aadf334 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -562,6 +562,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa recurring_details, poll_config: None, tax_data: None, + session_id: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs index 53fd32acc07..81702979ac4 100644 --- a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs +++ b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs @@ -164,6 +164,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsPostSessionToke recurring_details: None, poll_config: None, tax_data: None, + session_id: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 040eb92d459..2257ff0402c 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -188,6 +188,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for P recurring_details: None, poll_config: None, tax_data: None, + session_id: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index eedadc54132..2257c42f446 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use api_models::routing::RoutableConnectorChoice; use async_trait::async_trait; -use common_enums::AuthorizationStatus; +use common_enums::{AuthorizationStatus, SessionUpdateStatus}; use common_utils::{ ext_traits::{AsyncExt, Encode}, types::{keymanager::KeyManagerState, MinorUnit}, @@ -25,6 +25,7 @@ use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, mandate, payment_methods, + payment_methods::cards::create_encrypted_data, payments::{ helpers::{ self as payments_helpers, @@ -32,7 +33,7 @@ use crate::{ }, tokenization, types::MultipleCaptureData, - PaymentData, + PaymentData, PaymentMethodChecker, }, utils as core_utils, }, @@ -615,16 +616,16 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SdkPaymentsSessionUpd { async fn update_tracker<'b>( &'b self, - _db: &'b SessionState, + db: &'b SessionState, _payment_id: &api::PaymentIdType, - payment_data: PaymentData<F>, - _router_data: types::RouterData< + mut payment_data: PaymentData<F>, + router_data: types::RouterData< F, types::SdkPaymentsSessionUpdateData, types::PaymentsResponseData, >, - _key_store: &domain::MerchantKeyStore, - _storage_scheme: enums::MerchantStorageScheme, + key_store: &domain::MerchantKeyStore, + storage_scheme: enums::MerchantStorageScheme, _locale: &Option<String>, #[cfg(feature = "dynamic_routing")] _routable_connector: Vec<RoutableConnectorChoice>, #[cfg(feature = "dynamic_routing")] _business_profile: &domain::Profile, @@ -632,53 +633,96 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SdkPaymentsSessionUpd where F: 'b + Send, { - // let session_update_details = - // payment_data - // .payment_intent - // .tax_details - // .clone() - // .ok_or_else(|| { - // report!(errors::ApiErrorResponse::InternalServerError) - // .attach_printable("missing tax_details in payment_intent") - // })?; - - // let pmt_amount = session_update_details - // .pmt - // .clone() - // .map(|pmt| pmt.order_tax_amount) - // .ok_or(errors::ApiErrorResponse::InternalServerError) - // .attach_printable("Missing tax_details.order_tax_amount")?; - - // let total_amount = MinorUnit::from(payment_data.amount) + pmt_amount; - - // // if connector_ call successful -> payment_intent.amount update - // match router_data.response.clone() { - // Err(_) => (None, None), - // Ok(types::PaymentsResponseData::SessionUpdateResponse { status }) => { - // if status == SessionUpdateStatus::Success { - // ( - // Some( - // storage::PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { - // amount: total_amount, - // amount_capturable: total_amount, - // }, - // ), - // Some( - // storage::PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { - // amount: pmt_amount, - // }, - // ), - // ) - // } else { - // (None, None) - // } - // } - // _ => Err(errors::ApiErrorResponse::InternalServerError) - // .attach_printable("unexpected response in session_update flow")?, - // }; - - // let _shipping_address = payment_data.address.get_shipping(); - // let _amount = payment_data.amount; + let connector = payment_data + .payment_attempt + .connector + .clone() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("connector not found")?; + + // For PayPal, if we call TaxJar for tax calculation, we need to call the connector again to update the order amount so that we can confirm the updated amount and order details. Therefore, we will store the required changes in the database during the post_update_tracker call. + if payment_data.should_update_in_post_update_tracker() { + match router_data.response.clone() { + Ok(types::PaymentsResponseData::SessionUpdateResponse { status }) => { + if status == SessionUpdateStatus::Success { + let shipping_address = payment_data + .tax_data + .clone() + .map(|tax_data| tax_data.shipping_details); + + let shipping_details = shipping_address + .clone() + .async_map(|shipping_details| { + create_encrypted_data(db, key_store, shipping_details) + }) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt shipping details")?; + + let shipping_address = + payments_helpers::create_or_update_address_for_payment_by_request( + db, + shipping_address.as_ref(), + payment_data.payment_intent.shipping_address_id.as_deref(), + &payment_data.payment_intent.merchant_id, + payment_data.payment_intent.customer_id.as_ref(), + key_store, + &payment_data.payment_intent.payment_id, + storage_scheme, + ) + .await?; + + let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::SessionResponseUpdate { + tax_details: payment_data.payment_intent.tax_details.clone().ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("payment_intent.tax_details not found")?, + shipping_address_id: shipping_address.map(|address| address.address_id), + updated_by: payment_data.payment_intent.updated_by.clone(), + shipping_details, + }; + + let m_db = db.clone().store; + let payment_intent = payment_data.payment_intent.clone(); + let key_manager_state: KeyManagerState = db.into(); + + let updated_payment_intent = m_db + .update_payment_intent( + &key_manager_state, + payment_intent, + payment_intent_update, + key_store, + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + payment_data.payment_intent = updated_payment_intent; + } else { + router_data.response.map_err(|err| { + errors::ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector, + status_code: err.status_code, + reason: err.reason, + } + })?; + } + } + Err(err) => { + Err(errors::ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector, + status_code: err.status_code, + reason: err.reason, + })?; + } + _ => { + Err(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unexpected response in session_update flow")?; + } + } + } Ok(payment_data) } @@ -1546,7 +1590,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => (None, None), - // types::PaymentsResponseData::SessionUpdateResponse { .. } => (None, None), + types::PaymentsResponseData::SessionUpdateResponse { .. } => (None, None), types::PaymentsResponseData::MultipleCaptureResponse { capture_sync_response_list, } => match payment_data.multiple_capture_data { diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 2e37d26cdec..d2154f16b6a 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -211,6 +211,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> recurring_details: None, poll_config: None, tax_data: None, + session_id: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 4b44933f6dd..3042b15bfa1 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -196,6 +196,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f recurring_details: None, poll_config: None, tax_data: None, + session_id: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index d28476b67b8..47f16786ab9 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -505,6 +505,7 @@ async fn get_tracker_for_sync< recurring_details: None, poll_config: None, tax_data: None, + session_id: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index a436100dc0e..45a358ab2d7 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -479,6 +479,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa recurring_details, poll_config: None, tax_data: None, + session_id: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs index 758a17d3fa7..9d80206b9f2 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -170,6 +170,7 @@ impl<F: Send + Clone> recurring_details: None, poll_config: None, tax_data: None, + session_id: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/tax_calculation.rs b/crates/router/src/core/payments/operations/tax_calculation.rs index 246485c353a..d72d25cdd56 100644 --- a/crates/router/src/core/payments/operations/tax_calculation.rs +++ b/crates/router/src/core/payments/operations/tax_calculation.rs @@ -13,7 +13,7 @@ use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payment_methods::cards::create_encrypted_data, - payments::{self, helpers, operations, PaymentData}, + payments::{self, helpers, operations, PaymentData, PaymentMethodChecker}, utils as core_utils, }, db::errors::ConnectorErrorExt, @@ -177,6 +177,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsDynamicTaxCalcu recurring_details: None, poll_config: None, tax_data: Some(tax_data), + session_id: request.session_id.clone(), }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), @@ -382,54 +383,61 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsDynamicTaxCalculati where F: 'b + Send, { - let shipping_address = payment_data - .tax_data - .clone() - .map(|tax_data| tax_data.shipping_details); - - let shipping_details = shipping_address - .clone() - .async_map(|shipping_details| create_encrypted_data(state, key_store, shipping_details)) - .await - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt shipping details")?; + // For Google Pay and Apple Pay, we don’t need to call the connector again; we can directly confirm the payment after tax_calculation. So, we update the required fields in the database during the update_tracker call. + if payment_data.should_update_in_update_tracker() { + let shipping_address = payment_data + .tax_data + .clone() + .map(|tax_data| tax_data.shipping_details); - let shipping_address = helpers::create_or_update_address_for_payment_by_request( - state, - shipping_address.as_ref(), - payment_data.payment_intent.shipping_address_id.as_deref(), - &payment_data.payment_intent.merchant_id, - payment_data.payment_intent.customer_id.as_ref(), - key_store, - &payment_data.payment_intent.payment_id, - storage_scheme, - ) - .await?; + let shipping_details = shipping_address + .clone() + .async_map(|shipping_details| { + create_encrypted_data(state, key_store, shipping_details) + }) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt shipping details")?; + + let shipping_address = helpers::create_or_update_address_for_payment_by_request( + state, + shipping_address.as_ref(), + payment_data.payment_intent.shipping_address_id.as_deref(), + &payment_data.payment_intent.merchant_id, + payment_data.payment_intent.customer_id.as_ref(), + key_store, + &payment_data.payment_intent.payment_id, + storage_scheme, + ) + .await?; - let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::SessionResponseUpdate { + let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::SessionResponseUpdate { tax_details: payment_data.payment_intent.tax_details.clone().ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("payment_intent.tax_details not found")?, shipping_address_id: shipping_address.map(|address| address.address_id), updated_by: payment_data.payment_intent.updated_by.clone(), shipping_details, }; - let db = &*state.store; - let payment_intent = payment_data.payment_intent.clone(); + let db = &*state.store; + let payment_intent = payment_data.payment_intent.clone(); - let updated_payment_intent = db - .update_payment_intent( - &state.into(), - payment_intent, - payment_intent_update, - key_store, - storage_scheme, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + let updated_payment_intent = db + .update_payment_intent( + &state.into(), + payment_intent, + payment_intent_update, + key_store, + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_data.payment_intent = updated_payment_intent; - Ok((Box::new(self), payment_data)) + payment_data.payment_intent = updated_payment_intent; + Ok((Box::new(self), payment_data)) + } else { + Ok((Box::new(self), payment_data)) + } } } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 5d253f44dd4..72e6c6b9979 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -2110,6 +2110,9 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SdkPaymentsSessi Ok(Self { net_amount, order_tax_amount, + currency: payment_data.currency, + amount: payment_data.payment_intent.amount, + session_id: payment_data.session_id, }) } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 6f0448ef777..35857154332 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -84,8 +84,8 @@ pub use hyperswitch_interfaces::types::{ PaymentsCompleteAuthorizeType, PaymentsInitType, PaymentsPostProcessingType, PaymentsPostSessionTokensType, PaymentsPreAuthorizeType, PaymentsPreProcessingType, PaymentsSessionType, PaymentsSyncType, PaymentsVoidType, RefreshTokenType, RefundExecuteType, - RefundSyncType, Response, RetrieveFileType, SetupMandateType, SubmitEvidenceType, - TokenizationType, UploadFileType, VerifyWebhookSourceType, + RefundSyncType, Response, RetrieveFileType, SdkSessionUpdateType, SetupMandateType, + SubmitEvidenceType, TokenizationType, UploadFileType, VerifyWebhookSourceType, }; #[cfg(feature = "payouts")] pub use hyperswitch_interfaces::types::{ @@ -168,6 +168,8 @@ pub type PaymentsSessionResponseRouterData<R> = ResponseRouterData<Session, R, PaymentsSessionData, PaymentsResponseData>; pub type PaymentsInitResponseRouterData<R> = ResponseRouterData<InitPayment, R, PaymentsAuthorizeData, PaymentsResponseData>; +pub type SdkSessionUpdateResponseRouterData<R> = + ResponseRouterData<SdkSessionUpdate, R, SdkPaymentsSessionUpdateData, PaymentsResponseData>; pub type PaymentsCaptureResponseRouterData<R> = ResponseRouterData<Capture, R, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsPreprocessingResponseRouterData<R> = diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index c68032369a1..5acfd67c547 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -567,7 +567,7 @@ pub trait ConnectorActions: Connector { Ok(types::PaymentsResponseData::MultipleCaptureResponse { .. }) => None, Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse { .. }) => None, Ok(types::PaymentsResponseData::PostProcessingResponse { .. }) => None, - // Ok(types::PaymentsResponseData::SessionUpdateResponse { .. }) => None, + Ok(types::PaymentsResponseData::SessionUpdateResponse { .. }) => None, Err(_) => None, } } @@ -1079,7 +1079,7 @@ pub fn get_connector_transaction_id( Ok(types::PaymentsResponseData::MultipleCaptureResponse { .. }) => None, Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse { .. }) => None, Ok(types::PaymentsResponseData::PostProcessingResponse { .. }) => None, - // Ok(types::PaymentsResponseData::SessionUpdateResponse { .. }) => None, + Ok(types::PaymentsResponseData::SessionUpdateResponse { .. }) => None, Err(_) => None, } }
feat
implement post_update_tracker for SessionUpdate Flow and add support for session_update_flow for Paypal (#6299)
73da641b58bbfc1b0bd4bf8872b7b316a135b5c7
2023-09-11 13:09:04
Prajjwal Kumar
feat(router): saving verified domains to business_profile table (#2109)
false
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index e0be641fe9a..d0b27e53f41 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -1012,6 +1012,9 @@ pub struct BusinessProfileCreate { deserialize_with = "payout_routing_algorithm::deserialize_option" )] pub payout_routing_algorithm: Option<serde_json::Value>, + + /// Verified applepay domains for a particular profile + pub applepay_verified_domains: Option<Vec<String>>, } #[derive(Clone, Debug, ToSchema, Serialize)] @@ -1073,6 +1076,9 @@ pub struct BusinessProfileResponse { deserialize_with = "payout_routing_algorithm::deserialize_option" )] pub payout_routing_algorithm: Option<serde_json::Value>, + + /// Verified applepay domains for a particular profile + pub applepay_verified_domains: Option<Vec<String>>, } #[derive(Clone, Debug, Deserialize, ToSchema)] @@ -1127,4 +1133,7 @@ pub struct BusinessProfileUpdate { deserialize_with = "payout_routing_algorithm::deserialize_option" )] pub payout_routing_algorithm: Option<serde_json::Value>, + + /// Verified applepay domains for a particular profile + pub applepay_verified_domains: Option<Vec<String>>, } diff --git a/crates/api_models/src/verifications.rs b/crates/api_models/src/verifications.rs index fc5009ce4fe..d7d2b16c711 100644 --- a/crates/api_models/src/verifications.rs +++ b/crates/api_models/src/verifications.rs @@ -13,6 +13,7 @@ pub struct ApplepayMerchantVerificationConfigs { #[serde(rename_all = "camelCase")] pub struct ApplepayMerchantVerificationRequest { pub domain_names: Vec<String>, + pub business_profile_id: String, } /// Response to be sent for the verify/applepay api diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 23fe0aed33f..f7b7b760f53 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -30,6 +30,8 @@ pub struct BusinessProfile { pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub is_recon_enabled: bool, + #[diesel(deserialize_as = super::OptionalDieselArray<String>)] + pub applepay_verified_domains: Option<Vec<String>>, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] @@ -51,6 +53,8 @@ pub struct BusinessProfileNew { pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub is_recon_enabled: bool, + #[diesel(deserialize_as = super::OptionalDieselArray<String>)] + pub applepay_verified_domains: Option<Vec<String>>, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] @@ -69,6 +73,8 @@ pub struct BusinessProfileUpdateInternal { pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub is_recon_enabled: Option<bool>, + #[diesel(deserialize_as = super::OptionalDieselArray<String>)] + pub applepay_verified_domains: Option<Vec<String>>, } impl From<BusinessProfileNew> for BusinessProfile { @@ -90,6 +96,7 @@ impl From<BusinessProfileNew> for BusinessProfile { frm_routing_algorithm: new.frm_routing_algorithm, payout_routing_algorithm: new.payout_routing_algorithm, is_recon_enabled: new.is_recon_enabled, + applepay_verified_domains: new.applepay_verified_domains, } } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 31aa03ff4a8..f6c2bed8abb 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -78,6 +78,7 @@ diesel::table! { frm_routing_algorithm -> Nullable<Jsonb>, payout_routing_algorithm -> Nullable<Jsonb>, is_recon_enabled -> Bool, + applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, } } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index e1464006851..7a3a6055f74 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1166,6 +1166,7 @@ pub async fn update_business_profile( frm_routing_algorithm: request.frm_routing_algorithm, payout_routing_algorithm: request.payout_routing_algorithm, is_recon_enabled: None, + applepay_verified_domains: request.applepay_verified_domains, }; let updated_business_profile = db diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 6a73c39bb22..94cdeae85f3 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -70,6 +70,7 @@ impl ForeignTryFrom<storage::business_profile::BusinessProfile> for BusinessProf intent_fulfillment_time: item.intent_fulfillment_time, frm_routing_algorithm: item.frm_routing_algorithm, payout_routing_algorithm: item.payout_routing_algorithm, + applepay_verified_domains: item.applepay_verified_domains, }) } } @@ -136,6 +137,7 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)> .payout_routing_algorithm .or(merchant_account.payout_routing_algorithm), is_recon_enabled: merchant_account.is_recon_enabled, + applepay_verified_domains: request.applepay_verified_domains, }) } } diff --git a/crates/router/src/utils/verification.rs b/crates/router/src/utils/verification.rs index db50a47e352..7bb269e3218 100644 --- a/crates/router/src/utils/verification.rs +++ b/crates/router/src/utils/verification.rs @@ -1,6 +1,8 @@ use actix_web::web; #[cfg(all(feature = "olap", feature = "kms"))] use api_models::verifications::{self, ApplepayMerchantResponse}; +use common_utils::errors::CustomResult; +use diesel_models::business_profile::{BusinessProfile, BusinessProfileUpdateInternal}; use error_stack::{Report, ResultExt}; #[cfg(feature = "kms")] use external_services::kms; @@ -19,7 +21,7 @@ pub async fn verify_merchant_creds_for_applepay( _req: &actix_web::HttpRequest, body: web::Json<verifications::ApplepayMerchantVerificationRequest>, kms_config: &kms::KmsConfig, -) -> common_utils::errors::CustomResult< +) -> CustomResult< services::ApplicationResponse<ApplepayMerchantResponse>, api_error_response::ApiErrorResponse, > { @@ -30,7 +32,6 @@ pub async fn verify_merchant_creds_for_applepay( let encrypted_cert = &state.conf.applepay_merchant_configs.merchant_cert; let encrypted_key = &state.conf.applepay_merchant_configs.merchant_cert_key; let applepay_endpoint = &state.conf.applepay_merchant_configs.applepay_endpoint; - let applepay_internal_merchant_identifier = kms::get_kms_client(kms_config) .await .decrypt(encrypted_merchant_identifier) @@ -84,10 +85,19 @@ pub async fn verify_merchant_creds_for_applepay( // Error is already logged Ok(match applepay_response { - Ok(_) => services::api::ApplicationResponse::Json(ApplepayMerchantResponse { - status_code: "200".to_string(), - status_message: "Applepay verification Completed".to_string(), - }), + Ok(_) => { + check_existence_and_add_domain_to_db( + state, + body.business_profile_id.clone(), + body.domain_names.clone(), + ) + .await + .change_context(api_error_response::ApiErrorResponse::InternalServerError)?; + services::api::ApplicationResponse::Json(ApplepayMerchantResponse { + status_code: "200".to_string(), + status_message: "Applepay verification Completed".to_string(), + }) + } Err(error) => { logger::error!(?error); services::api::ApplicationResponse::Json(ApplepayMerchantResponse { @@ -98,6 +108,52 @@ pub async fn verify_merchant_creds_for_applepay( }) } +// Checks whether or not the domain verified is already present in db if not adds it +async fn check_existence_and_add_domain_to_db( + state: &AppState, + business_profile_id: String, + domain_from_req: Vec<String>, +) -> CustomResult<BusinessProfile, errors::StorageError> { + let business_profile = state + .store + .find_business_profile_by_profile_id(&business_profile_id) + .await?; + let business_profile_to_update = business_profile.clone(); + let mut already_verified_domains = business_profile + .applepay_verified_domains + .unwrap_or_default(); + + let mut new_verified_domains: Vec<String> = domain_from_req + .into_iter() + .filter(|req_domain| !already_verified_domains.contains(req_domain)) + .collect(); + + already_verified_domains.append(&mut new_verified_domains); + + let update_business_profile = BusinessProfileUpdateInternal { + applepay_verified_domains: Some(already_verified_domains), + profile_name: Some(business_profile.profile_name), + modified_at: Some(business_profile.modified_at), + return_url: business_profile.return_url, + enable_payment_response_hash: Some(business_profile.enable_payment_response_hash), + payment_response_hash_key: business_profile.payment_response_hash_key, + redirect_to_merchant_with_http_post: Some( + business_profile.redirect_to_merchant_with_http_post, + ), + webhook_details: business_profile.webhook_details, + metadata: business_profile.metadata, + routing_algorithm: business_profile.routing_algorithm, + intent_fulfillment_time: business_profile.intent_fulfillment_time, + frm_routing_algorithm: business_profile.frm_routing_algorithm, + payout_routing_algorithm: business_profile.payout_routing_algorithm, + is_recon_enabled: Some(business_profile.is_recon_enabled), + }; + + state + .store + .update_business_profile_by_profile_id(business_profile_to_update, update_business_profile) + .await +} fn log_applepay_verification_response_if_error( response: &Result<Result<types::Response, types::Response>, Report<errors::ApiClientError>>, ) { diff --git a/migrations/2023-09-08-112817_applepay_verified_domains_in_business_profile/down.sql b/migrations/2023-09-08-112817_applepay_verified_domains_in_business_profile/down.sql new file mode 100644 index 00000000000..20c2ce7a521 --- /dev/null +++ b/migrations/2023-09-08-112817_applepay_verified_domains_in_business_profile/down.sql @@ -0,0 +1,2 @@ +ALTER TABLE business_profile DROP COLUMN IF EXISTS applepay_verified_domains; + diff --git a/migrations/2023-09-08-112817_applepay_verified_domains_in_business_profile/up.sql b/migrations/2023-09-08-112817_applepay_verified_domains_in_business_profile/up.sql new file mode 100644 index 00000000000..8643a2f30a9 --- /dev/null +++ b/migrations/2023-09-08-112817_applepay_verified_domains_in_business_profile/up.sql @@ -0,0 +1,3 @@ +ALTER TABLE business_profile +ADD COLUMN IF NOT EXISTS applepay_verified_domains text[]; +
feat
saving verified domains to business_profile table (#2109)
33298b38081c46fe4ee38f8ad6ddffd2b98a1d5c
2024-07-19 13:08:58
Arjun Karthik
feat: encryption service integration to support batch encryption and decryption (#5164)
false
diff --git a/Cargo.lock b/Cargo.lock index 193f19453b9..66b38d09c1f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2006,6 +2006,7 @@ name = "common_utils" version = "0.1.0" dependencies = [ "async-trait", + "base64 0.22.0", "blake3", "bytes 1.6.0", "common_enums", @@ -2704,6 +2705,7 @@ dependencies = [ "masking", "router_derive", "router_env", + "rustc-hash", "serde", "serde_json", "strum 0.26.2", @@ -3858,6 +3860,7 @@ dependencies = [ "mime", "router_derive", "router_env", + "rustc-hash", "serde", "serde_json", "serde_with", diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs index 37c4cd0f1b8..73fb5264ed9 100644 --- a/crates/api_models/src/customers.rs +++ b/crates/api_models/src/customers.rs @@ -1,5 +1,12 @@ -use common_utils::{crypto, custom_serde, id_type, pii}; -use masking::Secret; +use common_utils::{ + crypto, custom_serde, + encryption::Encryption, + id_type, + pii::{self, EmailStrategy}, + types::keymanager::ToEncryptable, +}; +use euclid::dssa::graph::euclid_graph_prelude::FxHashMap; +use masking::{ExposeInterface, Secret, SwitchStrategy}; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -40,6 +47,85 @@ pub struct CustomerRequest { pub metadata: Option<pii::SecretSerdeValue>, } +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"), + }) + } +} + #[derive(Debug, Clone, Serialize, ToSchema)] pub struct CustomerResponse { /// The identifier for the customer object diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 619f345a333..5ac8d0edcc3 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -11,10 +11,11 @@ use common_utils::{ ext_traits::{ConfigExt, Encode}, hashing::HashedString, id_type, - pii::{self, Email}, - types::{MinorUnit, StringMajorUnit}, + pii::{self, Email, EmailStrategy}, + types::{keymanager::ToEncryptable, MinorUnit, StringMajorUnit}, }; -use masking::{PeekInterface, Secret, WithType}; +use euclid::dssa::graph::euclid_graph_prelude::FxHashMap; +use masking::{ExposeInterface, PeekInterface, Secret, SwitchStrategy, WithType}; use router_derive::Setter; use serde::{ de::{self, Unexpected, Visitor}, @@ -3187,6 +3188,72 @@ impl AddressDetails { } } +pub struct AddressDetailsWithPhone { + pub address: Option<AddressDetails>, + pub phone_number: Option<Secret<String>>, + pub email: Option<Email>, +} + +pub struct EncryptableAddressDetails { + pub line1: crypto::OptionalEncryptableSecretString, + pub line2: crypto::OptionalEncryptableSecretString, + pub line3: crypto::OptionalEncryptableSecretString, + pub state: crypto::OptionalEncryptableSecretString, + pub zip: crypto::OptionalEncryptableSecretString, + pub first_name: crypto::OptionalEncryptableSecretString, + pub last_name: crypto::OptionalEncryptableSecretString, + pub phone_number: crypto::OptionalEncryptableSecretString, + pub email: crypto::OptionalEncryptableEmail, +} + +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/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index df6b4400633..61d96a21737 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -10,6 +10,7 @@ license.workspace = true [features] keymanager = ["dep:router_env"] keymanager_mtls = ["reqwest/rustls-tls"] +encryption_service = ["dep:router_env"] signals = ["dep:signal-hook-tokio", "dep:signal-hook", "dep:tokio", "dep:router_env", "dep:futures"] async_ext = ["dep:async-trait", "dep:futures"] logs = ["dep:router_env"] @@ -17,6 +18,7 @@ metrics = ["dep:router_env", "dep:futures"] [dependencies] async-trait = { version = "0.1.79", optional = true } +base64 = "0.22.0" blake3 = { version = "1.5.1", features = ["serde"] } bytes = "1.6.0" diesel = "2.1.5" diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index 848189cd899..e52d24c9baa 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -99,6 +99,8 @@ pub const MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 64; /// Minimum allowed length for MerchantReferenceId pub const MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 1; +/// General purpose base64 engine +pub const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD; /// Regex for matching a domain /// Eg - /// http://www.example.com diff --git a/crates/diesel_models/src/encryption.rs b/crates/common_utils/src/encryption.rs similarity index 88% rename from crates/diesel_models/src/encryption.rs rename to crates/common_utils/src/encryption.rs index 6c6063c1604..9c566432782 100644 --- a/crates/diesel_models/src/encryption.rs +++ b/crates/common_utils/src/encryption.rs @@ -1,40 +1,13 @@ -use common_utils::pii::EncryptionStrategy; use diesel::{ backend::Backend, deserialize::{self, FromSql, Queryable}, + expression::AsExpression, serialize::ToSql, - sql_types, AsExpression, + sql_types, }; use masking::Secret; -#[derive(Debug, AsExpression, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)] -#[diesel(sql_type = sql_types::Binary)] -#[repr(transparent)] -pub struct Encryption { - inner: Secret<Vec<u8>, EncryptionStrategy>, -} - -impl<T: Clone> From<common_utils::crypto::Encryptable<T>> for Encryption { - fn from(value: common_utils::crypto::Encryptable<T>) -> Self { - Self::new(value.into_encrypted()) - } -} - -impl Encryption { - pub fn new(item: Secret<Vec<u8>, EncryptionStrategy>) -> Self { - Self { inner: item } - } - - #[inline] - pub fn into_inner(self) -> Secret<Vec<u8>, EncryptionStrategy> { - self.inner - } - - #[inline] - pub fn get_inner(&self) -> &Secret<Vec<u8>, EncryptionStrategy> { - &self.inner - } -} +use crate::{crypto::Encryptable, pii::EncryptionStrategy}; impl<DB> FromSql<sql_types::Binary, DB> for Encryption where @@ -69,3 +42,32 @@ where Ok(Self { inner: row }) } } + +#[derive(Debug, AsExpression, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)] +#[diesel(sql_type = sql_types::Binary)] +#[repr(transparent)] +pub struct Encryption { + inner: Secret<Vec<u8>, EncryptionStrategy>, +} + +impl<T: Clone> From<Encryptable<T>> for Encryption { + fn from(value: Encryptable<T>) -> Self { + Self::new(value.into_encrypted()) + } +} + +impl Encryption { + pub fn new(item: Secret<Vec<u8>, EncryptionStrategy>) -> Self { + Self { inner: item } + } + + #[inline] + pub fn into_inner(self) -> Secret<Vec<u8>, EncryptionStrategy> { + self.inner + } + + #[inline] + pub fn get_inner(&self) -> &Secret<Vec<u8>, EncryptionStrategy> { + &self.inner + } +} diff --git a/crates/common_utils/src/keymanager.rs b/crates/common_utils/src/keymanager.rs index ecdb9b63ad5..9d6e9315074 100644 --- a/crates/common_utils/src/keymanager.rs +++ b/crates/common_utils/src/keymanager.rs @@ -3,22 +3,26 @@ use core::fmt::Debug; use std::str::FromStr; +use base64::Engine; use error_stack::ResultExt; use http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; -#[cfg(feature = "keymanager_mtls")] -use masking::PeekInterface; +use masking::{PeekInterface, StrongSecret}; use once_cell::sync::OnceCell; use router_env::{instrument, logger, tracing}; use crate::{ + consts::BASE64_ENGINE, errors, types::keymanager::{ - DataKeyCreateResponse, EncryptionCreateRequest, EncryptionTransferRequest, KeyManagerState, + BatchDecryptDataRequest, DataKeyCreateResponse, DecryptDataRequest, + EncryptionCreateRequest, EncryptionTransferRequest, KeyManagerState, + TransientBatchDecryptDataRequest, TransientDecryptDataRequest, }, }; const CONTENT_TYPE: &str = "Content-Type"; static ENCRYPTION_API_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); +static DEFAULT_ENCRYPTION_VERSION: &str = "v1"; /// Get keymanager client constructed from the url and state #[instrument(skip_all)] @@ -68,7 +72,7 @@ pub async fn send_encryption_request<T>( request_body: T, ) -> errors::CustomResult<reqwest::Response, errors::KeyManagerClientError> where - T: serde::Serialize, + T: ConvertRaw, { let client = get_api_encryption_client(state)?; let url = reqwest::Url::parse(&url) @@ -76,7 +80,7 @@ where client .request(method, url) - .json(&request_body) + .json(&ConvertRaw::convert_raw(request_body)?) .headers(headers) .send() .await @@ -94,7 +98,7 @@ pub async fn call_encryption_service<T, R>( request_body: T, ) -> errors::CustomResult<R, errors::KeyManagerClientError> where - T: serde::Serialize + Send + Sync + 'static + Debug, + T: ConvertRaw + Send + Sync + 'static + Debug, R: serde::de::DeserializeOwned, { let url = format!("{}/{endpoint}", &state.url); @@ -152,6 +156,62 @@ where } } +/// Trait to convert the raw data to the required format for encryption service request +pub trait ConvertRaw { + /// Return type of the convert_raw function + type Output: serde::Serialize; + /// Function to convert the raw data to the required format for encryption service request + fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError>; +} + +impl<T: serde::Serialize> ConvertRaw for T { + type Output = T; + fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> { + Ok(self) + } +} + +impl ConvertRaw for TransientDecryptDataRequest { + type Output = DecryptDataRequest; + fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> { + let data = match String::from_utf8(self.data.peek().clone()) { + Ok(data) => data, + Err(_) => { + let data = BASE64_ENGINE.encode(self.data.peek().clone()); + format!("{DEFAULT_ENCRYPTION_VERSION}:{data}") + } + }; + Ok(DecryptDataRequest { + identifier: self.identifier, + data: StrongSecret::new(data), + }) + } +} + +impl ConvertRaw for TransientBatchDecryptDataRequest { + type Output = BatchDecryptDataRequest; + fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> { + let data = self + .data + .iter() + .map(|(k, v)| { + let value = match String::from_utf8(v.peek().clone()) { + Ok(data) => data, + Err(_) => { + let data = BASE64_ENGINE.encode(v.peek().clone()); + format!("{DEFAULT_ENCRYPTION_VERSION}:{data}") + } + }; + (k.to_owned(), StrongSecret::new(value)) + }) + .collect(); + Ok(BatchDecryptDataRequest { + data, + identifier: self.identifier, + }) + } +} + /// A function to create the key in keymanager #[instrument(skip_all)] pub async fn create_key_in_key_manager( diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs index 9b339fb956e..e93b0c66ceb 100644 --- a/crates/common_utils/src/lib.rs +++ b/crates/common_utils/src/lib.rs @@ -13,6 +13,8 @@ pub mod access_token; pub mod consts; pub mod crypto; pub mod custom_serde; +#[allow(missing_docs)] // Todo: add docs +pub mod encryption; pub mod errors; #[allow(missing_docs)] // Todo: add docs pub mod events; @@ -31,6 +33,7 @@ pub mod request; pub mod signals; #[allow(missing_docs)] // Todo: add docs pub mod static_cache; +pub mod transformers; pub mod types; pub mod validation; diff --git a/crates/common_utils/src/transformers.rs b/crates/common_utils/src/transformers.rs new file mode 100644 index 00000000000..3799522e16d --- /dev/null +++ b/crates/common_utils/src/transformers.rs @@ -0,0 +1,15 @@ +//! Utilities for converting between foreign types + +/// Trait for converting from one foreign type to another +pub trait ForeignFrom<F> { + /// Convert from a foreign type to the current type + fn foreign_from(from: F) -> Self; +} + +/// Trait for converting from one foreign type to another +pub trait ForeignTryFrom<F>: Sized { + /// Custom error for conversion failure + type Error; + /// Convert from a foreign type to the current type and return an error if the conversion fails + fn foreign_try_from(from: F) -> Result<Self, Self::Error>; +} diff --git a/crates/common_utils/src/types/keymanager.rs b/crates/common_utils/src/types/keymanager.rs index 356ccdd4832..5a7b87d0ce0 100644 --- a/crates/common_utils/src/types/keymanager.rs +++ b/crates/common_utils/src/types/keymanager.rs @@ -1,8 +1,24 @@ #![allow(missing_docs)] -#[cfg(feature = "keymanager_mtls")] -use masking::Secret; -use serde::{Deserialize, Serialize}; +use core::fmt; + +use base64::Engine; +use masking::{ExposeInterface, PeekInterface, Secret, Strategy, StrongSecret}; +#[cfg(feature = "encryption_service")] +use router_env::logger; +use rustc_hash::FxHashMap; +use serde::{ + de::{self, Unexpected, Visitor}, + ser, Deserialize, Deserializer, Serialize, +}; + +use crate::{ + consts::BASE64_ENGINE, + crypto::Encryptable, + encryption::Encryption, + errors::{self, CustomResult}, + transformers::{ForeignFrom, ForeignTryFrom}, +}; #[derive(Debug)] pub struct KeyManagerState { @@ -18,6 +34,7 @@ pub struct KeyManagerState { pub enum Identifier { User(String), Merchant(String), + UserAuth(String), } #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] @@ -39,3 +56,420 @@ pub struct DataKeyCreateResponse { pub identifier: Identifier, pub key_version: String, } + +#[derive(Serialize, Deserialize, Debug)] +pub struct BatchEncryptDataRequest { + #[serde(flatten)] + pub identifier: Identifier, + pub data: DecryptedDataGroup, +} + +impl<S> From<(Secret<Vec<u8>, S>, Identifier)> for EncryptDataRequest +where + S: Strategy<Vec<u8>>, +{ + fn from((secret, identifier): (Secret<Vec<u8>, S>, Identifier)) -> Self { + Self { + identifier, + data: DecryptedData(StrongSecret::new(secret.expose())), + } + } +} + +impl<S> From<(FxHashMap<String, Secret<Vec<u8>, S>>, Identifier)> for BatchEncryptDataRequest +where + S: Strategy<Vec<u8>>, +{ + fn from((map, identifier): (FxHashMap<String, Secret<Vec<u8>, S>>, Identifier)) -> Self { + let group = map + .into_iter() + .map(|(key, value)| (key, DecryptedData(StrongSecret::new(value.expose())))) + .collect(); + Self { + identifier, + data: DecryptedDataGroup(group), + } + } +} + +impl<S> From<(Secret<String, S>, Identifier)> for EncryptDataRequest +where + S: Strategy<String>, +{ + fn from((secret, identifier): (Secret<String, S>, Identifier)) -> Self { + Self { + data: DecryptedData(StrongSecret::new(secret.expose().as_bytes().to_vec())), + identifier, + } + } +} + +impl<S> From<(Secret<serde_json::Value, S>, Identifier)> for EncryptDataRequest +where + S: Strategy<serde_json::Value>, +{ + fn from((secret, identifier): (Secret<serde_json::Value, S>, Identifier)) -> Self { + Self { + data: DecryptedData(StrongSecret::new( + secret.expose().to_string().as_bytes().to_vec(), + )), + identifier, + } + } +} + +impl<S> From<(FxHashMap<String, Secret<serde_json::Value, S>>, Identifier)> + for BatchEncryptDataRequest +where + S: Strategy<serde_json::Value>, +{ + fn from( + (map, identifier): (FxHashMap<String, Secret<serde_json::Value, S>>, Identifier), + ) -> Self { + let group = map + .into_iter() + .map(|(key, value)| { + ( + key, + DecryptedData(StrongSecret::new( + value.expose().to_string().as_bytes().to_vec(), + )), + ) + }) + .collect(); + Self { + data: DecryptedDataGroup(group), + identifier, + } + } +} + +impl<S> From<(FxHashMap<String, Secret<String, S>>, Identifier)> for BatchEncryptDataRequest +where + S: Strategy<String>, +{ + fn from((map, identifier): (FxHashMap<String, Secret<String, S>>, Identifier)) -> Self { + let group = map + .into_iter() + .map(|(key, value)| { + ( + key, + DecryptedData(StrongSecret::new(value.expose().as_bytes().to_vec())), + ) + }) + .collect(); + Self { + data: DecryptedDataGroup(group), + identifier, + } + } +} + +#[derive(Serialize, Deserialize, Debug)] +pub struct EncryptDataRequest { + #[serde(flatten)] + pub identifier: Identifier, + pub data: DecryptedData, +} + +#[derive(Debug, Serialize, serde::Deserialize)] +pub struct DecryptedDataGroup(pub FxHashMap<String, DecryptedData>); + +#[derive(Debug, Serialize, Deserialize)] +pub struct BatchEncryptDataResponse { + pub data: EncryptedDataGroup, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct EncryptDataResponse { + pub data: EncryptedData, +} + +#[derive(Debug, Serialize, serde::Deserialize)] +pub struct EncryptedDataGroup(pub FxHashMap<String, EncryptedData>); +#[derive(Debug)] +pub struct TransientBatchDecryptDataRequest { + pub identifier: Identifier, + pub data: FxHashMap<String, StrongSecret<Vec<u8>>>, +} + +#[derive(Debug)] +pub struct TransientDecryptDataRequest { + pub identifier: Identifier, + pub data: StrongSecret<Vec<u8>>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct BatchDecryptDataRequest { + #[serde(flatten)] + pub identifier: Identifier, + pub data: FxHashMap<String, StrongSecret<String>>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct DecryptDataRequest { + #[serde(flatten)] + pub identifier: Identifier, + pub data: StrongSecret<String>, +} + +impl<T, S> ForeignFrom<(FxHashMap<String, Secret<T, S>>, BatchEncryptDataResponse)> + for FxHashMap<String, Encryptable<Secret<T, S>>> +where + T: Clone, + S: Strategy<T> + Send, +{ + fn foreign_from( + (mut masked_data, response): (FxHashMap<String, Secret<T, S>>, BatchEncryptDataResponse), + ) -> Self { + response + .data + .0 + .into_iter() + .flat_map(|(k, v)| { + masked_data.remove(&k).map(|inner| { + ( + k, + Encryptable::new(inner.clone(), v.data.peek().clone().into()), + ) + }) + }) + .collect() + } +} + +impl<T, S> ForeignFrom<(Secret<T, S>, EncryptDataResponse)> for Encryptable<Secret<T, S>> +where + T: Clone, + S: Strategy<T> + Send, +{ + fn foreign_from((masked_data, response): (Secret<T, S>, EncryptDataResponse)) -> Self { + Self::new(masked_data, response.data.data.peek().clone().into()) + } +} + +pub trait DecryptedDataConversion<T: Clone, S: Strategy<T> + Send>: Sized { + fn convert( + value: &DecryptedData, + encryption: Encryption, + ) -> CustomResult<Self, errors::CryptoError>; +} + +impl<S: Strategy<String> + Send> DecryptedDataConversion<String, S> + for Encryptable<Secret<String, S>> +{ + fn convert( + value: &DecryptedData, + encryption: Encryption, + ) -> CustomResult<Self, errors::CryptoError> { + let string = String::from_utf8(value.clone().inner().peek().clone()).map_err(|_err| { + #[cfg(feature = "encryption_service")] + logger::error!("Decryption error {:?}", _err); + errors::CryptoError::DecodingFailed + })?; + Ok(Self::new(Secret::new(string), encryption.into_inner())) + } +} + +impl<S: Strategy<serde_json::Value> + Send> DecryptedDataConversion<serde_json::Value, S> + for Encryptable<Secret<serde_json::Value, S>> +{ + fn convert( + value: &DecryptedData, + encryption: Encryption, + ) -> CustomResult<Self, errors::CryptoError> { + let val = serde_json::from_slice(value.clone().inner().peek()).map_err(|_err| { + #[cfg(feature = "encryption_service")] + logger::error!("Decryption error {:?}", _err); + errors::CryptoError::DecodingFailed + })?; + Ok(Self::new(Secret::new(val), encryption.clone().into_inner())) + } +} + +impl<S: Strategy<Vec<u8>> + Send> DecryptedDataConversion<Vec<u8>, S> + for Encryptable<Secret<Vec<u8>, S>> +{ + fn convert( + value: &DecryptedData, + encryption: Encryption, + ) -> CustomResult<Self, errors::CryptoError> { + Ok(Self::new( + Secret::new(value.clone().inner().peek().clone()), + encryption.clone().into_inner(), + )) + } +} + +impl<T, S> ForeignTryFrom<(Encryption, DecryptDataResponse)> for Encryptable<Secret<T, S>> +where + T: Clone, + S: Strategy<T> + Send, + Self: DecryptedDataConversion<T, S>, +{ + type Error = error_stack::Report<errors::CryptoError>; + fn foreign_try_from( + (encrypted_data, response): (Encryption, DecryptDataResponse), + ) -> Result<Self, Self::Error> { + Self::convert(&response.data, encrypted_data) + } +} + +impl<T, S> ForeignTryFrom<(FxHashMap<String, Encryption>, BatchDecryptDataResponse)> + for FxHashMap<String, Encryptable<Secret<T, S>>> +where + T: Clone, + S: Strategy<T> + Send, + Encryptable<Secret<T, S>>: DecryptedDataConversion<T, S>, +{ + type Error = error_stack::Report<errors::CryptoError>; + fn foreign_try_from( + (mut encrypted_data, response): (FxHashMap<String, Encryption>, BatchDecryptDataResponse), + ) -> Result<Self, Self::Error> { + response + .data + .0 + .into_iter() + .map(|(k, v)| match encrypted_data.remove(&k) { + Some(encrypted) => Ok((k.clone(), Encryptable::convert(&v, encrypted.clone())?)), + None => Err(errors::CryptoError::DecodingFailed)?, + }) + .collect() + } +} + +impl From<(Encryption, Identifier)> for TransientDecryptDataRequest { + fn from((encryption, identifier): (Encryption, Identifier)) -> Self { + Self { + data: StrongSecret::new(encryption.clone().into_inner().expose()), + identifier, + } + } +} + +impl From<(FxHashMap<String, Encryption>, Identifier)> for TransientBatchDecryptDataRequest { + fn from((map, identifier): (FxHashMap<String, Encryption>, Identifier)) -> Self { + let data = map + .into_iter() + .map(|(k, v)| (k, StrongSecret::new(v.clone().into_inner().expose()))) + .collect(); + Self { data, identifier } + } +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct BatchDecryptDataResponse { + pub data: DecryptedDataGroup, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct DecryptDataResponse { + pub data: DecryptedData, +} + +#[derive(Clone, Debug)] +pub struct DecryptedData(StrongSecret<Vec<u8>>); + +impl Serialize for DecryptedData { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer, + { + let data = BASE64_ENGINE.encode(self.0.peek()); + serializer.serialize_str(&data) + } +} + +impl<'de> Deserialize<'de> for DecryptedData { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + struct DecryptedDataVisitor; + + impl<'de> Visitor<'de> for DecryptedDataVisitor { + type Value = DecryptedData; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("string of the format {version}:{base64_encoded_data}'") + } + + fn visit_str<E>(self, value: &str) -> Result<DecryptedData, E> + where + E: de::Error, + { + let dec_data = BASE64_ENGINE.decode(value).map_err(|err| { + let err = err.to_string(); + E::invalid_value(Unexpected::Str(value), &err.as_str()) + })?; + + Ok(DecryptedData(dec_data.into())) + } + } + + deserializer.deserialize_str(DecryptedDataVisitor) + } +} + +impl DecryptedData { + pub fn from_data(data: StrongSecret<Vec<u8>>) -> Self { + Self(data) + } + + pub fn inner(self) -> StrongSecret<Vec<u8>> { + self.0 + } +} + +#[derive(Debug)] +pub struct EncryptedData { + pub data: StrongSecret<Vec<u8>>, +} + +impl Serialize for EncryptedData { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer, + { + let data = String::from_utf8(self.data.peek().clone()).map_err(ser::Error::custom)?; + serializer.serialize_str(data.as_str()) + } +} + +impl<'de> Deserialize<'de> for EncryptedData { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + struct EncryptedDataVisitor; + + impl<'de> Visitor<'de> for EncryptedDataVisitor { + type Value = EncryptedData; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("string of the format {version}:{base64_encoded_data}'") + } + + fn visit_str<E>(self, value: &str) -> Result<EncryptedData, E> + where + E: de::Error, + { + Ok(EncryptedData { + data: StrongSecret::new(value.as_bytes().to_vec()), + }) + } + } + + deserializer.deserialize_str(EncryptedDataVisitor) + } +} + +/// A trait which converts the struct to Hashmap required for encryption and back to struct +pub trait ToEncryptable<T, S: Clone, E>: Sized { + /// Serializes the type to a hashmap + fn to_encryptable(self) -> FxHashMap<String, E>; + /// Deserializes the hashmap back to the type + fn from_encryptable( + hashmap: FxHashMap<String, Encryptable<S>>, + ) -> CustomResult<T, errors::ParsingError>; +} diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml index f33427aaf30..10890ef0cf0 100644 --- a/crates/diesel_models/Cargo.toml +++ b/crates/diesel_models/Cargo.toml @@ -15,6 +15,7 @@ kv_store = [] async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } diesel = { version = "2.1.5", features = ["postgres", "serde_json", "time", "64-column-tables"] } error-stack = "0.4.1" +rustc-hash = "1.1.0" serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" strum = { version = "0.26.2", features = ["derive"] } diff --git a/crates/diesel_models/src/address.rs b/crates/diesel_models/src/address.rs index d695d2a0e70..57c4e36c786 100644 --- a/crates/diesel_models/src/address.rs +++ b/crates/diesel_models/src/address.rs @@ -1,9 +1,17 @@ -use common_utils::id_type; +use common_utils::{ + crypto::{self, Encryptable}, + encryption::Encryption, + id_type, + pii::EmailStrategy, + types::keymanager::ToEncryptable, +}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; +use masking::{Secret, SwitchStrategy}; +use rustc_hash::FxHashMap; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{encryption::Encryption, enums, schema::address}; +use crate::{enums, schema::address}; #[derive(Clone, Debug, Insertable, Serialize, Deserialize, router_derive::DebugAsDisplay)] #[diesel(table_name = address)] @@ -54,6 +62,62 @@ pub struct Address { pub email: Option<Encryption>, } +#[derive(Clone)] +// Intermediate struct to convert HashMap to Address +pub struct EncryptableAddress { + pub line1: crypto::OptionalEncryptableSecretString, + pub line2: crypto::OptionalEncryptableSecretString, + pub line3: crypto::OptionalEncryptableSecretString, + pub state: crypto::OptionalEncryptableSecretString, + pub zip: crypto::OptionalEncryptableSecretString, + pub first_name: crypto::OptionalEncryptableSecretString, + pub last_name: crypto::OptionalEncryptableSecretString, + pub phone_number: crypto::OptionalEncryptableSecretString, + pub email: crypto::OptionalEncryptableEmail, +} + +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/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 6bd1e1f9e41..b964b290a9e 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -1,7 +1,7 @@ -use common_utils::pii; +use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; -use crate::{encryption::Encryption, schema::business_profile}; +use crate::schema::business_profile; #[derive( Clone, diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs index deb1ac73f41..302772b7f9e 100644 --- a/crates/diesel_models/src/customers.rs +++ b/crates/diesel_models/src/customers.rs @@ -1,8 +1,8 @@ -use common_utils::{id_type, pii}; +use common_utils::{encryption::Encryption, id_type, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; -use crate::{encryption::Encryption, schema::customers}; +use crate::schema::customers; #[derive( Clone, Debug, Insertable, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize, diff --git a/crates/diesel_models/src/events.rs b/crates/diesel_models/src/events.rs index b3b1230441f..99879dafaf9 100644 --- a/crates/diesel_models/src/events.rs +++ b/crates/diesel_models/src/events.rs @@ -1,11 +1,15 @@ -use common_utils::custom_serde; +use common_utils::{ + crypto::OptionalEncryptableSecretString, custom_serde, encryption::Encryption, + types::keymanager::ToEncryptable, +}; use diesel::{ expression::AsExpression, AsChangeset, Identifiable, Insertable, Queryable, Selectable, }; +use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{encryption::Encryption, enums as storage_enums, schema::events}; +use crate::{enums as storage_enums, schema::events}; #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = events)] @@ -59,6 +63,38 @@ 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/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index 67061bf6c33..6af1e0e5208 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -12,7 +12,6 @@ pub mod blocklist; pub mod blocklist_fingerprint; pub mod customers; pub mod dispute; -pub mod encryption; pub mod enums; pub mod ephemeral_key; pub mod errors; diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rs index 71c437bbb41..5c48ade55c0 100644 --- a/crates/diesel_models/src/merchant_account.rs +++ b/crates/diesel_models/src/merchant_account.rs @@ -1,7 +1,7 @@ -use common_utils::pii; +use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; -use crate::{encryption::Encryption, enums as storage_enums, schema::merchant_account}; +use crate::{enums as storage_enums, schema::merchant_account}; #[derive( Clone, diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs index 05707f71737..5a549892dca 100644 --- a/crates/diesel_models/src/merchant_connector_account.rs +++ b/crates/diesel_models/src/merchant_connector_account.rs @@ -1,10 +1,10 @@ use std::fmt::Debug; -use common_utils::pii; +use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; -use crate::{encryption::Encryption, enums as storage_enums, schema::merchant_connector_account}; +use crate::{enums as storage_enums, schema::merchant_connector_account}; #[derive( Clone, diff --git a/crates/diesel_models/src/merchant_key_store.rs b/crates/diesel_models/src/merchant_key_store.rs index 30781927e94..b11d9970532 100644 --- a/crates/diesel_models/src/merchant_key_store.rs +++ b/crates/diesel_models/src/merchant_key_store.rs @@ -1,8 +1,8 @@ -use common_utils::custom_serde; +use common_utils::{custom_serde, encryption::Encryption}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; -use crate::{encryption::Encryption, schema::merchant_key_store}; +use crate::schema::merchant_key_store; #[derive( Clone, diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 499d72a648a..e4d8dcc315a 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -1,10 +1,10 @@ use common_enums::RequestIncrementalAuthorization; -use common_utils::{id_type, pii, types::MinorUnit}; +use common_utils::{encryption::Encryption, id_type, pii, types::MinorUnit}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{encryption::Encryption, enums as storage_enums, schema::payment_intent}; +use crate::{enums as storage_enums, schema::payment_intent}; #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize)] #[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index a9db90abb20..6bb40e4b166 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -1,11 +1,11 @@ use common_enums::MerchantStorageScheme; -use common_utils::{id_type, pii}; +use common_utils::{encryption::Encryption, id_type, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{encryption::Encryption, enums as storage_enums, schema::payment_methods}; +use crate::{enums as storage_enums, schema::payment_methods}; #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs index 56c6f00f2b0..9d6514916d8 100644 --- a/crates/diesel_models/src/user.rs +++ b/crates/diesel_models/src/user.rs @@ -1,11 +1,9 @@ -use common_utils::pii; +use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use time::PrimitiveDateTime; -use crate::{ - diesel_impl::OptionalDieselArray, encryption::Encryption, enums::TotpStatus, schema::users, -}; +use crate::{diesel_impl::OptionalDieselArray, enums::TotpStatus, schema::users}; pub mod dashboard_metadata; diff --git a/crates/diesel_models/src/user_authentication_method.rs b/crates/diesel_models/src/user_authentication_method.rs index 18a65b9f104..76e1abe7575 100644 --- a/crates/diesel_models/src/user_authentication_method.rs +++ b/crates/diesel_models/src/user_authentication_method.rs @@ -1,7 +1,8 @@ +use common_utils::encryption::Encryption; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; -use crate::{encryption::Encryption, enums, schema::user_authentication_methods}; +use crate::{enums, schema::user_authentication_methods}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = user_authentication_methods, check_for_backend(diesel::pg::Pg))] diff --git a/crates/diesel_models/src/user_key_store.rs b/crates/diesel_models/src/user_key_store.rs index 1b19ef31a49..4d880ebf8f9 100644 --- a/crates/diesel_models/src/user_key_store.rs +++ b/crates/diesel_models/src/user_key_store.rs @@ -1,7 +1,8 @@ +use common_utils::encryption::Encryption; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; -use crate::{encryption::Encryption, schema::user_key_store}; +use crate::schema::user_key_store; #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable, diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml index ab569464684..310c2731b42 100644 --- a/crates/hyperswitch_domain_models/Cargo.toml +++ b/crates/hyperswitch_domain_models/Cargo.toml @@ -9,6 +9,7 @@ license.workspace = true [features] default = ["olap", "payouts", "frm"] +encryption_service =[] olap = [] payouts = ["api_models/payouts"] frm = ["api_models/frm"] @@ -18,7 +19,7 @@ frm = ["api_models/frm"] api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] } cards = { version = "0.1.0", path = "../cards" } common_enums = { version = "0.1.0", path = "../common_enums" } -common_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext", "metrics"] } +common_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext", "metrics", "encryption_service", "keymanager"] } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } masking = { version = "0.1.0", path = "../masking" } router_derive = { version = "0.1.0", path = "../router_derive" } @@ -31,6 +32,7 @@ error-stack = "0.4.1" futures = "0.3.30" http = "0.2.12" mime = "0.3.17" +rustc-hash = "1.1.0" serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" serde_with = "3.7.0" diff --git a/crates/hyperswitch_domain_models/src/behaviour.rs b/crates/hyperswitch_domain_models/src/behaviour.rs index 9976dd25a98..07911e8ea69 100644 --- a/crates/hyperswitch_domain_models/src/behaviour.rs +++ b/crates/hyperswitch_domain_models/src/behaviour.rs @@ -1,4 +1,7 @@ -use common_utils::errors::{CustomResult, ValidationError}; +use common_utils::{ + errors::{CustomResult, ValidationError}, + types::keymanager::KeyManagerState, +}; use masking::Secret; /// Trait for converting domain types to storage models @@ -9,8 +12,10 @@ pub trait Conversion { async fn convert(self) -> CustomResult<Self::DstType, ValidationError>; async fn convert_back( + state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, + key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> where Self: Sized; @@ -20,12 +25,22 @@ pub trait Conversion { #[async_trait::async_trait] pub trait ReverseConversion<SrcType: Conversion> { - async fn convert(self, key: &Secret<Vec<u8>>) -> CustomResult<SrcType, ValidationError>; + async fn convert( + self, + state: &KeyManagerState, + key: &Secret<Vec<u8>>, + key_store_ref_id: String, + ) -> CustomResult<SrcType, ValidationError>; } #[async_trait::async_trait] impl<T: Send, U: Conversion<DstType = T>> ReverseConversion<U> for T { - async fn convert(self, key: &Secret<Vec<u8>>) -> CustomResult<U, ValidationError> { - U::convert_back(self, key).await + async fn convert( + self, + state: &KeyManagerState, + key: &Secret<Vec<u8>>, + key_store_ref_id: String, + ) -> CustomResult<U, ValidationError> { + U::convert_back(state, self, key, key_store_ref_id).await } } diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs index e42f21dc7c7..a430673c59a 100644 --- a/crates/hyperswitch_domain_models/src/merchant_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_account.rs @@ -1,13 +1,14 @@ use common_utils::{ crypto::{OptionalEncryptableName, OptionalEncryptableValue}, date_time, + encryption::Encryption, errors::{CustomResult, ValidationError}, ext_traits::ValueExt, pii, + types::keymanager, }; use diesel_models::{ - encryption::Encryption, enums::MerchantStorageScheme, - merchant_account::MerchantAccountUpdateInternal, + enums::MerchantStorageScheme, merchant_account::MerchantAccountUpdateInternal, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; @@ -195,8 +196,10 @@ impl super::behaviour::Conversion for MerchantAccount { } async fn convert_back( + state: &keymanager::KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, + key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> where Self: Sized, @@ -206,7 +209,7 @@ impl super::behaviour::Conversion for MerchantAccount { .ok_or(ValidationError::MissingRequiredField { field_name: "publishable_key".to_string(), })?; - + let identifier = keymanager::Identifier::Merchant(key_store_ref_id.clone()); async { Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { id: Some(item.id), @@ -217,11 +220,11 @@ impl super::behaviour::Conversion for MerchantAccount { redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, merchant_name: item .merchant_name - .async_lift(|inner| decrypt(inner, key.peek())) + .async_lift(|inner| decrypt(state, inner, identifier.clone(), key.peek())) .await?, merchant_details: item .merchant_details - .async_lift(|inner| decrypt(inner, key.peek())) + .async_lift(|inner| decrypt(state, inner, identifier.clone(), key.peek())) .await?, webhook_details: item.webhook_details, sub_merchants_enabled: item.sub_merchants_enabled, diff --git a/crates/hyperswitch_domain_models/src/merchant_key_store.rs b/crates/hyperswitch_domain_models/src/merchant_key_store.rs index 29050b7eb49..76acf0f1404 100644 --- a/crates/hyperswitch_domain_models/src/merchant_key_store.rs +++ b/crates/hyperswitch_domain_models/src/merchant_key_store.rs @@ -2,6 +2,7 @@ use common_utils::{ crypto::{Encryptable, GcmAes256}, custom_serde, date_time, errors::{CustomResult, ValidationError}, + types::keymanager::{Identifier, KeyManagerState}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; @@ -30,14 +31,17 @@ impl super::behaviour::Conversion for MerchantKeyStore { } async fn convert_back( + state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, + _key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> where Self: Sized, { + let identifier = Identifier::Merchant(item.merchant_id.clone()); Ok(Self { - key: Encryptable::decrypt(item.key, key.peek(), GcmAes256) + key: Encryptable::decrypt_via_api(state, item.key, identifier, key.peek(), GcmAes256) .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting customer data".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 6ff74a95e46..5f8dd3934a2 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -1,9 +1,10 @@ use api_models::enums::Connector; use common_enums as storage_enums; use common_utils::{ + encryption::Encryption, errors::{CustomResult, ValidationError}, pii, - types::MinorUnit, + types::{keymanager::KeyManagerState, MinorUnit}, }; use error_stack::ResultExt; use masking::PeekInterface; @@ -479,8 +480,7 @@ impl ForeignIDRef for PaymentAttempt { } use diesel_models::{ - encryption::Encryption, PaymentIntent as DieselPaymentIntent, - PaymentIntentNew as DieselPaymentIntentNew, + PaymentIntent as DieselPaymentIntent, PaymentIntentNew as DieselPaymentIntentNew, }; #[async_trait::async_trait] @@ -542,14 +542,23 @@ impl behaviour::Conversion for PaymentIntent { } async fn convert_back( + state: &KeyManagerState, storage_model: Self::DstType, key: &masking::Secret<Vec<u8>>, + key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> where Self: Sized, { async { - let inner_decrypt = |inner| decrypt(inner, key.peek()); + let inner_decrypt = |inner| { + decrypt( + state, + inner, + common_utils::types::keymanager::Identifier::Merchant(key_store_ref_id.clone()), + key.peek(), + ) + }; Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 6eb35616729..f4f6be97055 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -2,9 +2,10 @@ use common_enums as storage_enums; use common_utils::{ consts::{PAYMENTS_LIST_MAX_LIMIT_V1, PAYMENTS_LIST_MAX_LIMIT_V2}, crypto::Encryptable, + encryption::Encryption, id_type, pii::{self, Email}, - types::MinorUnit, + types::{keymanager::KeyManagerState, MinorUnit}, }; use masking::{Deserialize, Secret}; use serde::Serialize; @@ -16,6 +17,7 @@ use crate::{errors, merchant_key_store::MerchantKeyStore, RemoteStorageObject}; pub trait PaymentIntentInterface { async fn update_payment_intent( &self, + state: &KeyManagerState, this: PaymentIntent, payment_intent: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, @@ -24,6 +26,7 @@ pub trait PaymentIntentInterface { async fn insert_payment_intent( &self, + state: &KeyManagerState, new: PaymentIntent, merchant_key_store: &MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, @@ -31,6 +34,7 @@ pub trait PaymentIntentInterface { async fn find_payment_intent_by_payment_id_merchant_id( &self, + state: &KeyManagerState, payment_id: &str, merchant_id: &str, merchant_key_store: &MerchantKeyStore, @@ -46,6 +50,7 @@ pub trait PaymentIntentInterface { #[cfg(feature = "olap")] async fn filter_payment_intent_by_constraints( &self, + state: &KeyManagerState, merchant_id: &str, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, @@ -55,6 +60,7 @@ pub trait PaymentIntentInterface { #[cfg(feature = "olap")] async fn filter_payment_intents_by_time_range_constraints( &self, + state: &KeyManagerState, merchant_id: &str, time_range: &api_models::payments::TimeRange, merchant_key_store: &MerchantKeyStore, @@ -64,6 +70,7 @@ pub trait PaymentIntentInterface { #[cfg(feature = "olap")] async fn get_filtered_payment_intents_attempt( &self, + state: &KeyManagerState, merchant_id: &str, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, @@ -467,7 +474,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { } use diesel_models::{ - encryption::Encryption, PaymentIntentUpdate as DieselPaymentIntentUpdate, + PaymentIntentUpdate as DieselPaymentIntentUpdate, PaymentIntentUpdateFields as DieselPaymentIntentUpdateFields, }; diff --git a/crates/hyperswitch_domain_models/src/type_encryption.rs b/crates/hyperswitch_domain_models/src/type_encryption.rs index 82d904ccf49..d656afc9251 100644 --- a/crates/hyperswitch_domain_models/src/type_encryption.rs +++ b/crates/hyperswitch_domain_models/src/type_encryption.rs @@ -1,14 +1,30 @@ use async_trait::async_trait; use common_utils::{ crypto, + encryption::Encryption, errors::{self, CustomResult}, ext_traits::AsyncExt, metrics::utils::record_operation_time, + types::keymanager::{Identifier, KeyManagerState}, }; -use diesel_models::encryption::Encryption; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use router_env::{instrument, tracing}; +use rustc_hash::FxHashMap; +#[cfg(feature = "encryption_service")] +use { + common_utils::{ + keymanager::call_encryption_service, + transformers::{ForeignFrom, ForeignTryFrom}, + types::keymanager::{ + BatchDecryptDataResponse, BatchEncryptDataRequest, BatchEncryptDataResponse, + DecryptDataResponse, EncryptDataRequest, EncryptDataResponse, + TransientBatchDecryptDataRequest, TransientDecryptDataRequest, + }, + }, + http::Method, + router_env::logger, +}; #[async_trait] pub trait TypeEncryption< @@ -17,6 +33,22 @@ pub trait TypeEncryption< S: masking::Strategy<T>, >: Sized { + async fn encrypt_via_api( + state: &KeyManagerState, + masked_data: Secret<T, S>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError>; + + async fn decrypt_via_api( + state: &KeyManagerState, + encrypted_data: Encryption, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError>; + async fn encrypt( masked_data: Secret<T, S>, key: &[u8], @@ -28,31 +60,141 @@ pub trait TypeEncryption< key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError>; + + async fn batch_encrypt_via_api( + state: &KeyManagerState, + masked_data: FxHashMap<String, Secret<T, S>>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; + + async fn batch_decrypt_via_api( + state: &KeyManagerState, + encrypted_data: FxHashMap<String, Encryption>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; + + async fn batch_encrypt( + masked_data: FxHashMap<String, Secret<T, S>>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; + + async fn batch_decrypt( + encrypted_data: FxHashMap<String, Encryption>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; } #[async_trait] impl< V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, - S: masking::Strategy<String> + Send, + S: masking::Strategy<String> + Send + Sync, > TypeEncryption<String, V, S> for crypto::Encryptable<Secret<String, S>> { #[instrument(skip_all)] + #[allow(unused_variables)] + async fn encrypt_via_api( + state: &KeyManagerState, + masked_data: Secret<String, S>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::encrypt(masked_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + EncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + EncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), + Err(err) => { + logger::error!("Encryption error {:?}", err); + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Encryption"); + Self::encrypt(masked_data, key, crypt_algo).await + } + } + } + } + + #[instrument(skip_all)] + #[allow(unused_variables)] + async fn decrypt_via_api( + state: &KeyManagerState, + encrypted_data: Encryption, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::decrypt(encrypted_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + DecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(decrypted_data) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::DecodingFailed)) + } + }; + + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::decrypt(encrypted_data, key, crypt_algo).await + } + } + } + } + async fn encrypt( masked_data: Secret<String, S>, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); let encrypted_data = crypt_algo.encode_message(key, masked_data.peek().as_bytes())?; - Ok(Self::new(masked_data, encrypted_data.into())) } - #[instrument(skip_all)] async fn decrypt( encrypted_data: Encryption, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); let encrypted = encrypted_data.into_inner(); let data = crypt_algo.decode_message(key, encrypted.clone())?; @@ -62,25 +204,227 @@ impl< Ok(Self::new(value.into(), encrypted)) } + + #[allow(unused_variables)] + async fn batch_encrypt_via_api( + state: &KeyManagerState, + masked_data: FxHashMap<String, Secret<String, S>>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_encrypt(masked_data, key, crypt_algo).await + } + + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchEncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + BatchEncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), + Err(err) => { + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::error!("Encryption error {:?}", err); + logger::info!("Fall back to Application Encryption"); + Self::batch_encrypt(masked_data, key, crypt_algo).await + } + } + } + } + + #[allow(unused_variables)] + async fn batch_decrypt_via_api( + state: &KeyManagerState, + encrypted_data: FxHashMap<String, Encryption>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } + + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchDecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(decrypted_data) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::DecodingFailed)) + } + }; + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } + } + } + } + + async fn batch_encrypt( + masked_data: FxHashMap<String, Secret<String, S>>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + masked_data + .into_iter() + .map(|(k, v)| { + Ok(( + k, + Self::new( + v.clone(), + crypt_algo.encode_message(key, v.peek().as_bytes())?.into(), + ), + )) + }) + .collect() + } + + async fn batch_decrypt( + encrypted_data: FxHashMap<String, Encryption>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + encrypted_data + .into_iter() + .map(|(k, v)| { + let data = crypt_algo.decode_message(key, v.clone().into_inner())?; + let value: String = std::str::from_utf8(&data) + .change_context(errors::CryptoError::DecodingFailed)? + .to_string(); + Ok((k, Self::new(value.into(), v.into_inner()))) + }) + .collect() + } } #[async_trait] impl< V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, - S: masking::Strategy<serde_json::Value> + Send, + S: masking::Strategy<serde_json::Value> + Send + Sync, > TypeEncryption<serde_json::Value, V, S> for crypto::Encryptable<Secret<serde_json::Value, S>> { + #[instrument(skip_all)] + #[allow(unused_variables)] + async fn encrypt_via_api( + state: &KeyManagerState, + masked_data: Secret<serde_json::Value, S>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::encrypt(masked_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + EncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + EncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), + Err(err) => { + logger::error!("Encryption error {:?}", err); + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Encryption"); + Self::encrypt(masked_data, key, crypt_algo).await + } + } + } + } + + #[instrument(skip_all)] + #[allow(unused_variables)] + async fn decrypt_via_api( + state: &KeyManagerState, + encrypted_data: Encryption, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::decrypt(encrypted_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + DecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(decrypted_data) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::EncodingFailed)) + } + }; + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::decrypt(encrypted_data, key, crypt_algo).await + } + } + } + } + #[instrument(skip_all)] async fn encrypt( masked_data: Secret<serde_json::Value, S>, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); let data = serde_json::to_vec(&masked_data.peek()) .change_context(errors::CryptoError::DecodingFailed)?; let encrypted_data = crypt_algo.encode_message(key, &data)?; - Ok(Self::new(masked_data, encrypted_data.into())) } @@ -90,30 +434,229 @@ impl< key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); let encrypted = encrypted_data.into_inner(); let data = crypt_algo.decode_message(key, encrypted.clone())?; let value: serde_json::Value = serde_json::from_slice(&data).change_context(errors::CryptoError::DecodingFailed)?; - Ok(Self::new(value.into(), encrypted)) } + + #[allow(unused_variables)] + async fn batch_encrypt_via_api( + state: &KeyManagerState, + masked_data: FxHashMap<String, Secret<serde_json::Value, S>>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_encrypt(masked_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchEncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + BatchEncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), + Err(err) => { + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::error!("Encryption error {:?}", err); + logger::info!("Fall back to Application Encryption"); + Self::batch_encrypt(masked_data, key, crypt_algo).await + } + } + } + } + + #[allow(unused_variables)] + async fn batch_decrypt_via_api( + state: &KeyManagerState, + encrypted_data: FxHashMap<String, Encryption>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchDecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(decrypted_data) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::DecodingFailed)) + } + }; + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } + } + } + } + + async fn batch_encrypt( + masked_data: FxHashMap<String, Secret<serde_json::Value, S>>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + masked_data + .into_iter() + .map(|(k, v)| { + let data = serde_json::to_vec(v.peek()) + .change_context(errors::CryptoError::DecodingFailed)?; + Ok(( + k, + Self::new(v, crypt_algo.encode_message(key, &data)?.into()), + )) + }) + .collect() + } + + async fn batch_decrypt( + encrypted_data: FxHashMap<String, Encryption>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + encrypted_data + .into_iter() + .map(|(k, v)| { + let data = crypt_algo.decode_message(key, v.clone().into_inner().clone())?; + + let value: serde_json::Value = serde_json::from_slice(&data) + .change_context(errors::CryptoError::DecodingFailed)?; + Ok((k, Self::new(value.into(), v.into_inner()))) + }) + .collect() + } } #[async_trait] impl< V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, - S: masking::Strategy<Vec<u8>> + Send, + S: masking::Strategy<Vec<u8>> + Send + Sync, > TypeEncryption<Vec<u8>, V, S> for crypto::Encryptable<Secret<Vec<u8>, S>> { + #[instrument(skip_all)] + #[allow(unused_variables)] + async fn encrypt_via_api( + state: &KeyManagerState, + masked_data: Secret<Vec<u8>, S>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::encrypt(masked_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + EncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + EncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), + Err(err) => { + logger::error!("Encryption error {:?}", err); + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Encryption"); + Self::encrypt(masked_data, key, crypt_algo).await + } + } + } + } + + #[instrument(skip_all)] + #[allow(unused_variables)] + async fn decrypt_via_api( + state: &KeyManagerState, + encrypted_data: Encryption, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<Self, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::decrypt(encrypted_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + DecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(decrypted_data) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::DecodingFailed)) + } + }; + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::decrypt(encrypted_data, key, crypt_algo).await + } + } + } + } + #[instrument(skip_all)] async fn encrypt( masked_data: Secret<Vec<u8>, S>, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); let encrypted_data = crypt_algo.encode_message(key, masked_data.peek())?; - Ok(Self::new(masked_data, encrypted_data.into())) } @@ -123,11 +666,131 @@ impl< key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); let encrypted = encrypted_data.into_inner(); let data = crypt_algo.decode_message(key, encrypted.clone())?; - Ok(Self::new(data.into(), encrypted)) } + + #[allow(unused_variables)] + async fn batch_encrypt_via_api( + state: &KeyManagerState, + masked_data: FxHashMap<String, Secret<Vec<u8>, S>>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_encrypt(masked_data, key, crypt_algo).await + } + + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchEncryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/encrypt", + BatchEncryptDataRequest::from((masked_data.clone(), identifier)), + ) + .await; + match result { + Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), + Err(err) => { + metrics::ENCRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::error!("Encryption error {:?}", err); + logger::info!("Fall back to Application Encryption"); + Self::batch_encrypt(masked_data, key, crypt_algo).await + } + } + } + } + + #[allow(unused_variables)] + async fn batch_decrypt_via_api( + state: &KeyManagerState, + encrypted_data: FxHashMap<String, Encryption>, + identifier: Identifier, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + #[cfg(not(feature = "encryption_service"))] + { + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } + #[cfg(feature = "encryption_service")] + { + let result: Result< + BatchDecryptDataResponse, + error_stack::Report<errors::KeyManagerClientError>, + > = call_encryption_service( + state, + Method::POST, + "data/decrypt", + TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), + ) + .await; + let decrypted = match result { + Ok(response) => { + ForeignTryFrom::foreign_try_from((encrypted_data.clone(), response)) + } + Err(err) => { + logger::error!("Decryption error {:?}", err); + Err(err.change_context(errors::CryptoError::DecodingFailed)) + } + }; + match decrypted { + Ok(de) => Ok(de), + Err(_) => { + metrics::DECRYPTION_API_FAILURES.add(&metrics::CONTEXT, 1, &[]); + logger::info!("Fall back to Application Decryption"); + Self::batch_decrypt(encrypted_data, key, crypt_algo).await + } + } + } + } + + async fn batch_encrypt( + masked_data: FxHashMap<String, Secret<Vec<u8>, S>>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_ENCRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + masked_data + .into_iter() + .map(|(k, v)| { + Ok(( + k, + Self::new(v.clone(), crypt_algo.encode_message(key, v.peek())?.into()), + )) + }) + .collect() + } + + async fn batch_decrypt( + encrypted_data: FxHashMap<String, Encryption>, + key: &[u8], + crypt_algo: V, + ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { + metrics::APPLICATION_DECRYPTION_COUNT.add(&metrics::CONTEXT, 1, &[]); + encrypted_data + .into_iter() + .map(|(k, v)| { + Ok(( + k, + Self::new( + crypt_algo + .decode_message(key, v.clone().into_inner().clone())? + .into(), + v.into_inner(), + ), + )) + }) + .collect() + } } pub trait Lift<U> { @@ -178,7 +841,9 @@ impl<U, V: Lift<U> + Lift<U, SelfWrapper<U> = V> + Send> AsyncLift<U> for V { #[inline] pub async fn encrypt<E: Clone, S>( + state: &KeyManagerState, inner: Secret<E, S>, + identifier: Identifier, key: &[u8], ) -> CustomResult<crypto::Encryptable<Secret<E, S>>, errors::CryptoError> where @@ -186,7 +851,7 @@ where crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, { record_operation_time( - crypto::Encryptable::encrypt(inner, key, crypto::GcmAes256), + crypto::Encryptable::encrypt_via_api(state, inner, identifier, key, crypto::GcmAes256), &metrics::ENCRYPTION_TIME, &metrics::CONTEXT, &[], @@ -194,9 +859,41 @@ where .await } +#[inline] +pub async fn batch_encrypt<E: Clone, S>( + state: &KeyManagerState, + inner: FxHashMap<String, Secret<E, S>>, + identifier: Identifier, + key: &[u8], +) -> CustomResult<FxHashMap<String, crypto::Encryptable<Secret<E, S>>>, errors::CryptoError> +where + S: masking::Strategy<E>, + crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, +{ + if !inner.is_empty() { + record_operation_time( + crypto::Encryptable::batch_encrypt_via_api( + state, + inner, + identifier, + key, + crypto::GcmAes256, + ), + &metrics::ENCRYPTION_TIME, + &metrics::CONTEXT, + &[], + ) + .await + } else { + Ok(FxHashMap::default()) + } +} + #[inline] pub async fn encrypt_optional<E: Clone, S>( + state: &KeyManagerState, inner: Option<Secret<E, S>>, + identifier: Identifier, key: &[u8], ) -> CustomResult<Option<crypto::Encryptable<Secret<E, S>>>, errors::CryptoError> where @@ -204,19 +901,26 @@ where S: masking::Strategy<E>, crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, { - inner.async_map(|f| encrypt(f, key)).await.transpose() + inner + .async_map(|f| encrypt(state, f, identifier, key)) + .await + .transpose() } #[inline] pub async fn decrypt<T: Clone, S: masking::Strategy<T>>( + state: &KeyManagerState, inner: Option<Encryption>, + identifier: Identifier, key: &[u8], ) -> CustomResult<Option<crypto::Encryptable<Secret<T, S>>>, errors::CryptoError> where crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>, { record_operation_time( - inner.async_map(|item| crypto::Encryptable::decrypt(item, key, crypto::GcmAes256)), + inner.async_map(|item| { + crypto::Encryptable::decrypt_via_api(state, item, identifier, key, crypto::GcmAes256) + }), &metrics::DECRYPTION_TIME, &metrics::CONTEXT, &[], @@ -225,8 +929,38 @@ where .transpose() } +#[inline] +pub async fn batch_decrypt<E: Clone, S>( + state: &KeyManagerState, + inner: FxHashMap<String, Encryption>, + identifier: Identifier, + key: &[u8], +) -> CustomResult<FxHashMap<String, crypto::Encryptable<Secret<E, S>>>, errors::CryptoError> +where + S: masking::Strategy<E>, + crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, +{ + if !inner.is_empty() { + record_operation_time( + crypto::Encryptable::batch_decrypt_via_api( + state, + inner, + identifier, + key, + crypto::GcmAes256, + ), + &metrics::ENCRYPTION_TIME, + &metrics::CONTEXT, + &[], + ) + .await + } else { + Ok(FxHashMap::default()) + } +} + pub(crate) mod metrics { - use router_env::{global_meter, histogram_metric, metrics_context, once_cell}; + use router_env::{counter_metric, global_meter, histogram_metric, metrics_context, once_cell}; metrics_context!(CONTEXT); global_meter!(GLOBAL_METER, "ROUTER_API"); @@ -234,4 +968,8 @@ pub(crate) mod metrics { // Encryption and Decryption metrics histogram_metric!(ENCRYPTION_TIME, GLOBAL_METER); histogram_metric!(DECRYPTION_TIME, GLOBAL_METER); + counter_metric!(ENCRYPTION_API_FAILURES, GLOBAL_METER); + counter_metric!(DECRYPTION_API_FAILURES, GLOBAL_METER); + counter_metric!(APPLICATION_ENCRYPTION_COUNT, GLOBAL_METER); + counter_metric!(APPLICATION_DECRYPTION_COUNT, GLOBAL_METER); } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 1379b17eec4..b9488a0804e 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -11,12 +11,13 @@ license.workspace = true [features] default = ["kv_store", "stripe", "oltp", "olap", "accounts_cache", "dummy_connector", "payouts", "payout_retry", "retry", "frm", "tls"] tls = ["actix-web/rustls-0_22"] -keymanager_mtls = ["reqwest/rustls-tls", "common_utils/keymanager_mtls"] +keymanager_mtls = ["reqwest/rustls-tls","common_utils/keymanager_mtls"] +encryption_service = ["hyperswitch_domain_models/encryption_service", "common_utils/encryption_service"] email = ["external_services/email", "scheduler/email", "olap"] keymanager_create = [] frm = ["api_models/frm", "hyperswitch_domain_models/frm"] stripe = ["dep:serde_qs"] -release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3", "keymanager_mtls", "keymanager_create"] +release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3", "keymanager_mtls", "keymanager_create", "encryption_service"] olap = ["hyperswitch_domain_models/olap", "storage_impl/olap", "scheduler/olap", "api_models/olap", "dep:analytics"] oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"] @@ -114,7 +115,7 @@ analytics = { version = "0.1.0", path = "../analytics", optional = true } api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] } cards = { version = "0.1.0", path = "../cards" } common_enums = { version = "0.1.0", path = "../common_enums" } -common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics", "keymanager"] } +common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics", "keymanager", "encryption_service"] } currency_conversion = { version = "0.1.0", path = "../currency_conversion" } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } euclid = { version = "0.1.0", path = "../euclid", features = ["valued_jit"] } diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index 61f9c473a22..269c7d5b3b4 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -38,7 +38,11 @@ async fn main() -> CustomResult<(), ProcessTrackerError> { let api_client = Box::new( services::ProxyClient::new( conf.proxy.clone(), - services::proxy_bypass_urls(&conf.locker, &conf.proxy.bypass_proxy_urls), + services::proxy_bypass_urls( + conf.key_manager.get_inner(), + &conf.locker, + &conf.proxy.bypass_proxy_urls, + ), ) .change_context(ProcessTrackerError::ConfigurationError)?, ); diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index d3091875f48..bdf8db2828e 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -2,6 +2,7 @@ pub mod opensearch; #[cfg(feature = "olap")] pub mod user; pub mod user_role; +use common_utils::consts; pub use hyperswitch_interfaces::consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}; // ID generation pub(crate) const ID_LENGTH: usize = 20; @@ -43,8 +44,9 @@ pub(crate) const CANNOT_CONTINUE_AUTH: &str = pub(crate) const DEFAULT_NOTIFICATION_SCRIPT_LANGUAGE: &str = "en-US"; // General purpose base64 engines -pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose = - base64::engine::general_purpose::STANDARD; + +pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose = consts::BASE64_ENGINE; + pub(crate) const BASE64_ENGINE_URL_SAFE: base64::engine::GeneralPurpose = base64::engine::general_purpose::URL_SAFE; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 8a7854d658b..a851be95d5e 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -8,9 +8,8 @@ use common_utils::{ date_time, ext_traits::{AsyncExt, ConfigExt, Encode, ValueExt}, id_type, pii, + types::keymanager as km_types, }; -#[cfg(all(feature = "keymanager_create", feature = "olap"))] -use common_utils::{keymanager, types::keymanager as km_types}; use diesel_models::configs; use error_stack::{report, FutureExt, ResultExt}; use futures::future::try_join_all; @@ -111,6 +110,9 @@ pub async fn create_merchant_account( state: SessionState, req: api::MerchantAccountCreate, ) -> RouterResponse<api::MerchantAccountResponse> { + #[cfg(feature = "keymanager_create")] + use common_utils::keymanager; + let db = state.store.as_ref(); let key = services::generate_aes256_key() @@ -119,27 +121,16 @@ pub async fn create_merchant_account( let master_key = db.get_master_key(); + let key_manager_state = &(&state).into(); let merchant_id = req.get_merchant_reference_id().get_string_repr().to_owned(); - - let key_store = domain::MerchantKeyStore { - merchant_id: merchant_id.clone(), - key: domain_types::encrypt(key.to_vec().into(), master_key) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to decrypt data from key store")?, - created_at: date_time::now(), - }; - - let domain_merchant_account = req - .create_domain_model_from_request(db, key_store.clone()) - .await?; + let identifier = km_types::Identifier::Merchant(merchant_id.clone()); #[cfg(feature = "keymanager_create")] { keymanager::create_key_in_key_manager( - &(&state).into(), + key_manager_state, km_types::EncryptionCreateRequest { - identifier: km_types::Identifier::Merchant(merchant_id.clone()), + identifier: identifier.clone(), }, ) .await @@ -147,12 +138,34 @@ pub async fn create_merchant_account( .attach_printable("Failed to insert key to KeyManager")?; } - db.insert_merchant_key_store(key_store.clone(), &master_key.to_vec().into()) + let key_store = domain::MerchantKeyStore { + merchant_id: merchant_id.clone(), + key: domain_types::encrypt( + key_manager_state, + key.to_vec().into(), + identifier.clone(), + master_key, + ) .await - .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to decrypt data from key store")?, + created_at: date_time::now(), + }; + + let domain_merchant_account = req + .create_domain_model_from_request(&state, key_store.clone()) + .await?; + let key_manager_state = &(&state).into(); + db.insert_merchant_key_store( + key_manager_state, + key_store.clone(), + &master_key.to_vec().into(), + ) + .await + .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; let merchant_account = db - .insert_merchant(domain_merchant_account, &key_store) + .insert_merchant(key_manager_state, domain_merchant_account, &key_store) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; @@ -172,7 +185,7 @@ pub async fn create_merchant_account( trait MerchantAccountCreateBridge { async fn create_domain_model_from_request( self, - db: &dyn StorageInterface, + state: &SessionState, key: domain::MerchantKeyStore, ) -> RouterResult<domain::MerchantAccount>; } @@ -182,9 +195,10 @@ trait MerchantAccountCreateBridge { impl MerchantAccountCreateBridge for api::MerchantAccountCreate { async fn create_domain_model_from_request( self, - db: &dyn StorageInterface, + state: &SessionState, key_store: domain::MerchantKeyStore, ) -> RouterResult<domain::MerchantAccount> { + let db = &*state.store; let publishable_key = create_merchant_publishable_key(); let primary_business_details = self.get_primary_details_as_value().change_context( @@ -229,7 +243,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { let payment_response_hash_key = self.get_payment_response_hash_key(); let parent_merchant_id = get_parent_merchant( - db, + state, self.sub_merchants_enabled, self.parent_merchant_id, &key_store, @@ -241,6 +255,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { .await?; let key = key_store.key.clone().into_inner(); + let key_manager_state = state.into(); let mut merchant_account = async { Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( @@ -248,10 +263,24 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { merchant_id: self.merchant_id.get_string_repr().to_owned(), merchant_name: self .merchant_name - .async_lift(|inner| domain_types::encrypt_optional(inner, key.peek())) + .async_lift(|inner| { + domain_types::encrypt_optional( + &key_manager_state, + inner, + km_types::Identifier::Merchant(key_store.merchant_id.clone()), + key.peek(), + ) + }) .await?, merchant_details: merchant_details - .async_lift(|inner| domain_types::encrypt_optional(inner, key.peek())) + .async_lift(|inner| { + domain_types::encrypt_optional( + &key_manager_state, + inner, + km_types::Identifier::Merchant(key_store.merchant_id.clone()), + key.peek(), + ) + }) .await?, return_url: self.return_url.map(|a| a.to_string()), webhook_details, @@ -293,7 +322,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { .change_context(errors::ApiErrorResponse::InternalServerError)?; CreateBusinessProfile::new(self.primary_business_details.clone()) - .create_business_profiles(db, &mut merchant_account, &key_store) + .create_business_profiles(state, &mut merchant_account, &key_store) .await?; Ok(merchant_account) @@ -385,7 +414,7 @@ impl CreateBusinessProfile { async fn create_business_profiles( &self, - db: &dyn StorageInterface, + state: &SessionState, merchant_account: &mut domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<()> { @@ -394,7 +423,7 @@ impl CreateBusinessProfile { primary_business_details, } => { let business_profiles = Self::create_business_profiles_for_each_business_details( - db, + state, merchant_account.clone(), primary_business_details, key_store, @@ -410,7 +439,7 @@ impl CreateBusinessProfile { } Self::CreateDefaultBusinessProfile => { let business_profile = self - .create_default_business_profile(db, merchant_account.clone(), key_store) + .create_default_business_profile(state, merchant_account.clone(), key_store) .await?; merchant_account.default_profile = Some(business_profile.profile_id); @@ -423,12 +452,12 @@ impl CreateBusinessProfile { /// Create default business profile async fn create_default_business_profile( &self, - db: &dyn StorageInterface, + state: &SessionState, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<diesel_models::business_profile::BusinessProfile> { let business_profile = create_and_insert_business_profile( - db, + state, api_models::admin::BusinessProfileCreate::default(), merchant_account.clone(), key_store, @@ -442,7 +471,7 @@ impl CreateBusinessProfile { /// If there is no default profile in merchant account and only one primary_business_detail /// is available, then create a default business profile. async fn create_business_profiles_for_each_business_details( - db: &dyn StorageInterface, + state: &SessionState, merchant_account: domain::MerchantAccount, primary_business_details: &Vec<admin_types::PrimaryBusinessDetails>, key_store: &domain::MerchantKeyStore, @@ -462,7 +491,7 @@ impl CreateBusinessProfile { }; create_and_insert_business_profile( - db, + state, business_profile_create_request, merchant_account.clone(), key_store, @@ -486,10 +515,11 @@ impl CreateBusinessProfile { impl MerchantAccountCreateBridge for api::MerchantAccountCreate { async fn create_domain_model_from_request( self, - db: &dyn StorageInterface, + state: &SessionState, key_store: domain::MerchantKeyStore, ) -> RouterResult<domain::MerchantAccount> { let publishable_key = create_merchant_publishable_key(); + let db = &*state.store; let metadata = self.get_metadata_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { @@ -514,24 +544,36 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { .await?; let key = key_store.key.into_inner(); + let merchant_id = self + .get_merchant_reference_id() + .get_string_repr() + .to_owned(); + let key_manager_state = state.into(); + let identifier = km_types::Identifier::Merchant(merchant_id.clone()); async { Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( domain::MerchantAccount { - merchant_id: self - .get_merchant_reference_id() - .get_string_repr() - .to_owned(), + merchant_id, merchant_name: Some( domain_types::encrypt( + &key_manager_state, self.merchant_name .map(|merchant_name| merchant_name.into_inner()), + identifier.clone(), key.peek(), ) .await?, ), merchant_details: merchant_details - .async_lift(|inner| domain_types::encrypt_optional(inner, key.peek())) + .async_lift(|inner| { + domain_types::encrypt_optional( + &key_manager_state, + inner, + identifier.clone(), + key.peek(), + ) + }) .await?, return_url: None, webhook_details: None, @@ -577,7 +619,7 @@ pub async fn list_merchant_account( ) -> RouterResponse<Vec<api::MerchantAccountResponse>> { let merchant_accounts = state .store - .list_merchant_accounts_by_organization_id(&req.organization_id) + .list_merchant_accounts_by_organization_id(&(&state).into(), &req.organization_id) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -600,8 +642,10 @@ pub async fn get_merchant_account( req: api::MerchantId, ) -> RouterResponse<api::MerchantAccountResponse> { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( + key_manager_state, &req.merchant_id, &db.get_master_key().to_vec().into(), ) @@ -609,7 +653,7 @@ pub async fn get_merchant_account( .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db - .find_merchant_account_by_merchant_id(&req.merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &req.merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -623,13 +667,15 @@ pub async fn get_merchant_account( /// For backwards compatibility, whenever new business labels are passed in /// primary_business_details, create a business profile pub async fn create_business_profile_from_business_labels( + state: &SessionState, db: &dyn StorageInterface, key_store: &domain::MerchantKeyStore, merchant_id: &str, new_business_details: Vec<admin_types::PrimaryBusinessDetails>, ) -> RouterResult<()> { + let key_manager_state = &state.into(); let merchant_account = db - .find_merchant_account_by_merchant_id(merchant_id, key_store) + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -657,7 +703,7 @@ pub async fn create_business_profile_from_business_labels( }; let business_profile_create_result = create_and_insert_business_profile( - db, + state, business_profile_create_request, merchant_account.clone(), key_store, @@ -673,9 +719,14 @@ pub async fn create_business_profile_from_business_labels( // If a business_profile is created, then unset the default profile if business_profile_create_result.is_ok() && merchant_account.default_profile.is_some() { let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile; - db.update_merchant(merchant_account.clone(), unset_default_profile, key_store) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + db.update_merchant( + key_manager_state, + merchant_account.clone(), + unset_default_profile, + key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; } } @@ -758,8 +809,10 @@ pub async fn merchant_account_update( req: api::MerchantAccountUpdate, ) -> RouterResponse<api::MerchantAccountResponse> { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( + key_manager_state, &req.merchant_id, &db.get_master_key().to_vec().into(), ) @@ -817,6 +870,7 @@ pub async fn merchant_account_update( .clone() .async_map(|primary_business_details| async { let _ = create_business_profile_from_business_labels( + &state, db, &key_store, merchant_id, @@ -845,11 +899,14 @@ pub async fn merchant_account_update( // Update the business profile, This is for backwards compatibility update_business_profile_cascade(state.clone(), req.clone(), merchant_id.to_string()).await?; + let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone()); let updated_merchant_account = storage::MerchantAccountUpdate::Update { merchant_name: req .merchant_name .map(Secret::new) - .async_lift(|inner| domain_types::encrypt_optional(inner, key)) + .async_lift(|inner| { + domain_types::encrypt_optional(key_manager_state, inner, identifier.clone(), key) + }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt merchant name")?, @@ -862,7 +919,9 @@ pub async fn merchant_account_update( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to convert merchant_details to a value")? .map(Secret::new) - .async_lift(|inner| domain_types::encrypt_optional(inner, key)) + .async_lift(|inner| { + domain_types::encrypt_optional(key_manager_state, inner, identifier.clone(), key) + }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt merchant details")?, @@ -880,7 +939,7 @@ pub async fn merchant_account_update( sub_merchants_enabled: req.sub_merchants_enabled, parent_merchant_id: get_parent_merchant( - db, + &state, req.sub_merchants_enabled, req.parent_merchant_id, &key_store, @@ -905,7 +964,12 @@ pub async fn merchant_account_update( }; let response = db - .update_specific_fields_in_merchant(merchant_id, updated_merchant_account, &key_store) + .update_specific_fields_in_merchant( + key_manager_state, + merchant_id, + updated_merchant_account, + &key_store, + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -924,9 +988,10 @@ pub async fn merchant_account_delete( ) -> RouterResponse<api::MerchantAccountDeleteResponse> { let mut is_deleted = false; let db = state.store.as_ref(); - + let key_manager_state = &(&state).into(); let merchant_key_store = db .get_merchant_key_store_by_merchant_id( + key_manager_state, &merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -934,7 +999,7 @@ pub async fn merchant_account_delete( .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db - .find_merchant_account_by_merchant_id(&merchant_id, &merchant_key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &merchant_key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -988,7 +1053,7 @@ pub async fn merchant_account_delete( } async fn get_parent_merchant( - db: &dyn StorageInterface, + state: &SessionState, sub_merchants_enabled: Option<bool>, parent_merchant: Option<String>, key_store: &domain::MerchantKeyStore, @@ -1004,7 +1069,7 @@ async fn get_parent_merchant( message: "If `sub_merchants_enabled` is `true`, then `parent_merchant_id` is mandatory".to_string(), }) }) - .map(|id| validate_merchant_id(db, id,key_store).change_context( + .map(|id| validate_merchant_id(state, id,key_store).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "parent_merchant_id" } ))? .await? @@ -1016,11 +1081,12 @@ async fn get_parent_merchant( } async fn validate_merchant_id<S: Into<String>>( - db: &dyn StorageInterface, + state: &SessionState, merchant_id: S, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::MerchantAccount> { - db.find_merchant_account_by_merchant_id(&merchant_id.into(), key_store) + let db = &*state.store; + db.find_merchant_account_by_merchant_id(&state.into(), &merchant_id.into(), key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) } @@ -1066,10 +1132,12 @@ pub async fn create_payment_connector( merchant_id: &String, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); + let key_manager_state = &(&state).into(); #[cfg(feature = "dummy_connector")] validate_dummy_connector_enabled(&state, &req.connector_name).await?; let key_store = store .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -1083,7 +1151,7 @@ pub async fn create_payment_connector( let merchant_account = state .store - .find_merchant_account_by_merchant_id(merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -1221,6 +1289,7 @@ pub async fn create_payment_connector( state .store .update_specific_fields_in_merchant( + key_manager_state, merchant_id, storage::MerchantAccountUpdate::ModifiedAtUpdate, &key_store, @@ -1242,7 +1311,7 @@ pub async fn create_payment_connector( if let Some(val) = req.pm_auth_config.clone() { validate_pm_auth( val, - &*state.clone().store, + &state, merchant_id.clone().as_str(), &key_store, merchant_account, @@ -1256,14 +1325,15 @@ pub async fn create_payment_connector( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encoding ConnectorAuthType to serde_json::Value")?; let conn_auth = Secret::new(connector_auth); - + let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone()); let merchant_connector_account = domain::MerchantConnectorAccount { merchant_id: merchant_id.to_string(), connector_type: req.connector_type, connector_name: req.connector_name.to_string(), merchant_connector_id: utils::generate_id(consts::ID_LENGTH, "mca"), - connector_account_details: domain_types::encrypt( + connector_account_details: domain_types::encrypt(key_manager_state, conn_auth, + identifier.clone(), key_store.key.peek(), ) .await @@ -1296,10 +1366,11 @@ pub async fn create_payment_connector( applepay_verified_domains: None, pm_auth_config: req.pm_auth_config.clone(), status: connector_status, - connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(&key_store, &req.metadata).await?, + connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(&state, &key_store, &req.metadata).await?, additional_merchant_data: if let Some(mcd) = merchant_recipient_data { - Some(domain_types::encrypt( + Some(domain_types::encrypt(key_manager_state, Secret::new(mcd), + identifier, key_store.key.peek(), ) .await @@ -1329,7 +1400,11 @@ pub async fn create_payment_connector( let mca = state .store - .insert_merchant_connector_account(merchant_connector_account, &key_store) + .insert_merchant_connector_account( + key_manager_state, + merchant_connector_account, + &key_store, + ) .await .to_duplicate_response( errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { @@ -1382,7 +1457,7 @@ pub async fn create_payment_connector( async fn validate_pm_auth( val: serde_json::Value, - db: &dyn StorageInterface, + state: &SessionState, merchant_id: &str, key_store: &domain::MerchantKeyStore, merchant_account: domain::MerchantAccount, @@ -1394,8 +1469,10 @@ async fn validate_pm_auth( }) .attach_printable("Failed to deserialize Payment Method Auth config")?; - let all_mcas = db + let all_mcas = &*state + .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( + &state.into(), merchant_id, true, key_store, @@ -1407,8 +1484,7 @@ async fn validate_pm_auth( for conn_choice in config.enabled_payment_methods { let pm_auth_mca = all_mcas - .clone() - .into_iter() + .iter() .find(|mca| mca.merchant_connector_id == conn_choice.mca_id) .ok_or(errors::ApiErrorResponse::GenericNotFoundError { message: "payment method auth connector account not found".to_string(), @@ -1432,8 +1508,10 @@ pub async fn retrieve_payment_connector( merchant_connector_id: String, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = store .get_merchant_key_store_by_merchant_id( + key_manager_state, &merchant_id, &store.get_master_key().to_vec().into(), ) @@ -1441,12 +1519,13 @@ pub async fn retrieve_payment_connector( .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let _merchant_account = store - .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let mca = store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, &merchant_id, &merchant_connector_id, &key_store, @@ -1464,8 +1543,10 @@ pub async fn list_payment_connectors( merchant_id: String, ) -> RouterResponse<Vec<api_models::admin::MerchantConnectorResponse>> { let store = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = store .get_merchant_key_store_by_merchant_id( + key_manager_state, &merchant_id, &store.get_master_key().to_vec().into(), ) @@ -1474,12 +1555,13 @@ pub async fn list_payment_connectors( // Validate merchant account store - .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_connector_accounts = store .find_merchant_connector_account_by_merchant_id_and_disabled_list( + key_manager_state, &merchant_id, true, &key_store, @@ -1503,18 +1585,24 @@ pub async fn update_payment_connector( req: api_models::admin::MerchantConnectorUpdate, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = db - .get_merchant_key_store_by_merchant_id(merchant_id, &db.get_master_key().to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &db.get_master_key().to_vec().into(), + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db - .find_merchant_account_by_merchant_id(merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, merchant_id, merchant_connector_id, &key_store, @@ -1559,7 +1647,7 @@ pub async fn update_payment_connector( if let Some(val) = req.pm_auth_config.clone() { validate_pm_auth( val, - db, + &state, merchant_id, &key_store, merchant_account, @@ -1568,7 +1656,6 @@ pub async fn update_payment_connector( .await?; } } - let payment_connector = storage::MerchantConnectorAccountUpdate::Update { merchant_id: None, connector_type: Some(req.connector_type), @@ -1578,7 +1665,12 @@ pub async fn update_payment_connector( connector_account_details: req .connector_account_details .async_lift(|inner| { - domain_types::encrypt_optional(inner, key_store.key.get_inner().peek()) + domain_types::encrypt_optional( + key_manager_state, + inner, + km_types::Identifier::Merchant(key_store.merchant_id.clone()), + key_store.key.get_inner().peek(), + ) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1600,7 +1692,7 @@ pub async fn update_payment_connector( pm_auth_config: req.pm_auth_config, status: Some(connector_status), connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details( - &key_store, &metadata, + &state, &key_store, &metadata, ) .await?, }; @@ -1615,7 +1707,12 @@ pub async fn update_payment_connector( let request_connector_label = req.connector_label; let updated_mca = db - .update_merchant_connector_account(mca, payment_connector.into(), &key_store) + .update_merchant_connector_account( + key_manager_state, + mca, + payment_connector.into(), + &key_store, + ) .await .change_context( errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { @@ -1638,18 +1735,24 @@ pub async fn delete_payment_connector( merchant_connector_id: String, ) -> RouterResponse<api::MerchantConnectorDeleteResponse> { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = db - .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &merchant_id, + &db.get_master_key().to_vec().into(), + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let _merchant_account = db - .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let _mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, &merchant_id, &merchant_connector_id, &key_store, @@ -1683,14 +1786,19 @@ pub async fn kv_for_merchant( enable: bool, ) -> RouterResponse<api_models::admin::ToggleKVResponse> { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = db - .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &merchant_id, + &db.get_master_key().to_vec().into(), + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // check if the merchant account exists let merchant_account = db - .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -1707,6 +1815,7 @@ pub async fn kv_for_merchant( } db.update_merchant( + key_manager_state, merchant_account, storage::MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme: MerchantStorageScheme::RedisKv, @@ -1717,6 +1826,7 @@ pub async fn kv_for_merchant( } (false, MerchantStorageScheme::RedisKv) => { db.update_merchant( + key_manager_state, merchant_account, storage::MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme: MerchantStorageScheme::PostgresOnly, @@ -1779,14 +1889,19 @@ pub async fn check_merchant_account_kv_status( merchant_id: String, ) -> RouterResponse<api_models::admin::ToggleKVResponse> { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = db - .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &merchant_id, + &db.get_master_key().to_vec().into(), + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // check if the merchant account exists let merchant_account = db - .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -1825,17 +1940,19 @@ pub fn get_frm_config_as_secret( } pub async fn create_and_insert_business_profile( - db: &dyn StorageInterface, + state: &SessionState, request: api::BusinessProfileCreate, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<storage::business_profile::BusinessProfile> { let business_profile_new = - admin::create_business_profile(merchant_account, request, key_store).await?; + admin::create_business_profile(state, merchant_account, request, key_store).await?; let profile_name = business_profile_new.profile_name.clone(); - db.insert_business_profile(business_profile_new) + state + .store + .insert_business_profile(business_profile_new) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( @@ -1859,15 +1976,20 @@ pub async fn create_business_profile( } let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = db - .get_merchant_key_store_by_merchant_id(merchant_id, &db.get_master_key().to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &db.get_master_key().to_vec().into(), + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // Get the merchant account, if few fields are not passed, then they will be inherited from // merchant account let merchant_account = db - .find_merchant_account_by_merchant_id(merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -1882,18 +2004,23 @@ pub async fn create_business_profile( } let business_profile = - create_and_insert_business_profile(db, request, merchant_account.clone(), &key_store) + create_and_insert_business_profile(&state, request, merchant_account.clone(), &key_store) .await?; if merchant_account.default_profile.is_some() { let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile; - db.update_merchant(merchant_account, unset_default_profile, &key_store) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + db.update_merchant( + key_manager_state, + merchant_account, + unset_default_profile, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; } Ok(service_api::ApplicationResponse::Json( - admin::business_profile_response(business_profile, &key_store) + admin::business_profile_response(&state, business_profile, &key_store) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details") .await?, @@ -1906,7 +2033,11 @@ pub async fn list_business_profile( ) -> RouterResponse<Vec<api_models::admin::BusinessProfileResponse>> { let db = state.store.as_ref(); let key_store = db - .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into()) + .get_merchant_key_store_by_merchant_id( + &(&state).into(), + &merchant_id, + &db.get_master_key().to_vec().into(), + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let profiles = db @@ -1916,7 +2047,7 @@ pub async fn list_business_profile( .clone(); let mut business_profiles = Vec::new(); for profile in profiles { - let business_profile = admin::business_profile_response(profile, &key_store) + let business_profile = admin::business_profile_response(&state, profile, &key_store) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details")?; @@ -1933,7 +2064,11 @@ pub async fn retrieve_business_profile( ) -> RouterResponse<api_models::admin::BusinessProfileResponse> { let db = state.store.as_ref(); let key_store = db - .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into()) + .get_merchant_key_store_by_merchant_id( + &(&state).into(), + &merchant_id, + &db.get_master_key().to_vec().into(), + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let business_profile = db @@ -1944,7 +2079,7 @@ pub async fn retrieve_business_profile( })?; Ok(service_api::ApplicationResponse::Json( - admin::business_profile_response(business_profile, &key_store) + admin::business_profile_response(&state, business_profile, &key_store) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details") .await?, @@ -1982,6 +2117,7 @@ pub async fn update_business_profile( })?; let key_store = db .get_merchant_key_store_by_merchant_id( + &(&state).into(), merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -2051,7 +2187,7 @@ pub async fn update_business_profile( .map(Secret::new); let outgoing_webhook_custom_http_headers = request .outgoing_webhook_custom_http_headers - .async_map(|headers| create_encrypted_data(&key_store, headers)) + .async_map(|headers| create_encrypted_data(&state, &key_store, headers)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -2119,7 +2255,7 @@ pub async fn update_business_profile( })?; Ok(service_api::ApplicationResponse::Json( - admin::business_profile_response(updated_business_profile, &key_store) + admin::business_profile_response(&state, updated_business_profile, &key_store) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details") .await?, diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index df8a55cd718..6af82a6b7a8 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -122,6 +122,7 @@ pub async fn create_api_key( // non-existence of a merchant account. store .get_merchant_key_store_by_merchant_id( + &(&state).into(), merchant_id.as_str(), &store.get_master_key().to_vec().into(), ) diff --git a/crates/router/src/core/apple_pay_certificates_migration.rs b/crates/router/src/core/apple_pay_certificates_migration.rs index 327358bda50..87c15935715 100644 --- a/crates/router/src/core/apple_pay_certificates_migration.rs +++ b/crates/router/src/core/apple_pay_certificates_migration.rs @@ -1,5 +1,5 @@ use api_models::apple_pay_certificates_migration; -use common_utils::errors::CustomResult; +use common_utils::{errors::CustomResult, types::keymanager::Identifier}; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; @@ -28,11 +28,12 @@ pub async fn apple_pay_certificates_migration( let mut migration_successful_merchant_ids = vec![]; let mut migration_failed_merchant_ids = vec![]; - + let key_manager_state = &(&state).into(); for merchant_id in merchant_id_list { let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -41,6 +42,7 @@ pub async fn apple_pay_certificates_migration( let merchant_connector_accounts = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( + key_manager_state, merchant_id, true, &key_store, @@ -63,11 +65,13 @@ pub async fn apple_pay_certificates_migration( .ok(); if let Some(apple_pay_metadata) = connector_apple_pay_metadata { let encrypted_apple_pay_metadata = domain_types::encrypt( + &(&state).into(), Secret::new( serde_json::to_value(apple_pay_metadata) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize apple pay metadata as JSON")?, ), + Identifier::Merchant(merchant_id.clone()), key_store.key.get_inner().peek(), ) .await diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs index 97324effa80..c739a86ee51 100644 --- a/crates/router/src/core/blocklist/utils.rs +++ b/crates/router/src/core/blocklist/utils.rs @@ -398,6 +398,7 @@ where if should_payment_be_blocked { // Update db for attempt and intent status. db.update_payment_intent( + &state.into(), payment_data.payment_intent.clone(), storage::PaymentIntentUpdate::RejectUpdate { status: common_enums::IntentStatus::Failed, diff --git a/crates/router/src/core/cards_info.rs b/crates/router/src/core/cards_info.rs index b0c1aca5322..98719b5a1e6 100644 --- a/crates/router/src/core/cards_info.rs +++ b/crates/router/src/core/cards_info.rs @@ -30,7 +30,7 @@ pub async fn retrieve_card_info( verify_iin_length(&request.card_iin)?; helpers::verify_payment_intent_time_and_client_secret( - db, + &state, &merchant_account, &key_store, request.client_secret, diff --git a/crates/router/src/core/conditional_config.rs b/crates/router/src/core/conditional_config.rs index f740c6dfcc2..c34f8e7116d 100644 --- a/crates/router/src/core/conditional_config.rs +++ b/crates/router/src/core/conditional_config.rs @@ -102,7 +102,7 @@ pub async fn upsert_conditional_config( algo_id.update_conditional_config_id(key.clone()); let config_key = cache::CacheKind::DecisionManager(key.into()); - update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) + update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; @@ -138,7 +138,7 @@ pub async fn upsert_conditional_config( algo_id.update_conditional_config_id(key.clone()); let config_key = cache::CacheKind::DecisionManager(key.into()); - update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) + update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; @@ -168,7 +168,7 @@ pub async fn delete_conditional_config( .unwrap_or_default(); algo_id.config_algo_id = None; let config_key = cache::CacheKind::DecisionManager(key.clone().into()); - update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) + update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update deleted algorithm ref")?; diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index c0e0291b8c4..e9126200acc 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -1,10 +1,12 @@ +use api_models::customers::CustomerRequestWithEmail; use common_utils::{ crypto::{Encryptable, GcmAes256}, errors::ReportSwitchExt, ext_traits::OptionExt, + types::keymanager::{Identifier, ToEncryptable}, }; use error_stack::{report, ResultExt}; -use masking::ExposeInterface; +use masking::{Secret, SwitchStrategy}; use router_env::{instrument, tracing}; use crate::{ @@ -19,7 +21,7 @@ use crate::{ api::customers, domain::{ self, - types::{self, AsyncLift, TypeEncryption}, + types::{self, TypeEncryption}, }, storage::{self, enums}, }, @@ -43,6 +45,7 @@ pub async fn create_customer( let merchant_id = &merchant_account.merchant_id; merchant_id.clone_into(&mut customer_data.merchant_id); + let key_manager_state = &(&state).into(); // We first need to validate whether the customer with the given customer id already exists // this may seem like a redundant db call, as the insert_customer will anyway return this error @@ -51,6 +54,7 @@ pub async fn create_customer( // it errors out, now the address that was inserted is not deleted match db .find_customer_by_customer_id_merchant_id( + key_manager_state, &customer_id, merchant_id, &key_store, @@ -76,6 +80,7 @@ pub async fn create_customer( let address = customer_data .get_domain_address( + &state, customer_address, merchant_id, &customer_id, @@ -87,7 +92,7 @@ pub async fn create_customer( .attach_printable("Failed while encrypting address")?; Some( - db.insert_address_for_customers(address, &key_store) + db.insert_address_for_customers(key_manager_state, address, &key_store) .await .switch() .attach_printable("Failed while inserting new address")?, @@ -96,40 +101,46 @@ pub async fn create_customer( None }; - let new_customer = async { - Ok(domain::Customer { - customer_id: customer_id.to_owned(), - merchant_id: merchant_id.to_string(), - name: customer_data - .name - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - email: customer_data - .email - .async_lift(|inner| types::encrypt_optional(inner.map(|inner| inner.expose()), key)) - .await?, - phone: customer_data - .phone - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - description: customer_data.description, - phone_country_code: customer_data.phone_country_code, - metadata: customer_data.metadata, - id: None, - connector_customer: None, - address_id: address.clone().map(|addr| addr.address_id), - created_at: common_utils::date_time::now(), - modified_at: common_utils::date_time::now(), - default_payment_method_id: None, - updated_by: None, - }) - } + let encrypted_data = types::batch_encrypt( + &(&state).into(), + CustomerRequestWithEmail::to_encryptable(CustomerRequestWithEmail { + name: customer_data.name.clone(), + email: customer_data.email.clone(), + phone: customer_data.phone.clone(), + }), + Identifier::Merchant(key_store.merchant_id.clone()), + key, + ) .await .switch() .attach_printable("Failed while encrypting Customer")?; + let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data) + .change_context(errors::CustomersErrorResponse::InternalServerError)?; + let new_customer = domain::Customer { + customer_id: customer_id.to_owned(), + merchant_id: merchant_id.to_string(), + name: encryptable_customer.name, + email: encryptable_customer.email, + phone: encryptable_customer.phone, + description: customer_data.description, + phone_country_code: customer_data.phone_country_code, + metadata: customer_data.metadata, + id: None, + connector_customer: None, + address_id: address.clone().map(|addr| addr.address_id), + created_at: common_utils::date_time::now(), + modified_at: common_utils::date_time::now(), + default_payment_method_id: None, + updated_by: None, + }; let customer = db - .insert_customer(new_customer, &key_store, merchant_account.storage_scheme) + .insert_customer( + key_manager_state, + new_customer, + &key_store, + merchant_account.storage_scheme, + ) .await .to_duplicate_response(errors::CustomersErrorResponse::CustomerAlreadyExists)?; @@ -148,8 +159,10 @@ pub async fn retrieve_customer( req: customers::CustomerId, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let response = db .find_customer_by_customer_id_merchant_id( + key_manager_state, &req.customer_id, &merchant_account.merchant_id, &key_store, @@ -159,7 +172,7 @@ pub async fn retrieve_customer( .switch()?; let address = match &response.address_id { Some(address_id) => Some(api_models::payments::AddressDetails::from( - db.find_address_by_address_id(address_id, &key_store) + db.find_address_by_address_id(key_manager_state, address_id, &key_store) .await .switch()?, )), @@ -179,7 +192,7 @@ pub async fn list_customers( let db = state.store.as_ref(); let domain_customers = db - .list_customers_by_merchant_id(&merchant_id, &key_store) + .list_customers_by_merchant_id(&(&state).into(), &merchant_id, &key_store) .await .switch()?; @@ -199,9 +212,10 @@ pub async fn delete_customer( key_store: domain::MerchantKeyStore, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse> { let db = &state.store; - + let key_manager_state = &(&state).into(); let customer_orig = db .find_customer_by_customer_id_merchant_id( + key_manager_state, &req.customer_id, &merchant_account.merchant_id, &key_store, @@ -262,17 +276,24 @@ pub async fn delete_customer( }; let key = key_store.key.get_inner().peek(); + let identifier = Identifier::Merchant(key_store.merchant_id.clone()); + let redacted_encrypted_value: Encryptable<Secret<_>> = Encryptable::encrypt_via_api( + key_manager_state, + REDACTED.to_string().into(), + identifier.clone(), + key, + GcmAes256, + ) + .await + .switch()?; - let redacted_encrypted_value: Encryptable<masking::Secret<_>> = - Encryptable::encrypt(REDACTED.to_string().into(), key, GcmAes256) - .await - .switch()?; - - let redacted_encrypted_email: Encryptable< - masking::Secret<_, common_utils::pii::EmailStrategy>, - > = Encryptable::encrypt(REDACTED.to_string().into(), key, GcmAes256) - .await - .switch()?; + let redacted_encrypted_email = Encryptable::new( + redacted_encrypted_value + .clone() + .into_inner() + .switch_strategy(), + redacted_encrypted_value.clone().into_encrypted(), + ); let update_address = storage::AddressUpdate::Update { city: Some(REDACTED.to_string()), @@ -292,6 +313,7 @@ pub async fn delete_customer( match db .update_address_by_merchant_id_customer_id( + key_manager_state, &req.customer_id, &merchant_account.merchant_id, update_address, @@ -314,9 +336,15 @@ pub async fn delete_customer( let updated_customer = storage::CustomerUpdate::Update { name: Some(redacted_encrypted_value.clone()), email: Some( - Encryptable::encrypt(REDACTED.to_string().into(), key, GcmAes256) - .await - .switch()?, + Encryptable::encrypt_via_api( + key_manager_state, + REDACTED.to_string().into(), + identifier, + key, + GcmAes256, + ) + .await + .switch()?, ), phone: Box::new(Some(redacted_encrypted_value.clone())), description: Some(REDACTED.to_string()), @@ -326,6 +354,7 @@ pub async fn delete_customer( address_id: None, }; db.update_customer_by_customer_id_merchant_id( + key_manager_state, req.customer_id.clone(), merchant_account.merchant_id, customer_orig, @@ -362,9 +391,10 @@ pub async fn update_customer( .get_required_value("customer_id") .change_context(errors::CustomersErrorResponse::InternalServerError) .attach("Missing required field `customer_id`")?; - + let key_manager_state = &(&state).into(); let customer = db .find_customer_by_customer_id_merchant_id( + key_manager_state, customer_id, &merchant_account.merchant_id, &key_store, @@ -380,12 +410,18 @@ pub async fn update_customer( Some(address_id) => { let customer_address: api_models::payments::AddressDetails = addr.clone(); let update_address = update_customer - .get_address_update(customer_address, key, merchant_account.storage_scheme) + .get_address_update( + &state, + customer_address, + key, + merchant_account.storage_scheme, + merchant_account.merchant_id.clone(), + ) .await .switch() .attach_printable("Failed while encrypting Address while Update")?; Some( - db.update_address(address_id, update_address, &key_store) + db.update_address(key_manager_state, address_id, update_address, &key_store) .await .switch() .attach_printable(format!( @@ -399,6 +435,7 @@ pub async fn update_customer( let address = update_customer .get_domain_address( + &state, customer_address, &merchant_account.merchant_id, &customer.customer_id, @@ -409,7 +446,7 @@ pub async fn update_customer( .switch() .attach_printable("Failed while encrypting address")?; Some( - db.insert_address_for_customers(address, &key_store) + db.insert_address_for_customers(key_manager_state, address, &key_store) .await .switch() .attach_printable("Failed while inserting new address")?, @@ -419,47 +456,44 @@ pub async fn update_customer( } else { match &customer.address_id { Some(address_id) => Some( - db.find_address_by_address_id(address_id, &key_store) + db.find_address_by_address_id(key_manager_state, address_id, &key_store) .await .switch()?, ), None => None, } }; + let encrypted_data = types::batch_encrypt( + &(&state).into(), + CustomerRequestWithEmail::to_encryptable(CustomerRequestWithEmail { + name: update_customer.name.clone(), + email: update_customer.email.clone(), + phone: update_customer.phone.clone(), + }), + Identifier::Merchant(key_store.merchant_id.clone()), + key, + ) + .await + .switch()?; + let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data) + .change_context(errors::CustomersErrorResponse::InternalServerError)?; let response = db .update_customer_by_customer_id_merchant_id( + key_manager_state, customer_id.to_owned(), merchant_account.merchant_id.to_owned(), customer, - async { - Ok(storage::CustomerUpdate::Update { - name: update_customer - .name - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - email: update_customer - .email - .async_lift(|inner| { - types::encrypt_optional(inner.map(|inner| inner.expose()), key) - }) - .await?, - phone: Box::new( - update_customer - .phone - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - ), - phone_country_code: update_customer.phone_country_code, - metadata: update_customer.metadata, - description: update_customer.description, - connector_customer: None, - address_id: address.clone().map(|addr| addr.address_id), - }) - } - .await - .switch() - .attach_printable("Failed while encrypting while updating customer")?, + storage::CustomerUpdate::Update { + name: encryptable_customer.name, + email: encryptable_customer.email, + phone: Box::new(encryptable_customer.phone), + phone_country_code: update_customer.phone_country_code, + metadata: update_customer.metadata, + description: update_customer.description, + connector_customer: None, + address_id: address.clone().map(|addr| addr.address_id), + }, &key_store, merchant_account.storage_scheme, ) diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs index 2d2d7bbcaeb..6a7f531f5a0 100644 --- a/crates/router/src/core/disputes.rs +++ b/crates/router/src/core/disputes.rs @@ -89,6 +89,7 @@ pub async fn accept_dispute( )?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &dispute.payment_id, &merchant_account.merchant_id, &key_store, @@ -202,6 +203,7 @@ pub async fn submit_evidence( .await?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &dispute.payment_id, &merchant_account.merchant_id, &key_store, diff --git a/crates/router/src/core/encryption.rs b/crates/router/src/core/encryption.rs index 7f7945bfd1c..efd7d3bfeaa 100644 --- a/crates/router/src/core/encryption.rs +++ b/crates/router/src/core/encryption.rs @@ -14,7 +14,7 @@ pub async fn transfer_encryption_key( ) -> errors::CustomResult<usize, errors::ApiErrorResponse> { let db = &*state.store; let key_stores = db - .get_all_key_stores(&db.get_master_key().to_vec().into()) + .get_all_key_stores(&state.into(), &db.get_master_key().to_vec().into()) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; send_request_to_key_service_for_merchant(state, key_stores).await diff --git a/crates/router/src/core/files/helpers.rs b/crates/router/src/core/files/helpers.rs index 3a565865603..ed95e7790e7 100644 --- a/crates/router/src/core/files/helpers.rs +++ b/crates/router/src/core/files/helpers.rs @@ -261,6 +261,7 @@ pub async fn upload_and_get_provider_provider_file_id_profile_id( let payment_intent = state .store .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &dispute.payment_id, &merchant_account.merchant_id, key_store, diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs index 331eb430211..8ddd0b7aa24 100644 --- a/crates/router/src/core/fraud_check.rs +++ b/crates/router/src/core/fraud_check.rs @@ -123,7 +123,7 @@ where pub async fn should_call_frm<F>( merchant_account: &domain::MerchantAccount, payment_data: &payments::PaymentData<F>, - db: &dyn StorageInterface, + state: &SessionState, key_store: domain::MerchantKeyStore, ) -> RouterResult<( bool, @@ -136,6 +136,7 @@ where { match merchant_account.frm_routing_algorithm.clone() { Some(frm_routing_algorithm_value) => { + let db = &*state.store; let frm_routing_algorithm_struct: FrmRoutingAlgorithm = frm_routing_algorithm_value .clone() .parse_value("FrmRoutingAlgorithm") @@ -157,6 +158,7 @@ where let merchant_connector_account_from_db_option = db .find_merchant_connector_account_by_profile_id_connector_name( + &state.into(), &profile_id, &frm_routing_algorithm_struct.data, &key_store, @@ -417,7 +419,7 @@ where let frm_data_updated = fraud_check_operation .to_update_tracker()? .update_tracker( - &*state.store, + state, &key_store, frm_data.clone(), payment_data, @@ -492,7 +494,7 @@ where let mut frm_data = fraud_check_operation .to_update_tracker()? .update_tracker( - &*state.store, + state, &key_store, frm_data.to_owned(), payment_data, @@ -527,7 +529,7 @@ where let updated_frm_data = fraud_check_operation .to_update_tracker()? .update_tracker( - &*state.store, + state, &key_store, frm_data.to_owned(), payment_data, @@ -547,7 +549,6 @@ where #[allow(clippy::too_many_arguments)] pub async fn call_frm_before_connector_call<'a, F, Req>( - db: &dyn StorageInterface, operation: &BoxedOperation<'_, F, Req>, merchant_account: &domain::MerchantAccount, payment_data: &mut payments::PaymentData<F>, @@ -562,13 +563,13 @@ where F: Send + Clone, { let (is_frm_enabled, frm_routing_algorithm, frm_connector_label, frm_configs) = - should_call_frm(merchant_account, payment_data, db, key_store.clone()).await?; + should_call_frm(merchant_account, payment_data, state, key_store.clone()).await?; if let Some((frm_routing_algorithm_val, profile_id)) = frm_routing_algorithm.zip(frm_connector_label) { if let Some(frm_configs) = frm_configs.clone() { let mut updated_frm_info = Box::pin(make_frm_data_and_fraud_check_operation( - db, + &*state.store, state, merchant_account, payment_data.to_owned(), @@ -655,6 +656,7 @@ pub async fn frm_fulfillment_core( let db = &*state.clone().store; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &req.payment_id.clone(), &merchant_account.merchant_id, &key_store, diff --git a/crates/router/src/core/fraud_check/operation.rs b/crates/router/src/core/fraud_check/operation.rs index 8c6f8b7bf52..2d159d2e220 100644 --- a/crates/router/src/core/fraud_check/operation.rs +++ b/crates/router/src/core/fraud_check/operation.rs @@ -14,7 +14,6 @@ use crate::{ errors::{self, RouterResult}, payments, }, - db::StorageInterface, routes::{app::ReqState, SessionState}, types::{domain, fraud_check::FrmRouterData}, }; @@ -101,7 +100,7 @@ pub trait Domain<F>: Send + Sync { pub trait UpdateTracker<D, F: Clone>: Send { async fn update_tracker<'b>( &'b self, - db: &dyn StorageInterface, + state: &SessionState, key_store: &domain::MerchantKeyStore, frm_data: D, payment_data: &mut payments::PaymentData<F>, diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs index 7c97eee8b49..698eb43385e 100644 --- a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs +++ b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs @@ -19,7 +19,6 @@ use crate::{ }, payments, }, - db::StorageInterface, errors, routes::app::ReqState, services::{self, api}, @@ -329,13 +328,14 @@ impl<F: Send + Clone> Domain<F> for FraudCheckPost { impl<F: Clone + Send> UpdateTracker<FrmData, F> for FraudCheckPost { async fn update_tracker<'b>( &'b self, - db: &dyn StorageInterface, + state: &SessionState, key_store: &domain::MerchantKeyStore, mut frm_data: FrmData, payment_data: &mut payments::PaymentData<F>, frm_suggestion: Option<FrmSuggestion>, frm_router_data: FrmRouterData, ) -> RouterResult<FrmData> { + let db = &*state.store; let frm_check_update = match frm_router_data.response { FrmResponse::Sale(response) => match response { Err(err) => Some(FraudCheckUpdate::ErrorUpdate { @@ -515,6 +515,7 @@ impl<F: Clone + Send> UpdateTracker<FrmData, F> for FraudCheckPost { payment_data.payment_intent = db .update_payment_intent( + &state.into(), payment_data.payment_intent.clone(), PaymentIntentUpdate::RejectUpdate { status: payment_intent_status, diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs index c153acc7544..6a0bd78130d 100644 --- a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs +++ b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs @@ -16,7 +16,6 @@ use crate::{ }, payments, }, - db::StorageInterface, errors, routes::app::ReqState, types::{ @@ -218,7 +217,7 @@ impl<F: Send + Clone> Domain<F> for FraudCheckPre { impl<F: Clone + Send> UpdateTracker<FrmData, F> for FraudCheckPre { async fn update_tracker<'b>( &'b self, - db: &dyn StorageInterface, + state: &SessionState, _key_store: &domain::MerchantKeyStore, mut frm_data: FrmData, payment_data: &mut payments::PaymentData<F>, @@ -337,6 +336,7 @@ impl<F: Clone + Send> UpdateTracker<FrmData, F> for FraudCheckPre { }), }; + let db = &*state.store; frm_data.fraud_check = match frm_check_update { Some(fraud_check_update) => db .update_fraud_check_response_with_attempt_id( diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs index 24ba06bcf36..22b3b29e03b 100644 --- a/crates/router/src/core/locker_migration.rs +++ b/crates/router/src/core/locker_migration.rs @@ -17,10 +17,11 @@ pub async fn rust_locker_migration( merchant_id: &str, ) -> CustomResult<services::ApplicationResponse<MigrateCardResponse>, errors::ApiErrorResponse> { let db = state.store.as_ref(); - + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -28,13 +29,13 @@ pub async fn rust_locker_migration( .change_context(errors::ApiErrorResponse::InternalServerError)?; let merchant_account = db - .find_merchant_account_by_merchant_id(merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .change_context(errors::ApiErrorResponse::InternalServerError)?; let domain_customers = db - .list_customers_by_merchant_id(merchant_id, &key_store) + .list_customers_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; diff --git a/crates/router/src/core/mandate/helpers.rs b/crates/router/src/core/mandate/helpers.rs index 2bb981d03e8..a4eb18371f0 100644 --- a/crates/router/src/core/mandate/helpers.rs +++ b/crates/router/src/core/mandate/helpers.rs @@ -21,6 +21,7 @@ pub async fn get_profile_id_for_mandate( let pi = state .store .find_payment_intent_by_payment_id_merchant_id( + &state.into(), payment_id, &merchant_account.merchant_id, key_store, diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index 49e4885dc93..bf50405ba81 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -59,6 +59,7 @@ pub async fn initiate_payment_link_flow( let db = &*state.store; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &payment_id, &merchant_id, &key_store, @@ -497,6 +498,7 @@ pub async fn get_payment_link_status( let db = &*state.store; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &payment_id, &merchant_id, &key_store, diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index b9e21b616c0..86cb1fc1b1e 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -266,6 +266,7 @@ pub async fn render_pm_collect_link( // Fetch customer let customer = db .find_customer_by_customer_id_merchant_id( + &(&state).into(), &customer_id, &req.merchant_id, &key_store, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 468bc0dbfc3..431826fbdb0 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -23,11 +23,15 @@ use common_enums::enums::MerchantStorageScheme; use common_utils::{ consts, crypto::Encryptable, + encryption::Encryption, ext_traits::{AsyncExt, Encode, StringExt, ValueExt}, generate_id, id_type, - types::MinorUnit, + types::{ + keymanager::{Identifier, KeyManagerState}, + MinorUnit, + }, }; -use diesel_models::{business_profile::BusinessProfile, encryption::Encryption, payment_method}; +use diesel_models::{business_profile::BusinessProfile, payment_method}; use domain::CustomerUpdate; use error_stack::{report, ResultExt}; use euclid::{ @@ -77,7 +81,7 @@ use crate::{ #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn create_payment_method( - db: &dyn db::StorageInterface, + state: &routes::SessionState, req: &api::PaymentMethodCreate, customer_id: &id_type::CustomerId, payment_method_id: &str, @@ -94,8 +98,10 @@ pub async fn create_payment_method( payment_method_billing_address: Option<Encryption>, card_scheme: Option<String>, ) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> { + let db = &*state.store; let customer = db .find_customer_by_customer_id_merchant_id( + &state.into(), customer_id, merchant_id, key_store, @@ -153,7 +159,7 @@ pub async fn create_payment_method( if customer.default_payment_method_id.is_none() && req.payment_method.is_some() { let _ = set_default_payment_method( - db, + state, merchant_id.to_string(), key_store.clone(), customer_id, @@ -197,7 +203,7 @@ pub fn store_default_payment_method( } #[instrument(skip_all)] pub async fn get_or_insert_payment_method( - db: &dyn db::StorageInterface, + state: &routes::SessionState, req: api::PaymentMethodCreate, resp: &mut api::PaymentMethodResponse, merchant_account: &domain::MerchantAccount, @@ -206,6 +212,7 @@ pub async fn get_or_insert_payment_method( ) -> errors::RouterResult<diesel_models::PaymentMethod> { let mut payment_method_id = resp.payment_method_id.clone(); let mut locker_id = None; + let db = &*state.store; let payment_method = { let existing_pm_by_pmid = db .find_payment_method(&payment_method_id, merchant_account.storage_scheme) @@ -240,7 +247,7 @@ pub async fn get_or_insert_payment_method( Err(err) => { if err.current_context().is_db_not_found() { insert_payment_method( - db, + state, resp, &req, key_store, @@ -278,7 +285,7 @@ pub async fn migrate_payment_method( if let Some(connector_mandate_details) = &req.connector_mandate_details { helpers::validate_merchant_connector_ids_in_connector_mandate_details( - &*state.store, + &state, key_store, connector_mandate_details, merchant_id, @@ -294,7 +301,7 @@ pub async fn migrate_payment_method( &req, ); get_client_secret_or_add_payment_method( - state, + &state, payment_method_create_request, merchant_account, key_store, @@ -338,7 +345,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() - .async_map(|billing| create_encrypted_data(key_store, billing)) + .async_map(|billing| create_encrypted_data(&state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -346,6 +353,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( let customer = db .find_customer_by_customer_id_merchant_id( + &(&state).into(), &customer_id, &merchant_id, key_store, @@ -475,7 +483,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( let payment_method_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = payment_method_card_details - .async_map(|card_details| create_encrypted_data(key_store, card_details)) + .async_map(|card_details| create_encrypted_data(&state, key_store, card_details)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -535,7 +543,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( if customer.default_payment_method_id.is_none() && req.payment_method.is_some() { let _ = set_default_payment_method( - &*state.store, + &state, merchant_id.to_string(), key_store.clone(), &customer_id, @@ -572,12 +580,11 @@ pub fn get_card_bin_and_last4_digits_for_masked_card( #[instrument(skip_all)] pub async fn get_client_secret_or_add_payment_method( - state: routes::SessionState, + state: &routes::SessionState, req: api::PaymentMethodCreate, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodResponse> { - let db = &*state.store; let merchant_id = &merchant_account.merchant_id; let customer_id = req.customer_id.clone().get_required_value("customer_id")?; @@ -589,7 +596,7 @@ pub async fn get_client_secret_or_add_payment_method( let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() - .async_map(|billing| create_encrypted_data(key_store, billing)) + .async_map(|billing| create_encrypted_data(state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -608,7 +615,7 @@ pub async fn get_client_secret_or_add_payment_method( let payment_method_id = generate_id(consts::ID_LENGTH, "pm"); let res = create_payment_method( - db, + state, &req, &customer_id, payment_method_id.as_str(), @@ -629,7 +636,7 @@ pub async fn get_client_secret_or_add_payment_method( if res.status == enums::PaymentMethodStatus::AwaitingData { add_payment_method_status_update_task( - db, + &*state.store, &res, enums::PaymentMethodStatus::AwaitingData, enums::PaymentMethodStatus::Inactive, @@ -708,6 +715,7 @@ pub async fn add_payment_method_data( let customer_id = payment_method.customer_id.clone(); let customer = db .find_customer_by_customer_id_merchant_id( + &(&state).into(), &customer_id, &merchant_account.merchant_id, &key_store, @@ -754,7 +762,7 @@ pub async fn add_payment_method_data( .attach_printable("Failed to add payment method in db")?; get_or_insert_payment_method( - db, + &state, req.clone(), &mut pm_resp, &merchant_account, @@ -795,6 +803,7 @@ pub async fn add_payment_method_data( let pm_data_encrypted: Encryptable<Secret<serde_json::Value>> = create_encrypted_data( + &state, &key_store, PaymentMethodsData::Card(updated_card), ) @@ -822,7 +831,7 @@ pub async fn add_payment_method_data( if customer.default_payment_method_id.is_none() { let _ = set_default_payment_method( - db, + &state, merchant_account.merchant_id.clone(), key_store.clone(), &customer_id, @@ -864,7 +873,7 @@ pub async fn add_payment_method_data( #[instrument(skip_all)] pub async fn add_payment_method( - state: routes::SessionState, + state: &routes::SessionState, req: api::PaymentMethodCreate, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, @@ -877,7 +886,7 @@ pub async fn add_payment_method( let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() - .async_map(|billing| create_encrypted_data(key_store, billing)) + .async_map(|billing| create_encrypted_data(state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -894,7 +903,7 @@ pub async fn add_payment_method( #[cfg(feature = "payouts")] api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() { Some(bank) => add_bank_to_locker( - &state, + state, req.clone(), merchant_account, key_store, @@ -923,7 +932,7 @@ pub async fn add_payment_method( &card_details.card_exp_year, )?; Box::pin(add_card_to_locker( - &state, + state, req.clone(), &card_details, &customer_id, @@ -953,7 +962,7 @@ pub async fn add_payment_method( Some(duplication_check) => match duplication_check { payment_methods::DataDuplicationCheck::Duplicated => { let existing_pm = get_or_insert_payment_method( - db, + state, req.clone(), &mut resp, merchant_account, @@ -967,7 +976,7 @@ pub async fn add_payment_method( payment_methods::DataDuplicationCheck::MetaDataChanged => { if let Some(card) = req.card.clone() { let existing_pm = get_or_insert_payment_method( - db, + state, req.clone(), &mut resp, merchant_account, @@ -979,7 +988,7 @@ pub async fn add_payment_method( let client_secret = existing_pm.client_secret.clone(); delete_card_from_locker( - &state, + state, &customer_id, merchant_id, existing_pm @@ -990,7 +999,7 @@ pub async fn add_payment_method( .await?; let add_card_resp = add_card_hs( - &state, + state, req.clone(), &card, &customer_id, @@ -1018,12 +1027,9 @@ pub async fn add_payment_method( .attach_printable("Failed while updating card metadata changes"))? }; - let existing_pm_data = get_card_details_without_locker_fallback( - &existing_pm, - key_store.key.peek(), - &state, - ) - .await?; + let existing_pm_data = + get_card_details_without_locker_fallback(&existing_pm, state, key_store) + .await?; let updated_card = Some(api::CardDetailFromLocker { scheme: existing_pm.scheme.clone(), @@ -1052,7 +1058,9 @@ pub async fn add_payment_method( }); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd - .async_map(|updated_pmd| create_encrypted_data(key_store, updated_pmd)) + .async_map(|updated_pmd| { + create_encrypted_data(state, key_store, updated_pmd) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1087,7 +1095,7 @@ pub async fn add_payment_method( }; resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); let pm = insert_payment_method( - db, + state, &resp, &req, key_store, @@ -1112,7 +1120,7 @@ pub async fn add_payment_method( #[allow(clippy::too_many_arguments)] pub async fn insert_payment_method( - db: &dyn db::StorageInterface, + state: &routes::SessionState, resp: &api::PaymentMethodResponse, req: &api::PaymentMethodCreate, key_store: &domain::MerchantKeyStore, @@ -1133,14 +1141,14 @@ pub async fn insert_payment_method( let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = pm_card_details .clone() - .async_map(|pm_card| create_encrypted_data(key_store, pm_card)) + .async_map(|pm_card| create_encrypted_data(state, key_store, pm_card)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")?; create_payment_method( - db, + state, req, customer_id, &resp.payment_method_id, @@ -1202,7 +1210,9 @@ pub async fn update_customer_payment_method( // Fetch the existing payment method data from db let existing_card_data = decrypt::<serde_json::Value, masking::WithType>( + &(&state).into(), pm.payment_method_data.clone(), + Identifier::Merchant(key_store.merchant_id.clone()), key_store.key.get_inner().peek(), ) .await @@ -1327,7 +1337,7 @@ pub async fn update_customer_payment_method( .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd - .async_map(|updated_pmd| create_encrypted_data(&key_store, updated_pmd)) + .async_map(|updated_pmd| create_encrypted_data(&state, &key_store, updated_pmd)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1445,6 +1455,7 @@ pub async fn add_bank_to_locker( > { let key = key_store.key.get_inner().peek(); let payout_method_data = api::PayoutMethodData::Bank(bank.clone()); + let key_manager_state: KeyManagerState = state.into(); let enc_data = async { serde_json::to_value(payout_method_data.to_owned()) .map_err(|err| { @@ -1458,7 +1469,14 @@ pub async fn add_bank_to_locker( let secret: Secret<String> = Secret::new(v.to_string()); secret }) - .async_lift(|inner| domain::types::encrypt_optional(inner, key)) + .async_lift(|inner| { + domain::types::encrypt_optional( + &key_manager_state, + inner, + Identifier::Merchant(key_store.merchant_id.clone()), + key, + ) + }) .await } .await @@ -1654,6 +1672,7 @@ pub async fn add_card_hs( #[instrument(skip_all)] pub async fn decode_and_decrypt_locker_data( + state: &routes::SessionState, key_store: &domain::MerchantKeyStore, enc_card_data: String, ) -> errors::CustomResult<Secret<String>, errors::VaultError> { @@ -1664,13 +1683,18 @@ pub async fn decode_and_decrypt_locker_data( .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to decode hex string into bytes")?; // Decrypt - decrypt(Some(Encryption::new(decoded_bytes.into())), key) - .await - .change_context(errors::VaultError::FetchPaymentMethodFailed)? - .map_or( - Err(report!(errors::VaultError::FetchPaymentMethodFailed)), - |d| Ok(d.into_inner()), - ) + decrypt( + &state.into(), + Some(Encryption::new(decoded_bytes.into())), + Identifier::Merchant(key_store.merchant_id.clone()), + key, + ) + .await + .change_context(errors::VaultError::FetchPaymentMethodFailed)? + .map_or( + Err(report!(errors::VaultError::FetchPaymentMethodFailed)), + |d| Ok(d.into_inner()), + ) } #[instrument(skip_all)] @@ -1729,9 +1753,9 @@ pub async fn get_payment_method_from_hs_locker<'a>( .attach_printable( "Failed to retrieve field - enc_card_data from RetrieveCardRespPayload", )?; - decode_and_decrypt_locker_data(key_store, enc_card_data.peek().to_string()).await? + decode_and_decrypt_locker_data(state, key_store, enc_card_data.peek().to_string()).await? } else { - mock_get_payment_method(&*state.store, key_store, payment_method_reference) + mock_get_payment_method(state, key_store, payment_method_reference) .await? .payment_method .payment_method_data @@ -2036,16 +2060,17 @@ pub async fn mock_get_card<'a>( #[instrument(skip_all)] pub async fn mock_get_payment_method<'a>( - db: &dyn db::StorageInterface, + state: &routes::SessionState, key_store: &domain::MerchantKeyStore, card_id: &'a str, ) -> errors::CustomResult<payment_methods::GetPaymentMethodResponse, errors::VaultError> { + let db = &*state.store; let locker_mock_up = db .find_locker_by_card_id(card_id) .await .change_context(errors::VaultError::FetchPaymentMethodFailed)?; let dec_data = if let Some(e) = locker_mock_up.enc_card_data { - decode_and_decrypt_locker_data(key_store, e).await + decode_and_decrypt_locker_data(state, key_store, e).await } else { Err(report!(errors::VaultError::FetchPaymentMethodFailed)) }?; @@ -2187,14 +2212,14 @@ pub async fn list_payment_methods( ) -> errors::RouterResponse<api::PaymentMethodListResponse> { let db = &*state.store; let pm_config_mapping = &state.conf.pm_filters; - + let key_manager_state = &(&state).into(); let payment_intent = if let Some(cs) = &req.client_secret { if cs.starts_with("pm_") { validate_payment_method_and_client_secret(cs, db, &merchant_account).await?; None } else { helpers::verify_payment_intent_time_and_client_secret( - db, + &state, &merchant_account, &key_store, req.client_secret.clone(), @@ -2209,7 +2234,7 @@ pub async fn list_payment_methods( .as_ref() .async_map(|pi| async { helpers::get_address_by_id( - db, + &state, pi.shipping_address_id.clone(), &key_store, &pi.payment_id, @@ -2226,7 +2251,7 @@ pub async fn list_payment_methods( .as_ref() .async_map(|pi| async { helpers::get_address_by_id( - db, + &state, pi.billing_address_id.clone(), &key_store, &pi.payment_id, @@ -2246,6 +2271,7 @@ pub async fn list_payment_methods( .as_ref() .async_and_then(|cust| async { db.find_customer_by_customer_id_merchant_id( + key_manager_state, cust, &pi.merchant_id, &key_store, @@ -2293,6 +2319,7 @@ pub async fn list_payment_methods( let all_mcas = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( + key_manager_state, &merchant_account.merchant_id, false, &key_store, @@ -3273,6 +3300,7 @@ pub async fn call_surcharge_decision_management( let _ = state .store .update_payment_intent( + &(&state).into(), payment_intent, storage::PaymentIntentUpdate::SurchargeApplicableUpdate { surcharge_applicable: true, @@ -3322,6 +3350,7 @@ pub async fn call_surcharge_decision_management_for_saved_card( let _ = state .store .update_payment_intent( + &state.into(), payment_intent, storage::PaymentIntentUpdate::SurchargeApplicableUpdate { surcharge_applicable: true, @@ -3586,7 +3615,6 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed( customer_id: Option<&id_type::CustomerId>, ephemeral_api_key: Option<&str>, ) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> { - let db = state.store.as_ref(); let limit = req.clone().and_then(|pml_req| pml_req.limit); let auth_cust = if let Some(key) = ephemeral_api_key { @@ -3617,7 +3645,7 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed( let cloned_secret = req.and_then(|r| r.client_secret.as_ref().cloned()); let payment_intent: Option<hyperswitch_domain_models::payments::PaymentIntent> = helpers::verify_payment_intent_time_and_client_secret( - db, + &state, &merchant_account, &key_store, cloned_secret, @@ -3671,6 +3699,7 @@ pub async fn list_customer_payment_method( let customer = db .find_customer_by_customer_id_merchant_id( + &state.into(), customer_id, &merchant_account.merchant_id, &key_store, @@ -3679,8 +3708,6 @@ pub async fn list_customer_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; - let key = key_store.key.get_inner().peek(); - let is_requires_cvv = db .find_config_by_key_unwrap_or( format!("{}_requires_cvv", merchant_account.merchant_id).as_str(), @@ -3741,7 +3768,8 @@ pub async fn list_customer_payment_method( let payment_method_retrieval_context = match payment_method { enums::PaymentMethod::Card => { - let card_details = get_card_details_with_locker_fallback(&pm, key, state).await?; + let card_details = + get_card_details_with_locker_fallback(&pm, state, &key_store).await?; if card_details.is_some() { PaymentMethodListContext { @@ -3761,12 +3789,13 @@ pub async fn list_customer_payment_method( enums::PaymentMethod::BankDebit => { // Retrieve the pm_auth connector details so that it can be tokenized - let bank_account_token_data = get_bank_account_connector_details(&pm, key) - .await - .unwrap_or_else(|error| { - logger::error!(?error); - None - }); + let bank_account_token_data = + get_bank_account_connector_details(state, &pm, &key_store) + .await + .unwrap_or_else(|error| { + logger::error!(?error); + None + }); if let Some(data) = bank_account_token_data { let token_data = PaymentTokenData::AuthBankDebit(data); @@ -3822,7 +3851,7 @@ pub async fn list_customer_payment_method( // Retrieve the masked bank details to be sent as a response let bank_details = if payment_method == enums::PaymentMethod::BankDebit { - get_masked_bank_details(&pm, key) + get_masked_bank_details(state, &pm, &key_store) .await .unwrap_or_else(|error| { logger::error!(?error); @@ -3833,8 +3862,9 @@ pub async fn list_customer_payment_method( }; let payment_method_billing = decrypt_generic_data::<api_models::payments::Address>( + state, pm.payment_method_billing_address, - key, + &key_store, ) .await .attach_printable("unable to decrypt payment method billing address details")?; @@ -3993,6 +4023,7 @@ pub async fn get_mca_status( let mcas = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( + &state.into(), merchant_id, true, key_store, @@ -4021,17 +4052,21 @@ pub async fn get_mca_status( Ok(false) } pub async fn decrypt_generic_data<T>( + state: &routes::SessionState, data: Option<Encryption>, - key: &[u8], + key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<Option<T>> where T: serde::de::DeserializeOwned, { - let decrypted_data = decrypt::<serde_json::Value, masking::WithType>(data, key) - .await - .change_context(errors::StorageError::DecryptionError) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to decrypt data")?; + let key = key_store.key.get_inner().peek(); + let identifier = Identifier::Merchant(key_store.merchant_id.clone()); + let decrypted_data = + decrypt::<serde_json::Value, masking::WithType>(&state.into(), data, identifier, key) + .await + .change_context(errors::StorageError::DecryptionError) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to decrypt data")?; decrypted_data .map(|decrypted_data| decrypted_data.into_inner().expose()) @@ -4043,22 +4078,28 @@ where pub async fn get_card_details_with_locker_fallback( pm: &payment_method::PaymentMethod, - key: &[u8], state: &routes::SessionState, + key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<Option<api::CardDetailFromLocker>> { - let card_decrypted = - decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key) - .await - .change_context(errors::StorageError::DecryptionError) - .attach_printable("unable to decrypt card details") - .ok() - .flatten() - .map(|x| x.into_inner().expose()) - .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok()) - .and_then(|pmd| match pmd { - PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), - _ => None, - }); + let key = key_store.key.get_inner().peek(); + let identifier = Identifier::Merchant(key_store.merchant_id.clone()); + let card_decrypted = decrypt::<serde_json::Value, masking::WithType>( + &state.into(), + pm.payment_method_data.clone(), + identifier, + key, + ) + .await + .change_context(errors::StorageError::DecryptionError) + .attach_printable("unable to decrypt card details") + .ok() + .flatten() + .map(|x| x.into_inner().expose()) + .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok()) + .and_then(|pmd| match pmd { + PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), + _ => None, + }); Ok(if let Some(mut crd) = card_decrypted { crd.scheme.clone_from(&pm.scheme); @@ -4073,22 +4114,28 @@ pub async fn get_card_details_with_locker_fallback( pub async fn get_card_details_without_locker_fallback( pm: &payment_method::PaymentMethod, - key: &[u8], state: &routes::SessionState, + key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<api::CardDetailFromLocker> { - let card_decrypted = - decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key) - .await - .change_context(errors::StorageError::DecryptionError) - .attach_printable("unable to decrypt card details") - .ok() - .flatten() - .map(|x| x.into_inner().expose()) - .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok()) - .and_then(|pmd| match pmd { - PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), - _ => None, - }); + let key = key_store.key.get_inner().peek(); + let identifier = Identifier::Merchant(key_store.merchant_id.clone()); + let card_decrypted = decrypt::<serde_json::Value, masking::WithType>( + &state.into(), + pm.payment_method_data.clone(), + identifier, + key, + ) + .await + .change_context(errors::StorageError::DecryptionError) + .attach_printable("unable to decrypt card details") + .ok() + .flatten() + .map(|x| x.into_inner().expose()) + .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok()) + .and_then(|pmd| match pmd { + PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), + _ => None, + }); Ok(if let Some(mut crd) = card_decrypted { crd.scheme.clone_from(&pm.scheme); @@ -4141,25 +4188,32 @@ pub async fn get_lookup_key_from_locker( } async fn get_masked_bank_details( + state: &routes::SessionState, pm: &payment_method::PaymentMethod, - key: &[u8], + key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<Option<MaskedBankDetails>> { - let payment_method_data = - decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key) - .await - .change_context(errors::StorageError::DecryptionError) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to decrypt bank details")? - .map(|x| x.into_inner().expose()) - .map( - |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> { - v.parse_value::<PaymentMethodsData>("PaymentMethodsData") - .change_context(errors::StorageError::DeserializationFailed) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to deserialize Payment Method Auth config") - }, - ) - .transpose()?; + let key = key_store.key.get_inner().peek(); + let identifier = Identifier::Merchant(key_store.merchant_id.clone()); + let payment_method_data = decrypt::<serde_json::Value, masking::WithType>( + &state.into(), + pm.payment_method_data.clone(), + identifier, + key, + ) + .await + .change_context(errors::StorageError::DecryptionError) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to decrypt bank details")? + .map(|x| x.into_inner().expose()) + .map( + |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> { + v.parse_value::<PaymentMethodsData>("PaymentMethodsData") + .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize Payment Method Auth config") + }, + ) + .transpose()?; match payment_method_data { Some(pmd) => match pmd { @@ -4174,25 +4228,32 @@ async fn get_masked_bank_details( } async fn get_bank_account_connector_details( + state: &routes::SessionState, pm: &payment_method::PaymentMethod, - key: &[u8], + key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<Option<BankAccountTokenData>> { - let payment_method_data = - decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key) - .await - .change_context(errors::StorageError::DecryptionError) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to decrypt bank details")? - .map(|x| x.into_inner().expose()) - .map( - |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> { - v.parse_value::<PaymentMethodsData>("PaymentMethodsData") - .change_context(errors::StorageError::DeserializationFailed) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to deserialize Payment Method Auth config") - }, - ) - .transpose()?; + let key = key_store.key.get_inner().peek(); + let identifier = Identifier::Merchant(key_store.merchant_id.clone()); + let payment_method_data = decrypt::<serde_json::Value, masking::WithType>( + &state.into(), + pm.payment_method_data.clone(), + identifier, + key, + ) + .await + .change_context(errors::StorageError::DecryptionError) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to decrypt bank details")? + .map(|x| x.into_inner().expose()) + .map( + |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> { + v.parse_value::<PaymentMethodsData>("PaymentMethodsData") + .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize Payment Method Auth config") + }, + ) + .transpose()?; match payment_method_data { Some(pmd) => match pmd { @@ -4229,17 +4290,20 @@ async fn get_bank_account_connector_details( } } pub async fn set_default_payment_method( - db: &dyn db::StorageInterface, + state: &routes::SessionState, merchant_id: String, key_store: domain::MerchantKeyStore, customer_id: &id_type::CustomerId, payment_method_id: String, storage_scheme: MerchantStorageScheme, ) -> errors::RouterResponse<CustomerDefaultPaymentMethodResponse> { + let db = &*state.store; + let key_manager_state = &state.into(); // check for the customer // TODO: customer need not be checked again here, this function can take an optional customer and check for existence of customer based on the optional value let customer = db .find_customer_by_customer_id_merchant_id( + key_manager_state, customer_id, &merchant_id, &key_store, @@ -4283,6 +4347,7 @@ pub async fn set_default_payment_method( // update the db with the default payment method id let updated_customer_details = db .update_customer_by_customer_id_merchant_id( + key_manager_state, customer_id.to_owned(), merchant_id.to_owned(), customer, @@ -4470,7 +4535,6 @@ pub async fn retrieve_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; - let key = key_store.key.peek(); let card = if pm.payment_method == Some(enums::PaymentMethod::Card) { let card_detail = if state.conf.locker.locker_enabled { let card = get_card_from_locker( @@ -4486,7 +4550,7 @@ pub async fn retrieve_payment_method( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting card details from locker")? } else { - get_card_details_without_locker_fallback(&pm, key, &state).await? + get_card_details_without_locker_fallback(&pm, &state, &key_store).await? }; Some(card_detail) } else { @@ -4521,6 +4585,7 @@ pub async fn delete_payment_method( key_store: domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodDeleteResponse> { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key = db .find_payment_method( pm_id.payment_method_id.as_str(), @@ -4531,6 +4596,7 @@ pub async fn delete_payment_method( let customer = db .find_customer_by_customer_id_merchant_id( + key_manager_state, &key.customer_id, &merchant_account.merchant_id, &key_store, @@ -4570,6 +4636,7 @@ pub async fn delete_payment_method( }; db.update_customer_by_customer_id_merchant_id( + key_manager_state, key.customer_id, key.merchant_id, customer, @@ -4591,6 +4658,7 @@ pub async fn delete_payment_method( } pub async fn create_encrypted_data<T>( + state: &routes::SessionState, key_store: &domain::MerchantKeyStore, data: T, ) -> Result<Encryptable<Secret<serde_json::Value>>, error_stack::Report<errors::StorageError>> @@ -4598,6 +4666,8 @@ where T: Debug + serde::Serialize, { let key = key_store.key.get_inner().peek(); + let identifier = Identifier::Merchant(key_store.merchant_id.clone()); + let key_manager_state: KeyManagerState = state.into(); let encoded_data = Encode::encode_to_value(&data) .change_context(errors::StorageError::SerializationFailed) @@ -4605,10 +4675,11 @@ where let secret_data = Secret::<_, masking::WithType>::new(encoded_data); - let encrypted_data = domain::types::encrypt(secret_data, key) - .await - .change_context(errors::StorageError::EncryptionError) - .attach_printable("Unable to encrypt data")?; + let encrypted_data = + domain::types::encrypt(&key_manager_state, secret_data, identifier.clone(), key) + .await + .change_context(errors::StorageError::EncryptionError) + .attach_printable("Unable to encrypt data")?; Ok(encrypted_data) } diff --git a/crates/router/src/core/payment_methods/validator.rs b/crates/router/src/core/payment_methods/validator.rs index be34d3db38c..23470fb3ef1 100644 --- a/crates/router/src/core/payment_methods/validator.rs +++ b/crates/router/src/core/payment_methods/validator.rs @@ -27,6 +27,7 @@ pub async fn validate_request_and_initiate_payment_method_collect_link( let merchant_id = merchant_account.merchant_id.clone(); match db .find_customer_by_customer_id_merchant_id( + &state.into(), &customer_id, &merchant_id, key_store, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 5cad096bd39..9c420c1e44d 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -164,7 +164,7 @@ where let (operation, customer) = operation .to_domain()? .get_or_create_customer_details( - &*state.store, + state, &mut payment_data, customer_details, &key_store, @@ -208,8 +208,6 @@ where // Fetch and check FRM configs #[cfg(feature = "frm")] let mut frm_info = None; - #[cfg(feature = "frm")] - let db = &*state.store; #[allow(unused_variables, unused_mut)] let mut should_continue_transaction: bool = true; #[cfg(feature = "frm")] @@ -217,7 +215,6 @@ where #[cfg(feature = "frm")] let frm_configs = if state.conf.frm.enabled { Box::pin(frm_core::call_frm_before_connector_call( - db, &operation, &merchant_account, &mut payment_data, @@ -1203,6 +1200,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { let payment_intent = state .store .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, &merchant_id, &merchant_key_store, @@ -2883,7 +2881,7 @@ pub async fn list_payments( let merchant_id = &merchant.merchant_id; let db = state.store.as_ref(); let payment_intents = helpers::filter_by_constraints( - db, + &state, &constraints, merchant_id, &key_store, @@ -2955,6 +2953,7 @@ pub async fn apply_filters_on_payments( let db = state.store.as_ref(); let list: Vec<(storage::PaymentIntent, storage::PaymentAttempt)> = db .get_filtered_payment_intents_attempt( + &(&state).into(), &merchant.merchant_id, &constraints.clone().into(), &merchant_key_store, @@ -3008,6 +3007,7 @@ pub async fn get_filters_for_payments( let db = state.store.as_ref(); let pi = db .filter_payment_intents_by_time_range_constraints( + &(&state).into(), &merchant.merchant_id, &time_range, &merchant_key_store, @@ -4021,6 +4021,7 @@ pub async fn payment_external_authentication( let payment_id = req.payment_id; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &payment_id, merchant_id, &key_store, @@ -4054,6 +4055,7 @@ pub async fn payment_external_authentication( state .store .find_customer_by_customer_id_merchant_id( + &(&state).into(), customer_id, &merchant_account.merchant_id, &key_store, @@ -4076,7 +4078,7 @@ pub async fn payment_external_authentication( let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount(); let shipping_address = helpers::create_or_find_address_for_payment_by_request( - db, + &state, None, payment_intent.shipping_address_id.as_deref(), merchant_id, @@ -4087,7 +4089,7 @@ pub async fn payment_external_authentication( ) .await?; let billing_address = helpers::create_or_find_address_for_payment_by_request( - db, + &state, None, payment_intent.billing_address_id.as_deref(), merchant_id, @@ -4259,9 +4261,11 @@ pub async fn payments_manual_update( error_message, error_reason, } = req; + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, &merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -4270,7 +4274,7 @@ pub async fn payments_manual_update( .attach_printable("Error while fetching the key store by merchant_id")?; let merchant_account = state .store - .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the merchant_account by merchant_id")?; @@ -4290,6 +4294,7 @@ pub async fn payments_manual_update( let payment_intent = state .store .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &payment_id, &merchant_account.merchant_id, &key_store, @@ -4345,6 +4350,7 @@ pub async fn payments_manual_update( state .store .update_payment_intent( + &(&state).into(), payment_intent, payment_intent_update, &key_store, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 3629457d5ab..ecf8ff0c40d 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1,8 +1,9 @@ use std::{borrow::Cow, str::FromStr}; use api_models::{ + customers::CustomerRequestWithEmail, mandates::RecurringDetails, - payments::{CardToken, GetPaymentMethodType, RequestSurchargeDetails}, + payments::{AddressDetailsWithPhone, CardToken, GetPaymentMethodType, RequestSurchargeDetails}, }; use base64::Engine; use common_enums::ConnectorType; @@ -10,7 +11,10 @@ use common_utils::{ crypto::Encryptable, ext_traits::{AsyncExt, ByteSliceExt, Encode, ValueExt}, fp_utils, generate_id, id_type, pii, - types::MinorUnit, + types::{ + keymanager::{Identifier, KeyManagerState, ToEncryptable}, + MinorUnit, + }, }; use diesel_models::enums::{self}; // TODO : Evaluate all the helper functions () @@ -139,7 +143,7 @@ pub fn filter_mca_based_on_connector_type( #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn create_or_update_address_for_payment_by_request( - db: &dyn StorageInterface, + session_state: &SessionState, req_address: Option<&api::Address>, address_id: Option<&str>, merchant_id: &str, @@ -149,87 +153,54 @@ pub async fn create_or_update_address_for_payment_by_request( storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> { let key = merchant_key_store.key.get_inner().peek(); - + let db = &session_state.store; + let key_manager_state = &session_state.into(); Ok(match address_id { Some(id) => match req_address { Some(address) => { - let address_update = async { - Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( - storage::AddressUpdate::Update { - city: address - .address - .as_ref() - .and_then(|value| value.city.clone()), - country: address.address.as_ref().and_then(|value| value.country), - line1: address - .address - .as_ref() - .and_then(|value| value.line1.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - line2: address - .address - .as_ref() - .and_then(|value| value.line2.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - line3: address - .address - .as_ref() - .and_then(|value| value.line3.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - state: address - .address - .as_ref() - .and_then(|value| value.state.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - zip: address - .address - .as_ref() - .and_then(|value| value.zip.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - first_name: address - .address - .as_ref() - .and_then(|value| value.first_name.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - last_name: address - .address - .as_ref() - .and_then(|value| value.last_name.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - phone_number: address - .phone - .as_ref() - .and_then(|value| value.number.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - country_code: address - .phone - .as_ref() - .and_then(|value| value.country_code.clone()), - updated_by: storage_scheme.to_string(), - email: address - .email - .as_ref() - .cloned() - .async_lift(|inner| { - types::encrypt_optional(inner.map(|inner| inner.expose()), key) - }) - .await?, - }, - ) - } + let encrypted_data = types::batch_encrypt( + &session_state.into(), + AddressDetailsWithPhone::to_encryptable(AddressDetailsWithPhone { + address: address.address.clone(), + phone_number: address + .phone + .as_ref() + .and_then(|phone| phone.number.clone()), + email: address.email.clone(), + }), + Identifier::Merchant(merchant_key_store.merchant_id.clone()), + key, + ) .await .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 address_update = storage::AddressUpdate::Update { + city: address + .address + .as_ref() + .and_then(|value| value.city.clone()), + country: address.address.as_ref().and_then(|value| value.country), + line1: encryptable_address.line1, + line2: encryptable_address.line2, + line3: encryptable_address.line3, + state: encryptable_address.state, + zip: encryptable_address.zip, + first_name: encryptable_address.first_name, + last_name: encryptable_address.last_name, + phone_number: encryptable_address.phone_number, + country_code: address + .phone + .as_ref() + .and_then(|value| value.country_code.clone()), + updated_by: storage_scheme.to_string(), + email: encryptable_address.email, + }; let address = db .find_address_by_merchant_id_payment_id_address_id( + key_manager_state, merchant_id, payment_id, id, @@ -241,6 +212,7 @@ pub async fn create_or_update_address_for_payment_by_request( .attach_printable("Error while fetching address")?; Some( db.update_address_for_payments( + key_manager_state, address, address_update, payment_id.to_string(), @@ -254,6 +226,7 @@ pub async fn create_or_update_address_for_payment_by_request( } None => Some( db.find_address_by_merchant_id_payment_id_address_id( + key_manager_state, merchant_id, payment_id, id, @@ -268,10 +241,11 @@ pub async fn create_or_update_address_for_payment_by_request( }, None => match req_address { Some(address) => { - let address = get_domain_address(address, merchant_id, key, storage_scheme) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while encrypting address while insert")?; + let address = + get_domain_address(session_state, address, merchant_id, key, storage_scheme) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while encrypting address while insert")?; let payment_address = domain::PaymentAddress { address, @@ -281,6 +255,7 @@ pub async fn create_or_update_address_for_payment_by_request( Some( db.insert_address_for_payments( + key_manager_state, payment_id, payment_address, merchant_key_store, @@ -301,7 +276,7 @@ pub async fn create_or_update_address_for_payment_by_request( #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn create_or_find_address_for_payment_by_request( - db: &dyn StorageInterface, + state: &SessionState, req_address: Option<&api::Address>, address_id: Option<&str>, merchant_id: &str, @@ -311,10 +286,12 @@ pub async fn create_or_find_address_for_payment_by_request( storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> { let key = merchant_key_store.key.get_inner().peek(); - + let db = &state.store; + let key_manager_state = &state.into(); Ok(match address_id { Some(id) => Some( db.find_address_by_merchant_id_payment_id_address_id( + key_manager_state, merchant_id, payment_id, id, @@ -329,7 +306,7 @@ pub async fn create_or_find_address_for_payment_by_request( None => match req_address { Some(address) => { // generate a new address here - let address = get_domain_address(address, merchant_id, key, storage_scheme) + let address = get_domain_address(state, address, merchant_id, key, storage_scheme) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting address while insert")?; @@ -342,6 +319,7 @@ pub async fn create_or_find_address_for_payment_by_request( Some( db.insert_address_for_payments( + key_manager_state, payment_id, payment_address, merchant_key_store, @@ -359,70 +337,56 @@ pub async fn create_or_find_address_for_payment_by_request( } pub async fn get_domain_address( + session_state: &SessionState, address: &api_models::payments::Address, merchant_id: &str, key: &[u8], storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<domain::Address, common_utils::errors::CryptoError> { async { - let address_details = address.address.as_ref(); + let address_details = &address.address.as_ref(); + let encrypted_data = types::batch_encrypt( + &session_state.into(), + AddressDetailsWithPhone::to_encryptable(AddressDetailsWithPhone { + address: address_details.cloned(), + phone_number: address + .phone + .as_ref() + .and_then(|phone| phone.number.clone()), + email: address.email.clone(), + }), + Identifier::Merchant(merchant_id.to_string()), + key, + ) + .await?; + let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data) + .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(domain::Address { id: None, - phone_number: address - .phone - .as_ref() - .and_then(|a| a.number.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, + phone_number: encryptable_address.phone_number, country_code: address.phone.as_ref().and_then(|a| a.country_code.clone()), merchant_id: merchant_id.to_string(), address_id: generate_id(consts::ID_LENGTH, "add"), city: address_details.and_then(|address_details| address_details.city.clone()), country: address_details.and_then(|address_details| address_details.country), - line1: address_details - .and_then(|address_details| address_details.line1.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - line2: address_details - .and_then(|address_details| address_details.line2.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - line3: address_details - .and_then(|address_details| address_details.line3.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - state: address_details - .and_then(|address_details| address_details.state.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, + line1: encryptable_address.line1, + line2: encryptable_address.line2, + line3: encryptable_address.line3, + state: encryptable_address.state, created_at: common_utils::date_time::now(), - first_name: address_details - .and_then(|address_details| address_details.first_name.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - last_name: address_details - .and_then(|address_details| address_details.last_name.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, + first_name: encryptable_address.first_name, + last_name: encryptable_address.last_name, modified_at: common_utils::date_time::now(), - zip: address_details - .and_then(|address_details| address_details.zip.clone()) - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, + zip: encryptable_address.zip, updated_by: storage_scheme.to_string(), - email: address - .email - .as_ref() - .cloned() - .async_lift(|inner| types::encrypt_optional(inner.map(|inner| inner.expose()), key)) - .await?, + email: encryptable_address.email, }) } .await } pub async fn get_address_by_id( - db: &dyn StorageInterface, + state: &SessionState, address_id: Option<String>, merchant_key_store: &domain::MerchantKeyStore, payment_id: &str, @@ -431,17 +395,21 @@ pub async fn get_address_by_id( ) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> { match address_id { None => Ok(None), - Some(address_id) => Ok(db - .find_address_by_merchant_id_payment_id_address_id( - merchant_id, - payment_id, - &address_id, - merchant_key_store, - storage_scheme, - ) - .await - .map(|payment_address| payment_address.address) - .ok()), + Some(address_id) => { + let db = &*state.store; + Ok(db + .find_address_by_merchant_id_payment_id_address_id( + &state.into(), + merchant_id, + payment_id, + &address_id, + merchant_key_store, + storage_scheme, + ) + .await + .map(|payment_address| payment_address.address) + .ok()) + } } } @@ -688,12 +656,13 @@ pub async fn get_token_for_recurring_mandate( ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; - + let key_manager_state: KeyManagerState = state.into(); let original_payment_intent = mandate .original_payment_id .as_ref() .async_map(|payment_id| async { db.find_payment_intent_by_payment_id_merchant_id( + &key_manager_state, payment_id, &mandate.merchant_id, merchant_key_store, @@ -1429,7 +1398,7 @@ pub(crate) async fn get_payment_method_create_request( } pub async fn get_customer_from_details<F: Clone>( - db: &dyn StorageInterface, + state: &SessionState, customer_id: Option<id_type::CustomerId>, merchant_id: &str, payment_data: &mut PaymentData<F>, @@ -1439,8 +1408,10 @@ pub async fn get_customer_from_details<F: Clone>( match customer_id { None => Ok(None), Some(customer_id) => { + let db = &*state.store; let customer = db .find_customer_optional_by_customer_id_merchant_id( + &state.into(), &customer_id, merchant_id, merchant_key_store, @@ -1549,8 +1520,8 @@ pub async fn get_connector_default( #[instrument(skip_all)] #[allow(clippy::type_complexity)] pub async fn create_customer_if_not_exist<'a, F: Clone, R>( + state: &SessionState, operation: BoxedOperation<'a, F, R>, - db: &dyn StorageInterface, payment_data: &mut PaymentData<F>, req: Option<CustomerDetails>, merchant_id: &str, @@ -1613,7 +1584,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( payment_data.payment_intent.customer_details = raw_customer_details .clone() - .async_map(|customer_details| create_encrypted_data(key_store, customer_details)) + .async_map(|customer_details| create_encrypted_data(state, key_store, customer_details)) .await .transpose() .change_context(errors::StorageError::EncryptionError) @@ -1622,18 +1593,36 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( let customer_id = request_customer_details .customer_id .or(payment_data.payment_intent.customer_id.clone()); - + let db = &*state.store; + let key_manager_state = &state.into(); let optional_customer = match customer_id { Some(customer_id) => { let customer_data = db .find_customer_optional_by_customer_id_merchant_id( + key_manager_state, &customer_id, merchant_id, key_store, storage_scheme, ) .await?; - + let key = key_store.key.get_inner().peek(); + let encrypted_data = types::batch_encrypt( + key_manager_state, + CustomerRequestWithEmail::to_encryptable(CustomerRequestWithEmail { + name: request_customer_details.name.clone(), + email: request_customer_details.email.clone(), + phone: request_customer_details.phone.clone(), + }), + Identifier::Merchant(key_store.merchant_id.clone()), + key, + ) + .await + .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")?; Some(match customer_data { Some(c) => { // Update the customer data if new data is passed in the request @@ -1642,44 +1631,19 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( | request_customer_details.phone.is_some() | request_customer_details.phone_country_code.is_some() { - let key = key_store.key.get_inner().peek(); - let customer_update = async { - Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( - Update { - name: request_customer_details - .name - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - email: request_customer_details - .email - .clone() - .async_lift(|inner| { - types::encrypt_optional( - inner.map(|inner| inner.expose()), - key, - ) - }) - .await?, - phone: Box::new( - request_customer_details - .phone - .clone() - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - ), - phone_country_code: request_customer_details.phone_country_code, - description: None, - connector_customer: None, - metadata: None, - address_id: None, - }, - ) - } - .await - .change_context(errors::StorageError::SerializationFailed) - .attach_printable("Failed while encrypting Customer while Update")?; + let customer_update = Update { + name: encryptable_customer.name, + email: encryptable_customer.email, + phone: Box::new(encryptable_customer.phone), + phone_country_code: request_customer_details.phone_country_code, + description: None, + connector_customer: None, + metadata: None, + address_id: None, + }; db.update_customer_by_customer_id_merchant_id( + key_manager_state, customer_id, merchant_id.to_string(), c, @@ -1693,51 +1657,25 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( } } None => { - let new_customer = async { - let key = key_store.key.get_inner().peek(); - Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( - domain::Customer { - customer_id, - merchant_id: merchant_id.to_string(), - name: request_customer_details - .name - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - email: request_customer_details - .email - .clone() - .async_lift(|inner| { - types::encrypt_optional( - inner.map(|inner| inner.expose()), - key, - ) - }) - .await?, - phone: request_customer_details - .phone - .clone() - .async_lift(|inner| types::encrypt_optional(inner, key)) - .await?, - phone_country_code: request_customer_details - .phone_country_code - .clone(), - description: None, - created_at: common_utils::date_time::now(), - id: None, - metadata: None, - modified_at: common_utils::date_time::now(), - connector_customer: None, - address_id: None, - default_payment_method_id: None, - updated_by: None, - }, - ) - } - .await - .change_context(errors::StorageError::SerializationFailed) - .attach_printable("Failed while encrypting Customer while insert")?; + let new_customer = domain::Customer { + customer_id, + merchant_id: merchant_id.to_string(), + name: encryptable_customer.name, + email: encryptable_customer.email, + phone: encryptable_customer.phone, + phone_country_code: request_customer_details.phone_country_code.clone(), + description: None, + created_at: common_utils::date_time::now(), + id: None, + metadata: None, + modified_at: common_utils::date_time::now(), + connector_customer: None, + address_id: None, + default_payment_method_id: None, + updated_by: None, + }; metrics::CUSTOMER_CREATED.add(&metrics::CONTEXT, 1, &[]); - db.insert_customer(new_customer, key_store, storage_scheme) + db.insert_customer(key_manager_state, new_customer, key_store, storage_scheme) .await } }) @@ -1746,6 +1684,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( None => None, Some(customer_id) => db .find_customer_optional_by_customer_id_merchant_id( + key_manager_state, customer_id, merchant_id, key_store, @@ -2533,14 +2472,16 @@ where #[cfg(feature = "olap")] pub(super) async fn filter_by_constraints( - db: &dyn StorageInterface, + state: &SessionState, constraints: &api::PaymentListConstraints, merchant_id: &str, key_store: &domain::MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Vec<PaymentIntent>, errors::DataStorageError> { + let db = &*state.store; let result = db .filter_payment_intent_by_constraints( + &(state).into(), merchant_id, &constraints.clone().into(), key_store, @@ -2957,17 +2898,19 @@ pub(crate) fn validate_pm_or_token_given( // A function to perform database lookup and then verify the client secret pub async fn verify_payment_intent_time_and_client_secret( - db: &dyn StorageInterface, + state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, client_secret: Option<String>, ) -> error_stack::Result<Option<PaymentIntent>, errors::ApiErrorResponse> { + let db = &*state.store; client_secret .async_map(|cs| async move { let payment_id = get_payment_id_from_client_secret(&cs)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, &merchant_account.merchant_id, key_store, @@ -3371,6 +3314,7 @@ pub async fn get_merchant_connector_account( merchant_connector_id: Option<&String>, ) -> RouterResult<MerchantConnectorAccountType> { let db = &*state.store; + let key_manager_state = &state.into(); match creds_identifier { Some(creds_identifier) => { let key = format!("mcd_{merchant_id}_{creds_identifier}"); @@ -3445,6 +3389,7 @@ pub async fn get_merchant_connector_account( None => { if let Some(merchant_connector_id) = merchant_connector_id { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, merchant_id, merchant_connector_id, key_store, @@ -3457,6 +3402,7 @@ pub async fn get_merchant_connector_account( ) } else { db.find_merchant_connector_account_by_profile_id_connector_name( + key_manager_state, profile_id, connector_name, key_store, @@ -3737,13 +3683,14 @@ impl AttemptType { request: &api::PaymentsRequest, fetched_payment_intent: PaymentIntent, fetched_payment_attempt: PaymentAttempt, - db: &dyn StorageInterface, + state: &SessionState, key_store: &domain::MerchantKeyStore, storage_scheme: storage::enums::MerchantStorageScheme, ) -> RouterResult<(PaymentIntent, PaymentAttempt)> { match self { Self::SameOld => Ok((fetched_payment_intent, fetched_payment_attempt)), Self::New => { + let db = &*state.store; let new_attempt_count = fetched_payment_intent.attempt_count + 1; let new_payment_attempt = db .insert_payment_attempt( @@ -3766,6 +3713,7 @@ impl AttemptType { let updated_payment_intent = db .update_payment_intent( + &state.into(), fetched_payment_intent, storage::PaymentIntentUpdate::StatusAndAttemptUpdate { status: payment_intent_status_fsm( @@ -4159,6 +4107,7 @@ pub fn is_apple_pay_simplified_flow( } pub async fn get_encrypted_apple_pay_connector_wallets_details( + state: &SessionState, key_store: &domain::MerchantKeyStore, connector_metadata: &Option<masking::Secret<tera::Value>>, ) -> RouterResult<Option<Encryptable<masking::Secret<serde_json::Value>>>> { @@ -4179,10 +4128,15 @@ pub async fn get_encrypted_apple_pay_connector_wallets_details( }) .transpose()? .map(masking::Secret::new); - + let key_manager_state: KeyManagerState = state.into(); let encrypted_connector_apple_pay_details = connector_apple_pay_details .async_lift(|wallets_details| { - types::encrypt_optional(wallets_details, key_store.key.get_inner().peek()) + types::encrypt_optional( + &key_manager_state, + wallets_details, + Identifier::Merchant(key_store.merchant_id.clone()), + key_store.key.get_inner().peek(), + ) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -4266,6 +4220,7 @@ where let merchant_connector_account_list = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( + &state.into(), merchant_account.merchant_id.as_str(), false, key_store, @@ -5126,13 +5081,15 @@ pub async fn override_setup_future_usage_to_on_session<F: Clone>( } pub async fn validate_merchant_connector_ids_in_connector_mandate_details( - db: &dyn StorageInterface, + state: &SessionState, key_store: &domain::MerchantKeyStore, connector_mandate_details: &api_models::payment_methods::PaymentsMandateReference, merchant_id: &str, ) -> CustomResult<(), errors::ApiErrorResponse> { + let db = &*state.store; let merchant_connector_account_list = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( + &state.into(), merchant_id, true, key_store, diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index be54ead0ac1..70cc77aa536 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -28,7 +28,6 @@ pub use self::{ use super::{helpers, CustomerDetails, PaymentData}; use crate::{ core::errors::{self, CustomResult, RouterResult}, - db::StorageInterface, routes::{app::ReqState, SessionState}, services, types::{ @@ -117,7 +116,7 @@ pub trait Domain<F: Clone, R>: Send + Sync { /// This will fetch customer details, (this operation is flow specific) async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, @@ -259,7 +258,7 @@ where #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, _request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, @@ -274,7 +273,7 @@ where Ok(( Box::new(self), helpers::get_customer_from_details( - db, + state, payment_data.payment_intent.customer_id.clone(), &merchant_key_store.merchant_id, payment_data, @@ -334,7 +333,7 @@ where #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, _request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, @@ -349,7 +348,7 @@ where Ok(( Box::new(self), helpers::get_customer_from_details( - db, + state, payment_data.payment_intent.customer_id.clone(), &merchant_key_store.merchant_id, payment_data, @@ -408,7 +407,7 @@ where #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, _request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, @@ -423,7 +422,7 @@ where Ok(( Box::new(self), helpers::get_customer_from_details( - db, + state, payment_data.payment_intent.customer_id.clone(), &merchant_key_store.merchant_id, payment_data, @@ -483,7 +482,7 @@ where #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - _db: &dyn StorageInterface, + _state: &SessionState, _payment_data: &mut PaymentData<F>, _request: Option<CustomerDetails>, _merchant_key_store: &domain::MerchantKeyStore, diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index 172c5943c0c..5b18512fe20 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -53,6 +53,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -97,7 +98,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( - db, + state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id, @@ -107,7 +108,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> .await?; let billing_address = helpers::get_address_by_id( - db, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -117,7 +118,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> .await?; let payment_method_billing = helpers::get_address_by_id( - db, + state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -199,7 +200,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> for #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, - db: &'b SessionState, + state: &'b SessionState, _req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, @@ -224,9 +225,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> for merchant_decision: Some(api_models::enums::MerchantDecision::Approved.to_string()), updated_by: storage_scheme.to_string(), }; - payment_data.payment_intent = db + payment_data.payment_intent = state .store .update_payment_intent( + &state.into(), payment_data.payment_intent, intent_status_update, key_store, @@ -234,7 +236,8 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> for ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - db.store + state + .store .update_payment_attempt_with_attempt_id( payment_data.payment_attempt.clone(), storage::PaymentAttemptUpdate::StatusUpdate { diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 94591d44e4b..a8a2756a58d 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -51,6 +51,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -82,7 +83,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let shipping_address = helpers::get_address_by_id( - db, + state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id, @@ -92,7 +93,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> .await?; let billing_address = helpers::get_address_by_id( - db, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -102,7 +103,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> .await?; let payment_method_billing = helpers::get_address_by_id( - db, + state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -212,7 +213,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, - db: &'b SessionState, + state: &'b SessionState, req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, @@ -242,9 +243,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for }; if let Some(payment_intent_update) = intent_status_update { - payment_data.payment_intent = db + payment_data.payment_intent = state .store .update_payment_intent( + &state.into(), payment_data.payment_intent, payment_intent_update, key_store, @@ -254,7 +256,8 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; } - db.store + state + .store .update_payment_attempt_with_attempt_id( payment_data.payment_attempt.clone(), storage::PaymentAttemptUpdate::VoidUpdate { diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index f6e6dee14a5..03a3d031e1a 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -54,6 +54,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -135,7 +136,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( - db, + state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id, @@ -145,7 +146,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu .await?; let billing_address = helpers::get_address_by_id( - db, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -155,7 +156,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu .await?; let payment_method_billing = helpers::get_address_by_id( - db, + state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 9c48df1dd53..c6875392750 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -17,7 +17,6 @@ use crate::{ }, utils as core_utils, }, - db::StorageInterface, routes::{app::ReqState, SessionState}, services, types::{ @@ -56,6 +55,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -200,7 +200,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co )?; let shipping_address = helpers::create_or_update_address_for_payment_by_request( - db, + state, request.shipping.as_ref(), payment_intent.shipping_address_id.clone().as_deref(), merchant_id.as_ref(), @@ -216,7 +216,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co .map(|shipping_address| shipping_address.address_id.clone()); let billing_address = helpers::get_address_by_id( - db, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -226,7 +226,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co .await?; let payment_method_billing = helpers::get_address_by_id( - db, + state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -364,7 +364,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for CompleteAuthorize { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, @@ -377,8 +377,8 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for CompleteAuthorize { errors::StorageError, > { helpers::create_customer_if_not_exist( + state, Box::new(self), - db, payment_data, request, &key_store.merchant_id, @@ -478,6 +478,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Comple let updated_payment_intent = db .update_payment_intent( + &state.into(), payment_intent, payment_intent_update, key_store, diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 2955b0c3850..addd2f30670 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -7,7 +7,10 @@ use api_models::{ payments::{AdditionalPaymentData, ExtendedCardInfo}, }; use async_trait::async_trait; -use common_utils::ext_traits::{AsyncExt, Encode, StringExt, ValueExt}; +use common_utils::{ + ext_traits::{AsyncExt, Encode, StringExt, ValueExt}, + types::keymanager::Identifier, +}; use error_stack::{report, ResultExt}; use futures::FutureExt; use hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdateFields; @@ -30,7 +33,6 @@ use crate::{ }, utils as core_utils, }, - db::StorageInterface, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, @@ -74,6 +76,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa // Parallel calls - level 0 let mut payment_intent = store .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, m_merchant_id.as_str(), key_store, @@ -181,13 +184,13 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa let m_payment_intent_payment_id = payment_intent.payment_id.clone(); let m_customer_details_customer_id = customer_details.customer_id.clone(); let m_payment_intent_customer_id = payment_intent.customer_id.clone(); - let store = state.clone().store; let m_key_store = key_store.clone(); + let session_state = state.clone(); let shipping_address_fut = tokio::spawn( async move { helpers::create_or_update_address_for_payment_by_request( - store.as_ref(), + &session_state, m_request_shipping.as_ref(), m_payment_intent_shipping_address_id.as_deref(), m_merchant_id.as_str(), @@ -209,13 +212,13 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa let m_payment_intent_customer_id = payment_intent.customer_id.clone(); let m_payment_intent_billing_address_id = payment_intent.billing_address_id.clone(); let m_payment_intent_payment_id = payment_intent.payment_id.clone(); - let store = state.clone().store; let m_key_store = key_store.clone(); + let session_state = state.clone(); let billing_address_fut = tokio::spawn( async move { helpers::create_or_update_address_for_payment_by_request( - store.as_ref(), + &session_state, m_request_billing.as_ref(), m_payment_intent_billing_address_id.as_deref(), m_merchant_id.as_ref(), @@ -306,7 +309,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa request, payment_intent, payment_attempt, - &*state.store, + state, key_store, storage_scheme, ) @@ -467,8 +470,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .in_current_span(), ); - let store = state.clone().store; - let n_payment_method_billing_address_id = payment_attempt.payment_method_billing_address_id.clone(); let n_request_payment_method_billing_address = request @@ -480,11 +481,12 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa let m_key_store = key_store.clone(); let m_customer_details_customer_id = customer_details.customer_id.clone(); let m_merchant_id = merchant_id.clone(); + let session_state = state.clone(); let payment_method_billing_future = tokio::spawn( async move { helpers::create_or_update_address_for_payment_by_request( - store.as_ref(), + &session_state, n_request_payment_method_billing_address.as_ref(), n_payment_method_billing_address_id.as_deref(), m_merchant_id.as_str(), @@ -688,7 +690,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, @@ -701,8 +703,8 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm { errors::StorageError, > { helpers::create_customer_if_not_exist( + state, Box::new(self), - db, payment_data, request, &key_store.merchant_id, @@ -1077,12 +1079,15 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode additional pm data")?; + let key_manager_state = &state.into(); let encode_additional_pm_to_value = if let Some(ref pm) = payment_data.payment_method_info { let key = key_store.key.get_inner().peek(); let card_detail_from_locker: Option<api::CardDetailFromLocker> = decrypt::<serde_json::Value, masking::WithType>( + key_manager_state, pm.payment_method_data.clone(), + Identifier::Merchant(key_store.merchant_id.clone()), key, ) .await @@ -1243,7 +1248,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let billing_address = payment_data.address.get_payment_billing(); let billing_details = billing_address - .async_map(|billing_details| create_encrypted_data(key_store, billing_details)) + .async_map(|billing_details| create_encrypted_data(state, key_store, billing_details)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1251,7 +1256,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let shipping_address = payment_data.address.get_shipping(); let shipping_details = shipping_address - .async_map(|shipping_details| create_encrypted_data(key_store, shipping_details)) + .async_map(|shipping_details| create_encrypted_data(state, key_store, shipping_details)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1273,10 +1278,12 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let m_storage_scheme = storage_scheme.to_string(); let session_expiry = m_payment_data_payment_intent.session_expiry; let m_key_store = key_store.clone(); + let key_manager_state = state.into(); let payment_intent_fut = tokio::spawn( async move { m_db.update_payment_intent( + &key_manager_state, m_payment_data_payment_intent, storage::PaymentIntentUpdate::Update(Box::new(PaymentIntentUpdateFields { amount: payment_data.payment_intent.amount, @@ -1320,10 +1327,13 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let m_customer_merchant_id = customer.merchant_id.to_owned(); let m_key_store = key_store.clone(); let m_updated_customer = updated_customer.clone(); - let m_db = state.clone().store; + let session_state = state.clone(); + let m_db = session_state.store.clone(); + let key_manager_state = state.into(); tokio::spawn( async move { m_db.update_customer_by_customer_id_merchant_id( + &key_manager_state, m_customer_customer_id, m_customer_merchant_id, customer, diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 18dc2c5f39a..929f404eae9 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -6,7 +6,7 @@ use api_models::{ use async_trait::async_trait; use common_utils::{ ext_traits::{AsyncExt, Encode, ValueExt}, - types::MinorUnit, + types::{keymanager::Identifier, MinorUnit}, }; use diesel_models::{ephemeral_key, PaymentMethod}; use error_stack::{self, ResultExt}; @@ -32,7 +32,10 @@ use crate::{ utils as core_utils, }, db::StorageInterface, - routes::{app::ReqState, SessionState}, + routes::{ + app::{ReqState, SessionStateInfo}, + SessionState, + }, services, types::{ api::{self, PaymentIdTypeExt}, @@ -143,7 +146,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa let customer_details = helpers::get_customer_details_from_request(request); let shipping_address = helpers::create_or_find_address_for_payment_by_request( - db, + state, request.shipping.as_ref(), None, merchant_id, @@ -155,7 +158,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .await?; let billing_address = helpers::create_or_find_address_for_payment_by_request( - db, + state, request.billing.as_ref(), None, merchant_id, @@ -168,7 +171,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa let payment_method_billing_address = helpers::create_or_find_address_for_payment_by_request( - db, + state, request .payment_method_data .as_ref() @@ -286,7 +289,12 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .await?; payment_intent = db - .insert_payment_intent(payment_intent_new, merchant_key_store, storage_scheme) + .insert_payment_intent( + &state.into(), + payment_intent_new, + merchant_key_store, + storage_scheme, + ) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { payment_id: payment_id.clone(), @@ -475,7 +483,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, @@ -488,8 +496,8 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate { errors::StorageError, > { helpers::create_customer_if_not_exist( + state, Box::new(self), - db, payment_data, request, &key_store.merchant_id, @@ -638,12 +646,15 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let raw_customer_details = customer .map(|customer| CustomerData::try_from(customer.clone())) .transpose()?; + let session_state = state.session_state(); // Updation of Customer Details for the cases where both customer_id and specific customer // details are provided in Payment Create Request let customer_details = raw_customer_details .clone() - .async_map(|customer_details| create_encrypted_data(key_store, customer_details)) + .async_map(|customer_details| { + create_encrypted_data(&session_state, key_store, customer_details) + }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -652,6 +663,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen payment_data.payment_intent = state .store .update_payment_intent( + &state.into(), payment_data.payment_intent, storage::PaymentIntentUpdate::PaymentCreateUpdate { return_url: None, @@ -836,7 +848,9 @@ impl PaymentCreate { .as_ref() .async_map(|pm_info| async { decrypt::<serde_json::Value, masking::WithType>( + &state.into(), pm_info.payment_method_data.clone(), + Identifier::Merchant(key_store.merchant_id.clone()), key_store.key.get_inner().peek(), ) .await @@ -983,7 +997,7 @@ impl PaymentCreate { #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] async fn make_payment_intent( - _state: &SessionState, + state: &SessionState, payment_id: &str, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, @@ -1057,7 +1071,7 @@ impl PaymentCreate { let billing_details = request .billing .clone() - .async_map(|billing_details| create_encrypted_data(key_store, billing_details)) + .async_map(|billing_details| create_encrypted_data(state, key_store, billing_details)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1068,7 +1082,7 @@ impl PaymentCreate { let shipping_details = request .shipping .clone() - .async_map(|shipping_details| create_encrypted_data(key_store, shipping_details)) + .async_map(|shipping_details| create_encrypted_data(state, key_store, shipping_details)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1093,7 +1107,7 @@ impl PaymentCreate { // Encrypting our Customer Details to be stored in Payment Intent let customer_details = raw_customer_details - .async_map(|customer_details| create_encrypted_data(key_store, customer_details)) + .async_map(|customer_details| create_encrypted_data(state, key_store, customer_details)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index a3a8130a9f6..a83079a6a43 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -48,6 +48,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for P let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -79,7 +80,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for P .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let shipping_address = helpers::get_address_by_id( - db, + state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id, @@ -89,7 +90,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for P .await?; let billing_address = helpers::get_address_by_id( - db, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -99,7 +100,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for P .await?; let payment_method_billing = helpers::get_address_by_id( - db, + state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -234,6 +235,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> for Payme payment_data.payment_intent = state .store .update_payment_intent( + &state.into(), payment_data.payment_intent, intent_status_update, key_store, diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index fc075f29799..808b2ae6181 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -2,7 +2,10 @@ use std::collections::HashMap; use async_trait::async_trait; use common_enums::AuthorizationStatus; -use common_utils::{ext_traits::Encode, types::MinorUnit}; +use common_utils::{ + ext_traits::Encode, + types::{keymanager::KeyManagerState, MinorUnit}, +}; use error_stack::{report, ResultExt}; use futures::FutureExt; use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt; @@ -265,7 +268,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu { async fn update_tracker<'b>( &'b self, - db: &'b SessionState, + state: &'b SessionState, _payment_id: &api::PaymentIdType, mut payment_data: PaymentData<F>, router_data: types::RouterData< @@ -317,7 +320,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu }; //payment_attempt update if let Some(payment_attempt_update) = option_payment_attempt_update { - payment_data.payment_attempt = db + payment_data.payment_attempt = state .store .update_payment_attempt_with_attempt_id( payment_data.payment_attempt.clone(), @@ -329,9 +332,10 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu } // payment_intent update if let Some(payment_intent_update) = option_payment_intent_update { - payment_data.payment_intent = db + payment_data.payment_intent = state .store .update_payment_intent( + &state.into(), payment_data.payment_intent.clone(), payment_intent_update, key_store, @@ -370,7 +374,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu "missing authorization_id in incremental_authorization_details in payment_data", ), )?; - db.store + state + .store .update_authorization_by_merchant_id_authorization_id( router_data.merchant_id.clone(), authorization_id, @@ -380,7 +385,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed while updating authorization")?; //Fetch all the authorizations of the payment and send in incremental authorization response - let authorizations = db + let authorizations = state .store .find_all_authorizations_by_merchant_id_payment_id( &router_data.merchant_id, @@ -1255,9 +1260,11 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( let m_key_store = key_store.clone(); let m_payment_data_payment_intent = payment_data.payment_intent.clone(); let m_payment_intent_update = payment_intent_update.clone(); + let key_manager_state: KeyManagerState = state.into(); let payment_intent_fut = tokio::spawn( async move { m_db.update_payment_intent( + &key_manager_state, m_payment_data_payment_intent, m_payment_intent_update, &m_key_store, diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 503a5c5f2bb..00f599d4095 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -13,7 +13,6 @@ use crate::{ errors::{self, RouterResult, StorageErrorExt}, payments::{self, helpers, operations, PaymentData}, }, - db::StorageInterface, routes::{app::ReqState, SessionState}, services, types::{ @@ -53,6 +52,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> let mut payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -89,7 +89,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> let amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( - db, + state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id, @@ -99,7 +99,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> .await?; let billing_address = helpers::get_address_by_id( - db, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -109,7 +109,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> .await?; let payment_method_billing = helpers::get_address_by_id( - db, + state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -244,6 +244,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest> for Some(metadata) => state .store .update_payment_intent( + &state.into(), payment_data.payment_intent, storage::PaymentIntentUpdate::MetadataUpdate { metadata, @@ -295,7 +296,7 @@ where #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<payments::CustomerDetails>, key_store: &domain::MerchantKeyStore, @@ -308,8 +309,8 @@ where errors::StorageError, > { helpers::create_customer_if_not_exist( + state, Box::new(self), - db, payment_data, request, &key_store.merchant_id, @@ -358,6 +359,7 @@ where let all_connector_accounts = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( + &state.into(), &merchant_account.merchant_id, false, key_store, diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index c4096c6ea5a..98befe122cc 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -12,7 +12,6 @@ use crate::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, }, - db::StorageInterface, routes::{app::ReqState, SessionState}, services, types::{ @@ -51,6 +50,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -86,7 +86,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( - db, + state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id, @@ -96,7 +96,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f .await?; let billing_address = helpers::get_address_by_id( - db, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -106,7 +106,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f .await?; let payment_method_billing = helpers::get_address_by_id( - db, + state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id, @@ -268,7 +268,7 @@ where #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, @@ -281,8 +281,8 @@ where errors::StorageError, > { helpers::create_customer_if_not_exist( + state, Box::new(self), - db, payment_data, request, &key_store.merchant_id, diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 5f20ccdf277..fff096d9b4c 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -2,7 +2,7 @@ use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; -use common_utils::ext_traits::AsyncExt; +use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use error_stack::ResultExt; use router_derive::PaymentOperation; use router_env::{instrument, logger, tracing}; @@ -16,7 +16,6 @@ use crate::{ PaymentData, }, }, - db::StorageInterface, routes::{app::ReqState, SessionState}, services, types::{ @@ -58,7 +57,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, @@ -71,8 +70,8 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus { errors::StorageError, > { helpers::create_customer_if_not_exist( + state, Box::new(self), - db, payment_data, request, &key_store.merchant_id, @@ -197,7 +196,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest payment_id, merchant_account, key_store, - &*state.store, + state, request, self, merchant_account.storage_scheme, @@ -214,7 +213,7 @@ async fn get_tracker_for_sync< payment_id: &api::PaymentIdType, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - db: &dyn StorageInterface, + state: &SessionState, request: &api::PaymentsRetrieveRequest, operation: Op, storage_scheme: enums::MerchantStorageScheme, @@ -222,7 +221,7 @@ async fn get_tracker_for_sync< let (payment_intent, mut payment_attempt, currency, amount); (payment_intent, payment_attempt) = get_payment_intent_payment_attempt( - db, + state, payment_id, &merchant_account.merchant_id, key_store, @@ -238,7 +237,7 @@ async fn get_tracker_for_sync< amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( - db, + state, payment_intent.shipping_address_id.clone(), key_store, &payment_intent.payment_id.clone(), @@ -247,7 +246,7 @@ async fn get_tracker_for_sync< ) .await?; let billing_address = helpers::get_address_by_id( - db, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id.clone(), @@ -257,7 +256,7 @@ async fn get_tracker_for_sync< .await?; let payment_method_billing = helpers::get_address_by_id( - db, + state, payment_attempt.payment_method_billing_address_id.clone(), key_store, &payment_intent.payment_id.clone(), @@ -267,7 +266,7 @@ async fn get_tracker_for_sync< .await?; payment_attempt.encoded_data.clone_from(&request.param); - + let db = &*state.store; let attempts = match request.expand_attempts { Some(true) => { Some(db @@ -510,18 +509,21 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRetrieveRequest> for Payme } pub async fn get_payment_intent_payment_attempt( - db: &dyn StorageInterface, + state: &SessionState, payment_id: &api::PaymentIdType, merchant_id: &str, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<(storage::PaymentIntent, storage::PaymentAttempt)> { + let key_manager_state: KeyManagerState = state.into(); + let db = &*state.store; let get_pi_pa = || async { let (pi, pa); match payment_id { api_models::payments::PaymentIdType::PaymentIntentId(ref id) => { pi = db .find_payment_intent_by_payment_id_merchant_id( + &key_manager_state, id, merchant_id, key_store, @@ -547,6 +549,7 @@ pub async fn get_payment_intent_payment_attempt( .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( + &key_manager_state, pa.payment_id.as_str(), merchant_id, key_store, @@ -560,6 +563,7 @@ pub async fn get_payment_intent_payment_attempt( .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( + &key_manager_state, pa.payment_id.as_str(), merchant_id, key_store, @@ -578,6 +582,7 @@ pub async fn get_payment_intent_payment_attempt( pi = db .find_payment_intent_by_payment_id_merchant_id( + &key_manager_state, pa.payment_id.as_str(), merchant_id, key_store, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 98006e574ca..f95ec0d0143 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -24,7 +24,6 @@ use crate::{ payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, utils as core_utils, }, - db::StorageInterface, routes::{app::ReqState, SessionState}, services, types::{ @@ -64,6 +63,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -193,7 +193,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa } let shipping_address = helpers::create_or_update_address_for_payment_by_request( - db, + state, request.shipping.as_ref(), payment_intent.shipping_address_id.as_deref(), merchant_id, @@ -207,7 +207,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa ) .await?; let billing_address = helpers::create_or_update_address_for_payment_by_request( - db, + state, request.billing.as_ref(), payment_intent.billing_address_id.as_deref(), merchant_id, @@ -222,7 +222,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .await?; let payment_method_billing = helpers::create_or_update_address_for_payment_by_request( - db, + state, request .payment_method_data .as_ref() @@ -491,7 +491,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - db: &dyn StorageInterface, + state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, @@ -504,8 +504,8 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate { errors::StorageError, > { helpers::create_customer_if_not_exist( + state, Box::new(self), - db, payment_data, request, &key_store.merchant_id, @@ -715,7 +715,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let billing_details = payment_data .address .get_payment_billing() - .async_map(|billing_details| create_encrypted_data(key_store, billing_details)) + .async_map(|billing_details| create_encrypted_data(state, key_store, billing_details)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -724,7 +724,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen let shipping_details = payment_data .address .get_shipping() - .async_map(|shipping_details| create_encrypted_data(key_store, shipping_details)) + .async_map(|shipping_details| create_encrypted_data(state, key_store, shipping_details)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -741,6 +741,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen payment_data.payment_intent = state .store .update_payment_intent( + &state.into(), payment_data.payment_intent.clone(), storage::PaymentIntentUpdate::Update(Box::new(PaymentIntentUpdateFields { amount: payment_data.amount.into(), diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs index 61a629df622..20c2e051b61 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -16,10 +16,7 @@ use crate::{ PaymentAddress, }, }, - routes::{ - app::{ReqState, StorageInterface}, - SessionState, - }, + routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, @@ -59,6 +56,7 @@ impl<F: Send + Clone> let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &state.into(), &payment_id, merchant_id, key_store, @@ -179,7 +177,7 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, PaymentsIncrementalAut #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, - db: &'b SessionState, + state: &'b SessionState, _req_state: ReqState, mut payment_data: payments::PaymentData<F>, _customer: Option<domain::Customer>, @@ -224,7 +222,7 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, PaymentsIncrementalAut connector_authorization_id: None, previously_authorized_amount: payment_data.payment_intent.amount, }; - let authorization = db + let authorization = state .store .insert_authorization(authorization_new.clone()) .await @@ -236,9 +234,10 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, PaymentsIncrementalAut }) .attach_printable("failed while inserting new authorization")?; // Update authorization_count in payment_intent - payment_data.payment_intent = db + payment_data.payment_intent = state .store .update_payment_intent( + &state.into(), payment_data.payment_intent.clone(), storage::PaymentIntentUpdate::AuthorizationCountUpdate { authorization_count: new_authorization_count, @@ -295,7 +294,7 @@ impl<F: Clone + Send> Domain<F, PaymentsIncrementalAuthorizationRequest> #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, - _db: &dyn StorageInterface, + _state: &SessionState, _payment_data: &mut payments::PaymentData<F>, _request: Option<CustomerDetails>, _merchant_key_store: &domain::MerchantKeyStore, diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index bf5ae5aa635..99cb6aaec68 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -469,6 +469,7 @@ where payment_data.payment_intent = db .update_payment_intent( + &state.into(), payment_data.payment_intent.clone(), storage::PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { active_attempt_id: payment_data.payment_attempt.attempt_id.clone(), diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 0ff53c63b48..ff9f6ddbf3a 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -528,6 +528,7 @@ pub async fn refresh_cgraph_cache<'a>( let mut merchant_connector_accounts = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( + &state.into(), &key_store.merchant_id, false, key_store, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index b77bdb7515e..40163367139 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -8,7 +8,7 @@ use common_utils::{ id_type, pii, }; use error_stack::{report, ResultExt}; -use masking::{ExposeInterface, PeekInterface, Secret}; +use masking::{ExposeInterface, Secret}; use router_env::{instrument, metrics::add_attributes, tracing}; use super::helpers; @@ -214,7 +214,7 @@ where let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = pm_card_details - .async_map(|pm_card| create_encrypted_data(key_store, pm_card)) + .async_map(|pm_card| create_encrypted_data(state, key_store, pm_card)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -223,7 +223,7 @@ where let encrypted_payment_method_billing_address: Option< Encryptable<Secret<serde_json::Value>>, > = payment_method_billing_address - .async_map(|address| create_encrypted_data(key_store, address.clone())) + .async_map(|address| create_encrypted_data(state, key_store, address.clone())) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -310,7 +310,7 @@ where let pm_metadata = create_payment_method_metadata(None, connector_token)?; payment_methods::cards::create_payment_method( - db, + state, &payment_method_create_request, &customer_id, &resp.payment_method_id, @@ -407,7 +407,7 @@ where Err(err) => { if err.current_context().is_db_not_found() { payment_methods::cards::insert_payment_method( - db, + state, &resp, &payment_method_create_request.clone(), key_store, @@ -479,10 +479,8 @@ where ))? }; - let existing_pm_data = payment_methods::cards::get_card_details_without_locker_fallback( - &existing_pm, - key_store.key.peek(), - state, + let existing_pm_data = payment_methods::cards::get_card_details_without_locker_fallback(&existing_pm,state, + key_store, ) .await?; @@ -518,7 +516,7 @@ where let pm_data_encrypted: Option< Encryptable<Secret<serde_json::Value>>, > = updated_pmd - .async_map(|pmd| create_encrypted_data(key_store, pmd)) + .async_map(|pmd| create_encrypted_data(state, key_store, pmd)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -601,7 +599,7 @@ where resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); payment_methods::cards::create_payment_method( - db, + state, &payment_method_create_request, &customer_id, &resp.payment_method_id, diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs index 3de8e505499..78ff9900f66 100644 --- a/crates/router/src/core/payout_link.rs +++ b/crates/router/src/core/payout_link.rs @@ -122,6 +122,7 @@ pub async fn initiate_payout_link( // Fetch customer let customer = db .find_customer_by_customer_id_merchant_id( + &(&state).into(), &customer_id, &req.merchant_id, &key_store, @@ -263,10 +264,12 @@ pub async fn filter_payout_methods( key_store: &domain::MerchantKeyStore, payout: &hyperswitch_domain_models::payouts::payouts::Payouts, ) -> errors::RouterResult<Vec<link_utils::EnabledPaymentMethod>> { - let db: &dyn StorageInterface = &*state.store; + let db = &*state.store; + let key_manager_state = &state.into(); //Fetch all merchant connector accounts let all_mcas = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( + key_manager_state, &merchant_account.merchant_id, false, key_store, @@ -282,7 +285,7 @@ pub async fn filter_payout_methods( common_enums::ConnectorType::PayoutProcessor, ); let address = db - .find_address_by_address_id(&payout.address_id.clone(), key_store) + .find_address_by_address_id(key_manager_state, &payout.address_id.clone(), key_store) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index b2c883c381b..6db3c1edf43 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -732,6 +732,7 @@ pub async fn payouts_list_core( Ok(payout_attempt) => { match db .find_customer_by_customer_id_merchant_id( + &(&state).into(), &payouts.customer_id, merchant_id, &key_store, @@ -822,7 +823,14 @@ pub async fn payouts_filtered_list_core( .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let data: Vec<api::PayoutCreateResponse> = join_all(list.into_iter().map(|(p, pa, c)| async { - match domain::Customer::convert_back(c, &key_store.key).await { + match domain::Customer::convert_back( + &(&state).into(), + c, + &key_store.key, + key_store.merchant_id.clone(), + ) + .await + { Ok(domain_cust) => Some((p, pa, domain_cust)), Err(err) => { logger::warn!( @@ -1084,6 +1092,7 @@ pub async fn create_recipient( { payout_data.customer_details = Some( db.update_customer_by_customer_id_merchant_id( + &state.into(), customer_id, merchant_id, customer, @@ -2184,7 +2193,7 @@ pub async fn payout_create_db_entries( // Get or create address let billing_address = payment_helpers::create_or_find_address_for_payment_by_request( - db, + state, req.billing.as_ref(), None, merchant_id, @@ -2345,7 +2354,7 @@ pub async fn make_payout_data( .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let billing_address = payment_helpers::create_or_find_address_for_payment_by_request( - db, + state, None, Some(&payouts.address_id.to_owned()), merchant_id, @@ -2358,6 +2367,7 @@ pub async fn make_payout_data( let customer_details = db .find_customer_optional_by_customer_id_merchant_id( + &state.into(), &payouts.customer_id.to_owned(), merchant_id, key_store, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 3ab17143202..6cda7b28433 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -1,13 +1,17 @@ -use api_models::{enums, payment_methods::Card, payouts}; +use api_models::{customers::CustomerRequestWithEmail, enums, payment_methods::Card, payouts}; use common_utils::{ + encryption::Encryption, errors::CustomResult, ext_traits::{AsyncExt, StringExt}, fp_utils, generate_customer_id_of_default_length, id_type, - types::MinorUnit, + types::{ + keymanager::{Identifier, KeyManagerState, ToEncryptable}, + MinorUnit, + }, }; -use diesel_models::encryption::Encryption; use error_stack::{report, ResultExt}; -use masking::{ExposeInterface, PeekInterface, Secret}; +use hyperswitch_domain_models::type_encryption::batch_encrypt; +use masking::{PeekInterface, Secret}; use router_env::logger; use super::PayoutData; @@ -233,6 +237,7 @@ pub async fn save_payout_data_to_locker( } _ => { let key = key_store.key.get_inner().peek(); + let key_manager_state: KeyManagerState = state.into(); let enc_data = async { serde_json::to_value(payout_method_data.to_owned()) .change_context(errors::ApiErrorResponse::InternalServerError) @@ -242,7 +247,14 @@ pub async fn save_payout_data_to_locker( let secret: Secret<String> = Secret::new(v.to_string()); secret }) - .async_lift(|inner| domain_types::encrypt_optional(inner, key)) + .async_lift(|inner| { + domain_types::encrypt_optional( + &key_manager_state, + inner, + Identifier::Merchant(key_store.merchant_id.clone()), + key, + ) + }) .await } .await @@ -453,7 +465,7 @@ pub async fn save_payout_data_to_locker( }); ( Some( - cards::create_encrypted_data(key_store, pm_data) + cards::create_encrypted_data(state, key_store, pm_data) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt customer details")?, @@ -489,7 +501,7 @@ pub async fn save_payout_data_to_locker( if should_insert_in_pm_table { let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); cards::create_payment_method( - db, + state, &new_payment_method, &payout_attempt.customer_id, &payment_method_id, @@ -601,9 +613,11 @@ pub async fn get_or_create_customer_details( let merchant_id = &merchant_account.merchant_id; let key = key_store.key.get_inner().peek(); + let key_manager_state = &state.into(); match db .find_customer_optional_by_customer_id_merchant_id( + key_manager_state, &customer_id, merchant_id, key_store, @@ -614,21 +628,28 @@ pub async fn get_or_create_customer_details( { Some(customer) => Ok(Some(customer)), None => { + let encrypted_data = batch_encrypt( + &state.into(), + CustomerRequestWithEmail::to_encryptable(CustomerRequestWithEmail { + name: customer_details.name.clone(), + email: customer_details.email.clone(), + phone: customer_details.phone.clone(), + }), + Identifier::Merchant(key_store.merchant_id.clone()), + key, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + let encryptable_customer = + CustomerRequestWithEmail::from_encryptable(encrypted_data) + .change_context(errors::ApiErrorResponse::InternalServerError)?; + let customer = domain::Customer { customer_id, merchant_id: merchant_id.to_string(), - name: domain_types::encrypt_optional(customer_details.name.to_owned(), key) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?, - email: domain_types::encrypt_optional( - customer_details.email.to_owned().map(|e| e.expose()), - key, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?, - phone: domain_types::encrypt_optional(customer_details.phone.to_owned(), key) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?, + name: encryptable_customer.name, + email: encryptable_customer.email, + phone: encryptable_customer.phone, description: None, phone_country_code: customer_details.phone_country_code.to_owned(), metadata: None, @@ -642,9 +663,14 @@ pub async fn get_or_create_customer_details( }; Ok(Some( - db.insert_customer(customer, key_store, merchant_account.storage_scheme) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?, + db.insert_customer( + key_manager_state, + customer, + key_store, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?, )) } } diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index 3434ac3e9c7..32e5ef308cf 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -15,7 +15,7 @@ use common_utils::{ crypto::{HmacSha256, SignMessage}, ext_traits::AsyncExt, generate_id, - types::{self as util_types, AmountConvertor}, + types::{self as util_types, keymanager::Identifier, AmountConvertor}, }; use error_stack::ResultExt; use helpers::PaymentAuthConnectorDataExt; @@ -110,7 +110,7 @@ pub async fn create_link_token( > = connector.connector.get_connector_integration(); let payment_intent = oss_helpers::verify_payment_intent_time_and_client_secret( - &*state.store, + &state, &merchant_account, &key_store, payload.client_secret, @@ -121,7 +121,7 @@ pub async fn create_link_token( .as_ref() .async_map(|pi| async { oss_helpers::get_address_by_id( - &*state.store, + &state, pi.billing_address_id.clone(), &key_store, &pi.payment_id, @@ -139,6 +139,7 @@ pub async fn create_link_token( let merchant_connector_account = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &(&state).into(), merchant_account.merchant_id.as_str(), &selected_config.mca_id, &key_store, @@ -234,6 +235,7 @@ pub async fn exchange_token_core( let merchant_connector_account = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &(&state).into(), merchant_account.merchant_id.as_str(), &config.mca_id, &key_store, @@ -294,6 +296,7 @@ async fn store_bank_details_in_payment_methods( let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &payload.payment_id, &merchant_account.merchant_id, &key_store, @@ -326,7 +329,9 @@ async fn store_bank_details_in_payment_methods( for pm in payment_methods { if pm.payment_method == Some(enums::PaymentMethod::BankDebit) { let bank_details_pm_data = decrypt::<serde_json::Value, masking::WithType>( + &(&state).into(), pm.payment_method_data.clone(), + Identifier::Merchant(key_store.merchant_id.clone()), key, ) .await @@ -433,10 +438,11 @@ async fn store_bank_details_in_payment_methods( ); let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd); - let encrypted_data = cards::create_encrypted_data(&key_store, payment_method_data) - .await - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt customer details")?; + let encrypted_data = + cards::create_encrypted_data(&state, &key_store, payment_method_data) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt customer details")?; let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data: Some(encrypted_data.into()), @@ -446,7 +452,7 @@ async fn store_bank_details_in_payment_methods( } else { let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd); let encrypted_data = - cards::create_encrypted_data(&key_store, Some(payment_method_data)) + cards::create_encrypted_data(&state, &key_store, Some(payment_method_data)) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt customer details")?; @@ -701,14 +707,19 @@ pub async fn retrieve_payment_method_from_auth_service( let connector = PaymentAuthConnectorData::get_connector_by_name( auth_token.connector_details.connector.as_str(), )?; - + let key_manager_state = &state.into(); let merchant_account = db - .find_merchant_account_by_merchant_id(&payment_intent.merchant_id, key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &payment_intent.merchant_id, + key_store, + ) .await .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?; let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, &payment_intent.merchant_id, &auth_token.connector_details.mca_id, key_store, @@ -770,7 +781,7 @@ pub async fn retrieve_payment_method_from_auth_service( } let address = oss_helpers::get_address_by_id( - &*state.store, + state, payment_intent.billing_address_id.clone(), key_store, &payment_intent.payment_id, diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 5b74eefb9a4..374c37dc217 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -57,6 +57,7 @@ pub async fn refund_create_core( payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), &req.payment_id, merchant_id, &key_store, @@ -415,6 +416,7 @@ pub async fn refund_retrieve_core( let payment_id = refund.payment_id.as_str(); payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(&state).into(), payment_id, merchant_id, &key_store, @@ -924,9 +926,11 @@ pub async fn refund_manual_update( state: SessionState, req: api_models::refunds::RefundManualUpdateRequest, ) -> RouterResponse<serde_json::Value> { + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, &req.merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -935,7 +939,7 @@ pub async fn refund_manual_update( .attach_printable("Error while fetching the key store by merchant_id")?; let merchant_account = state .store - .find_merchant_account_by_merchant_id(&req.merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &req.merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the merchant_account by merchant_id")?; @@ -1125,6 +1129,7 @@ pub async fn sync_refund_with_gateway_workflow( state: &SessionState, refund_tracker: &storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { + let key_manager_state = &state.into(); let refund_core = serde_json::from_value::<storage::RefundCoreWorkflow>(refund_tracker.tracking_data.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1138,6 +1143,7 @@ pub async fn sync_refund_with_gateway_workflow( let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, &refund_core.merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -1145,7 +1151,11 @@ pub async fn sync_refund_with_gateway_workflow( let merchant_account = state .store - .find_merchant_account_by_merchant_id(&refund_core.merchant_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &refund_core.merchant_id, + &key_store, + ) .await?; let response = Box::pin(refund_retrieve_core( @@ -1220,17 +1230,22 @@ pub async fn trigger_refund_execute_workflow( refund_tracker.tracking_data ) })?; - + let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, &refund_core.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await?; let merchant_account = db - .find_merchant_account_by_merchant_id(&refund_core.merchant_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &refund_core.merchant_id, + &key_store, + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -1245,7 +1260,11 @@ pub async fn trigger_refund_execute_workflow( match (&refund.sent_to_gateway, &refund.refund_status) { (false, enums::RefundStatus::Pending) => { let merchant_account = db - .find_merchant_account_by_merchant_id(&refund.merchant_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &refund.merchant_id, + &key_store, + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -1261,6 +1280,7 @@ pub async fn trigger_refund_execute_workflow( let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( + &(state.into()), &payment_attempt.payment_id, &refund.merchant_id, &key_store, diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 5f10de56e47..b17217737be 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -120,7 +120,7 @@ pub async fn create_routing_config( .await?; helpers::validate_connectors_in_routing_config( - db, + &state, &key_store, &merchant_account.merchant_id, &profile_id, diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index d99177aa555..707ed41d95a 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -15,6 +15,7 @@ use storage_impl::redis::cache; use crate::{ core::errors::{self, RouterResult}, db::StorageInterface, + routes::SessionState, types::{domain, storage}, utils::StringExt, }; @@ -186,7 +187,7 @@ pub async fn update_routing_algorithm( /// This will help make one of all configured algorithms to be in active state for a particular /// merchant pub async fn update_merchant_active_algorithm_ref( - db: &dyn StorageInterface, + state: &SessionState, key_store: &domain::MerchantKeyStore, config_key: cache::CacheKind<'_>, algorithm_id: routing_types::RoutingAlgorithmRef, @@ -218,8 +219,9 @@ pub async fn update_merchant_active_algorithm_ref( payment_link_config: None, pm_collect_link_config: None, }; - + let db = &*state.store; db.update_specific_fields_in_merchant( + &state.into(), &key_store.merchant_id, merchant_account_update, key_store, @@ -300,14 +302,16 @@ pub async fn update_business_profile_active_algorithm_ref( } pub async fn validate_connectors_in_routing_config( - db: &dyn StorageInterface, + state: &SessionState, key_store: &domain::MerchantKeyStore, merchant_id: &str, profile_id: &str, routing_algorithm: &routing_types::RoutingAlgorithm, ) -> RouterResult<()> { - let all_mcas = db + let all_mcas = &*state + .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( + &state.into(), merchant_id, true, key_store, diff --git a/crates/router/src/core/surcharge_decision_config.rs b/crates/router/src/core/surcharge_decision_config.rs index b35d7c5ad28..55ea4ba16f8 100644 --- a/crates/router/src/core/surcharge_decision_config.rs +++ b/crates/router/src/core/surcharge_decision_config.rs @@ -91,7 +91,7 @@ pub async fn upsert_surcharge_decision_config( algo_id.update_surcharge_config_id(key.clone()); let config_key = cache::CacheKind::Surcharge(key.into()); - update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) + update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; @@ -128,7 +128,7 @@ pub async fn upsert_surcharge_decision_config( algo_id.update_surcharge_config_id(key.clone()); let config_key = cache::CacheKind::Surcharge(key.clone().into()); - update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) + update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; @@ -158,7 +158,7 @@ pub async fn delete_surcharge_decision_config( .unwrap_or_default(); algo_id.surcharge_config_algo_id = None; let config_key = cache::CacheKind::Surcharge(key.clone().into()); - update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) + update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update deleted algorithm ref")?; diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 461ac855364..be33ccc69e1 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -4,6 +4,7 @@ use api_models::{ payments::RedirectionResponse, user::{self as user_api, InviteMultipleUserResponse}, }; +use common_utils::types::keymanager::Identifier; #[cfg(feature = "email")] use diesel_models::user_role::UserRoleUpdate; use diesel_models::{ @@ -1104,9 +1105,11 @@ pub async fn create_internal_user( state: SessionState, request: user_api::CreateInternalUserRequest, ) -> UserResponse<()> { + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, consts::user_role::INTERNAL_USER_MERCHANT_ID, &state.store.get_master_key().to_vec().into(), ) @@ -1122,6 +1125,7 @@ pub async fn create_internal_user( let internal_merchant = state .store .find_merchant_account_by_merchant_id( + key_manager_state, consts::user_role::INTERNAL_USER_MERCHANT_ID, &key_store, ) @@ -1176,7 +1180,7 @@ pub async fn switch_merchant_id( } let user = user_from_token.get_user_from_db(&state).await?; - + let key_manager_state = &(&state).into(); let role_info = roles::RoleInfo::from_role_id( &state, &user_from_token.role_id, @@ -1190,6 +1194,7 @@ pub async fn switch_merchant_id( let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, request.merchant_id.as_str(), &state.store.get_master_key().to_vec().into(), ) @@ -1204,7 +1209,11 @@ pub async fn switch_merchant_id( let org_id = state .store - .find_merchant_account_by_merchant_id(request.merchant_id.as_str(), &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + request.merchant_id.as_str(), + &key_store, + ) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -1306,6 +1315,7 @@ pub async fn list_merchants_for_user( let merchant_accounts = state .store .list_multiple_merchant_accounts( + &(&state).into(), user_roles .iter() .map(|role| role.merchant_id.clone()) @@ -1852,7 +1862,9 @@ pub async fn update_totp( totp_secret: Some( // TODO: Impl conversion trait for User and move this there domain::types::encrypt::<String, masking::WithType>( + &(&state).into(), totp.get_secret_base32().into(), + Identifier::User(key_store.user_id.clone()), key_store.key.peek(), ) .await @@ -1918,7 +1930,10 @@ pub async fn transfer_user_key_store_keymanager( let db = &state.global_store; let key_stores = db - .get_all_user_key_store(&state.store.get_master_key().to_vec().into()) + .get_all_user_key_store( + &(&state).into(), + &state.store.get_master_key().to_vec().into(), + ) .await .change_context(UserErrors::InternalServerError)?; @@ -2056,10 +2071,12 @@ pub async fn create_user_authentication_method( ) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to decode DEK")?; - + let id = uuid::Uuid::new_v4().to_string(); let (private_config, public_config) = utils::user::construct_public_and_private_db_configs( + &state, &req.auth_method, &user_auth_encryption_key, + id.clone(), ) .await?; @@ -2103,7 +2120,7 @@ pub async fn create_user_authentication_method( state .store .insert_user_authentication_method(UserAuthenticationMethodNew { - id: uuid::Uuid::new_v4().to_string(), + id, auth_id, owner_id: req.owner_id, owner_type: req.owner_type, @@ -2137,8 +2154,10 @@ pub async fn update_user_authentication_method( .attach_printable("Failed to decode DEK")?; let (private_config, public_config) = utils::user::construct_public_and_private_db_configs( + &state, &req.auth_method, &user_auth_encryption_key, + req.id.clone(), ) .await?; @@ -2212,9 +2231,12 @@ pub async fn get_sso_auth_url( .await .to_not_found_response(UserErrors::InvalidUserAuthMethodOperation)?; - let open_id_private_config = - utils::user::decrypt_oidc_private_config(&state, user_authentication_method.private_config) - .await?; + let open_id_private_config = utils::user::decrypt_oidc_private_config( + &state, + user_authentication_method.private_config, + request.id.clone(), + ) + .await?; let open_id_public_config = serde_json::from_value::<user_api::OpenIdConnectPublicConfig>( user_authentication_method @@ -2264,9 +2286,12 @@ pub async fn sso_sign( .await .change_context(UserErrors::InternalServerError)?; - let open_id_private_config = - utils::user::decrypt_oidc_private_config(&state, user_authentication_method.private_config) - .await?; + let open_id_private_config = utils::user::decrypt_oidc_private_config( + &state, + user_authentication_method.private_config, + authentication_method_id, + ) + .await?; let open_id_public_config = serde_json::from_value::<user_api::OpenIdConnectPublicConfig>( user_authentication_method diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index 36489846294..b279d852d40 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -613,6 +613,7 @@ pub async fn backfill_metadata( let key_store = state .store .get_merchant_key_store_by_merchant_id( + &state.into(), &user.merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -713,6 +714,7 @@ pub async fn get_merchant_connector_account_by_name( state .store .find_merchant_connector_account_by_merchant_id_connector_name( + &state.into(), merchant_id, connector_name, key_store, diff --git a/crates/router/src/core/user/sample_data.rs b/crates/router/src/core/user/sample_data.rs index e1ccb3b0335..b679753b56c 100644 --- a/crates/router/src/core/user/sample_data.rs +++ b/crates/router/src/core/user/sample_data.rs @@ -25,6 +25,7 @@ pub async fn generate_sample_data_for_user( let key_store = state .store .get_merchant_key_store_by_merchant_id( + &(&state).into(), &user_from_token.merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -50,7 +51,7 @@ pub async fn generate_sample_data_for_user( state .store - .insert_payment_intents_batch_for_sample_data(payment_intents, &key_store) + .insert_payment_intents_batch_for_sample_data(&(&state).into(), payment_intents, &key_store) .await .switch()?; state @@ -74,10 +75,11 @@ pub async fn delete_sample_data_for_user( _req_state: ReqState, ) -> SampleDataApiResponse<()> { let merchant_id_del = user_from_token.merchant_id.as_str(); - + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, &user_from_token.merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -87,7 +89,7 @@ pub async fn delete_sample_data_for_user( state .store - .delete_payment_intents_for_sample_data(merchant_id_del, &key_store) + .delete_payment_intents_for_sample_data(key_manager_state, merchant_id_del, &key_store) .await .switch()?; state diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rs index b6e71b2828f..65ac5688325 100644 --- a/crates/router/src/core/verification.rs +++ b/crates/router/src/core/verification.rs @@ -91,13 +91,19 @@ pub async fn get_verified_apple_domains_with_mid_mca_id( errors::ApiErrorResponse, > { let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let key_store = db - .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &merchant_id, + &db.get_master_key().to_vec().into(), + ) .await .change_context(errors::ApiErrorResponse::MerchantAccountNotFound)?; let verified_domains = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, merchant_id.as_str(), merchant_connector_id.as_str(), &key_store, diff --git a/crates/router/src/core/verification/utils.rs b/crates/router/src/core/verification/utils.rs index bfbc1cb8b44..a59789b2802 100644 --- a/crates/router/src/core/verification/utils.rs +++ b/crates/router/src/core/verification/utils.rs @@ -15,9 +15,11 @@ pub async fn check_existence_and_add_domain_to_db( merchant_connector_id: String, domain_from_req: Vec<String>, ) -> CustomResult<Vec<String>, errors::ApiErrorResponse> { + let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, &merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -27,6 +29,7 @@ pub async fn check_existence_and_add_domain_to_db( let merchant_connector_account = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, &merchant_id, &merchant_connector_id, &key_store, @@ -66,6 +69,7 @@ pub async fn check_existence_and_add_domain_to_db( state .store .update_merchant_connector_account( + key_manager_state, merchant_connector_account, updated_mca.into(), &key_store, diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 9eb74dc2df4..5c5346ce134 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -258,7 +258,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( Some(merchant_connector_account) => merchant_connector_account, None => { helper_utils::get_mca_from_object_reference_id( - &*state.clone().store, + &state, object_ref_id.clone(), &merchant_account, &connector_name, @@ -1675,6 +1675,7 @@ async fn fetch_optional_mca_and_connector( if connector_name_or_mca_id.starts_with("mca_") { let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &state.into(), &merchant_account.merchant_id, connector_name_or_mca_id, key_store, diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs index c40b4ae8869..ed2b41dc64d 100644 --- a/crates/router/src/core/webhooks/outgoing.rs +++ b/crates/router/src/core/webhooks/outgoing.rs @@ -4,7 +4,7 @@ use api_models::{ webhook_events::{OutgoingWebhookRequestContent, OutgoingWebhookResponseContent}, webhooks, }; -use common_utils::{ext_traits::Encode, request::RequestContent}; +use common_utils::{ext_traits::Encode, request::RequestContent, types::keymanager::Identifier}; use diesel_models::process_tracker::business_status; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::type_encryption::decrypt; @@ -87,6 +87,7 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook( }; let request_content = get_outgoing_webhook_request( + &state, &merchant_account, outgoing_webhook, &business_profile, @@ -97,7 +98,7 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook( .attach_printable("Failed to construct outgoing webhook request content")?; let event_metadata = storage::EventMetadata::foreign_from((&content, &primary_object_id)); - + let key_manager_state = &(&state).into(); let new_event = domain::Event { event_id: event_id.clone(), event_type, @@ -113,11 +114,13 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook( initial_attempt_id: Some(event_id.clone()), request: Some( domain_types::encrypt( + key_manager_state, request_content .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("Failed to encode outgoing webhook request content") .map(Secret::new)?, + Identifier::Merchant(merchant_key_store.merchant_id.clone()), merchant_key_store.key.get_inner().peek(), ) .await @@ -131,7 +134,7 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook( let event_insert_result = state .store - .insert_event(new_event, merchant_key_store) + .insert_event(key_manager_state, new_event, merchant_key_store) .await; let event = match event_insert_result { @@ -552,6 +555,7 @@ fn get_webhook_url_from_business_profile( } pub(crate) async fn get_outgoing_webhook_request( + state: &SessionState, merchant_account: &domain::MerchantAccount, outgoing_webhook: api::OutgoingWebhook, business_profile: &diesel_models::business_profile::BusinessProfile, @@ -559,6 +563,7 @@ pub(crate) async fn get_outgoing_webhook_request( ) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> { #[inline] async fn get_outgoing_webhook_request_inner<WebhookType: types::OutgoingWebhookType>( + state: &SessionState, outgoing_webhook: api::OutgoingWebhook, business_profile: &diesel_models::business_profile::BusinessProfile, key_store: &domain::MerchantKeyStore, @@ -571,9 +576,11 @@ pub(crate) async fn get_outgoing_webhook_request( let transformed_outgoing_webhook = WebhookType::from(outgoing_webhook); let payment_response_hash_key = business_profile.payment_response_hash_key.clone(); let custom_headers = decrypt::<serde_json::Value, masking::WithType>( + &state.into(), business_profile .outgoing_webhook_custom_http_headers .clone(), + Identifier::Merchant(key_store.merchant_id.clone()), key_store.key.get_inner().peek(), ) .await @@ -614,6 +621,7 @@ pub(crate) async fn get_outgoing_webhook_request( #[cfg(feature = "stripe")] Some(api_models::enums::Connector::Stripe) => { get_outgoing_webhook_request_inner::<stripe_webhooks::StripeOutgoingWebhook>( + state, outgoing_webhook, business_profile, key_store, @@ -622,6 +630,7 @@ pub(crate) async fn get_outgoing_webhook_request( } _ => { get_outgoing_webhook_request_inner::<webhooks::OutgoingWebhook>( + state, outgoing_webhook, business_profile, key_store, @@ -645,7 +654,7 @@ async fn update_event_if_client_error( error_message: String, ) -> CustomResult<domain::Event, errors::WebhooksFlowError> { let is_webhook_notified = false; - + let key_manager_state = &(&state).into(); let response_to_store = OutgoingWebhookResponseContent { body: None, headers: None, @@ -657,12 +666,14 @@ async fn update_event_if_client_error( is_webhook_notified, response: Some( domain_types::encrypt( + key_manager_state, response_to_store .encode_to_string_of_json() .change_context( errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed, ) .map(Secret::new)?, + Identifier::Merchant(merchant_key_store.merchant_id.clone()), merchant_key_store.key.get_inner().peek(), ) .await @@ -674,6 +685,7 @@ async fn update_event_if_client_error( state .store .update_event_by_merchant_id_event_id( + key_manager_state, merchant_id, event_id, event_update, @@ -733,7 +745,7 @@ async fn update_event_in_storage( ) -> CustomResult<domain::Event, errors::WebhooksFlowError> { let status_code = response.status(); let is_webhook_notified = status_code.is_success(); - + let key_manager_state = &(&state).into(); let response_headers = response .headers() .iter() @@ -772,12 +784,14 @@ async fn update_event_in_storage( is_webhook_notified, response: Some( domain_types::encrypt( + key_manager_state, response_to_store .encode_to_string_of_json() .change_context( errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed, ) .map(Secret::new)?, + Identifier::Merchant(merchant_key_store.merchant_id.clone()), merchant_key_store.key.get_inner().peek(), ) .await @@ -788,6 +802,7 @@ async fn update_event_in_storage( state .store .update_event_by_merchant_id_event_id( + key_manager_state, merchant_id, event_id, event_update, diff --git a/crates/router/src/core/webhooks/webhook_events.rs b/crates/router/src/core/webhooks/webhook_events.rs index 2a16ccce0b4..19118ad639a 100644 --- a/crates/router/src/core/webhooks/webhook_events.rs +++ b/crates/router/src/core/webhooks/webhook_events.rs @@ -28,7 +28,7 @@ pub async fn list_initial_delivery_attempts( api::webhook_events::EventListConstraintsInternal::foreign_try_from(constraints)?; let store = state.store.as_ref(); - + let key_manager_state = &(&state).into(); let (account, key_store) = determine_identifier_and_get_key_store(state.clone(), merchant_id_or_profile_id).await?; @@ -36,14 +36,14 @@ pub async fn list_initial_delivery_attempts( api_models::webhook_events::EventListConstraintsInternal::ObjectIdFilter { object_id } => { match account { MerchantAccountOrBusinessProfile::MerchantAccount(merchant_account) => store - .list_initial_events_by_merchant_id_primary_object_id( + .list_initial_events_by_merchant_id_primary_object_id(key_manager_state, &merchant_account.merchant_id, &object_id, &key_store, ) .await, MerchantAccountOrBusinessProfile::BusinessProfile(business_profile) => store - .list_initial_events_by_profile_id_primary_object_id( + .list_initial_events_by_profile_id_primary_object_id(key_manager_state, &business_profile.profile_id, &object_id, &key_store, @@ -73,7 +73,7 @@ pub async fn list_initial_delivery_attempts( match account { MerchantAccountOrBusinessProfile::MerchantAccount(merchant_account) => store - .list_initial_events_by_merchant_id_constraints( + .list_initial_events_by_merchant_id_constraints(key_manager_state, &merchant_account.merchant_id, created_after, created_before, @@ -83,7 +83,7 @@ pub async fn list_initial_delivery_attempts( ) .await, MerchantAccountOrBusinessProfile::BusinessProfile(business_profile) => store - .list_initial_events_by_profile_id_constraints( + .list_initial_events_by_profile_id_constraints(key_manager_state, &business_profile.profile_id, created_after, created_before, @@ -116,11 +116,12 @@ pub async fn list_delivery_attempts( let (account, key_store) = determine_identifier_and_get_key_store(state.clone(), merchant_id_or_profile_id).await?; - + let key_manager_state = &(&state).into(); let events = match account { MerchantAccountOrBusinessProfile::MerchantAccount(merchant_account) => { store .list_events_by_merchant_id_initial_attempt_id( + key_manager_state, &merchant_account.merchant_id, &initial_attempt_id, &key_store, @@ -130,6 +131,7 @@ pub async fn list_delivery_attempts( MerchantAccountOrBusinessProfile::BusinessProfile(business_profile) => { store .list_events_by_profile_id_initial_attempt_id( + key_manager_state, &business_profile.profile_id, &initial_attempt_id, &key_store, @@ -162,12 +164,17 @@ pub async fn retry_delivery_attempt( event_id: String, ) -> RouterResponse<api::webhook_events::EventRetrieveResponse> { let store = state.store.as_ref(); - + let key_manager_state = &(&state).into(); let (account, key_store) = determine_identifier_and_get_key_store(state.clone(), merchant_id_or_profile_id).await?; let event_to_retry = store - .find_event_by_merchant_id_event_id(&key_store.merchant_id, &event_id, &key_store) + .find_event_by_merchant_id_event_id( + key_manager_state, + &key_store.merchant_id, + &event_id, + &key_store, + ) .await .to_not_found_response(errors::ApiErrorResponse::EventNotFound)?; @@ -216,7 +223,7 @@ pub async fn retry_delivery_attempt( }; let event = store - .insert_event(new_event, &key_store) + .insert_event(key_manager_state, new_event, &key_store) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert event")?; @@ -245,7 +252,12 @@ pub async fn retry_delivery_attempt( .await; let updated_event = store - .find_event_by_merchant_id_event_id(&key_store.merchant_id, &new_event_id, &key_store) + .find_event_by_merchant_id_event_id( + key_manager_state, + &key_store.merchant_id, + &new_event_id, + &key_store, + ) .await .to_not_found_response(errors::ApiErrorResponse::EventNotFound)?; @@ -259,8 +271,10 @@ async fn determine_identifier_and_get_key_store( merchant_id_or_profile_id: String, ) -> errors::RouterResult<(MerchantAccountOrBusinessProfile, domain::MerchantKeyStore)> { let store = state.store.as_ref(); + let key_manager_state = &(&state).into(); match store .get_merchant_key_store_by_merchant_id( + key_manager_state, &merchant_id_or_profile_id, &store.get_master_key().to_vec().into(), ) @@ -271,7 +285,11 @@ async fn determine_identifier_and_get_key_store( // Find a merchant account having `merchant_id` = `merchant_id_or_profile_id`. Ok(key_store) => { let merchant_account = store - .find_merchant_account_by_merchant_id(&merchant_id_or_profile_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &merchant_id_or_profile_id, + &key_store, + ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -301,6 +319,7 @@ async fn determine_identifier_and_get_key_store( let key_store = store .get_merchant_key_store_by_merchant_id( + key_manager_state, &business_profile.merchant_id, &store.get_master_key().to_vec().into(), ) diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs index f210019b4da..04a8f673a94 100644 --- a/crates/router/src/db/address.rs +++ b/crates/router/src/db/address.rs @@ -1,4 +1,4 @@ -use common_utils::id_type; +use common_utils::{id_type, types::keymanager::KeyManagerState}; use diesel_models::{address::AddressUpdateInternal, enums::MerchantStorageScheme}; use error_stack::ResultExt; @@ -22,6 +22,7 @@ where { async fn update_address( &self, + state: &KeyManagerState, address_id: String, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, @@ -29,6 +30,7 @@ where async fn update_address_for_payments( &self, + state: &KeyManagerState, this: domain::PaymentAddress, address: domain::AddressUpdate, payment_id: String, @@ -38,12 +40,14 @@ where async fn find_address_by_address_id( &self, + state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError>; async fn insert_address_for_payments( &self, + state: &KeyManagerState, payment_id: &str, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, @@ -52,12 +56,14 @@ where async fn insert_address_for_customers( &self, + state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError>; async fn find_address_by_merchant_id_payment_id_address_id( &self, + state: &KeyManagerState, merchant_id: &str, payment_id: &str, address_id: &str, @@ -67,6 +73,7 @@ where async fn update_address_by_merchant_id_customer_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, address: storage_types::AddressUpdate, @@ -76,7 +83,7 @@ where #[cfg(not(feature = "kv_store"))] mod storage { - use common_utils::{ext_traits::AsyncExt, id_type}; + use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; @@ -98,6 +105,7 @@ mod storage { #[instrument(skip_all)] async fn find_address_by_address_id( &self, + state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { @@ -107,7 +115,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -117,6 +129,7 @@ mod storage { #[instrument(skip_all)] async fn find_address_by_merchant_id_payment_id_address_id( &self, + state: &KeyManagerState, merchant_id: &str, payment_id: &str, address_id: &str, @@ -134,7 +147,7 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert(state, key_store.key.get_inner(), merchant_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) }) @@ -144,6 +157,7 @@ mod storage { #[instrument(skip_all)] async fn update_address( &self, + state: &KeyManagerState, address_id: String, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, @@ -154,7 +168,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -164,6 +182,7 @@ mod storage { #[instrument(skip_all)] async fn update_address_for_payments( &self, + state: &KeyManagerState, this: domain::PaymentAddress, address_update: domain::AddressUpdate, _payment_id: String, @@ -180,7 +199,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -190,6 +213,7 @@ mod storage { #[instrument(skip_all)] async fn insert_address_for_payments( &self, + state: &KeyManagerState, _payment_id: &str, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, @@ -205,7 +229,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -215,6 +243,7 @@ mod storage { #[instrument(skip_all)] async fn insert_address_for_customers( &self, + state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { @@ -228,7 +257,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -238,6 +271,7 @@ mod storage { #[instrument(skip_all)] async fn update_address_by_merchant_id_customer_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, address: storage_types::AddressUpdate, @@ -257,7 +291,7 @@ mod storage { for address in addresses.into_iter() { output.push( address - .convert(key_store.key.get_inner()) + .convert(state, key_store.key.get_inner(), merchant_id.to_string()) .await .change_context(errors::StorageError::DecryptionError)?, ) @@ -271,7 +305,7 @@ mod storage { #[cfg(feature = "kv_store")] mod storage { - use common_utils::{ext_traits::AsyncExt, id_type}; + use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use diesel_models::{enums::MerchantStorageScheme, AddressUpdateInternal}; use error_stack::{report, ResultExt}; use redis_interface::HsetnxReply; @@ -299,6 +333,7 @@ mod storage { #[instrument(skip_all)] async fn find_address_by_address_id( &self, + state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { @@ -308,7 +343,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -318,6 +357,7 @@ mod storage { #[instrument(skip_all)] async fn find_address_by_merchant_id_payment_id_address_id( &self, + state: &KeyManagerState, merchant_id: &str, payment_id: &str, address_id: &str, @@ -362,7 +402,11 @@ mod storage { } }?; address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -370,6 +414,7 @@ mod storage { #[instrument(skip_all)] async fn update_address( &self, + state: &KeyManagerState, address_id: String, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, @@ -380,7 +425,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -390,6 +439,7 @@ mod storage { #[instrument(skip_all)] async fn update_address_for_payments( &self, + state: &KeyManagerState, this: domain::PaymentAddress, address_update: domain::AddressUpdate, payment_id: String, @@ -420,7 +470,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -457,7 +511,11 @@ mod storage { .change_context(errors::StorageError::KVError)?; updated_address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -467,6 +525,7 @@ mod storage { #[instrument(skip_all)] async fn insert_address_for_payments( &self, + state: &KeyManagerState, payment_id: &str, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, @@ -493,7 +552,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -553,7 +616,11 @@ mod storage { } .into()), Ok(HsetnxReply::KeySet) => Ok(created_address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?), Err(er) => Err(er).change_context(errors::StorageError::KVError), @@ -565,6 +632,7 @@ mod storage { #[instrument(skip_all)] async fn insert_address_for_customers( &self, + state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { @@ -578,7 +646,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -588,6 +660,7 @@ mod storage { #[instrument(skip_all)] async fn update_address_by_merchant_id_customer_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, address: storage_types::AddressUpdate, @@ -607,7 +680,11 @@ mod storage { for address in addresses.into_iter() { output.push( address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ) @@ -623,6 +700,7 @@ mod storage { impl AddressInterface for MockDb { async fn find_address_by_address_id( &self, + state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { @@ -635,7 +713,11 @@ impl AddressInterface for MockDb { { Some(address) => address .clone() - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError), None => { @@ -648,6 +730,7 @@ impl AddressInterface for MockDb { async fn find_address_by_merchant_id_payment_id_address_id( &self, + state: &KeyManagerState, _merchant_id: &str, _payment_id: &str, address_id: &str, @@ -663,7 +746,11 @@ impl AddressInterface for MockDb { { Some(address) => address .clone() - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError), None => { @@ -676,6 +763,7 @@ impl AddressInterface for MockDb { async fn update_address( &self, + state: &KeyManagerState, address_id: String, address_update: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, @@ -694,7 +782,11 @@ impl AddressInterface for MockDb { }); match updated_addr { Some(address_updated) => address_updated - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError), None => Err(errors::StorageError::ValueNotFound( @@ -706,6 +798,7 @@ impl AddressInterface for MockDb { async fn update_address_for_payments( &self, + state: &KeyManagerState, this: domain::PaymentAddress, address_update: domain::AddressUpdate, _payment_id: String, @@ -726,7 +819,11 @@ impl AddressInterface for MockDb { }); match updated_addr { Some(address_updated) => address_updated - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError), None => Err(errors::StorageError::ValueNotFound( @@ -738,6 +835,7 @@ impl AddressInterface for MockDb { async fn insert_address_for_payments( &self, + state: &KeyManagerState, _payment_id: &str, address_new: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, @@ -752,13 +850,18 @@ impl AddressInterface for MockDb { addresses.push(address.clone()); address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } async fn insert_address_for_customers( &self, + state: &KeyManagerState, address_new: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { @@ -771,13 +874,18 @@ impl AddressInterface for MockDb { addresses.push(address.clone()); address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } async fn update_address_by_merchant_id_customer_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, address_update: storage_types::AddressUpdate, @@ -801,7 +909,11 @@ impl AddressInterface for MockDb { match updated_addr { Some(address) => { let address: domain::Address = address - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?; Ok(vec![address]) diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs index cad3d2969fe..1bfda658521 100644 --- a/crates/router/src/db/customers.rs +++ b/crates/router/src/db/customers.rs @@ -1,4 +1,4 @@ -use common_utils::{ext_traits::AsyncExt, id_type}; +use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use error_stack::ResultExt; use futures::future::try_join_all; use router_env::{instrument, tracing}; @@ -29,14 +29,17 @@ where async fn find_customer_optional_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, errors::StorageError>; + #[allow(clippy::too_many_arguments)] async fn update_customer_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: String, customer: domain::Customer, @@ -47,6 +50,7 @@ where async fn find_customer_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -55,12 +59,14 @@ where async fn list_customers_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Customer>, errors::StorageError>; async fn insert_customer( &self, + state: &KeyManagerState, customer_data: domain::Customer, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -69,7 +75,7 @@ where #[cfg(feature = "kv_store")] mod storage { - use common_utils::{ext_traits::AsyncExt, id_type}; + use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use diesel_models::kv; use error_stack::{report, ResultExt}; use futures::future::try_join_all; @@ -103,6 +109,7 @@ mod storage { // check customer not found in kv and fallback to db async fn find_customer_optional_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -149,9 +156,13 @@ mod storage { let maybe_result = maybe_customer .async_map(|c| async { - c.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + c.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; @@ -167,6 +178,7 @@ mod storage { #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: String, customer: domain::Customer, @@ -236,7 +248,11 @@ mod storage { }; updated_object? - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -244,6 +260,7 @@ mod storage { #[instrument(skip_all)] async fn find_customer_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -287,7 +304,11 @@ mod storage { }?; let result: domain::Customer = customer - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?; //.await @@ -303,6 +324,7 @@ mod storage { #[instrument(skip_all)] async fn list_customers_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> { @@ -316,7 +338,11 @@ mod storage { let customers = try_join_all(encrypted_customers.into_iter().map( |encrypted_customer| async { encrypted_customer - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }, @@ -329,6 +355,7 @@ mod storage { #[instrument(skip_all)] async fn insert_customer( &self, + state: &KeyManagerState, customer_data: domain::Customer, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -394,7 +421,11 @@ mod storage { }?; create_customer - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -419,7 +450,7 @@ mod storage { #[cfg(not(feature = "kv_store"))] mod storage { - use common_utils::{ext_traits::AsyncExt, id_type}; + use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use futures::future::try_join_all; use masking::PeekInterface; @@ -447,6 +478,7 @@ mod storage { #[instrument(skip_all)] async fn find_customer_optional_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -462,7 +494,7 @@ mod storage { .await .map_err(|error| report!(errors::StorageError::from(error)))? .async_map(|c| async { - c.convert(key_store.key.get_inner()) + c.convert(state, key_store.key.get_inner(), merchant_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) }) @@ -483,6 +515,7 @@ mod storage { #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: String, _customer: domain::Customer, @@ -494,13 +527,13 @@ mod storage { storage_types::Customer::update_by_customer_id_merchant_id( &conn, customer_id, - merchant_id, + merchant_id.clone(), customer_update.into(), ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { - c.convert(key_store.key.get_inner()) + c.convert(state, key_store.key.get_inner(), merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) @@ -510,6 +543,7 @@ mod storage { #[instrument(skip_all)] async fn find_customer_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -525,7 +559,7 @@ mod storage { .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { - c.convert(key_store.key.get_inner()) + c.convert(state, key_store.key.get_inner(), merchant_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) }) @@ -541,6 +575,7 @@ mod storage { #[instrument(skip_all)] async fn list_customers_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> { @@ -554,7 +589,7 @@ mod storage { let customers = try_join_all(encrypted_customers.into_iter().map( |encrypted_customer| async { encrypted_customer - .convert(key_store.key.get_inner()) + .convert(state, key_store.key.get_inner(), merchant_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) }, @@ -567,6 +602,7 @@ mod storage { #[instrument(skip_all)] async fn insert_customer( &self, + state: &KeyManagerState, customer_data: domain::Customer, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, @@ -580,9 +616,13 @@ mod storage { .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { - c.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + c.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError) }) .await } @@ -610,6 +650,7 @@ impl CustomerInterface for MockDb { #[allow(clippy::panic)] async fn find_customer_optional_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -624,9 +665,13 @@ impl CustomerInterface for MockDb { .cloned(); customer .async_map(|c| async { - c.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + c.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError) }) .await .transpose() @@ -634,6 +679,7 @@ impl CustomerInterface for MockDb { async fn list_customers_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> { @@ -646,7 +692,11 @@ impl CustomerInterface for MockDb { .map(|customer| async { customer .to_owned() - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }), @@ -659,6 +709,7 @@ impl CustomerInterface for MockDb { #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, + _state: &KeyManagerState, _customer_id: id_type::CustomerId, _merchant_id: String, _customer: domain::Customer, @@ -672,6 +723,7 @@ impl CustomerInterface for MockDb { async fn find_customer_by_customer_id_merchant_id( &self, + _state: &KeyManagerState, _customer_id: &id_type::CustomerId, _merchant_id: &str, _key_store: &domain::MerchantKeyStore, @@ -684,6 +736,7 @@ impl CustomerInterface for MockDb { #[allow(clippy::panic)] async fn insert_customer( &self, + state: &KeyManagerState, customer_data: domain::Customer, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, @@ -697,7 +750,11 @@ impl CustomerInterface for MockDb { customers.push(customer.clone()); customer - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs index aba11f95988..2fd8a09f173 100644 --- a/crates/router/src/db/events.rs +++ b/crates/router/src/db/events.rs @@ -1,4 +1,4 @@ -use common_utils::ext_traits::AsyncExt; +use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; @@ -23,12 +23,14 @@ where { async fn insert_event( &self, + state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError>; async fn find_event_by_merchant_id_event_id( &self, + state: &KeyManagerState, merchant_id: &str, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -36,13 +38,16 @@ where async fn list_initial_events_by_merchant_id_primary_object_id( &self, + state: &KeyManagerState, merchant_id: &str, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; + #[allow(clippy::too_many_arguments)] async fn list_initial_events_by_merchant_id_constraints( &self, + state: &KeyManagerState, merchant_id: &str, created_after: Option<time::PrimitiveDateTime>, created_before: Option<time::PrimitiveDateTime>, @@ -53,6 +58,7 @@ where async fn list_events_by_merchant_id_initial_attempt_id( &self, + state: &KeyManagerState, merchant_id: &str, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -60,13 +66,16 @@ where async fn list_initial_events_by_profile_id_primary_object_id( &self, + state: &KeyManagerState, profile_id: &str, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; + #[allow(clippy::too_many_arguments)] async fn list_initial_events_by_profile_id_constraints( &self, + state: &KeyManagerState, profile_id: &str, created_after: Option<time::PrimitiveDateTime>, created_before: Option<time::PrimitiveDateTime>, @@ -77,6 +86,7 @@ where async fn list_events_by_profile_id_initial_attempt_id( &self, + state: &KeyManagerState, profile_id: &str, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -84,6 +94,7 @@ where async fn update_event_by_merchant_id_event_id( &self, + state: &KeyManagerState, merchant_id: &str, event_id: &str, event: domain::EventUpdate, @@ -96,6 +107,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn insert_event( &self, + state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { @@ -107,7 +119,11 @@ impl EventInterface for Store { .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -115,6 +131,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn find_event_by_merchant_id_event_id( &self, + state: &KeyManagerState, merchant_id: &str, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -123,7 +140,11 @@ impl EventInterface for Store { storage::Event::find_by_merchant_id_event_id(&conn, merchant_id, event_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -131,6 +152,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn list_initial_events_by_merchant_id_primary_object_id( &self, + state: &KeyManagerState, merchant_id: &str, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -148,7 +170,11 @@ impl EventInterface for Store { for event in events.into_iter() { domain_events.push( event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ); @@ -161,6 +187,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn list_initial_events_by_merchant_id_constraints( &self, + state: &KeyManagerState, merchant_id: &str, created_after: Option<time::PrimitiveDateTime>, created_before: Option<time::PrimitiveDateTime>, @@ -184,7 +211,11 @@ impl EventInterface for Store { for event in events.into_iter() { domain_events.push( event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ); @@ -197,6 +228,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn list_events_by_merchant_id_initial_attempt_id( &self, + state: &KeyManagerState, merchant_id: &str, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -214,7 +246,11 @@ impl EventInterface for Store { for event in events.into_iter() { domain_events.push( event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ); @@ -227,6 +263,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn list_initial_events_by_profile_id_primary_object_id( &self, + state: &KeyManagerState, profile_id: &str, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -244,7 +281,11 @@ impl EventInterface for Store { for event in events.into_iter() { domain_events.push( event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ); @@ -257,6 +298,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn list_initial_events_by_profile_id_constraints( &self, + state: &KeyManagerState, profile_id: &str, created_after: Option<time::PrimitiveDateTime>, created_before: Option<time::PrimitiveDateTime>, @@ -280,7 +322,11 @@ impl EventInterface for Store { for event in events.into_iter() { domain_events.push( event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ); @@ -293,6 +339,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn list_events_by_profile_id_initial_attempt_id( &self, + state: &KeyManagerState, profile_id: &str, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -306,7 +353,11 @@ impl EventInterface for Store { for event in events.into_iter() { domain_events.push( event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ); @@ -319,6 +370,7 @@ impl EventInterface for Store { #[instrument(skip_all)] async fn update_event_by_merchant_id_event_id( &self, + state: &KeyManagerState, merchant_id: &str, event_id: &str, event: domain::EventUpdate, @@ -328,7 +380,11 @@ impl EventInterface for Store { storage::Event::update_by_merchant_id_event_id(&conn, merchant_id, event_id, event.into()) .await .map_err(|error| report!(errors::StorageError::from(error)))? - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -338,6 +394,7 @@ impl EventInterface for Store { impl EventInterface for MockDb { async fn insert_event( &self, + state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { @@ -350,13 +407,18 @@ impl EventInterface for MockDb { locked_events.push(stored_event.clone()); stored_event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_event_by_merchant_id_event_id( &self, + state: &KeyManagerState, merchant_id: &str, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -370,7 +432,11 @@ impl EventInterface for MockDb { .cloned() .async_map(|event| async { event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -386,6 +452,7 @@ impl EventInterface for MockDb { async fn list_initial_events_by_merchant_id_primary_object_id( &self, + state: &KeyManagerState, merchant_id: &str, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -405,7 +472,11 @@ impl EventInterface for MockDb { for event in events { let domain_event = event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); @@ -416,6 +487,7 @@ impl EventInterface for MockDb { async fn list_initial_events_by_merchant_id_constraints( &self, + state: &KeyManagerState, merchant_id: &str, created_after: Option<time::PrimitiveDateTime>, created_before: Option<time::PrimitiveDateTime>, @@ -470,7 +542,11 @@ impl EventInterface for MockDb { for event in events { let domain_event = event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); @@ -481,6 +557,7 @@ impl EventInterface for MockDb { async fn list_events_by_merchant_id_initial_attempt_id( &self, + state: &KeyManagerState, merchant_id: &str, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -498,7 +575,11 @@ impl EventInterface for MockDb { for event in events { let domain_event = event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); @@ -509,6 +590,7 @@ impl EventInterface for MockDb { async fn list_initial_events_by_profile_id_primary_object_id( &self, + state: &KeyManagerState, profile_id: &str, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -528,7 +610,11 @@ impl EventInterface for MockDb { for event in events { let domain_event = event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); @@ -539,6 +625,7 @@ impl EventInterface for MockDb { async fn list_initial_events_by_profile_id_constraints( &self, + state: &KeyManagerState, profile_id: &str, created_after: Option<time::PrimitiveDateTime>, created_before: Option<time::PrimitiveDateTime>, @@ -593,7 +680,11 @@ impl EventInterface for MockDb { for event in events { let domain_event = event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); @@ -604,6 +695,7 @@ impl EventInterface for MockDb { async fn list_events_by_profile_id_initial_attempt_id( &self, + state: &KeyManagerState, profile_id: &str, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, @@ -621,7 +713,11 @@ impl EventInterface for MockDb { for event in events { let domain_event = event - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); @@ -632,6 +728,7 @@ impl EventInterface for MockDb { async fn update_event_by_merchant_id_event_id( &self, + state: &KeyManagerState, merchant_id: &str, event_id: &str, event: domain::EventUpdate, @@ -657,7 +754,11 @@ impl EventInterface for MockDb { event_to_update .clone() - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -665,6 +766,9 @@ impl EventInterface for MockDb { #[cfg(test)] mod tests { + use std::sync::Arc; + + use common_utils::types::keymanager::Identifier; use diesel_models::{enums, events::EventMetadata}; use time::macros::datetime; @@ -673,6 +777,10 @@ mod tests { events::EventInterface, merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb, }, + routes::{ + self, + app::{settings::Settings, StorageImpl}, + }, services, types::domain, }; @@ -685,17 +793,31 @@ mod tests { .await .expect("Failed to create Mock store"); let event_id = "test_event_id"; + let (tx, _) = tokio::sync::oneshot::channel(); + let app_state = Box::pin(routes::AppState::with_storage( + Settings::default(), + StorageImpl::PostgresqlTest, + tx, + Box::new(services::MockApiClient), + )) + .await; + let state = &Arc::new(app_state) + .get_session_state("public", || {}) + .unwrap(); let merchant_id = "merchant1"; let business_profile_id = "profile1"; let payment_id = "test_payment_id"; - + let key_manager_state = &state.into(); let master_key = mockdb.get_master_key(); mockdb .insert_merchant_key_store( + key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.into(), key: domain::types::encrypt( + key_manager_state, services::generate_aes256_key().unwrap().to_vec().into(), + Identifier::Merchant(merchant_id.to_string()), master_key, ) .await @@ -707,12 +829,17 @@ mod tests { .await .unwrap(); let merchant_key_store = mockdb - .get_merchant_key_store_by_merchant_id(merchant_id, &master_key.to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &master_key.to_vec().into(), + ) .await .unwrap(); let event1 = mockdb .insert_event( + key_manager_state, domain::Event { event_id: event_id.into(), event_type: enums::EventType::PaymentSucceeded, @@ -742,6 +869,7 @@ mod tests { let updated_event = mockdb .update_event_by_merchant_id_event_id( + key_manager_state, merchant_id, event_id, domain::EventUpdate::UpdateResponse { diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index ce0821c6322..ed2357c1a1c 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use common_enums::enums::MerchantStorageScheme; -use common_utils::{errors::CustomResult, id_type, pii}; +use common_utils::{errors::CustomResult, id_type, pii, types::keymanager::KeyManagerState}; use diesel_models::{ enums, enums::ProcessTrackerStatus, @@ -102,27 +102,30 @@ impl KafkaStore { impl AddressInterface for KafkaStore { async fn find_address_by_address_id( &self, + state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { self.diesel_store - .find_address_by_address_id(address_id, key_store) + .find_address_by_address_id(state, address_id, key_store) .await } async fn update_address( &self, + state: &KeyManagerState, address_id: String, address: storage::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { self.diesel_store - .update_address(address_id, address, key_store) + .update_address(state, address_id, address, key_store) .await } async fn update_address_for_payments( &self, + state: &KeyManagerState, this: domain::PaymentAddress, address: domain::AddressUpdate, payment_id: String, @@ -130,24 +133,33 @@ impl AddressInterface for KafkaStore { storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { self.diesel_store - .update_address_for_payments(this, address, payment_id, key_store, storage_scheme) + .update_address_for_payments( + state, + this, + address, + payment_id, + key_store, + storage_scheme, + ) .await } async fn insert_address_for_payments( &self, + state: &KeyManagerState, payment_id: &str, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { self.diesel_store - .insert_address_for_payments(payment_id, address, key_store, storage_scheme) + .insert_address_for_payments(state, payment_id, address, key_store, storage_scheme) .await } async fn find_address_by_merchant_id_payment_id_address_id( &self, + state: &KeyManagerState, merchant_id: &str, payment_id: &str, address_id: &str, @@ -156,6 +168,7 @@ impl AddressInterface for KafkaStore { ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { self.diesel_store .find_address_by_merchant_id_payment_id_address_id( + state, merchant_id, payment_id, address_id, @@ -167,23 +180,31 @@ impl AddressInterface for KafkaStore { async fn insert_address_for_customers( &self, + state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { self.diesel_store - .insert_address_for_customers(address, key_store) + .insert_address_for_customers(state, address, key_store) .await } async fn update_address_by_merchant_id_customer_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, address: storage::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Address>, errors::StorageError> { self.diesel_store - .update_address_by_merchant_id_customer_id(customer_id, merchant_id, address, key_store) + .update_address_by_merchant_id_customer_id( + state, + customer_id, + merchant_id, + address, + key_store, + ) .await } } @@ -332,6 +353,7 @@ impl CustomerInterface for KafkaStore { async fn find_customer_optional_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -339,6 +361,7 @@ impl CustomerInterface for KafkaStore { ) -> CustomResult<Option<domain::Customer>, errors::StorageError> { self.diesel_store .find_customer_optional_by_customer_id_merchant_id( + state, customer_id, merchant_id, key_store, @@ -349,6 +372,7 @@ impl CustomerInterface for KafkaStore { async fn update_customer_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: String, customer: domain::Customer, @@ -358,6 +382,7 @@ impl CustomerInterface for KafkaStore { ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store .update_customer_by_customer_id_merchant_id( + state, customer_id, merchant_id, customer, @@ -370,16 +395,18 @@ impl CustomerInterface for KafkaStore { async fn list_customers_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> { self.diesel_store - .list_customers_by_merchant_id(merchant_id, key_store) + .list_customers_by_merchant_id(state, merchant_id, key_store) .await } async fn find_customer_by_customer_id_merchant_id( &self, + state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -387,6 +414,7 @@ impl CustomerInterface for KafkaStore { ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store .find_customer_by_customer_id_merchant_id( + state, customer_id, merchant_id, key_store, @@ -397,12 +425,13 @@ impl CustomerInterface for KafkaStore { async fn insert_customer( &self, + state: &KeyManagerState, customer_data: domain::Customer, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store - .insert_customer(customer_data, key_store, storage_scheme) + .insert_customer(state, customer_data, key_store, storage_scheme) .await } } @@ -519,33 +548,37 @@ impl EphemeralKeyInterface for KafkaStore { impl EventInterface for KafkaStore { async fn insert_event( &self, + state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { self.diesel_store - .insert_event(event, merchant_key_store) + .insert_event(state, event, merchant_key_store) .await } async fn find_event_by_merchant_id_event_id( &self, + state: &KeyManagerState, merchant_id: &str, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { self.diesel_store - .find_event_by_merchant_id_event_id(merchant_id, event_id, merchant_key_store) + .find_event_by_merchant_id_event_id(state, merchant_id, event_id, merchant_key_store) .await } async fn list_initial_events_by_merchant_id_primary_object_id( &self, + state: &KeyManagerState, merchant_id: &str, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_initial_events_by_merchant_id_primary_object_id( + state, merchant_id, primary_object_id, merchant_key_store, @@ -555,6 +588,7 @@ impl EventInterface for KafkaStore { async fn list_initial_events_by_merchant_id_constraints( &self, + state: &KeyManagerState, merchant_id: &str, created_after: Option<PrimitiveDateTime>, created_before: Option<PrimitiveDateTime>, @@ -564,6 +598,7 @@ impl EventInterface for KafkaStore { ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_initial_events_by_merchant_id_constraints( + state, merchant_id, created_after, created_before, @@ -576,12 +611,14 @@ impl EventInterface for KafkaStore { async fn list_events_by_merchant_id_initial_attempt_id( &self, + state: &KeyManagerState, merchant_id: &str, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_events_by_merchant_id_initial_attempt_id( + state, merchant_id, initial_attempt_id, merchant_key_store, @@ -591,12 +628,14 @@ impl EventInterface for KafkaStore { async fn list_initial_events_by_profile_id_primary_object_id( &self, + state: &KeyManagerState, profile_id: &str, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_initial_events_by_profile_id_primary_object_id( + state, profile_id, primary_object_id, merchant_key_store, @@ -606,6 +645,7 @@ impl EventInterface for KafkaStore { async fn list_initial_events_by_profile_id_constraints( &self, + state: &KeyManagerState, profile_id: &str, created_after: Option<PrimitiveDateTime>, created_before: Option<PrimitiveDateTime>, @@ -615,6 +655,7 @@ impl EventInterface for KafkaStore { ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_initial_events_by_profile_id_constraints( + state, profile_id, created_after, created_before, @@ -627,12 +668,14 @@ impl EventInterface for KafkaStore { async fn list_events_by_profile_id_initial_attempt_id( &self, + state: &KeyManagerState, profile_id: &str, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_events_by_profile_id_initial_attempt_id( + state, profile_id, initial_attempt_id, merchant_key_store, @@ -642,13 +685,20 @@ impl EventInterface for KafkaStore { async fn update_event_by_merchant_id_event_id( &self, + state: &KeyManagerState, merchant_id: &str, event_id: &str, event: domain::EventUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { self.diesel_store - .update_event_by_merchant_id_event_id(merchant_id, event_id, event, merchant_key_store) + .update_event_by_merchant_id_event_id( + state, + merchant_id, + event_id, + event, + merchant_key_store, + ) .await } } @@ -790,43 +840,47 @@ impl PaymentLinkInterface for KafkaStore { impl MerchantAccountInterface for KafkaStore { async fn insert_merchant( &self, + state: &KeyManagerState, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store - .insert_merchant(merchant_account, key_store) + .insert_merchant(state, merchant_account, key_store) .await } async fn find_merchant_account_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store - .find_merchant_account_by_merchant_id(merchant_id, key_store) + .find_merchant_account_by_merchant_id(state, merchant_id, key_store) .await } async fn update_merchant( &self, + state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: storage::MerchantAccountUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store - .update_merchant(this, merchant_account, key_store) + .update_merchant(state, this, merchant_account, key_store) .await } async fn update_specific_fields_in_merchant( &self, + state: &KeyManagerState, merchant_id: &str, merchant_account: storage::MerchantAccountUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store - .update_specific_fields_in_merchant(merchant_id, merchant_account, key_store) + .update_specific_fields_in_merchant(state, merchant_id, merchant_account, key_store) .await } @@ -841,20 +895,22 @@ impl MerchantAccountInterface for KafkaStore { async fn find_merchant_account_by_publishable_key( &self, + state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<authentication::AuthenticationData, errors::StorageError> { self.diesel_store - .find_merchant_account_by_publishable_key(publishable_key) + .find_merchant_account_by_publishable_key(state, publishable_key) .await } #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, + state: &KeyManagerState, organization_id: &str, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { self.diesel_store - .list_merchant_accounts_by_organization_id(organization_id) + .list_merchant_accounts_by_organization_id(state, organization_id) .await } @@ -870,10 +926,11 @@ impl MerchantAccountInterface for KafkaStore { #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, + state: &KeyManagerState, merchant_ids: Vec<String>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { self.diesel_store - .list_multiple_merchant_accounts(merchant_ids) + .list_multiple_merchant_accounts(state, merchant_ids) .await } } @@ -957,12 +1014,14 @@ impl MerchantConnectorAccountInterface for KafkaStore { } async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, + state: &KeyManagerState, merchant_id: &str, connector: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_merchant_id_connector_label( + state, merchant_id, connector, key_store, @@ -972,12 +1031,14 @@ impl MerchantConnectorAccountInterface for KafkaStore { async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, + state: &KeyManagerState, merchant_id: &str, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_merchant_id_connector_name( + state, merchant_id, connector_name, key_store, @@ -987,12 +1048,14 @@ impl MerchantConnectorAccountInterface for KafkaStore { async fn find_merchant_connector_account_by_profile_id_connector_name( &self, + state: &KeyManagerState, profile_id: &str, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_profile_id_connector_name( + state, profile_id, connector_name, key_store, @@ -1002,22 +1065,25 @@ impl MerchantConnectorAccountInterface for KafkaStore { async fn insert_merchant_connector_account( &self, + state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store - .insert_merchant_connector_account(t, key_store) + .insert_merchant_connector_account(state, t, key_store) .await } async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, + state: &KeyManagerState, merchant_id: &str, merchant_connector_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + state, merchant_id, merchant_connector_id, key_store, @@ -1027,12 +1093,14 @@ impl MerchantConnectorAccountInterface for KafkaStore { async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, + state: &KeyManagerState, merchant_id: &str, get_disabled: bool, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_merchant_id_and_disabled_list( + state, merchant_id, get_disabled, key_store, @@ -1042,12 +1110,13 @@ impl MerchantConnectorAccountInterface for KafkaStore { async fn update_merchant_connector_account( &self, + state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store - .update_merchant_connector_account(this, merchant_connector_account, key_store) + .update_merchant_connector_account(state, this, merchant_connector_account, key_store) .await } @@ -1326,6 +1395,7 @@ impl PaymentAttemptInterface for KafkaStore { impl PaymentIntentInterface for KafkaStore { async fn update_payment_intent( &self, + state: &KeyManagerState, this: storage::PaymentIntent, payment_intent: storage::PaymentIntentUpdate, key_store: &domain::MerchantKeyStore, @@ -1333,7 +1403,13 @@ impl PaymentIntentInterface for KafkaStore { ) -> CustomResult<storage::PaymentIntent, errors::DataStorageError> { let intent = self .diesel_store - .update_payment_intent(this.clone(), payment_intent, key_store, storage_scheme) + .update_payment_intent( + state, + this.clone(), + payment_intent, + key_store, + storage_scheme, + ) .await?; if let Err(er) = self @@ -1349,6 +1425,7 @@ impl PaymentIntentInterface for KafkaStore { async fn insert_payment_intent( &self, + state: &KeyManagerState, new: storage::PaymentIntent, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -1356,7 +1433,7 @@ impl PaymentIntentInterface for KafkaStore { logger::debug!("Inserting PaymentIntent Via KafkaStore"); let intent = self .diesel_store - .insert_payment_intent(new, key_store, storage_scheme) + .insert_payment_intent(state, new, key_store, storage_scheme) .await?; if let Err(er) = self @@ -1372,6 +1449,7 @@ impl PaymentIntentInterface for KafkaStore { async fn find_payment_intent_by_payment_id_merchant_id( &self, + state: &KeyManagerState, payment_id: &str, merchant_id: &str, key_store: &domain::MerchantKeyStore, @@ -1379,6 +1457,7 @@ impl PaymentIntentInterface for KafkaStore { ) -> CustomResult<storage::PaymentIntent, errors::DataStorageError> { self.diesel_store .find_payment_intent_by_payment_id_merchant_id( + state, payment_id, merchant_id, key_store, @@ -1390,19 +1469,27 @@ impl PaymentIntentInterface for KafkaStore { #[cfg(feature = "olap")] async fn filter_payment_intent_by_constraints( &self, + state: &KeyManagerState, merchant_id: &str, filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::PaymentIntent>, errors::DataStorageError> { self.diesel_store - .filter_payment_intent_by_constraints(merchant_id, filters, key_store, storage_scheme) + .filter_payment_intent_by_constraints( + state, + merchant_id, + filters, + key_store, + storage_scheme, + ) .await } #[cfg(feature = "olap")] async fn filter_payment_intents_by_time_range_constraints( &self, + state: &KeyManagerState, merchant_id: &str, time_range: &api_models::payments::TimeRange, key_store: &domain::MerchantKeyStore, @@ -1410,6 +1497,7 @@ impl PaymentIntentInterface for KafkaStore { ) -> CustomResult<Vec<storage::PaymentIntent>, errors::DataStorageError> { self.diesel_store .filter_payment_intents_by_time_range_constraints( + state, merchant_id, time_range, key_store, @@ -1421,6 +1509,7 @@ impl PaymentIntentInterface for KafkaStore { #[cfg(feature = "olap")] async fn get_filtered_payment_intents_attempt( &self, + state: &KeyManagerState, merchant_id: &str, constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, key_store: &domain::MerchantKeyStore, @@ -1434,6 +1523,7 @@ impl PaymentIntentInterface for KafkaStore { > { self.diesel_store .get_filtered_payment_intents_attempt( + state, merchant_id, constraints, key_store, @@ -2059,21 +2149,23 @@ impl RefundInterface for KafkaStore { impl MerchantKeyStoreInterface for KafkaStore { async fn insert_merchant_key_store( &self, + state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { self.diesel_store - .insert_merchant_key_store(merchant_key_store, key) + .insert_merchant_key_store(state, merchant_key_store, key) .await } async fn get_merchant_key_store_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { self.diesel_store - .get_merchant_key_store_by_merchant_id(merchant_id, key) + .get_merchant_key_store_by_merchant_id(state, merchant_id, key) .await } @@ -2089,18 +2181,20 @@ impl MerchantKeyStoreInterface for KafkaStore { #[cfg(feature = "olap")] async fn list_multiple_key_stores( &self, + state: &KeyManagerState, merchant_ids: Vec<String>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { self.diesel_store - .list_multiple_key_stores(merchant_ids, key) + .list_multiple_key_stores(state, merchant_ids, key) .await } async fn get_all_key_stores( &self, + state: &KeyManagerState, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { - self.diesel_store.get_all_key_stores(key).await + self.diesel_store.get_all_key_stores(state, key).await } } @@ -2592,6 +2686,7 @@ impl DashboardMetadataInterface for KafkaStore { impl BatchSampleDataInterface for KafkaStore { async fn insert_payment_intents_batch_for_sample_data( &self, + state: &KeyManagerState, batch: Vec<hyperswitch_domain_models::payments::PaymentIntent>, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, ) -> CustomResult< @@ -2600,7 +2695,7 @@ impl BatchSampleDataInterface for KafkaStore { > { let payment_intents_list = self .diesel_store - .insert_payment_intents_batch_for_sample_data(batch, key_store) + .insert_payment_intents_batch_for_sample_data(state, batch, key_store) .await?; for payment_intent in payment_intents_list.iter() { @@ -2654,6 +2749,7 @@ impl BatchSampleDataInterface for KafkaStore { async fn delete_payment_intents_for_sample_data( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, ) -> CustomResult< @@ -2662,7 +2758,7 @@ impl BatchSampleDataInterface for KafkaStore { > { let payment_intents_list = self .diesel_store - .delete_payment_intents_for_sample_data(merchant_id, key_store) + .delete_payment_intents_for_sample_data(state, merchant_id, key_store) .await?; for payment_intent in payment_intents_list.iter() { @@ -2947,29 +3043,32 @@ impl GenericLinkInterface for KafkaStore { impl UserKeyStoreInterface for KafkaStore { async fn insert_user_key_store( &self, + state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { self.diesel_store - .insert_user_key_store(user_key_store, key) + .insert_user_key_store(state, user_key_store, key) .await } async fn get_user_key_store_by_user_id( &self, + state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { self.diesel_store - .get_user_key_store_by_user_id(user_id, key) + .get_user_key_store_by_user_id(state, user_id, key) .await } async fn get_all_user_key_store( &self, + state: &KeyManagerState, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { - self.diesel_store.get_all_user_key_store(key).await + self.diesel_store.get_all_user_key_store(state, key).await } } diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index ff3830b2381..eadf00c872c 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -1,7 +1,7 @@ #[cfg(feature = "olap")] use std::collections::HashMap; -use common_utils::ext_traits::AsyncExt; +use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use diesel_models::MerchantAccountUpdateInternal; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; @@ -31,12 +31,14 @@ where { async fn insert_merchant( &self, + state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError>; async fn find_merchant_account_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError>; @@ -48,6 +50,7 @@ where async fn update_merchant( &self, + state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, @@ -55,6 +58,7 @@ where async fn update_specific_fields_in_merchant( &self, + state: &KeyManagerState, merchant_id: &str, merchant_account: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, @@ -62,12 +66,14 @@ where async fn find_merchant_account_by_publishable_key( &self, + state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<authentication::AuthenticationData, errors::StorageError>; #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, + state: &KeyManagerState, organization_id: &str, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError>; @@ -79,6 +85,7 @@ where #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, + state: &KeyManagerState, merchant_ids: Vec<String>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError>; } @@ -88,6 +95,7 @@ impl MerchantAccountInterface for Store { #[instrument(skip_all)] async fn insert_merchant( &self, + state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { @@ -99,7 +107,11 @@ impl MerchantAccountInterface for Store { .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -107,6 +119,7 @@ impl MerchantAccountInterface for Store { #[instrument(skip_all)] async fn find_merchant_account_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { @@ -121,7 +134,11 @@ impl MerchantAccountInterface for Store { { fetch_func() .await? - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_id.to_string(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -130,7 +147,11 @@ impl MerchantAccountInterface for Store { { cache::get_or_populate_in_memory(self, merchant_id, fetch_func, &ACCOUNTS_CACHE) .await? - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -139,6 +160,7 @@ impl MerchantAccountInterface for Store { #[instrument(skip_all)] async fn update_merchant( &self, + state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, @@ -157,7 +179,11 @@ impl MerchantAccountInterface for Store { publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?; } updated_merchant_account - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -165,6 +191,7 @@ impl MerchantAccountInterface for Store { #[instrument(skip_all)] async fn update_specific_fields_in_merchant( &self, + state: &KeyManagerState, merchant_id: &str, merchant_account: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, @@ -183,7 +210,11 @@ impl MerchantAccountInterface for Store { publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?; } updated_merchant_account - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -191,6 +222,7 @@ impl MerchantAccountInterface for Store { #[instrument(skip_all)] async fn find_merchant_account_by_publishable_key( &self, + state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<authentication::AuthenticationData, errors::StorageError> { let fetch_by_pub_key_func = || async { @@ -219,6 +251,7 @@ impl MerchantAccountInterface for Store { } let key_store = self .get_merchant_key_store_by_merchant_id( + state, &merchant_account.merchant_id, &self.get_master_key().to_vec().into(), ) @@ -226,7 +259,11 @@ impl MerchantAccountInterface for Store { Ok(authentication::AuthenticationData { merchant_account: merchant_account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, @@ -238,6 +275,7 @@ impl MerchantAccountInterface for Store { #[instrument(skip_all)] async fn list_merchant_accounts_by_organization_id( &self, + state: &KeyManagerState, organization_id: &str, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { use futures::future::try_join_all; @@ -253,6 +291,7 @@ impl MerchantAccountInterface for Store { let merchant_key_stores = try_join_all(encrypted_merchant_accounts.iter().map(|merchant_account| { self.get_merchant_key_store_by_merchant_id( + state, &merchant_account.merchant_id, &db_master_key, ) @@ -265,7 +304,11 @@ impl MerchantAccountInterface for Store { .zip(merchant_key_stores.iter()) .map(|(merchant_account, key_store)| async { merchant_account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }), @@ -314,6 +357,7 @@ impl MerchantAccountInterface for Store { #[instrument(skip_all)] async fn list_multiple_merchant_accounts( &self, + state: &KeyManagerState, merchant_ids: Vec<String>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; @@ -327,6 +371,7 @@ impl MerchantAccountInterface for Store { let merchant_key_stores = self .list_multiple_key_stores( + state, encrypted_merchant_accounts .iter() .map(|merchant_account| &merchant_account.merchant_id) @@ -351,7 +396,11 @@ impl MerchantAccountInterface for Store { )), )?; merchant_account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }, @@ -399,6 +448,7 @@ impl MerchantAccountInterface for MockDb { #[allow(clippy::panic)] async fn insert_merchant( &self, + state: &KeyManagerState, mut merchant_account: domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { @@ -412,7 +462,11 @@ impl MerchantAccountInterface for MockDb { accounts.push(account.clone()); account - .convert(merchant_key_store.key.get_inner()) + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -420,6 +474,7 @@ impl MerchantAccountInterface for MockDb { #[allow(clippy::panic)] async fn find_merchant_account_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { @@ -429,9 +484,13 @@ impl MerchantAccountInterface for MockDb { .find(|account| account.merchant_id == merchant_id) .cloned() .async_map(|a| async { - a.convert(merchant_key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + a.convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; @@ -445,6 +504,7 @@ impl MerchantAccountInterface for MockDb { async fn update_merchant( &self, + _state: &KeyManagerState, _this: domain::MerchantAccount, _merchant_account: storage::MerchantAccountUpdate, _merchant_key_store: &domain::MerchantKeyStore, @@ -455,6 +515,7 @@ impl MerchantAccountInterface for MockDb { async fn update_specific_fields_in_merchant( &self, + _state: &KeyManagerState, _merchant_id: &str, _merchant_account: storage::MerchantAccountUpdate, _merchant_key_store: &domain::MerchantKeyStore, @@ -465,6 +526,7 @@ impl MerchantAccountInterface for MockDb { async fn find_merchant_account_by_publishable_key( &self, + _state: &KeyManagerState, _publishable_key: &str, ) -> CustomResult<authentication::AuthenticationData, errors::StorageError> { // [#172]: Implement function for `MockDb` @@ -489,6 +551,7 @@ impl MerchantAccountInterface for MockDb { #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, + _state: &KeyManagerState, _organization_id: &str, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { Err(errors::StorageError::MockDbError)? @@ -497,6 +560,7 @@ impl MerchantAccountInterface for MockDb { #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, + _state: &KeyManagerState, _merchant_ids: Vec<String>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { Err(errors::StorageError::MockDbError)? diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index b9becb90dca..078980f9184 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -1,6 +1,9 @@ use async_bb8_diesel::AsyncConnection; -use common_utils::ext_traits::{AsyncExt, ByteSliceExt, Encode}; -use diesel_models::encryption::Encryption; +use common_utils::{ + encryption::Encryption, + ext_traits::{AsyncExt, ByteSliceExt, Encode}, + types::keymanager::KeyManagerState, +}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] @@ -121,6 +124,7 @@ where { async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, + state: &KeyManagerState, merchant_id: &str, connector_label: &str, key_store: &domain::MerchantKeyStore, @@ -128,6 +132,7 @@ where async fn find_merchant_connector_account_by_profile_id_connector_name( &self, + state: &KeyManagerState, profile_id: &str, connector_name: &str, key_store: &domain::MerchantKeyStore, @@ -135,6 +140,7 @@ where async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, + state: &KeyManagerState, merchant_id: &str, connector_name: &str, key_store: &domain::MerchantKeyStore, @@ -142,12 +148,14 @@ where async fn insert_merchant_connector_account( &self, + state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>; async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, + state: &KeyManagerState, merchant_id: &str, merchant_connector_id: &str, key_store: &domain::MerchantKeyStore, @@ -155,6 +163,7 @@ where async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, + state: &KeyManagerState, merchant_id: &str, get_disabled: bool, key_store: &domain::MerchantKeyStore, @@ -162,6 +171,7 @@ where async fn update_merchant_connector_account( &self, + state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, @@ -187,6 +197,7 @@ impl MerchantConnectorAccountInterface for Store { #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, + state: &KeyManagerState, merchant_id: &str, connector_label: &str, key_store: &domain::MerchantKeyStore, @@ -206,7 +217,7 @@ impl MerchantConnectorAccountInterface for Store { { find_call() .await? - .convert(key_store.key.get_inner()) + .convert(state, key_store.key.get_inner(), merchant_id.to_string()) .await .change_context(errors::StorageError::DeserializationFailed) } @@ -221,9 +232,13 @@ impl MerchantConnectorAccountInterface for Store { ) .await .async_and_then(|item| async { - item.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + item.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError) }) .await } @@ -232,6 +247,7 @@ impl MerchantConnectorAccountInterface for Store { #[instrument(skip_all)] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, + state: &KeyManagerState, profile_id: &str, connector_name: &str, key_store: &domain::MerchantKeyStore, @@ -251,7 +267,11 @@ impl MerchantConnectorAccountInterface for Store { { find_call() .await? - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DeserializationFailed) } @@ -266,9 +286,13 @@ impl MerchantConnectorAccountInterface for Store { ) .await .async_and_then(|item| async { - item.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + item.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError) }) .await } @@ -277,6 +301,7 @@ impl MerchantConnectorAccountInterface for Store { #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, + state: &KeyManagerState, merchant_id: &str, connector_name: &str, key_store: &domain::MerchantKeyStore, @@ -293,9 +318,13 @@ impl MerchantConnectorAccountInterface for Store { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( - item.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError)?, + item.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) @@ -306,6 +335,7 @@ impl MerchantConnectorAccountInterface for Store { #[instrument(skip_all)] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, + state: &KeyManagerState, merchant_id: &str, merchant_connector_id: &str, key_store: &domain::MerchantKeyStore, @@ -325,7 +355,11 @@ impl MerchantConnectorAccountInterface for Store { { find_call() .await? - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -339,7 +373,11 @@ impl MerchantConnectorAccountInterface for Store { &cache::ACCOUNTS_CACHE, ) .await? - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } @@ -348,6 +386,7 @@ impl MerchantConnectorAccountInterface for Store { #[instrument(skip_all)] async fn insert_merchant_connector_account( &self, + state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { @@ -359,9 +398,13 @@ impl MerchantConnectorAccountInterface for Store { .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|item| async { - item.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + item.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError) }) .await } @@ -369,6 +412,7 @@ impl MerchantConnectorAccountInterface for Store { #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, + state: &KeyManagerState, merchant_id: &str, get_disabled: bool, key_store: &domain::MerchantKeyStore, @@ -381,9 +425,13 @@ impl MerchantConnectorAccountInterface for Store { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( - item.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError)?, + item.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) @@ -492,6 +540,7 @@ impl MerchantConnectorAccountInterface for Store { #[instrument(skip_all)] async fn update_merchant_connector_account( &self, + state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, @@ -516,9 +565,13 @@ impl MerchantConnectorAccountInterface for Store { .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|item| async { - item.convert(key_store.key.get_inner()) - .await - .change_context(errors::StorageError::DecryptionError) + item.convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) + .await + .change_context(errors::StorageError::DecryptionError) }) .await }; @@ -629,6 +682,7 @@ impl MerchantConnectorAccountInterface for MockDb { } async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, + state: &KeyManagerState, merchant_id: &str, connector: &str, key_store: &domain::MerchantKeyStore, @@ -645,7 +699,11 @@ impl MerchantConnectorAccountInterface for MockDb { .cloned() .async_map(|account| async { account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -663,6 +721,7 @@ impl MerchantConnectorAccountInterface for MockDb { async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, + state: &KeyManagerState, merchant_id: &str, connector_name: &str, key_store: &domain::MerchantKeyStore, @@ -681,7 +740,11 @@ impl MerchantConnectorAccountInterface for MockDb { for account in accounts.into_iter() { output.push( account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ) @@ -691,6 +754,7 @@ impl MerchantConnectorAccountInterface for MockDb { async fn find_merchant_connector_account_by_profile_id_connector_name( &self, + state: &KeyManagerState, profile_id: &str, connector_name: &str, key_store: &domain::MerchantKeyStore, @@ -709,7 +773,11 @@ impl MerchantConnectorAccountInterface for MockDb { match maybe_mca { Some(mca) => mca .to_owned() - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError), None => Err(errors::StorageError::ValueNotFound( @@ -721,6 +789,7 @@ impl MerchantConnectorAccountInterface for MockDb { async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, + state: &KeyManagerState, merchant_id: &str, merchant_connector_id: &str, key_store: &domain::MerchantKeyStore, @@ -737,7 +806,11 @@ impl MerchantConnectorAccountInterface for MockDb { .cloned() .async_map(|account| async { account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -755,6 +828,7 @@ impl MerchantConnectorAccountInterface for MockDb { async fn insert_merchant_connector_account( &self, + state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { @@ -788,13 +862,18 @@ impl MerchantConnectorAccountInterface for MockDb { }; accounts.push(account.clone()); account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, + state: &KeyManagerState, merchant_id: &str, get_disabled: bool, key_store: &domain::MerchantKeyStore, @@ -818,7 +897,11 @@ impl MerchantConnectorAccountInterface for MockDb { for account in accounts.into_iter() { output.push( account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError)?, ) @@ -828,6 +911,7 @@ impl MerchantConnectorAccountInterface for MockDb { async fn update_merchant_connector_account( &self, + state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, @@ -846,7 +930,11 @@ impl MerchantConnectorAccountInterface for MockDb { }) .async_map(|account| async { account - .convert(key_store.key.get_inner()) + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) .await .change_context(errors::StorageError::DecryptionError) }) @@ -890,8 +978,10 @@ impl MerchantConnectorAccountInterface for MockDb { #[cfg(feature = "accounts_cache")] #[cfg(test)] mod merchant_connector_account_cache_tests { + use std::sync::Arc; + use api_models::enums::CountryAlpha2; - use common_utils::date_time; + use common_utils::{date_time, types::keymanager::Identifier}; use diesel_models::enums::ConnectorType; use error_stack::ResultExt; use masking::PeekInterface; @@ -901,6 +991,7 @@ mod merchant_connector_account_cache_tests { pub_sub::PubSubInterface, }; use time::macros::datetime; + use tokio::sync::oneshot; use crate::{ core::errors, @@ -908,6 +999,10 @@ mod merchant_connector_account_cache_tests { merchant_connector_account::MerchantConnectorAccountInterface, merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb, }, + routes::{ + self, + app::{settings::Settings, StorageImpl}, + }, services, types::{ domain::{self, behaviour::Conversion}, @@ -918,6 +1013,19 @@ mod merchant_connector_account_cache_tests { #[allow(clippy::unwrap_used)] #[tokio::test] async fn test_connector_profile_id_cache() { + let conf = Settings::new().unwrap(); + let tx: oneshot::Sender<()> = oneshot::channel().0; + + let app_state = Box::pin(routes::AppState::with_storage( + conf, + StorageImpl::PostgresqlTest, + tx, + Box::new(services::MockApiClient), + )) + .await; + let state = &Arc::new(app_state) + .get_session_state("public", || {}) + .unwrap(); #[allow(clippy::expect_used)] let db = MockDb::new(&redis_interface::RedisSettings::default()) .await @@ -934,12 +1042,15 @@ mod merchant_connector_account_cache_tests { let connector_label = "stripe_USA"; let merchant_connector_id = "simple_merchant_connector_id"; let profile_id = "pro_max_ultra"; - + let key_manager_state = &state.into(); db.insert_merchant_key_store( + key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.into(), key: domain::types::encrypt( + key_manager_state, services::generate_aes256_key().unwrap().to_vec().into(), + Identifier::Merchant(merchant_id.to_string()), master_key, ) .await @@ -952,7 +1063,11 @@ mod merchant_connector_account_cache_tests { .unwrap(); let merchant_key = db - .get_merchant_key_store_by_merchant_id(merchant_id, &master_key.to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &master_key.to_vec().into(), + ) .await .unwrap(); @@ -961,7 +1076,9 @@ mod merchant_connector_account_cache_tests { merchant_id: merchant_id.to_string(), connector_name: "stripe".to_string(), connector_account_details: domain::types::encrypt( + key_manager_state, serde_json::Value::default().into(), + Identifier::Merchant(merchant_key.merchant_id.clone()), merchant_key.key.get_inner().peek(), ) .await @@ -986,7 +1103,9 @@ mod merchant_connector_account_cache_tests { status: common_enums::ConnectorStatus::Inactive, connector_wallets_details: Some( domain::types::encrypt( + key_manager_state, serde_json::Value::default().into(), + Identifier::Merchant(merchant_key.merchant_id.clone()), merchant_key.key.get_inner().peek(), ) .await @@ -995,13 +1114,14 @@ mod merchant_connector_account_cache_tests { additional_merchant_data: None, }; - db.insert_merchant_connector_account(mca.clone(), &merchant_key) + db.insert_merchant_connector_account(key_manager_state, mca.clone(), &merchant_key) .await .unwrap(); let find_call = || async { Conversion::convert( db.find_merchant_connector_account_by_profile_id_connector_name( + key_manager_state, profile_id, &mca.connector_name, &merchant_key, diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs index 42a862e2d3d..1cc12796bc6 100644 --- a/crates/router/src/db/merchant_key_store.rs +++ b/crates/router/src/db/merchant_key_store.rs @@ -1,3 +1,4 @@ +use common_utils::types::keymanager::KeyManagerState; use error_stack::{report, ResultExt}; use masking::Secret; use router_env::{instrument, tracing}; @@ -19,12 +20,14 @@ use crate::{ pub trait MerchantKeyStoreInterface { async fn insert_merchant_key_store( &self, + state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError>; async fn get_merchant_key_store_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError>; @@ -37,12 +40,14 @@ pub trait MerchantKeyStoreInterface { #[cfg(feature = "olap")] async fn list_multiple_key_stores( &self, + state: &KeyManagerState, merchant_ids: Vec<String>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError>; async fn get_all_key_stores( &self, + state: &KeyManagerState, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError>; } @@ -52,10 +57,12 @@ impl MerchantKeyStoreInterface for Store { #[instrument(skip_all)] async fn insert_merchant_key_store( &self, + state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; + let merchant_id = merchant_key_store.merchant_id.clone(); merchant_key_store .construct_new() .await @@ -63,7 +70,7 @@ impl MerchantKeyStoreInterface for Store { .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? - .convert(key) + .convert(state, key, merchant_id) .await .change_context(errors::StorageError::DecryptionError) } @@ -71,6 +78,7 @@ impl MerchantKeyStoreInterface for Store { #[instrument(skip_all)] async fn get_merchant_key_store_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { @@ -89,7 +97,7 @@ impl MerchantKeyStoreInterface for Store { { fetch_func() .await? - .convert(key) + .convert(state, key, merchant_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) } @@ -104,7 +112,7 @@ impl MerchantKeyStoreInterface for Store { &ACCOUNTS_CACHE, ) .await? - .convert(key) + .convert(state, key, merchant_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) } @@ -146,6 +154,7 @@ impl MerchantKeyStoreInterface for Store { #[instrument(skip_all)] async fn list_multiple_key_stores( &self, + state: &KeyManagerState, merchant_ids: Vec<String>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { @@ -161,8 +170,9 @@ impl MerchantKeyStoreInterface for Store { }; futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async { + let merchant_id = key_store.merchant_id.clone(); key_store - .convert(key) + .convert(state, key, merchant_id) .await .change_context(errors::StorageError::DecryptionError) })) @@ -171,6 +181,7 @@ impl MerchantKeyStoreInterface for Store { async fn get_all_key_stores( &self, + state: &KeyManagerState, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; @@ -181,8 +192,9 @@ impl MerchantKeyStoreInterface for Store { }; futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async { + let merchant_id = key_store.merchant_id.clone(); key_store - .convert(key) + .convert(state, key, merchant_id) .await .change_context(errors::StorageError::DecryptionError) })) @@ -194,6 +206,7 @@ impl MerchantKeyStoreInterface for Store { impl MerchantKeyStoreInterface for MockDb { async fn insert_merchant_key_store( &self, + state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { @@ -213,15 +226,16 @@ impl MerchantKeyStoreInterface for MockDb { .await .change_context(errors::StorageError::MockDbError)?; locked_merchant_key_store.push(merchant_key.clone()); - + let merchant_id = merchant_key.merchant_id.clone(); merchant_key - .convert(key) + .convert(state, key, merchant_id) .await .change_context(errors::StorageError::DecryptionError) } async fn get_merchant_key_store_by_merchant_id( &self, + state: &KeyManagerState, merchant_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { @@ -234,7 +248,7 @@ impl MerchantKeyStoreInterface for MockDb { .ok_or(errors::StorageError::ValueNotFound(String::from( "merchant_key_store", )))? - .convert(key) + .convert(state, key, merchant_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) } @@ -258,6 +272,7 @@ impl MerchantKeyStoreInterface for MockDb { #[cfg(feature = "olap")] async fn list_multiple_key_stores( &self, + state: &KeyManagerState, merchant_ids: Vec<String>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { @@ -269,7 +284,7 @@ impl MerchantKeyStoreInterface for MockDb { .map(|merchant_key| async { merchant_key .to_owned() - .convert(key) + .convert(state, key, merchant_key.merchant_id.clone()) .await .change_context(errors::StorageError::DecryptionError) }), @@ -278,6 +293,7 @@ impl MerchantKeyStoreInterface for MockDb { } async fn get_all_key_stores( &self, + state: &KeyManagerState, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { let merchant_key_stores = self.merchant_key_store.lock().await; @@ -285,7 +301,7 @@ impl MerchantKeyStoreInterface for MockDb { futures::future::try_join_all(merchant_key_stores.iter().map(|merchant_key| async { merchant_key .to_owned() - .convert(key) + .convert(state, key, merchant_key.merchant_id.clone()) .await .change_context(errors::StorageError::DecryptionError) })) @@ -295,30 +311,54 @@ impl MerchantKeyStoreInterface for MockDb { #[cfg(test)] mod tests { + use std::sync::Arc; + + use common_utils::types::keymanager::Identifier; use time::macros::datetime; + use tokio::sync::oneshot; use crate::{ db::{merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb}, + routes::{ + self, + app::{settings::Settings, StorageImpl}, + }, services, - types::domain::{self}, + types::domain, }; - #[allow(clippy::unwrap_used)] + #[allow(clippy::unwrap_used, clippy::expect_used)] #[tokio::test] async fn test_mock_db_merchant_key_store_interface() { + let conf = Settings::new().expect("invalid settings"); + let tx: oneshot::Sender<()> = oneshot::channel().0; + let app_state = Box::pin(routes::AppState::with_storage( + conf, + StorageImpl::PostgresqlTest, + tx, + Box::new(services::MockApiClient), + )) + .await; + let state = &Arc::new(app_state) + .get_session_state("public", || {}) + .unwrap(); #[allow(clippy::expect_used)] let mock_db = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create mock DB"); let master_key = mock_db.get_master_key(); let merchant_id = "merchant1"; - + let identifier = Identifier::Merchant(merchant_id.to_string()); + let key_manager_state = &state.into(); let merchant_key1 = mock_db .insert_merchant_key_store( + key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.into(), key: domain::types::encrypt( + key_manager_state, services::generate_aes256_key().unwrap().to_vec().into(), + identifier.clone(), master_key, ) .await @@ -331,7 +371,11 @@ mod tests { .unwrap(); let found_merchant_key1 = mock_db - .get_merchant_key_store_by_merchant_id(merchant_id, &master_key.to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &master_key.to_vec().into(), + ) .await .unwrap(); @@ -340,10 +384,13 @@ mod tests { let insert_duplicate_merchant_key1_result = mock_db .insert_merchant_key_store( + key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.into(), key: domain::types::encrypt( + key_manager_state, services::generate_aes256_key().unwrap().to_vec().into(), + identifier.clone(), master_key, ) .await @@ -356,12 +403,20 @@ mod tests { assert!(insert_duplicate_merchant_key1_result.is_err()); let find_non_existent_merchant_key_result = mock_db - .get_merchant_key_store_by_merchant_id("non_existent", &master_key.to_vec().into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + "non_existent", + &master_key.to_vec().into(), + ) .await; assert!(find_non_existent_merchant_key_result.is_err()); let find_merchant_key_with_incorrect_master_key_result = mock_db - .get_merchant_key_store_by_merchant_id(merchant_id, &vec![0; 32].into()) + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &vec![0; 32].into(), + ) .await; assert!(find_merchant_key_with_incorrect_master_key_result.is_err()); } diff --git a/crates/router/src/db/user/sample_data.rs b/crates/router/src/db/user/sample_data.rs index 5a23666c7b1..cabf62b850e 100644 --- a/crates/router/src/db/user/sample_data.rs +++ b/crates/router/src/db/user/sample_data.rs @@ -1,3 +1,4 @@ +use common_utils::types::keymanager::KeyManagerState; use diesel_models::{ errors::DatabaseError, query::user::sample_data as sample_data_queries, @@ -20,6 +21,7 @@ use crate::{connection::pg_connection_write, core::errors::CustomResult, service pub trait BatchSampleDataInterface { async fn insert_payment_intents_batch_for_sample_data( &self, + state: &KeyManagerState, batch: Vec<PaymentIntent>, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError>; @@ -36,6 +38,7 @@ pub trait BatchSampleDataInterface { async fn delete_payment_intents_for_sample_data( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError>; @@ -55,6 +58,7 @@ pub trait BatchSampleDataInterface { impl BatchSampleDataInterface for Store { async fn insert_payment_intents_batch_for_sample_data( &self, + state: &KeyManagerState, batch: Vec<PaymentIntent>, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { @@ -68,13 +72,17 @@ impl BatchSampleDataInterface for Store { .change_context(StorageError::EncryptionError) })) .await?; - sample_data_queries::insert_payment_intents(&conn, new_intents) .await .map_err(diesel_error_to_data_error) .map(|v| { try_join_all(v.into_iter().map(|payment_intent| { - PaymentIntent::convert_back(payment_intent, key_store.key.get_inner()) + PaymentIntent::convert_back( + state, + payment_intent, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) })? @@ -111,6 +119,7 @@ impl BatchSampleDataInterface for Store { async fn delete_payment_intents_for_sample_data( &self, + state: &KeyManagerState, merchant_id: &str, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { @@ -122,7 +131,12 @@ impl BatchSampleDataInterface for Store { .map_err(diesel_error_to_data_error) .map(|v| { try_join_all(v.into_iter().map(|payment_intent| { - PaymentIntent::convert_back(payment_intent, key_store.key.get_inner()) + PaymentIntent::convert_back( + state, + payment_intent, + key_store.key.get_inner(), + key_store.merchant_id.clone(), + ) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) })? @@ -162,6 +176,7 @@ impl BatchSampleDataInterface for Store { impl BatchSampleDataInterface for storage_impl::MockDb { async fn insert_payment_intents_batch_for_sample_data( &self, + _state: &KeyManagerState, _batch: Vec<PaymentIntent>, _key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { @@ -184,6 +199,7 @@ impl BatchSampleDataInterface for storage_impl::MockDb { async fn delete_payment_intents_for_sample_data( &self, + _state: &KeyManagerState, _merchant_id: &str, _key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { diff --git a/crates/router/src/db/user_key_store.rs b/crates/router/src/db/user_key_store.rs index c7e48037e96..e7dbe531c65 100644 --- a/crates/router/src/db/user_key_store.rs +++ b/crates/router/src/db/user_key_store.rs @@ -1,4 +1,4 @@ -use common_utils::errors::CustomResult; +use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use masking::Secret; use router_env::{instrument, tracing}; @@ -18,18 +18,21 @@ use crate::{ pub trait UserKeyStoreInterface { async fn insert_user_key_store( &self, + state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError>; async fn get_user_key_store_by_user_id( &self, + state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError>; async fn get_all_user_key_store( &self, + state: &KeyManagerState, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError>; } @@ -39,10 +42,12 @@ impl UserKeyStoreInterface for Store { #[instrument(skip_all)] async fn insert_user_key_store( &self, + state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; + let user_id = user_key_store.user_id.clone(); user_key_store .construct_new() .await @@ -50,7 +55,7 @@ impl UserKeyStoreInterface for Store { .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? - .convert(key) + .convert(state, key, user_id) .await .change_context(errors::StorageError::DecryptionError) } @@ -58,6 +63,7 @@ impl UserKeyStoreInterface for Store { #[instrument(skip_all)] async fn get_user_key_store_by_user_id( &self, + state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { @@ -66,13 +72,14 @@ impl UserKeyStoreInterface for Store { diesel_models::user_key_store::UserKeyStore::find_by_user_id(&conn, user_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? - .convert(key) + .convert(state, key, user_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) } async fn get_all_user_key_store( &self, + state: &KeyManagerState, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; @@ -84,8 +91,9 @@ impl UserKeyStoreInterface for Store { }; futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async { + let user_id = key_store.user_id.clone(); key_store - .convert(key) + .convert(state, key, user_id) .await .change_context(errors::StorageError::DecryptionError) })) @@ -98,6 +106,7 @@ impl UserKeyStoreInterface for MockDb { #[instrument(skip_all)] async fn insert_user_key_store( &self, + state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { @@ -117,23 +126,25 @@ impl UserKeyStoreInterface for MockDb { .await .change_context(errors::StorageError::MockDbError)?; locked_user_key_store.push(user_key_store.clone()); - + let user_id = user_key_store.user_id.clone(); user_key_store - .convert(key) + .convert(state, key, user_id) .await .change_context(errors::StorageError::DecryptionError) } async fn get_all_user_key_store( &self, + state: &KeyManagerState, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { let user_key_store = self.user_key_store.lock().await; futures::future::try_join_all(user_key_store.iter().map(|user_key| async { + let user_id = user_key.user_id.clone(); user_key .to_owned() - .convert(key) + .convert(state, key, user_id) .await .change_context(errors::StorageError::DecryptionError) })) @@ -143,6 +154,7 @@ impl UserKeyStoreInterface for MockDb { #[instrument(skip_all)] async fn get_user_key_store_by_user_id( &self, + state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { @@ -156,7 +168,7 @@ impl UserKeyStoreInterface for MockDb { "No user_key_store is found for user_id={}", user_id )))? - .convert(key) + .convert(state, key, user_id.to_string()) .await .change_context(errors::StorageError::DecryptionError) } diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 38000f7b664..6405a3b8479 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -193,7 +193,11 @@ pub async fn start_server(conf: settings::Settings<SecuredSecret>) -> Applicatio let api_client = Box::new( services::ProxyClient::new( conf.proxy.clone(), - services::proxy_bypass_urls(&conf.locker, &conf.proxy.bypass_proxy_urls), + services::proxy_bypass_urls( + conf.key_manager.get_inner(), + &conf.locker, + &conf.proxy.bypass_proxy_urls, + ), ) .map_err(|error| { errors::ApplicationError::ApiClientError(error.current_context().clone()) diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 0d7d042f7af..b733e76289e 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -110,6 +110,7 @@ pub trait SessionStateInfo { fn event_handler(&self) -> EventsHandler; fn get_request_id(&self) -> Option<String>; fn add_request_id(&mut self, request_id: RequestId); + fn session_state(&self) -> SessionState; } impl SessionStateInfo for SessionState { @@ -130,6 +131,9 @@ impl SessionStateInfo for SessionState { self.store.add_request_id(request_id.to_string()); self.request_id.replace(request_id); } + fn session_state(&self) -> SessionState { + self.clone() + } } #[derive(Clone)] pub struct AppState { diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 003cd71c00d..25df0ef6434 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -40,7 +40,7 @@ pub async fn create_payment_method_api( json_payload.into_inner(), |state, auth, req, _| async move { Box::pin(cards::get_client_secret_or_add_payment_method( - state, + &state, req, &auth.merchant_account, &auth.key_store, @@ -88,9 +88,11 @@ async fn get_merchant_account( state: &SessionState, merchant_id: &str, ) -> CustomResult<(MerchantKeyStore, domain::MerchantAccount), errors::ApiErrorResponse> { + let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -99,7 +101,7 @@ async fn get_merchant_account( let merchant_account = state .store - .find_merchant_account_by_merchant_id(merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; Ok((key_store, merchant_account)) @@ -530,7 +532,7 @@ pub async fn default_payment_method_set_api( payload, |state, auth: auth::AuthenticationData, default_payment_method, _| async move { cards::set_default_payment_method( - &*state.clone().store, + &state, auth.merchant_account.merchant_id, auth.key_store, customer_id, diff --git a/crates/router/src/routes/recon.rs b/crates/router/src/routes/recon.rs index aabbd637ae7..d8100e8d341 100644 --- a/crates/router/src/routes/recon.rs +++ b/crates/router/src/routes/recon.rs @@ -85,15 +85,17 @@ pub async fn send_recon_request( .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)? .merchant_id; + let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id.as_str(), &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db - .find_merchant_account_by_merchant_id(merchant_id.as_str(), &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id.as_str(), &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -130,7 +132,12 @@ pub async fn send_recon_request( }; let response = db - .update_merchant(merchant_account, updated_merchant_account, &key_store) + .update_merchant( + key_manager_state, + merchant_account, + updated_merchant_account, + &key_store, + ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { @@ -162,6 +169,7 @@ pub async fn recon_merchant_account_update( let key_store = db .get_merchant_key_store_by_merchant_id( + &(&state).into(), &req.merchant_id, &db.get_master_key().to_vec().into(), ) @@ -169,7 +177,7 @@ pub async fn recon_merchant_account_update( .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db - .find_merchant_account_by_merchant_id(merchant_id, &key_store) + .find_merchant_account_by_merchant_id(&(&state).into(), merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -178,7 +186,12 @@ pub async fn recon_merchant_account_update( }; let response = db - .update_merchant(merchant_account, updated_merchant_account, &key_store) + .update_merchant( + &(&state).into(), + merchant_account, + updated_merchant_account, + &key_store, + ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 5dc46d35652..ea9ce177439 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -474,12 +474,19 @@ pub async fn send_request( let should_bypass_proxy = url .as_str() .starts_with(&state.conf.connectors.dummyconnector.base_url) - || proxy_bypass_urls(&state.conf.locker, &state.conf.proxy.bypass_proxy_urls) - .contains(&url.to_string()); + || proxy_bypass_urls( + state.conf.key_manager.get_inner(), + &state.conf.locker, + &state.conf.proxy.bypass_proxy_urls, + ) + .contains(&url.to_string()); #[cfg(not(feature = "dummy_connector"))] - let should_bypass_proxy = - proxy_bypass_urls(&state.conf.locker, &state.conf.proxy.bypass_proxy_urls) - .contains(&url.to_string()); + let should_bypass_proxy = proxy_bypass_urls( + &state.conf.key_manager.get_inner(), + &state.conf.locker, + &state.conf.proxy.bypass_proxy_urls, + ) + .contains(&url.to_string()); let client = client::create_client( &state.conf.proxy, should_bypass_proxy, diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index f3cb2f3f314..4dda8eab627 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -15,7 +15,7 @@ use crate::{ errors::{ApiClientError, CustomResult}, payments, }, - routes::SessionState, + routes::{app::settings::KeyManagerConfig, SessionState}, }; static NON_PROXIED_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); @@ -110,7 +110,12 @@ pub fn create_client( } } -pub fn proxy_bypass_urls(locker: &Locker, config_whitelist: &[String]) -> Vec<String> { +pub fn proxy_bypass_urls( + key_manager: &KeyManagerConfig, + locker: &Locker, + config_whitelist: &[String], +) -> Vec<String> { + let key_manager_host = key_manager.url.to_owned(); let locker_host = locker.host.to_owned(); let locker_host_rs = locker.host_rs.to_owned(); @@ -126,8 +131,11 @@ pub fn proxy_bypass_urls(locker: &Locker, config_whitelist: &[String]) -> Vec<St format!("{locker_host}/card/addCard"), format!("{locker_host}/card/getCard"), format!("{locker_host}/card/deleteCard"), + format!("{key_manager_host}/data/encrypt"), + format!("{key_manager_host}/data/decrypt"), + format!("{key_manager_host}/key/create"), + format!("{key_manager_host}/key/rotate"), ]; - [&proxy_list, config_whitelist].concat().to_vec() } diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index adc23935d9c..22c7f25ff82 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -319,9 +319,12 @@ where .attach_printable("API key has expired"); } + let key_manager_state = &(&state.session_state()).into(); + let key_store = state .store() .get_merchant_key_store_by_merchant_id( + key_manager_state, &stored_api_key.merchant_id, &state.store().get_master_key().to_vec().into(), ) @@ -331,7 +334,11 @@ where let merchant = state .store() - .find_merchant_account_by_merchant_id(&stored_api_key.merchant_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &stored_api_key.merchant_id, + &key_store, + ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; @@ -534,9 +541,11 @@ where _request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( + key_manager_state, self.0.as_ref(), &state.store().get_master_key().to_vec().into(), ) @@ -552,7 +561,7 @@ where let merchant = state .store() - .find_merchant_account_by_merchant_id(self.0.as_ref(), &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, self.0.as_ref(), &key_store) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -590,10 +599,10 @@ where ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let publishable_key = get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; - + let key_manager_state = &(&state.session_state()).into(); state .store() - .find_merchant_account_by_publishable_key(publishable_key) + .find_merchant_account_by_publishable_key(key_manager_state, publishable_key) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -818,10 +827,11 @@ where let permissions = authorization::get_permissions(state, &payload).await?; authorization::check_authorization(&self.0, &permissions)?; - + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( + key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) @@ -831,7 +841,11 @@ where let merchant = state .store() - .find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &payload.merchant_id, + &key_store, + ) .await .change_context(errors::ApiErrorResponse::InvalidJwtToken)?; @@ -868,10 +882,11 @@ where let permissions = authorization::get_permissions(state, &payload).await?; authorization::check_authorization(&self.0, &permissions)?; - + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( + key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) @@ -881,7 +896,11 @@ where let merchant = state .store() - .find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &payload.merchant_id, + &key_store, + ) .await .change_context(errors::ApiErrorResponse::InvalidJwtToken)?; @@ -963,10 +982,11 @@ where state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; - + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( + key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) @@ -976,7 +996,11 @@ where let merchant = state .store() - .find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &payload.merchant_id, + &key_store, + ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 884e47c6fc4..054888d1dfe 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -8,13 +8,17 @@ pub use api_models::admin::{ MerchantId, PaymentMethodsEnabled, ToggleAllKVRequest, ToggleAllKVResponse, ToggleKVRequest, ToggleKVResponse, WebhookDetails, }; -use common_utils::ext_traits::{AsyncExt, Encode, ValueExt}; +use common_utils::{ + ext_traits::{AsyncExt, Encode, ValueExt}, + types::keymanager::Identifier, +}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{merchant_key_store::MerchantKeyStore, type_encryption::decrypt}; use masking::{ExposeInterface, PeekInterface, Secret}; use crate::{ core::{errors, payment_methods::cards::create_encrypted_data}, + routes::SessionState, types::{domain, storage, transformers::ForeignTryFrom}, }; @@ -84,11 +88,14 @@ impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse { } pub async fn business_profile_response( + state: &SessionState, item: storage::business_profile::BusinessProfile, key_store: &MerchantKeyStore, ) -> Result<BusinessProfileResponse, error_stack::Report<errors::ParsingError>> { let outgoing_webhook_custom_http_headers = decrypt::<serde_json::Value, masking::WithType>( + &state.into(), item.outgoing_webhook_custom_http_headers.clone(), + Identifier::Merchant(key_store.merchant_id.clone()), key_store.key.get_inner().peek(), ) .await @@ -147,6 +154,7 @@ pub async fn business_profile_response( } pub async fn create_business_profile( + state: &SessionState, merchant_account: domain::MerchantAccount, request: BusinessProfileCreate, key_store: &MerchantKeyStore, @@ -188,7 +196,7 @@ pub async fn create_business_profile( .transpose()?; let outgoing_webhook_custom_http_headers = request .outgoing_webhook_custom_http_headers - .async_map(|headers| create_encrypted_data(key_store, headers)) + .async_map(|headers| create_encrypted_data(state, key_store, headers)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs index 71b90ab41c3..686f7f3ce49 100644 --- a/crates/router/src/types/api/mandates.rs +++ b/crates/router/src/types/api/mandates.rs @@ -2,7 +2,6 @@ use api_models::mandates; pub use api_models::mandates::{MandateId, MandateResponse, MandateRevokedResponse}; use common_utils::ext_traits::OptionExt; use error_stack::ResultExt; -use masking::PeekInterface; use serde::{Deserialize, Serialize}; use crate::{ @@ -73,8 +72,8 @@ impl MandateResponseExt for MandateResponse { } else { payment_methods::cards::get_card_details_without_locker_fallback( &payment_method, - key_store.key.get_inner().peek(), state, + &key_store, ) .await? }; diff --git a/crates/router/src/types/domain/address.rs b/crates/router/src/types/domain/address.rs index 0ed09a35013..e14ab8ea641 100644 --- a/crates/router/src/types/domain/address.rs +++ b/crates/router/src/types/domain/address.rs @@ -1,18 +1,19 @@ use async_trait::async_trait; use common_utils::{ - crypto, date_time, + crypto::{self, Encryptable}, + date_time, + encryption::Encryption, errors::{CustomResult, ValidationError}, id_type, + types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, }; -use diesel_models::{address::AddressUpdateInternal, encryption::Encryption, enums}; +use diesel_models::{address::AddressUpdateInternal, enums}; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; +use rustc_hash::FxHashMap; use time::{OffsetDateTime, PrimitiveDateTime}; -use super::{ - behaviour, - types::{self, AsyncLift}, -}; +use super::{behaviour, types}; #[derive(Clone, Debug, serde::Serialize)] pub struct Address { @@ -73,8 +74,10 @@ impl behaviour::Conversion for CustomerAddress { } async fn convert_back( + state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, + key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> { let customer_id = other @@ -84,7 +87,7 @@ impl behaviour::Conversion for CustomerAddress { field_name: "customer_id".to_string(), })?; - let address = Address::convert_back(other, key).await?; + let address = Address::convert_back(state, other, key, key_store_ref_id).await?; Ok(Self { address, @@ -117,8 +120,10 @@ impl behaviour::Conversion for PaymentAddress { } async fn convert_back( + state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, + key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> { let payment_id = other .payment_id @@ -129,7 +134,7 @@ impl behaviour::Conversion for PaymentAddress { let customer_id = other.customer_id.clone(); - let address = Address::convert_back(other, key).await?; + let address = Address::convert_back(state, other, key, key_store_ref_id).await?; Ok(Self { address, @@ -180,36 +185,45 @@ impl behaviour::Conversion for Address { } async fn convert_back( + state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, + _key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> { - async { - let inner_decrypt = |inner| types::decrypt(inner, key.peek()); - let inner_decrypt_email = |inner| types::decrypt(inner, key.peek()); - Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { - id: other.id, - address_id: other.address_id, - city: other.city, - country: other.country, - line1: other.line1.async_lift(inner_decrypt).await?, - line2: other.line2.async_lift(inner_decrypt).await?, - line3: other.line3.async_lift(inner_decrypt).await?, - state: other.state.async_lift(inner_decrypt).await?, - zip: other.zip.async_lift(inner_decrypt).await?, - first_name: other.first_name.async_lift(inner_decrypt).await?, - last_name: other.last_name.async_lift(inner_decrypt).await?, - phone_number: other.phone_number.async_lift(inner_decrypt).await?, - country_code: other.country_code, - created_at: other.created_at, - modified_at: other.modified_at, - updated_by: other.updated_by, - merchant_id: other.merchant_id, - email: other.email.async_lift(inner_decrypt_email).await?, - }) - } + let identifier = Identifier::Merchant(other.merchant_id.clone()); + let decrypted: FxHashMap<String, Encryptable<Secret<String>>> = types::batch_decrypt( + state, + diesel_models::Address::to_encryptable(other.clone()), + identifier.clone(), + key.peek(), + ) .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting".to_string(), + })?; + let encryptable_address = diesel_models::Address::from_encryptable(decrypted) + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting".to_string(), + })?; + Ok(Self { + id: other.id, + address_id: other.address_id, + city: other.city, + country: other.country, + line1: encryptable_address.line1, + line2: encryptable_address.line2, + line3: encryptable_address.line3, + state: encryptable_address.state, + zip: encryptable_address.zip, + first_name: encryptable_address.first_name, + last_name: encryptable_address.last_name, + phone_number: encryptable_address.phone_number, + country_code: other.country_code, + created_at: other.created_at, + modified_at: other.modified_at, + updated_by: other.updated_by, + merchant_id: other.merchant_id, + email: encryptable_address.email, }) } diff --git a/crates/router/src/types/domain/customer.rs b/crates/router/src/types/domain/customer.rs index c5b0b3701cb..b7ed05e3506 100644 --- a/crates/router/src/types/domain/customer.rs +++ b/crates/router/src/types/domain/customer.rs @@ -1,10 +1,16 @@ -use common_utils::{crypto, date_time, id_type, pii}; -use diesel_models::{customers::CustomerUpdateInternal, encryption::Encryption}; +use api_models::customers::CustomerRequestWithEncryption; +use common_utils::{ + crypto, date_time, + encryption::Encryption, + id_type, pii, + types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, +}; +use diesel_models::customers::CustomerUpdateInternal; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use time::PrimitiveDateTime; -use super::types::{self, AsyncLift}; +use super::types; use crate::errors::{CustomResult, ValidationError}; #[derive(Clone, Debug)] @@ -53,36 +59,49 @@ impl super::behaviour::Conversion for Customer { } async fn convert_back( + state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, + _key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> where Self: Sized, { - async { - let inner_decrypt = |inner| types::decrypt(inner, key.peek()); - let inner_decrypt_email = |inner| types::decrypt(inner, key.peek()); - Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { - id: Some(item.id), - customer_id: item.customer_id, - merchant_id: item.merchant_id, - name: item.name.async_lift(inner_decrypt).await?, - email: item.email.async_lift(inner_decrypt_email).await?, - phone: item.phone.async_lift(inner_decrypt).await?, - phone_country_code: item.phone_country_code, - description: item.description, - created_at: item.created_at, - metadata: item.metadata, - modified_at: item.modified_at, - connector_customer: item.connector_customer, - address_id: item.address_id, - default_payment_method_id: item.default_payment_method_id, - updated_by: item.updated_by, - }) - } + let decrypted = types::batch_decrypt( + state, + CustomerRequestWithEncryption::to_encryptable(CustomerRequestWithEncryption { + name: item.name.clone(), + phone: item.phone.clone(), + email: item.email.clone(), + }), + Identifier::Merchant(item.merchant_id.clone()), + key.peek(), + ) .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), + })?; + let encryptable_customer = CustomerRequestWithEncryption::from_encryptable(decrypted) + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting customer data".to_string(), + })?; + + Ok(Self { + id: Some(item.id), + customer_id: item.customer_id, + merchant_id: item.merchant_id, + name: encryptable_customer.name, + email: encryptable_customer.email, + phone: encryptable_customer.phone, + phone_country_code: item.phone_country_code, + description: item.description, + created_at: item.created_at, + metadata: item.metadata, + modified_at: item.modified_at, + connector_customer: item.connector_customer, + address_id: item.address_id, + default_payment_method_id: item.default_payment_method_id, + updated_by: item.updated_by, }) } diff --git a/crates/router/src/types/domain/event.rs b/crates/router/src/types/domain/event.rs index 74a6cfb47b5..c5eca1ab5ea 100644 --- a/crates/router/src/types/domain/event.rs +++ b/crates/router/src/types/domain/event.rs @@ -1,14 +1,18 @@ -use common_utils::crypto::OptionalEncryptableSecretString; +use common_utils::{ + crypto::OptionalEncryptableSecretString, + types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, +}; use diesel_models::{ enums::{EventClass, EventObjectType, EventType, WebhookDeliveryAttempt}, events::{EventMetadata, EventUpdateInternal}, + EventWithEncryption, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use crate::{ errors::{CustomResult, ValidationError}, - types::domain::types::{self, AsyncLift}, + types::domain::types, }; #[derive(Clone, Debug)] @@ -80,41 +84,49 @@ impl super::behaviour::Conversion for Event { } async fn convert_back( + state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, + key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> where Self: Sized, { - async { - Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { - event_id: item.event_id, - event_type: item.event_type, - event_class: item.event_class, - is_webhook_notified: item.is_webhook_notified, - primary_object_id: item.primary_object_id, - primary_object_type: item.primary_object_type, - created_at: item.created_at, - merchant_id: item.merchant_id, - business_profile_id: item.business_profile_id, - primary_object_created_at: item.primary_object_created_at, - idempotent_event_id: item.idempotent_event_id, - initial_attempt_id: item.initial_attempt_id, - request: item - .request - .async_lift(|inner| types::decrypt(inner, key.peek())) - .await?, - response: item - .response - .async_lift(|inner| types::decrypt(inner, key.peek())) - .await?, - delivery_attempt: item.delivery_attempt, - metadata: item.metadata, - }) - } + let decrypted = types::batch_decrypt( + state, + EventWithEncryption::to_encryptable(EventWithEncryption { + request: item.request.clone(), + response: item.response.clone(), + }), + Identifier::Merchant(key_store_ref_id.clone()), + key.peek(), + ) .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting event data".to_string(), + })?; + let encryptable_event = EventWithEncryption::from_encryptable(decrypted).change_context( + ValidationError::InvalidValue { + message: "Failed while decrypting event data".to_string(), + }, + )?; + Ok(Self { + event_id: item.event_id, + event_type: item.event_type, + event_class: item.event_class, + is_webhook_notified: item.is_webhook_notified, + primary_object_id: item.primary_object_id, + primary_object_type: item.primary_object_type, + created_at: item.created_at, + merchant_id: item.merchant_id, + business_profile_id: item.business_profile_id, + primary_object_created_at: item.primary_object_created_at, + idempotent_event_id: item.idempotent_event_id, + initial_attempt_id: item.initial_attempt_id, + request: encryptable_event.request, + response: encryptable_event.response, + delivery_attempt: item.delivery_attempt, + metadata: item.metadata, }) } diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs index 2cf091eda12..6f654848f60 100644 --- a/crates/router/src/types/domain/merchant_connector_account.rs +++ b/crates/router/src/types/domain/merchant_connector_account.rs @@ -1,13 +1,12 @@ use common_utils::{ crypto::{Encryptable, GcmAes256}, date_time, + encryption::Encryption, errors::{CustomResult, ValidationError}, pii, + types::keymanager::{Identifier, KeyManagerState}, }; -use diesel_models::{ - encryption::Encryption, enums, - merchant_connector_account::MerchantConnectorAccountUpdateInternal, -}; +use diesel_models::{enums, merchant_connector_account::MerchantConnectorAccountUpdateInternal}; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; @@ -108,15 +107,20 @@ impl behaviour::Conversion for MerchantConnectorAccount { } async fn convert_back( + state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, + _key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> { + let identifier = Identifier::Merchant(other.merchant_id.clone()); Ok(Self { id: Some(other.id), merchant_id: other.merchant_id, connector_name: other.connector_name, - connector_account_details: Encryptable::decrypt( + connector_account_details: Encryptable::decrypt_via_api( + state, other.connector_account_details, + identifier.clone(), key.peek(), GcmAes256, ) @@ -145,7 +149,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { status: other.status, connector_wallets_details: other .connector_wallets_details - .async_lift(|inner| types::decrypt(inner, key.peek())) + .async_lift(|inner| types::decrypt(state, inner, identifier.clone(), key.peek())) .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting connector wallets details".to_string(), diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rs index 151ae61f5fe..53239cd27cf 100644 --- a/crates/router/src/types/domain/types.rs +++ b/crates/router/src/types/domain/types.rs @@ -1,6 +1,7 @@ use common_utils::types::keymanager::KeyManagerState; pub use hyperswitch_domain_models::type_encryption::{ - decrypt, encrypt, encrypt_optional, AsyncLift, Lift, TypeEncryption, + batch_decrypt, batch_encrypt, decrypt, encrypt, encrypt_optional, AsyncLift, Lift, + TypeEncryption, }; impl From<&crate::SessionState> for KeyManagerState { diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index c4c67796d46..ec44103a8f0 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -7,8 +7,11 @@ use common_enums::TokenPurpose; #[cfg(not(feature = "v2"))] use common_utils::id_type; #[cfg(feature = "keymanager_create")] -use common_utils::types::keymanager::{EncryptionCreateRequest, Identifier}; -use common_utils::{crypto::Encryptable, errors::CustomResult, new_type::MerchantName, pii}; +use common_utils::types::keymanager::EncryptionCreateRequest; +use common_utils::{ + crypto::Encryptable, errors::CustomResult, new_type::MerchantName, pii, + types::keymanager::Identifier, +}; use diesel_models::{ enums::{TotpStatus, UserStatus}, organization as diesel_org, @@ -368,6 +371,7 @@ impl NewUserMerchant { if state .store .get_merchant_key_store_by_merchant_id( + &(&state).into(), self.get_merchant_id().as_str(), &state.store.get_master_key().to_vec().into(), ) @@ -949,9 +953,14 @@ impl UserFromStorage { pub async fn get_or_create_key_store(&self, state: &SessionState) -> UserResult<UserKeyStore> { let master_key = state.store.get_master_key(); + let key_manager_state = &state.into(); let key_store_result = state .global_store - .get_user_key_store_by_user_id(self.get_user_id(), &master_key.to_vec().into()) + .get_user_key_store_by_user_id( + key_manager_state, + self.get_user_id(), + &master_key.to_vec().into(), + ) .await; if let Ok(key_store) = key_store_result { @@ -968,16 +977,21 @@ impl UserFromStorage { let key_store = UserKeyStore { user_id: self.get_user_id().to_string(), - key: domain_types::encrypt(key.to_vec().into(), master_key) - .await - .change_context(UserErrors::InternalServerError)?, + key: domain_types::encrypt( + key_manager_state, + key.to_vec().into(), + Identifier::User(self.get_user_id().to_string()), + master_key, + ) + .await + .change_context(UserErrors::InternalServerError)?, created_at: common_utils::date_time::now(), }; #[cfg(feature = "keymanager_create")] { common_utils::keymanager::create_key_in_key_manager( - &state.into(), + key_manager_state, EncryptionCreateRequest { identifier: Identifier::User(key_store.user_id.clone()), }, @@ -988,7 +1002,7 @@ impl UserFromStorage { state .global_store - .insert_user_key_store(key_store, &master_key.to_vec().into()) + .insert_user_key_store(key_manager_state, key_store, &master_key.to_vec().into()) .await .change_context(UserErrors::InternalServerError) } else { @@ -1014,10 +1028,11 @@ impl UserFromStorage { if self.0.totp_secret.is_none() { return Ok(None); } - + let key_manager_state = &state.into(); let user_key_store = state .global_store .get_user_key_store_by_user_id( + key_manager_state, self.get_user_id(), &state.store.get_master_key().to_vec().into(), ) @@ -1025,7 +1040,9 @@ impl UserFromStorage { .change_context(UserErrors::InternalServerError)?; Ok(domain_types::decrypt::<String, masking::WithType>( + key_manager_state, self.0.totp_secret.clone(), + Identifier::User(user_key_store.user_id.clone()), user_key_store.key.peek(), ) .await @@ -1141,6 +1158,7 @@ impl SignInWithMultipleRolesStrategy { let merchant_accounts = state .store .list_multiple_merchant_accounts( + &state.into(), self.user_roles .iter() .map(|role| role.merchant_id.clone()) diff --git a/crates/router/src/types/domain/user_key_store.rs b/crates/router/src/types/domain/user_key_store.rs index 4c1427d58dc..3a1a9a60e95 100644 --- a/crates/router/src/types/domain/user_key_store.rs +++ b/crates/router/src/types/domain/user_key_store.rs @@ -1,6 +1,7 @@ use common_utils::{ crypto::{Encryptable, GcmAes256}, date_time, + types::keymanager::{Identifier, KeyManagerState}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; @@ -32,14 +33,17 @@ impl super::behaviour::Conversion for UserKeyStore { } async fn convert_back( + state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, + _key_store_ref_id: String, ) -> CustomResult<Self, ValidationError> where Self: Sized, { + let identifier = Identifier::User(item.user_id.clone()); Ok(Self { - key: Encryptable::decrypt(item.key, key.peek(), GcmAes256) + key: Encryptable::decrypt_via_api(state, item.key, identifier, key.peek(), GcmAes256) .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index 64e2f534b7a..a36aee4593e 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -14,19 +14,25 @@ pub mod verify_connector; use std::fmt::Debug; -use api_models::{enums, payments, webhooks}; +use api_models::{ + enums, + payments::{self, AddressDetailsWithPhone}, + webhooks, +}; use base64::Engine; -use common_utils::id_type; pub use common_utils::{ crypto, ext_traits::{ByteSliceExt, BytesExt, Encode, StringExt, ValueExt}, fp_utils::when, validation::validate_email, }; +use common_utils::{ + id_type, + types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, +}; use error_stack::ResultExt; -use hyperswitch_domain_models::payments::PaymentIntent; +use hyperswitch_domain_models::{payments::PaymentIntent, type_encryption::batch_encrypt}; use image::Luma; -use masking::ExposeInterface; use nanoid::nanoid; use qrcode; use router_env::metrics::add_attributes; @@ -43,19 +49,10 @@ use crate::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, utils, webhooks as webhooks_core, }, - db::StorageInterface, logger, - routes::metrics, + routes::{metrics, SessionState}, services, - types::{ - self, - domain::{ - self, - types::{encrypt_optional, AsyncLift}, - }, - storage, - transformers::ForeignFrom, - }, + types::{self, domain, storage, transformers::ForeignFrom}, }; pub mod error_parser { @@ -194,14 +191,17 @@ impl QrImage { } pub async fn find_payment_intent_from_payment_id_type( - db: &dyn StorageInterface, + state: &SessionState, payment_id_type: payments::PaymentIdType, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { + let key_manager_state: KeyManagerState = state.into(); + let db = &*state.store; match payment_id_type { payments::PaymentIdType::PaymentIntentId(payment_id) => db .find_payment_intent_by_payment_id_merchant_id( + &key_manager_state, &payment_id, &merchant_account.merchant_id, key_store, @@ -219,6 +219,7 @@ pub async fn find_payment_intent_from_payment_id_type( .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( + &key_manager_state, &attempt.payment_id, &merchant_account.merchant_id, key_store, @@ -237,6 +238,7 @@ pub async fn find_payment_intent_from_payment_id_type( .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( + &key_manager_state, &attempt.payment_id, &merchant_account.merchant_id, key_store, @@ -252,12 +254,13 @@ pub async fn find_payment_intent_from_payment_id_type( } pub async fn find_payment_intent_from_refund_id_type( - db: &dyn StorageInterface, + state: &SessionState, refund_id_type: webhooks::RefundIdType, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, connector_name: &str, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { + let db = &*state.store; let refund = match refund_id_type { webhooks::RefundIdType::RefundId(id) => db .find_refund_by_merchant_id_refund_id( @@ -286,6 +289,7 @@ pub async fn find_payment_intent_from_refund_id_type( .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( + &state.into(), &attempt.payment_id, &merchant_account.merchant_id, key_store, @@ -296,11 +300,12 @@ pub async fn find_payment_intent_from_refund_id_type( } pub async fn find_payment_intent_from_mandate_id_type( - db: &dyn StorageInterface, + state: &SessionState, mandate_id_type: webhooks::MandateIdType, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { + let db = &*state.store; let mandate = match mandate_id_type { webhooks::MandateIdType::MandateId(mandate_id) => db .find_mandate_by_merchant_id_mandate_id( @@ -320,6 +325,7 @@ pub async fn find_payment_intent_from_mandate_id_type( .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, }; db.find_payment_intent_by_payment_id_merchant_id( + &state.into(), &mandate .original_payment_id .ok_or(errors::ApiErrorResponse::InternalServerError) @@ -333,11 +339,12 @@ pub async fn find_payment_intent_from_mandate_id_type( } pub async fn find_mca_from_authentication_id_type( - db: &dyn StorageInterface, + state: &SessionState, authentication_id_type: webhooks::AuthenticationIdType, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { + let db = &*state.store; let authentication = match authentication_id_type { webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => db .find_authentication_by_merchant_id_authentication_id( @@ -356,6 +363,7 @@ pub async fn find_mca_from_authentication_id_type( } }; db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &state.into(), &merchant_account.merchant_id, &authentication.merchant_connector_id, key_store, @@ -367,12 +375,13 @@ pub async fn find_mca_from_authentication_id_type( } pub async fn get_mca_from_payment_intent( - db: &dyn StorageInterface, + state: &SessionState, merchant_account: &domain::MerchantAccount, payment_intent: PaymentIntent, key_store: &domain::MerchantKeyStore, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { + let db = &*state.store; let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &payment_intent.active_attempt.get_id(), @@ -381,10 +390,11 @@ pub async fn get_mca_from_payment_intent( ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - + let key_manager_state = &state.into(); match payment_attempt.merchant_connector_id { Some(merchant_connector_id) => db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, &merchant_account.merchant_id, &merchant_connector_id, key_store, @@ -410,6 +420,7 @@ pub async fn get_mca_from_payment_intent( }; db.find_merchant_connector_account_by_profile_id_connector_name( + key_manager_state, &profile_id, connector_name, key_store, @@ -426,12 +437,13 @@ pub async fn get_mca_from_payment_intent( #[cfg(feature = "payouts")] pub async fn get_mca_from_payout_attempt( - db: &dyn StorageInterface, + state: &SessionState, merchant_account: &domain::MerchantAccount, payout_id_type: webhooks::PayoutIdType, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { + let db = &*state.store; let payout = match payout_id_type { webhooks::PayoutIdType::PayoutAttemptId(payout_attempt_id) => db .find_payout_attempt_by_merchant_id_payout_attempt_id( @@ -450,10 +462,11 @@ pub async fn get_mca_from_payout_attempt( .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?, }; - + let key_manager_state = &state.into(); match payout.merchant_connector_id { Some(merchant_connector_id) => db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, &merchant_account.merchant_id, &merchant_connector_id, key_store, @@ -464,6 +477,7 @@ pub async fn get_mca_from_payout_attempt( }), None => db .find_merchant_connector_account_by_profile_id_connector_name( + key_manager_state, &payout.profile_id, connector_name, key_store, @@ -479,15 +493,17 @@ pub async fn get_mca_from_payout_attempt( } pub async fn get_mca_from_object_reference_id( - db: &dyn StorageInterface, + state: &SessionState, object_reference_id: webhooks::ObjectReferenceId, merchant_account: &domain::MerchantAccount, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { + let db = &*state.store; match merchant_account.default_profile.as_ref() { Some(profile_id) => db .find_merchant_connector_account_by_profile_id_connector_name( + &state.into(), profile_id, connector_name, key_store, @@ -499,10 +515,10 @@ pub async fn get_mca_from_object_reference_id( _ => match object_reference_id { webhooks::ObjectReferenceId::PaymentId(payment_id_type) => { get_mca_from_payment_intent( - db, + state, merchant_account, find_payment_intent_from_payment_id_type( - db, + state, payment_id_type, merchant_account, key_store, @@ -515,10 +531,10 @@ pub async fn get_mca_from_object_reference_id( } webhooks::ObjectReferenceId::RefundId(refund_id_type) => { get_mca_from_payment_intent( - db, + state, merchant_account, find_payment_intent_from_refund_id_type( - db, + state, refund_id_type, merchant_account, key_store, @@ -532,10 +548,10 @@ pub async fn get_mca_from_object_reference_id( } webhooks::ObjectReferenceId::MandateId(mandate_id_type) => { get_mca_from_payment_intent( - db, + state, merchant_account, find_payment_intent_from_mandate_id_type( - db, + state, mandate_id_type, merchant_account, key_store, @@ -548,7 +564,7 @@ pub async fn get_mca_from_object_reference_id( } webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) => { find_mca_from_authentication_id_type( - db, + state, authentication_id_type, merchant_account, key_store, @@ -558,7 +574,7 @@ pub async fn get_mca_from_object_reference_id( #[cfg(feature = "payouts")] webhooks::ObjectReferenceId::PayoutId(payout_id_type) => { get_mca_from_payout_attempt( - db, + state, merchant_account, payout_id_type, connector_name, @@ -649,13 +665,16 @@ pub fn add_connector_http_status_code_metrics(option_status_code: Option<u16>) { pub trait CustomerAddress { async fn get_address_update( &self, + state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, + merchant_id: String, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError>; async fn get_domain_address( &self, + state: &SessionState, address_details: payments::AddressDetails, merchant_id: &str, customer_id: &id_type::CustomerId, @@ -668,126 +687,89 @@ pub trait CustomerAddress { impl CustomerAddress for api_models::customers::CustomerRequest { async fn get_address_update( &self, + state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, + merchant_id: String, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> { - async { - Ok(storage::AddressUpdate::Update { - city: address_details.city, - country: address_details.country, - line1: address_details - .line1 - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - line2: address_details - .line2 - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - line3: address_details - .line3 - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - zip: address_details - .zip - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - state: address_details - .state - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - first_name: address_details - .first_name - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - last_name: address_details - .last_name - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - phone_number: self - .phone - .clone() - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - country_code: self.phone_country_code.clone(), - updated_by: storage_scheme.to_string(), - email: self - .email - .as_ref() - .cloned() - .async_lift(|inner| encrypt_optional(inner.map(|inner| inner.expose()), key)) - .await?, - }) - } - .await + let encrypted_data = batch_encrypt( + &state.into(), + AddressDetailsWithPhone::to_encryptable(AddressDetailsWithPhone { + address: Some(address_details.clone()), + phone_number: self.phone.clone(), + email: self.email.clone(), + }), + Identifier::Merchant(merchant_id), + key, + ) + .await?; + let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data) + .change_context(common_utils::errors::CryptoError::EncodingFailed)?; + Ok(storage::AddressUpdate::Update { + city: address_details.city, + country: address_details.country, + line1: encryptable_address.line1, + line2: encryptable_address.line2, + line3: encryptable_address.line3, + zip: encryptable_address.zip, + state: encryptable_address.state, + first_name: encryptable_address.first_name, + last_name: encryptable_address.last_name, + phone_number: encryptable_address.phone_number, + country_code: self.phone_country_code.clone(), + updated_by: storage_scheme.to_string(), + email: encryptable_address.email, + }) } async fn get_domain_address( &self, + state: &SessionState, address_details: payments::AddressDetails, merchant_id: &str, customer_id: &id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError> { - async { - let address = domain::Address { - id: None, - city: address_details.city, - country: address_details.country, - line1: address_details - .line1 - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - line2: address_details - .line2 - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - line3: address_details - .line3 - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - zip: address_details - .zip - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - state: address_details - .state - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - first_name: address_details - .first_name - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - last_name: address_details - .last_name - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - phone_number: self - .phone - .clone() - .async_lift(|inner| encrypt_optional(inner, key)) - .await?, - country_code: self.phone_country_code.clone(), - merchant_id: merchant_id.to_string(), - address_id: generate_id(consts::ID_LENGTH, "add"), - created_at: common_utils::date_time::now(), - modified_at: common_utils::date_time::now(), - updated_by: storage_scheme.to_string(), - email: self - .email - .as_ref() - .cloned() - .async_lift(|inner| encrypt_optional(inner.map(|inner| inner.expose()), key)) - .await?, - }; + let encrypted_data = batch_encrypt( + &state.into(), + AddressDetailsWithPhone::to_encryptable(AddressDetailsWithPhone { + address: Some(address_details.clone()), + phone_number: self.phone.clone(), + email: self.email.clone(), + }), + Identifier::Merchant(merchant_id.to_string()), + key, + ) + .await?; + let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data) + .change_context(common_utils::errors::CryptoError::EncodingFailed)?; + let address = domain::Address { + id: None, + city: address_details.city, + country: address_details.country, + line1: encryptable_address.line1, + line2: encryptable_address.line2, + line3: encryptable_address.line3, + zip: encryptable_address.zip, + state: encryptable_address.state, + first_name: encryptable_address.first_name, + last_name: encryptable_address.last_name, + phone_number: encryptable_address.phone_number, + country_code: self.phone_country_code.clone(), + merchant_id: merchant_id.to_string(), + address_id: generate_id(consts::ID_LENGTH, "add"), + created_at: common_utils::date_time::now(), + modified_at: common_utils::date_time::now(), + updated_by: storage_scheme.to_string(), + email: encryptable_address.email, + }; - Ok(domain::CustomerAddress { - address, - customer_id: customer_id.to_owned(), - }) - } - .await + Ok(domain::CustomerAddress { + address, + customer_id: customer_id.to_owned(), + }) } } @@ -911,7 +893,7 @@ pub async fn trigger_payments_webhook<F, Op>( key_store: &domain::MerchantKeyStore, payment_data: crate::core::payments::PaymentData<F>, customer: Option<domain::Customer>, - state: &crate::routes::SessionState, + state: &SessionState, operation: Op, ) -> RouterResult<()> where diff --git a/crates/router/src/utils/connector_onboarding.rs b/crates/router/src/utils/connector_onboarding.rs index 15ad2eb8954..0bc8e58fcc4 100644 --- a/crates/router/src/utils/connector_onboarding.rs +++ b/crates/router/src/utils/connector_onboarding.rs @@ -45,9 +45,11 @@ pub async fn check_if_connector_exists( connector_id: &str, merchant_id: &str, ) -> RouterResult<()> { + let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -57,6 +59,7 @@ pub async fn check_if_connector_exists( let _connector = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, merchant_id, connector_id, &key_store, diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 3cd35886ffe..9734122a260 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -2,8 +2,8 @@ use std::{collections::HashMap, sync::Arc}; use api_models::user as user_api; use common_enums::UserAuthType; -use common_utils::errors::CustomResult; -use diesel_models::{encryption::Encryption, enums::UserStatus, user_role::UserRole}; +use common_utils::{encryption::Encryption, errors::CustomResult, types::keymanager::Identifier}; +use diesel_models::{enums::UserStatus, user_role::UserRole}; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; use redis_interface::RedisConnectionPool; @@ -33,9 +33,11 @@ impl UserFromToken { &self, state: SessionState, ) -> UserResult<MerchantAccount> { + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, &self.merchant_id, &state.store.get_master_key().to_vec().into(), ) @@ -49,7 +51,7 @@ impl UserFromToken { })?; let merchant_account = state .store - .find_merchant_account_by_merchant_id(&self.merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &self.merchant_id, &key_store) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -218,8 +220,10 @@ impl ForeignFrom<&user_api::AuthConfig> for UserAuthType { } pub async fn construct_public_and_private_db_configs( + state: &SessionState, auth_config: &user_api::AuthConfig, encryption_key: &[u8], + id: String, ) -> UserResult<(Option<Encryption>, Option<serde_json::Value>)> { match auth_config { user_api::AuthConfig::OpenIdConnect { @@ -231,7 +235,9 @@ pub async fn construct_public_and_private_db_configs( .attach_printable("Failed to convert auth config to json")?; let encrypted_config = domain::types::encrypt::<serde_json::Value, masking::WithType>( + &state.into(), private_config_value.into(), + Identifier::UserAuth(id), encryption_key, ) .await @@ -263,6 +269,7 @@ where pub async fn decrypt_oidc_private_config( state: &SessionState, encrypted_config: Option<Encryption>, + id: String, ) -> UserResult<user_api::OpenIdConnectPrivateConfig> { let user_auth_key = hex::decode( state @@ -277,7 +284,9 @@ pub async fn decrypt_oidc_private_config( .attach_printable("Failed to decode DEK")?; let private_config = domain::types::decrypt::<serde_json::Value, masking::WithType>( + &state.into(), encrypted_config, + Identifier::UserAuth(id), &user_auth_key, ) .await diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index b817d3e1cd7..0909f4ffbeb 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -23,7 +23,7 @@ pub async fn generate_sample_data( ) -> SampleDataResult<Vec<(PaymentIntent, PaymentAttemptBatchNew, Option<RefundNew>)>> { let merchant_id = merchant_id.to_string(); let sample_data_size: usize = req.record.unwrap_or(100); - + let key_manager_state = &state.into(); if !(10..=100).contains(&sample_data_size) { return Err(SampleDataError::InvalidRange.into()); } @@ -31,6 +31,7 @@ pub async fn generate_sample_data( let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id.as_str(), &state.store.get_master_key().to_vec().into(), ) @@ -39,7 +40,7 @@ pub async fn generate_sample_data( let merchant_from_db = state .store - .find_merchant_account_by_merchant_id(merchant_id.as_str(), &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id.as_str(), &key_store) .await .change_context::<SampleDataError>(SampleDataError::DataDoesNotExist)?; diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index dc39de8f933..e49a5f86c3c 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -28,17 +28,22 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow { .tracking_data .clone() .parse_value("ApiKeyExpiryTrackingData")?; - + let key_manager_satte = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_satte, tracking_data.merchant_id.as_str(), &state.store.get_master_key().to_vec().into(), ) .await?; let merchant_account = db - .find_merchant_account_by_merchant_id(tracking_data.merchant_id.as_str(), &key_store) + .find_merchant_account_by_merchant_id( + key_manager_satte, + tracking_data.merchant_id.as_str(), + &key_store, + ) .await?; let email_id = merchant_account diff --git a/crates/router/src/workflows/attach_payout_account_workflow.rs b/crates/router/src/workflows/attach_payout_account_workflow.rs index eb60510ad75..7ff0faefa68 100644 --- a/crates/router/src/workflows/attach_payout_account_workflow.rs +++ b/crates/router/src/workflows/attach_payout_account_workflow.rs @@ -31,16 +31,17 @@ impl ProcessTrackerWorkflow<SessionState> for AttachPayoutAccountWorkflow { .merchant_id .clone() .get_required_value("merchant_id")?; - + let key_manager_state = &state.into(); let key_store = db .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id.as_ref(), &db.get_master_key().to_vec().into(), ) .await?; let merchant_account = db - .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await?; let request = api::payouts::PayoutRequest::PayoutRetrieveRequest(tracking_data); diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs index a8d5c28b64f..d181aedd18f 100644 --- a/crates/router/src/workflows/outgoing_webhook_retry.rs +++ b/crates/router/src/workflows/outgoing_webhook_retry.rs @@ -43,8 +43,10 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { .parse_value("OutgoingWebhookTrackingData")?; let db = &*state.store; + let key_manager_state = &state.into(); let key_store = db .get_merchant_key_store_by_merchant_id( + key_manager_state, &tracking_data.merchant_id, &db.get_master_key().to_vec().into(), ) @@ -63,6 +65,7 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { let initial_event = match &tracking_data.initial_attempt_id { Some(initial_attempt_id) => { db.find_event_by_merchant_id_event_id( + key_manager_state, &business_profile.merchant_id, initial_attempt_id, &key_store, @@ -77,6 +80,7 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { tracking_data.primary_object_id, tracking_data.event_type ); db.find_event_by_merchant_id_event_id( + key_manager_state, &business_profile.merchant_id, &old_event_id, &key_store, @@ -106,7 +110,7 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { }; let event = db - .insert_event(new_event, &key_store) + .insert_event(key_manager_state, new_event, &key_store) .await .map_err(|error| { logger::error!(?error, "Failed to insert event in events table"); @@ -137,7 +141,11 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { // resource None => { let merchant_account = db - .find_merchant_account_by_merchant_id(&tracking_data.merchant_id, &key_store) + .find_merchant_account_by_merchant_id( + key_manager_state, + &tracking_data.merchant_id, + &key_store, + ) .await?; // TODO: Add request state for the PT flows as well @@ -162,6 +170,7 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { }; let request_content = webhooks_core::get_outgoing_webhook_request( + state, &merchant_account, outgoing_webhook, &business_profile, diff --git a/crates/router/src/workflows/payment_method_status_update.rs b/crates/router/src/workflows/payment_method_status_update.rs index b8e57360d90..fa0631cc5c2 100644 --- a/crates/router/src/workflows/payment_method_status_update.rs +++ b/crates/router/src/workflows/payment_method_status_update.rs @@ -30,17 +30,18 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodStatusUpdateWorkflow let prev_pm_status = tracking_data.prev_status; let curr_pm_status = tracking_data.curr_status; let merchant_id = tracking_data.merchant_id; - + let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, merchant_id.as_str(), &state.store.get_master_key().to_vec().into(), ) .await?; let merchant_account = db - .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await?; let payment_method = db diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index ef0fe07e9b7..2bc7b183ec1 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -38,9 +38,10 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow { .tracking_data .clone() .parse_value("PaymentsRetrieveRequest")?; - + let key_manager_state = &state.into(); let key_store = db .get_merchant_key_store_by_merchant_id( + key_manager_state, tracking_data .merchant_id .as_ref() @@ -51,6 +52,7 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow { let merchant_account = db .find_merchant_account_by_merchant_id( + key_manager_state, tracking_data .merchant_id .as_ref() @@ -148,6 +150,7 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow { payment_data.payment_intent = db .update_payment_intent( + &state.into(), payment_data.payment_intent, payment_intent_update, &key_store, diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index ed11f3b8b1c..997ae51cf31 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -288,10 +288,11 @@ async fn payments_create_core() { let state = Arc::new(app_state) .get_session_state("public", || {}) .unwrap(); - + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, "juspay_merchant", &state.store.get_master_key().to_vec().into(), ) @@ -300,7 +301,7 @@ async fn payments_create_core() { let merchant_account = state .store - .find_merchant_account_by_merchant_id("juspay_merchant", &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, "juspay_merchant", &key_store) .await .unwrap(); @@ -476,10 +477,11 @@ async fn payments_create_core_adyen_no_redirect() { let customer_id = format!("cust_{}", Uuid::new_v4()); let merchant_id = "arunraj".to_string(); let payment_id = "pay_mbabizu24mvu3mela5njyhpit10".to_string(); - + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, "juspay_merchant", &state.store.get_master_key().to_vec().into(), ) @@ -488,7 +490,7 @@ async fn payments_create_core_adyen_no_redirect() { let merchant_account = state .store - .find_merchant_account_by_merchant_id("juspay_merchant", &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, "juspay_merchant", &key_store) .await .unwrap(); diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index 4c178e4122b..fcf106a9efc 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -48,10 +48,11 @@ async fn payments_create_core() { let state = Arc::new(app_state) .get_session_state("public", || {}) .unwrap(); - + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, "juspay_merchant", &state.store.get_master_key().to_vec().into(), ) @@ -60,7 +61,7 @@ async fn payments_create_core() { let merchant_account = state .store - .find_merchant_account_by_merchant_id("juspay_merchant", &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, "juspay_merchant", &key_store) .await .unwrap(); @@ -243,10 +244,11 @@ async fn payments_create_core_adyen_no_redirect() { let customer_id = format!("cust_{}", Uuid::new_v4()); let merchant_id = "arunraj".to_string(); let payment_id = "pay_mbabizu24mvu3mela5njyhpit10".to_string(); - + let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( + key_manager_state, "juspay_merchant", &state.store.get_master_key().to_vec().into(), ) @@ -255,7 +257,7 @@ async fn payments_create_core_adyen_no_redirect() { let merchant_account = state .store - .find_merchant_account_by_merchant_id("juspay_merchant", &key_store) + .find_merchant_account_by_merchant_id(key_manager_state, "juspay_merchant", &key_store) .await .unwrap(); diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs index bf3ce0baaab..3e183b94c26 100644 --- a/crates/storage_impl/src/mock_db/payment_intent.rs +++ b/crates/storage_impl/src/mock_db/payment_intent.rs @@ -1,4 +1,4 @@ -use common_utils::errors::CustomResult; +use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use hyperswitch_domain_models::{ @@ -19,6 +19,7 @@ impl PaymentIntentInterface for MockDb { #[cfg(feature = "olap")] async fn filter_payment_intent_by_constraints( &self, + _state: &KeyManagerState, _merchant_id: &str, _filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, _key_store: &MerchantKeyStore, @@ -30,6 +31,7 @@ impl PaymentIntentInterface for MockDb { #[cfg(feature = "olap")] async fn filter_payment_intents_by_time_range_constraints( &self, + _state: &KeyManagerState, _merchant_id: &str, _time_range: &api_models::payments::TimeRange, _key_store: &MerchantKeyStore, @@ -51,6 +53,7 @@ impl PaymentIntentInterface for MockDb { #[cfg(feature = "olap")] async fn get_filtered_payment_intents_attempt( &self, + _state: &KeyManagerState, _merchant_id: &str, _constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, _key_store: &MerchantKeyStore, @@ -63,6 +66,7 @@ impl PaymentIntentInterface for MockDb { #[allow(clippy::panic)] async fn insert_payment_intent( &self, + _state: &KeyManagerState, new: PaymentIntent, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, @@ -76,6 +80,7 @@ impl PaymentIntentInterface for MockDb { #[allow(clippy::unwrap_used)] async fn update_payment_intent( &self, + state: &KeyManagerState, this: PaymentIntent, update: PaymentIntentUpdate, key_store: &MerchantKeyStore, @@ -95,8 +100,10 @@ impl PaymentIntentInterface for MockDb { .change_context(StorageError::EncryptionError)?; *payment_intent = PaymentIntent::convert_back( + state, diesel_payment_intent_update.apply_changeset(diesel_payment_intent), key_store.key.get_inner(), + key_store.merchant_id.clone(), ) .await .change_context(StorageError::DecryptionError)?; @@ -108,6 +115,7 @@ impl PaymentIntentInterface for MockDb { #[allow(clippy::unwrap_used)] async fn find_payment_intent_by_payment_id_merchant_id( &self, + _state: &KeyManagerState, payment_id: &str, merchant_id: &str, _key_store: &MerchantKeyStore, diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index 62854cb261a..ced94b5717b 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -4,7 +4,10 @@ use api_models::payments::AmountFilter; use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; #[cfg(feature = "olap")] use common_utils::errors::ReportSwitchExt; -use common_utils::ext_traits::{AsyncExt, Encode}; +use common_utils::{ + ext_traits::{AsyncExt, Encode}, + types::keymanager::KeyManagerState, +}; #[cfg(feature = "olap")] use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl}; use diesel_models::{ @@ -53,6 +56,7 @@ use crate::{ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { async fn insert_payment_intent( &self, + state: &KeyManagerState, payment_intent: PaymentIntent, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -69,7 +73,12 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store - .insert_payment_intent(payment_intent, merchant_key_store, storage_scheme) + .insert_payment_intent( + state, + payment_intent, + merchant_key_store, + storage_scheme, + ) .await } @@ -121,6 +130,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { #[instrument(skip_all)] async fn update_payment_intent( &self, + state: &KeyManagerState, this: PaymentIntent, payment_intent_update: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, @@ -143,6 +153,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { MerchantStorageScheme::PostgresOnly => { self.router_store .update_payment_intent( + state, this, payment_intent_update, merchant_key_store, @@ -189,10 +200,14 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { .try_into_hset() .change_context(StorageError::KVError)?; - let payment_intent = - PaymentIntent::convert_back(diesel_intent, merchant_key_store.key.get_inner()) - .await - .change_context(StorageError::DecryptionError)?; + let payment_intent = PaymentIntent::convert_back( + state, + diesel_intent, + merchant_key_store.key.get_inner(), + merchant_id, + ) + .await + .change_context(StorageError::DecryptionError)?; Ok(payment_intent) } @@ -202,6 +217,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { #[instrument(skip_all)] async fn find_payment_intent_by_payment_id_merchant_id( &self, + state: &KeyManagerState, payment_id: &str, merchant_id: &str, merchant_key_store: &MerchantKeyStore, @@ -243,9 +259,14 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { } }?; - PaymentIntent::convert_back(diesel_payment_intent, merchant_key_store.key.get_inner()) - .await - .change_context(StorageError::DecryptionError) + PaymentIntent::convert_back( + state, + diesel_payment_intent, + merchant_key_store.key.get_inner(), + merchant_id.to_string(), + ) + .await + .change_context(StorageError::DecryptionError) } async fn get_active_payment_attempt( @@ -278,6 +299,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { #[cfg(feature = "olap")] async fn filter_payment_intent_by_constraints( &self, + state: &KeyManagerState, merchant_id: &str, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, @@ -285,6 +307,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { self.router_store .filter_payment_intent_by_constraints( + state, merchant_id, filters, merchant_key_store, @@ -296,6 +319,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { #[cfg(feature = "olap")] async fn filter_payment_intents_by_time_range_constraints( &self, + state: &KeyManagerState, merchant_id: &str, time_range: &api_models::payments::TimeRange, merchant_key_store: &MerchantKeyStore, @@ -303,6 +327,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { self.router_store .filter_payment_intents_by_time_range_constraints( + state, merchant_id, time_range, merchant_key_store, @@ -314,6 +339,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { #[cfg(feature = "olap")] async fn get_filtered_payment_intents_attempt( &self, + state: &KeyManagerState, merchant_id: &str, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, @@ -321,6 +347,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> { self.router_store .get_filtered_payment_intents_attempt( + state, merchant_id, filters, merchant_key_store, @@ -351,6 +378,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { #[instrument(skip_all)] async fn insert_payment_intent( &self, + state: &KeyManagerState, payment_intent: PaymentIntent, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, @@ -367,14 +395,20 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { er.change_context(new_err) })?; - PaymentIntent::convert_back(diesel_payment_intent, merchant_key_store.key.get_inner()) - .await - .change_context(StorageError::DecryptionError) + PaymentIntent::convert_back( + state, + diesel_payment_intent, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) + .await + .change_context(StorageError::DecryptionError) } #[instrument(skip_all)] async fn update_payment_intent( &self, + state: &KeyManagerState, this: PaymentIntent, payment_intent: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, @@ -394,14 +428,20 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { er.change_context(new_err) })?; - PaymentIntent::convert_back(diesel_payment_intent, merchant_key_store.key.get_inner()) - .await - .change_context(StorageError::DecryptionError) + PaymentIntent::convert_back( + state, + diesel_payment_intent, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), + ) + .await + .change_context(StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_payment_intent_by_payment_id_merchant_id( &self, + state: &KeyManagerState, payment_id: &str, merchant_id: &str, merchant_key_store: &MerchantKeyStore, @@ -417,8 +457,10 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { }) .async_and_then(|diesel_payment_intent| async { PaymentIntent::convert_back( + state, diesel_payment_intent, merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), ) .await .change_context(StorageError::DecryptionError) @@ -458,6 +500,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { #[instrument(skip_all)] async fn filter_payment_intent_by_constraints( &self, + state: &KeyManagerState, merchant_id: &str, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, @@ -498,6 +541,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { // TODO: Fetch partial columns for this query since we only need some columns let starting_at = self .find_payment_intent_by_payment_id_merchant_id( + state, starting_after_id, merchant_id, merchant_key_store, @@ -516,6 +560,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { // TODO: Fetch partial columns for this query since we only need some columns let ending_at = self .find_payment_intent_by_payment_id_merchant_id( + state, ending_before_id, merchant_id, merchant_key_store, @@ -560,8 +605,10 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { .map(|payment_intents| { try_join_all(payment_intents.into_iter().map(|diesel_payment_intent| { PaymentIntent::convert_back( + state, diesel_payment_intent, merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone(), ) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) @@ -579,6 +626,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { #[instrument(skip_all)] async fn filter_payment_intents_by_time_range_constraints( &self, + state: &KeyManagerState, merchant_id: &str, time_range: &api_models::payments::TimeRange, merchant_key_store: &MerchantKeyStore, @@ -587,6 +635,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { // TODO: Remove this redundant function let payment_filters = (*time_range).into(); self.filter_payment_intent_by_constraints( + state, merchant_id, &payment_filters, merchant_key_store, @@ -599,6 +648,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { #[instrument(skip_all)] async fn get_filtered_payment_intents_attempt( &self, + state: &KeyManagerState, merchant_id: &str, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, @@ -640,6 +690,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { // TODO: Fetch partial columns for this query since we only need some columns let starting_at = self .find_payment_intent_by_payment_id_merchant_id( + state, starting_after_id, merchant_id, merchant_key_store, @@ -658,6 +709,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { // TODO: Fetch partial columns for this query since we only need some columns let ending_at = self .find_payment_intent_by_payment_id_merchant_id( + state, ending_before_id, merchant_id, merchant_key_store, @@ -745,13 +797,17 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { .await .map(|results| { try_join_all(results.into_iter().map(|(pi, pa)| { - PaymentIntent::convert_back(pi, merchant_key_store.key.get_inner()).map( - |payment_intent| { - payment_intent.map(|payment_intent| { - (payment_intent, PaymentAttempt::from_storage_model(pa)) - }) - }, + PaymentIntent::convert_back( + state, + pi, + merchant_key_store.key.get_inner(), + merchant_id.to_string(), ) + .map(|payment_intent| { + payment_intent.map(|payment_intent| { + (payment_intent, PaymentAttempt::from_storage_model(pa)) + }) + }) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) })
feat
encryption service integration to support batch encryption and decryption (#5164)
06440eb6400adf166b203d7e4f587c1e2d5fe4f8
2024-04-08 18:59:52
AkshayaFoiger
feat(router): add local bank transfer payment method (#4294)
false
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index bff6dbec3ce..6805363b265 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1465,6 +1465,7 @@ impl GetPaymentMethodType for BankTransferData { Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix {} => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, + Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, } } } @@ -2029,6 +2030,9 @@ pub enum BankTransferData { }, Pix {}, Pse {}, + LocalBankTransfer { + bank_code: Option<String>, + }, } impl GetAddressFromPaymentMethodData for BankTransferData { @@ -2079,7 +2083,7 @@ impl GetAddressFromPaymentMethodData for BankTransferData { phone: None, email: Some(billing_details.email.clone()), }), - Self::Pix {} | Self::Pse {} => None, + Self::LocalBankTransfer { .. } | Self::Pix {} | Self::Pse {} => None, } } } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 932b82ae09c..1134d072c2c 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1423,6 +1423,7 @@ pub enum PaymentMethodType { FamilyMart, Seicomart, PayEasy, + LocalBankTransfer, } /// Indicates the type of payment method. Eg: 'card', 'wallet', etc. diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index 63abfdb3f73..922d2a71c1b 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1842,6 +1842,7 @@ impl From<PaymentMethodType> for PaymentMethod { PaymentMethodType::PermataBankTransfer => Self::BankTransfer, PaymentMethodType::Pix => Self::BankTransfer, PaymentMethodType::Pse => Self::BankTransfer, + PaymentMethodType::LocalBankTransfer => Self::BankTransfer, PaymentMethodType::PayBright => Self::PayLater, PaymentMethodType::Paypal => Self::Wallet, PaymentMethodType::PaySafeCard => Self::GiftCard, diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs index ee64c4ca333..22ab0235866 100644 --- a/crates/euclid/src/frontend/dir/enums.rs +++ b/crates/euclid/src/frontend/dir/enums.rs @@ -186,6 +186,7 @@ pub enum BankTransferType { PermataBankTransfer, Pix, Pse, + LocalBankTransfer, } #[derive( diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs index b1f03e8dd55..f89877ca21a 100644 --- a/crates/euclid/src/frontend/dir/lowering.rs +++ b/crates/euclid/src/frontend/dir/lowering.rs @@ -115,6 +115,7 @@ impl From<enums::BankTransferType> for global_enums::PaymentMethodType { enums::BankTransferType::DanamonVa => Self::DanamonVa, enums::BankTransferType::MandiriVa => Self::MandiriVa, enums::BankTransferType::PermataBankTransfer => Self::PermataBankTransfer, + enums::BankTransferType::LocalBankTransfer => Self::LocalBankTransfer, } } } diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs index c99b39e36f4..929b878f2c2 100644 --- a/crates/euclid/src/frontend/dir/transformers.rs +++ b/crates/euclid/src/frontend/dir/transformers.rs @@ -143,6 +143,9 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet global_enums::PaymentMethodType::DanamonVa => Ok(dirval!(BankTransferType = DanamonVa)), global_enums::PaymentMethodType::Indomaret => Ok(dirval!(VoucherType = Indomaret)), global_enums::PaymentMethodType::MandiriVa => Ok(dirval!(BankTransferType = MandiriVa)), + global_enums::PaymentMethodType::LocalBankTransfer => { + Ok(dirval!(BankTransferType = LocalBankTransfer)) + } global_enums::PaymentMethodType::PermataBankTransfer => { Ok(dirval!(BankTransferType = PermataBankTransfer)) } diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 5bcb64fd875..000a16a2634 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -262,6 +262,9 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { api_enums::PaymentMethodType::DanamonVa => Ok(dirval!(BankTransferType = DanamonVa)), api_enums::PaymentMethodType::Indomaret => Ok(dirval!(VoucherType = Indomaret)), api_enums::PaymentMethodType::MandiriVa => Ok(dirval!(BankTransferType = MandiriVa)), + api_enums::PaymentMethodType::LocalBankTransfer => { + Ok(dirval!(BankTransferType = LocalBankTransfer)) + } api_enums::PaymentMethodType::PermataBankTransfer => { Ok(dirval!(BankTransferType = PermataBankTransfer)) } diff --git a/crates/router/build.rs b/crates/router/build.rs index b33c168833d..99d6de0fda4 100644 --- a/crates/router/build.rs +++ b/crates/router/build.rs @@ -2,7 +2,7 @@ fn main() { // Set thread stack size to 8 MiB for debug builds // Reference: https://doc.rust-lang.org/std/thread/#stack-size #[cfg(debug_assertions)] - println!("cargo:rustc-env=RUST_MIN_STACK=8388608"); // 8 * 1024 * 1024 = 8 MiB + println!("cargo:rustc-env=RUST_MIN_STACK=18388608"); // 8 * 1024 * 1024 = 8 MiB #[cfg(feature = "vergen")] router_env::vergen::generate_cargo_instructions(); diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 44e889ed9db..481eba0df70 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -202,6 +202,7 @@ impl ConnectorValidation for Adyen { | PaymentMethodType::Becs | PaymentMethodType::ClassicReward | PaymentMethodType::Pse + | PaymentMethodType::LocalBankTransfer | PaymentMethodType::Efecty | PaymentMethodType::PagoEfectivo | PaymentMethodType::RedCompra diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index cc37f464ae6..e47b570a062 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2484,6 +2484,7 @@ impl<'a> TryFrom<&api_models::payments::BankTransferData> for AdyenPaymentMethod | api_models::payments::BankTransferData::SepaBankTransfer { .. } | api_models::payments::BankTransferData::BacsBankTransfer { .. } | api_models::payments::BankTransferData::MultibancoBankTransfer { .. } + | api_models::payments::BankTransferData::LocalBankTransfer { .. } | payments::BankTransferData::Pse {} => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Adyen"), ) diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 190e1705411..814bd68da68 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -403,6 +403,7 @@ impl | common_enums::PaymentMethodType::WeChatPay | common_enums::PaymentMethodType::SevenEleven | common_enums::PaymentMethodType::Lawson + | common_enums::PaymentMethodType::LocalBankTransfer | common_enums::PaymentMethodType::MiniStop | common_enums::PaymentMethodType::FamilyMart | common_enums::PaymentMethodType::Seicomart diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 64ff7db2a89..6a3d396c835 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -690,7 +690,8 @@ impl TryFrom<&api_models::payments::BankTransferData> for PaypalPaymentsRequest | api_models::payments::BankTransferData::DanamonVaBankTransfer { .. } | api_models::payments::BankTransferData::MandiriVaBankTransfer { .. } | api_models::payments::BankTransferData::Pix {} - | api_models::payments::BankTransferData::Pse {} => { + | api_models::payments::BankTransferData::Pse {} + | api_models::payments::BankTransferData::LocalBankTransfer { .. } => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), ) diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index bb46a207df4..1137fa58e86 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -232,10 +232,13 @@ impl TryFrom<&api_models::payments::BankTransferData> for Shift4PaymentMethod { | payments::BankTransferData::DanamonVaBankTransfer { .. } | payments::BankTransferData::MandiriVaBankTransfer { .. } | payments::BankTransferData::Pix {} - | payments::BankTransferData::Pse {} => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Shift4"), - ) - .into()), + | payments::BankTransferData::Pse {} + | payments::BankTransferData::LocalBankTransfer { .. } => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) + .into()) + } } } } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index a73e1045cfc..7c5ef36127c 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -705,6 +705,7 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { | enums::PaymentMethodType::FamilyMart | enums::PaymentMethodType::Seicomart | enums::PaymentMethodType::PayEasy + | enums::PaymentMethodType::LocalBankTransfer | enums::PaymentMethodType::Walley => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) @@ -1413,6 +1414,7 @@ fn create_stripe_payment_method( ) .into()), payments::BankTransferData::Pse {} + | payments::BankTransferData::LocalBankTransfer { .. } | payments::BankTransferData::PermataBankTransfer { .. } | payments::BankTransferData::BcaBankTransfer { .. } | payments::BankTransferData::BniVaBankTransfer { .. } @@ -3266,6 +3268,7 @@ impl TryFrom<&types::PaymentsPreProcessingRouterData> for StripeCreditTransferSo | payments::BankTransferData::CimbVaBankTransfer { .. } | payments::BankTransferData::DanamonVaBankTransfer { .. } | payments::BankTransferData::MandiriVaBankTransfer { .. } + | payments::BankTransferData::LocalBankTransfer { .. } | payments::BankTransferData::Pix { .. } | payments::BankTransferData::Pse { .. } => { Err(errors::ConnectorError::NotImplemented( @@ -3723,6 +3726,7 @@ impl | payments::BankTransferData::BriVaBankTransfer { .. } | payments::BankTransferData::CimbVaBankTransfer { .. } | payments::BankTransferData::DanamonVaBankTransfer { .. } + | payments::BankTransferData::LocalBankTransfer { .. } | payments::BankTransferData::MandiriVaBankTransfer { .. } => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index eb658528452..4f11af6a33a 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -358,6 +358,7 @@ impl | api_models::payments::BankTransferData::BriVaBankTransfer { .. } | api_models::payments::BankTransferData::CimbVaBankTransfer { .. } | api_models::payments::BankTransferData::DanamonVaBankTransfer { .. } + | api_models::payments::BankTransferData::LocalBankTransfer { .. } | api_models::payments::BankTransferData::MandiriVaBankTransfer { .. } => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Zen"), diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 51b95041898..9ec570b441e 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2204,6 +2204,7 @@ pub fn validate_payment_method_type_against_payment_method( | api_enums::PaymentMethodType::CimbVa | api_enums::PaymentMethodType::DanamonVa | api_enums::PaymentMethodType::MandiriVa + | api_enums::PaymentMethodType::LocalBankTransfer ), api_enums::PaymentMethod::BankDebit => matches!( payment_method_type, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 3362aad6fc5..c5250b0cc73 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -453,6 +453,7 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { | api_enums::PaymentMethodType::CimbVa | api_enums::PaymentMethodType::DanamonVa | api_enums::PaymentMethodType::MandiriVa + | api_enums::PaymentMethodType::LocalBankTransfer | api_enums::PaymentMethodType::Pix => Self::BankTransfer, api_enums::PaymentMethodType::Givex | api_enums::PaymentMethodType::PaySafeCard => { Self::GiftCard diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index aacc1386411..1af82da7f59 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -6242,6 +6242,23 @@ "type": "object" } } + }, + { + "type": "object", + "required": [ + "local_bank_transfer" + ], + "properties": { + "local_bank_transfer": { + "type": "object", + "properties": { + "bank_code": { + "type": "string", + "nullable": true + } + } + } + } } ] }, @@ -12870,7 +12887,8 @@ "mini_stop", "family_mart", "seicomart", - "pay_easy" + "pay_easy", + "local_bank_transfer" ] }, "PaymentMethodUpdate": {
feat
add local bank transfer payment method (#4294)
df0ef157c3a107f8b3d2bbf37ef9e19ea66425fc
2023-07-18 18:08:51
AkshayaFoiger
feat(connector): [Adyen] Implement Gcash for Adyen (#1576)
false
diff --git a/config/development.toml b/config/development.toml index 6c01b9546ae..eb944262920 100644 --- a/config/development.toml +++ b/config/development.toml @@ -245,6 +245,7 @@ ali_pay_hk = {country = "HK", currency = "HKD"} bizum = {country = "ES", currency = "EUR"} go_pay = {country = "ID", currency = "IDR"} kakao_pay = {country = "KR", currency = "KRW"} +gcash = {country = "PH", currency = "PHP"} [pm_filters.braintree] paypal = { currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,RUB,SGD,SEK,CHF,THB,USD" } diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 9e7b5562e38..90dd1f22e92 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -956,6 +956,8 @@ pub enum WalletData { KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), + /// The wallet data for Gcash redirect + GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow @@ -1048,6 +1050,9 @@ pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct GcashRedirection {} + #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 58b5c48b635..a05089d4b8b 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -571,6 +571,7 @@ pub enum PaymentMethodType { Giropay, GooglePay, GoPay, + Gcash, Ideal, Interac, Klarna, diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index 33baed2cf92..1218e983bc6 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1555,6 +1555,7 @@ impl From<PaymentMethodType> for PaymentMethod { PaymentMethodType::Giropay => Self::BankRedirect, PaymentMethodType::GooglePay => Self::Wallet, PaymentMethodType::GoPay => Self::Wallet, + PaymentMethodType::Gcash => Self::Wallet, PaymentMethodType::Ideal => Self::BankRedirect, PaymentMethodType::Klarna => Self::PayLater, PaymentMethodType::KakaoPay => Self::Wallet, diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 972d7a6d860..7a43f6f314a 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -283,11 +283,14 @@ pub enum AdyenPaymentMethod<'a> { Blik(Box<BlikRedirectionData>), ClearPay(Box<AdyenPayLaterData>), Eps(Box<BankRedirectionWithIssuer<'a>>), + #[serde(rename = "gcash")] + Gcash(Box<GcashData>), Giropay(Box<BankRedirectionPMData>), Gpay(Box<AdyenGPay>), #[serde(rename = "gopay_wallet")] GoPay(Box<GoPayData>), Ideal(Box<BankRedirectionWithIssuer<'a>>), + #[serde(rename = "kakaopay")] Kakaopay(Box<KakaoPayData>), Mandate(Box<AdyenMandate>), Mbway(Box<MbwayData>), @@ -646,6 +649,8 @@ pub struct GoPayData {} #[derive(Debug, Clone, Serialize, Deserialize)] pub struct KakaoPayData {} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct GcashData {} #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AdyenGPay { @@ -713,6 +718,7 @@ pub enum PaymentType { Blik, ClearPay, Eps, + Gcash, Giropay, Googlepay, #[serde(rename = "gopay_wallet")] @@ -1200,6 +1206,10 @@ impl<'a> TryFrom<&api::WalletData> for AdyenPaymentMethod<'a> { let kakao_pay_data = KakaoPayData {}; Ok(AdyenPaymentMethod::Kakaopay(Box::new(kakao_pay_data))) } + api_models::payments::WalletData::GcashRedirect(_) => { + let gcash_data = GcashData {}; + Ok(AdyenPaymentMethod::Gcash(Box::new(gcash_data))) + } api_models::payments::WalletData::MbWayRedirect(data) => { let mbway_data = MbwayData { payment_type: PaymentType::Mbway, diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index 4ede9eca3ad..74773958a1d 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -170,6 +170,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::BankDebitData, api_models::payments::AliPayQr, api_models::payments::AliPayRedirection, + api_models::payments::GcashRedirection, api_models::payments::KakaoPayRedirection, api_models::payments::AliPayHkRedirection, api_models::payments::GoPayRedirection, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 12e1922b2a6..4335aece5c1 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -177,6 +177,7 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { | api_enums::PaymentMethodType::Twint | api_enums::PaymentMethodType::WeChatPay | api_enums::PaymentMethodType::GoPay + | api_enums::PaymentMethodType::Gcash | api_enums::PaymentMethodType::KakaoPay => Self::Wallet, api_enums::PaymentMethodType::Affirm | api_enums::PaymentMethodType::AfterpayClearpay diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 1c6690a47fb..e2686ca24b0 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4348,6 +4348,9 @@ "on_session" ] }, + "GcashRedirection": { + "type": "object" + }, "GoPayRedirection": { "type": "object" }, @@ -6809,6 +6812,7 @@ "giropay", "google_pay", "go_pay", + "gcash", "ideal", "interac", "klarna", @@ -8937,6 +8941,17 @@ } } }, + { + "type": "object", + "required": [ + "gcash_redirect" + ], + "properties": { + "gcash_redirect": { + "$ref": "#/components/schemas/GcashRedirection" + } + } + }, { "type": "object", "required": [
feat
[Adyen] Implement Gcash for Adyen (#1576)
d335879f9289b57a90a76c6587a58a0b3e12c9ad
2023-11-06 13:40:10
Sai Harsha Vardhan
feat(router): make webhook events config disabled only and by default enable all the events (#2770)
false
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 8b7df2a14be..ba4d7f6549e 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -963,8 +963,13 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr return Ok((response, WebhookResponseTracker::NoEffect)); } }; + logger::info!(event_type=?event_type); - let process_webhook_further = utils::lookup_webhook_event( + let is_webhook_event_supported = !matches!( + event_type, + api_models::webhooks::IncomingWebhookEvent::EventNotSupported + ); + let is_webhook_event_enabled = !utils::is_webhook_event_disabled( &*state.clone().store, connector_name.as_str(), &merchant_account.merchant_id, @@ -972,8 +977,10 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr ) .await; + //process webhook further only if webhook event is enabled and is not event_not_supported + let process_webhook_further = is_webhook_event_enabled && is_webhook_event_supported; + logger::info!(process_webhook=?process_webhook_further); - logger::info!(event_type=?event_type); let flow_type: api::WebhookFlow = event_type.to_owned().into(); let webhook_effect = if process_webhook_further diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs index b187001e10e..322440e5313 100644 --- a/crates/router/src/core/webhooks/utils.rs +++ b/crates/router/src/core/webhooks/utils.rs @@ -9,20 +9,10 @@ use crate::{ payments::helpers, }, db::{get_and_deserialize_key, StorageInterface}, + services::logger, types::{self, api, domain, PaymentAddress}, }; -fn default_webhook_config() -> api::MerchantWebhookConfig { - std::collections::HashSet::from([ - api::IncomingWebhookEvent::PaymentIntentSuccess, - api::IncomingWebhookEvent::PaymentIntentFailure, - api::IncomingWebhookEvent::PaymentIntentProcessing, - api::IncomingWebhookEvent::PaymentIntentCancelled, - api::IncomingWebhookEvent::PaymentActionRequired, - api::IncomingWebhookEvent::RefundSuccess, - ]) -} - const IRRELEVANT_PAYMENT_ID_IN_SOURCE_VERIFICATION_FLOW: &str = "irrelevant_payment_id_in_source_verification_flow"; const IRRELEVANT_ATTEMPT_ID_IN_SOURCE_VERIFICATION_FLOW: &str = @@ -30,38 +20,40 @@ const IRRELEVANT_ATTEMPT_ID_IN_SOURCE_VERIFICATION_FLOW: &str = const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_SOURCE_VERIFICATION_FLOW: &str = "irrelevant_connector_request_reference_id_in_source_verification_flow"; -/// Check whether the merchant has configured to process the webhook `event` for the `connector` +/// Check whether the merchant has configured to disable the webhook `event` for the `connector` /// First check for the key "whconf_{merchant_id}_{connector_id}" in redis, -/// if not found, fetch from configs table in database, if not found use default -pub async fn lookup_webhook_event( +/// if not found, fetch from configs table in database +pub async fn is_webhook_event_disabled( db: &dyn StorageInterface, connector_id: &str, merchant_id: &str, event: &api::IncomingWebhookEvent, ) -> bool { - let redis_key = format!("whconf_{merchant_id}_{connector_id}"); - let merchant_webhook_config_result = - get_and_deserialize_key(db, &redis_key, "MerchantWebhookConfig") - .await - .map(|h| &h | &default_webhook_config()); + let redis_key = format!("whconf_disabled_events_{merchant_id}_{connector_id}"); + let merchant_webhook_disable_config_result: CustomResult< + api::MerchantWebhookConfig, + redis_interface::errors::RedisError, + > = get_and_deserialize_key(db, &redis_key, "MerchantWebhookConfig").await; - match merchant_webhook_config_result { + match merchant_webhook_disable_config_result { Ok(merchant_webhook_config) => merchant_webhook_config.contains(event), Err(..) => { //if failed to fetch from redis. fetch from db and populate redis db.find_config_by_key(&redis_key) .await .map(|config| { - if let Ok(set) = - serde_json::from_str::<api::MerchantWebhookConfig>(&config.config) - { - &set | &default_webhook_config() - } else { - default_webhook_config() + match serde_json::from_str::<api::MerchantWebhookConfig>(&config.config) { + Ok(set) => set.contains(event), + Err(err) => { + logger::warn!(?err, "error while parsing merchant webhook config"); + false + } } }) - .unwrap_or_else(|_| default_webhook_config()) - .contains(event) + .unwrap_or_else(|err| { + logger::warn!(?err, "error while fetching merchant webhook config"); + false + }) } } }
feat
make webhook events config disabled only and by default enable all the events (#2770)
45111337e42527ff96bd8348a2cde50eccc904f4
2023-04-06 14:25:15
ItsMeShashank
deps: update ci workflows for common_enums crate (#843)
false
diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 0356b9f997b..92bed90d8db 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -117,6 +117,11 @@ jobs: else echo "api_models_changes_exist=true" >> $GITHUB_ENV fi + if git diff --exit-code --quiet origin/$GITHUB_BASE_REF -- crates/common_enums/; then + echo "common_enums_changes_exist=false" >> $GITHUB_ENV + else + echo "common_enums_changes_exist=true" >> $GITHUB_ENV + fi if git diff --exit-code --quiet origin/$GITHUB_BASE_REF -- crates/common_utils/; then echo "common_utils_changes_exist=false" >> $GITHUB_ENV else @@ -162,6 +167,10 @@ jobs: if: env.api_models_changes_exist == 'true' run: cargo hack check --each-feature --no-dev-deps -p api_models + - name: Cargo hack common_enums + if: env.common_enums_changes_exist == 'true' + run: cargo hack check --each-feature --no-dev-deps -p common_enums + - name: Cargo hack common_utils if: env.common_utils_changes_exist == 'true' run: cargo hack check --each-feature --no-dev-deps -p common_utils @@ -280,6 +289,11 @@ jobs: else echo "api_models_changes_exist=true" >> $GITHUB_ENV fi + if git diff --exit-code --quiet origin/$GITHUB_BASE_REF -- crates/common_enums/; then + echo "common_enums_changes_exist=false" >> $GITHUB_ENV + else + echo "common_enums_changes_exist=true" >> $GITHUB_ENV + fi if git diff --exit-code --quiet origin/$GITHUB_BASE_REF -- crates/common_utils/; then echo "common_utils_changes_exist=false" >> $GITHUB_ENV else @@ -325,6 +339,10 @@ jobs: if: env.api_models_changes_exist == 'true' run: cargo hack check --each-feature --no-dev-deps -p api_models + - name: Cargo hack common_enums + if: env.common_enums_changes_exist == 'true' + run: cargo hack check --each-feature --no-dev-deps -p common_enums + - name: Cargo hack common_utils if: env.common_utils_changes_exist == 'true' run: cargo hack check --each-feature --no-dev-deps -p common_utils
deps
update ci workflows for common_enums crate (#843)