Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(analytics): add ClickHouse-backed payment intents aggregate endpoints (#12387)
Venu Madhav Bandarupallif31231fc262e
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rsindex dc1b0cd8b1..315a4fe311 100644--- a/crates/analytics/src/lib.rs+++ b/crates/analytics/src/lib.rs@@ -35,7 +35,10 @@ pub use types::AnalyticsDomain;pub mod lambda_utils;pub mod utils;-use std::{collections::HashSet, sync::Arc};+use std::{+ collections::{HashMap, HashSet},+ sync::Arc,+};use api_models::analytics::{active_payments::{ActivePaymentsMetrics, ActivePaymentsMetricsBucketIdentifier},@@ -432,6 +435,23 @@ impl AnalyticsProvider {.await}+ pub async fn get_intent_status_with_count(+ &self,+ auth: &AuthInfo,+ time_range: &TimeRange,+ ) -> types::MetricsResult<HashMap<common_enums::IntentStatus, i64>> {+ match self {+ Self::Clickhouse(ckh_pool)+ | Self::CombinedCkh(_, ckh_pool)+ | Self::CombinedSqlx(_, ckh_pool) => {+ payment_intents::aggregate::get_intent_status_with_count(ckh_pool, auth, time_range)+ .await+ }+ Self::Sqlx(_) => Err(report!(MetricsError::NotImplemented)+ .attach_printable("ClickHouse aggregate not available: analytics source is sqlx")),+ }+ }+pub async fn get_refund_metrics(&self,metric: &RefundMetrics,@@ -1131,6 +1151,7 @@ pub enum AnalyticsFlow {GetInfo,GetPaymentMetrics,GetPaymentIntentMetrics,+ GetPaymentIntentsAggregate,GetRefundsMetrics,GetFrmMetrics,GetSdkMetrics,diff --git a/crates/analytics/src/payment_intents.rs b/crates/analytics/src/payment_intents.rsindex 809be1b20a..4e751ec1ee 100644--- a/crates/analytics/src/payment_intents.rs+++ b/crates/analytics/src/payment_intents.rs@@ -1,4 +1,5 @@pub mod accumulator;+pub mod aggregate;mod core;pub mod filters;pub mod metrics;diff --git a/crates/analytics/src/payment_intents/aggregate.rs b/crates/analytics/src/payment_intents/aggregate.rsnew file mode 100644index 0000000000..c4823308da--- /dev/null+++ b/crates/analytics/src/payment_intents/aggregate.rs@@ -0,0 +1,82 @@+use std::collections::HashMap;++use common_enums::IntentStatus;+use common_utils::{+ errors::ParsingError,+ types::{authentication::AuthInfo, TimeRange},+};+use error_stack::ResultExt;+use router_env::logger;++use crate::{+ clickhouse::ClickhouseClient,+ query::{Aggregate, QueryBuilder, QueryFilter},+ types::{AnalyticsCollection, DBEnumWrapper, MetricsError, MetricsResult},+};++#[derive(Debug, serde::Deserialize, serde::Serialize)]+pub struct IntentStatusCountRow {+ pub status: DBEnumWrapper<IntentStatus>,+ pub count: i64,+}++impl TryInto<IntentStatusCountRow> for serde_json::Value {+ type Error = error_stack::Report<ParsingError>;++ fn try_into(self) -> Result<IntentStatusCountRow, Self::Error> {+ logger::debug!("Parsing IntentStatusCountRow from {:?}", self);+ serde_json::from_value(self).change_context(ParsingError::StructParseFailure(+ "Failed to parse IntentStatusCount in clickhouse results",+ ))+ }+}++pub async fn get_intent_status_with_count(+ clickhouse_client: &ClickhouseClient,+ auth: &AuthInfo,+ time_range: &TimeRange,+) -> MetricsResult<HashMap<IntentStatus, i64>> {+ let mut query_builder =+ QueryBuilder::<ClickhouseClient>::new(AnalyticsCollection::PaymentIntent);++ query_builder+ .add_select_column("status")+ .attach_printable("Error adding select status")+ .change_context(MetricsError::QueryBuildingError)?;++ query_builder+ .add_select_column(Aggregate::<String>::Sum {+ field: "sign_flag".to_string(),+ alias: Some("count"),+ })+ .change_context(MetricsError::QueryBuildingError)?;++ auth.set_filter_clause(&mut query_builder)+ .change_context(MetricsError::QueryBuildingError)?;++ time_range+ .set_filter_clause(&mut query_builder)+ .change_context(MetricsError::QueryBuildingError)?;++ query_builder+ .add_group_by_clause("status")+ .attach_printable("Error adding group by status")+ .change_context(MetricsError::QueryBuildingError)?;++ let rows: Vec<IntentStatusCountRow> = query_builder+ .execute_query::<IntentStatusCountRow, _>(clickhouse_client)+ .await+ .change_context(MetricsError::QueryBuildingError)?+ .change_context(MetricsError::QueryExecutionFailure)?;++ let mut status_map: HashMap<IntentStatus, i64> = rows+ .into_iter()+ .map(|row| (row.status.0, row.count))+ .collect();++ for status in <IntentStatus as strum::IntoEnumIterator>::iter() {+ status_map.entry(status).or_insert(0);+ }++ Ok(status_map)+}diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rsindex b02641b016..c712c7d70a 100644--- a/crates/router/src/analytics.rs+++ b/crates/router/src/analytics.rs@@ -57,16 +57,26 @@ pub mod routes {web::scope("/v2/analytics").app_data(web::Data::new(state)).service(- web::scope("/profile").service(- web::resource("report/payments")- .route(web::post().to(generate_profile_payment_report)),- ),+ web::scope("/profile")+ .service(+ web::resource("report/payments")+ .route(web::post().to(generate_profile_payment_report)),+ )+ .service(+ web::resource("payment_intents/aggregate")+ .route(web::get().to(get_profile_payment_intent_aggregate)),+ ),).service(- web::scope("/merchant").service(- web::resource("report/payments")- .route(web::post().to(generate_merchant_payment_report)),- ),+ web::scope("/merchant")+ .service(+ web::resource("report/payments")+ .route(web::post().to(generate_merchant_payment_report)),+ )+ .service(+ web::resource("payment_intents/aggregate")+ .route(web::get().to(get_merchant_payment_intent_aggregate)),+ ),).service(web::scope("/org").service(@@ -204,6 +214,10 @@ pub mod routes {web::resource("metrics/sankey").route(web::post().to(get_merchant_sankey)),)+ .service(+ web::resource("payment_intents/aggregate")+ .route(web::get().to(get_merchant_payment_intent_aggregate)),+ ).service(web::resource("metrics/auth_events/sankey").route(web::post().to(get_merchant_auth_event_sankey)),@@ -455,6 +469,10 @@ pub mod routes {web::resource("metrics/sankey").route(web::post().to(get_profile_sankey)),)+ .service(+ web::resource("payment_intents/aggregate")+ .route(web::get().to(get_profile_payment_intent_aggregate)),+ ).service(web::resource("metrics/auth_events/sankey").route(web::post().to(get_profile_auth_event_sankey)),@@ -726,6 +744,81 @@ pub mod routes {.await}+ pub async fn get_merchant_payment_intent_aggregate(+ state: web::Data<AppState>,+ req: actix_web::HttpRequest,+ query: web::Query<TimeRange>,+ ) -> impl Responder {+ let flow = AnalyticsFlow::GetPaymentIntentsAggregate;+ let payload = query.into_inner();+ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ |state, auth: AuthenticationData, req, _| async move {+ let auth_info = auth.platform.to_merchant_level_auth_info();+ let status_with_count = state+ .pool+ .get_intent_status_with_count(&auth_info, &req)+ .await+ .change_context(AnalyticsError::UnknownError)?;+ Ok(ApplicationResponse::Json(+ api_models::payments::PaymentsAggregateResponse { status_with_count },+ ))+ },+ &auth::JWTAuth {+ permission: Permission::MerchantPaymentRead,+ allow_connected: true,+ allow_platform: false,+ },+ api_locking::LockAction::NotApplicable,+ ))+ .await+ }++ pub async fn get_profile_payment_intent_aggregate(+ state: web::Data<AppState>,+ req: actix_web::HttpRequest,+ query: web::Query<TimeRange>,+ ) -> impl Responder {+ let flow = AnalyticsFlow::GetPaymentIntentsAggregate;+ let payload = query.into_inner();+ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ |state, auth: AuthenticationData, req, _| async move {+ #[cfg(feature = "v1")]+ let profile_id = auth+ .profile+ .ok_or(report!(UserErrors::JwtProfileIdMissing))+ .change_context(AnalyticsError::AccessForbiddenError)?+ .get_id()+ .clone();+ #[cfg(feature = "v2")]+ let profile_id = auth.profile.get_id().clone();+ let auth_info = auth.platform.to_profile_level_auth_info(profile_id);+ let status_with_count = state+ .pool+ .get_intent_status_with_count(&auth_info, &req)+ .await+ .change_context(AnalyticsError::UnknownError)?;+ Ok(ApplicationResponse::Json(+ api_models::payments::PaymentsAggregateResponse { status_with_count },+ ))+ },+ &auth::JWTAuth {+ permission: Permission::ProfilePaymentRead,+ allow_connected: true,+ allow_platform: false,+ },+ api_locking::LockAction::NotApplicable,+ ))+ .await+ }+#[cfg(feature = "v1")]/// # Panics///