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): generate analytics reports on the process tracker (#14751)
Jagan402b6280127b
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.tomlindex 5b8175ac8c..3b21822ce9 100644--- a/config/deployments/env_specific.toml+++ b/config/deployments/env_specific.toml@@ -281,7 +281,8 @@ cluster_urls = ["redis.cluster.uri-2:4115",] # List of redis cluster urls-# Replica SQL data store credentials+# Replica SQL data store credentials. Process tracker reports read this database (on the scheduler+# consumer too), so point it at a read replica to keep them off the primary.[replica_database]username = "replica_user" # DB Usernamepassword = "db_pass" # DB Password. Use base-64 encoded kms encrypted value here when kms is enabled@@ -330,6 +331,19 @@ refund_function = "report_download_config_refund_function" # Config to downloapayout_function = "report_download_config_payout_function" # Config to download payout reportrelay_function = "report_download_config_relay_function" # Config to download relay reportregion = "report_download_config_region" # Region of the bucket+process_tracker_reports = [] # Reports generated by the process tracker instead of their Lambda: v1_payments, refunds, disputes, payouts, relay, authentications, v2_payments, revenue_recovery++# Used by the reports in process_tracker_reports. Reads replica_database and writes to file storage.+[report_download_config.process_tracker]+file_key_prefix = "analytics_reports" # Key prefix of report files in the file storage bucket+download_url_expiry_days = 7 # Lifetime of the emailed / webhooked download link; S3 allows at most 7+page_size = 5000 # Rows fetched per page from the replica; bounds memory (about three pages)+query_timeout_secs = 300 # Longest one page's fetch may run on the replica+email_bcc = [] # Addresses blind-copied on every report email+email_env_label = "Hyperswitch" # Environment name in the email subject, e.g. "Sandbox"++# Replaces email_bcc for the reports listed, e.g. disputes = ["[email protected]"]+[report_download_config.process_tracker.report_email_bcc][opensearch]host = "https://localhost:9200"diff --git a/crates/analytics/src/errors.rs b/crates/analytics/src/errors.rsindex 05ea711d3c..647c01a2db 100644--- a/crates/analytics/src/errors.rs+++ b/crates/analytics/src/errors.rs@@ -18,6 +18,8 @@ pub enum AnalyticsError {MissingEmail,#[error("Invalid URL scheme: {0}")]InvalidReturnUrl(String),+ #[error("Invalid report columns: {0}")]+ InvalidReportColumns(String),}impl ErrorSwitch<ApiErrorResponse> for AnalyticsError {@@ -56,6 +58,12 @@ impl ErrorSwitch<ApiErrorResponse> for AnalyticsError {format!("Invalid return URL: {invalid_url_err}"),None,)),+ Self::InvalidReportColumns(reason) => ApiErrorResponse::BadRequest(ApiError::new(+ "IR",+ 6,+ format!("Invalid report columns: {reason}"),+ None,+ )),}}}diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rsindex 2f914c07da..6cc621b51b 100644--- a/crates/analytics/src/lib.rs+++ b/crates/analytics/src/lib.rs@@ -16,6 +16,7 @@ pub mod payment_intents;pub mod payments;mod query;pub mod refunds;+pub mod reports;pub mod routing_events;pub mod sdk_events;pub mod search;@@ -1132,7 +1133,10 @@ impl Default for AnalyticsConfig {}}-#[derive(Clone, Debug, serde::Deserialize, Default, serde::Serialize)]+/// Every field is optional, so a deployment that has moved its reports off Lambda need not name+/// the functions.+#[derive(Clone, Debug, serde::Deserialize, Default)]+#[serde(default)]pub struct ReportConfig {pub payment_function: String,pub refund_function: String,@@ -1141,6 +1145,77 @@ pub struct ReportConfig {pub payout_function: String,pub relay_function: String,pub region: String,+ /// Reports generated by the process tracker rather than their Lambda, e.g. `["v1_payments"]`.+ pub process_tracker_reports: Vec<reports::ReportKind>,+ pub process_tracker: ProcessTrackerReportConfig,+}++impl ReportConfig {+ /// Whether `report` is generated by the process tracker rather than its Lambda.+ pub fn uses_process_tracker(&self, report: reports::ReportKind) -> bool {+ self.process_tracker_reports.contains(&report)+ }++ /// The Lambda generating `report` on the Lambda backend.+ pub fn lambda_function(&self, report: reports::ReportKind) -> &str {+ use reports::ReportKind;+ match report {+ ReportKind::V1Payments | ReportKind::V2Payments | ReportKind::RevenueRecovery => {+ &self.payment_function+ }+ ReportKind::Refunds => &self.refund_function,+ ReportKind::Disputes => &self.dispute_function,+ ReportKind::Payouts => &self.payout_function,+ ReportKind::Relay => &self.relay_function,+ ReportKind::Authentications => &self.authentication_function,+ }+ }+}++/// Settings for reports generated by the process tracker.+#[derive(Clone, Debug, serde::Deserialize)]+#[serde(default)]+pub struct ProcessTrackerReportConfig {+ /// Prefix of the report files' keys in the file storage bucket.+ pub file_key_prefix: String,+ /// Lifetime of the download link sent by webhook or email. S3 caps presigned URLs at 7 days,+ /// and at the signing credentials' own lifetime when those are temporary.+ pub download_url_expiry_days: u32,+ /// Rows fetched per page from the report's cursor; with the page being written and the one+ /// queued, at most three pages are in memory however large the report.+ pub page_size: usize,+ /// Longest one page's fetch may run on the replica, in seconds.+ pub query_timeout_secs: u64,+ /// Blind-copied on every report email.+ pub email_bcc: Vec<common_utils::pii::Email>,+ /// Replaces `email_bcc` for the reports it lists, as each Lambda had its own BCC list, e.g.+ /// `disputes = ["[email protected]"]`.+ pub report_email_bcc: HashMap<reports::ReportKind, Vec<common_utils::pii::Email>>,+ /// Names the environment in the email subject, as `REPORT_ENV_LABEL` did for the Lambda.+ pub email_env_label: String,+}++impl ProcessTrackerReportConfig {+ /// The addresses blind-copied on `report`'s emails.+ pub fn email_bcc(&self, report: reports::ReportKind) -> &[common_utils::pii::Email] {+ self.report_email_bcc+ .get(&report)+ .unwrap_or(&self.email_bcc)+ }+}++impl Default for ProcessTrackerReportConfig {+ fn default() -> Self {+ Self {+ file_key_prefix: "analytics_reports".to_owned(),+ download_url_expiry_days: 7,+ page_size: 5_000,+ query_timeout_secs: 300,+ email_bcc: Vec::new(),+ report_email_bcc: HashMap::new(),+ email_env_label: "Hyperswitch".to_owned(),+ }+ }}/// Analytics Flow routes Enumsdiff --git a/crates/analytics/src/reports.rs b/crates/analytics/src/reports.rsnew file mode 100644index 0000000000..3d732e6e53--- /dev/null+++ b/crates/analytics/src/reports.rs@@ -0,0 +1,548 @@+//! Reports replacing the reporting Lambdas.+//!+//! A report is a [`ReportDefinition`]: where its rows come from and the SQL rendering each column+//! as text. [`ReportKind::query`] builds any definition's query, which the store runs on the read+//! replica. Postgres renders the values, so the CSV carries+//! standard ones: JSON as JSON, booleans as `true`/`false`, timestamps as ISO 8601 UTC with+//! milliseconds (the format API responses use) and amounts as exact decimals.++mod definitions;++use std::fmt::Write as _;++use api_models::analytics::{GenerateReportRequest, ReportColumns};+use common_utils::errors::CustomResult;++use crate::{enums::AuthInfo, errors::AnalyticsError, AnalyticsFlow};++/// Where a report's rows come from and the columns written for each.+#[derive(Debug)]+pub struct ReportDefinition {+ /// Names the report in file keys and file names, e.g. `v1_payments`.+ pub name: &'static str,+ /// `data.report_type` in the report webhook, e.g. `payment_report`.+ pub webhook_type: &'static str,+ /// Names the report in the email's subject and link, e.g. `Refunds`.+ pub title: &'static str,+ /// The report, as the email's body names it: "the `refund` report".+ pub noun: &'static str,+ /// The rows, as the email's body describes them: "an overview of `refunds made by your+ /// customers` via Hyperswitch".+ pub covers: &'static str,+ /// The `FROM` clause, joins included.+ from: &'static str,+ /// The alias whose `organization_id`, `merchant_id`, `processor_merchant_id`, `profile_id`+ /// and `created_at` scope the rows.+ table: &'static str,+ /// Whether `table` has an `organization_id` column; `relay` does not.+ organization_scoped: bool,+ columns: &'static [Column],+}++/// One CSV column, rendered to text by Postgres. `NULL` becomes an empty field.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Column {+ /// A column cast to text, headed by its name: `ref.refund_id` heads `refund_id`.+ Text(&'static str),+ /// A timestamp column, as ISO 8601 UTC with milliseconds.+ Time(&'static str),+ /// Any other expression, with its header.+ Expr(&'static str, &'static str),+}++impl Column {+ fn header(self) -> &'static str {+ match self {+ Self::Text(column) | Self::Time(column) => {+ column.rsplit_once('.').map_or(column, |(_, name)| name)+ }+ Self::Expr(header, _) => header,+ }+ }++ fn sql(self) -> String {+ match self {+ Self::Text(column) => format!("{column}::text"),+ // TIMESTAMP_FORMAT for `to_char`, so CSV cells match the webhook and email.+ Self::Time(column) => format!("to_char({column}, 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"),+ Self::Expr(_, expression) => expression.to_owned(),+ }+ }+}++/// The reports that can be generated.+#[derive(+ Clone,+ Copy,+ Debug,+ PartialEq,+ Eq,+ Hash,+ serde::Serialize,+ serde::Deserialize,+ strum::Display,+ strum::EnumIter,+)]+#[strum(serialize_all = "snake_case")]+#[serde(rename_all = "snake_case")]+pub enum ReportKind {+ V1Payments,+ Refunds,+ Disputes,+ Payouts,+ Relay,+ Authentications,+ V2Payments,+ RevenueRecovery,+}++impl ReportKind {+ pub fn definition(self) -> &'static ReportDefinition {+ match self {+ Self::V1Payments => &definitions::V1_PAYMENTS,+ Self::Refunds => &definitions::REFUNDS,+ Self::Disputes => &definitions::DISPUTES,+ Self::Payouts => &definitions::PAYOUTS,+ Self::Relay => &definitions::RELAY,+ Self::Authentications => &definitions::AUTHENTICATIONS,+ Self::V2Payments => &definitions::V2_PAYMENTS,+ Self::RevenueRecovery => &definitions::REVENUE_RECOVERY,+ }+ }++ /// The report `request` asks for from `self`'s routes: on v2 the payment routes serve the+ /// report its `report_type` names, as the payment Lambda did.+ pub fn requested_by(self, request: &api_models::analytics::ReportRequest) -> Self {+ #[cfg(feature = "v2")]+ if self == Self::V1Payments {+ use api_models::analytics::ReportType;+ return match request.report_type {+ ReportType::V2Payments => Self::V2Payments,+ ReportType::RevenueRecovery => Self::RevenueRecovery,+ };+ }+ let _ = request;+ self+ }++ /// The flow the report's API requests are logged under.+ pub fn flow(self) -> AnalyticsFlow {+ match self {+ Self::V1Payments | Self::V2Payments | Self::RevenueRecovery => {+ AnalyticsFlow::GeneratePaymentReport+ }+ Self::Refunds => AnalyticsFlow::GenerateRefundReport,+ Self::Disputes => AnalyticsFlow::GenerateDisputeReport,+ Self::Payouts => AnalyticsFlow::GeneratePayoutReport,+ Self::Relay => AnalyticsFlow::GenerateRelayReport,+ Self::Authentications => AnalyticsFlow::GenerateAuthenticationReport,+ }+ }++ /// The columns `requested` selects, in its order and each once; every column when it names+ /// none. Rejects an empty list, names the report does not define, and choices for a report+ /// whose columns cannot be chosen.+ fn columns(+ self,+ requested: Option<&ReportColumns>,+ ) -> CustomResult<Vec<Column>, AnalyticsError> {+ let invalid =+ |reason: String| error_stack::report!(AnalyticsError::InvalidReportColumns(reason));+ let definition = self.definition();+ let names: Vec<&str> = match (self, requested) {+ (_, None) => return Ok(definition.columns.to_vec()),+ (Self::V1Payments, Some(ReportColumns::Payment(columns))) => {+ columns.iter().map(AsRef::as_ref).collect()+ }+ (_, Some(_)) => {+ return Err(invalid(format!(+ "columns cannot be chosen for the {} report",+ definition.name+ )))+ }+ };+ if names.is_empty() {+ return Err(invalid("at least one column must be requested".to_owned()));+ }++ let mut selected = Vec::with_capacity(names.len());+ for name in names {+ let column = definition+ .columns+ .iter()+ .copied()+ .find(|column| column.header() == name)+ .ok_or_else(|| {+ invalid(format!(+ "`{name}` is not a column of the {} report",+ definition.name+ ))+ })?;+ if !selected.contains(&column) {+ selected.push(column);+ }+ }+ Ok(selected)+ }++ /// Checks the request's column choice, so a bad one is rejected when the report is requested.+ pub fn validate_columns(+ self,+ request: &GenerateReportRequest,+ ) -> CustomResult<(), AnalyticsError> {+ self.columns(request.request.columns.as_ref()).map(|_| ())+ }+}++/// The format of every timestamp in a report: ISO 8601 UTC with milliseconds.+const TIMESTAMP_FORMAT: &[time::format_description::FormatItem<'static>] = time::macros::format_description!(+ "[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:3]Z"+);++/// An amount in major units as an exact decimal carrying its currency's places (`65.00`, `4.074`,+/// `2537`). The exponent table is the Lambdas' own.+macro_rules! major_units {+ ($amount:literal, $currency:literal) => {+ concat!(+ "(CASE WHEN ", $currency, " IN ('BHD','IQD','JOD','KWD','LYD','OMR','TND') THEN round(",+ $amount,+ "::numeric / 1000, 3) WHEN ", $currency, " IN ('BIF','CLP','DJF','GNF','JPY','KMF','KRW','MGA','PYG','RWF','UGX','VND','VUV','XAF','XOF','XPF') THEN ",+ $amount,+ "::numeric ELSE round(",+ $amount,+ "::numeric / 100, 2) END)::text"+ )+ };+}+pub(crate) use major_units;++/// Formats a timestamp as the report's CSV cells do.+pub fn format_timestamp(value: time::PrimitiveDateTime) -> String {+ value+ .format(TIMESTAMP_FORMAT)+ .unwrap_or_else(|_| value.to_string())+}++/// A value bound to one of a report query's `$n` placeholders.+#[derive(Clone, Debug)]+pub enum ReportBind {+ Text(String),+ Texts(Vec<String>),+ Timestamp(time::PrimitiveDateTime),+}++/// A report's query and the CSV header for it. Each row has one column, `cells`: the requested+/// columns as `text[]`, in header order.+#[derive(Clone, Debug)]+pub struct ReportQuery {+ pub sql: String,+ pub binds: Vec<ReportBind>,+ pub header: Vec<u8>,+}++impl ReportQuery {+ fn bind(&mut self, value: ReportBind) -> String {+ self.binds.push(value);+ format!("${}", self.binds.len())+ }+}++impl ReportKind {+ /// The query for the requested columns of the rows `request.auth` may see, created within+ /// its time range (inclusive at both ends, as the Lambda was), oldest first.+ pub fn query(+ self,+ request: &GenerateReportRequest,+ ) -> CustomResult<ReportQuery, AnalyticsError> {+ let definition = self.definition();+ let columns = self.columns(request.request.columns.as_ref())?;+ let table = definition.table;+ let time_range = request.request.time_range;++ let cells = columns+ .iter()+ .map(|column| column.sql())+ .collect::<Vec<_>>()+ .join(", ");+ let mut query = ReportQuery {+ sql: format!(+ "SELECT ARRAY[{cells}]::text[] AS cells FROM {} WHERE TRUE",+ definition.from+ ),+ binds: Vec::new(),+ header: csv_record(columns.iter().map(|column| column.header())),+ };+ push_scope(&mut query, definition, &request.auth);+ let start = query.bind(ReportBind::Timestamp(time_range.start_time));+ let end = query.bind(ReportBind::Timestamp(+ time_range+ .end_time+ .unwrap_or_else(common_utils::date_time::now),+ ));+ let _ = write!(+ query.sql,+ " AND {table}.created_at >= {start} AND {table}.created_at <= {end} \+ ORDER BY {table}.created_at"+ );+ Ok(query)+ }+}++/// The same scope the analytics query builder applies for `auth`. The Lambda ignored+/// `processor_merchant_id`, so a connected merchant received its platform's other rows.+fn push_scope(query: &mut ReportQuery, report: &ReportDefinition, auth: &AuthInfo) {+ let strings = |ids: &[common_utils::id_type::MerchantId]| {+ ids.iter()+ .map(|id| id.get_string_repr().to_owned())+ .collect::<Vec<_>>()+ };+ let (org_id, merchant_ids, processor_merchant_ids, profile_ids) = match auth {+ AuthInfo::OrgLevel { org_id } => (org_id, None, None, None),+ AuthInfo::MerchantLevel {+ org_id,+ merchant_ids,+ processor_merchant_ids,+ } => (+ org_id,+ Some(strings(merchant_ids)),+ processor_merchant_ids.as_deref().map(strings),+ None,+ ),+ AuthInfo::ProfileLevel {+ org_id,+ merchant_id,+ profile_ids,+ processor_merchant_id,+ } => (+ org_id,+ Some(strings(std::slice::from_ref(merchant_id))),+ processor_merchant_id+ .as_ref()+ .map(|id| strings(std::slice::from_ref(id))),+ Some(+ profile_ids+ .iter()+ .map(|id| id.get_string_repr().to_owned())+ .collect(),+ ),+ ),+ };++ let table = report.table;+ if report.organization_scoped {+ let org_id = query.bind(ReportBind::Text(org_id.get_string_repr().to_owned()));+ let _ = write!(query.sql, " AND {table}.organization_id = {org_id}");+ }+ for (column, values) in [+ ("merchant_id", merchant_ids),+ ("processor_merchant_id", processor_merchant_ids),+ ("profile_id", profile_ids),+ ] {+ if let Some(values) = values {+ let values = query.bind(ReportBind::Texts(values));+ let _ = write!(query.sql, " AND {table}.{column} = ANY({values})");+ }+ }+}++/// One RFC 4180 record: every field quoted, quotes doubled, CRLF line ending.+pub fn csv_record<S: AsRef<str>>(fields: impl IntoIterator<Item = S>) -> Vec<u8> {+ let mut out = Vec::new();+ for (index, field) in fields.into_iter().enumerate() {+ if index > 0 {+ out.push(b',');+ }+ out.push(b'"');+ out.extend_from_slice(field.as_ref().replace('"', "\"\"").as_bytes());+ out.push(b'"');+ }+ out.extend_from_slice(b"\r\n");+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn csv_record_quotes_every_field() {+ assert_eq!(+ csv_record(["", "a\"b", "x\ny", "true", "1.50"]),+ b"\"\",\"a\"\"b\",\"x\ny\",\"true\",\"1.50\"\r\n"+ );+ }++ #[test]+ fn timestamps_use_the_api_format() {+ assert_eq!(+ format_timestamp(time::macros::datetime!(2026-10-12 09:10:07.215205)),+ "2026-10-12T09:10:07.215Z"+ );+ }++ #[test]+ fn requested_columns_are_selected_in_order() {+ use api_models::analytics::payments::PaymentReportColumn as PaymentColumn;++ let headers = |requested: Option<ReportColumns>| {+ ReportKind::V1Payments+ .columns(requested.as_ref())+ .map(|columns| columns.iter().map(|c| c.header()).collect::<Vec<_>>())+ };++ assert_eq!(+ headers(None).ok().map(|all| all.len()),+ Some(definitions::V1_PAYMENTS.columns.len())+ );+ assert_eq!(+ headers(Some(ReportColumns::Payment(vec![+ PaymentColumn::Amount,+ PaymentColumn::PaymentId,+ PaymentColumn::Amount,+ ])))+ .ok(),+ Some(vec!["amount", "payment_id"])+ );+ assert!(headers(Some(ReportColumns::Payment(Vec::new()))).is_err());+ }++ #[test]+ fn every_payment_report_column_can_be_requested() {+ use api_models::analytics::payments::PaymentReportColumn;+ use strum::IntoEnumIterator;++ let all = PaymentReportColumn::iter().collect::<Vec<_>>();+ let selected = ReportKind::V1Payments.columns(Some(&ReportColumns::Payment(all.clone())));+ assert_eq!(selected.map(|columns| columns.len()).ok(), Some(all.len()));+ }++ #[test]+ #[allow(clippy::unwrap_used)]+ fn query_binds_scope_and_range_for_a_profile() {+ use std::borrow::Cow;++ use api_models::analytics::{+ payments::PaymentReportColumn as PaymentColumn, ReportRequest,+ };+ use common_utils::id_type;++ let request = GenerateReportRequest {+ request: ReportRequest {+ time_range: common_utils::types::TimeRange {+ start_time: time::macros::datetime!(2026-10-01 00:00:00),+ end_time: Some(time::macros::datetime!(2026-10-07 00:00:00)),+ },+ emails: None,+ return_url: None,+ #[cfg(feature = "v2")]+ report_type: Default::default(),+ columns: Some(ReportColumns::Payment(vec![+ PaymentColumn::PaymentId,+ PaymentColumn::Amount,+ ])),+ },+ merchant_id: None,+ auth: AuthInfo::ProfileLevel {+ org_id: id_type::OrganizationId::try_from(Cow::from("org_1")).unwrap(),+ merchant_id: id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(),+ profile_ids: vec![id_type::ProfileId::try_from(Cow::from("pro_1")).unwrap()],+ processor_merchant_id: None,+ },+ email: common_utils::pii::Email::try_from("[email protected]".to_owned()).unwrap(),+ payment_response_hash_key: None,+ };++ let query = ReportKind::V1Payments.query(&request).unwrap();+ assert!(query+ .sql+ .starts_with("SELECT ARRAY[pi.payment_id::text, (CASE WHEN"));+ assert!(query.sql.ends_with(+ " AND pa.organization_id = $1 AND pa.merchant_id = ANY($2) \+ AND pa.profile_id = ANY($3) AND pa.created_at >= $4 AND pa.created_at <= $5 \+ ORDER BY pa.created_at"+ ));+ assert_eq!(query.binds.len(), 5);+ assert_eq!(query.header, b"\"payment_id\",\"amount\"\r\n");+ }++ #[test]+ fn every_report_has_unique_headers() {+ use strum::IntoEnumIterator;++ for report in ReportKind::iter() {+ let headers = report+ .definition()+ .columns+ .iter()+ .map(|c| c.header())+ .collect::<Vec<_>>();+ let unique = headers.iter().collect::<std::collections::HashSet<_>>();+ assert_eq!(unique.len(), headers.len(), "{report:?}");+ }+ // The Lambdas' column counts.+ let counts = ReportKind::iter()+ .map(|report| report.definition().columns.len())+ .collect::<Vec<_>>();+ assert_eq!(counts, [35, 23, 16, 33, 13, 35, 31, 27]);+ }++ #[test]+ fn v2_payment_report_headers_match_lambda() {+ // BASE_CSV_COLUMNS and V2_PAYMENTS_EXTRA_CSV_COLUMNS from+ // weekly_payment_report_generator_step_1.+ let base = concat!(+ r#""id","attempt_id","status","amount","currency","connector","connector_payment_id","#,+ r#""amount_to_capture","customer_id","created_at","order_details","error_message","#,+ r#""capture_method","authentication_type","payment_method_type_v2","#,+ r#""payment_method_subtype","metadata","setup_future_usage","statement_descriptor","#,+ r#""description","payment_method_data","card_network","modified_at","error_code","#,+ r#""payment_method_id","merchant_reference_id","profile_id""#,+ );+ let header = |definition: &ReportDefinition| {+ String::from_utf8_lossy(&csv_record(definition.columns.iter().map(|c| c.header())))+ .into_owned()+ };+ assert_eq!(+ header(&definitions::REVENUE_RECOVERY),+ format!("{base}\r\n")+ );+ assert_eq!(+ header(&definitions::V2_PAYMENTS),+ format!(+ "{base},\"mandate_id\",\"allowed_payment_method_types\",\"fingerprint_id\",\"card_holder_name\"\r\n"+ )+ );+ }++ #[test]+ fn columns_are_chosen_only_for_payments() {+ let choice = ReportColumns::Payment(vec![+ api_models::analytics::payments::PaymentReportColumn::Amount,+ ]);+ assert!(ReportKind::V1Payments.columns(Some(&choice)).is_ok());+ assert!(ReportKind::Refunds.columns(Some(&choice)).is_err());+ assert_eq!(+ ReportKind::Refunds.columns(None).map(|c| c.len()).ok(),+ Some(definitions::REFUNDS.columns.len())+ );+ }++ #[test]+ fn payment_report_header_matches_lambda() {+ // V1_PAYMENTS_CSV_COLUMNS from weekly_payment_report_generator_step_1.+ let expected = concat!(+ r#""payment_id","attempt_id","status","amount","currency","connector","#,+ r#""connector_transaction_id","amount_to_capture","customer_id","created_at","#,+ r#""order_details","error_message","capture_method","authentication_type","#,+ r#""mandate_id","payment_method","payment_method_type","metadata","#,+ r#""setup_future_usage","statement_descriptor_name","description","off_session","#,+ r#""business_country","business_label","business_sub_label","#,+ r#""allowed_payment_method_types","payment_method_data","card_network","#,+ r#""fingerprint_id","modified_at","error_code","payment_method_id","#,+ r#""card_holder_name","merchant_order_reference_id","profile_id""#,+ "\r\n"+ );+ let header = csv_record(definitions::V1_PAYMENTS.columns.iter().map(|c| c.header()));+ assert_eq!(String::from_utf8_lossy(&header), expected);+ }+}diff --git a/crates/analytics/src/reports/definitions.rs b/crates/analytics/src/reports/definitions.rsnew file mode 100644index 0000000000..b2fe77d9ea--- /dev/null+++ b/crates/analytics/src/reports/definitions.rs@@ -0,0 +1,349 @@+//! The reports ported from the `weekly_*_report_generator_step_1` Lambdas: their headers, column+//! order and rows, with standard values. Amounts are written as the Lambdas did: payments and+//! payouts in major units, refunds and disputes as stored. The email wording is each Lambda's.++use super::{+ major_units,+ Column::{Expr, Text, Time},+ ReportDefinition,+};++/// Every attempt, with its payment's details when it is the payment's active attempt. The Lambda+/// joined on `active_attempt_id` alone; also matching the merchant and payment keeps the join on+/// the intent's primary key.+pub(super) const V1_PAYMENTS: ReportDefinition = ReportDefinition {+ name: "v1_payments",+ webhook_type: "payment_report",+ title: "Payments",+ noun: "payments",+ covers: "payments processed",+ from: "payment_attempt AS pa LEFT JOIN payment_intent AS pi \+ ON pi.merchant_id = pa.merchant_id \+ AND pi.payment_id = pa.payment_id \+ AND pi.active_attempt_id = pa.attempt_id",+ table: "pa",+ organization_scoped: true,+ columns: &[+ Text("pi.payment_id"),+ Text("pa.attempt_id"),+ Text("pa.status"),+ Expr("amount", major_units!("pi.amount", "pi.currency")),+ Text("pi.currency"),+ Text("pa.connector"),+ Text("pa.connector_transaction_id"),+ Expr(+ "amount_to_capture",+ major_units!("pa.amount_to_capture", "pi.currency"),+ ),+ Text("pi.customer_id"),+ Time("pa.created_at"),+ Expr("order_details", "to_jsonb(pi.order_details)::text"),+ Text("pa.error_message"),+ Text("pa.capture_method"),+ Text("pa.authentication_type"),+ Text("pa.mandate_id"),+ Text("pa.payment_method"),+ Text("pa.payment_method_type"),+ Text("pi.metadata"),+ Text("pi.setup_future_usage"),+ Text("pi.statement_descriptor_name"),+ Text("pi.description"),+ Text("pi.off_session"),+ Text("pi.business_country"),+ Text("pi.business_label"),+ Text("pa.business_sub_label"),+ Expr(+ "allowed_payment_method_types",+ "pi.allowed_payment_method_types::jsonb::text",+ ),+ Text("pa.payment_method_data"),+ Expr(+ "card_network",+ "pa.payment_method_data->'card'->>'card_network'",+ ),+ Text("pi.fingerprint_id"),+ Time("pa.modified_at"),+ Text("pa.error_code"),+ Text("pa.payment_method_id"),+ Expr(+ "card_holder_name",+ "pa.payment_method_data->'card'->>'card_holder_name'",+ ),+ Text("pi.merchant_order_reference_id"),+ Text("pi.profile_id"),+ ],+};++pub(super) const REFUNDS: ReportDefinition = ReportDefinition {+ name: "refunds",+ webhook_type: "refund_report",+ title: "Refunds",+ noun: "refund",+ covers: "refunds made by your customers",+ from: "refund AS ref",+ table: "ref",+ organization_scoped: true,+ columns: &[+ Text("ref.internal_reference_id"),+ Text("ref.refund_id"),+ Text("ref.payment_id"),+ Text("ref.merchant_id"),+ Text("ref.connector_transaction_id"),+ Text("ref.connector"),+ Text("ref.total_amount"),+ Text("ref.currency"),+ Text("ref.refund_amount"),+ Text("ref.refund_status"),+ Text("ref.connector_refund_id"),+ Text("ref.external_reference_id"),+ Text("ref.refund_reason"),+ Text("ref.refund_type"),+ Text("ref.sent_to_gateway"),+ Text("ref.refund_error_message"),+ Text("ref.metadata"),+ Time("ref.created_at"),+ Time("ref.modified_at"),+ Text("ref.description"),+ Text("ref.attempt_id"),+ Text("ref.refund_error_code"),+ Text("ref.profile_id"),+ ],+};++/// The Lambda filtered disputes by merchant alone, so profile reports carried the merchant's other+/// profiles and organization reports were empty; the shared scope fixes both.+pub(super) const DISPUTES: ReportDefinition = ReportDefinition {+ name: "disputes",+ webhook_type: "dispute_report",+ title: "Disputes",+ noun: "dispute",+ covers: "disputes made by your customers",+ from: "dispute",+ table: "dispute",+ organization_scoped: true,+ columns: &[+ // Dropped by the 2025-02-06-111828 migration removing the int `id` columns, which left the+ // Lambda's query failing; kept empty so the columns stay where they were.+ Expr("id", "NULL::text"),+ Text("dispute.dispute_id"),+ Text("dispute.payment_id"),+ Text("dispute.connector_dispute_id"),+ Text("dispute.connector"),+ Text("dispute.amount"),+ Text("dispute.currency"),+ Text("dispute.dispute_stage"),+ Text("dispute.dispute_status"),+ Text("dispute.connector_status"),+ Text("dispute.connector_reason"),+ Text("dispute.connector_reason_code"),+ Time("dispute.created_at"),+ Time("dispute.modified_at"),+ Time("dispute.challenge_required_by"),+ Text("dispute.evidence"),+ ],+};++/// One row per payout attempt. Matching the merchant as well keeps the join to one payout.+pub(super) const PAYOUTS: ReportDefinition = ReportDefinition {+ name: "payouts",+ webhook_type: "payout_report",+ title: "Payouts",+ noun: "payout",+ covers: "payouts made by your customers",+ from: "payouts AS p LEFT JOIN payout_attempt AS pa \+ ON pa.merchant_id = p.merchant_id AND pa.payout_id = p.payout_id",+ table: "p",+ organization_scoped: true,+ columns: &[+ Text("p.payout_id"),+ Text("pa.payout_attempt_id"),+ Text("p.payout_link_id"),+ Text("pa.merchant_order_reference_id"),+ Text("pa.connector_payout_id"),+ Text("pa.status"),+ Expr("amount", major_units!("p.amount", "p.destination_currency")),+ Expr("currency", "p.destination_currency::text"),+ Text("p.payout_type"),+ Text("p.confirm"),+ Text("p.attempt_count"),+ Text("pa.is_eligible"),+ Text("pa.connector"),+ Text("p.payout_method_id"),+ Text("p.profile_id"),+ Text("p.merchant_id"),+ Text("p.organization_id"),+ Text("p.customer_id"),+ Text("p.recurring"),+ Text("p.auto_fulfill"),+ Text("p.priority"),+ Text("p.description"),+ Text("pa.error_code"),+ Text("pa.error_message"),+ Text("pa.unified_code"),+ Text("pa.unified_message"),+ Text("pa.business_country"),+ Text("pa.business_label"),+ Text("p.entity_type"),+ Time("p.created_at"),+ Time("p.last_modified_at"),+ Text("pa.additional_payout_method_data"),+ Text("p.metadata"),+ ],+};++/// `relay` has no `organization_id`, so it is scoped by merchant and profile only.+pub(super) const RELAY: ReportDefinition = ReportDefinition {+ name: "relay",+ webhook_type: "relay_report",+ title: "Relay",+ noun: "relay",+ covers: "relay requests made by your customers",+ from: "relay",+ table: "relay",+ organization_scoped: false,+ columns: &[+ Text("relay.id"),+ Text("relay.profile_id"),+ Text("relay.connector_id"),+ Text("relay.relay_type"),+ Text("relay.connector_resource_id"),+ Text("relay.request_data"),+ Text("relay.status"),+ Text("relay.connector_reference_id"),+ Text("relay.error_code"),+ Text("relay.error_message"),+ Text("relay.response_data"),+ Time("relay.created_at"),+ Time("relay.modified_at"),+ ],+};++pub(super) const AUTHENTICATIONS: ReportDefinition = ReportDefinition {+ name: "authentication",+ webhook_type: "authentication_report",+ title: "Authentication",+ noun: "authentication",+ covers: "authentications made by your customers",+ from: "authentication",+ table: "authentication",+ organization_scoped: true,+ columns: &[+ Text("authentication.authentication_id"),+ Text("authentication.merchant_id"),+ Text("authentication.authentication_connector"),+ Text("authentication.connector_authentication_id"),+ Text("authentication.authentication_data"),+ Text("authentication.payment_method_id"),+ Text("authentication.authentication_type"),+ Text("authentication.authentication_status"),+ Text("authentication.authentication_lifecycle_status"),+ Time("authentication.created_at"),+ Time("authentication.modified_at"),+ Text("authentication.error_message"),+ Text("authentication.error_code"),+ Text("authentication.connector_metadata"),+ Text("authentication.maximum_supported_version"),+ Text("authentication.threeds_server_transaction_id"),+ Text("authentication.authentication_flow_type"),+ Text("authentication.message_version"),+ Text("authentication.eci"),+ Text("authentication.trans_status"),+ Text("authentication.acquirer_bin"),+ Text("authentication.acquirer_merchant_id"),+ Text("authentication.three_ds_method_url"),+ Text("authentication.acs_url"),+ Text("authentication.acs_reference_number"),+ Text("authentication.acs_trans_id"),+ // Dropped by 2024-05-08-111348_delete_unused_column_from_authentication, which left the+ // Lambda's query failing; kept empty so the columns stay where they were.+ Expr("three_dsserver_trans_id", "NULL::text"),+ Text("authentication.profile_id"),+ Text("authentication.payment_id"),+ Text("authentication.merchant_connector_id"),+ Text("authentication.directory_server_id"),+ Text("authentication.ds_trans_id"),+ Text("authentication.acquirer_country_code"),+ Text("authentication.service_details"),+ Text("authentication.organization_id"),+ ],+};++/// `v2_payments` and `revenue_recovery` read v2's tables: every attempt, with its payment, scoped+/// and ordered by the payment.+const V2_PAYMENTS_FROM: &str =+ "payment_attempt AS pa INNER JOIN payment_intent AS pi ON pi.id = pa.payment_id";++macro_rules! v2_payment_columns {+ ($($extra:expr),* $(,)?) => {+ &[+ Text("pi.id"),+ Expr("attempt_id", "pa.id::text"),+ Text("pa.status"),+ Expr("amount", major_units!("pi.amount", "pi.currency")),+ Text("pi.currency"),+ Text("pa.connector"),+ Text("pa.connector_payment_id"),+ Expr(+ "amount_to_capture",+ major_units!("pa.amount_to_capture", "pi.currency"),+ ),+ Text("pi.customer_id"),+ Time("pi.created_at"),+ Expr("order_details", "to_jsonb(pi.order_details)::text"),+ Text("pa.error_message"),+ Text("pi.capture_method"),+ Text("pa.authentication_type"),+ Text("pa.payment_method_type_v2"),+ Text("pa.payment_method_subtype"),+ Text("pi.metadata"),+ Text("pi.setup_future_usage"),+ Text("pi.statement_descriptor"),+ Text("pi.description"),+ Text("pa.payment_method_data"),+ Text("pa.card_network"),+ Time("pi.modified_at"),+ Text("pa.error_code"),+ Text("pa.payment_method_id"),+ Text("pi.merchant_reference_id"),+ Text("pi.profile_id"),+ $($extra,)*+ ]+ };+}++pub(super) const V2_PAYMENTS: ReportDefinition = ReportDefinition {+ name: "v2_payments",+ webhook_type: "payment_report",+ title: "Payments",+ noun: "payments",+ covers: "payments processed",+ from: V2_PAYMENTS_FROM,+ table: "pi",+ organization_scoped: true,+ columns: v2_payment_columns![+ // v2's payment_attempt has no mandate_id, which left the Lambda's query failing; kept empty+ // so the column stays where it was.+ Expr("mandate_id", "NULL::text"),+ Expr(+ "allowed_payment_method_types",+ "pi.allowed_payment_method_types::jsonb::text",+ ),+ Text("pa.fingerprint_id"),+ Expr(+ "card_holder_name",+ "pa.payment_method_data->'card'->>'card_holder_name'",+ ),+ ],+};++pub(super) const REVENUE_RECOVERY: ReportDefinition = ReportDefinition {+ name: "revenue_recovery",+ webhook_type: "payment_report",+ title: "Revenue Recovery",+ noun: "revenue recovery transactions",+ covers: "revenue recovery transactions processed",+ from: V2_PAYMENTS_FROM,+ table: "pi",+ organization_scoped: true,+ columns: v2_payment_columns![],+};diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 217ad5b085..49fc7fb1e1 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -11885,6 +11885,7 @@ pub enum ProcessTrackerRunner {OfferEngineNotifyWorkflow,BlocklistExportWorkflow,BlocklistProfileCloneWorkflow,+ AnalyticsReportWorkflow,}#[derive(diff --git a/crates/external_services/src/file_storage.rs b/crates/external_services/src/file_storage.rsindex 952020f4f1..1b2d5c4836 100644--- a/crates/external_services/src/file_storage.rs+++ b/crates/external_services/src/file_storage.rs@@ -124,6 +124,79 @@ pub trait FileStorageInterface: dyn_clone::DynClone + Sync + Send {dyn_clone::clone_trait_object!(FileStorageInterface);+/// Writes a file of unknown size as a multipart upload, buffering writes into parts of the 5 MB+/// minimum every part but the last must reach.+#[allow(missing_debug_implementations)]+pub struct MultipartUpload<'a> {+ client: &'a dyn FileStorageInterface,+ file_key: &'a str,+ upload_id: String,+ buffer: Vec<u8>,+ parts: Vec<(i32, String)>,+}++impl<'a> MultipartUpload<'a> {+ /// The minimum size of every part but the last.+ pub const PART_SIZE: usize = 5 * 1024 * 1024;++ /// Begins an upload to `file_key`.+ pub async fn start(+ client: &'a dyn FileStorageInterface,+ file_key: &'a str,+ ) -> CustomResult<Self, FileStorageError> {+ Ok(Self {+ client,+ file_key,+ upload_id: client.create_multipart_upload(file_key).await?,+ buffer: Vec::with_capacity(Self::PART_SIZE),+ parts: Vec::new(),+ })+ }++ /// Appends `bytes`, uploading a part once the buffer reaches `PART_SIZE`.+ pub async fn write(&mut self, bytes: &[u8]) -> CustomResult<(), FileStorageError> {+ self.buffer.extend_from_slice(bytes);+ if self.buffer.len() >= Self::PART_SIZE {+ self.upload_buffer().await?;+ }+ Ok(())+ }++ /// Uploads what remains and assembles the file, returning the backend's expiry description+ /// when a lifecycle rule applies.+ pub async fn finish(mut self) -> CustomResult<Option<String>, FileStorageError> {+ if !self.buffer.is_empty() || self.parts.is_empty() {+ self.upload_buffer().await?;+ }+ self.client+ .complete_multipart_upload(self.file_key, &self.upload_id, self.parts)+ .await+ }++ /// Discards the upload, so its parts stop being billed.+ pub async fn abort(self) -> CustomResult<(), FileStorageError> {+ self.client+ .abort_multipart_upload(self.file_key, &self.upload_id)+ .await+ }++ async fn upload_buffer(&mut self) -> CustomResult<(), FileStorageError> {+ let part_number = i32::try_from(self.parts.len() + 1)+ .map_err(|_| error_stack::report!(FileStorageError::MultipartUploadPartFailed))?;+ let e_tag = self+ .client+ .upload_part(+ self.file_key,+ &self.upload_id,+ part_number,+ std::mem::take(&mut self.buffer),+ )+ .await?;+ self.parts.push((part_number, e_tag));+ Ok(())+ }+}+/// Error thrown when the file storage config is invalid#[derive(Debug, Clone, thiserror::Error)]pub enum InvalidFileStorageConfig {diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rsindex 7d395867fa..8223f53cc8 100644--- a/crates/router/src/analytics.rs+++ b/crates/router/src/analytics.rs@@ -12,9 +12,9 @@ pub mod routes {connector_events::{connector_events_core, ConnectorEventSource},enums::AuthInfo,errors::AnalyticsError,- lambda_utils::invoke_lambda,opensearch::OpenSearchError,outgoing_webhook_event::outgoing_webhook_events_core,+ reports::ReportKind,routing_events::routing_events_core,sdk_events::sdk_events_core,AnalyticsFlow,@@ -44,7 +44,7 @@ pub mod routes {consts::opensearch::SEARCH_INDEXES,core::{api_locking, errors::user::UserErrors, verification::utils},db::user_role::ListUserRolesByUserIdPayload,- routes::{metrics, AppState},+ routes::{metrics, AppState, SessionState},services::{api,authentication::{self as auth, AuthenticationData, UserFromToken},@@ -1878,1533 +1878,144 @@ pub mod routes {.await}- #[cfg(feature = "v1")]- pub async fn generate_merchant_refund_report(- state: web::Data<AppState>,- req: actix_web::HttpRequest,- json_payload: web::Json<ReportRequest>,- ) -> impl Responder {- let flow = AnalyticsFlow::GenerateRefundReport;- Box::pin(api::server_wrap(- flow,- state.clone(),- &req,- json_payload.into_inner(),- |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };-- let auth_info = auth.platform.to_merchant_level_auth_info();- let hash_key = match &payload.return_url {- Some(_) => {- get_payment_response_hash_key(- state.store.as_ref(),- auth.platform.get_processor().get_key_store(),- &auth_info,- )- .await?- }- None => None,- };-- let lambda_req = GenerateReportRequest {- request: payload,- merchant_id: Some(auth.platform.get_processor().get_account().get_id().clone()),- auth: auth_info,- email: user_email,- payment_response_hash_key: hash_key,- };-- 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::auth_type(- &auth::ApiKeyAuth {- allow_connected_scope_operation: true,- allow_platform_self_operation: true,- },- &auth::JWTAuth {- permission: Permission::MerchantReportRead,- allow_connected: true,- allow_platform: true,- },- req.headers(),- ),- api_locking::LockAction::NotApplicable,- ))- .await- }-- #[cfg(feature = "v1")]- pub async fn generate_org_refund_report(- state: web::Data<AppState>,- req: actix_web::HttpRequest,- json_payload: web::Json<ReportRequest>,- ) -> impl Responder {- let flow = AnalyticsFlow::GenerateRefundReport;- Box::pin(api::server_wrap(- flow,- state.clone(),- &req,- json_payload.into_inner(),- |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };-- let auth_info = auth.platform.to_org_level_auth_info();-- let lambda_req = GenerateReportRequest {- request: payload,- merchant_id: None,- auth: auth_info,- email: user_email,- payment_response_hash_key: None,- };-- 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: Permission::OrganizationReportRead,- allow_connected: true,- allow_platform: true,- },- api_locking::LockAction::NotApplicable,- ))- .await- }-- #[cfg(feature = "v1")]- pub async fn generate_profile_refund_report(- state: web::Data<AppState>,- req: actix_web::HttpRequest,- json_payload: web::Json<ReportRequest>,- ) -> impl Responder {- let flow = AnalyticsFlow::GenerateRefundReport;- Box::pin(api::server_wrap(- flow,- state.clone(),- &req,- json_payload.into_inner(),- |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };-- let profile_id = auth- .profile- .ok_or(report!(UserErrors::JwtProfileIdMissing))- .change_context(AnalyticsError::AccessForbiddenError)?- .get_id()- .clone();-- let auth_info = auth.platform.to_profile_level_auth_info(profile_id);- let hash_key = match &payload.return_url {- Some(_) => {- get_payment_response_hash_key(- state.store.as_ref(),- auth.platform.get_processor().get_key_store(),- &auth_info,- )- .await?- }- None => None,- };-- let lambda_req = GenerateReportRequest {- request: payload,- merchant_id: Some(auth.platform.get_processor().get_account().get_id().clone()),- auth: auth_info,- email: user_email,- payment_response_hash_key: hash_key,- };-- 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::auth_type(- &auth::ApiKeyAuth {- allow_connected_scope_operation: true,- allow_platform_self_operation: false,- },- &auth::JWTAuth {- permission: Permission::ProfileReportRead,- allow_connected: true,- allow_platform: false,- },- req.headers(),- ),- api_locking::LockAction::NotApplicable,- ))- .await- }- #[cfg(feature = "v1")]- pub async fn generate_merchant_relay_report(- state: web::Data<AppState>,- req: actix_web::HttpRequest,- json_payload: web::Json<ReportRequest>,- ) -> impl Responder {- let flow = AnalyticsFlow::GenerateRelayReport;- Box::pin(api::server_wrap(- flow,- state.clone(),- &req,- json_payload.into_inner(),- |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };-- let auth_info = auth.platform.to_merchant_level_auth_info();- let hash_key = match &payload.return_url {- Some(_) => {- get_payment_response_hash_key(- state.store.as_ref(),- auth.platform.get_processor().get_key_store(),- &auth_info,- )- .await?- }- None => None,- };-- let lambda_req = GenerateReportRequest {- request: payload,- merchant_id: Some(auth.platform.get_processor().get_account().get_id().clone()),- auth: auth_info,- email: user_email,- payment_response_hash_key: hash_key,- };-- let json_bytes =- serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;-- let lambda_result = invoke_lambda(- &state.conf.report_download_config.relay_function,- &state.conf.report_download_config.region,- &json_bytes,- )- .await;-- match &lambda_result {- Ok(_) => logger::info!(- merchant_id = ?lambda_req.merchant_id,- "Successfully invoked relay report lambda function"- ),- Err(error) => logger::error!(- merchant_id = ?lambda_req.merchant_id,- ?error,- "Failed to invoke relay report lambda function"- ),- }-- lambda_result.map(ApplicationResponse::Json)- },- auth::auth_type(- &auth::ApiKeyAuth {- allow_connected_scope_operation: true,- allow_platform_self_operation: false,- },- &auth::JWTAuth {- permission: Permission::MerchantReportRead,- allow_connected: true,- allow_platform: false,- },- req.headers(),- ),- api_locking::LockAction::NotApplicable,- ))- .await- }-- #[cfg(feature = "v1")]- pub async fn generate_profile_relay_report(- state: web::Data<AppState>,- req: actix_web::HttpRequest,- json_payload: web::Json<ReportRequest>,- ) -> impl Responder {- let flow = AnalyticsFlow::GenerateRelayReport;- Box::pin(api::server_wrap(- flow,- state.clone(),- &req,- json_payload.into_inner(),- |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };-- let profile_id = auth- .profile- .ok_or(report!(UserErrors::JwtProfileIdMissing))- .change_context(AnalyticsError::AccessForbiddenError)?- .get_id()- .clone();-- let auth_info = auth.platform.to_profile_level_auth_info(profile_id);- let hash_key = match &payload.return_url {- Some(_) => {- get_payment_response_hash_key(- state.store.as_ref(),- auth.platform.get_processor().get_key_store(),- &auth_info,- )- .await?- }- None => None,- };-- let lambda_req = GenerateReportRequest {- request: payload,- merchant_id: Some(auth.platform.get_processor().get_account().get_id().clone()),- auth: auth_info,- email: user_email,- payment_response_hash_key: hash_key,- };-- let json_bytes =- serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;-- let lambda_result = invoke_lambda(- &state.conf.report_download_config.relay_function,- &state.conf.report_download_config.region,- &json_bytes,- )- .await;-- match &lambda_result {- Ok(_) => logger::info!(- merchant_id = ?lambda_req.merchant_id,- "Successfully invoked relay report lambda function"- ),- Err(error) => logger::error!(- merchant_id = ?lambda_req.merchant_id,- ?error,- "Failed to invoke relay report lambda function"- ),- }-- lambda_result.map(ApplicationResponse::Json)- },- auth::auth_type(- &auth::ApiKeyAuth {- allow_connected_scope_operation: true,- allow_platform_self_operation: false,- },- &auth::JWTAuth {- permission: Permission::ProfileReportRead,- allow_connected: true,- allow_platform: false,- },- req.headers(),- ),- api_locking::LockAction::NotApplicable,- ))- .await- }-- #[cfg(feature = "v1")]- pub async fn generate_merchant_dispute_report(- state: web::Data<AppState>,- req: actix_web::HttpRequest,- json_payload: web::Json<ReportRequest>,- ) -> impl Responder {- let flow = AnalyticsFlow::GenerateDisputeReport;- Box::pin(api::server_wrap(- flow,- state.clone(),- &req,- json_payload.into_inner(),- |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };-- let auth_info = auth.platform.to_merchant_level_auth_info();- let hash_key = match &payload.return_url {- Some(_) => {- get_payment_response_hash_key(- state.store.as_ref(),- auth.platform.get_processor().get_key_store(),- &auth_info,- )- .await?- }- None => None,- };-- let lambda_req = GenerateReportRequest {- request: payload,- merchant_id: Some(auth.platform.get_processor().get_account().get_id().clone()),- auth: auth_info,- email: user_email,- payment_response_hash_key: hash_key,- };-- 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::auth_type(- &auth::ApiKeyAuth {- allow_connected_scope_operation: true,- allow_platform_self_operation: true,- },- &auth::JWTAuth {- permission: Permission::MerchantReportRead,- allow_connected: true,- allow_platform: true,- },- req.headers(),- ),- api_locking::LockAction::NotApplicable,- ))- .await- }- #[cfg(feature = "v1")]- pub async fn generate_org_dispute_report(- state: web::Data<AppState>,- req: actix_web::HttpRequest,- json_payload: web::Json<ReportRequest>,- ) -> impl Responder {- let flow = AnalyticsFlow::GenerateDisputeReport;- Box::pin(api::server_wrap(- flow,- state.clone(),- &req,- json_payload.into_inner(),- |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };-- let auth_info = auth.platform.to_org_level_auth_info();-- let lambda_req = GenerateReportRequest {- request: payload,- merchant_id: None,- auth: auth_info,- email: user_email,- payment_response_hash_key: None,- };-- 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: Permission::OrganizationReportRead,- allow_connected: true,- allow_platform: true,- },- api_locking::LockAction::NotApplicable,- ))- .await- }-- #[cfg(feature = "v1")]- pub async fn generate_profile_dispute_report(- state: web::Data<AppState>,- req: actix_web::HttpRequest,- json_payload: web::Json<ReportRequest>,- ) -> impl Responder {- let flow = AnalyticsFlow::GenerateDisputeReport;- Box::pin(api::server_wrap(- flow,- state.clone(),- &req,- json_payload.into_inner(),- |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };-- let profile_id = auth- .profile- .ok_or(report!(UserErrors::JwtProfileIdMissing))- .change_context(AnalyticsError::AccessForbiddenError)?- .get_id()- .clone();- let auth_info = auth.platform.to_profile_level_auth_info(profile_id);- let hash_key = match &payload.return_url {- Some(_) => {- get_payment_response_hash_key(- state.store.as_ref(),- auth.platform.get_processor().get_key_store(),- &auth_info,- )- .await?- }- None => None,- };-- let lambda_req = GenerateReportRequest {- request: payload,- merchant_id: Some(auth.platform.get_processor().get_account().get_id().clone()),- auth: auth_info,- email: user_email,- payment_response_hash_key: hash_key,- };-- 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::auth_type(- &auth::ApiKeyAuth {- allow_connected_scope_operation: true,- allow_platform_self_operation: false,- },- &auth::JWTAuth {- permission: Permission::ProfileReportRead,- allow_connected: true,- allow_platform: false,- },- req.headers(),- ),- api_locking::LockAction::NotApplicable,- ))- .await- }-- #[cfg(feature = "v1")]- pub async fn generate_merchant_payout_report(- state: web::Data<AppState>,- req: actix_web::HttpRequest,- json_payload: web::Json<ReportRequest>,- ) -> impl Responder {- let flow = AnalyticsFlow::GeneratePayoutReport;- Box::pin(api::server_wrap(- flow,- state.clone(),- &req,- json_payload.into_inner(),- |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };-- let auth_info = auth.platform.to_merchant_level_auth_info();- let hash_key = match &payload.return_url {- Some(_) => {- get_payment_response_hash_key(- state.store.as_ref(),- auth.platform.get_processor().get_key_store(),- &auth_info,- )- .await?- }- None => None,- };-- let lambda_req = GenerateReportRequest {- request: payload,- merchant_id: Some(auth.platform.get_processor().get_account().get_id().clone()),- auth: auth_info,- email: user_email,- payment_response_hash_key: hash_key,- };-- let json_bytes =- serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;- invoke_lambda(- &state.conf.report_download_config.payout_function,- &state.conf.report_download_config.region,- &json_bytes,- )- .await- .map(ApplicationResponse::Json)- },- auth::auth_type(- &auth::ApiKeyAuth {- allow_connected_scope_operation: true,- allow_platform_self_operation: true,- },- &auth::JWTAuth {- permission: Permission::MerchantReportRead,- allow_connected: true,- allow_platform: true,- },- req.headers(),- ),- api_locking::LockAction::NotApplicable,- ))- .await- }-- #[cfg(feature = "v1")]- pub async fn generate_org_payout_report(- state: web::Data<AppState>,- req: actix_web::HttpRequest,- json_payload: web::Json<ReportRequest>,- ) -> impl Responder {- let flow = AnalyticsFlow::GeneratePayoutReport;- Box::pin(api::server_wrap(- flow,- state.clone(),- &req,- json_payload.into_inner(),- |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };-- let auth_info = auth.platform.to_org_level_auth_info();-- let lambda_req = GenerateReportRequest {- request: payload,- merchant_id: None,- auth: auth_info,- email: user_email,- payment_response_hash_key: None,- };-- let json_bytes =- serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;- invoke_lambda(- &state.conf.report_download_config.payout_function,- &state.conf.report_download_config.region,- &json_bytes,- )- .await- .map(ApplicationResponse::Json)- },- &auth::JWTAuth {- permission: Permission::OrganizationReportRead,- allow_connected: true,- allow_platform: true,- },- api_locking::LockAction::NotApplicable,- ))- .await- }-- #[cfg(feature = "v1")]- pub async fn generate_profile_payout_report(- state: web::Data<AppState>,- req: actix_web::HttpRequest,- json_payload: web::Json<ReportRequest>,- ) -> impl Responder {- let flow = AnalyticsFlow::GeneratePayoutReport;- Box::pin(api::server_wrap(- flow,- state.clone(),- &req,- json_payload.into_inner(),- |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };- let profile_id = auth- .profile- .ok_or(report!(UserErrors::JwtProfileIdMissing))- .change_context(AnalyticsError::AccessForbiddenError)?- .get_id()- .clone();- let auth_info = auth.platform.to_profile_level_auth_info(profile_id);- let hash_key = match &payload.return_url {- Some(_) => {- get_payment_response_hash_key(- state.store.as_ref(),- auth.platform.get_processor().get_key_store(),- &auth_info,- )- .await?- }- None => None,- };-- let lambda_req = GenerateReportRequest {- request: payload,- merchant_id: Some(auth.platform.get_processor().get_account().get_id().clone()),- auth: auth_info,- email: user_email,- payment_response_hash_key: hash_key,- };-- let json_bytes =- serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;- invoke_lambda(- &state.conf.report_download_config.payout_function,- &state.conf.report_download_config.region,- &json_bytes,- )- .await- .map(ApplicationResponse::Json)- },- auth::auth_type(- &auth::ApiKeyAuth {- allow_connected_scope_operation: true,- allow_platform_self_operation: false,- },- &auth::JWTAuth {- permission: Permission::ProfileReportRead,- allow_connected: true,- allow_platform: false,- },- req.headers(),- ),- api_locking::LockAction::NotApplicable,- ))- .await- }-- pub async fn generate_merchant_payment_report(- state: web::Data<AppState>,- req: actix_web::HttpRequest,- json_payload: web::Json<ReportRequest>,- ) -> impl Responder {- let flow = AnalyticsFlow::GeneratePaymentReport;- Box::pin(api::server_wrap(- flow,- state.clone(),- &req,- json_payload.into_inner(),- |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };-- let auth_info = auth.platform.to_merchant_level_auth_info();- let hash_key = match &payload.return_url {- Some(_) => {- get_payment_response_hash_key(- state.store.as_ref(),- auth.platform.get_processor().get_key_store(),- &auth_info,- )- .await?- }- None => None,- };-- let lambda_req = GenerateReportRequest {- request: payload,- merchant_id: Some(auth.platform.get_processor().get_account().get_id().clone()),- auth: auth_info,- email: user_email,- payment_response_hash_key: hash_key,- };-- 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::auth_type::<auth::AuthenticationDataWithUserId, _>(- &auth::ApiKeyAuth {- allow_connected_scope_operation: true,- allow_platform_self_operation: true,- },- &auth::JWTAuth {- permission: Permission::MerchantReportRead,- allow_connected: true,- allow_platform: true,- },- req.headers(),- ),- api_locking::LockAction::NotApplicable,- ))- .await- }-- pub async fn generate_org_payment_report(- state: web::Data<AppState>,- req: actix_web::HttpRequest,- json_payload: web::Json<ReportRequest>,- ) -> impl Responder {- let flow = AnalyticsFlow::GeneratePaymentReport;- Box::pin(api::server_wrap(- flow,- state.clone(),- &req,- json_payload.into_inner(),- |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };-- let auth_info = auth.platform.to_org_level_auth_info();-- let lambda_req = GenerateReportRequest {- request: payload,- merchant_id: None,- auth: auth_info,- email: user_email,- payment_response_hash_key: None,- };-- 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: Permission::OrganizationReportRead,- allow_connected: true,- allow_platform: true,- },- api_locking::LockAction::NotApplicable,- ))- .await+ /// The report routes' handlers: one per report and level, all served by the three below.+ macro_rules! report_handlers {+ ($($(#[$attribute:meta])* $name:ident => $level:ident($report:ident);)*) => {$(+ $(#[$attribute])*+ pub async fn $name(+ state: web::Data<AppState>,+ req: actix_web::HttpRequest,+ json_payload: web::Json<ReportRequest>,+ ) -> impl Responder {+ $level(state, req, json_payload, ReportKind::$report).await+ }+ )*};}- pub async fn generate_profile_payment_report(- state: web::Data<AppState>,- req: actix_web::HttpRequest,- json_payload: web::Json<ReportRequest>,- ) -> impl Responder {- let flow = AnalyticsFlow::GeneratePaymentReport;- Box::pin(api::server_wrap(- flow,- state.clone(),- &req,- json_payload.into_inner(),- |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };- let profile_id = {- #[cfg(feature = "v1")]- {- auth.profile- .ok_or(report!(UserErrors::JwtProfileIdMissing))- .change_context(AnalyticsError::AccessForbiddenError)?- .get_id()- .clone()- }- #[cfg(feature = "v2")]- {- auth.profile.get_id().clone()- }- };-- let auth_info = auth.platform.to_profile_level_auth_info(profile_id);- let hash_key = match &payload.return_url {- Some(_) => {- get_payment_response_hash_key(- state.store.as_ref(),- auth.platform.get_processor().get_key_store(),- &auth_info,- )- .await?- }- None => None,- };-- let lambda_req = GenerateReportRequest {- request: payload,- merchant_id: Some(auth.platform.get_processor().get_account().get_id().clone()),- auth: auth_info,- email: user_email,- payment_response_hash_key: hash_key,- };-- 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,+ report_handlers! {+ generate_merchant_payment_report => merchant_report(V1Payments);+ generate_org_payment_report => org_report(V1Payments);+ generate_profile_payment_report => profile_report(V1Payments);+ #[cfg(feature = "v1")]+ generate_merchant_refund_report => merchant_report(Refunds);+ #[cfg(feature = "v1")]+ generate_org_refund_report => org_report(Refunds);+ #[cfg(feature = "v1")]+ generate_profile_refund_report => profile_report(Refunds);+ #[cfg(feature = "v1")]+ generate_merchant_dispute_report => merchant_report(Disputes);+ #[cfg(feature = "v1")]+ generate_org_dispute_report => org_report(Disputes);+ #[cfg(feature = "v1")]+ generate_profile_dispute_report => profile_report(Disputes);+ #[cfg(feature = "v1")]+ generate_merchant_payout_report => merchant_report(Payouts);+ #[cfg(feature = "v1")]+ generate_org_payout_report => org_report(Payouts);+ #[cfg(feature = "v1")]+ generate_profile_payout_report => profile_report(Payouts);+ #[cfg(feature = "v1")]+ generate_merchant_relay_report => merchant_report(Relay);+ #[cfg(feature = "v1")]+ generate_profile_relay_report => profile_report(Relay);+ #[cfg(feature = "v1")]+ generate_merchant_authentication_report => merchant_report(Authentications);+ #[cfg(feature = "v1")]+ generate_org_authentication_report => org_report(Authentications);+ #[cfg(feature = "v1")]+ generate_profile_authentication_report => profile_report(Authentications);+ }++ /// Who receives the report: a dashboard user receives it themselves; an API key request names+ /// its recipients, the first being the primary one.+ async fn report_recipients(+ state: &SessionState,+ user_id: Option<String>,+ payload: ReportRequest,+ ) -> Result<(Email, ReportRequest), error_stack::Report<AnalyticsError>> {+ let (email, emails) = match user_id {+ Some(user_id) => {+ let user = state+ .global_store+ .find_active_user_by_user_id(&user_id)+ .await+ .change_context(AnalyticsError::UnknownError)?;+ let email = Email::try_from(+ UserEmail::from_pii_email(user.email)+ .change_context(AnalyticsError::UnknownError)?+ .get_secret()+ .expose()+ .to_string(),)- .await- .map(ApplicationResponse::Json)- },- auth::auth_type::<auth::AuthenticationDataWithUserId, _>(- &auth::ApiKeyAuth {- allow_connected_scope_operation: true,- allow_platform_self_operation: false,- },- &auth::JWTAuth {- permission: Permission::ProfileReportRead,- allow_connected: true,- allow_platform: false,- },- req.headers(),- ),- api_locking::LockAction::NotApplicable,- ))- .await+ .change_context(AnalyticsError::MissingEmail)?;+ (email, payload.emails.clone())+ }+ None => {+ validate_report_request(&payload)?;+ let mut emails = payload+ .emails+ .clone()+ .filter(|emails| !emails.is_empty())+ .ok_or(AnalyticsError::MissingEmail)?;+ (emails.remove(0), Some(emails))+ }+ };+ Ok((email, ReportRequest { emails, ..payload }))+ }++ /// The key signing the report webhook; only fetched when the request names a `return_url`.+ async fn report_hash_key(+ state: &SessionState,+ key_store: &crate::types::domain::MerchantKeyStore,+ auth_info: &AuthInfo,+ payload: &ReportRequest,+ ) -> Result<Option<String>, error_stack::Report<AnalyticsError>> {+ match payload.return_url {+ Some(_) => {+ get_payment_response_hash_key(state.store.as_ref(), key_store, auth_info).await+ }+ None => Ok(None),+ }}- #[cfg(feature = "v1")]- pub async fn generate_merchant_authentication_report(+ async fn merchant_report(state: web::Data<AppState>,req: actix_web::HttpRequest,json_payload: web::Json<ReportRequest>,+ report: ReportKind,) -> impl Responder {- let flow = AnalyticsFlow::GenerateAuthenticationReport;+ // Relay reports are not served to a platform acting on itself.+ let platform = report != ReportKind::Relay;Box::pin(api::server_wrap(- flow,+ report.flow(),state.clone(),&req,json_payload.into_inner(),|state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };-+ let (email, payload) = report_recipients(&state, user_id, payload).await?;+ let processor = auth.platform.get_processor();let auth_info = auth.platform.to_merchant_level_auth_info();- let hash_key = match &payload.return_url {- Some(_) => {- get_payment_response_hash_key(- state.store.as_ref(),- auth.platform.get_processor().get_key_store(),- &auth_info,- )- .await?- }- None => None,- };-- let lambda_req = GenerateReportRequest {+ let payment_response_hash_key =+ report_hash_key(&state, processor.get_key_store(), &auth_info, &payload)+ .await?;+ let request = GenerateReportRequest {request: payload,- merchant_id: Some(auth.platform.get_processor().get_account().get_id().clone()),+ merchant_id: Some(processor.get_account().get_id().clone()),auth: auth_info,- email: user_email,- payment_response_hash_key: hash_key,+ email,+ payment_response_hash_key,};-- let json_bytes =- serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;- invoke_lambda(- &state.conf.report_download_config.authentication_function,- &state.conf.report_download_config.region,- &json_bytes,- )- .await- .map(ApplicationResponse::Json)+ crate::core::analytics_report::generate_report(&state, report, request).await},- auth::auth_type(+ auth::auth_type::<auth::AuthenticationDataWithUserId, _>(&auth::ApiKeyAuth {allow_connected_scope_operation: true,- allow_platform_self_operation: true,+ allow_platform_self_operation: platform,},&auth::JWTAuth {permission: Permission::MerchantReportRead,allow_connected: true,- allow_platform: true,+ allow_platform: platform,},req.headers(),),@@ -3413,80 +2024,27 @@ pub mod routes {.await}- #[cfg(feature = "v1")]- pub async fn generate_org_authentication_report(+ async fn org_report(state: web::Data<AppState>,req: actix_web::HttpRequest,json_payload: web::Json<ReportRequest>,+ report: ReportKind,) -> impl Responder {- let flow = AnalyticsFlow::GenerateAuthenticationReport;Box::pin(api::server_wrap(- flow,+ report.flow(),state.clone(),&req,json_payload.into_inner(),|state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };-- let auth_info = auth.platform.to_org_level_auth_info();-- let lambda_req = GenerateReportRequest {+ let (email, payload) = report_recipients(&state, user_id, payload).await?;+ let request = GenerateReportRequest {request: payload,merchant_id: None,- auth: auth_info,- email: user_email,+ auth: auth.platform.to_org_level_auth_info(),+ email,payment_response_hash_key: None,};-- let json_bytes =- serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;- invoke_lambda(- &state.conf.report_download_config.authentication_function,- &state.conf.report_download_config.region,- &json_bytes,- )- .await- .map(ApplicationResponse::Json)+ crate::core::analytics_report::generate_report(&state, report, request).await},&auth::JWTAuth {permission: Permission::OrganizationReportRead,@@ -3498,98 +2056,44 @@ pub mod routes {.await}- #[cfg(feature = "v1")]- pub async fn generate_profile_authentication_report(+ async fn profile_report(state: web::Data<AppState>,req: actix_web::HttpRequest,json_payload: web::Json<ReportRequest>,+ report: ReportKind,) -> impl Responder {- let flow = AnalyticsFlow::GenerateAuthenticationReport;Box::pin(api::server_wrap(- flow,+ report.flow(),state.clone(),&req,json_payload.into_inner(),|state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {- let (user_email, optional_emails) = match user_id {- Some(user_id) => {- let user = state- .global_store- .find_active_user_by_user_id(&user_id)- .await- .change_context(AnalyticsError::UnknownError)?;-- let user_email = Email::try_from(- UserEmail::from_pii_email(user.email)- .change_context(AnalyticsError::UnknownError)?- .get_secret()- .expose()- .to_string(),- )- .change_context(AnalyticsError::MissingEmail)?;-- (user_email, payload.emails)- }- None => {- validate_report_request(&payload)?;- let (primary_email, other_emails) = payload- .emails- .and_then(|mut emails| {- if emails.is_empty() {- None- } else {- let primary_email = emails.remove(0);- Some((primary_email, emails))- }- })- .ok_or(AnalyticsError::MissingEmail)?;-- (primary_email, Some(other_emails))- }- };-- let payload = ReportRequest {- emails: optional_emails,- ..payload- };+ let (email, payload) = report_recipients(&state, user_id, payload).await?;+ #[cfg(feature = "v1")]let profile_id = auth.profile.ok_or(report!(UserErrors::JwtProfileIdMissing)).change_context(AnalyticsError::AccessForbiddenError)?.get_id().clone();- let auth_info = auth.platform.to_profile_level_auth_info(profile_id);- let hash_key = match &payload.return_url {- Some(_) => {- get_payment_response_hash_key(- state.store.as_ref(),- auth.platform.get_processor().get_key_store(),- &auth_info,- )- .await?- }- None => None,- };+ #[cfg(feature = "v2")]+ let profile_id = auth.profile.get_id().clone();- let lambda_req = GenerateReportRequest {+ let processor = auth.platform.get_processor();+ let auth_info = auth.platform.to_profile_level_auth_info(profile_id);+ let payment_response_hash_key =+ report_hash_key(&state, processor.get_key_store(), &auth_info, &payload)+ .await?;+ let request = GenerateReportRequest {request: payload,- merchant_id: Some(auth.platform.get_processor().get_account().get_id().clone()),+ merchant_id: Some(processor.get_account().get_id().clone()),auth: auth_info,- email: user_email,- payment_response_hash_key: hash_key,+ email,+ payment_response_hash_key,};-- let json_bytes =- serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;- invoke_lambda(- &state.conf.report_download_config.authentication_function,- &state.conf.report_download_config.region,- &json_bytes,- )- .await- .map(ApplicationResponse::Json)+ crate::core::analytics_report::generate_report(&state, report, request).await},- auth::auth_type(+ auth::auth_type::<auth::AuthenticationDataWithUserId, _>(&auth::ApiKeyAuth {allow_connected_scope_operation: true,allow_platform_self_operation: false,@@ -4679,7 +3183,7 @@ pub mod routes {state,&req,payload,- |state: crate::routes::SessionState, auth: AuthenticationData, req, _| async move {+ |state: SessionState, auth: AuthenticationData, req, _| async move {let profile_id = auth.profile.ok_or(report!(UserErrors::JwtProfileIdMissing))diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rsindex 1018a1863c..958a9dda54 100644--- a/crates/router/src/bin/scheduler.rs+++ b/crates/router/src/bin/scheduler.rs@@ -432,6 +432,21 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {)}}+ storage::ProcessTrackerRunner::AnalyticsReportWorkflow => {+ #[cfg(feature = "olap")]+ {+ Ok(Box::new(+ workflows::analytics_report::AnalyticsReportWorkflow,+ ))+ }+ #[cfg(not(feature = "olap"))]+ {+ Err(error_stack::report!(ProcessTrackerError::UnexpectedFlow))+ .attach_printable(+ "Cannot run analytics report workflow when olap feature is disabled",+ )+ }+ }storage::ProcessTrackerRunner::BlocklistProfileCloneWorkflow => {#[cfg(feature = "v1")]{diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex daef280570..a93c042c5b 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -1563,12 +1563,24 @@ impl Settings<SecuredSecret> {.with_list_parse_key("redis.cluster_urls").with_list_parse_key("events.kafka.brokers").with_list_parse_key("connectors.supported.wallets")+ .with_list_parse_key("report_download_config.process_tracker.email_bcc")+ .with_list_parse_key("report_download_config.process_tracker_reports").with_list_parse_key("connector_request_reference_id_config.merchant_ids_send_payment_id_as_connector_request_id");#[cfg(feature = "deja")]let environment_source =environment_source.with_list_parse_key("deja.recording.kafka.brokers");+ #[cfg(feature = "olap")]+ let environment_source = {+ use strum::IntoEnumIterator;+ analytics::reports::ReportKind::iter().fold(environment_source, |source, report| {+ source.with_list_parse_key(&format!(+ "report_download_config.process_tracker.report_email_bcc.{report}"+ ))+ })+ };+let config = config.add_source(environment_source).build()diff --git a/crates/router/src/core.rs b/crates/router/src/core.rsindex 41ab5c7f5b..9b0288d335 100644--- a/crates/router/src/core.rs+++ b/crates/router/src/core.rs@@ -1,6 +1,8 @@#[cfg(feature = "v2")]pub mod account_updater;pub mod admin;+#[cfg(feature = "olap")]+pub mod analytics_report;pub mod api_keys;pub mod api_locking;#[cfg(feature = "v1")]diff --git a/crates/router/src/core/analytics_report.rs b/crates/router/src/core/analytics_report.rsnew file mode 100644index 0000000000..506bdb56cb--- /dev/null+++ b/crates/router/src/core/analytics_report.rs@@ -0,0 +1,621 @@+//! Analytics reports generated by the process tracker instead of the reporting Lambdas.+//!+//! [`generate_report`] invokes the report's Lambda, or enqueues an `AnalyticsReportWorkflow` task,+//! as `report_download_config` selects for that report. The task writes the CSV to file storage,+//! then sends a download link by webhook to the request's `return_url`, or by email. The webhook+//! keeps the Lambda's fields and its `X-Webhook-Signature-512` header.++use analytics::{+ enums::AuthInfo,+ errors::AnalyticsError,+ lambda_utils::invoke_lambda,+ reports::{self, ReportKind},+};+use api_models::analytics::GenerateReportRequest;+use common_utils::{+ crypto::{HmacSha512, SignMessage},+ date_time,+ errors::CustomResult,+ pii::Email,+ request::RequestContent,+};+use error_stack::{report, ResultExt};+use external_services::file_storage::MultipartUpload;+use hyperswitch_masking::PeekInterface;+use router_env::{instrument, tracing};++use crate::{+ logger,+ routes::SessionState,+ services::{self, ApplicationResponse},+ types::storage,+};++const ANALYTICS_REPORT_TASK: &str = "ANALYTICS_REPORT";++/// The Lambda gave the merchant's endpoint 10 seconds.+const WEBHOOK_TIMEOUT_SECS: u64 = 10;++#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]+pub struct AnalyticsReportTrackingData {+ pub job_id: String,+ pub report: ReportKind,+ /// As the handler built it, with `time_range.end_time` always set. Its+ /// `payment_response_hash_key` is never stored: the signing key is read again on delivery.+ pub request: GenerateReportRequest,+ pub file_key: String,+ /// Set once the file is written; from then on retries only redo delivery.+ #[serde(default)]+ pub generated: bool,+}++impl AnalyticsReportTrackingData {+ fn time_range(&self) -> (time::PrimitiveDateTime, time::PrimitiveDateTime) {+ let range = self.request.request.time_range;+ (range.start_time, range.end_time.unwrap_or(range.start_time))+ }++ /// Also the download's name. The range carries no separators, so the name is valid on every+ /// file system.+ fn file_name(&self) -> String {+ let (start, end) = self.time_range();+ let compact = |value| {+ date_time::format_date(value, date_time::DateFormat::YYYYMMDDHHmmss)+ .unwrap_or_else(|_| value.to_string())+ };+ let name = self.report.definition().name;+ format!("{name}_report_{}_{}.csv", compact(start), compact(end))+ }++ /// The org, merchant and profile naming the report in its file key and webhook. A connected+ /// merchant is named by its platform, as the Lambda did.+ fn owner(&self) -> (&str, Option<&str>, Option<&str>) {+ match &self.request.auth {+ AuthInfo::OrgLevel { org_id } => (org_id.get_string_repr(), None, None),+ AuthInfo::MerchantLevel {+ org_id,+ merchant_ids,+ ..+ } => (+ org_id.get_string_repr(),+ merchant_ids.first().map(|id| id.get_string_repr()),+ None,+ ),+ AuthInfo::ProfileLevel {+ org_id,+ merchant_id,+ profile_ids,+ ..+ } => (+ org_id.get_string_repr(),+ Some(merchant_id.get_string_repr()),+ profile_ids.first().map(|id| id.get_string_repr()),+ ),+ }+ }++ /// The Lambda's key layout, with the job id added so two requests for the same range cannot+ /// overwrite each other's file.+ fn file_key(&self, prefix: &str) -> String {+ let (org_id, merchant_id, profile_id) = self.owner();+ let owner = [Some(org_id), merchant_id, profile_id]+ .into_iter()+ .flatten()+ .collect::<Vec<_>>()+ .join("/");+ let name = self.report.definition().name;+ format!(+ "{prefix}/{owner}/{name}/{}/{}",+ self.job_id,+ self.file_name()+ )+ }+}++/// Starts `report` on the process tracker when `report_download_config.process_tracker_reports`+/// lists it, else on its Lambda.+pub async fn generate_report(+ state: &SessionState,+ report: ReportKind,+ request: GenerateReportRequest,+) -> CustomResult<ApplicationResponse<()>, AnalyticsError> {+ let config = &state.conf.report_download_config;+ let report = report.requested_by(&request.request);+ match config.uses_process_tracker(report) {+ false => {+ let json_bytes =+ serde_json::to_vec(&request).map_err(|_| AnalyticsError::UnknownError)?;+ invoke_lambda(config.lambda_function(report), &config.region, &json_bytes)+ .await+ .map(ApplicationResponse::Json)+ }+ true => enqueue_report(state, report, request)+ .await+ .map(ApplicationResponse::Json),+ }+}++#[instrument(skip_all, fields(report = ?report))]+async fn enqueue_report(+ state: &SessionState,+ report: ReportKind,+ mut request: GenerateReportRequest,+) -> CustomResult<(), AnalyticsError> {+ // Rejected here, with a 400, rather than failing in the background.+ report.validate_columns(&request)?;++ let now = date_time::now();+ request.payment_response_hash_key = None;+ request.request.time_range.end_time.get_or_insert(now);++ let job_id = common_utils::generate_id(crate::consts::ID_LENGTH, "report");+ let mut tracking_data = AnalyticsReportTrackingData {+ job_id: job_id.clone(),+ report,+ request,+ file_key: String::new(),+ generated: false,+ };+ tracking_data.file_key = tracking_data.file_key(+ &state+ .conf+ .report_download_config+ .process_tracker+ .file_key_prefix,+ );++ let runner = storage::ProcessTrackerRunner::AnalyticsReportWorkflow;+ let entry = storage::ProcessTrackerNew::new(+ format!("{runner}_{ANALYTICS_REPORT_TASK}_{job_id}"),+ ANALYTICS_REPORT_TASK,+ runner,+ ["ANALYTICS", "REPORT"],+ tracking_data,+ None,+ now,+ common_types::consts::API_VERSION,+ common_enums::ApplicationSource::Main,+ )+ .change_context(AnalyticsError::UnknownError)?;++ state+ .store+ .insert_process(entry)+ .await+ .change_context(AnalyticsError::UnknownError)+ .attach_printable("Failed to enqueue the analytics report")?;++ logger::info!(job_id = %job_id, "Analytics report enqueued");+ Ok(())+}++/// Writes the report's CSV to `file_key`, returning the number of rows in it. The replica's rows+/// arrive a page at a time and each page is uploaded before the next is taken, so memory never+/// holds more than a few pages.+pub(crate) async fn generate_report_file(+ state: &SessionState,+ tracking_data: &AnalyticsReportTrackingData,+) -> CustomResult<usize, AnalyticsError> {+ let settings = &state.conf.report_download_config.process_tracker;+ let query = tracking_data.report.query(&tracking_data.request)?;+ let header = query.header.clone();+ let mut upload =+ MultipartUpload::start(state.file_storage_client.as_ref(), &tracking_data.file_key)+ .await+ .change_context(AnalyticsError::UnknownError)?;++ // One page queued while another is written: the reader waits rather than running ahead.+ let (sender, receiver) = tokio::sync::mpsc::channel(1);+ let read = state.store.stream_analytics_report(+ query,+ settings.page_size,+ std::time::Duration::from_secs(settings.query_timeout_secs),+ sender,+ );+ let write = async {+ // Dropped on the way out, which stops the reader if writing fails first.+ let mut pages = receiver;+ upload+ .write(&header)+ .await+ .change_context(AnalyticsError::UnknownError)?;+ let mut row_count = 0;+ while let Some(page) = pages.recv().await {+ let mut records = Vec::new();+ for row in &page {+ records.extend(reports::csv_record(+ row.cells+ .iter()+ .map(|cell| cell.as_deref().unwrap_or_default()),+ ));+ }+ upload+ .write(&records)+ .await+ .change_context(AnalyticsError::UnknownError)?;+ row_count += page.len();+ }+ Ok::<_, error_stack::Report<AnalyticsError>>(row_count)+ };+ let (read, written) = tokio::join!(read, write);++ let written = read+ .change_context(AnalyticsError::UnknownError)+ .attach_printable("Failed to read the report from the replica")+ .and(written);+ match written {+ Ok(row_count) => {+ upload+ .finish()+ .await+ .change_context(AnalyticsError::UnknownError)?;+ Ok(row_count)+ }+ Err(error) => {+ if let Err(abort_error) = upload.abort().await {+ logger::warn!(?abort_error, "Failed to abort the analytics report upload");+ }+ Err(error)+ }+ }+}++/// Sends the download link by webhook when the request names a `return_url`, else by email.+pub(crate) async fn deliver_report(+ state: &SessionState,+ tracking_data: &AnalyticsReportTrackingData,+) -> CustomResult<(), AnalyticsError> {+ let expiry_days = state+ .conf+ .report_download_config+ .process_tracker+ .download_url_expiry_days;+ let download_url = state+ .file_storage_client+ .get_presigned_download_url(+ &tracking_data.file_key,+ std::time::Duration::from_secs(u64::from(expiry_days) * 86_400),+ Some(&tracking_data.file_name()),+ )+ .await+ .change_context(AnalyticsError::UnknownError)+ .attach_printable("Failed to sign the analytics report download URL")?;++ if tracking_data.request.request.return_url.is_none() {+ return send_emails(state, tracking_data, download_url.as_str(), expiry_days).await;+ }+ let (start, end) = tracking_data.time_range();+ let data = serde_json::json!({+ "report_type": tracking_data.report.definition().webhook_type,+ "start_date_utc": reports::format_timestamp(start),+ "end_date_utc": reports::format_timestamp(end),+ "download_url": download_url.as_str(),+ "expires_in_hours": expiry_days * 24,+ });+ send_webhook(state, tracking_data, "report_generation.completed", data).await+}++/// Tells the merchant's endpoint the report could not be produced, once retries are exhausted.+pub(crate) async fn notify_report_failed(+ state: &SessionState,+ tracking_data: &AnalyticsReportTrackingData,+) -> CustomResult<(), AnalyticsError> {+ let data = serde_json::json!({+ "code": "internal_server_error",+ "message": "We could not generate the report due to a internal server error. Please request the report again.",+ });+ send_webhook(state, tracking_data, "report_generation.failed", data).await+}++fn webhook_body(+ tracking_data: &AnalyticsReportTrackingData,+ event: &str,+ data: serde_json::Value,+) -> Vec<u8> {+ // The Lambda's key order: org, merchant, profile when there is one, data, event.+ let (org_id, merchant_id, profile_id) = tracking_data.owner();+ let mut payload = serde_json::Map::new();+ payload.insert("org_id".into(), org_id.into());+ payload.insert("merchant_id".into(), merchant_id.into());+ if let Some(profile_id) = profile_id {+ payload.insert("profile_id".into(), profile_id.into());+ }+ payload.insert("data".into(), data);+ payload.insert("event".into(), event.into());+ serde_json::Value::Object(payload).to_string().into_bytes()+}++/// Posts `event` to the request's `return_url`; does nothing when it has none.+async fn send_webhook(+ state: &SessionState,+ tracking_data: &AnalyticsReportTrackingData,+ event: &str,+ data: serde_json::Value,+) -> CustomResult<(), AnalyticsError> {+ let Some(url) = tracking_data.request.request.return_url.as_ref() else {+ return Ok(());+ };+ let body = webhook_body(tracking_data, event, data);+ let mut request = services::RequestBuilder::new()+ .method(services::Method::Post)+ .url(url.get_string_repr())+ .header("Content-Type", "application/json")+ .header("User-Agent", "Hyperswitch-Webhook/1.0");+ if let Some(hash_key) = payment_response_hash_key(state, &tracking_data.request).await? {+ request = request.header(+ "X-Webhook-Signature-512",+ &webhook_signature(&hash_key, &body)?,+ );+ }++ let response = state+ .api_client+ .send_request(+ state,+ request.set_body(RequestContent::RawBytes(body)).build(),+ Some(WEBHOOK_TIMEOUT_SECS),+ false,+ )+ .await+ .change_context(AnalyticsError::UnknownError)+ .attach_printable("Failed to reach the analytics report webhook endpoint")?;++ let status = response.status();+ if !status.is_success() {+ return Err(report!(AnalyticsError::UnknownError)).attach_printable(format!(+ "The report webhook endpoint responded with {status}"+ ));+ }+ Ok(())+}++/// Lowercase hex HMAC-SHA512 of the body, as the Lambda signed it.+fn webhook_signature(hash_key: &str, body: &[u8]) -> CustomResult<String, AnalyticsError> {+ HmacSha512+ .sign_message(hash_key.as_bytes(), body)+ .map(hex::encode)+ .change_context(AnalyticsError::UnknownError)+}++/// `request.merchant_id` holds the key store's merchant; organization reports have none and go+/// unsigned, as they did from the Lambda.+async fn payment_response_hash_key(+ state: &SessionState,+ request: &GenerateReportRequest,+) -> CustomResult<Option<String>, AnalyticsError> {+ let Some(merchant_id) = request.merchant_id.as_ref() else {+ return Ok(None);+ };+ let key_store = state+ .store+ .get_merchant_key_store_by_merchant_id(+ merchant_id,+ &state.store.get_master_key().to_vec().into(),+ )+ .await+ .change_context(AnalyticsError::UnknownError)?;+ crate::utils::get_payment_response_hash_key(state.store.as_ref(), &key_store, &request.auth)+ .await+}++async fn send_emails(+ state: &SessionState,+ tracking_data: &AnalyticsReportTrackingData,+ download_url: &str,+ expiry_days: u32,+) -> CustomResult<(), AnalyticsError> {+ #[cfg(feature = "email")]+ {+ let config = &state.conf.report_download_config.process_tracker;+ let (start, end) = tracking_data.time_range();+ let report = tracking_data.report;+ let definition = report.definition();+ let email = services::email::types::AnalyticsReportEmail {+ recipients: email_recipients(&tracking_data.request, config.email_bcc(report)),+ report_name: format!("{} {}", config.email_env_label, definition.title),+ noun: definition.noun.to_owned(),+ covers: definition.covers.to_owned(),+ start: reports::format_timestamp(start),+ end: reports::format_timestamp(end),+ download_url: download_url.to_owned(),+ expiry: match expiry_days {+ 1 => "1 day".to_owned(),+ days => format!("{days} days"),+ },+ };+ state+ .email_client+ .compose_and_send_email(+ crate::utils::user::get_base_url(state),+ Box::new(email),+ state.conf.proxy.https_url.as_ref(),+ )+ .await+ .change_context(AnalyticsError::UnknownError)+ .attach_printable("Failed to send the analytics report email")+ }++ #[cfg(not(feature = "email"))]+ {+ let _ = (state, tracking_data, download_url, expiry_days);+ Err(report!(AnalyticsError::NotImplemented(+ "Emailing analytics reports without the email feature"+ )))+ }+}++/// One email to the requester and the other requested addresses, blind-copying the BCC list;+/// each address once, ignoring case.+#[cfg(any(feature = "email", test))]+fn email_recipients(+ request: &GenerateReportRequest,+ bcc: &[Email],+) -> external_services::email::EmailRecipients {+ let mut recipients = external_services::email::EmailRecipients::default();+ let seen = |list: &[Email], email: &Email| {+ list.iter()+ .any(|existing| existing.peek().eq_ignore_ascii_case(email.peek()))+ };+ for email in std::iter::once(&request.email).chain(request.request.emails.iter().flatten()) {+ if !seen(&recipients.to, email) {+ recipients.to.push(email.clone());+ }+ }+ for email in bcc {+ if !seen(&recipients.to, email) && !seen(&recipients.bcc, email) {+ recipients.bcc.push(email.clone());+ }+ }+ recipients+}++/// Saves `tracking_data` on the task. The business status stays `Pending` until the task finishes,+/// since the consumer skips any task whose business status is anything else.+pub(crate) async fn persist_tracking_data(+ state: &SessionState,+ process_id: &str,+ tracking_data: &AnalyticsReportTrackingData,+) -> CustomResult<(), AnalyticsError> {+ let value = serde_json::to_value(tracking_data).change_context(AnalyticsError::UnknownError)?;+ state+ .store+ .as_scheduler()+ .process_tracker_update_process_status_by_ids(+ vec![process_id.to_owned()],+ storage::ProcessTrackerUpdate::Update {+ name: None,+ retry_count: None,+ schedule_time: None,+ tracking_data: Some(value),+ business_status: None,+ status: None,+ updated_at: Some(date_time::now()),+ },+ )+ .await+ .change_context(AnalyticsError::UnknownError)+ .attach_printable("Failed to save analytics report progress")?;+ Ok(())+}++#[cfg(test)]+#[allow(clippy::unwrap_used)]+mod tests {+ use api_models::analytics::ReportRequest;+ use common_utils::id_type;++ use super::*;++ fn tracking_data(auth: AuthInfo, emails: Option<Vec<Email>>) -> AnalyticsReportTrackingData {+ AnalyticsReportTrackingData {+ job_id: "report_abc".to_owned(),+ report: ReportKind::V1Payments,+ request: GenerateReportRequest {+ request: ReportRequest {+ time_range: common_utils::types::TimeRange {+ start_time: time::macros::datetime!(2026-10-01 00:00:00),+ end_time: Some(time::macros::datetime!(2026-10-07 23:59:59.999)),+ },+ emails,+ return_url: None,+ #[cfg(feature = "v2")]+ report_type: Default::default(),+ columns: None,+ },+ merchant_id: None,+ auth,+ email: Email::try_from("[email protected]".to_owned()).unwrap(),+ payment_response_hash_key: None,+ },+ file_key: String::new(),+ generated: false,+ }+ }++ fn profile_auth() -> AuthInfo {+ AuthInfo::ProfileLevel {+ org_id: id_type::OrganizationId::try_from(std::borrow::Cow::from("org_1")).unwrap(),+ merchant_id: id_type::MerchantId::try_from(std::borrow::Cow::from("merchant_1"))+ .unwrap(),+ profile_ids: vec![+ id_type::ProfileId::try_from(std::borrow::Cow::from("pro_1")).unwrap(),+ ],+ processor_merchant_id: None,+ }+ }++ #[test]+ fn file_key_follows_lambda_layout() {+ assert_eq!(+ tracking_data(profile_auth(), None).file_key("analytics_reports"),+ "analytics_reports/org_1/merchant_1/pro_1/v1_payments/report_abc/\+ v1_payments_report_20261001000000_20261007235959.csv"+ );+ }++ #[test]+ fn webhook_body_carries_lambda_fields() {+ let data = tracking_data(profile_auth(), None);+ let body = webhook_body(+ &data,+ "report_generation.completed",+ serde_json::json!({+ "report_type": "payment_report",+ "start_date_utc": "2026-10-01T00:00:00.000Z",+ "end_date_utc": "2026-10-07T23:59:59.999Z",+ "download_url": "https://bucket.example/key?X-Amz-Signature=ab",+ "expires_in_hours": 168,+ }),+ );++ // Field order follows build_webhook_payload in weekly_payment_report_generator_step_2.+ assert_eq!(+ String::from_utf8(body.clone()).unwrap(),+ r#"{"org_id":"org_1","merchant_id":"merchant_1","profile_id":"pro_1","data":{"report_type":"payment_report","start_date_utc":"2026-10-01T00:00:00.000Z","end_date_utc":"2026-10-07T23:59:59.999Z","download_url":"https://bucket.example/key?X-Amz-Signature=ab","expires_in_hours":168},"event":"report_generation.completed"}"#+ );+ // Python: hmac.new(b"whsec_test_key", body, hashlib.sha512).hexdigest()+ assert_eq!(+ webhook_signature("whsec_test_key", &body).unwrap(),+ "76f475de13962c74f934f8dc2e21a88b2ae3d5f3ba825e523a15089c90dd5251ae895f87aa4d1c8bffc60004fdfbc546cd9666c4946640876d44a20fc8577ed1"+ );+ }++ #[test]+ fn organization_webhook_has_no_merchant_or_profile() {+ let auth = AuthInfo::OrgLevel {+ org_id: id_type::OrganizationId::try_from(std::borrow::Cow::from("org_1")).unwrap(),+ };+ let body = webhook_body(+ &tracking_data(auth, None),+ "report_generation.failed",+ serde_json::json!({+ "code": "internal_server_error",+ "message": "We could not generate the report due to a internal server error. Please request the report again.",+ }),+ );+ assert_eq!(+ String::from_utf8(body).unwrap(),+ r#"{"org_id":"org_1","merchant_id":null,"data":{"code":"internal_server_error","message":"We could not generate the report due to a internal server error. Please request the report again."},"event":"report_generation.failed"}"#+ );+ }++ #[test]+ fn email_recipients_are_deduplicated() {+ let email = |value: &str| Email::try_from(value.to_owned()).unwrap();+ let data = tracking_data(+ profile_auth(),+ Some(vec![email("[email protected]"), email("[email protected]")]),+ );+ let recipients = email_recipients(+ &data.request,+ &[email("[email protected]"), email("[email protected]")],+ );+ let addresses =+ |list: &[Email]| list.iter().map(|e| e.peek().to_owned()).collect::<Vec<_>>();+ assert_eq!(+ addresses(&recipients.to),+ ["[email protected]", "[email protected]"]+ );+ assert_eq!(addresses(&recipients.bcc), ["[email protected]"]);+ }+}diff --git a/crates/router/src/db.rs b/crates/router/src/db.rsindex 6833897a6a..64d6e95f23 100644--- a/crates/router/src/db.rs+++ b/crates/router/src/db.rs@@ -1,4 +1,5 @@pub mod address;+pub mod analytics_report;pub mod api_keys;pub mod authentication;pub mod authorization;@@ -123,6 +124,7 @@ pub trait StorageInterface:+ PaymentAttemptInterface<Error = StorageError>+ PaymentIntentInterface<Error = StorageError>+ PaymentMethodInterface<Error = StorageError>+ + analytics_report::AnalyticsReportInterface+ blocklist::BlocklistInterface+ blocklist_fingerprint::BlocklistFingerprintInterface+ batch_blocklist_job::BatchBlocklistJobInterfacediff --git a/crates/router/src/db/analytics_report.rs b/crates/router/src/db/analytics_report.rsnew file mode 100644index 0000000000..9c27a91859--- /dev/null+++ b/crates/router/src/db/analytics_report.rs@@ -0,0 +1,134 @@+//! Storage for analytics reports generated by the process tracker.++#[cfg(feature = "olap")]+pub use olap::*;++/// Reports need the `olap` feature; without it the interface is empty.+#[cfg(not(feature = "olap"))]+pub trait AnalyticsReportInterface {}++#[cfg(not(feature = "olap"))]+impl<T: ?Sized> AnalyticsReportInterface for T {}++#[cfg(feature = "olap")]+mod olap {+ use analytics::reports::{ReportBind, ReportQuery};+ use diesel::sql_types::{Array, Text};+ use error_stack::report;+ use router_env::{instrument, tracing};+ pub use row::ReportRow;+ use storage_impl::{utils::pg_connection_read_replica, MockDb};++ use crate::{+ core::errors::{self, CustomResult},+ db::{kafka_store::KafkaStore, Store},+ };++ // The derive's generated impl trips `unused_qualifications` and, from Rust 1.99,+ // `clippy::redundant_field_names`; this module scopes the allows.+ #[allow(unused_qualifications, clippy::redundant_field_names)]+ mod row {+ use diesel::sql_types::{Array, Nullable, Text};++ /// One report row: its cells as text, in the report's header order.+ #[derive(Debug, diesel::QueryableByName)]+ pub struct ReportRow {+ #[diesel(sql_type = Array<Nullable<Text>>)]+ pub cells: Vec<Option<String>>,+ }+ }++ #[async_trait::async_trait]+ pub trait AnalyticsReportInterface {+ /// Runs `query` on the read replica as one read-only cursor, so Postgres scans once, and sends+ /// its rows through `pages` at most `page_size` at a time; memory holds a page, never the+ /// result. Each fetch is bounded by `fetch_timeout`. Stops early, rolling back, once `pages`+ /// is dropped.+ async fn stream_analytics_report(+ &self,+ query: ReportQuery,+ page_size: usize,+ fetch_timeout: std::time::Duration,+ pages: tokio::sync::mpsc::Sender<Vec<ReportRow>>,+ ) -> CustomResult<(), errors::StorageError>;+ }++ #[async_trait::async_trait]+ impl AnalyticsReportInterface for Store {+ #[instrument(skip_all)]+ async fn stream_analytics_report(+ &self,+ query: ReportQuery,+ page_size: usize,+ fetch_timeout: std::time::Duration,+ pages: tokio::sync::mpsc::Sender<Vec<ReportRow>>,+ ) -> CustomResult<(), errors::StorageError> {+ use async_bb8_diesel::AsyncConnection;+ use diesel::{pg::Pg, sql_types::Timestamp, Connection, RunQueryDsl};++ let conn = pg_connection_read_replica(self).await?;+ let timeout_ms = fetch_timeout.as_millis();+ conn.raw_connection()+ .run(move |conn| {+ conn.transaction(|conn| {+ diesel::sql_query("SET TRANSACTION READ ONLY").execute(conn)?;+ diesel::sql_query(format!("SET LOCAL statement_timeout = {timeout_ms}"))+ .execute(conn)?;++ let mut declare = diesel::sql_query(format!(+ "DECLARE analytics_report NO SCROLL CURSOR FOR {}",+ query.sql+ ))+ .into_boxed::<Pg>();+ for bind in query.binds {+ declare = match bind {+ ReportBind::Text(value) => declare.bind::<Text, _>(value),+ ReportBind::Texts(values) => declare.bind::<Array<Text>, _>(values),+ ReportBind::Timestamp(value) => declare.bind::<Timestamp, _>(value),+ };+ }+ declare.execute(conn)?;++ let fetch = format!("FETCH {} FROM analytics_report", page_size.max(1));+ loop {+ let page = diesel::sql_query(&fetch).load::<ReportRow>(conn)?;+ // An empty page ends the cursor; a closed channel means the writer gave up.+ if page.is_empty() || pages.blocking_send(page).is_err() {+ return Ok(());+ }+ }+ })+ })+ .await+ .map_err(|error: diesel::result::Error| report!(errors::StorageError::from(error)))+ }+ }++ #[async_trait::async_trait]+ impl AnalyticsReportInterface for KafkaStore {+ async fn stream_analytics_report(+ &self,+ query: ReportQuery,+ page_size: usize,+ fetch_timeout: std::time::Duration,+ pages: tokio::sync::mpsc::Sender<Vec<ReportRow>>,+ ) -> CustomResult<(), errors::StorageError> {+ self.diesel_store+ .stream_analytics_report(query, page_size, fetch_timeout, pages)+ .await+ }+ }++ #[async_trait::async_trait]+ impl AnalyticsReportInterface for MockDb {+ async fn stream_analytics_report(+ &self,+ _query: ReportQuery,+ _page_size: usize,+ _fetch_timeout: std::time::Duration,+ _pages: tokio::sync::mpsc::Sender<Vec<ReportRow>>,+ ) -> CustomResult<(), errors::StorageError> {+ Err(errors::StorageError::MockDbError)?+ }+ }+}diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rsindex ffda75f9b9..19101cc66f 100644--- a/crates/router/src/routes/metrics.rs+++ b/crates/router/src/routes/metrics.rs@@ -389,3 +389,27 @@ counter_metric!(leaving the remaining retry budget underivable and ending recovery",unit: "1",);++// Analytics reports generated by the process tracker+counter_metric!(+ ANALYTICS_REPORTS_DELIVERED,+ GLOBAL_METER,+ name: "analytics_report.delivered",+ description: "Analytics reports delivered by webhook or email",+ unit: "1",+);+counter_metric!(+ ANALYTICS_REPORTS_FAILED,+ GLOBAL_METER,+ name: "analytics_report.failed",+ description: "Analytics reports abandoned after exhausting their retries, by the stage that \+ failed (generation or delivery); alert on any",+ unit: "1",+);+histogram_metric_f64!(+ ANALYTICS_REPORT_GENERATION_DURATION,+ GLOBAL_METER,+ name: "analytics_report.generation.duration",+ description: "Time to query an analytics report and write its file",+ unit: "s",+);diff --git a/crates/router/src/services/email/assets/analytics_report.html b/crates/router/src/services/email/assets/analytics_report.htmlnew file mode 100644index 0000000000..27a82dbb60--- /dev/null+++ b/crates/router/src/services/email/assets/analytics_report.html@@ -0,0 +1,26 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>{report_name} Report</title>+ </head>+ <body style="font-family: Arial, Helvetica, sans-serif">+ <p>+ Please find the {noun} report for the period of {start} to {end}.<br />+ This file provides a comprehensive overview of {covers} via Hyperswitch+ during this time frame.+ </p>+ <p>+ Access your report here:+ <a href="{download_url}">Download {report_name} Report</a>.<br />+ (The link expires in {expiry})+ </p>+ <p>+ If you have any questions or require further assistance, please don't+ hesitate to reach out to us at+ <a href="mailto:[email protected]">[email protected]</a>.+ </p>+ <p>Best regards,<br />Hyperswitch Team</p>+ </body>+</html>diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rsindex 41a4a18828..19c41ae89c 100644--- a/crates/router/src/services/email/types.rs+++ b/crates/router/src/services/email/types.rs@@ -92,6 +92,15 @@ pub enum EmailBody {background_color: String,foreground_color: String,},+ AnalyticsReport {+ report_name: String,+ noun: String,+ covers: String,+ start: String,+ end: String,+ download_url: String,+ expiry: String,+ },}pub mod html {@@ -275,6 +284,24 @@ Email : {user_email}foreground_color = foreground_color)}+ EmailBody::AnalyticsReport {+ report_name,+ noun,+ covers,+ start,+ end,+ download_url,+ expiry,+ } => format!(+ include_str!("assets/analytics_report.html"),+ report_name = report_name,+ noun = noun,+ covers = covers,+ start = start,+ end = end,+ download_url = download_url,+ expiry = expiry,+ ),}}}@@ -785,3 +812,43 @@ impl EmailData for RoleDeleted {})}}++/// A finished analytics report's download link, sent once to all its recipients.+pub struct AnalyticsReportEmail {+ pub recipients: external_services::email::EmailRecipients,+ /// Names the report, with the environment, e.g. "Sandbox Payments".+ pub report_name: String,+ /// The report, as the body names it: "the refund report".+ pub noun: String,+ /// The rows, as the body describes them, e.g. "refunds made by your customers".+ pub covers: String,+ pub start: String,+ pub end: String,+ pub download_url: String,+ /// How long the link lasts, e.g. "7 days".+ pub expiry: String,+}++#[async_trait::async_trait]+impl EmailData for AnalyticsReportEmail {+ async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> {+ let body = html::get_html_body(EmailBody::AnalyticsReport {+ report_name: self.report_name.clone(),+ noun: self.noun.clone(),+ covers: self.covers.clone(),+ start: self.start.clone(),+ end: self.end.clone(),+ download_url: self.download_url.clone(),+ expiry: self.expiry.clone(),+ });++ Ok(EmailContents {+ subject: format!(+ "Your {} Report: {} - {}",+ self.report_name, self.start, self.end+ ),+ body: external_services::email::IntermediateString::new(body),+ recipients: self.recipients.clone(),+ })+ }+}diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rsindex b5978e0a47..4683f02f3e 100644--- a/crates/router/src/workflows.rs+++ b/crates/router/src/workflows.rs@@ -1,3 +1,5 @@+#[cfg(feature = "olap")]+pub mod analytics_report;#[cfg(feature = "email")]pub mod api_key_expiry;#[cfg(feature = "payouts")]diff --git a/crates/router/src/workflows/analytics_report.rs b/crates/router/src/workflows/analytics_report.rsnew file mode 100644index 0000000000..91ea70bc52--- /dev/null+++ b/crates/router/src/workflows/analytics_report.rs@@ -0,0 +1,113 @@+use common_utils::ext_traits::ValueExt;+use router_env::{instrument, tracing};+use scheduler::{+ consumer::{self, types::process_data},+ utils as pt_utils,+ workflows::ProcessTrackerWorkflow,+};++use crate::{+ core::{+ analytics_report::{self, AnalyticsReportTrackingData},+ errors,+ },+ logger::{error, info, warn},+ routes::{metrics, SessionState},+ types::storage::{self, business_status},+};++pub struct AnalyticsReportWorkflow;++/// Writes the file unless an earlier attempt already did, then delivers it.+async fn run(+ state: &SessionState,+ process_id: &str,+ tracking_data: &mut AnalyticsReportTrackingData,+) -> errors::CustomResult<(), analytics::errors::AnalyticsError> {+ if !tracking_data.generated {+ let started = std::time::Instant::now();+ let row_count = analytics_report::generate_report_file(state, tracking_data).await?;+ metrics::ANALYTICS_REPORT_GENERATION_DURATION.record(+ started.elapsed().as_secs_f64(),+ router_env::metric_attributes!(("report", tracking_data.report.definition().name)),+ );+ tracking_data.generated = true;+ analytics_report::persist_tracking_data(state, process_id, tracking_data).await?;+ info!(job_id = %tracking_data.job_id, row_count, "Analytics report generated");+ }+ analytics_report::deliver_report(state, tracking_data).await+}++#[async_trait::async_trait]+impl ProcessTrackerWorkflow<SessionState> for AnalyticsReportWorkflow {+ #[instrument(skip_all)]+ async fn execute_workflow<'a>(+ &'a self,+ state: &'a SessionState,+ process: storage::ProcessTracker,+ ) -> Result<(), errors::ProcessTrackerError> {+ let scheduler = state.store.as_scheduler();+ let mut tracking_data: AnalyticsReportTrackingData = process+ .tracking_data+ .clone()+ .parse_value("AnalyticsReportTrackingData")?;++ let Err(error) = run(state, &process.id, &mut tracking_data).await else {+ info!(job_id = %tracking_data.job_id, "Analytics report delivered");+ metrics::ANALYTICS_REPORTS_DELIVERED.add(+ 1,+ router_env::metric_attributes!(("report", tracking_data.report.definition().name)),+ );+ scheduler+ .finish_process_with_business_status(process, business_status::COMPLETED_BY_PT)+ .await?;+ return Ok(());+ };+ error!(job_id = %tracking_data.job_id, ?error, retry_count = process.retry_count, "Analytics report failed");++ let mapping = process_data::RetryMapping::default();+ let delay = match process.retry_count {+ 0 => Some(mapping.start_after),+ retry_count => pt_utils::get_delay(retry_count + 1, &mapping.frequencies),+ };+ match pt_utils::get_time_from_delta(delay) {+ Some(schedule_time) => scheduler.retry_process(process, schedule_time).await?,+ None => {+ let stage = if tracking_data.generated {+ "delivery"+ } else {+ "generation"+ };+ metrics::ANALYTICS_REPORTS_FAILED.add(+ 1,+ router_env::metric_attributes!(+ ("report", tracking_data.report.definition().name),+ ("stage", stage),+ ),+ );+ // A failed delivery means the endpoint is the problem; telling it again that the+ // report failed would fail the same way.+ if !tracking_data.generated {+ if let Err(error) =+ analytics_report::notify_report_failed(state, &tracking_data).await+ {+ warn!(job_id = %tracking_data.job_id, ?error, "Failed to send the report_generation.failed webhook");+ }+ }+ scheduler+ .finish_process_with_business_status(process, business_status::RETRIES_EXCEEDED)+ .await?;+ }+ }+ Ok(())+ }++ async fn error_handler<'a>(+ &'a self,+ state: &'a SessionState,+ process: storage::ProcessTracker,+ error: errors::ProcessTrackerError,+ ) -> errors::CustomResult<(), errors::ProcessTrackerError> {+ consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await+ }+}