text
stringlengths
81
477k
file_path
stringlengths
22
92
module
stringlengths
13
87
token_count
int64
24
94.8k
has_source_code
bool
1 class
// File: crates/analytics/src/auth_events/metrics/challenge_success_count.rs // Module: analytics::src::auth_events::metrics::challenge_success_count use std::collections::HashSet; use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_enums::{AuthenticationStatus, DecoupledAuthenticationType}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, AuthInfo, }; #[derive(Default)] pub(super) struct ChallengeSuccessCount; #[async_trait::async_trait] impl<T> super::AuthEventMetric<T> for ChallengeSuccessCount where T: AnalyticsDataSource + super::AuthEventMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; query_builder .add_filter_clause("authentication_status", AuthenticationStatus::Success) .switch()?; query_builder .add_filter_clause( "authentication_type", DecoupledAuthenticationType::Challenge, ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; auth.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder .add_group_by_clause(dim) .attach_printable("Error grouping by dimensions") .switch()?; } if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } query_builder .execute_query::<AuthEventMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), i.acs_reference_number.clone(), i.mcc.clone(), i.currency.as_ref().map(|i| i.0), i.merchant_country.clone(), i.billing_country.clone(), i.shipping_country.clone(), i.issuer_country.clone(), i.earliest_supported_version.clone(), i.latest_supported_version.clone(), i.whitelist_decision, i.device_manufacturer.clone(), i.device_type.clone(), i.device_brand.clone(), i.device_os.clone(), i.device_display.clone(), i.browser_name.clone(), i.browser_version.clone(), i.issuer_id.clone(), i.scheme_name.clone(), i.exemption_requested, i.exemption_accepted, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result< HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/auth_events/metrics/challenge_success_count.rs
analytics::src::auth_events::metrics::challenge_success_count
1,109
true
// File: crates/analytics/src/refunds/core.rs // Module: analytics::src::refunds::core #![allow(dead_code)] use std::collections::{HashMap, HashSet}; use api_models::analytics::{ refunds::{ RefundDimensions, RefundDistributions, RefundMetrics, RefundMetricsBucketIdentifier, RefundMetricsBucketResponse, }, GetRefundFilterRequest, GetRefundMetricRequest, RefundFilterValue, RefundFiltersResponse, RefundsAnalyticsMetadata, RefundsMetricsResponse, }; use bigdecimal::ToPrimitive; use common_enums::Currency; use common_utils::errors::CustomResult; use currency_conversion::{conversion::convert, types::ExchangeRates}; use error_stack::ResultExt; use router_env::{ logger, tracing::{self, Instrument}, }; use super::{ distribution::RefundDistributionRow, filters::{get_refund_filter_for_dimension, RefundFilterRow}, metrics::RefundMetricRow, RefundMetricsAccumulator, }; use crate::{ enums::AuthInfo, errors::{AnalyticsError, AnalyticsResult}, metrics, refunds::{accumulator::RefundDistributionAccumulator, RefundMetricAccumulator}, AnalyticsProvider, }; #[derive(Debug)] pub enum TaskType { MetricTask( RefundMetrics, CustomResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>, AnalyticsError>, ), DistributionTask( RefundDistributions, CustomResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>, AnalyticsError>, ), } pub async fn get_metrics( pool: &AnalyticsProvider, ex_rates: &Option<ExchangeRates>, auth: &AuthInfo, req: GetRefundMetricRequest, ) -> AnalyticsResult<RefundsMetricsResponse<RefundMetricsBucketResponse>> { let mut metrics_accumulator: HashMap<RefundMetricsBucketIdentifier, RefundMetricsAccumulator> = HashMap::new(); let mut set = tokio::task::JoinSet::new(); for metric_type in req.metrics.iter().cloned() { let req = req.clone(); let pool = pool.clone(); let task_span = tracing::debug_span!( "analytics_refund_query", refund_metric = metric_type.as_ref() ); // Currently JoinSet works with only static lifetime references even if the task pool does not outlive the given reference // We can optimize away this clone once that is fixed let auth_scoped = auth.to_owned(); set.spawn( async move { let data = pool .get_refund_metrics( &metric_type, &req.group_by_names.clone(), &auth_scoped, &req.filters, req.time_series.map(|t| t.granularity), &req.time_range, ) .await .change_context(AnalyticsError::UnknownError); TaskType::MetricTask(metric_type, data) } .instrument(task_span), ); } if let Some(distribution) = req.clone().distribution { let req = req.clone(); let pool = pool.clone(); let task_span = tracing::debug_span!( "analytics_refunds_distribution_query", refund_distribution = distribution.distribution_for.as_ref() ); let auth_scoped = auth.to_owned(); set.spawn( async move { let data = pool .get_refund_distribution( &distribution, &req.group_by_names.clone(), &auth_scoped, &req.filters, &req.time_series.map(|t| t.granularity), &req.time_range, ) .await .change_context(AnalyticsError::UnknownError); TaskType::DistributionTask(distribution.distribution_for, data) } .instrument(task_span), ); } while let Some(task_type) = set .join_next() .await .transpose() .change_context(AnalyticsError::UnknownError)? { match task_type { TaskType::MetricTask(metric, data) => { let data = data?; let attributes = router_env::metric_attributes!( ("metric_type", metric.to_string()), ("source", pool.to_string()), ); let value = u64::try_from(data.len()); if let Ok(val) = value { metrics::BUCKETS_FETCHED.record(val, attributes); logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val); } for (id, value) in data { logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}"); let metrics_builder = metrics_accumulator.entry(id).or_default(); match metric { RefundMetrics::RefundSuccessRate | RefundMetrics::SessionizedRefundSuccessRate => metrics_builder .refund_success_rate .add_metrics_bucket(&value), RefundMetrics::RefundCount | RefundMetrics::SessionizedRefundCount => { metrics_builder.refund_count.add_metrics_bucket(&value) } RefundMetrics::RefundSuccessCount | RefundMetrics::SessionizedRefundSuccessCount => { metrics_builder.refund_success.add_metrics_bucket(&value) } RefundMetrics::RefundProcessedAmount | RefundMetrics::SessionizedRefundProcessedAmount => { metrics_builder.processed_amount.add_metrics_bucket(&value) } RefundMetrics::SessionizedRefundReason => { metrics_builder.refund_reason.add_metrics_bucket(&value) } RefundMetrics::SessionizedRefundErrorMessage => metrics_builder .refund_error_message .add_metrics_bucket(&value), } } logger::debug!( "Analytics Accumulated Results: metric: {}, results: {:#?}", metric, metrics_accumulator ); } TaskType::DistributionTask(distribution, data) => { let data = data?; let attributes = router_env::metric_attributes!( ("distribution_type", distribution.to_string()), ("source", pool.to_string()), ); let value = u64::try_from(data.len()); if let Ok(val) = value { metrics::BUCKETS_FETCHED.record(val, attributes); logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val); } for (id, value) in data { logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for distribution {distribution}"); let metrics_builder = metrics_accumulator.entry(id).or_default(); match distribution { RefundDistributions::SessionizedRefundReason => metrics_builder .refund_reason_distribution .add_distribution_bucket(&value), RefundDistributions::SessionizedRefundErrorMessage => metrics_builder .refund_error_message_distribution .add_distribution_bucket(&value), } } logger::debug!( "Analytics Accumulated Results: distribution: {}, results: {:#?}", distribution, metrics_accumulator ); } } } let mut success = 0; let mut total = 0; let mut total_refund_processed_amount = 0; let mut total_refund_processed_amount_in_usd = 0; let mut total_refund_processed_count = 0; let mut total_refund_reason_count = 0; let mut total_refund_error_message_count = 0; let query_data: Vec<RefundMetricsBucketResponse> = metrics_accumulator .into_iter() .map(|(id, val)| { let mut collected_values = val.collect(); if let Some(success_count) = collected_values.successful_refunds { success += success_count; } if let Some(total_count) = collected_values.total_refunds { total += total_count; } if let Some(amount) = collected_values.refund_processed_amount { let amount_in_usd = if let Some(ex_rates) = ex_rates { id.currency .and_then(|currency| { i64::try_from(amount) .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) .ok() .and_then(|amount_i64| { convert(ex_rates, currency, Currency::USD, amount_i64) .inspect_err(|e| { logger::error!("Currency conversion error: {:?}", e) }) .ok() }) }) .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) .unwrap_or_default() } else { None }; collected_values.refund_processed_amount_in_usd = amount_in_usd; total_refund_processed_amount += amount; total_refund_processed_amount_in_usd += amount_in_usd.unwrap_or(0); } if let Some(count) = collected_values.refund_processed_count { total_refund_processed_count += count; } if let Some(total_count) = collected_values.refund_reason_count { total_refund_reason_count += total_count; } if let Some(total_count) = collected_values.refund_error_message_count { total_refund_error_message_count += total_count; } RefundMetricsBucketResponse { values: collected_values, dimensions: id, } }) .collect(); let total_refund_success_rate = match (success, total) { (s, t) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), _ => None, }; Ok(RefundsMetricsResponse { query_data, meta_data: [RefundsAnalyticsMetadata { total_refund_success_rate, total_refund_processed_amount: Some(total_refund_processed_amount), total_refund_processed_amount_in_usd: if ex_rates.is_some() { Some(total_refund_processed_amount_in_usd) } else { None }, total_refund_processed_count: Some(total_refund_processed_count), total_refund_reason_count: Some(total_refund_reason_count), total_refund_error_message_count: Some(total_refund_error_message_count), }], }) } pub async fn get_filters( pool: &AnalyticsProvider, req: GetRefundFilterRequest, auth: &AuthInfo, ) -> AnalyticsResult<RefundFiltersResponse> { let mut res = RefundFiltersResponse::default(); for dim in req.group_by_names { let values = match pool { AnalyticsProvider::Sqlx(pool) => { get_refund_filter_for_dimension(dim, auth, &req.time_range, pool) .await } AnalyticsProvider::Clickhouse(pool) => { get_refund_filter_for_dimension(dim, auth, &req.time_range, pool) .await } AnalyticsProvider::CombinedCkh(sqlx_pool, ckh_pool) => { let ckh_result = get_refund_filter_for_dimension( dim, auth, &req.time_range, ckh_pool, ) .await; let sqlx_result = get_refund_filter_for_dimension( dim, auth, &req.time_range, sqlx_pool, ) .await; match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres refunds analytics filters") }, _ => {} }; ckh_result } AnalyticsProvider::CombinedSqlx(sqlx_pool, ckh_pool) => { let ckh_result = get_refund_filter_for_dimension( dim, auth, &req.time_range, ckh_pool, ) .await; let sqlx_result = get_refund_filter_for_dimension( dim, auth, &req.time_range, sqlx_pool, ) .await; match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres refunds analytics filters") }, _ => {} }; sqlx_result } } .change_context(AnalyticsError::UnknownError)? .into_iter() .filter_map(|fil: RefundFilterRow| match dim { RefundDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()), RefundDimensions::RefundStatus => fil.refund_status.map(|i| i.as_ref().to_string()), RefundDimensions::Connector => fil.connector, RefundDimensions::RefundType => fil.refund_type.map(|i| i.as_ref().to_string()), RefundDimensions::ProfileId => fil.profile_id, RefundDimensions::RefundReason => fil.refund_reason, RefundDimensions::RefundErrorMessage => fil.refund_error_message, }) .collect::<Vec<String>>(); res.query_data.push(RefundFilterValue { dimension: dim, values, }) } Ok(res) }
crates/analytics/src/refunds/core.rs
analytics::src::refunds::core
2,857
true
// File: crates/analytics/src/refunds/distribution.rs // Module: analytics::src::refunds::distribution use api_models::analytics::{ refunds::{ RefundDimensions, RefundDistributions, RefundFilters, RefundMetricsBucketIdentifier, RefundType, }, Granularity, RefundDistributionBody, TimeRange, }; use diesel_models::enums as storage_enums; use time::PrimitiveDateTime; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, }; mod sessionized_distribution; #[derive(Debug, PartialEq, Eq, serde::Deserialize)] pub struct RefundDistributionRow { pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, pub refund_status: Option<DBEnumWrapper<storage_enums::RefundStatus>>, pub connector: Option<String>, pub refund_type: Option<DBEnumWrapper<RefundType>>, pub profile_id: Option<String>, pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, pub refund_reason: Option<String>, pub refund_error_message: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub start_bucket: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub end_bucket: Option<PrimitiveDateTime>, } pub trait RefundDistributionAnalytics: LoadRow<RefundDistributionRow> {} #[async_trait::async_trait] pub trait RefundDistribution<T> where T: AnalyticsDataSource + RefundDistributionAnalytics, { #[allow(clippy::too_many_arguments)] async fn load_distribution( &self, distribution: &RefundDistributionBody, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>>; } #[async_trait::async_trait] impl<T> RefundDistribution<T> for RefundDistributions where T: AnalyticsDataSource + RefundDistributionAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_distribution( &self, distribution: &RefundDistributionBody, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>> { match self { Self::SessionizedRefundReason => { sessionized_distribution::RefundReason .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::SessionizedRefundErrorMessage => { sessionized_distribution::RefundErrorMessage .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, pool, ) .await } } } }
crates/analytics/src/refunds/distribution.rs
analytics::src::refunds::distribution
744
true
// File: crates/analytics/src/refunds/types.rs // Module: analytics::src::refunds::types use api_models::analytics::refunds::{RefundDimensions, RefundFilters}; use error_stack::ResultExt; use crate::{ query::{QueryBuilder, QueryFilter, QueryResult, ToSql}, types::{AnalyticsCollection, AnalyticsDataSource}, }; impl<T> QueryFilter<T> for RefundFilters where T: AnalyticsDataSource, AnalyticsCollection: ToSql<T>, { fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> { if !self.currency.is_empty() { builder .add_filter_in_range_clause(RefundDimensions::Currency, &self.currency) .attach_printable("Error adding currency filter")?; } if !self.refund_status.is_empty() { builder .add_filter_in_range_clause(RefundDimensions::RefundStatus, &self.refund_status) .attach_printable("Error adding refund status filter")?; } if !self.connector.is_empty() { builder .add_filter_in_range_clause(RefundDimensions::Connector, &self.connector) .attach_printable("Error adding connector filter")?; } if !self.refund_type.is_empty() { builder .add_filter_in_range_clause(RefundDimensions::RefundType, &self.refund_type) .attach_printable("Error adding auth type filter")?; } if !self.profile_id.is_empty() { builder .add_filter_in_range_clause(RefundDimensions::ProfileId, &self.profile_id) .attach_printable("Error adding profile id filter")?; } if !self.refund_reason.is_empty() { builder .add_filter_in_range_clause(RefundDimensions::RefundReason, &self.refund_reason) .attach_printable("Error adding refund reason filter")?; } if !self.refund_error_message.is_empty() { builder .add_filter_in_range_clause( RefundDimensions::RefundErrorMessage, &self.refund_error_message, ) .attach_printable("Error adding refund error message filter")?; } Ok(()) } }
crates/analytics/src/refunds/types.rs
analytics::src::refunds::types
478
true
// File: crates/analytics/src/refunds/metrics.rs // Module: analytics::src::refunds::metrics use api_models::analytics::{ refunds::{ RefundDimensions, RefundFilters, RefundMetrics, RefundMetricsBucketIdentifier, RefundType, }, Granularity, TimeRange, }; use diesel_models::enums as storage_enums; use time::PrimitiveDateTime; mod refund_count; mod refund_processed_amount; mod refund_success_count; mod refund_success_rate; mod sessionized_metrics; use std::collections::HashSet; use refund_count::RefundCount; use refund_processed_amount::RefundProcessedAmount; use refund_success_count::RefundSuccessCount; use refund_success_rate::RefundSuccessRate; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, }; #[derive(Debug, Eq, PartialEq, serde::Deserialize, Hash)] pub struct RefundMetricRow { pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, pub refund_status: Option<DBEnumWrapper<storage_enums::RefundStatus>>, pub connector: Option<String>, pub refund_type: Option<DBEnumWrapper<RefundType>>, pub profile_id: Option<String>, pub refund_reason: Option<String>, pub refund_error_message: Option<String>, pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub start_bucket: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub end_bucket: Option<PrimitiveDateTime>, } pub trait RefundMetricAnalytics: LoadRow<RefundMetricRow> {} #[async_trait::async_trait] pub trait RefundMetric<T> where T: AnalyticsDataSource + RefundMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>>; } #[async_trait::async_trait] impl<T> RefundMetric<T> for RefundMetrics where T: AnalyticsDataSource + RefundMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { match self { Self::RefundSuccessRate => { RefundSuccessRate::default() .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::RefundCount => { RefundCount::default() .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::RefundSuccessCount => { RefundSuccessCount::default() .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::RefundProcessedAmount => { RefundProcessedAmount::default() .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedRefundSuccessRate => { sessionized_metrics::RefundSuccessRate::default() .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedRefundCount => { sessionized_metrics::RefundCount::default() .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedRefundSuccessCount => { sessionized_metrics::RefundSuccessCount::default() .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedRefundProcessedAmount => { sessionized_metrics::RefundProcessedAmount::default() .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedRefundReason => { sessionized_metrics::RefundReason .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } Self::SessionizedRefundErrorMessage => { sessionized_metrics::RefundErrorMessage .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } } } }
crates/analytics/src/refunds/metrics.rs
analytics::src::refunds::metrics
1,147
true
// File: crates/analytics/src/refunds/filters.rs // Module: analytics::src::refunds::filters use api_models::analytics::{ refunds::{RefundDimensions, RefundType}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use diesel_models::enums::{Currency, RefundStatus}; use error_stack::ResultExt; use time::PrimitiveDateTime; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{ AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, FiltersError, FiltersResult, LoadRow, }, }; pub trait RefundFilterAnalytics: LoadRow<RefundFilterRow> {} pub async fn get_refund_filter_for_dimension<T>( dimension: RefundDimensions, auth: &AuthInfo, time_range: &TimeRange, pool: &T, ) -> FiltersResult<Vec<RefundFilterRow>> where T: AnalyticsDataSource + RefundFilterAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Refund); query_builder.add_select_column(dimension).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; auth.set_filter_clause(&mut query_builder).switch()?; query_builder.set_distinct(); query_builder .execute_query::<RefundFilterRow, _>(pool) .await .change_context(FiltersError::QueryBuildingError)? .change_context(FiltersError::QueryExecutionFailure) } #[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] pub struct RefundFilterRow { pub currency: Option<DBEnumWrapper<Currency>>, pub refund_status: Option<DBEnumWrapper<RefundStatus>>, pub connector: Option<String>, pub refund_type: Option<DBEnumWrapper<RefundType>>, pub profile_id: Option<String>, pub refund_reason: Option<String>, pub refund_error_message: Option<String>, }
crates/analytics/src/refunds/filters.rs
analytics::src::refunds::filters
496
true
// File: crates/analytics/src/refunds/accumulator.rs // Module: analytics::src::refunds::accumulator use api_models::analytics::refunds::{ ErrorMessagesResult, ReasonsResult, RefundMetricsBucketValue, }; use bigdecimal::ToPrimitive; use diesel_models::enums as storage_enums; use super::{distribution::RefundDistributionRow, metrics::RefundMetricRow}; #[derive(Debug, Default)] pub struct RefundMetricsAccumulator { pub refund_success_rate: SuccessRateAccumulator, pub refund_count: CountAccumulator, pub refund_success: CountAccumulator, pub processed_amount: RefundProcessedAmountAccumulator, pub refund_reason: RefundReasonAccumulator, pub refund_reason_distribution: RefundReasonDistributionAccumulator, pub refund_error_message: RefundReasonAccumulator, pub refund_error_message_distribution: RefundErrorMessageDistributionAccumulator, } #[derive(Debug, Default)] pub struct RefundReasonDistributionRow { pub count: i64, pub total: i64, pub refund_reason: String, } #[derive(Debug, Default)] pub struct RefundReasonDistributionAccumulator { pub refund_reason_vec: Vec<RefundReasonDistributionRow>, } #[derive(Debug, Default)] pub struct RefundErrorMessageDistributionRow { pub count: i64, pub total: i64, pub refund_error_message: String, } #[derive(Debug, Default)] pub struct RefundErrorMessageDistributionAccumulator { pub refund_error_message_vec: Vec<RefundErrorMessageDistributionRow>, } #[derive(Debug, Default)] #[repr(transparent)] pub struct RefundReasonAccumulator { pub count: u64, } #[derive(Debug, Default)] pub struct SuccessRateAccumulator { pub success: u32, pub total: u32, } #[derive(Debug, Default)] #[repr(transparent)] pub struct CountAccumulator { pub count: Option<i64>, } #[derive(Debug, Default)] pub struct RefundProcessedAmountAccumulator { pub count: Option<i64>, pub total: Option<i64>, } pub trait RefundMetricAccumulator { type MetricOutput; fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow); fn collect(self) -> Self::MetricOutput; } pub trait RefundDistributionAccumulator { type DistributionOutput; fn add_distribution_bucket(&mut self, distribution: &RefundDistributionRow); fn collect(self) -> Self::DistributionOutput; } impl RefundDistributionAccumulator for RefundReasonDistributionAccumulator { type DistributionOutput = Option<Vec<ReasonsResult>>; fn add_distribution_bucket(&mut self, distribution: &RefundDistributionRow) { self.refund_reason_vec.push(RefundReasonDistributionRow { count: distribution.count.unwrap_or_default(), total: distribution .total .clone() .map(|i| i.to_i64().unwrap_or_default()) .unwrap_or_default(), refund_reason: distribution.refund_reason.clone().unwrap_or_default(), }) } fn collect(mut self) -> Self::DistributionOutput { if self.refund_reason_vec.is_empty() { None } else { self.refund_reason_vec.sort_by(|a, b| b.count.cmp(&a.count)); let mut res: Vec<ReasonsResult> = Vec::new(); for val in self.refund_reason_vec.into_iter() { let perc = f64::from(u32::try_from(val.count).ok()?) * 100.0 / f64::from(u32::try_from(val.total).ok()?); res.push(ReasonsResult { reason: val.refund_reason, count: val.count, percentage: (perc * 100.0).round() / 100.0, }) } Some(res) } } } impl RefundDistributionAccumulator for RefundErrorMessageDistributionAccumulator { type DistributionOutput = Option<Vec<ErrorMessagesResult>>; fn add_distribution_bucket(&mut self, distribution: &RefundDistributionRow) { self.refund_error_message_vec .push(RefundErrorMessageDistributionRow { count: distribution.count.unwrap_or_default(), total: distribution .total .clone() .map(|i| i.to_i64().unwrap_or_default()) .unwrap_or_default(), refund_error_message: distribution .refund_error_message .clone() .unwrap_or_default(), }) } fn collect(mut self) -> Self::DistributionOutput { if self.refund_error_message_vec.is_empty() { None } else { self.refund_error_message_vec .sort_by(|a, b| b.count.cmp(&a.count)); let mut res: Vec<ErrorMessagesResult> = Vec::new(); for val in self.refund_error_message_vec.into_iter() { let perc = f64::from(u32::try_from(val.count).ok()?) * 100.0 / f64::from(u32::try_from(val.total).ok()?); res.push(ErrorMessagesResult { error_message: val.refund_error_message, count: val.count, percentage: (perc * 100.0).round() / 100.0, }) } Some(res) } } } impl RefundMetricAccumulator for CountAccumulator { type MetricOutput = Option<u64>; #[inline] fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) { self.count = match (self.count, metrics.count) { (None, None) => None, (None, i @ Some(_)) | (i @ Some(_), None) => i, (Some(a), Some(b)) => Some(a + b), } } #[inline] fn collect(self) -> Self::MetricOutput { self.count.and_then(|i| u64::try_from(i).ok()) } } impl RefundMetricAccumulator for RefundProcessedAmountAccumulator { type MetricOutput = (Option<u64>, Option<u64>, Option<u64>); #[inline] fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) { self.total = match ( self.total, metrics.total.as_ref().and_then(ToPrimitive::to_i64), ) { (None, None) => None, (None, i @ Some(_)) | (i @ Some(_), None) => i, (Some(a), Some(b)) => Some(a + b), }; self.count = match (self.count, metrics.count) { (None, None) => None, (None, i @ Some(_)) | (i @ Some(_), None) => i, (Some(a), Some(b)) => Some(a + b), }; } #[inline] fn collect(self) -> Self::MetricOutput { let total = u64::try_from(self.total.unwrap_or_default()).ok(); let count = self.count.and_then(|i| u64::try_from(i).ok()); (total, count, Some(0)) } } impl RefundMetricAccumulator for SuccessRateAccumulator { type MetricOutput = (Option<u32>, Option<u32>, Option<f64>); fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) { if let Some(ref refund_status) = metrics.refund_status { if refund_status.as_ref() == &storage_enums::RefundStatus::Success { if let Some(success) = metrics .count .and_then(|success| u32::try_from(success).ok()) { self.success += success; } } }; if let Some(total) = metrics.count.and_then(|total| u32::try_from(total).ok()) { self.total += total; } } fn collect(self) -> Self::MetricOutput { if self.total == 0 { (None, None, None) } else { let success = Some(self.success); let total = Some(self.total); let success_rate = match (success, total) { (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), _ => None, }; (success, total, success_rate) } } } impl RefundMetricAccumulator for RefundReasonAccumulator { type MetricOutput = Option<u64>; fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) { if let Some(count) = metrics.count { if let Ok(count_u64) = u64::try_from(count) { self.count += count_u64; } } } fn collect(self) -> Self::MetricOutput { Some(self.count) } } impl RefundMetricsAccumulator { pub fn collect(self) -> RefundMetricsBucketValue { let (successful_refunds, total_refunds, refund_success_rate) = self.refund_success_rate.collect(); let (refund_processed_amount, refund_processed_count, refund_processed_amount_in_usd) = self.processed_amount.collect(); RefundMetricsBucketValue { successful_refunds, total_refunds, refund_success_rate, refund_count: self.refund_count.collect(), refund_success_count: self.refund_success.collect(), refund_processed_amount, refund_processed_amount_in_usd, refund_processed_count, refund_reason_distribution: self.refund_reason_distribution.collect(), refund_error_message_distribution: self.refund_error_message_distribution.collect(), refund_reason_count: self.refund_reason.collect(), refund_error_message_count: self.refund_error_message.collect(), } } }
crates/analytics/src/refunds/accumulator.rs
analytics::src::refunds::accumulator
2,166
true
// File: crates/analytics/src/refunds/metrics/refund_processed_amount.rs // Module: analytics::src::refunds::metrics::refund_processed_amount use std::collections::HashSet; use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::RefundMetricRow; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(super) struct RefundProcessedAmount {} #[async_trait::async_trait] impl<T> super::RefundMetric<T> for RefundProcessedAmount where T: AnalyticsDataSource + super::RefundMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> where T: AnalyticsDataSource + super::RefundMetricAnalytics, { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Refund); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Sum { field: "refund_amount", alias: Some("total"), }) .switch()?; query_builder.add_select_column("currency").switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; auth.set_filter_clause(&mut query_builder).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; for dim in dimensions.iter() { query_builder.add_group_by_clause(dim).switch()?; } query_builder.add_group_by_clause("currency").switch()?; if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; } query_builder .add_filter_clause( RefundDimensions::RefundStatus, storage_enums::RefundStatus::Success, ) .switch()?; query_builder .execute_query::<RefundMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), None, i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), i.refund_reason.clone(), i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/refunds/metrics/refund_processed_amount.rs
analytics::src::refunds::metrics::refund_processed_amount
934
true
// File: crates/analytics/src/refunds/metrics/refund_success_rate.rs // Module: analytics::src::refunds::metrics::refund_success_rate use std::collections::HashSet; use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::RefundMetricRow; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(super) struct RefundSuccessRate {} #[async_trait::async_trait] impl<T> super::RefundMetric<T> for RefundSuccessRate where T: AnalyticsDataSource + super::RefundMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> where T: AnalyticsDataSource + super::RefundMetricAnalytics, { let mut query_builder = QueryBuilder::new(AnalyticsCollection::Refund); let mut dimensions = dimensions.to_vec(); dimensions.push(RefundDimensions::RefundStatus); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; auth.set_filter_clause(&mut query_builder).switch()?; time_range.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder.add_group_by_clause(dim).switch()?; } if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; } query_builder .execute_query::<RefundMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), None, i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), i.refund_reason.clone(), i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result< HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/refunds/metrics/refund_success_rate.rs
analytics::src::refunds::metrics::refund_success_rate
877
true
// File: crates/analytics/src/refunds/metrics/sessionized_metrics.rs // Module: analytics::src::refunds::metrics::sessionized_metrics mod refund_count; mod refund_error_message; mod refund_processed_amount; mod refund_reason; mod refund_success_count; mod refund_success_rate; pub(super) use refund_count::RefundCount; pub(super) use refund_error_message::RefundErrorMessage; pub(super) use refund_processed_amount::RefundProcessedAmount; pub(super) use refund_reason::RefundReason; pub(super) use refund_success_count::RefundSuccessCount; pub(super) use refund_success_rate::RefundSuccessRate; pub use super::{RefundMetric, RefundMetricAnalytics, RefundMetricRow};
crates/analytics/src/refunds/metrics/sessionized_metrics.rs
analytics::src::refunds::metrics::sessionized_metrics
151
true
// File: crates/analytics/src/refunds/metrics/refund_success_count.rs // Module: analytics::src::refunds::metrics::refund_success_count use std::collections::HashSet; use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::RefundMetricRow; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(super) struct RefundSuccessCount {} #[async_trait::async_trait] impl<T> super::RefundMetric<T> for RefundSuccessCount where T: AnalyticsDataSource + super::RefundMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> where T: AnalyticsDataSource + super::RefundMetricAnalytics, { let mut query_builder = QueryBuilder::new(AnalyticsCollection::Refund); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; auth.set_filter_clause(&mut query_builder).switch()?; time_range.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder.add_group_by_clause(dim).switch()?; } if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; } query_builder .add_filter_clause( RefundDimensions::RefundStatus, storage_enums::RefundStatus::Success, ) .switch()?; query_builder .execute_query::<RefundMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), None, i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), i.refund_reason.clone(), i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result< HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/refunds/metrics/refund_success_count.rs
analytics::src::refunds::metrics::refund_success_count
902
true
// File: crates/analytics/src/refunds/metrics/refund_count.rs // Module: analytics::src::refunds::metrics::refund_count use std::collections::HashSet; use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::RefundMetricRow; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(super) struct RefundCount {} #[async_trait::async_trait] impl<T> super::RefundMetric<T> for RefundCount where T: AnalyticsDataSource + super::RefundMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Refund); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; auth.set_filter_clause(&mut query_builder).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; for dim in dimensions.iter() { query_builder .add_group_by_clause(dim) .attach_printable("Error grouping by dimensions") .switch()?; } if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } query_builder .execute_query::<RefundMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), i.refund_status.as_ref().map(|i| i.0.to_string()), i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), i.refund_reason.clone(), i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/refunds/metrics/refund_count.rs
analytics::src::refunds::metrics::refund_count
881
true
// File: crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs // Module: analytics::src::refunds::metrics::sessionized_metrics::refund_processed_amount use std::collections::HashSet; use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::RefundMetricRow; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(crate) struct RefundProcessedAmount {} #[async_trait::async_trait] impl<T> super::RefundMetric<T> for RefundProcessedAmount where T: AnalyticsDataSource + super::RefundMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> where T: AnalyticsDataSource + super::RefundMetricAnalytics, { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::RefundSessionized); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column(Aggregate::Sum { field: "refund_amount", alias: Some("total"), }) .switch()?; query_builder.add_select_column("currency").switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; auth.set_filter_clause(&mut query_builder).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; for dim in dimensions.iter() { query_builder.add_group_by_clause(dim).switch()?; } query_builder.add_group_by_clause("currency").switch()?; if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; } query_builder .add_filter_clause( RefundDimensions::RefundStatus, storage_enums::RefundStatus::Success, ) .switch()?; query_builder .execute_query::<RefundMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), None, i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), i.refund_reason.clone(), i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs
analytics::src::refunds::metrics::sessionized_metrics::refund_processed_amount
978
true
// File: crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs // Module: analytics::src::refunds::metrics::sessionized_metrics::refund_success_rate use std::collections::HashSet; use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::RefundMetricRow; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(crate) struct RefundSuccessRate {} #[async_trait::async_trait] impl<T> super::RefundMetric<T> for RefundSuccessRate where T: AnalyticsDataSource + super::RefundMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> where T: AnalyticsDataSource + super::RefundMetricAnalytics, { let mut query_builder = QueryBuilder::new(AnalyticsCollection::RefundSessionized); let mut dimensions = dimensions.to_vec(); dimensions.push(RefundDimensions::RefundStatus); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; auth.set_filter_clause(&mut query_builder).switch()?; time_range.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder.add_group_by_clause(dim).switch()?; } if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; } query_builder .execute_query::<RefundMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), None, i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), i.refund_reason.clone(), i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result< HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs
analytics::src::refunds::metrics::sessionized_metrics::refund_success_rate
886
true
// File: crates/analytics/src/refunds/metrics/sessionized_metrics/refund_error_message.rs // Module: analytics::src::refunds::metrics::sessionized_metrics::refund_error_message use std::collections::HashSet; use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::RefundMetricRow; use crate::{ enums::AuthInfo, query::{ Aggregate, FilterTypes, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window, }, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(crate) struct RefundErrorMessage; #[async_trait::async_trait] impl<T> super::RefundMetric<T> for RefundErrorMessage where T: AnalyticsDataSource + super::RefundMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { let mut inner_query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::RefundSessionized); inner_query_builder .add_select_column("sum(sign_flag)") .switch()?; inner_query_builder .add_custom_filter_clause( RefundDimensions::RefundErrorMessage, "NULL", FilterTypes::IsNotNull, ) .switch()?; time_range .set_filter_clause(&mut inner_query_builder) .attach_printable("Error filtering time range for inner query") .switch()?; let inner_query_string = inner_query_builder .build_query() .attach_printable("Error building inner query") .change_context(MetricsError::QueryBuildingError)?; let mut outer_query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::RefundSessionized); for dim in dimensions.iter() { outer_query_builder.add_select_column(dim).switch()?; } outer_query_builder .add_select_column("sum(sign_flag) AS count") .switch()?; outer_query_builder .add_select_column(format!("({inner_query_string}) AS total")) .switch()?; outer_query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; outer_query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters .set_filter_clause(&mut outer_query_builder) .switch()?; auth.set_filter_clause(&mut outer_query_builder).switch()?; time_range .set_filter_clause(&mut outer_query_builder) .attach_printable("Error filtering time range for outer query") .switch()?; outer_query_builder .add_filter_clause( RefundDimensions::RefundStatus, storage_enums::RefundStatus::Failure, ) .switch()?; outer_query_builder .add_custom_filter_clause( RefundDimensions::RefundErrorMessage, "NULL", FilterTypes::IsNotNull, ) .switch()?; for dim in dimensions.iter() { outer_query_builder .add_group_by_clause(dim) .attach_printable("Error grouping by dimensions") .switch()?; } if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut outer_query_builder) .attach_printable("Error adding granularity") .switch()?; } outer_query_builder .add_order_by_clause("count", Order::Descending) .attach_printable("Error adding order by clause") .switch()?; let filtered_dimensions: Vec<&RefundDimensions> = dimensions .iter() .filter(|&&dim| dim != RefundDimensions::RefundErrorMessage) .collect(); for dim in &filtered_dimensions { outer_query_builder .add_order_by_clause(*dim, Order::Ascending) .attach_printable("Error adding order by clause") .switch()?; } outer_query_builder .execute_query::<RefundMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), None, i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), i.refund_reason.clone(), i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result< HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/refunds/metrics/sessionized_metrics/refund_error_message.rs
analytics::src::refunds::metrics::sessionized_metrics::refund_error_message
1,298
true
// File: crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs // Module: analytics::src::refunds::metrics::sessionized_metrics::refund_success_count use std::collections::HashSet; use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::RefundMetricRow; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(crate) struct RefundSuccessCount {} #[async_trait::async_trait] impl<T> super::RefundMetric<T> for RefundSuccessCount where T: AnalyticsDataSource + super::RefundMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> where T: AnalyticsDataSource + super::RefundMetricAnalytics, { let mut query_builder = QueryBuilder::new(AnalyticsCollection::RefundSessionized); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; auth.set_filter_clause(&mut query_builder).switch()?; time_range.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder.add_group_by_clause(dim).switch()?; } if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .switch()?; } query_builder .add_filter_clause( RefundDimensions::RefundStatus, storage_enums::RefundStatus::Success, ) .switch()?; query_builder .execute_query::<RefundMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), None, i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), i.refund_reason.clone(), i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result< HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs
analytics::src::refunds::metrics::sessionized_metrics::refund_success_count
911
true
// File: crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs // Module: analytics::src::refunds::metrics::sessionized_metrics::refund_reason use std::collections::HashSet; use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::RefundMetricRow; use crate::{ enums::AuthInfo, query::{ Aggregate, FilterTypes, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window, }, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(crate) struct RefundReason; #[async_trait::async_trait] impl<T> super::RefundMetric<T> for RefundReason where T: AnalyticsDataSource + super::RefundMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { let mut inner_query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::RefundSessionized); inner_query_builder .add_select_column("sum(sign_flag)") .switch()?; inner_query_builder .add_custom_filter_clause( RefundDimensions::RefundReason, "NULL", FilterTypes::IsNotNull, ) .switch()?; time_range .set_filter_clause(&mut inner_query_builder) .attach_printable("Error filtering time range for inner query") .switch()?; let inner_query_string = inner_query_builder .build_query() .attach_printable("Error building inner query") .change_context(MetricsError::QueryBuildingError)?; let mut outer_query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::RefundSessionized); for dim in dimensions.iter() { outer_query_builder.add_select_column(dim).switch()?; } outer_query_builder .add_select_column("sum(sign_flag) AS count") .switch()?; outer_query_builder .add_select_column(format!("({inner_query_string}) AS total")) .switch()?; outer_query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; outer_query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters .set_filter_clause(&mut outer_query_builder) .switch()?; auth.set_filter_clause(&mut outer_query_builder).switch()?; time_range .set_filter_clause(&mut outer_query_builder) .attach_printable("Error filtering time range for outer query") .switch()?; outer_query_builder .add_custom_filter_clause( RefundDimensions::RefundReason, "NULL", FilterTypes::IsNotNull, ) .switch()?; for dim in dimensions.iter() { outer_query_builder .add_group_by_clause(dim) .attach_printable("Error grouping by dimensions") .switch()?; } if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut outer_query_builder) .attach_printable("Error adding granularity") .switch()?; } outer_query_builder .add_order_by_clause("count", Order::Descending) .attach_printable("Error adding order by clause") .switch()?; let filtered_dimensions: Vec<&RefundDimensions> = dimensions .iter() .filter(|&&dim| dim != RefundDimensions::RefundReason) .collect(); for dim in &filtered_dimensions { outer_query_builder .add_order_by_clause(*dim, Order::Ascending) .attach_printable("Error adding order by clause") .switch()?; } outer_query_builder .execute_query::<RefundMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), None, i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), i.refund_reason.clone(), i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result< HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs
analytics::src::refunds::metrics::sessionized_metrics::refund_reason
1,248
true
// File: crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs // Module: analytics::src::refunds::metrics::sessionized_metrics::refund_count use std::collections::HashSet; use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::RefundMetricRow; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(crate) struct RefundCount {} #[async_trait::async_trait] impl<T> super::RefundMetric<T> for RefundCount where T: AnalyticsDataSource + super::RefundMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::RefundSessionized); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; auth.set_filter_clause(&mut query_builder).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; for dim in dimensions.iter() { query_builder .add_group_by_clause(dim) .attach_printable("Error grouping by dimensions") .switch()?; } if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } query_builder .execute_query::<RefundMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), i.refund_status.as_ref().map(|i| i.0.to_string()), i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), i.refund_reason.clone(), i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs
analytics::src::refunds::metrics::sessionized_metrics::refund_count
891
true
// File: crates/analytics/src/refunds/distribution/sessionized_distribution.rs // Module: analytics::src::refunds::distribution::sessionized_distribution mod refund_error_message; mod refund_reason; pub(super) use refund_error_message::RefundErrorMessage; pub(super) use refund_reason::RefundReason; pub use super::{RefundDistribution, RefundDistributionAnalytics, RefundDistributionRow};
crates/analytics/src/refunds/distribution/sessionized_distribution.rs
analytics::src::refunds::distribution::sessionized_distribution
82
true
// File: crates/analytics/src/refunds/distribution/sessionized_distribution/refund_error_message.rs // Module: analytics::src::refunds::distribution::sessionized_distribution::refund_error_message use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, RefundDistributionBody, TimeRange, }; use common_utils::errors::ReportSwitchExt; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::{RefundDistribution, RefundDistributionRow}; use crate::{ enums::AuthInfo, query::{ Aggregate, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window, }, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(crate) struct RefundErrorMessage; #[async_trait::async_trait] impl<T> RefundDistribution<T> for RefundErrorMessage where T: AnalyticsDataSource + super::RefundDistributionAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_distribution( &self, distribution: &RefundDistributionBody, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::RefundSessionized); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(&distribution.distribution_for) .switch()?; query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; auth.set_filter_clause(&mut query_builder).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; query_builder .add_filter_clause( RefundDimensions::RefundStatus, storage_enums::RefundStatus::Failure, ) .switch()?; for dim in dimensions.iter() { query_builder .add_group_by_clause(dim) .attach_printable("Error grouping by dimensions") .switch()?; } query_builder .add_group_by_clause(&distribution.distribution_for) .attach_printable("Error grouping by distribution_for") .switch()?; if let Some(granularity) = granularity.as_ref() { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } for dim in dimensions.iter() { query_builder.add_outer_select_column(dim).switch()?; } query_builder .add_outer_select_column(&distribution.distribution_for) .switch()?; query_builder.add_outer_select_column("count").switch()?; query_builder .add_outer_select_column("start_bucket") .switch()?; query_builder .add_outer_select_column("end_bucket") .switch()?; let sql_dimensions = query_builder.transform_to_sql_values(dimensions).switch()?; query_builder .add_outer_select_column(Window::Sum { field: "count", partition_by: Some(sql_dimensions), order_by: None, alias: Some("total"), }) .switch()?; query_builder .add_top_n_clause( dimensions, distribution.distribution_cardinality.into(), "count", Order::Descending, ) .switch()?; query_builder .execute_query::<RefundDistributionRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), i.refund_status.as_ref().map(|i| i.0.to_string()), i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), i.refund_reason.clone(), i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result< Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/refunds/distribution/sessionized_distribution/refund_error_message.rs
analytics::src::refunds::distribution::sessionized_distribution::refund_error_message
1,217
true
// File: crates/analytics/src/refunds/distribution/sessionized_distribution/refund_reason.rs // Module: analytics::src::refunds::distribution::sessionized_distribution::refund_reason use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, RefundDistributionBody, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::{RefundDistribution, RefundDistributionRow}; use crate::{ enums::AuthInfo, query::{ Aggregate, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window, }, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(crate) struct RefundReason; #[async_trait::async_trait] impl<T> RefundDistribution<T> for RefundReason where T: AnalyticsDataSource + super::RefundDistributionAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_distribution( &self, distribution: &RefundDistributionBody, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::RefundSessionized); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(&distribution.distribution_for) .switch()?; query_builder .add_select_column(Aggregate::Count { field: None, alias: Some("count"), }) .switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; auth.set_filter_clause(&mut query_builder).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; for dim in dimensions.iter() { query_builder .add_group_by_clause(dim) .attach_printable("Error grouping by dimensions") .switch()?; } query_builder .add_group_by_clause(&distribution.distribution_for) .attach_printable("Error grouping by distribution_for") .switch()?; if let Some(granularity) = granularity.as_ref() { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } for dim in dimensions.iter() { query_builder.add_outer_select_column(dim).switch()?; } query_builder .add_outer_select_column(&distribution.distribution_for) .switch()?; query_builder.add_outer_select_column("count").switch()?; query_builder .add_outer_select_column("start_bucket") .switch()?; query_builder .add_outer_select_column("end_bucket") .switch()?; let sql_dimensions = query_builder.transform_to_sql_values(dimensions).switch()?; query_builder .add_outer_select_column(Window::Sum { field: "count", partition_by: Some(sql_dimensions), order_by: None, alias: Some("total"), }) .switch()?; query_builder .add_top_n_clause( dimensions, distribution.distribution_cardinality.into(), "count", Order::Descending, ) .switch()?; query_builder .execute_query::<RefundDistributionRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), i.refund_status.as_ref().map(|i| i.0.to_string()), i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), i.refund_reason.clone(), i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result< Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/refunds/distribution/sessionized_distribution/refund_reason.rs
analytics::src::refunds::distribution::sessionized_distribution::refund_reason
1,168
true
// File: crates/hyperswitch_interfaces/src/consts.rs // Module: hyperswitch_interfaces::src::consts //! connector integration related const declarations /// No error message string const pub const NO_ERROR_MESSAGE: &str = "No error message"; /// No error code string const pub const NO_ERROR_CODE: &str = "No error code"; /// Accepted format for request pub const ACCEPT_HEADER: &str = "text/html,application/json"; /// User agent for request send from backend server pub const USER_AGENT: &str = "Hyperswitch-Backend-Server"; /// Request timeout error code pub const REQUEST_TIMEOUT_ERROR_CODE: &str = "TIMEOUT"; /// error message for timed out request pub const REQUEST_TIMEOUT_ERROR_MESSAGE: &str = "Connector did not respond in specified time"; /// Header value indicating that signature-key-based authentication is used. pub const UCS_AUTH_SIGNATURE_KEY: &str = "signature-key"; /// Header value indicating that body-key-based authentication is used. pub const UCS_AUTH_BODY_KEY: &str = "body-key"; /// Header value indicating that header-key-based authentication is used. pub const UCS_AUTH_HEADER_KEY: &str = "header-key"; /// Header value indicating that currency-auth-key-based authentication is used. pub const UCS_AUTH_CURRENCY_AUTH_KEY: &str = "currency-auth-key";
crates/hyperswitch_interfaces/src/consts.rs
hyperswitch_interfaces::src::consts
277
true
// File: crates/hyperswitch_interfaces/src/types.rs // Module: hyperswitch_interfaces::src::types //! Types interface use hyperswitch_domain_models::{ router_data::{AccessToken, AccessTokenAuthenticationResponse}, router_data_v2::flow_common_types, router_flow_types::{ access_token_auth::AccessTokenAuth, dispute::{Accept, Defend, Dsync, Evidence, Fetch}, files::{Retrieve, Upload}, mandate_revoke::MandateRevoke, payments::{ Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, ExtendAuthorization, IncrementalAuthorization, InitPayment, PSync, PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, refunds::{Execute, RSync}, revenue_recovery::{BillingConnectorPaymentsSync, InvoiceRecordBack}, subscriptions::{ GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate, }, unified_authentication_service::{ Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, }, vault::{ ExternalVaultCreateFlow, ExternalVaultDeleteFlow, ExternalVaultInsertFlow, ExternalVaultRetrieveFlow, }, webhooks::VerifyWebhookSource, AccessTokenAuthentication, BillingConnectorInvoiceSync, GiftCardBalanceCheck, }, router_request_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, InvoiceRecordBackRequest, }, subscriptions::{ GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, SubscriptionCreateRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, DisputeSyncData, FetchDisputesRequestData, GiftCardBalanceCheckRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, SubmitEvidenceRequestData, UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, InvoiceRecordBackResponse, }, subscriptions::{ GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, GiftCardBalanceCheckResponseData, MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, TaxCalculationResponseData, UploadFileResponse, VaultResponseData, VerifyWebhookSourceResponseData, }, }; #[cfg(feature = "payouts")] use hyperswitch_domain_models::{ router_flow_types::payouts::{ PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, }, router_request_types::PayoutsData, router_response_types::PayoutsResponseData, }; use crate::{api::ConnectorIntegration, connector_integration_v2::ConnectorIntegrationV2}; /// struct Response #[derive(Clone, Debug)] pub struct Response { /// headers pub headers: Option<http::HeaderMap>, /// response pub response: bytes::Bytes, /// status code pub status_code: u16, } /// Type alias for `ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>` pub type PaymentsAuthorizeType = dyn ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>` pub type PaymentsTaxCalculationType = dyn ConnectorIntegration<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>; /// Type alias for `ConnectorIntegration<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>` pub type PaymentsPostSessionTokensType = dyn ConnectorIntegration< PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData, >; /// Type alias for `ConnectorIntegration<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>` pub type PaymentsUpdateMetadataType = dyn ConnectorIntegration<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>` pub type SdkSessionUpdateType = dyn ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>` pub type SetupMandateType = dyn ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>` pub type MandateRevokeType = dyn ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>; /// Type alias for `ConnectorIntegration<CreateOrder, CreateOrderRequestData, PaymentsResponseData>` pub type CreateOrderType = dyn ConnectorIntegration<CreateOrder, CreateOrderRequestData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>` pub type PaymentsPreProcessingType = dyn ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>` pub type PaymentsPreAuthenticateType = dyn ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<Authenticate, PaymentsAuthenticateData, PaymentsResponseData>` pub type PaymentsAuthenticateType = dyn ConnectorIntegration<Authenticate, PaymentsAuthenticateData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData>` pub type PaymentsPostAuthenticateType = dyn ConnectorIntegration<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>` pub type PaymentsPostProcessingType = dyn ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>` pub type PaymentsCompleteAuthorizeType = dyn ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>` pub type PaymentsPreAuthorizeType = dyn ConnectorIntegration< AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData, >; /// Type alias for `ConnectorIntegration<GiftCardBalanceCheck, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData>` pub type PaymentsGiftCardBalanceCheckType = dyn ConnectorIntegration< GiftCardBalanceCheck, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData, >; /// Type alias for `ConnectorIntegration<InitPayment, PaymentsAuthorizeData, PaymentsResponseData>` pub type PaymentsInitType = dyn ConnectorIntegration<InitPayment, PaymentsAuthorizeData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<Balance, PaymentsAuthorizeData, PaymentsResponseData` pub type PaymentsBalanceType = dyn ConnectorIntegration<Balance, PaymentsAuthorizeData, PaymentsResponseData>; /// Type alias for `PaymentsSyncType = dyn ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData>` pub type PaymentsSyncType = dyn ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData>` pub type PaymentsCaptureType = dyn ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData>` pub type PaymentsSessionType = dyn ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData>` pub type PaymentsVoidType = dyn ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>` pub type PaymentsPostCaptureVoidType = dyn ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>` pub type TokenizationType = dyn ConnectorIntegration< PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData, >; /// Type alias for `ConnectorIntegration<IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData>` pub type IncrementalAuthorizationType = dyn ConnectorIntegration< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, >; /// Type alias for `ConnectorIntegration<ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData>` pub type ExtendedAuthorizationType = dyn ConnectorIntegration< ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData, >; /// Type alias for ConnectorIntegration<GetSubscriptionPlanPrices, GetSubscriptionPlanPricesRequest, GetSubscriptionPlanPricesResponse> pub type GetSubscriptionPlanPricesType = dyn ConnectorIntegration< GetSubscriptionPlanPrices, GetSubscriptionPlanPricesRequest, GetSubscriptionPlanPricesResponse, >; /// Type alias for `ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>` pub type ConnectorCustomerType = dyn ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<Execute, RefundsData, RefundsResponseData>` pub type RefundExecuteType = dyn ConnectorIntegration<Execute, RefundsData, RefundsResponseData>; /// Type alias for `ConnectorIntegration<RSync, RefundsData, RefundsResponseData>` pub type RefundSyncType = dyn ConnectorIntegration<RSync, RefundsData, RefundsResponseData>; /// Type alias for `ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutCancelType = dyn ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData>; /// Type alias for `ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutCreateType = dyn ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData>; /// Type alias for `ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutEligibilityType = dyn ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData>; /// Type alias for `ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutFulfillType = dyn ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData>; /// Type alias for `ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutRecipientType = dyn ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData>; /// Type alias for `ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutRecipientAccountType = dyn ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData>; /// Type alias for `ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutQuoteType = dyn ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData>; /// Type alias for `ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutSyncType = dyn ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData>; /// Type alias for `ConnectorIntegration<AccessTokenAuthentication, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse>` pub type AuthenticationTokenType = dyn ConnectorIntegration< AccessTokenAuthentication, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse, >; /// Type alias for `ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>` pub type RefreshTokenType = dyn ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>; /// Type alias for `ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>` pub type AcceptDisputeType = dyn ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>; /// Type alias for `ConnectorIntegration<VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData>` pub type VerifyWebhookSourceType = dyn ConnectorIntegration< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, >; /// Type alias for `ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>` pub type SubmitEvidenceType = dyn ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>; /// Type alias for `ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse>` pub type UploadFileType = dyn ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse>; /// Type alias for `ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>` pub type RetrieveFileType = dyn ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>; /// Type alias for `ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse>` pub type DefendDisputeType = dyn ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse>; /// Type alias for `ConnectorIntegration<Fetch, FetchDisputesRequestData, FetchDisputesResponse>` pub type FetchDisputesType = dyn ConnectorIntegration<Fetch, FetchDisputesRequestData, FetchDisputesResponse>; /// Type alias for `ConnectorIntegration<Dsync, DisputeSyncData, DisputeSyncResponse>` pub type DisputeSyncType = dyn ConnectorIntegration<Dsync, DisputeSyncData, DisputeSyncResponse>; /// Type alias for `ConnectorIntegration<PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData>` pub type UasPreAuthenticationType = dyn ConnectorIntegration< PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData, >; /// Type alias for `ConnectorIntegration<PostAuthenticate, UasPostAuthenticationRequestData, UasAuthenticationResponseData>` pub type UasPostAuthenticationType = dyn ConnectorIntegration< PostAuthenticate, UasPostAuthenticationRequestData, UasAuthenticationResponseData, >; /// Type alias for `ConnectorIntegration<Confirmation, UasConfirmationRequestData, UasAuthenticationResponseData>` pub type UasAuthenticationConfirmationType = dyn ConnectorIntegration< AuthenticationConfirmation, UasConfirmationRequestData, UasAuthenticationResponseData, >; /// Type alias for `ConnectorIntegration<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData>` pub type UasAuthenticationType = dyn ConnectorIntegration< Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData, >; /// Type alias for `ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse>` pub type InvoiceRecordBackType = dyn ConnectorIntegration< InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse, >; /// Type alias for `ConnectorIntegration<SubscriptionCreate, SubscriptionCreateRequest, SubscriptionCreateResponse>` pub type SubscriptionCreateType = dyn ConnectorIntegration< SubscriptionCreate, SubscriptionCreateRequest, SubscriptionCreateResponse, >; /// Type alias for `ConnectorIntegration<BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse>` pub type BillingConnectorPaymentsSyncType = dyn ConnectorIntegration< BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, >; /// Type alias for `ConnectorIntegration<BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse>` pub type BillingConnectorInvoiceSyncType = dyn ConnectorIntegration< BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, >; /// Type alias for `ConnectorIntegrationV2<InvoiceRecordBack, InvoiceRecordBackData, InvoiceRecordBackRequest, InvoiceRecordBackResponse>` pub type InvoiceRecordBackTypeV2 = dyn ConnectorIntegrationV2< InvoiceRecordBack, flow_common_types::InvoiceRecordBackData, InvoiceRecordBackRequest, InvoiceRecordBackResponse, >; /// Type alias for `ConnectorIntegrationV2<BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse>` pub type BillingConnectorPaymentsSyncTypeV2 = dyn ConnectorIntegrationV2< BillingConnectorPaymentsSync, flow_common_types::BillingConnectorPaymentsSyncFlowData, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, >; /// Type alias for `ConnectorIntegrationV2<BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncFlowData, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse>` pub type BillingConnectorInvoiceSyncTypeV2 = dyn ConnectorIntegrationV2< BillingConnectorInvoiceSync, flow_common_types::BillingConnectorInvoiceSyncFlowData, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, >; /// Type alias for `ConnectorIntegration<GetSubscriptionPlans, GetSubscriptionPlansRequest, GetSubscriptionPlansResponse>` pub type GetSubscriptionPlansType = dyn ConnectorIntegration< GetSubscriptionPlans, GetSubscriptionPlansRequest, GetSubscriptionPlansResponse, >; /// Type alias for `ConnectorIntegration<GetSubscriptionEstimate, GetSubscriptionEstimateRequest, GetSubscriptionEstimateResponse>` pub type GetSubscriptionEstimateType = dyn ConnectorIntegration< GetSubscriptionEstimate, GetSubscriptionEstimateRequest, GetSubscriptionEstimateResponse, >; /// Type alias for `ConnectorIntegration<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData>` pub type ExternalVaultInsertType = dyn ConnectorIntegration<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData>; /// Type alias for `ConnectorIntegration<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData>` pub type ExternalVaultRetrieveType = dyn ConnectorIntegration<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData>; /// Type alias for `ConnectorIntegration<ExternalVaultDeleteFlow, VaultRequestData, VaultResponseData>` pub type ExternalVaultDeleteType = dyn ConnectorIntegration<ExternalVaultDeleteFlow, VaultRequestData, VaultResponseData>; /// Type alias for `ConnectorIntegration<ExternalVaultCreateFlow, VaultRequestData, VaultResponseData>` pub type ExternalVaultCreateType = dyn ConnectorIntegration<ExternalVaultCreateFlow, VaultRequestData, VaultResponseData>; /// Proxy configuration structure #[derive(Debug, serde::Deserialize, Clone)] #[serde(default)] pub struct Proxy { /// The URL of the HTTP proxy server. pub http_url: Option<String>, /// The URL of the HTTPS proxy server. pub https_url: Option<String>, /// The timeout duration (in seconds) for idle connections in the proxy pool. pub idle_pool_connection_timeout: Option<u64>, /// A comma-separated list of hosts that should bypass the proxy. pub bypass_proxy_hosts: Option<String>, /// The CA certificate used for man-in-the-middle (MITM) proxying, if enabled. pub mitm_ca_certificate: Option<masking::Secret<String>>, /// Whether man-in-the-middle (MITM) proxying is enabled. pub mitm_enabled: Option<bool>, } impl Default for Proxy { fn default() -> Self { Self { http_url: Default::default(), https_url: Default::default(), idle_pool_connection_timeout: Some(90), bypass_proxy_hosts: Default::default(), mitm_ca_certificate: None, mitm_enabled: None, } } } /// Type alias for `ConnectorIntegrationV2<CreateConnectorCustomer, PaymentFlowData, ConnectorCustomerData, PaymentsResponseData>` pub type CreateCustomerTypeV2 = dyn ConnectorIntegrationV2< CreateConnectorCustomer, flow_common_types::PaymentFlowData, ConnectorCustomerData, PaymentsResponseData, >;
crates/hyperswitch_interfaces/src/types.rs
hyperswitch_interfaces::src::types
4,461
true
// File: crates/hyperswitch_interfaces/src/secrets_interface.rs // Module: hyperswitch_interfaces::src::secrets_interface //! Secrets management interface pub mod secret_handler; pub mod secret_state; use common_utils::errors::CustomResult; use masking::Secret; /// Trait defining the interface for managing application secrets #[async_trait::async_trait] pub trait SecretManagementInterface: Send + Sync { /* /// Given an input, encrypt/store the secret async fn store_secret( &self, input: Secret<String>, ) -> CustomResult<String, SecretsManagementError>; */ /// Given an input, decrypt/retrieve the secret async fn get_secret( &self, input: Secret<String>, ) -> CustomResult<Secret<String>, SecretsManagementError>; } /// Errors that may occur during secret management #[derive(Debug, thiserror::Error)] pub enum SecretsManagementError { /// An error occurred when retrieving raw data. #[error("Failed to fetch the raw data")] FetchSecretFailed, /// Failed while creating kms client #[error("Failed while creating a secrets management client")] ClientCreationFailed, }
crates/hyperswitch_interfaces/src/secrets_interface.rs
hyperswitch_interfaces::src::secrets_interface
244
true
// File: crates/hyperswitch_interfaces/src/crm.rs // Module: hyperswitch_interfaces::src::crm use common_enums::CountryAlpha2; use common_utils::{ errors::CustomResult, request::{Request, RequestContent}, }; use masking::Secret; use super::types::Proxy; use crate::errors::HttpClientError; /// Crm Payload structure #[derive(Clone, Debug, serde::Serialize, Default)] pub struct CrmPayload { /// The legal name of the business. pub legal_business_name: Option<String>, /// A label or tag associated with the business. pub business_label: Option<String>, /// The location of the business, represented as a country code (ISO Alpha-2 format). pub business_location: Option<CountryAlpha2>, /// The display name of the business. pub display_name: Option<String>, /// The email address of the point of contact (POC) for the business. pub poc_email: Option<Secret<String>>, /// The type of business (e.g., LLC, Corporation, etc.). pub business_type: Option<String>, /// A unique identifier for the business. pub business_identifier: Option<String>, /// The website URL of the business. pub business_website: Option<String>, /// The name of the point of contact (POC) for the business. pub poc_name: Option<Secret<String>>, /// The contact number of the point of contact (POC) for the business. pub poc_contact: Option<Secret<String>>, /// Additional comments or notes about the business. pub comments: Option<String>, /// Indicates whether the Crm process for the business is completed. pub is_completed: bool, /// The name of the country where the business is located. pub business_country_name: Option<String>, } /// Trait defining the interface for encryption management #[async_trait::async_trait] pub trait CrmInterface: Send + Sync { /// Make body for the request async fn make_body(&self, details: CrmPayload) -> RequestContent; /// Encrypt the given input data async fn make_request(&self, body: RequestContent, origin_base_url: String) -> Request; /// Decrypt the given input data async fn send_request( &self, proxy: &Proxy, request: Request, ) -> CustomResult<reqwest::Response, HttpClientError>; }
crates/hyperswitch_interfaces/src/crm.rs
hyperswitch_interfaces::src::crm
522
true
// File: crates/hyperswitch_interfaces/src/events.rs // Module: hyperswitch_interfaces::src::events use crate::events::connector_api_logs::ConnectorEvent; pub mod connector_api_logs; pub mod routing_api_logs; /// Event handling interface #[async_trait::async_trait] pub trait EventHandlerInterface: dyn_clone::DynClone where Self: Send + Sync, { /// Logs connector events #[track_caller] fn log_connector_event(&self, event: &ConnectorEvent); }
crates/hyperswitch_interfaces/src/events.rs
hyperswitch_interfaces::src::events
108
true
// File: crates/hyperswitch_interfaces/src/configs.rs // Module: hyperswitch_interfaces::src::configs use common_utils::{crypto::Encryptable, errors::CustomResult, id_type}; pub use hyperswitch_domain_models::{ connector_endpoints::Connectors, errors::api_error_response, merchant_connector_account, }; use masking::{PeekInterface, Secret}; use serde::Deserialize; #[allow(missing_docs)] #[derive(Debug, Clone)] pub struct Tenant { pub tenant_id: id_type::TenantId, pub base_url: String, pub schema: String, pub accounts_schema: String, pub redis_key_prefix: String, pub clickhouse_database: String, pub user: TenantUserConfig, } #[allow(missing_docs)] #[derive(Debug, Deserialize, Clone)] pub struct TenantUserConfig { pub control_center_url: String, } impl common_utils::types::TenantConfig for Tenant { fn get_tenant_id(&self) -> &id_type::TenantId { &self.tenant_id } fn get_accounts_schema(&self) -> &str { self.accounts_schema.as_str() } fn get_schema(&self) -> &str { self.schema.as_str() } fn get_redis_key_prefix(&self) -> &str { self.redis_key_prefix.as_str() } fn get_clickhouse_database(&self) -> &str { self.clickhouse_database.as_str() } } #[allow(missing_docs)] // Todo: Global tenant should not be part of tenant config(https://github.com/juspay/hyperswitch/issues/7237) #[derive(Debug, Deserialize, Clone)] pub struct GlobalTenant { #[serde(default = "id_type::TenantId::get_default_global_tenant_id")] pub tenant_id: id_type::TenantId, pub schema: String, pub redis_key_prefix: String, pub clickhouse_database: String, } // Todo: Global tenant should not be part of tenant config impl common_utils::types::TenantConfig for GlobalTenant { fn get_tenant_id(&self) -> &id_type::TenantId { &self.tenant_id } fn get_accounts_schema(&self) -> &str { self.schema.as_str() } fn get_schema(&self) -> &str { self.schema.as_str() } fn get_redis_key_prefix(&self) -> &str { self.redis_key_prefix.as_str() } fn get_clickhouse_database(&self) -> &str { self.clickhouse_database.as_str() } } impl Default for GlobalTenant { fn default() -> Self { Self { tenant_id: id_type::TenantId::get_default_global_tenant_id(), schema: String::from("global"), redis_key_prefix: String::from("global"), clickhouse_database: String::from("global"), } } } #[allow(missing_docs)] #[derive(Debug, Clone, Default, Deserialize)] #[serde(default)] pub struct InternalMerchantIdProfileIdAuthSettings { pub enabled: bool, pub internal_api_key: Secret<String>, } #[allow(missing_docs)] #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct InternalServicesConfig { pub payments_base_url: String, } #[allow(missing_docs)] #[derive(Debug, Clone)] pub enum MerchantConnectorAccountType { DbVal(Box<merchant_connector_account::MerchantConnectorAccount>), CacheVal(api_models::admin::MerchantConnectorDetails), } #[allow(missing_docs)] impl MerchantConnectorAccountType { pub fn get_metadata(&self) -> Option<Secret<serde_json::Value>> { match self { Self::DbVal(val) => val.metadata.to_owned(), Self::CacheVal(val) => val.metadata.to_owned(), } } pub fn get_connector_account_details(&self) -> serde_json::Value { match self { Self::DbVal(val) => val.connector_account_details.peek().to_owned(), Self::CacheVal(val) => val.connector_account_details.peek().to_owned(), } } pub fn get_connector_wallets_details(&self) -> Option<Secret<serde_json::Value>> { match self { Self::DbVal(val) => val.connector_wallets_details.as_deref().cloned(), Self::CacheVal(_) => None, } } pub fn is_disabled(&self) -> bool { match self { Self::DbVal(ref inner) => inner.disabled.unwrap_or(false), // Cached merchant connector account, only contains the account details, // the merchant connector account must only be cached if it's not disabled Self::CacheVal(_) => false, } } #[cfg(feature = "v1")] pub fn is_test_mode_on(&self) -> Option<bool> { match self { Self::DbVal(val) => val.test_mode, Self::CacheVal(_) => None, } } #[cfg(feature = "v2")] pub fn is_test_mode_on(&self) -> Option<bool> { None } pub fn get_mca_id(&self) -> Option<id_type::MerchantConnectorAccountId> { match self { Self::DbVal(db_val) => Some(db_val.get_id()), Self::CacheVal(_) => None, } } #[cfg(feature = "v1")] pub fn get_connector_name(&self) -> Option<String> { match self { Self::DbVal(db_val) => Some(db_val.connector_name.to_string()), Self::CacheVal(_) => None, } } #[cfg(feature = "v2")] pub fn get_connector_name(&self) -> Option<common_enums::connector_enums::Connector> { match self { Self::DbVal(db_val) => Some(db_val.connector_name), Self::CacheVal(_) => None, } } pub fn get_additional_merchant_data(&self) -> Option<Encryptable<Secret<serde_json::Value>>> { match self { Self::DbVal(db_val) => db_val.additional_merchant_data.clone(), Self::CacheVal(_) => None, } } pub fn get_webhook_details( &self, ) -> CustomResult<Option<&Secret<serde_json::Value>>, api_error_response::ApiErrorResponse> { match self { Self::DbVal(db_val) => Ok(db_val.connector_webhook_details.as_ref()), Self::CacheVal(_) => Ok(None), } } }
crates/hyperswitch_interfaces/src/configs.rs
hyperswitch_interfaces::src::configs
1,385
true
// File: crates/hyperswitch_interfaces/src/lib.rs // Module: hyperswitch_interfaces::src::lib //! Hyperswitch interface #![warn(missing_docs, missing_debug_implementations)] pub mod api; /// API client interface module pub mod api_client; pub mod authentication; /// Configuration related functionalities pub mod configs; /// Connector integration interface module pub mod connector_integration_interface; /// definition of the new connector integration trait pub mod connector_integration_v2; /// Constants used throughout the application pub mod consts; /// Conversion implementations pub mod conversion_impls; pub mod disputes; pub mod encryption_interface; pub mod errors; /// Event handling interface pub mod events; /// helper utils pub mod helpers; /// connector integrity check interface pub mod integrity; pub mod metrics; pub mod secrets_interface; pub mod types; /// ucs handlers pub mod unified_connector_service; pub mod webhooks; /// Crm interface pub mod crm;
crates/hyperswitch_interfaces/src/lib.rs
hyperswitch_interfaces::src::lib
198
true
// File: crates/hyperswitch_interfaces/src/disputes.rs // Module: hyperswitch_interfaces::src::disputes //! Disputes interface use common_utils::types::StringMinorUnit; use hyperswitch_domain_models::router_response_types::DisputeSyncResponse; use time::PrimitiveDateTime; /// struct DisputePayload #[derive(Default, Debug)] pub struct DisputePayload { /// amount pub amount: StringMinorUnit, /// currency pub currency: common_enums::enums::Currency, /// dispute_stage pub dispute_stage: common_enums::enums::DisputeStage, /// connector_status pub connector_status: String, /// connector_dispute_id pub connector_dispute_id: String, /// connector_reason pub connector_reason: Option<String>, /// connector_reason_code pub connector_reason_code: Option<String>, /// challenge_required_by pub challenge_required_by: Option<PrimitiveDateTime>, /// created_at pub created_at: Option<PrimitiveDateTime>, /// updated_at pub updated_at: Option<PrimitiveDateTime>, } impl From<DisputeSyncResponse> for DisputePayload { fn from(dispute_sync_data: DisputeSyncResponse) -> Self { Self { amount: dispute_sync_data.amount, currency: dispute_sync_data.currency, dispute_stage: dispute_sync_data.dispute_stage, connector_status: dispute_sync_data.connector_status, connector_dispute_id: dispute_sync_data.connector_dispute_id, connector_reason: dispute_sync_data.connector_reason, connector_reason_code: dispute_sync_data.connector_reason_code, challenge_required_by: dispute_sync_data.challenge_required_by, created_at: dispute_sync_data.created_at, updated_at: dispute_sync_data.updated_at, } } }
crates/hyperswitch_interfaces/src/disputes.rs
hyperswitch_interfaces::src::disputes
378
true
// File: crates/hyperswitch_interfaces/src/conversion_impls.rs // Module: hyperswitch_interfaces::src::conversion_impls use common_utils::{errors::CustomResult, id_type}; use error_stack::ResultExt; #[cfg(feature = "frm")] use hyperswitch_domain_models::router_data_v2::flow_common_types::FrmFlowData; #[cfg(feature = "payouts")] use hyperswitch_domain_models::router_data_v2::flow_common_types::PayoutFlowData; use hyperswitch_domain_models::{ payment_address::PaymentAddress, router_data::{self, RouterData}, router_data_v2::{ flow_common_types::{ AccessTokenFlowData, AuthenticationTokenFlowData, BillingConnectorInvoiceSyncFlowData, BillingConnectorPaymentsSyncFlowData, DisputesFlowData, ExternalAuthenticationFlowData, ExternalVaultProxyFlowData, FilesFlowData, GetSubscriptionEstimateData, GetSubscriptionPlanPricesData, GetSubscriptionPlansData, GiftCardBalanceCheckFlowData, InvoiceRecordBackData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData, SubscriptionCreateData, SubscriptionCustomerData, UasFlowData, VaultConnectorFlowData, WebhookSourceVerifyData, }, RouterDataV2, }, }; use crate::{connector_integration_interface::RouterDataConversion, errors::ConnectorError}; fn get_irrelevant_id_string(id_name: &str, flow_name: &str) -> String { format!("irrelevant {id_name} in {flow_name} flow") } fn get_default_router_data<F, Req, Resp>( tenant_id: id_type::TenantId, flow_name: &str, request: Req, response: Result<Resp, router_data::ErrorResponse>, ) -> RouterData<F, Req, Resp> { RouterData { tenant_id, flow: std::marker::PhantomData, merchant_id: id_type::MerchantId::get_irrelevant_merchant_id(), customer_id: None, connector_customer: None, connector: get_irrelevant_id_string("connector", flow_name), payment_id: id_type::PaymentId::get_irrelevant_id(flow_name) .get_string_repr() .to_owned(), attempt_id: get_irrelevant_id_string("attempt_id", flow_name), status: common_enums::AttemptStatus::default(), payment_method: common_enums::PaymentMethod::default(), connector_auth_type: router_data::ConnectorAuthType::default(), description: None, address: PaymentAddress::default(), auth_type: common_enums::AuthenticationType::default(), connector_meta_data: None, connector_wallets_details: None, amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, connector_api_version: None, request, response, connector_request_reference_id: get_irrelevant_id_string( "connector_request_reference_id", flow_name, ), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, dispute_id: None, refund_id: None, connector_response: None, payment_method_status: None, minor_amount_captured: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, payment_method_type: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for AuthenticationTokenFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self {}; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self {} = new_router_data.resource_common_data; let request = new_router_data.request.clone(); let response = new_router_data.response.clone(); let router_data = get_default_router_data( new_router_data.tenant_id.clone(), "authentication token", request, response, ); Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for AccessTokenFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self {}; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self {} = new_router_data.resource_common_data; let request = new_router_data.request.clone(); let response = new_router_data.response.clone(); let router_data = get_default_router_data( new_router_data.tenant_id.clone(), "access token", request, response, ); Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for GiftCardBalanceCheckFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let request = new_router_data.request.clone(); let response = new_router_data.response.clone(); let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "gift card balance check", request, response, ); router_data.connector_auth_type = new_router_data.connector_auth_type; Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for PaymentFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), customer_id: old_router_data.customer_id.clone(), connector_customer: old_router_data.connector_customer.clone(), connector: old_router_data.connector.clone(), payment_id: old_router_data.payment_id.clone(), attempt_id: old_router_data.attempt_id.clone(), status: old_router_data.status, payment_method: old_router_data.payment_method, description: old_router_data.description.clone(), address: old_router_data.address.clone(), auth_type: old_router_data.auth_type, connector_meta_data: old_router_data.connector_meta_data.clone(), amount_captured: old_router_data.amount_captured, minor_amount_captured: old_router_data.minor_amount_captured, access_token: old_router_data.access_token.clone(), session_token: old_router_data.session_token.clone(), reference_id: old_router_data.reference_id.clone(), payment_method_token: old_router_data.payment_method_token.clone(), recurring_mandate_payment_data: old_router_data.recurring_mandate_payment_data.clone(), preprocessing_id: old_router_data.preprocessing_id.clone(), payment_method_balance: old_router_data.payment_method_balance.clone(), connector_api_version: old_router_data.connector_api_version.clone(), connector_request_reference_id: old_router_data.connector_request_reference_id.clone(), test_mode: old_router_data.test_mode, connector_http_status_code: old_router_data.connector_http_status_code, external_latency: old_router_data.external_latency, apple_pay_flow: old_router_data.apple_pay_flow.clone(), connector_response: old_router_data.connector_response.clone(), payment_method_status: old_router_data.payment_method_status, }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, customer_id, connector_customer, connector, payment_id, attempt_id, status, payment_method, description, address, auth_type, connector_meta_data, amount_captured, minor_amount_captured, access_token, session_token, reference_id, payment_method_token, recurring_mandate_payment_data, preprocessing_id, payment_method_balance, connector_api_version, connector_request_reference_id, test_mode, connector_http_status_code, external_latency, apple_pay_flow, connector_response, payment_method_status, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "payment", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.customer_id = customer_id; router_data.connector_customer = connector_customer; router_data.connector = connector; router_data.payment_id = payment_id; router_data.attempt_id = attempt_id; router_data.status = status; router_data.payment_method = payment_method; router_data.description = description; router_data.address = address; router_data.auth_type = auth_type; router_data.connector_meta_data = connector_meta_data; router_data.amount_captured = amount_captured; router_data.minor_amount_captured = minor_amount_captured; router_data.access_token = access_token; router_data.session_token = session_token; router_data.reference_id = reference_id; router_data.payment_method_token = payment_method_token; router_data.recurring_mandate_payment_data = recurring_mandate_payment_data; router_data.preprocessing_id = preprocessing_id; router_data.payment_method_balance = payment_method_balance; router_data.connector_api_version = connector_api_version; router_data.connector_request_reference_id = connector_request_reference_id; router_data.test_mode = test_mode; router_data.connector_http_status_code = connector_http_status_code; router_data.external_latency = external_latency; router_data.apple_pay_flow = apple_pay_flow; router_data.connector_response = connector_response; router_data.payment_method_status = payment_method_status; router_data.connector_auth_type = new_router_data.connector_auth_type; Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for RefundFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), customer_id: old_router_data.customer_id.clone(), payment_id: old_router_data.payment_id.clone(), attempt_id: old_router_data.attempt_id.clone(), status: old_router_data.status, payment_method: old_router_data.payment_method, connector_meta_data: old_router_data.connector_meta_data.clone(), amount_captured: old_router_data.amount_captured, minor_amount_captured: old_router_data.minor_amount_captured, connector_request_reference_id: old_router_data.connector_request_reference_id.clone(), refund_id: old_router_data.refund_id.clone().ok_or( ConnectorError::MissingRequiredField { field_name: "refund_id", }, )?, }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, customer_id, payment_id, attempt_id, status, payment_method, connector_meta_data, amount_captured, minor_amount_captured, connector_request_reference_id, refund_id, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "refund", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.customer_id = customer_id; router_data.payment_id = payment_id; router_data.attempt_id = attempt_id; router_data.status = status; router_data.payment_method = payment_method; router_data.connector_meta_data = connector_meta_data; router_data.amount_captured = amount_captured; router_data.minor_amount_captured = minor_amount_captured; router_data.connector_request_reference_id = connector_request_reference_id; router_data.refund_id = Some(refund_id); Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for DisputesFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), payment_id: old_router_data.payment_id.clone(), attempt_id: old_router_data.attempt_id.clone(), payment_method: old_router_data.payment_method, connector_meta_data: old_router_data.connector_meta_data.clone(), amount_captured: old_router_data.amount_captured, minor_amount_captured: old_router_data.minor_amount_captured, connector_request_reference_id: old_router_data.connector_request_reference_id.clone(), dispute_id: old_router_data.dispute_id.clone().ok_or( ConnectorError::MissingRequiredField { field_name: "dispute_id", }, )?, }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, payment_id, attempt_id, payment_method, connector_meta_data, amount_captured, minor_amount_captured, connector_request_reference_id, dispute_id, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "Disputes", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.payment_id = payment_id; router_data.attempt_id = attempt_id; router_data.payment_method = payment_method; router_data.connector_meta_data = connector_meta_data; router_data.amount_captured = amount_captured; router_data.minor_amount_captured = minor_amount_captured; router_data.connector_request_reference_id = connector_request_reference_id; router_data.dispute_id = Some(dispute_id); Ok(router_data) } } #[cfg(feature = "frm")] impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for FrmFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), payment_id: old_router_data.payment_id.clone(), attempt_id: old_router_data.attempt_id.clone(), payment_method: old_router_data.payment_method, connector_request_reference_id: old_router_data.connector_request_reference_id.clone(), auth_type: old_router_data.auth_type, connector_wallets_details: old_router_data.connector_wallets_details.clone(), connector_meta_data: old_router_data.connector_meta_data.clone(), amount_captured: old_router_data.amount_captured, minor_amount_captured: old_router_data.minor_amount_captured, }; Ok(RouterDataV2 { tenant_id: old_router_data.tenant_id.clone(), flow: std::marker::PhantomData, resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, payment_id, attempt_id, payment_method, connector_request_reference_id, auth_type, connector_wallets_details, connector_meta_data, amount_captured, minor_amount_captured, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "frm", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.payment_id = payment_id; router_data.attempt_id = attempt_id; router_data.payment_method = payment_method; router_data.connector_request_reference_id = connector_request_reference_id; router_data.auth_type = auth_type; router_data.connector_wallets_details = connector_wallets_details; router_data.connector_meta_data = connector_meta_data; router_data.amount_captured = amount_captured; router_data.minor_amount_captured = minor_amount_captured; Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for FilesFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), payment_id: old_router_data.payment_id.clone(), attempt_id: old_router_data.attempt_id.clone(), connector_meta_data: old_router_data.connector_meta_data.clone(), connector_request_reference_id: old_router_data.connector_request_reference_id.clone(), }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, payment_id, attempt_id, connector_meta_data, connector_request_reference_id, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "files", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.payment_id = payment_id; router_data.attempt_id = attempt_id; router_data.connector_meta_data = connector_meta_data; router_data.connector_request_reference_id = connector_request_reference_id; Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for WebhookSourceVerifyData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), }; Ok(RouterDataV2 { tenant_id: old_router_data.tenant_id.clone(), flow: std::marker::PhantomData, resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "webhook source verify", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for MandateRevokeFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), customer_id: old_router_data.customer_id.clone().ok_or( ConnectorError::MissingRequiredField { field_name: "customer_id", }, )?, payment_id: Some(old_router_data.payment_id.clone()), }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, customer_id, payment_id, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "mandate revoke", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.customer_id = Some(customer_id); router_data.payment_id = payment_id .unwrap_or_else(|| { id_type::PaymentId::get_irrelevant_id("mandate revoke") .get_string_repr() .to_owned() }) .to_owned(); Ok(router_data) } } #[cfg(feature = "payouts")] impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for PayoutFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), customer_id: old_router_data.customer_id.clone(), connector_customer: old_router_data.connector_customer.clone(), address: old_router_data.address.clone(), connector_meta_data: old_router_data.connector_meta_data.clone(), connector_wallets_details: old_router_data.connector_wallets_details.clone(), connector_request_reference_id: old_router_data.connector_request_reference_id.clone(), payout_method_data: old_router_data.payout_method_data.clone(), quote_id: old_router_data.quote_id.clone(), }; Ok(RouterDataV2 { tenant_id: old_router_data.tenant_id.clone(), flow: std::marker::PhantomData, resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, customer_id, connector_customer, address, connector_meta_data, connector_wallets_details, connector_request_reference_id, payout_method_data, quote_id, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "payout", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.customer_id = customer_id; router_data.connector_customer = connector_customer; router_data.address = address; router_data.connector_meta_data = connector_meta_data; router_data.connector_wallets_details = connector_wallets_details; router_data.connector_request_reference_id = connector_request_reference_id; router_data.payout_method_data = payout_method_data; router_data.quote_id = quote_id; Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for ExternalAuthenticationFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), connector_meta_data: old_router_data.connector_meta_data.clone(), address: old_router_data.address.clone(), }; Ok(RouterDataV2 { tenant_id: old_router_data.tenant_id.clone(), flow: std::marker::PhantomData, resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, connector_meta_data, address, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "external authentication", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.connector_meta_data = connector_meta_data; router_data.address = address; Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for InvoiceRecordBackData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { connector_meta_data: old_router_data.connector_meta_data.clone(), }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { connector_meta_data, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "recovery_record_back", new_router_data.request, new_router_data.response, ); router_data.connector_meta_data = connector_meta_data; router_data.connector_auth_type = new_router_data.connector_auth_type.clone(); Ok(router_data) } } macro_rules! default_router_data_conversion { ($flow_name:ty) => { impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for $flow_name { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { connector_meta_data: old_router_data.connector_meta_data.clone(), }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { connector_meta_data, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), stringify!($flow_name), new_router_data.request, new_router_data.response, ); router_data.connector_meta_data = connector_meta_data; router_data.connector_auth_type = new_router_data.connector_auth_type; Ok(router_data) } } }; } default_router_data_conversion!(GetSubscriptionPlansData); default_router_data_conversion!(GetSubscriptionPlanPricesData); default_router_data_conversion!(SubscriptionCreateData); default_router_data_conversion!(SubscriptionCustomerData); default_router_data_conversion!(GetSubscriptionEstimateData); impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for UasFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { authenticate_by: old_router_data.connector.clone(), source_authentication_id: old_router_data .authentication_id .clone() .ok_or(ConnectorError::MissingRequiredField { field_name: "source_authentication_id", }) .attach_printable("missing authentication id for uas")?, }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { authenticate_by, source_authentication_id, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "uas", new_router_data.request, new_router_data.response, ); router_data.connector = authenticate_by; router_data.authentication_id = Some(source_authentication_id); Ok(router_data) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for BillingConnectorPaymentsSyncFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self {}; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let router_data = get_default_router_data( new_router_data.tenant_id.clone(), "BillingConnectorPaymentsSync", new_router_data.request, new_router_data.response, ); Ok(RouterData { connector_auth_type: new_router_data.connector_auth_type.clone(), ..router_data }) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for BillingConnectorInvoiceSyncFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self {}; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let router_data = get_default_router_data( new_router_data.tenant_id.clone(), "BillingConnectorInvoiceSync", new_router_data.request, new_router_data.response, ); Ok(RouterData { connector_auth_type: new_router_data.connector_auth_type.clone(), ..router_data }) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for VaultConnectorFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let router_data = get_default_router_data( new_router_data.tenant_id.clone(), "VaultConnector", new_router_data.request, new_router_data.response, ); Ok(RouterData { connector_auth_type: new_router_data.connector_auth_type.clone(), ..router_data }) } } impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for ExternalVaultProxyFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> where Self: Sized, { let resource_common_data = Self { merchant_id: old_router_data.merchant_id.clone(), customer_id: old_router_data.customer_id.clone(), connector_customer: old_router_data.connector_customer.clone(), payment_id: old_router_data.payment_id.clone(), attempt_id: old_router_data.attempt_id.clone(), status: old_router_data.status, payment_method: old_router_data.payment_method, description: old_router_data.description.clone(), address: old_router_data.address.clone(), auth_type: old_router_data.auth_type, connector_meta_data: old_router_data.connector_meta_data.clone(), amount_captured: old_router_data.amount_captured, minor_amount_captured: old_router_data.minor_amount_captured, access_token: old_router_data.access_token.clone(), session_token: old_router_data.session_token.clone(), reference_id: old_router_data.reference_id.clone(), payment_method_token: old_router_data.payment_method_token.clone(), recurring_mandate_payment_data: old_router_data.recurring_mandate_payment_data.clone(), preprocessing_id: old_router_data.preprocessing_id.clone(), payment_method_balance: old_router_data.payment_method_balance.clone(), connector_api_version: old_router_data.connector_api_version.clone(), connector_request_reference_id: old_router_data.connector_request_reference_id.clone(), test_mode: old_router_data.test_mode, connector_http_status_code: old_router_data.connector_http_status_code, external_latency: old_router_data.external_latency, apple_pay_flow: old_router_data.apple_pay_flow.clone(), connector_response: old_router_data.connector_response.clone(), payment_method_status: old_router_data.payment_method_status, }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), response: old_router_data.response.clone(), }) } fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where Self: Sized, { let Self { merchant_id, customer_id, connector_customer, payment_id, attempt_id, status, payment_method, description, address, auth_type, connector_meta_data, amount_captured, minor_amount_captured, access_token, session_token, reference_id, payment_method_token, recurring_mandate_payment_data, preprocessing_id, payment_method_balance, connector_api_version, connector_request_reference_id, test_mode, connector_http_status_code, external_latency, apple_pay_flow, connector_response, payment_method_status, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), "external vault proxy", new_router_data.request, new_router_data.response, ); router_data.merchant_id = merchant_id; router_data.customer_id = customer_id; router_data.connector_customer = connector_customer; router_data.payment_id = payment_id; router_data.attempt_id = attempt_id; router_data.status = status; router_data.payment_method = payment_method; router_data.description = description; router_data.address = address; router_data.auth_type = auth_type; router_data.connector_meta_data = connector_meta_data; router_data.amount_captured = amount_captured; router_data.minor_amount_captured = minor_amount_captured; router_data.access_token = access_token; router_data.session_token = session_token; router_data.reference_id = reference_id; router_data.payment_method_token = payment_method_token; router_data.recurring_mandate_payment_data = recurring_mandate_payment_data; router_data.preprocessing_id = preprocessing_id; router_data.payment_method_balance = payment_method_balance; router_data.connector_api_version = connector_api_version; router_data.connector_request_reference_id = connector_request_reference_id; router_data.test_mode = test_mode; router_data.connector_http_status_code = connector_http_status_code; router_data.external_latency = external_latency; router_data.apple_pay_flow = apple_pay_flow; router_data.connector_response = connector_response; router_data.payment_method_status = payment_method_status; Ok(router_data) } }
crates/hyperswitch_interfaces/src/conversion_impls.rs
hyperswitch_interfaces::src::conversion_impls
9,373
true
// File: crates/hyperswitch_interfaces/src/metrics.rs // Module: hyperswitch_interfaces::src::metrics //! Metrics interface use router_env::{counter_metric, global_meter}; global_meter!(GLOBAL_METER, "ROUTER_API"); counter_metric!(UNIMPLEMENTED_FLOW, GLOBAL_METER); counter_metric!(CONNECTOR_CALL_COUNT, GLOBAL_METER); // Attributes needed counter_metric!(RESPONSE_DESERIALIZATION_FAILURE, GLOBAL_METER); counter_metric!(CONNECTOR_ERROR_RESPONSE_COUNT, GLOBAL_METER); // Connector Level Metric counter_metric!(REQUEST_BUILD_FAILURE, GLOBAL_METER);
crates/hyperswitch_interfaces/src/metrics.rs
hyperswitch_interfaces::src::metrics
123
true
// File: crates/hyperswitch_interfaces/src/unified_connector_service.rs // Module: hyperswitch_interfaces::src::unified_connector_service use common_enums::AttemptStatus; use common_utils::errors::CustomResult; use hyperswitch_domain_models::{ router_data::ErrorResponse, router_response_types::PaymentsResponseData, }; use unified_connector_service_client::payments as payments_grpc; use crate::helpers::ForeignTryFrom; /// Unified Connector Service (UCS) related transformers pub mod transformers; pub use transformers::WebhookTransformData; /// Type alias for return type used by unified connector service response handlers type UnifiedConnectorServiceResult = CustomResult< ( Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>, u16, ), transformers::UnifiedConnectorServiceError, >; #[allow(missing_docs)] pub fn handle_unified_connector_service_response_for_payment_get( response: payments_grpc::PaymentServiceGetResponse, ) -> UnifiedConnectorServiceResult { let status_code = transformers::convert_connector_service_status_code(response.status_code)?; let router_data_response = Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?; Ok((router_data_response, status_code)) }
crates/hyperswitch_interfaces/src/unified_connector_service.rs
hyperswitch_interfaces::src::unified_connector_service
254
true
// File: crates/hyperswitch_interfaces/src/integrity.rs // Module: hyperswitch_interfaces::src::integrity use common_utils::errors::IntegrityCheckError; use hyperswitch_domain_models::router_request_types::{ AuthoriseIntegrityObject, CaptureIntegrityObject, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsSyncData, RefundIntegrityObject, RefundsData, SyncIntegrityObject, }; /// Connector Integrity trait to check connector data integrity pub trait FlowIntegrity { /// Output type for the connector type IntegrityObject; /// helps in connector integrity check fn compare( req_integrity_object: Self::IntegrityObject, res_integrity_object: Self::IntegrityObject, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError>; } /// Trait to get connector integrity object based on request and response pub trait GetIntegrityObject<T: FlowIntegrity> { /// function to get response integrity object fn get_response_integrity_object(&self) -> Option<T::IntegrityObject>; /// function to get request integrity object fn get_request_integrity_object(&self) -> T::IntegrityObject; } /// Trait to check flow type, based on which various integrity checks will be performed pub trait CheckIntegrity<Request, T> { /// Function to check to initiate integrity check fn check_integrity( &self, request: &Request, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError>; } impl<T, Request> CheckIntegrity<Request, T> for RefundsData where T: FlowIntegrity, Request: GetIntegrityObject<T>, { fn check_integrity( &self, request: &Request, connector_refund_id: Option<String>, ) -> Result<(), IntegrityCheckError> { match request.get_response_integrity_object() { Some(res_integrity_object) => { let req_integrity_object = request.get_request_integrity_object(); T::compare( req_integrity_object, res_integrity_object, connector_refund_id, ) } None => Ok(()), } } } impl<T, Request> CheckIntegrity<Request, T> for PaymentsAuthorizeData where T: FlowIntegrity, Request: GetIntegrityObject<T>, { fn check_integrity( &self, request: &Request, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { match request.get_response_integrity_object() { Some(res_integrity_object) => { let req_integrity_object = request.get_request_integrity_object(); T::compare( req_integrity_object, res_integrity_object, connector_transaction_id, ) } None => Ok(()), } } } impl<T, Request> CheckIntegrity<Request, T> for PaymentsCaptureData where T: FlowIntegrity, Request: GetIntegrityObject<T>, { fn check_integrity( &self, request: &Request, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { match request.get_response_integrity_object() { Some(res_integrity_object) => { let req_integrity_object = request.get_request_integrity_object(); T::compare( req_integrity_object, res_integrity_object, connector_transaction_id, ) } None => Ok(()), } } } impl<T, Request> CheckIntegrity<Request, T> for PaymentsSyncData where T: FlowIntegrity, Request: GetIntegrityObject<T>, { fn check_integrity( &self, request: &Request, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { match request.get_response_integrity_object() { Some(res_integrity_object) => { let req_integrity_object = request.get_request_integrity_object(); T::compare( req_integrity_object, res_integrity_object, connector_transaction_id, ) } None => Ok(()), } } } impl FlowIntegrity for RefundIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } if req_integrity_object.refund_amount != res_integrity_object.refund_amount { mismatched_fields.push(format_mismatch( "refund_amount", &req_integrity_object.refund_amount.to_string(), &res_integrity_object.refund_amount.to_string(), )); } if mismatched_fields.is_empty() { Ok(()) } else { let field_names = mismatched_fields.join(", "); Err(IntegrityCheckError { field_names, connector_transaction_id, }) } } } impl FlowIntegrity for AuthoriseIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.amount != res_integrity_object.amount { mismatched_fields.push(format_mismatch( "amount", &req_integrity_object.amount.to_string(), &res_integrity_object.amount.to_string(), )); } if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } if mismatched_fields.is_empty() { Ok(()) } else { let field_names = mismatched_fields.join(", "); Err(IntegrityCheckError { field_names, connector_transaction_id, }) } } } impl FlowIntegrity for SyncIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); res_integrity_object .amount .zip(req_integrity_object.amount) .map(|(res_amount, req_amount)| { if res_amount != req_amount { mismatched_fields.push(format_mismatch( "amount", &req_amount.to_string(), &res_amount.to_string(), )); } }); res_integrity_object .currency .zip(req_integrity_object.currency) .map(|(res_currency, req_currency)| { if res_currency != req_currency { mismatched_fields.push(format_mismatch( "currency", &req_currency.to_string(), &res_currency.to_string(), )); } }); if mismatched_fields.is_empty() { Ok(()) } else { let field_names = mismatched_fields.join(", "); Err(IntegrityCheckError { field_names, connector_transaction_id, }) } } } impl FlowIntegrity for CaptureIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); res_integrity_object .capture_amount .zip(req_integrity_object.capture_amount) .map(|(res_amount, req_amount)| { if res_amount != req_amount { mismatched_fields.push(format_mismatch( "capture_amount", &req_amount.to_string(), &res_amount.to_string(), )); } }); if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } if mismatched_fields.is_empty() { Ok(()) } else { let field_names = mismatched_fields.join(", "); Err(IntegrityCheckError { field_names, connector_transaction_id, }) } } } impl GetIntegrityObject<CaptureIntegrityObject> for PaymentsCaptureData { fn get_response_integrity_object(&self) -> Option<CaptureIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> CaptureIntegrityObject { CaptureIntegrityObject { capture_amount: Some(self.minor_amount_to_capture), currency: self.currency, } } } impl GetIntegrityObject<RefundIntegrityObject> for RefundsData { fn get_response_integrity_object(&self) -> Option<RefundIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> RefundIntegrityObject { RefundIntegrityObject { currency: self.currency, refund_amount: self.minor_refund_amount, } } } impl GetIntegrityObject<AuthoriseIntegrityObject> for PaymentsAuthorizeData { fn get_response_integrity_object(&self) -> Option<AuthoriseIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> AuthoriseIntegrityObject { AuthoriseIntegrityObject { amount: self.minor_amount, currency: self.currency, } } } impl GetIntegrityObject<SyncIntegrityObject> for PaymentsSyncData { fn get_response_integrity_object(&self) -> Option<SyncIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> SyncIntegrityObject { SyncIntegrityObject { amount: Some(self.amount), currency: Some(self.currency), } } } #[inline] fn format_mismatch(field: &str, expected: &str, found: &str) -> String { format!("{field} expected {expected} but found {found}") }
crates/hyperswitch_interfaces/src/integrity.rs
hyperswitch_interfaces::src::integrity
2,233
true
// File: crates/hyperswitch_interfaces/src/connector_integration_interface.rs // Module: hyperswitch_interfaces::src::connector_integration_interface use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use common_enums::PaymentAction; use common_utils::{crypto, errors::CustomResult, request::Request}; use hyperswitch_domain_models::{ api::ApplicationResponse, connector_endpoints::Connectors, errors::api_error_response::ApiErrorResponse, payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_data_v2::RouterDataV2, router_response_types::{ConnectorInfo, SupportedPaymentMethods}, }; use crate::{ api, api::{ BoxedConnectorIntegration, CaptureSyncMethod, Connector, ConnectorCommon, ConnectorIntegration, ConnectorRedirectResponse, ConnectorSpecifications, ConnectorValidation, CurrencyUnit, }, authentication::ExternalAuthenticationPayload, connector_integration_v2::{BoxedConnectorIntegrationV2, ConnectorIntegrationV2, ConnectorV2}, disputes, errors, events::connector_api_logs::ConnectorEvent, types, webhooks::{IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails}, }; /// RouterDataConversion trait /// /// This trait must be implemented for conversion between Router data and RouterDataV2 pub trait RouterDataConversion<T, Req: Clone, Resp: Clone> { /// Convert RouterData to RouterDataV2 /// /// # Arguments /// /// * `old_router_data` - A reference to the old RouterData /// /// # Returns /// /// A `CustomResult` containing the new RouterDataV2 or a ConnectorError fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, errors::ConnectorError> where Self: Sized; /// Convert RouterDataV2 back to RouterData /// /// # Arguments /// /// * `new_router_data` - The new RouterDataV2 /// /// # Returns /// /// A `CustomResult` containing the old RouterData or a ConnectorError fn to_old_router_data( new_router_data: RouterDataV2<T, Self, Req, Resp>, ) -> CustomResult<RouterData<T, Req, Resp>, errors::ConnectorError> where Self: Sized; } /// Alias for Box<&'static (dyn Connector + Sync)> pub type BoxedConnector = Box<&'static (dyn Connector + Sync)>; /// Alias for Box<&'static (dyn ConnectorV2 + Sync)> pub type BoxedConnectorV2 = Box<&'static (dyn ConnectorV2 + Sync)>; /// Enum representing the Connector #[derive(Clone)] pub enum ConnectorEnum { /// Old connector type Old(BoxedConnector), /// New connector type New(BoxedConnectorV2), } impl std::fmt::Debug for ConnectorEnum { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Old(_) => f .debug_tuple("Old") .field(&std::any::type_name::<BoxedConnector>().to_string()) .finish(), Self::New(_) => f .debug_tuple("New") .field(&std::any::type_name::<BoxedConnectorV2>().to_string()) .finish(), } } } #[allow(missing_debug_implementations)] /// Enum representing the Connector Integration #[derive(Clone)] pub enum ConnectorIntegrationEnum<'a, F, ResourceCommonData, Req, Resp> { /// Old connector integration type Old(BoxedConnectorIntegration<'a, F, Req, Resp>), /// New connector integration type New(BoxedConnectorIntegrationV2<'a, F, ResourceCommonData, Req, Resp>), } /// Alias for Box<dyn ConnectorIntegrationInterface> pub type BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> = Box<dyn ConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> + Send + Sync>; impl ConnectorEnum { /// Get the connector integration /// /// # Returns /// /// A `BoxedConnectorIntegrationInterface` containing the connector integration pub fn get_connector_integration<F, ResourceCommonData, Req, Resp>( &self, ) -> BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> where dyn Connector + Sync: ConnectorIntegration<F, Req, Resp>, dyn ConnectorV2 + Sync: ConnectorIntegrationV2<F, ResourceCommonData, Req, Resp>, ResourceCommonData: RouterDataConversion<F, Req, Resp> + Clone + 'static, F: Clone + 'static, Req: Clone + 'static, Resp: Clone + 'static, { match self { Self::Old(old_integration) => Box::new(ConnectorIntegrationEnum::Old( old_integration.get_connector_integration(), )), Self::New(new_integration) => Box::new(ConnectorIntegrationEnum::New( new_integration.get_connector_integration_v2(), )), } } /// validates the file upload pub fn validate_file_upload( &self, purpose: api::files::FilePurpose, file_size: i32, file_type: mime::Mime, ) -> CustomResult<(), errors::ConnectorError> { match self { Self::Old(connector) => connector.validate_file_upload(purpose, file_size, file_type), Self::New(connector) => { connector.validate_file_upload_v2(purpose, file_size, file_type) } } } } #[async_trait::async_trait] impl IncomingWebhook for ConnectorEnum { fn get_webhook_body_decoding_algorithm( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::DecodeMessage + Send>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_body_decoding_algorithm(request), Self::New(connector) => connector.get_webhook_body_decoding_algorithm(request), } } fn get_webhook_body_decoding_message( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_body_decoding_message(request), Self::New(connector) => connector.get_webhook_body_decoding_message(request), } } async fn decode_webhook_body( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, connector_name: &str, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { match self { Self::Old(connector) => { connector .decode_webhook_body( request, merchant_id, connector_webhook_details, connector_name, ) .await } Self::New(connector) => { connector .decode_webhook_body( request, merchant_id, connector_webhook_details, connector_name, ) .await } } } fn get_webhook_source_verification_algorithm( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_source_verification_algorithm(request), Self::New(connector) => connector.get_webhook_source_verification_algorithm(request), } } async fn get_webhook_source_verification_merchant_secret( &self, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<api_models::webhooks::ConnectorWebhookSecrets, errors::ConnectorError> { match self { Self::Old(connector) => { connector .get_webhook_source_verification_merchant_secret( merchant_id, connector_name, connector_webhook_details, ) .await } Self::New(connector) => { connector .get_webhook_source_verification_merchant_secret( merchant_id, connector_name, connector_webhook_details, ) .await } } } fn get_webhook_source_verification_signature( &self, request: &IncomingWebhookRequestDetails<'_>, connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { match self { Self::Old(connector) => connector .get_webhook_source_verification_signature(request, connector_webhook_secrets), Self::New(connector) => connector .get_webhook_source_verification_signature(request, connector_webhook_secrets), } } fn get_webhook_source_verification_message( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_source_verification_message( request, merchant_id, connector_webhook_secrets, ), Self::New(connector) => connector.get_webhook_source_verification_message( request, merchant_id, connector_webhook_secrets, ), } } async fn verify_webhook_source( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, connector_account_details: crypto::Encryptable<masking::Secret<serde_json::Value>>, connector_name: &str, ) -> CustomResult<bool, errors::ConnectorError> { match self { Self::Old(connector) => { connector .verify_webhook_source( request, merchant_id, connector_webhook_details, connector_account_details, connector_name, ) .await } Self::New(connector) => { connector .verify_webhook_source( request, merchant_id, connector_webhook_details, connector_account_details, connector_name, ) .await } } } fn get_webhook_object_reference_id( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_object_reference_id(request), Self::New(connector) => connector.get_webhook_object_reference_id(request), } } fn get_webhook_event_type( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_event_type(request), Self::New(connector) => connector.get_webhook_event_type(request), } } fn get_webhook_resource_object( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_resource_object(request), Self::New(connector) => connector.get_webhook_resource_object(request), } } fn get_webhook_api_response( &self, request: &IncomingWebhookRequestDetails<'_>, error_kind: Option<IncomingWebhookFlowError>, ) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_webhook_api_response(request, error_kind), Self::New(connector) => connector.get_webhook_api_response(request, error_kind), } } fn get_dispute_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<disputes::DisputePayload, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_dispute_details(request), Self::New(connector) => connector.get_dispute_details(request), } } fn get_external_authentication_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ExternalAuthenticationPayload, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_external_authentication_details(request), Self::New(connector) => connector.get_external_authentication_details(request), } } fn get_mandate_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< Option<hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails>, errors::ConnectorError, > { match self { Self::Old(connector) => connector.get_mandate_details(request), Self::New(connector) => connector.get_mandate_details(request), } } fn get_network_txn_id( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< Option<hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId>, errors::ConnectorError, > { match self { Self::Old(connector) => connector.get_network_txn_id(request), Self::New(connector) => connector.get_network_txn_id(request), } } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] fn get_revenue_recovery_invoice_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< hyperswitch_domain_models::revenue_recovery::RevenueRecoveryInvoiceData, errors::ConnectorError, > { match self { Self::Old(connector) => connector.get_revenue_recovery_invoice_details(request), Self::New(connector) => connector.get_revenue_recovery_invoice_details(request), } } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] fn get_revenue_recovery_attempt_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< hyperswitch_domain_models::revenue_recovery::RevenueRecoveryAttemptData, errors::ConnectorError, > { match self { Self::Old(connector) => connector.get_revenue_recovery_attempt_details(request), Self::New(connector) => connector.get_revenue_recovery_attempt_details(request), } } fn get_subscription_mit_payment_data( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< hyperswitch_domain_models::router_flow_types::SubscriptionMitPaymentData, errors::ConnectorError, > { match self { Self::Old(connector) => connector.get_subscription_mit_payment_data(request), Self::New(connector) => connector.get_subscription_mit_payment_data(request), } } } impl ConnectorRedirectResponse for ConnectorEnum { fn get_flow_type( &self, query_params: &str, json_payload: Option<serde_json::Value>, action: PaymentAction, ) -> CustomResult<common_enums::CallConnectorAction, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_flow_type(query_params, json_payload, action), Self::New(connector) => connector.get_flow_type(query_params, json_payload, action), } } } impl ConnectorValidation for ConnectorEnum { fn validate_connector_against_payment_request( &self, capture_method: Option<common_enums::CaptureMethod>, payment_method: common_enums::PaymentMethod, pmt: Option<common_enums::PaymentMethodType>, ) -> CustomResult<(), errors::ConnectorError> { match self { Self::Old(connector) => connector.validate_connector_against_payment_request( capture_method, payment_method, pmt, ), Self::New(connector) => connector.validate_connector_against_payment_request( capture_method, payment_method, pmt, ), } } fn validate_mandate_payment( &self, pm_type: Option<common_enums::PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { match self { Self::Old(connector) => connector.validate_mandate_payment(pm_type, pm_data), Self::New(connector) => connector.validate_mandate_payment(pm_type, pm_data), } } fn validate_psync_reference_id( &self, data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, is_three_ds: bool, status: common_enums::enums::AttemptStatus, connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { match self { Self::Old(connector) => connector.validate_psync_reference_id( data, is_three_ds, status, connector_meta_data, ), Self::New(connector) => connector.validate_psync_reference_id( data, is_three_ds, status, connector_meta_data, ), } } fn is_webhook_source_verification_mandatory(&self) -> bool { match self { Self::Old(connector) => connector.is_webhook_source_verification_mandatory(), Self::New(connector) => connector.is_webhook_source_verification_mandatory(), } } } impl ConnectorSpecifications for ConnectorEnum { fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { match self { Self::Old(connector) => connector.get_supported_payment_methods(), Self::New(connector) => connector.get_supported_payment_methods(), } } /// Supported webhooks flows fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::EventClass]> { match self { Self::Old(connector) => connector.get_supported_webhook_flows(), Self::New(connector) => connector.get_supported_webhook_flows(), } } /// Details related to connector fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { match self { Self::Old(connector) => connector.get_connector_about(), Self::New(connector) => connector.get_connector_about(), } } /// Check if connector supports authentication token fn authentication_token_for_token_creation(&self) -> bool { match self { Self::Old(connector) => connector.authentication_token_for_token_creation(), Self::New(connector) => connector.authentication_token_for_token_creation(), } } /// If connector supports session token generation fn is_sdk_client_token_generation_enabled(&self) -> bool { match self { Self::Old(connector) => connector.is_sdk_client_token_generation_enabled(), Self::New(connector) => connector.is_sdk_client_token_generation_enabled(), } } /// Supported payment methods for session token generation fn supported_payment_method_types_for_sdk_client_token_generation( &self, ) -> Vec<common_enums::PaymentMethodType> { match self { Self::Old(connector) => { connector.supported_payment_method_types_for_sdk_client_token_generation() } Self::New(connector) => { connector.supported_payment_method_types_for_sdk_client_token_generation() } } } /// Validate whether session token is generated for payment payment type fn validate_sdk_session_token_for_payment_method( &self, current_core_payment_method_type: &common_enums::PaymentMethodType, ) -> bool { match self { Self::Old(connector) => connector .validate_sdk_session_token_for_payment_method(current_core_payment_method_type), Self::New(connector) => connector .validate_sdk_session_token_for_payment_method(current_core_payment_method_type), } } #[cfg(feature = "v1")] fn generate_connector_request_reference_id( &self, payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, is_config_enabled_to_send_payment_id_as_connector_request_id: bool, ) -> String { match self { Self::Old(connector) => connector.generate_connector_request_reference_id( payment_intent, payment_attempt, is_config_enabled_to_send_payment_id_as_connector_request_id, ), Self::New(connector) => connector.generate_connector_request_reference_id( payment_intent, payment_attempt, is_config_enabled_to_send_payment_id_as_connector_request_id, ), } } #[cfg(feature = "v2")] /// Generate connector request reference ID fn generate_connector_request_reference_id( &self, payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> String { match self { Self::Old(connector) => { connector.generate_connector_request_reference_id(payment_intent, payment_attempt) } Self::New(connector) => { connector.generate_connector_request_reference_id(payment_intent, payment_attempt) } } } /// Check if connector requires create customer call fn should_call_connector_customer( &self, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> bool { match self { Self::Old(connector) => connector.should_call_connector_customer(payment_attempt), Self::New(connector) => connector.should_call_connector_customer(payment_attempt), } } } impl ConnectorCommon for ConnectorEnum { fn id(&self) -> &'static str { match self { Self::Old(connector) => connector.id(), Self::New(connector) => connector.id(), } } fn get_currency_unit(&self) -> CurrencyUnit { match self { Self::Old(connector) => connector.get_currency_unit(), Self::New(connector) => connector.get_currency_unit(), } } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { match self { Self::Old(connector) => connector.get_auth_header(auth_type), Self::New(connector) => connector.get_auth_header(auth_type), } } fn common_get_content_type(&self) -> &'static str { match self { Self::Old(connector) => connector.common_get_content_type(), Self::New(connector) => connector.common_get_content_type(), } } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { match self { Self::Old(connector) => connector.base_url(connectors), Self::New(connector) => connector.base_url(connectors), } } fn build_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { match self { Self::Old(connector) => connector.build_error_response(res, event_builder), Self::New(connector) => connector.build_error_response(res, event_builder), } } } /// Trait representing the connector integration interface /// /// This trait defines the methods required for a connector integration interface. pub trait ConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>: Send + Sync { /// Clone the connector integration interface /// /// # Returns /// /// A `Box` containing the cloned connector integration interface fn clone_box( &self, ) -> Box<dyn ConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> + Send + Sync>; /// Get the multiple capture sync method /// /// # Returns /// /// A `CustomResult` containing the `CaptureSyncMethod` or a `ConnectorError` fn get_multiple_capture_sync_method( &self, ) -> CustomResult<CaptureSyncMethod, errors::ConnectorError>; /// Build a request for the connector integration /// /// # Arguments /// /// * `req` - A reference to the RouterData /// # Returns /// /// A `CustomResult` containing an optional Request or a ConnectorError fn build_request( &self, req: &RouterData<F, Req, Resp>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError>; /// handles response from the connector fn handle_response( &self, data: &RouterData<F, Req, Resp>, event_builder: Option<&mut ConnectorEvent>, _res: types::Response, ) -> CustomResult<RouterData<F, Req, Resp>, errors::ConnectorError> where F: Clone, Req: Clone, Resp: Clone; /// Get the error response /// /// # Arguments /// /// * `res` - The response /// * `event_builder` - An optional event builder /// /// # Returns /// /// A `CustomResult` containing the `ErrorResponse` or a `ConnectorError` fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError>; /// Get the 5xx error response /// /// # Arguments /// /// * `res` - The response /// * `event_builder` - An optional event builder /// /// # Returns /// /// A `CustomResult` containing the `ErrorResponse` or a `ConnectorError` fn get_5xx_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError>; } impl<T: 'static, ResourceCommonData: 'static, Req: 'static, Resp: 'static> ConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp> for ConnectorIntegrationEnum<'static, T, ResourceCommonData, Req, Resp> where ResourceCommonData: RouterDataConversion<T, Req, Resp> + Clone, T: Clone, Req: Clone, Resp: Clone, { fn get_multiple_capture_sync_method( &self, ) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> { match self { ConnectorIntegrationEnum::Old(old_integration) => { old_integration.get_multiple_capture_sync_method() } ConnectorIntegrationEnum::New(new_integration) => { new_integration.get_multiple_capture_sync_method() } } } fn build_request( &self, req: &RouterData<T, Req, Resp>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { match self { ConnectorIntegrationEnum::Old(old_integration) => { old_integration.build_request(req, connectors) } ConnectorIntegrationEnum::New(new_integration) => { let new_router_data = ResourceCommonData::from_old_router_data(req)?; new_integration.build_request_v2(&new_router_data) } } } fn handle_response( &self, data: &RouterData<T, Req, Resp>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<RouterData<T, Req, Resp>, errors::ConnectorError> where T: Clone, Req: Clone, Resp: Clone, { match self { ConnectorIntegrationEnum::Old(old_integration) => { old_integration.handle_response(data, event_builder, res) } ConnectorIntegrationEnum::New(new_integration) => { let new_router_data = ResourceCommonData::from_old_router_data(data)?; new_integration .handle_response_v2(&new_router_data, event_builder, res) .map(ResourceCommonData::to_old_router_data)? } } } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { match self { ConnectorIntegrationEnum::Old(old_integration) => { old_integration.get_error_response(res, event_builder) } ConnectorIntegrationEnum::New(new_integration) => { new_integration.get_error_response_v2(res, event_builder) } } } fn get_5xx_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { match self { ConnectorIntegrationEnum::Old(old_integration) => { old_integration.get_5xx_error_response(res, event_builder) } ConnectorIntegrationEnum::New(new_integration) => { new_integration.get_5xx_error_response(res, event_builder) } } } fn clone_box( &self, ) -> Box<dyn ConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp> + Send + Sync> { Box::new(self.clone()) } } impl api::ConnectorTransactionId for ConnectorEnum { /// Get the connector transaction ID /// /// # Arguments /// /// * `payment_attempt` - The payment attempt /// /// # Returns /// /// A `Result` containing an optional transaction ID or an ApiErrorResponse fn connector_transaction_id( &self, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> Result<Option<String>, ApiErrorResponse> { match self { Self::Old(connector) => connector.connector_transaction_id(payment_attempt), Self::New(connector) => connector.connector_transaction_id(payment_attempt), } } }
crates/hyperswitch_interfaces/src/connector_integration_interface.rs
hyperswitch_interfaces::src::connector_integration_interface
6,580
true
// File: crates/hyperswitch_interfaces/src/helpers.rs // Module: hyperswitch_interfaces::src::helpers /// Trait for converting from one foreign type to another pub trait ForeignTryFrom<F>: Sized { /// Custom error for conversion failure type Error; /// Convert from a foreign type to the current type and return an error if the conversion fails fn foreign_try_from(from: F) -> Result<Self, Self::Error>; }
crates/hyperswitch_interfaces/src/helpers.rs
hyperswitch_interfaces::src::helpers
94
true
// File: crates/hyperswitch_interfaces/src/webhooks.rs // Module: hyperswitch_interfaces::src::webhooks //! Webhooks interface use common_utils::{crypto, errors::CustomResult, ext_traits::ValueExt}; use error_stack::ResultExt; use hyperswitch_domain_models::{ api::ApplicationResponse, errors::api_error_response::ApiErrorResponse, }; use masking::{ExposeInterface, Secret}; use crate::{api::ConnectorCommon, errors}; /// struct IncomingWebhookRequestDetails #[derive(Debug)] pub struct IncomingWebhookRequestDetails<'a> { /// method pub method: http::Method, /// uri pub uri: http::Uri, /// headers pub headers: &'a actix_web::http::header::HeaderMap, /// body pub body: &'a [u8], /// query_params pub query_params: String, } /// IncomingWebhookFlowError enum defining the error type for incoming webhook #[derive(Debug)] pub enum IncomingWebhookFlowError { /// Resource not found for the webhook ResourceNotFound, /// Internal error for the webhook InternalError, } impl From<&ApiErrorResponse> for IncomingWebhookFlowError { fn from(api_error_response: &ApiErrorResponse) -> Self { match api_error_response { ApiErrorResponse::WebhookResourceNotFound | ApiErrorResponse::DisputeNotFound { .. } | ApiErrorResponse::PayoutNotFound | ApiErrorResponse::MandateNotFound | ApiErrorResponse::PaymentNotFound | ApiErrorResponse::RefundNotFound | ApiErrorResponse::AuthenticationNotFound { .. } => Self::ResourceNotFound, _ => Self::InternalError, } } } /// Trait defining incoming webhook #[async_trait::async_trait] pub trait IncomingWebhook: ConnectorCommon + Sync { /// fn get_webhook_body_decoding_algorithm fn get_webhook_body_decoding_algorithm( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::DecodeMessage + Send>, errors::ConnectorError> { Ok(Box::new(crypto::NoAlgorithm)) } /// fn get_webhook_body_decoding_message fn get_webhook_body_decoding_message( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { Ok(request.body.to_vec()) } /// fn decode_webhook_body async fn decode_webhook_body( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, connector_name: &str, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let algorithm = self.get_webhook_body_decoding_algorithm(request)?; let message = self .get_webhook_body_decoding_message(request) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let secret = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_name, connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; algorithm .decode_message(&secret.secret, message.into()) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed) } /// fn get_webhook_source_verification_algorithm fn get_webhook_source_verification_algorithm( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::NoAlgorithm)) } /// fn get_webhook_source_verification_merchant_secret async fn get_webhook_source_verification_merchant_secret( &self, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<api_models::webhooks::ConnectorWebhookSecrets, errors::ConnectorError> { let debug_suffix = format!("For merchant_id: {merchant_id:?}, and connector_name: {connector_name}"); let default_secret = "default_secret".to_string(); let merchant_secret = match connector_webhook_details { Some(merchant_connector_webhook_details) => { let connector_webhook_details = merchant_connector_webhook_details .parse_value::<api_models::admin::MerchantConnectorWebhookDetails>( "MerchantConnectorWebhookDetails", ) .change_context_lazy(|| errors::ConnectorError::WebhookSourceVerificationFailed) .attach_printable_lazy(|| { format!( "Deserializing MerchantConnectorWebhookDetails failed {debug_suffix}", ) })?; api_models::webhooks::ConnectorWebhookSecrets { secret: connector_webhook_details .merchant_secret .expose() .into_bytes(), additional_secret: connector_webhook_details.additional_secret, } } None => api_models::webhooks::ConnectorWebhookSecrets { secret: default_secret.into_bytes(), additional_secret: None, }, }; //need to fetch merchant secret from config table with caching in future for enhanced performance //If merchant has not set the secret for webhook source verification, "default_secret" is returned. //So it will fail during verification step and goes to psync flow. Ok(merchant_secret) } /// fn get_webhook_source_verification_signature fn get_webhook_source_verification_signature( &self, _request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { Ok(Vec::new()) } /// fn get_webhook_source_verification_message fn get_webhook_source_verification_message( &self, _request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { Ok(Vec::new()) } /// fn verify_webhook_source async fn verify_webhook_source( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_name: &str, ) -> CustomResult<bool, errors::ConnectorError> { let algorithm = self .get_webhook_source_verification_algorithm(request) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_name, connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let message = self .get_webhook_source_verification_message( request, merchant_id, &connector_webhook_secrets, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; algorithm .verify_signature(&connector_webhook_secrets.secret, &signature, &message) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) } /// fn get_webhook_object_reference_id fn get_webhook_object_reference_id( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError>; /// fn get_webhook_event_type fn get_webhook_event_type( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError>; /// fn get_webhook_resource_object fn get_webhook_resource_object( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError>; /// fn get_webhook_api_response fn get_webhook_api_response( &self, _request: &IncomingWebhookRequestDetails<'_>, _error_kind: Option<IncomingWebhookFlowError>, ) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> { Ok(ApplicationResponse::StatusOk) } /// fn get_dispute_details fn get_dispute_details( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<crate::disputes::DisputePayload, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_dispute_details method".to_string()).into()) } /// fn get_external_authentication_details fn get_external_authentication_details( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<crate::authentication::ExternalAuthenticationPayload, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented( "get_external_authentication_details method".to_string(), ) .into()) } /// fn get_mandate_details fn get_mandate_details( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< Option<hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails>, errors::ConnectorError, > { Ok(None) } /// fn get_network_txn_id fn get_network_txn_id( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< Option<hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId>, errors::ConnectorError, > { Ok(None) } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] /// get revenue recovery invoice details fn get_revenue_recovery_attempt_details( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< hyperswitch_domain_models::revenue_recovery::RevenueRecoveryAttemptData, errors::ConnectorError, > { Err(errors::ConnectorError::NotImplemented( "get_revenue_recovery_attempt_details method".to_string(), ) .into()) } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] /// get revenue recovery transaction details fn get_revenue_recovery_invoice_details( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< hyperswitch_domain_models::revenue_recovery::RevenueRecoveryInvoiceData, errors::ConnectorError, > { Err(errors::ConnectorError::NotImplemented( "get_revenue_recovery_invoice_details method".to_string(), ) .into()) } /// get subscription MIT payment data from webhook fn get_subscription_mit_payment_data( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< hyperswitch_domain_models::router_flow_types::SubscriptionMitPaymentData, errors::ConnectorError, > { Err(errors::ConnectorError::NotImplemented( "get_subscription_mit_payment_data method".to_string(), ) .into()) } }
crates/hyperswitch_interfaces/src/webhooks.rs
hyperswitch_interfaces::src::webhooks
2,547
true
// File: crates/hyperswitch_interfaces/src/encryption_interface.rs // Module: hyperswitch_interfaces::src::encryption_interface //! Encryption related interface and error types #![warn(missing_docs, missing_debug_implementations)] use common_utils::errors::CustomResult; /// Trait defining the interface for encryption management #[async_trait::async_trait] pub trait EncryptionManagementInterface: Sync + Send + dyn_clone::DynClone { /// Encrypt the given input data async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError>; /// Decrypt the given input data async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError>; } dyn_clone::clone_trait_object!(EncryptionManagementInterface); /// Errors that may occur during above encryption functionalities #[derive(Debug, thiserror::Error)] pub enum EncryptionError { /// An error occurred when encrypting input data. #[error("Failed to encrypt input data")] EncryptionFailed, /// An error occurred when decrypting input data. #[error("Failed to decrypt input data")] DecryptionFailed, }
crates/hyperswitch_interfaces/src/encryption_interface.rs
hyperswitch_interfaces::src::encryption_interface
238
true
// File: crates/hyperswitch_interfaces/src/errors.rs // Module: hyperswitch_interfaces::src::errors //! Errors interface use common_enums::ApiClientError; use common_utils::errors::ErrorSwitch; use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse; /// Connector Errors #[allow(missing_docs, missing_debug_implementations)] #[derive(Debug, thiserror::Error, PartialEq)] pub enum ConnectorError { #[error("Error while obtaining URL for the integration")] FailedToObtainIntegrationUrl, #[error("Failed to encode connector request")] RequestEncodingFailed, #[error("Request encoding failed : {0}")] RequestEncodingFailedWithReason(String), #[error("Parsing failed")] ParsingFailed, #[error("Failed to deserialize connector response")] ResponseDeserializationFailed, #[error("Failed to execute a processing step: {0:?}")] ProcessingStepFailed(Option<bytes::Bytes>), #[error("The connector returned an unexpected response: {0:?}")] UnexpectedResponseError(bytes::Bytes), #[error("Failed to parse custom routing rules from merchant account")] RoutingRulesParsingError, #[error("Failed to obtain preferred connector from merchant account")] FailedToObtainPreferredConnector, #[error("An invalid connector name was provided")] InvalidConnectorName, #[error("An invalid Wallet was used")] InvalidWallet, #[error("Failed to handle connector response")] ResponseHandlingFailed, #[error("Missing required field: {field_name}")] MissingRequiredField { field_name: &'static str }, #[error("Missing required fields: {field_names:?}")] MissingRequiredFields { field_names: Vec<&'static str> }, #[error("Failed to obtain authentication type")] FailedToObtainAuthType, #[error("Failed to obtain certificate")] FailedToObtainCertificate, #[error("Connector meta data not found")] NoConnectorMetaData, #[error("Connector wallet details not found")] NoConnectorWalletDetails, #[error("Failed to obtain certificate key")] FailedToObtainCertificateKey, #[error("This step has not been implemented for: {0}")] NotImplemented(String), #[error("{message} is not supported by {connector}")] NotSupported { message: String, connector: &'static str, }, #[error("{flow} flow not supported by {connector} connector")] FlowNotSupported { flow: String, connector: String }, #[error("Capture method not supported")] CaptureMethodNotSupported, #[error("Missing connector mandate ID")] MissingConnectorMandateID, #[error("Missing connector mandate metadata")] MissingConnectorMandateMetadata, #[error("Missing connector transaction ID")] MissingConnectorTransactionID, #[error("Missing connector refund ID")] MissingConnectorRefundID, #[error("Missing apple pay tokenization data")] MissingApplePayTokenData, #[error("Webhooks not implemented for this connector")] WebhooksNotImplemented, #[error("Failed to decode webhook event body")] WebhookBodyDecodingFailed, #[error("Signature not found for incoming webhook")] WebhookSignatureNotFound, #[error("Failed to verify webhook source")] WebhookSourceVerificationFailed, #[error("Could not find merchant secret in DB for incoming webhook source verification")] WebhookVerificationSecretNotFound, #[error("Merchant secret found for incoming webhook source verification is invalid")] WebhookVerificationSecretInvalid, #[error("Incoming webhook object reference ID not found")] WebhookReferenceIdNotFound, #[error("Incoming webhook event type not found")] WebhookEventTypeNotFound, #[error("Incoming webhook event resource object not found")] WebhookResourceObjectNotFound, #[error("Could not respond to the incoming webhook event")] WebhookResponseEncodingFailed, #[error("Invalid Date/time format")] InvalidDateFormat, #[error("Date Formatting Failed")] DateFormattingFailed, #[error("Invalid Data format")] InvalidDataFormat { field_name: &'static str }, #[error("Payment Method data / Payment Method Type / Payment Experience Mismatch ")] MismatchedPaymentData, #[error("Failed to parse {wallet_name} wallet token")] InvalidWalletToken { wallet_name: String }, #[error("Missing Connector Related Transaction ID")] MissingConnectorRelatedTransactionID { id: String }, #[error("File Validation failed")] FileValidationFailed { reason: String }, #[error("Missing 3DS redirection payload: {field_name}")] MissingConnectorRedirectionPayload { field_name: &'static str }, #[error("Failed at connector's end with code '{code}'")] FailedAtConnector { message: String, code: String }, #[error("Payment Method Type not found")] MissingPaymentMethodType, #[error("Balance in the payment method is low")] InSufficientBalanceInPaymentMethod, #[error("Server responded with Request Timeout")] RequestTimeoutReceived, #[error("The given currency method is not configured with the given connector")] CurrencyNotSupported { message: String, connector: &'static str, }, #[error("Invalid Configuration")] InvalidConnectorConfig { config: &'static str }, #[error("Failed to convert amount to required type")] AmountConversionFailed, #[error("Generic Error")] GenericError { error_message: String, error_object: serde_json::Value, }, #[error("Field {fields} doesn't match with the ones used during mandate creation")] MandatePaymentDataMismatch { fields: String }, #[error("Field '{field_name}' is too long for connector '{connector}'")] MaxFieldLengthViolated { connector: String, field_name: String, max_length: usize, received_length: usize, }, } impl ConnectorError { /// fn is_connector_timeout pub fn is_connector_timeout(&self) -> bool { self == &Self::RequestTimeoutReceived } } impl ErrorSwitch<ConnectorError> for common_utils::errors::ParsingError { fn switch(&self) -> ConnectorError { ConnectorError::ParsingFailed } } impl ErrorSwitch<ApiErrorResponse> for ConnectorError { fn switch(&self) -> ApiErrorResponse { match self { Self::WebhookSourceVerificationFailed => ApiErrorResponse::WebhookAuthenticationFailed, Self::WebhookSignatureNotFound | Self::WebhookReferenceIdNotFound | Self::WebhookResourceObjectNotFound | Self::WebhookBodyDecodingFailed | Self::WebhooksNotImplemented => ApiErrorResponse::WebhookBadRequest, Self::WebhookEventTypeNotFound => ApiErrorResponse::WebhookUnprocessableEntity, Self::WebhookVerificationSecretInvalid => { ApiErrorResponse::WebhookInvalidMerchantSecret } _ => ApiErrorResponse::InternalServerError, } } } // http client errors #[allow(missing_docs, missing_debug_implementations)] #[derive(Debug, Clone, thiserror::Error, PartialEq)] pub enum HttpClientError { #[error("Header map construction failed")] HeaderMapConstructionFailed, #[error("Invalid proxy configuration")] InvalidProxyConfiguration, #[error("Client construction failed")] ClientConstructionFailed, #[error("Certificate decode failed")] CertificateDecodeFailed, #[error("Request body serialization failed")] BodySerializationFailed, #[error("Unexpected state reached/Invariants conflicted")] UnexpectedState, #[error("Failed to parse URL")] UrlParsingFailed, #[error("URL encoding of request payload failed")] UrlEncodingFailed, #[error("Failed to send request to connector {0}")] RequestNotSent(String), #[error("Failed to decode response")] ResponseDecodingFailed, #[error("Server responded with Request Timeout")] RequestTimeoutReceived, #[error("connection closed before a message could complete")] ConnectionClosedIncompleteMessage, #[error("Server responded with Internal Server Error")] InternalServerErrorReceived, #[error("Server responded with Bad Gateway")] BadGatewayReceived, #[error("Server responded with Service Unavailable")] ServiceUnavailableReceived, #[error("Server responded with Gateway Timeout")] GatewayTimeoutReceived, #[error("Server responded with unexpected response")] UnexpectedServerResponse, } impl ErrorSwitch<ApiClientError> for HttpClientError { fn switch(&self) -> ApiClientError { match self { Self::HeaderMapConstructionFailed => ApiClientError::HeaderMapConstructionFailed, Self::InvalidProxyConfiguration => ApiClientError::InvalidProxyConfiguration, Self::ClientConstructionFailed => ApiClientError::ClientConstructionFailed, Self::CertificateDecodeFailed => ApiClientError::CertificateDecodeFailed, Self::BodySerializationFailed => ApiClientError::BodySerializationFailed, Self::UnexpectedState => ApiClientError::UnexpectedState, Self::UrlParsingFailed => ApiClientError::UrlParsingFailed, Self::UrlEncodingFailed => ApiClientError::UrlEncodingFailed, Self::RequestNotSent(reason) => ApiClientError::RequestNotSent(reason.clone()), Self::ResponseDecodingFailed => ApiClientError::ResponseDecodingFailed, Self::RequestTimeoutReceived => ApiClientError::RequestTimeoutReceived, Self::ConnectionClosedIncompleteMessage => { ApiClientError::ConnectionClosedIncompleteMessage } Self::InternalServerErrorReceived => ApiClientError::InternalServerErrorReceived, Self::BadGatewayReceived => ApiClientError::BadGatewayReceived, Self::ServiceUnavailableReceived => ApiClientError::ServiceUnavailableReceived, Self::GatewayTimeoutReceived => ApiClientError::GatewayTimeoutReceived, Self::UnexpectedServerResponse => ApiClientError::UnexpectedServerResponse, } } }
crates/hyperswitch_interfaces/src/errors.rs
hyperswitch_interfaces::src::errors
2,045
true
// File: crates/hyperswitch_interfaces/src/api_client.rs // Module: hyperswitch_interfaces::src::api_client use std::{ fmt::Debug, time::{Duration, Instant}, }; use common_enums::ApiClientError; use common_utils::{ consts::{X_CONNECTOR_NAME, X_FLOW_NAME, X_REQUEST_ID}, errors::CustomResult, request::{Request, RequestContent}, }; use error_stack::{report, ResultExt}; use http::Method; use hyperswitch_domain_models::{ errors::api_error_response, router_data::{ErrorResponse, RouterData}, }; use masking::Maskable; use reqwest::multipart::Form; use router_env::{instrument, logger, tracing, tracing_actix_web::RequestId}; use serde_json::json; use crate::{ configs, connector_integration_interface::{ BoxedConnectorIntegrationInterface, ConnectorEnum, RouterDataConversion, }, consts, errors::ConnectorError, events, events::connector_api_logs::ConnectorEvent, metrics, types, types::Proxy, unified_connector_service, }; /// A trait representing a converter for connector names to their corresponding enum variants. pub trait ConnectorConverter: Send + Sync { /// Get the connector enum variant by its name fn get_connector_enum_by_name( &self, connector: &str, ) -> CustomResult<ConnectorEnum, api_error_response::ApiErrorResponse>; } /// A trait representing a builder for HTTP requests. pub trait RequestBuilder: Send + Sync { /// Build a JSON request fn json(&mut self, body: serde_json::Value); /// Build a URL encoded form request fn url_encoded_form(&mut self, body: serde_json::Value); /// Set the timeout duration for the request fn timeout(&mut self, timeout: Duration); /// Build a multipart request fn multipart(&mut self, form: Form); /// Add a header to the request fn header(&mut self, key: String, value: Maskable<String>) -> CustomResult<(), ApiClientError>; /// Send the request and return a future that resolves to the response fn send( self, ) -> CustomResult< Box<dyn core::future::Future<Output = Result<reqwest::Response, reqwest::Error>> + 'static>, ApiClientError, >; } /// A trait representing an API client capable of making HTTP requests. #[async_trait::async_trait] pub trait ApiClient: dyn_clone::DynClone where Self: Send + Sync, { /// Create a new request with the specified HTTP method and URL fn request( &self, method: Method, url: String, ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError>; /// Create a new request with the specified HTTP method, URL, and client certificate fn request_with_certificate( &self, method: Method, url: String, certificate: Option<masking::Secret<String>>, certificate_key: Option<masking::Secret<String>>, ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError>; /// Send a request and return the response async fn send_request( &self, state: &dyn ApiClientWrapper, request: Request, option_timeout_secs: Option<u64>, forward_to_kafka: bool, ) -> CustomResult<reqwest::Response, ApiClientError>; /// Add a request ID to the client for tracking purposes fn add_request_id(&mut self, request_id: RequestId); /// Get the current request ID, if any fn get_request_id(&self) -> Option<RequestId>; /// Get the current request ID as a string, if any fn get_request_id_str(&self) -> Option<String>; /// Add a flow name to the client for tracking purposes fn add_flow_name(&mut self, flow_name: String); } dyn_clone::clone_trait_object!(ApiClient); /// A wrapper trait to get the ApiClient and Proxy from the state pub trait ApiClientWrapper: Send + Sync { /// Get the ApiClient instance fn get_api_client(&self) -> &dyn ApiClient; /// Get the Proxy configuration fn get_proxy(&self) -> Proxy; /// Get the request ID as String if any fn get_request_id_str(&self) -> Option<String>; /// Get the request ID as &RequestId if any fn get_request_id(&self) -> Option<RequestId>; /// Get the tenant information fn get_tenant(&self) -> configs::Tenant; /// Get connectors configuration fn get_connectors(&self) -> configs::Connectors; /// Get the event handler fn event_handler(&self) -> &dyn events::EventHandlerInterface; } /// Handle the flow by interacting with connector module /// `connector_request` is applicable only in case if the `CallConnectorAction` is `Trigger` /// In other cases, It will be created if required, even if it is not passed #[instrument(skip_all, fields(connector_name, payment_method))] pub async fn execute_connector_processing_step< 'b, 'a, T, ResourceCommonData: Clone + RouterDataConversion<T, Req, Resp> + 'static, Req: Debug + Clone + 'static, Resp: Debug + Clone + 'static, >( state: &dyn ApiClientWrapper, connector_integration: BoxedConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp>, req: &'b RouterData<T, Req, Resp>, call_connector_action: common_enums::CallConnectorAction, connector_request: Option<Request>, return_raw_connector_response: Option<bool>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where T: Clone + Debug + 'static, // BoxedConnectorIntegration<T, Req, Resp>: 'b, { // If needed add an error stack as follows // connector_integration.build_request(req).attach_printable("Failed to build request"); tracing::Span::current().record("connector_name", &req.connector); tracing::Span::current().record("payment_method", req.payment_method.to_string()); logger::debug!(connector_request=?connector_request); let mut router_data = req.clone(); match call_connector_action { common_enums::CallConnectorAction::HandleResponse(res) => { let response = types::Response { headers: None, response: res.into(), status_code: 200, }; connector_integration.handle_response(req, None, response) } common_enums::CallConnectorAction::UCSHandleResponse(transform_data_bytes) => { handle_ucs_response(router_data, transform_data_bytes) } common_enums::CallConnectorAction::Avoid => Ok(router_data), common_enums::CallConnectorAction::StatusUpdate { status, error_code, error_message, } => { router_data.status = status; let error_response = if error_code.is_some() | error_message.is_some() { Some(ErrorResponse { code: error_code.unwrap_or(consts::NO_ERROR_CODE.to_string()), message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), status_code: 200, // This status code is ignored in redirection response it will override with 302 status code. reason: None, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { None }; router_data.response = error_response.map(Err).unwrap_or(router_data.response); Ok(router_data) } common_enums::CallConnectorAction::Trigger => { metrics::CONNECTOR_CALL_COUNT.add( 1, router_env::metric_attributes!( ("connector", req.connector.to_string()), ( "flow", get_flow_name::<T>().unwrap_or_else(|_| "UnknownFlow".to_string()) ), ), ); let connector_request = match connector_request { Some(connector_request) => Some(connector_request), None => connector_integration .build_request(req, &state.get_connectors()) .inspect_err(|error| { if matches!( error.current_context(), &ConnectorError::RequestEncodingFailed | &ConnectorError::RequestEncodingFailedWithReason(_) ) { metrics::REQUEST_BUILD_FAILURE.add( 1, router_env::metric_attributes!(( "connector", req.connector.clone() )), ) } })?, }; match connector_request { Some(mut request) => { let masked_request_body = match &request.body { Some(request) => match request { RequestContent::Json(i) | RequestContent::FormUrlEncoded(i) | RequestContent::Xml(i) => i .masked_serialize() .unwrap_or(json!({ "error": "failed to mask serialize"})), RequestContent::FormData((_, i)) => i .masked_serialize() .unwrap_or(json!({ "error": "failed to mask serialize"})), RequestContent::RawBytes(_) => json!({"request_type": "RAW_BYTES"}), }, None => serde_json::Value::Null, }; let flow_name = get_flow_name::<T>().unwrap_or_else(|_| "UnknownFlow".to_string()); request.headers.insert(( X_FLOW_NAME.to_string(), Maskable::Masked(masking::Secret::new(flow_name.to_string())), )); let connector_name = req.connector.clone(); request.headers.insert(( X_CONNECTOR_NAME.to_string(), Maskable::Masked(masking::Secret::new(connector_name.clone().to_string())), )); state.get_request_id().as_ref().map(|id| { let request_id = id.to_string(); request.headers.insert(( X_REQUEST_ID.to_string(), Maskable::Normal(request_id.clone()), )); request_id }); let request_url = request.url.clone(); let request_method = request.method; let current_time = Instant::now(); let response = call_connector_api(state, request, "execute_connector_processing_step") .await; let external_latency = current_time.elapsed().as_millis(); logger::info!(raw_connector_request=?masked_request_body); let status_code = response .as_ref() .map(|i| { i.as_ref() .map_or_else(|value| value.status_code, |value| value.status_code) }) .unwrap_or_default(); let mut connector_event = ConnectorEvent::new( state.get_tenant().tenant_id.clone(), req.connector.clone(), std::any::type_name::<T>(), masked_request_body, request_url, request_method, req.payment_id.clone(), req.merchant_id.clone(), state.get_request_id().as_ref(), external_latency, req.refund_id.clone(), req.dispute_id.clone(), status_code, ); match response { Ok(body) => { let response = match body { Ok(body) => { let connector_http_status_code = Some(body.status_code); let handle_response_result = connector_integration .handle_response( req, Some(&mut connector_event), body.clone(), ) .inspect_err(|error| { if error.current_context() == &ConnectorError::ResponseDeserializationFailed { metrics::RESPONSE_DESERIALIZATION_FAILURE.add( 1, router_env::metric_attributes!(( "connector", req.connector.clone(), )), ) } }); match handle_response_result { Ok(mut data) => { state .event_handler() .log_connector_event(&connector_event); data.connector_http_status_code = connector_http_status_code; // Add up multiple external latencies in case of multiple external calls within the same request. data.external_latency = Some( data.external_latency .map_or(external_latency, |val| { val + external_latency }), ); store_raw_connector_response_if_required( return_raw_connector_response, &mut data, &body, )?; Ok(data) } Err(err) => { connector_event .set_error(json!({"error": err.to_string()})); state .event_handler() .log_connector_event(&connector_event); Err(err) } }? } Err(body) => { router_data.connector_http_status_code = Some(body.status_code); router_data.external_latency = Some( router_data .external_latency .map_or(external_latency, |val| val + external_latency), ); metrics::CONNECTOR_ERROR_RESPONSE_COUNT.add( 1, router_env::metric_attributes!(( "connector", req.connector.clone(), )), ); store_raw_connector_response_if_required( return_raw_connector_response, &mut router_data, &body, )?; let error = match body.status_code { 500..=511 => { let error_res = connector_integration .get_5xx_error_response( body, Some(&mut connector_event), )?; state .event_handler() .log_connector_event(&connector_event); error_res } _ => { let error_res = connector_integration .get_error_response( body, Some(&mut connector_event), )?; if let Some(status) = error_res.attempt_status { router_data.status = status; }; state .event_handler() .log_connector_event(&connector_event); error_res } }; router_data.response = Err(error); router_data } }; Ok(response) } Err(error) => { connector_event.set_error(json!({"error": error.to_string()})); state.event_handler().log_connector_event(&connector_event); if error.current_context().is_upstream_timeout() { let error_response = ErrorResponse { code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(), message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(), reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()), status_code: 504, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }; router_data.response = Err(error_response); router_data.connector_http_status_code = Some(504); router_data.external_latency = Some( router_data .external_latency .map_or(external_latency, |val| val + external_latency), ); Ok(router_data) } else { Err(error .change_context(ConnectorError::ProcessingStepFailed(None))) } } } } None => Ok(router_data), } } } } /// Handle UCS webhook response processing pub fn handle_ucs_response<T, Req, Resp>( router_data: RouterData<T, Req, Resp>, transform_data_bytes: Vec<u8>, ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> where T: Clone + Debug + 'static, Req: Debug + Clone + 'static, Resp: Debug + Clone + 'static, { let webhook_transform_data: unified_connector_service::WebhookTransformData = serde_json::from_slice(&transform_data_bytes) .change_context(ConnectorError::ResponseDeserializationFailed) .attach_printable("Failed to deserialize UCS webhook transform data")?; let webhook_content = webhook_transform_data .webhook_content .ok_or(ConnectorError::ResponseDeserializationFailed) .attach_printable("UCS webhook transform data missing webhook_content")?; let payment_get_response = match webhook_content.content { Some(unified_connector_service_client::payments::webhook_response_content::Content::PaymentsResponse(payments_response)) => { Ok(payments_response) }, Some(unified_connector_service_client::payments::webhook_response_content::Content::RefundsResponse(_)) => { Err(ConnectorError::ProcessingStepFailed(Some("UCS webhook contains refund response but payment processing was expected".to_string().into())).into()) }, Some(unified_connector_service_client::payments::webhook_response_content::Content::DisputesResponse(_)) => { Err(ConnectorError::ProcessingStepFailed(Some("UCS webhook contains dispute response but payment processing was expected".to_string().into())).into()) }, Some(unified_connector_service_client::payments::webhook_response_content::Content::IncompleteTransformation(_)) => { Err(ConnectorError::ProcessingStepFailed(Some("UCS webhook contains incomplete transformation but payment processing was expected".to_string().into())).into()) }, None => { Err(ConnectorError::ResponseDeserializationFailed) .attach_printable("UCS webhook content missing payments_response") } }?; let (router_data_response, status_code) = unified_connector_service::handle_unified_connector_service_response_for_payment_get( payment_get_response.clone(), ) .change_context(ConnectorError::ProcessingStepFailed(None)) .attach_printable("Failed to process UCS webhook response using PSync handler")?; let mut updated_router_data = router_data; let router_data_response = router_data_response.map(|(response, status)| { updated_router_data.status = status; response }); let _ = router_data_response.map_err(|error_response| { updated_router_data.response = Err(error_response); }); updated_router_data.raw_connector_response = payment_get_response .raw_connector_response .map(masking::Secret::new); updated_router_data.connector_http_status_code = Some(status_code); Ok(updated_router_data) } /// Calls the connector API and handles the response #[instrument(skip_all)] pub async fn call_connector_api( state: &dyn ApiClientWrapper, request: Request, flow_name: &str, ) -> CustomResult<Result<types::Response, types::Response>, ApiClientError> { let current_time = Instant::now(); let headers = request.headers.clone(); let url = request.url.clone(); let response = state .get_api_client() .send_request(state, request, None, true) .await; match response.as_ref() { Ok(resp) => { let status_code = resp.status().as_u16(); let elapsed_time = current_time.elapsed(); logger::info!( ?headers, url, status_code, flow=?flow_name, ?elapsed_time ); } Err(err) => { logger::info!( call_connector_api_error=?err ); } } handle_response(response).await } /// Handle the response from the API call #[instrument(skip_all)] pub async fn handle_response( response: CustomResult<reqwest::Response, ApiClientError>, ) -> CustomResult<Result<types::Response, types::Response>, ApiClientError> { response .map(|response| async { logger::info!(?response); let status_code = response.status().as_u16(); let headers = Some(response.headers().to_owned()); match status_code { 200..=202 | 302 | 204 => { // If needed add log line // logger:: error!( error_parsing_response=?err); let response = response .bytes() .await .change_context(ApiClientError::ResponseDecodingFailed) .attach_printable("Error while waiting for response")?; Ok(Ok(types::Response { headers, response, status_code, })) } status_code @ 500..=599 => { let bytes = response.bytes().await.map_err(|error| { report!(error) .change_context(ApiClientError::ResponseDecodingFailed) .attach_printable("Client error response received") })?; // let error = match status_code { // 500 => ApiClientError::InternalServerErrorReceived, // 502 => ApiClientError::BadGatewayReceived, // 503 => ApiClientError::ServiceUnavailableReceived, // 504 => ApiClientError::GatewayTimeoutReceived, // _ => ApiClientError::UnexpectedServerResponse, // }; Ok(Err(types::Response { headers, response: bytes, status_code, })) } status_code @ 400..=499 => { let bytes = response.bytes().await.map_err(|error| { report!(error) .change_context(ApiClientError::ResponseDecodingFailed) .attach_printable("Client error response received") })?; /* let error = match status_code { 400 => ApiClientError::BadRequestReceived(bytes), 401 => ApiClientError::UnauthorizedReceived(bytes), 403 => ApiClientError::ForbiddenReceived, 404 => ApiClientError::NotFoundReceived(bytes), 405 => ApiClientError::MethodNotAllowedReceived, 408 => ApiClientError::RequestTimeoutReceived, 422 => ApiClientError::UnprocessableEntityReceived(bytes), 429 => ApiClientError::TooManyRequestsReceived, _ => ApiClientError::UnexpectedServerResponse, }; Err(report!(error).attach_printable("Client error response received")) */ Ok(Err(types::Response { headers, response: bytes, status_code, })) } _ => Err(report!(ApiClientError::UnexpectedServerResponse) .attach_printable("Unexpected response from server")), } })? .await } /// Store the raw connector response in the router data if required pub fn store_raw_connector_response_if_required<T, Req, Resp>( return_raw_connector_response: Option<bool>, router_data: &mut RouterData<T, Req, Resp>, body: &types::Response, ) -> CustomResult<(), ConnectorError> where T: Clone + Debug + 'static, Req: Debug + Clone + 'static, Resp: Debug + Clone + 'static, { if return_raw_connector_response == Some(true) { let mut decoded = String::from_utf8(body.response.as_ref().to_vec()) .change_context(ConnectorError::ResponseDeserializationFailed)?; if decoded.starts_with('\u{feff}') { decoded = decoded.trim_start_matches('\u{feff}').to_string(); } router_data.raw_connector_response = Some(masking::Secret::new(decoded)); } Ok(()) } /// Get the flow name from the type #[inline] pub fn get_flow_name<F>() -> CustomResult<String, api_error_response::ApiErrorResponse> { Ok(std::any::type_name::<F>() .to_string() .rsplit("::") .next() .ok_or(api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Flow stringify failed")? .to_string()) }
crates/hyperswitch_interfaces/src/api_client.rs
hyperswitch_interfaces::src::api_client
4,976
true
// File: crates/hyperswitch_interfaces/src/connector_integration_v2.rs // Module: hyperswitch_interfaces::src::connector_integration_v2 //! definition of the new connector integration trait use common_utils::{ errors::CustomResult, request::{Method, Request, RequestBuilder, RequestContent}, }; use hyperswitch_domain_models::{router_data::ErrorResponse, router_data_v2::RouterDataV2}; use masking::Maskable; use serde_json::json; use crate::{ api::{self, subscriptions_v2, CaptureSyncMethod}, errors, events::connector_api_logs::ConnectorEvent, metrics, types, webhooks, }; /// ConnectorV2 trait pub trait ConnectorV2: Send + api::refunds_v2::RefundV2 + api::payments_v2::PaymentV2 + api::ConnectorRedirectResponse + webhooks::IncomingWebhook + api::ConnectorAuthenticationTokenV2 + api::ConnectorAccessTokenV2 + api::disputes_v2::DisputeV2 + api::files_v2::FileUploadV2 + api::ConnectorTransactionId + api::PayoutsV2 + api::ConnectorVerifyWebhookSourceV2 + api::FraudCheckV2 + api::ConnectorMandateRevokeV2 + api::authentication_v2::ExternalAuthenticationV2 + api::UnifiedAuthenticationServiceV2 + api::revenue_recovery_v2::RevenueRecoveryV2 + api::ExternalVaultV2 + subscriptions_v2::SubscriptionsV2 { } impl< T: api::refunds_v2::RefundV2 + api::payments_v2::PaymentV2 + api::ConnectorRedirectResponse + Send + webhooks::IncomingWebhook + api::ConnectorAuthenticationTokenV2 + api::ConnectorAccessTokenV2 + api::disputes_v2::DisputeV2 + api::files_v2::FileUploadV2 + api::ConnectorTransactionId + api::PayoutsV2 + api::ConnectorVerifyWebhookSourceV2 + api::FraudCheckV2 + api::ConnectorMandateRevokeV2 + api::authentication_v2::ExternalAuthenticationV2 + api::UnifiedAuthenticationServiceV2 + api::revenue_recovery_v2::RevenueRecoveryV2 + api::ExternalVaultV2 + subscriptions_v2::SubscriptionsV2, > ConnectorV2 for T { } /// Alias for Box<&'static (dyn ConnectorV2 + Sync)> pub type BoxedConnectorV2 = Box<&'static (dyn ConnectorV2 + Sync)>; /// alias for Box of a type that implements trait ConnectorIntegrationV2 pub type BoxedConnectorIntegrationV2<'a, Flow, ResourceCommonData, Req, Resp> = Box<&'a (dyn ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp> + Send + Sync)>; /// trait with a function that returns BoxedConnectorIntegrationV2 pub trait ConnectorIntegrationAnyV2<Flow, ResourceCommonData, Req, Resp>: Send + Sync + 'static { /// function what returns BoxedConnectorIntegrationV2 fn get_connector_integration_v2( &self, ) -> BoxedConnectorIntegrationV2<'_, Flow, ResourceCommonData, Req, Resp>; } impl<S, Flow, ResourceCommonData, Req, Resp> ConnectorIntegrationAnyV2<Flow, ResourceCommonData, Req, Resp> for S where S: ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp> + Send + Sync, { fn get_connector_integration_v2( &self, ) -> BoxedConnectorIntegrationV2<'_, Flow, ResourceCommonData, Req, Resp> { Box::new(self) } } /// The new connector integration trait with an additional ResourceCommonData generic parameter pub trait ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp>: ConnectorIntegrationAnyV2<Flow, ResourceCommonData, Req, Resp> + Sync + api::ConnectorCommon { /// returns a vec of tuple of header key and value fn get_headers( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(vec![]) } /// returns content type fn get_content_type(&self) -> &'static str { mime::APPLICATION_JSON.essence_str() } /// primarily used when creating signature based on request method of payment flow fn get_http_method(&self) -> Method { Method::Post } /// returns url fn get_url( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<String, errors::ConnectorError> { metrics::UNIMPLEMENTED_FLOW .add(1, router_env::metric_attributes!(("connector", self.id()))); Ok(String::new()) } /// returns request body fn get_request_body( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Option<RequestContent>, errors::ConnectorError> { Ok(None) } /// returns form data fn get_request_form_data( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Option<reqwest::multipart::Form>, errors::ConnectorError> { Ok(None) } /// builds the request and returns it fn build_request_v2( &self, req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(self.get_http_method()) .url(self.get_url(req)?.as_str()) .attach_default_headers() .headers(self.get_headers(req)?) .set_optional_body(self.get_request_body(req)?) .add_certificate(self.get_certificate(req)?) .add_certificate_key(self.get_certificate_key(req)?) .build(), )) } /// accepts the raw api response and decodes it fn handle_response_v2( &self, data: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, event_builder: Option<&mut ConnectorEvent>, _res: types::Response, ) -> CustomResult<RouterDataV2<Flow, ResourceCommonData, Req, Resp>, errors::ConnectorError> where Flow: Clone, ResourceCommonData: Clone, Req: Clone, Resp: Clone, { event_builder.map(|e| e.set_error(json!({"error": "Not Implemented"}))); Ok(data.clone()) } /// accepts the raw api error response and decodes it fn get_error_response_v2( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); Ok(ErrorResponse::get_not_implemented()) } /// accepts the raw 5xx error response and decodes it fn get_5xx_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); let error_message = match res.status_code { 500 => "internal_server_error", 501 => "not_implemented", 502 => "bad_gateway", 503 => "service_unavailable", 504 => "gateway_timeout", 505 => "http_version_not_supported", 506 => "variant_also_negotiates", 507 => "insufficient_storage", 508 => "loop_detected", 510 => "not_extended", 511 => "network_authentication_required", _ => "unknown_error", }; Ok(ErrorResponse { code: res.status_code.to_string(), message: error_message.to_string(), reason: String::from_utf8(res.response.to_vec()).ok(), status_code: res.status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } // whenever capture sync is implemented at the connector side, this method should be overridden /// retunes the capture sync method fn get_multiple_capture_sync_method( &self, ) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("multiple capture sync".into()).into()) } /// returns certificate string fn get_certificate( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Option<masking::Secret<String>>, errors::ConnectorError> { Ok(None) } /// returns private key string fn get_certificate_key( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Option<masking::Secret<String>>, errors::ConnectorError> { Ok(None) } }
crates/hyperswitch_interfaces/src/connector_integration_v2.rs
hyperswitch_interfaces::src::connector_integration_v2
2,158
true
// File: crates/hyperswitch_interfaces/src/authentication.rs // Module: hyperswitch_interfaces::src::authentication //! Authentication interface /// struct ExternalAuthenticationPayload #[derive(Clone, serde::Deserialize, Debug, serde::Serialize, PartialEq, Eq)] pub struct ExternalAuthenticationPayload { /// trans_status pub trans_status: common_enums::TransactionStatus, /// authentication_value pub authentication_value: Option<masking::Secret<String>>, /// eci pub eci: Option<String>, /// Indicates whether the challenge was canceled by the user or system. pub challenge_cancel: Option<String>, /// Reason for the challenge code, if applicable. pub challenge_code_reason: Option<String>, }
crates/hyperswitch_interfaces/src/authentication.rs
hyperswitch_interfaces::src::authentication
149
true
// File: crates/hyperswitch_interfaces/src/api.rs // Module: hyperswitch_interfaces::src::api //! API interface /// authentication module pub mod authentication; /// authentication_v2 module pub mod authentication_v2; pub mod disputes; pub mod disputes_v2; pub mod files; pub mod files_v2; #[cfg(feature = "frm")] pub mod fraud_check; #[cfg(feature = "frm")] pub mod fraud_check_v2; pub mod payments; pub mod payments_v2; #[cfg(feature = "payouts")] pub mod payouts; #[cfg(feature = "payouts")] pub mod payouts_v2; pub mod refunds; pub mod refunds_v2; pub mod revenue_recovery; pub mod revenue_recovery_v2; pub mod subscriptions; pub mod subscriptions_v2; pub mod vault; pub mod vault_v2; use std::fmt::Debug; use common_enums::{ enums::{CallConnectorAction, CaptureMethod, EventClass, PaymentAction, PaymentMethodType}, PaymentMethod, }; use common_utils::{ errors::CustomResult, request::{Method, Request, RequestContent}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ connector_endpoints::Connectors, errors::api_error_response::ApiErrorResponse, payment_method_data::PaymentMethodData, router_data::{ AccessToken, AccessTokenAuthenticationResponse, ConnectorAuthType, ErrorResponse, RouterData, }, router_data_v2::{ flow_common_types::{AuthenticationTokenFlowData, WebhookSourceVerifyData}, AccessTokenFlowData, MandateRevokeFlowData, UasFlowData, }, router_flow_types::{ mandate_revoke::MandateRevoke, AccessTokenAuth, AccessTokenAuthentication, Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, VerifyWebhookSource, }, router_request_types::{ unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, AccessTokenAuthenticationRequestData, AccessTokenRequestData, MandateRevokeRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, SupportedPaymentMethods, VerifyWebhookSourceResponseData, }, }; use masking::Maskable; use serde_json::json; #[cfg(feature = "frm")] pub use self::fraud_check::*; #[cfg(feature = "frm")] pub use self::fraud_check_v2::*; #[cfg(feature = "payouts")] pub use self::payouts::*; #[cfg(feature = "payouts")] pub use self::payouts_v2::*; pub use self::{payments::*, refunds::*, vault::*, vault_v2::*}; use crate::{ api::subscriptions::Subscriptions, connector_integration_v2::ConnectorIntegrationV2, consts, errors, events::connector_api_logs::ConnectorEvent, metrics, types, webhooks, }; /// Connector trait pub trait Connector: Send + Refund + Payment + ConnectorRedirectResponse + webhooks::IncomingWebhook + ConnectorAccessToken + ConnectorAuthenticationToken + disputes::Dispute + files::FileUpload + ConnectorTransactionId + Payouts + ConnectorVerifyWebhookSource + FraudCheck + ConnectorMandateRevoke + authentication::ExternalAuthentication + TaxCalculation + UnifiedAuthenticationService + revenue_recovery::RevenueRecovery + ExternalVault + Subscriptions { } impl< T: Refund + Payment + ConnectorRedirectResponse + Send + webhooks::IncomingWebhook + ConnectorAccessToken + ConnectorAuthenticationToken + disputes::Dispute + files::FileUpload + ConnectorTransactionId + Payouts + ConnectorVerifyWebhookSource + FraudCheck + ConnectorMandateRevoke + authentication::ExternalAuthentication + TaxCalculation + UnifiedAuthenticationService + revenue_recovery::RevenueRecovery + ExternalVault + Subscriptions, > Connector for T { } /// Alias for Box<&'static (dyn Connector + Sync)> pub type BoxedConnector = Box<&'static (dyn Connector + Sync)>; /// type BoxedConnectorIntegration pub type BoxedConnectorIntegration<'a, T, Req, Resp> = Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>; /// trait ConnectorIntegrationAny pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static { /// fn get_connector_integration fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>; } impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S where S: ConnectorIntegration<T, Req, Resp> + Send + Sync, { fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp> { Box::new(self) } } /// trait ConnectorIntegration pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Resp> + Sync + ConnectorCommon { /// fn get_headers fn get_headers( &self, _req: &RouterData<T, Req, Resp>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(vec![]) } /// fn get_content_type fn get_content_type(&self) -> &'static str { mime::APPLICATION_JSON.essence_str() } /// fn get_content_type fn get_accept_type(&self) -> &'static str { mime::APPLICATION_JSON.essence_str() } /// primarily used when creating signature based on request method of payment flow fn get_http_method(&self) -> Method { Method::Post } /// fn get_url fn get_url( &self, _req: &RouterData<T, Req, Resp>, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(String::new()) } /// fn get_request_body fn get_request_body( &self, _req: &RouterData<T, Req, Resp>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { Ok(RequestContent::Json(Box::new(json!(r#"{}"#)))) } /// fn get_request_form_data fn get_request_form_data( &self, _req: &RouterData<T, Req, Resp>, ) -> CustomResult<Option<reqwest::multipart::Form>, errors::ConnectorError> { Ok(None) } /// fn build_request fn build_request( &self, req: &RouterData<T, Req, Resp>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { metrics::UNIMPLEMENTED_FLOW.add( 1, router_env::metric_attributes!(("connector", req.connector.clone())), ); Ok(None) } /// fn handle_response fn handle_response( &self, data: &RouterData<T, Req, Resp>, event_builder: Option<&mut ConnectorEvent>, _res: types::Response, ) -> CustomResult<RouterData<T, Req, Resp>, errors::ConnectorError> where T: Clone, Req: Clone, Resp: Clone, { event_builder.map(|e| e.set_error(json!({"error": "Not Implemented"}))); Ok(data.clone()) } /// fn get_error_response fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); Ok(ErrorResponse::get_not_implemented()) } /// fn get_5xx_error_response fn get_5xx_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); let error_message = match res.status_code { 500 => "internal_server_error", 501 => "not_implemented", 502 => "bad_gateway", 503 => "service_unavailable", 504 => "gateway_timeout", 505 => "http_version_not_supported", 506 => "variant_also_negotiates", 507 => "insufficient_storage", 508 => "loop_detected", 510 => "not_extended", 511 => "network_authentication_required", _ => "unknown_error", }; Ok(ErrorResponse { code: res.status_code.to_string(), message: error_message.to_string(), reason: String::from_utf8(res.response.to_vec()).ok(), status_code: res.status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } /// whenever capture sync is implemented at the connector side, this method should be overridden fn get_multiple_capture_sync_method( &self, ) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("multiple capture sync".into()).into()) } /// fn get_certificate fn get_certificate( &self, _req: &RouterData<T, Req, Resp>, ) -> CustomResult<Option<String>, errors::ConnectorError> { Ok(None) } /// fn get_certificate_key fn get_certificate_key( &self, _req: &RouterData<T, Req, Resp>, ) -> CustomResult<Option<String>, errors::ConnectorError> { Ok(None) } } /// Sync Methods for multiple captures #[derive(Debug)] pub enum CaptureSyncMethod { /// For syncing multiple captures individually Individual, /// For syncing multiple captures together Bulk, } /// Connector accepted currency unit as either "Base" or "Minor" #[derive(Debug)] pub enum CurrencyUnit { /// Base currency unit Base, /// Minor currency unit Minor, } /// The trait that provides the common pub trait ConnectorCommon { /// Name of the connector (in lowercase). fn id(&self) -> &'static str; /// Connector accepted currency unit as either "Base" or "Minor" fn get_currency_unit(&self) -> CurrencyUnit { CurrencyUnit::Minor // Default implementation should be remove once it is implemented in all connectors } /// HTTP header used for authorization. fn get_auth_header( &self, _auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(Vec::new()) } /// HTTP `Content-Type` to be used for POST requests. /// Defaults to `application/json`. fn common_get_content_type(&self) -> &'static str { "application/json" } // FIXME write doc - think about this // fn headers(&self) -> Vec<(&str, &str)>; /// The base URL for interacting with the connector's API. fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str; /// common error response for a connector if it is same in all case fn build_error_response( &self, res: types::Response, _event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { Ok(ErrorResponse { status_code: res.status_code, code: consts::NO_ERROR_CODE.to_string(), message: consts::NO_ERROR_MESSAGE.to_string(), reason: None, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } /// The trait that provides specifications about the connector pub trait ConnectorSpecifications { /// Details related to payment method supported by the connector fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { None } /// Supported webhooks flows fn get_supported_webhook_flows(&self) -> Option<&'static [EventClass]> { None } /// About the connector fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { None } /// Check if connector should make another request to create an access token /// Connectors should override this method if they require an authentication token to create a new access token fn authentication_token_for_token_creation(&self) -> bool { false } /// Check if connector should make another request to create an customer /// Connectors should override this method if they require to create a connector customer fn should_call_connector_customer( &self, _payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> bool { false } /// Whether SDK session token generation is enabled for this connector fn is_sdk_client_token_generation_enabled(&self) -> bool { false } /// Payment method types that support SDK session token generation fn supported_payment_method_types_for_sdk_client_token_generation( &self, ) -> Vec<PaymentMethodType> { vec![] } /// Validate if SDK session token generation is allowed for given payment method type fn validate_sdk_session_token_for_payment_method( &self, current_core_payment_method_type: &PaymentMethodType, ) -> bool { self.is_sdk_client_token_generation_enabled() && self .supported_payment_method_types_for_sdk_client_token_generation() .contains(current_core_payment_method_type) } #[cfg(not(feature = "v2"))] /// Generate connector request reference ID fn generate_connector_request_reference_id( &self, _payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, is_config_enabled_to_send_payment_id_as_connector_request_id: bool, ) -> String { // Send payment_id if config is enabled for a merchant, else send attempt_id if is_config_enabled_to_send_payment_id_as_connector_request_id { payment_attempt.payment_id.get_string_repr().to_owned() } else { payment_attempt.attempt_id.to_owned() } } #[cfg(feature = "v2")] /// Generate connector request reference ID fn generate_connector_request_reference_id( &self, payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> String { payment_intent .merchant_reference_id .as_ref() .map(|id| id.get_string_repr().to_owned()) .unwrap_or_else(|| payment_attempt.id.get_string_repr().to_owned()) } } /// Extended trait for connector common to allow functions with generic type pub trait ConnectorCommonExt<Flow, Req, Resp>: ConnectorCommon + ConnectorIntegration<Flow, Req, Resp> { /// common header builder when every request for the connector have same headers fn build_headers( &self, _req: &RouterData<Flow, Req, Resp>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(Vec::new()) } } /// trait ConnectorMandateRevoke pub trait ConnectorMandateRevoke: ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData> { } /// trait ConnectorMandateRevokeV2 pub trait ConnectorMandateRevokeV2: ConnectorIntegrationV2< MandateRevoke, MandateRevokeFlowData, MandateRevokeRequestData, MandateRevokeResponseData, > { } /// trait ConnectorAuthenticationToken pub trait ConnectorAuthenticationToken: ConnectorIntegration< AccessTokenAuthentication, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse, > { } /// trait ConnectorAuthenticationTokenV2 pub trait ConnectorAuthenticationTokenV2: ConnectorIntegrationV2< AccessTokenAuthentication, AuthenticationTokenFlowData, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse, > { } /// trait ConnectorAccessToken pub trait ConnectorAccessToken: ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> { } /// trait ConnectorAccessTokenV2 pub trait ConnectorAccessTokenV2: ConnectorIntegrationV2<AccessTokenAuth, AccessTokenFlowData, AccessTokenRequestData, AccessToken> { } /// trait ConnectorVerifyWebhookSource pub trait ConnectorVerifyWebhookSource: ConnectorIntegration< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, > { } /// trait ConnectorVerifyWebhookSourceV2 pub trait ConnectorVerifyWebhookSourceV2: ConnectorIntegrationV2< VerifyWebhookSource, WebhookSourceVerifyData, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, > { } /// trait UnifiedAuthenticationService pub trait UnifiedAuthenticationService: ConnectorCommon + UasPreAuthentication + UasPostAuthentication + UasAuthenticationConfirmation + UasAuthentication { } /// trait UasPreAuthentication pub trait UasPreAuthentication: ConnectorIntegration< PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData, > { } /// trait UasPostAuthentication pub trait UasPostAuthentication: ConnectorIntegration< PostAuthenticate, UasPostAuthenticationRequestData, UasAuthenticationResponseData, > { } /// trait UasAuthenticationConfirmation pub trait UasAuthenticationConfirmation: ConnectorIntegration< AuthenticationConfirmation, UasConfirmationRequestData, UasAuthenticationResponseData, > { } /// trait UasAuthentication pub trait UasAuthentication: ConnectorIntegration<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData> { } /// trait UnifiedAuthenticationServiceV2 pub trait UnifiedAuthenticationServiceV2: ConnectorCommon + UasPreAuthenticationV2 + UasPostAuthenticationV2 + UasAuthenticationV2 + UasAuthenticationConfirmationV2 { } ///trait UasPreAuthenticationV2 pub trait UasPreAuthenticationV2: ConnectorIntegrationV2< PreAuthenticate, UasFlowData, UasPreAuthenticationRequestData, UasAuthenticationResponseData, > { } /// trait UasPostAuthenticationV2 pub trait UasPostAuthenticationV2: ConnectorIntegrationV2< PostAuthenticate, UasFlowData, UasPostAuthenticationRequestData, UasAuthenticationResponseData, > { } /// trait UasAuthenticationConfirmationV2 pub trait UasAuthenticationConfirmationV2: ConnectorIntegrationV2< AuthenticationConfirmation, UasFlowData, UasConfirmationRequestData, UasAuthenticationResponseData, > { } /// trait UasAuthenticationV2 pub trait UasAuthenticationV2: ConnectorIntegrationV2< Authenticate, UasFlowData, UasAuthenticationRequestData, UasAuthenticationResponseData, > { } /// trait ConnectorValidation pub trait ConnectorValidation: ConnectorCommon + ConnectorSpecifications { /// Validate, the payment request against the connector supported features fn validate_connector_against_payment_request( &self, capture_method: Option<CaptureMethod>, payment_method: PaymentMethod, pmt: Option<PaymentMethodType>, ) -> CustomResult<(), errors::ConnectorError> { let capture_method = capture_method.unwrap_or_default(); let is_default_capture_method = [CaptureMethod::Automatic, CaptureMethod::SequentialAutomatic] .contains(&capture_method); let is_feature_supported = match self.get_supported_payment_methods() { Some(supported_payment_methods) => { let connector_payment_method_type_info = get_connector_payment_method_type_info( supported_payment_methods, payment_method, pmt, self.id(), )?; connector_payment_method_type_info .map(|payment_method_type_info| { payment_method_type_info .supported_capture_methods .contains(&capture_method) }) .unwrap_or(true) } None => is_default_capture_method, }; if is_feature_supported { Ok(()) } else { Err(errors::ConnectorError::NotSupported { message: capture_method.to_string(), connector: self.id(), } .into()) } } /// fn validate_mandate_payment fn validate_mandate_payment( &self, pm_type: Option<PaymentMethodType>, _pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { let connector = self.id(); match pm_type { Some(pm_type) => Err(errors::ConnectorError::NotSupported { message: format!("{pm_type} mandate payment"), connector, } .into()), None => Err(errors::ConnectorError::NotSupported { message: " mandate payment".to_string(), connector, } .into()), } } /// fn validate_psync_reference_id fn validate_psync_reference_id( &self, data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, _is_three_ds: bool, _status: common_enums::enums::AttemptStatus, _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { data.connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID) .map(|_| ()) } /// fn is_webhook_source_verification_mandatory fn is_webhook_source_verification_mandatory(&self) -> bool { false } } /// trait ConnectorRedirectResponse pub trait ConnectorRedirectResponse { /// fn get_flow_type fn get_flow_type( &self, _query_params: &str, _json_payload: Option<serde_json::Value>, _action: PaymentAction, ) -> CustomResult<CallConnectorAction, errors::ConnectorError> { Ok(CallConnectorAction::Avoid) } } /// Empty trait for when payouts feature is disabled #[cfg(not(feature = "payouts"))] pub trait Payouts {} /// Empty trait for when payouts feature is disabled #[cfg(not(feature = "payouts"))] pub trait PayoutsV2 {} /// Empty trait for when frm feature is disabled #[cfg(not(feature = "frm"))] pub trait FraudCheck {} /// Empty trait for when frm feature is disabled #[cfg(not(feature = "frm"))] pub trait FraudCheckV2 {} fn get_connector_payment_method_type_info( supported_payment_method: &SupportedPaymentMethods, payment_method: PaymentMethod, payment_method_type: Option<PaymentMethodType>, connector: &'static str, ) -> CustomResult<Option<PaymentMethodDetails>, errors::ConnectorError> { let payment_method_details = supported_payment_method .get(&payment_method) .ok_or_else(|| errors::ConnectorError::NotSupported { message: payment_method.to_string(), connector, })?; payment_method_type .map(|pmt| { payment_method_details.get(&pmt).cloned().ok_or_else(|| { errors::ConnectorError::NotSupported { message: format!("{payment_method} {pmt}"), connector, } .into() }) }) .transpose() } /// ConnectorTransactionId trait pub trait ConnectorTransactionId: ConnectorCommon + Sync { /// fn connector_transaction_id fn connector_transaction_id( &self, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> Result<Option<String>, ApiErrorResponse> { Ok(payment_attempt .get_connector_payment_id() .map(ToString::to_string)) } }
crates/hyperswitch_interfaces/src/api.rs
hyperswitch_interfaces::src::api
5,320
true
// File: crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs // Module: hyperswitch_interfaces::src::secrets_interface::secret_handler //! Module containing trait for raw secret retrieval use common_utils::errors::CustomResult; use crate::secrets_interface::{ secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, SecretManagementInterface, SecretsManagementError, }; /// Trait defining the interface for retrieving a raw secret value, given a secured value #[async_trait::async_trait] pub trait SecretsHandler where Self: Sized, { /// Construct `Self` with raw secret value and transitions its type from `SecuredSecret` to `RawSecret` async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, kms_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError>; }
crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs
hyperswitch_interfaces::src::secrets_interface::secret_handler
195
true
// File: crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs // Module: hyperswitch_interfaces::src::secrets_interface::secret_state //! Module to manage encrypted and decrypted states for a given type. use std::marker::PhantomData; use serde::{Deserialize, Deserializer}; /// Trait defining the states of a secret pub trait SecretState {} /// Decrypted state #[derive(Debug, Clone, Deserialize, Default)] pub struct RawSecret {} /// Encrypted state #[derive(Debug, Clone, Deserialize, Default)] pub struct SecuredSecret {} impl SecretState for RawSecret {} impl SecretState for SecuredSecret {} /// Struct for managing the encrypted and decrypted states of a given type #[derive(Debug, Clone, Default)] pub struct SecretStateContainer<T, S: SecretState> { inner: T, marker: PhantomData<S>, } impl<T: Clone, S: SecretState> SecretStateContainer<T, S> { /// Get the inner data while consuming self #[inline] pub fn into_inner(self) -> T { self.inner } /// Get the reference to inner value #[inline] pub fn get_inner(&self) -> &T { &self.inner } } impl<'de, T: Deserialize<'de>, S: SecretState> Deserialize<'de> for SecretStateContainer<T, S> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let val = Deserialize::deserialize(deserializer)?; Ok(Self { inner: val, marker: PhantomData, }) } } impl<T> SecretStateContainer<T, SecuredSecret> { /// Transition the secret state from `SecuredSecret` to `RawSecret` pub fn transition_state( mut self, decryptor_fn: impl FnOnce(T) -> T, ) -> SecretStateContainer<T, RawSecret> { self.inner = decryptor_fn(self.inner); SecretStateContainer { inner: self.inner, marker: PhantomData, } } }
crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs
hyperswitch_interfaces::src::secrets_interface::secret_state
449
true
// File: crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs // Module: hyperswitch_interfaces::src::unified_connector_service::transformers use common_enums::AttemptStatus; use hyperswitch_domain_models::{ router_data::ErrorResponse, router_response_types::PaymentsResponseData, }; use crate::{helpers::ForeignTryFrom, unified_connector_service::payments_grpc}; /// Unified Connector Service error variants #[derive(Debug, Clone, thiserror::Error)] pub enum UnifiedConnectorServiceError { /// Error occurred while communicating with the gRPC server. #[error("Error from gRPC Server : {0}")] ConnectionError(String), /// Failed to encode the request to the unified connector service. #[error("Failed to encode unified connector service request")] RequestEncodingFailed, /// Request encoding failed due to a specific reason. #[error("Request encoding failed : {0}")] RequestEncodingFailedWithReason(String), /// Failed to deserialize the response from the connector. #[error("Failed to deserialize connector response")] ResponseDeserializationFailed, /// The connector name provided is invalid or unrecognized. #[error("An invalid connector name was provided")] InvalidConnectorName, /// Connector name is missing #[error("Connector name is missing")] MissingConnectorName, /// A required field was missing in the request. #[error("Missing required field: {field_name}")] MissingRequiredField { /// Missing Field field_name: &'static str, }, /// Multiple required fields were missing in the request. #[error("Missing required fields: {field_names:?}")] MissingRequiredFields { /// Missing Fields field_names: Vec<&'static str>, }, /// The requested step or feature is not yet implemented. #[error("This step has not been implemented for: {0}")] NotImplemented(String), /// Parsing of some value or input failed. #[error("Parsing failed")] ParsingFailed, /// Data format provided is invalid #[error("Invalid Data format")] InvalidDataFormat { /// Field Name for which data is invalid field_name: &'static str, }, /// Failed to obtain authentication type #[error("Failed to obtain authentication type")] FailedToObtainAuthType, /// Failed to inject metadata into request headers #[error("Failed to inject metadata into request headers: {0}")] HeaderInjectionFailed(String), /// Failed to perform Payment Authorize from gRPC Server #[error("Failed to perform Payment Authorize from gRPC Server")] PaymentAuthorizeFailure, /// Failed to perform Payment Get from gRPC Server #[error("Failed to perform Payment Get from gRPC Server")] PaymentGetFailure, /// Failed to perform Payment Setup Mandate from gRPC Server #[error("Failed to perform Setup Mandate from gRPC Server")] PaymentRegisterFailure, /// Failed to perform Payment Repeat Payment from gRPC Server #[error("Failed to perform Repeat Payment from gRPC Server")] PaymentRepeatEverythingFailure, /// Failed to transform incoming webhook from gRPC Server #[error("Failed to transform incoming webhook from gRPC Server")] WebhookTransformFailure, } #[allow(missing_docs)] /// Webhook transform data structure containing UCS response information #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct WebhookTransformData { pub event_type: api_models::webhooks::IncomingWebhookEvent, pub source_verified: bool, pub webhook_content: Option<payments_grpc::WebhookResponseContent>, pub response_ref_id: Option<String>, } impl ForeignTryFrom<payments_grpc::PaymentServiceGetResponse> for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse> { type Error = error_stack::Report<UnifiedConnectorServiceError>; fn foreign_try_from( response: payments_grpc::PaymentServiceGetResponse, ) -> Result<Self, Self::Error> { let connector_response_reference_id = response.response_ref_id.as_ref().and_then(|identifier| { identifier .id_type .clone() .and_then(|id_type| match id_type { payments_grpc::identifier::IdType::Id(id) => Some(id), payments_grpc::identifier::IdType::EncodedData(encoded_data) => { Some(encoded_data) } payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, }) }); let status_code = convert_connector_service_status_code(response.status_code)?; let resource_id: hyperswitch_domain_models::router_request_types::ResponseId = match response.transaction_id.as_ref().and_then(|id| id.id_type.clone()) { Some(payments_grpc::identifier::IdType::Id(id)) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(id), Some(payments_grpc::identifier::IdType::EncodedData(encoded_data)) => hyperswitch_domain_models::router_request_types::ResponseId::EncodedData(encoded_data), Some(payments_grpc::identifier::IdType::NoResponseIdMarker(_)) | None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId, }; let response = if response.error_code.is_some() { let attempt_status = match response.status() { payments_grpc::PaymentStatus::AttemptStatusUnspecified => None, _ => Some(AttemptStatus::foreign_try_from(response.status())?), }; Err(ErrorResponse { code: response.error_code().to_owned(), message: response.error_message().to_owned(), reason: Some(response.error_message().to_owned()), status_code, attempt_status, connector_transaction_id: connector_response_reference_id, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, }) } else { let status = AttemptStatus::foreign_try_from(response.status())?; Ok(( PaymentsResponseData::TransactionResponse { resource_id, redirection_data: Box::new(None), mandate_reference: Box::new(response.mandate_reference.map(|grpc_mandate| { hyperswitch_domain_models::router_response_types::MandateReference { connector_mandate_id: grpc_mandate.mandate_id, payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, } })), connector_metadata: None, network_txn_id: response.network_txn_id.clone(), connector_response_reference_id, incremental_authorization_allowed: None, charges: None, }, status, )) }; Ok(response) } } impl ForeignTryFrom<payments_grpc::PaymentStatus> for AttemptStatus { type Error = error_stack::Report<UnifiedConnectorServiceError>; fn foreign_try_from(grpc_status: payments_grpc::PaymentStatus) -> Result<Self, Self::Error> { match grpc_status { payments_grpc::PaymentStatus::Started => Ok(Self::Started), payments_grpc::PaymentStatus::AuthenticationFailed => Ok(Self::AuthenticationFailed), payments_grpc::PaymentStatus::RouterDeclined => Ok(Self::RouterDeclined), payments_grpc::PaymentStatus::AuthenticationPending => Ok(Self::AuthenticationPending), payments_grpc::PaymentStatus::AuthenticationSuccessful => { Ok(Self::AuthenticationSuccessful) } payments_grpc::PaymentStatus::Authorized => Ok(Self::Authorized), payments_grpc::PaymentStatus::AuthorizationFailed => Ok(Self::AuthorizationFailed), payments_grpc::PaymentStatus::Charged => Ok(Self::Charged), payments_grpc::PaymentStatus::Authorizing => Ok(Self::Authorizing), payments_grpc::PaymentStatus::CodInitiated => Ok(Self::CodInitiated), payments_grpc::PaymentStatus::Voided => Ok(Self::Voided), payments_grpc::PaymentStatus::VoidInitiated => Ok(Self::VoidInitiated), payments_grpc::PaymentStatus::CaptureInitiated => Ok(Self::CaptureInitiated), payments_grpc::PaymentStatus::CaptureFailed => Ok(Self::CaptureFailed), payments_grpc::PaymentStatus::VoidFailed => Ok(Self::VoidFailed), payments_grpc::PaymentStatus::AutoRefunded => Ok(Self::AutoRefunded), payments_grpc::PaymentStatus::PartialCharged => Ok(Self::PartialCharged), payments_grpc::PaymentStatus::PartialChargedAndChargeable => { Ok(Self::PartialChargedAndChargeable) } payments_grpc::PaymentStatus::Unresolved => Ok(Self::Unresolved), payments_grpc::PaymentStatus::Pending => Ok(Self::Pending), payments_grpc::PaymentStatus::Failure => Ok(Self::Failure), payments_grpc::PaymentStatus::PaymentMethodAwaited => Ok(Self::PaymentMethodAwaited), payments_grpc::PaymentStatus::ConfirmationAwaited => Ok(Self::ConfirmationAwaited), payments_grpc::PaymentStatus::DeviceDataCollectionPending => { Ok(Self::DeviceDataCollectionPending) } payments_grpc::PaymentStatus::AttemptStatusUnspecified => Ok(Self::Unresolved), } } } #[allow(missing_docs)] pub fn convert_connector_service_status_code( status_code: u32, ) -> Result<u16, error_stack::Report<UnifiedConnectorServiceError>> { u16::try_from(status_code).map_err(|err| { UnifiedConnectorServiceError::RequestEncodingFailedWithReason(format!( "Failed to convert connector service status code to u16: {err}" )) .into() }) }
crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
hyperswitch_interfaces::src::unified_connector_service::transformers
2,037
true
// File: crates/hyperswitch_interfaces/src/api/fraud_check_v2.rs // Module: hyperswitch_interfaces::src::api::fraud_check_v2 //! FRM V2 interface use hyperswitch_domain_models::{ router_data_v2::flow_common_types::FrmFlowData, router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, router_request_types::fraud_check::{ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData, }, router_response_types::fraud_check::FraudCheckResponseData, }; use crate::api::ConnectorIntegrationV2; /// trait FraudCheckSaleV2 pub trait FraudCheckSaleV2: ConnectorIntegrationV2<Sale, FrmFlowData, FraudCheckSaleData, FraudCheckResponseData> { } /// trait FraudCheckCheckoutV2 pub trait FraudCheckCheckoutV2: ConnectorIntegrationV2<Checkout, FrmFlowData, FraudCheckCheckoutData, FraudCheckResponseData> { } /// trait FraudCheckTransactionV2 pub trait FraudCheckTransactionV2: ConnectorIntegrationV2<Transaction, FrmFlowData, FraudCheckTransactionData, FraudCheckResponseData> { } /// trait FraudCheckFulfillmentV2 pub trait FraudCheckFulfillmentV2: ConnectorIntegrationV2<Fulfillment, FrmFlowData, FraudCheckFulfillmentData, FraudCheckResponseData> { } /// trait FraudCheckRecordReturnV2 pub trait FraudCheckRecordReturnV2: ConnectorIntegrationV2< RecordReturn, FrmFlowData, FraudCheckRecordReturnData, FraudCheckResponseData, > { } /// trait FraudCheckV2 pub trait FraudCheckV2: super::ConnectorCommon + FraudCheckSaleV2 + FraudCheckTransactionV2 + FraudCheckCheckoutV2 + FraudCheckFulfillmentV2 + FraudCheckRecordReturnV2 { }
crates/hyperswitch_interfaces/src/api/fraud_check_v2.rs
hyperswitch_interfaces::src::api::fraud_check_v2
428
true
// File: crates/hyperswitch_interfaces/src/api/payouts_v2.rs // Module: hyperswitch_interfaces::src::api::payouts_v2 //! Payouts V2 interface use hyperswitch_domain_models::{ router_data_v2::flow_common_types::PayoutFlowData, router_flow_types::payouts::{ PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, }, router_request_types::PayoutsData, router_response_types::PayoutsResponseData, }; use super::ConnectorCommon; use crate::api::ConnectorIntegrationV2; /// trait PayoutCancelV2 pub trait PayoutCancelV2: ConnectorIntegrationV2<PoCancel, PayoutFlowData, PayoutsData, PayoutsResponseData> { } /// trait PayoutCreateV2 pub trait PayoutCreateV2: ConnectorIntegrationV2<PoCreate, PayoutFlowData, PayoutsData, PayoutsResponseData> { } /// trait PayoutEligibilityV2 pub trait PayoutEligibilityV2: ConnectorIntegrationV2<PoEligibility, PayoutFlowData, PayoutsData, PayoutsResponseData> { } /// trait PayoutFulfillV2 pub trait PayoutFulfillV2: ConnectorIntegrationV2<PoFulfill, PayoutFlowData, PayoutsData, PayoutsResponseData> { } /// trait PayoutQuoteV2 pub trait PayoutQuoteV2: ConnectorIntegrationV2<PoQuote, PayoutFlowData, PayoutsData, PayoutsResponseData> { } /// trait PayoutRecipientV2 pub trait PayoutRecipientV2: ConnectorIntegrationV2<PoRecipient, PayoutFlowData, PayoutsData, PayoutsResponseData> { } /// trait PayoutRecipientAccountV2 pub trait PayoutRecipientAccountV2: ConnectorIntegrationV2<PoRecipientAccount, PayoutFlowData, PayoutsData, PayoutsResponseData> { } /// trait PayoutSyncV2 pub trait PayoutSyncV2: ConnectorIntegrationV2<PoSync, PayoutFlowData, PayoutsData, PayoutsResponseData> { } #[cfg(feature = "payouts")] /// trait Payouts pub trait PayoutsV2: ConnectorCommon + PayoutCancelV2 + PayoutCreateV2 + PayoutEligibilityV2 + PayoutFulfillV2 + PayoutQuoteV2 + PayoutRecipientV2 + PayoutRecipientAccountV2 + PayoutSyncV2 { } /// Empty trait for when payouts feature is disabled #[cfg(not(feature = "payouts"))] pub trait PayoutsV2 {}
crates/hyperswitch_interfaces/src/api/payouts_v2.rs
hyperswitch_interfaces::src::api::payouts_v2
625
true
// File: crates/hyperswitch_interfaces/src/api/refunds.rs // Module: hyperswitch_interfaces::src::api::refunds //! Refunds interface use hyperswitch_domain_models::{ router_flow_types::{Execute, RSync}, router_request_types::RefundsData, router_response_types::RefundsResponseData, }; use crate::api::{self, ConnectorCommon}; /// trait RefundExecute pub trait RefundExecute: api::ConnectorIntegration<Execute, RefundsData, RefundsResponseData> { } /// trait RefundSync pub trait RefundSync: api::ConnectorIntegration<RSync, RefundsData, RefundsResponseData> {} /// trait Refund pub trait Refund: ConnectorCommon + RefundExecute + RefundSync {}
crates/hyperswitch_interfaces/src/api/refunds.rs
hyperswitch_interfaces::src::api::refunds
162
true
// File: crates/hyperswitch_interfaces/src/api/subscriptions.rs // Module: hyperswitch_interfaces::src::api::subscriptions //! Subscriptions Interface for V1 use hyperswitch_domain_models::{ router_flow_types::{ subscriptions::{ GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate as SubscriptionCreateFlow, }, InvoiceRecordBack, }, router_request_types::{ revenue_recovery::InvoiceRecordBackRequest, subscriptions::{ GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, SubscriptionCreateRequest, }, }, router_response_types::{ revenue_recovery::InvoiceRecordBackResponse, subscriptions::{ GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, }, }; use super::{ payments::ConnectorCustomer as PaymentsConnectorCustomer, ConnectorCommon, ConnectorIntegration, }; /// trait GetSubscriptionPlans for V1 pub trait GetSubscriptionPlansFlow: ConnectorIntegration< GetSubscriptionPlans, GetSubscriptionPlansRequest, GetSubscriptionPlansResponse, > { } /// trait SubscriptionRecordBack for V1 pub trait SubscriptionRecordBackFlow: ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse> { } /// trait GetSubscriptionPlanPrices for V1 pub trait GetSubscriptionPlanPricesFlow: ConnectorIntegration< GetSubscriptionPlanPrices, GetSubscriptionPlanPricesRequest, GetSubscriptionPlanPricesResponse, > { } /// trait SubscriptionCreate pub trait SubscriptionCreate: ConnectorIntegration<SubscriptionCreateFlow, SubscriptionCreateRequest, SubscriptionCreateResponse> { } /// trait GetSubscriptionEstimate for V1 pub trait GetSubscriptionEstimateFlow: ConnectorIntegration< GetSubscriptionEstimate, GetSubscriptionEstimateRequest, GetSubscriptionEstimateResponse, > { } /// trait Subscriptions pub trait Subscriptions: ConnectorCommon + GetSubscriptionPlansFlow + GetSubscriptionPlanPricesFlow + SubscriptionCreate + PaymentsConnectorCustomer + SubscriptionRecordBackFlow + GetSubscriptionEstimateFlow { }
crates/hyperswitch_interfaces/src/api/subscriptions.rs
hyperswitch_interfaces::src::api::subscriptions
442
true
// File: crates/hyperswitch_interfaces/src/api/payouts.rs // Module: hyperswitch_interfaces::src::api::payouts //! Payouts interface use hyperswitch_domain_models::{ router_flow_types::payouts::{ PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, }, router_request_types::PayoutsData, router_response_types::PayoutsResponseData, }; use super::ConnectorCommon; use crate::api::ConnectorIntegration; /// trait PayoutCancel pub trait PayoutCancel: ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData> {} /// trait PayoutCreate pub trait PayoutCreate: ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> {} /// trait PayoutEligibility pub trait PayoutEligibility: ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData> { } /// trait PayoutFulfill pub trait PayoutFulfill: ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> {} /// trait PayoutQuote pub trait PayoutQuote: ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData> {} /// trait PayoutRecipient pub trait PayoutRecipient: ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData> { } /// trait PayoutRecipientAccount pub trait PayoutRecipientAccount: ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData> { } /// trait PayoutSync pub trait PayoutSync: ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> {} #[cfg(feature = "payouts")] /// trait Payouts pub trait Payouts: ConnectorCommon + PayoutCancel + PayoutCreate + PayoutEligibility + PayoutFulfill + PayoutQuote + PayoutRecipient + PayoutRecipientAccount + PayoutSync { } /// Empty trait for when payouts feature is disabled #[cfg(not(feature = "payouts"))] pub trait Payouts {}
crates/hyperswitch_interfaces/src/api/payouts.rs
hyperswitch_interfaces::src::api::payouts
484
true
// File: crates/hyperswitch_interfaces/src/api/refunds_v2.rs // Module: hyperswitch_interfaces::src::api::refunds_v2 //! Refunds V2 interface use hyperswitch_domain_models::{ router_data_v2::flow_common_types::RefundFlowData, router_flow_types::refunds::{Execute, RSync}, router_request_types::RefundsData, router_response_types::RefundsResponseData, }; use crate::api::{ConnectorCommon, ConnectorIntegrationV2}; /// trait RefundExecuteV2 pub trait RefundExecuteV2: ConnectorIntegrationV2<Execute, RefundFlowData, RefundsData, RefundsResponseData> { } /// trait RefundSyncV2 pub trait RefundSyncV2: ConnectorIntegrationV2<RSync, RefundFlowData, RefundsData, RefundsResponseData> { } /// trait RefundV2 pub trait RefundV2: ConnectorCommon + RefundExecuteV2 + RefundSyncV2 {}
crates/hyperswitch_interfaces/src/api/refunds_v2.rs
hyperswitch_interfaces::src::api::refunds_v2
217
true
// File: crates/hyperswitch_interfaces/src/api/fraud_check.rs // Module: hyperswitch_interfaces::src::api::fraud_check //! FRM interface use hyperswitch_domain_models::{ router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, router_request_types::fraud_check::{ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData, }, router_response_types::fraud_check::FraudCheckResponseData, }; use crate::api::ConnectorIntegration; /// trait FraudCheckSale pub trait FraudCheckSale: ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData> { } /// trait FraudCheckCheckout pub trait FraudCheckCheckout: ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData> { } /// trait FraudCheckTransaction pub trait FraudCheckTransaction: ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData> { } /// trait FraudCheckFulfillment pub trait FraudCheckFulfillment: ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData> { } /// trait FraudCheckRecordReturn pub trait FraudCheckRecordReturn: ConnectorIntegration<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData> { } /// trait FraudCheck pub trait FraudCheck: super::ConnectorCommon + FraudCheckSale + FraudCheckTransaction + FraudCheckCheckout + FraudCheckFulfillment + FraudCheckRecordReturn { }
crates/hyperswitch_interfaces/src/api/fraud_check.rs
hyperswitch_interfaces::src::api::fraud_check
336
true
// File: crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs // Module: hyperswitch_interfaces::src::api::subscriptions_v2 //! SubscriptionsV2 use hyperswitch_domain_models::{ router_data_v2::flow_common_types::{ GetSubscriptionEstimateData, GetSubscriptionPlanPricesData, GetSubscriptionPlansData, InvoiceRecordBackData, SubscriptionCreateData, SubscriptionCustomerData, }, router_flow_types::{ revenue_recovery::InvoiceRecordBack, subscriptions::{ GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate, }, CreateConnectorCustomer, }, router_request_types::{ revenue_recovery::InvoiceRecordBackRequest, subscriptions::{ GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, SubscriptionCreateRequest, }, ConnectorCustomerData, }, router_response_types::{ revenue_recovery::InvoiceRecordBackResponse, subscriptions::{ GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, PaymentsResponseData, }, }; use crate::connector_integration_v2::ConnectorIntegrationV2; /// trait SubscriptionsV2 pub trait SubscriptionsV2: GetSubscriptionPlansV2 + SubscriptionsCreateV2 + SubscriptionConnectorCustomerV2 + GetSubscriptionPlanPricesV2 + SubscriptionRecordBackV2 + GetSubscriptionEstimateV2 { } /// trait GetSubscriptionPlans for V2 pub trait GetSubscriptionPlansV2: ConnectorIntegrationV2< GetSubscriptionPlans, GetSubscriptionPlansData, GetSubscriptionPlansRequest, GetSubscriptionPlansResponse, > { } /// trait SubscriptionRecordBack for V2 pub trait SubscriptionRecordBackV2: ConnectorIntegrationV2< InvoiceRecordBack, InvoiceRecordBackData, InvoiceRecordBackRequest, InvoiceRecordBackResponse, > { } /// trait GetSubscriptionPlanPricesV2 for V2 pub trait GetSubscriptionPlanPricesV2: ConnectorIntegrationV2< GetSubscriptionPlanPrices, GetSubscriptionPlanPricesData, GetSubscriptionPlanPricesRequest, GetSubscriptionPlanPricesResponse, > { } /// trait SubscriptionsCreateV2 pub trait SubscriptionsCreateV2: ConnectorIntegrationV2< SubscriptionCreate, SubscriptionCreateData, SubscriptionCreateRequest, SubscriptionCreateResponse, > { } /// trait SubscriptionConnectorCustomerV2 pub trait SubscriptionConnectorCustomerV2: ConnectorIntegrationV2< CreateConnectorCustomer, SubscriptionCustomerData, ConnectorCustomerData, PaymentsResponseData, > { } /// trait GetSubscriptionEstimate for V2 pub trait GetSubscriptionEstimateV2: ConnectorIntegrationV2< GetSubscriptionEstimate, GetSubscriptionEstimateData, GetSubscriptionEstimateRequest, GetSubscriptionEstimateResponse, > { }
crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs
hyperswitch_interfaces::src::api::subscriptions_v2
608
true
// File: crates/hyperswitch_interfaces/src/api/payments.rs // Module: hyperswitch_interfaces::src::api::payments //! Payments interface use hyperswitch_domain_models::{ router_flow_types::{ payments::{ Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, ExtendAuthorization, IncrementalAuthorization, PSync, PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, Authenticate, CreateOrder, ExternalVaultProxy, GiftCardBalanceCheck, PostAuthenticate, PreAuthenticate, }, router_request_types::{ AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, ExternalVaultProxyPaymentsData, GiftCardBalanceCheckRequestData, PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, }, router_response_types::{ GiftCardBalanceCheckResponseData, PaymentsResponseData, TaxCalculationResponseData, }, }; use crate::api; /// trait Payment pub trait Payment: api::ConnectorCommon + api::ConnectorSpecifications + api::ConnectorValidation + PaymentAuthorize + PaymentAuthorizeSessionToken + PaymentsCompleteAuthorize + PaymentSync + PaymentCapture + PaymentVoid + PaymentPostCaptureVoid + PaymentApprove + PaymentReject + MandateSetup + PaymentSession + PaymentToken + PaymentsPreProcessing + PaymentsPostProcessing + ConnectorCustomer + PaymentIncrementalAuthorization + PaymentExtendAuthorization + PaymentSessionUpdate + PaymentPostSessionTokens + PaymentUpdateMetadata + PaymentsCreateOrder + ExternalVaultProxyPaymentsCreateV1 + PaymentsGiftCardBalanceCheck { } /// trait PaymentSession pub trait PaymentSession: api::ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> { } /// trait MandateSetup pub trait MandateSetup: api::ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> { } /// trait PaymentAuthorize pub trait PaymentAuthorize: api::ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> { } /// trait PaymentCapture pub trait PaymentCapture: api::ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> { } /// trait PaymentSync pub trait PaymentSync: api::ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> { } /// trait PaymentVoid pub trait PaymentVoid: api::ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> { } /// trait PaymentPostCaptureVoid pub trait PaymentPostCaptureVoid: api::ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData> { } /// trait PaymentExtendAuthorization pub trait PaymentExtendAuthorization: api::ConnectorIntegration< ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData, > { } /// trait PaymentApprove pub trait PaymentApprove: api::ConnectorIntegration<Approve, PaymentsApproveData, PaymentsResponseData> { } /// trait PaymentReject pub trait PaymentReject: api::ConnectorIntegration<Reject, PaymentsRejectData, PaymentsResponseData> { } /// trait PaymentToken pub trait PaymentToken: api::ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> { } /// trait PaymentAuthorizeSessionToken pub trait PaymentAuthorizeSessionToken: api::ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData> { } /// trait PaymentIncrementalAuthorization pub trait PaymentIncrementalAuthorization: api::ConnectorIntegration< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, > { } /// trait TaxCalculation pub trait TaxCalculation: api::ConnectorIntegration<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData> { } /// trait SessionUpdate pub trait PaymentSessionUpdate: api::ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData> { } /// trait PostSessionTokens pub trait PaymentPostSessionTokens: api::ConnectorIntegration<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData> { } /// trait UpdateMetadata pub trait PaymentUpdateMetadata: api::ConnectorIntegration<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData> { } /// trait PaymentsCompleteAuthorize pub trait PaymentsCompleteAuthorize: api::ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> { } /// trait ConnectorCustomer pub trait ConnectorCustomer: api::ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData> { } /// trait PaymentsPreProcessing pub trait PaymentsPreProcessing: api::ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> { } /// trait PaymentsPreAuthenticate pub trait PaymentsPreAuthenticate: api::ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData> { } /// trait PaymentsAuthenticate pub trait PaymentsAuthenticate: api::ConnectorIntegration<Authenticate, PaymentsAuthenticateData, PaymentsResponseData> { } /// trait PaymentsPostAuthenticate pub trait PaymentsPostAuthenticate: api::ConnectorIntegration<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData> { } /// trait PaymentsPostProcessing pub trait PaymentsPostProcessing: api::ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData> { } /// trait PaymentsCreateOrder pub trait PaymentsCreateOrder: api::ConnectorIntegration<CreateOrder, CreateOrderRequestData, PaymentsResponseData> { } /// trait ExternalVaultProxyPaymentsCreate pub trait ExternalVaultProxyPaymentsCreateV1: api::ConnectorIntegration<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData> { } /// trait PaymentsGiftCardBalanceCheck pub trait PaymentsGiftCardBalanceCheck: api::ConnectorIntegration< GiftCardBalanceCheck, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData, > { }
crates/hyperswitch_interfaces/src/api/payments.rs
hyperswitch_interfaces::src::api::payments
1,385
true
// File: crates/hyperswitch_interfaces/src/api/disputes.rs // Module: hyperswitch_interfaces::src::api::disputes //! Disputes interface use hyperswitch_domain_models::{ router_flow_types::dispute::{Accept, Defend, Dsync, Evidence, Fetch}, router_request_types::{ AcceptDisputeRequestData, DefendDisputeRequestData, DisputeSyncData, FetchDisputesRequestData, SubmitEvidenceRequestData, }, router_response_types::{ AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, SubmitEvidenceResponse, }, }; use crate::api::ConnectorIntegration; /// trait AcceptDispute pub trait AcceptDispute: ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse> { } /// trait SubmitEvidence pub trait SubmitEvidence: ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse> { } /// trait DefendDispute pub trait DefendDispute: ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse> { } /// trait Dispute pub trait Dispute: super::ConnectorCommon + AcceptDispute + SubmitEvidence + DefendDispute + FetchDisputes + DisputeSync { } /// trait FetchDisputes pub trait FetchDisputes: ConnectorIntegration<Fetch, FetchDisputesRequestData, FetchDisputesResponse> { } /// trait SyncDisputes pub trait DisputeSync: ConnectorIntegration<Dsync, DisputeSyncData, DisputeSyncResponse> {}
crates/hyperswitch_interfaces/src/api/disputes.rs
hyperswitch_interfaces::src::api::disputes
353
true
// File: crates/hyperswitch_interfaces/src/api/disputes_v2.rs // Module: hyperswitch_interfaces::src::api::disputes_v2 //! Disputes V2 interface use hyperswitch_domain_models::{ router_data_v2::DisputesFlowData, router_flow_types::dispute::{Accept, Defend, Dsync, Evidence, Fetch}, router_request_types::{ AcceptDisputeRequestData, DefendDisputeRequestData, DisputeSyncData, FetchDisputesRequestData, SubmitEvidenceRequestData, }, router_response_types::{ AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, SubmitEvidenceResponse, }, }; use crate::api::ConnectorIntegrationV2; /// trait AcceptDisputeV2 pub trait AcceptDisputeV2: ConnectorIntegrationV2<Accept, DisputesFlowData, AcceptDisputeRequestData, AcceptDisputeResponse> { } /// trait SubmitEvidenceV2 pub trait SubmitEvidenceV2: ConnectorIntegrationV2< Evidence, DisputesFlowData, SubmitEvidenceRequestData, SubmitEvidenceResponse, > { } /// trait DefendDisputeV2 pub trait DefendDisputeV2: ConnectorIntegrationV2<Defend, DisputesFlowData, DefendDisputeRequestData, DefendDisputeResponse> { } /// trait DisputeV2 pub trait DisputeV2: super::ConnectorCommon + AcceptDisputeV2 + SubmitEvidenceV2 + DefendDisputeV2 + FetchDisputesV2 + DisputeSyncV2 { } /// trait FetchDisputeV2 pub trait FetchDisputesV2: ConnectorIntegrationV2<Fetch, DisputesFlowData, FetchDisputesRequestData, FetchDisputesResponse> { } /// trait DisputeSyncV2 pub trait DisputeSyncV2: ConnectorIntegrationV2<Dsync, DisputesFlowData, DisputeSyncData, DisputeSyncResponse> { }
crates/hyperswitch_interfaces/src/api/disputes_v2.rs
hyperswitch_interfaces::src::api::disputes_v2
452
true
// File: crates/hyperswitch_interfaces/src/api/revenue_recovery_v2.rs // Module: hyperswitch_interfaces::src::api::revenue_recovery_v2 //! Revenue Recovery Interface V2 use hyperswitch_domain_models::{ router_data_v2::flow_common_types::{ BillingConnectorInvoiceSyncFlowData, BillingConnectorPaymentsSyncFlowData, InvoiceRecordBackData, }, router_flow_types::{ BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, InvoiceRecordBack, }, router_request_types::revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, InvoiceRecordBackRequest, }, router_response_types::revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, InvoiceRecordBackResponse, }, }; use crate::connector_integration_v2::ConnectorIntegrationV2; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] /// trait RevenueRecoveryV2 pub trait RevenueRecoveryV2: BillingConnectorPaymentsSyncIntegrationV2 + RevenueRecoveryRecordBackV2 + BillingConnectorInvoiceSyncIntegrationV2 { } #[cfg(not(all(feature = "v2", feature = "revenue_recovery")))] /// trait RevenueRecoveryV2 pub trait RevenueRecoveryV2 {} /// trait BillingConnectorPaymentsSyncIntegrationV2 pub trait BillingConnectorPaymentsSyncIntegrationV2: ConnectorIntegrationV2< BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncFlowData, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, > { } /// trait RevenueRecoveryRecordBackV2 pub trait RevenueRecoveryRecordBackV2: ConnectorIntegrationV2< InvoiceRecordBack, InvoiceRecordBackData, InvoiceRecordBackRequest, InvoiceRecordBackResponse, > { } /// trait BillingConnectorInvoiceSyncIntegrationV2 pub trait BillingConnectorInvoiceSyncIntegrationV2: ConnectorIntegrationV2< BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncFlowData, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, > { }
crates/hyperswitch_interfaces/src/api/revenue_recovery_v2.rs
hyperswitch_interfaces::src::api::revenue_recovery_v2
441
true
// File: crates/hyperswitch_interfaces/src/api/files.rs // Module: hyperswitch_interfaces::src::api::files //! Files interface use hyperswitch_domain_models::{ router_flow_types::files::{Retrieve, Upload}, router_request_types::{RetrieveFileRequestData, UploadFileRequestData}, router_response_types::{RetrieveFileResponse, UploadFileResponse}, }; use crate::{ api::{ConnectorCommon, ConnectorIntegration}, errors, }; /// enum FilePurpose #[derive(Debug, serde::Deserialize, strum::Display, Clone, serde::Serialize)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FilePurpose { /// DisputeEvidence DisputeEvidence, } /// trait UploadFile pub trait UploadFile: ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse> { } /// trait RetrieveFile pub trait RetrieveFile: ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse> { } /// trait FileUpload pub trait FileUpload: ConnectorCommon + Sync + UploadFile + RetrieveFile { /// fn validate_file_upload fn validate_file_upload( &self, _purpose: FilePurpose, _file_size: i32, _file_type: mime::Mime, ) -> common_utils::errors::CustomResult<(), errors::ConnectorError> { Err(errors::ConnectorError::FileValidationFailed { reason: "".to_owned(), } .into()) } }
crates/hyperswitch_interfaces/src/api/files.rs
hyperswitch_interfaces::src::api::files
316
true
// File: crates/hyperswitch_interfaces/src/api/authentication_v2.rs // Module: hyperswitch_interfaces::src::api::authentication_v2 use hyperswitch_domain_models::{ router_data_v2::ExternalAuthenticationFlowData, router_flow_types::authentication::{ Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, }, router_request_types::authentication::{ ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData, PreAuthNRequestData, }, router_response_types::AuthenticationResponseData, }; use crate::api::ConnectorIntegrationV2; /// trait ConnectorAuthenticationV2 pub trait ConnectorAuthenticationV2: ConnectorIntegrationV2< Authentication, ExternalAuthenticationFlowData, ConnectorAuthenticationRequestData, AuthenticationResponseData, > { } /// trait ConnectorPreAuthenticationV2 pub trait ConnectorPreAuthenticationV2: ConnectorIntegrationV2< PreAuthentication, ExternalAuthenticationFlowData, PreAuthNRequestData, AuthenticationResponseData, > { } /// trait ConnectorPreAuthenticationVersionCallV2 pub trait ConnectorPreAuthenticationVersionCallV2: ConnectorIntegrationV2< PreAuthenticationVersionCall, ExternalAuthenticationFlowData, PreAuthNRequestData, AuthenticationResponseData, > { } /// trait ConnectorPostAuthenticationV2 pub trait ConnectorPostAuthenticationV2: ConnectorIntegrationV2< PostAuthentication, ExternalAuthenticationFlowData, ConnectorPostAuthenticationRequestData, AuthenticationResponseData, > { } /// trait ExternalAuthenticationV2 pub trait ExternalAuthenticationV2: super::ConnectorCommon + ConnectorAuthenticationV2 + ConnectorPreAuthenticationV2 + ConnectorPreAuthenticationVersionCallV2 + ConnectorPostAuthenticationV2 { }
crates/hyperswitch_interfaces/src/api/authentication_v2.rs
hyperswitch_interfaces::src::api::authentication_v2
364
true
// File: crates/hyperswitch_interfaces/src/api/payments_v2.rs // Module: hyperswitch_interfaces::src::api::payments_v2 //! Payments V2 interface use hyperswitch_domain_models::{ router_data_v2::{flow_common_types::GiftCardBalanceCheckFlowData, PaymentFlowData}, router_flow_types::{ payments::{ Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, ExtendAuthorization, ExternalVaultProxy, IncrementalAuthorization, PSync, PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, Authenticate, GiftCardBalanceCheck, PostAuthenticate, PreAuthenticate, }, router_request_types::{ AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, ExternalVaultProxyPaymentsData, GiftCardBalanceCheckRequestData, PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, }, router_response_types::{ GiftCardBalanceCheckResponseData, PaymentsResponseData, TaxCalculationResponseData, }, }; use crate::api::{ ConnectorCommon, ConnectorIntegrationV2, ConnectorSpecifications, ConnectorValidation, }; /// trait PaymentAuthorizeV2 pub trait PaymentAuthorizeV2: ConnectorIntegrationV2<Authorize, PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData> { } /// trait PaymentAuthorizeSessionTokenV2 pub trait PaymentAuthorizeSessionTokenV2: ConnectorIntegrationV2< AuthorizeSessionToken, PaymentFlowData, AuthorizeSessionTokenData, PaymentsResponseData, > { } /// trait PaymentSyncV2 pub trait PaymentSyncV2: ConnectorIntegrationV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData> { } /// trait PaymentVoidV2 pub trait PaymentVoidV2: ConnectorIntegrationV2<Void, PaymentFlowData, PaymentsCancelData, PaymentsResponseData> { } /// trait PaymentPostCaptureVoidV2 pub trait PaymentPostCaptureVoidV2: ConnectorIntegrationV2< PostCaptureVoid, PaymentFlowData, PaymentsCancelPostCaptureData, PaymentsResponseData, > { } /// trait PaymentApproveV2 pub trait PaymentApproveV2: ConnectorIntegrationV2<Approve, PaymentFlowData, PaymentsApproveData, PaymentsResponseData> { } /// trait PaymentRejectV2 pub trait PaymentRejectV2: ConnectorIntegrationV2<Reject, PaymentFlowData, PaymentsRejectData, PaymentsResponseData> { } /// trait PaymentCaptureV2 pub trait PaymentCaptureV2: ConnectorIntegrationV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData> { } /// trait PaymentSessionV2 pub trait PaymentSessionV2: ConnectorIntegrationV2<Session, PaymentFlowData, PaymentsSessionData, PaymentsResponseData> { } /// trait MandateSetupV2 pub trait MandateSetupV2: ConnectorIntegrationV2<SetupMandate, PaymentFlowData, SetupMandateRequestData, PaymentsResponseData> { } /// trait PaymentIncrementalAuthorizationV2 pub trait PaymentIncrementalAuthorizationV2: ConnectorIntegrationV2< IncrementalAuthorization, PaymentFlowData, PaymentsIncrementalAuthorizationData, PaymentsResponseData, > { } /// trait PaymentExtendAuthorizationV2 pub trait PaymentExtendAuthorizationV2: ConnectorIntegrationV2< ExtendAuthorization, PaymentFlowData, PaymentsExtendAuthorizationData, PaymentsResponseData, > { } ///trait TaxCalculationV2 pub trait TaxCalculationV2: ConnectorIntegrationV2< CalculateTax, PaymentFlowData, PaymentsTaxCalculationData, TaxCalculationResponseData, > { } ///trait PaymentSessionUpdateV2 pub trait PaymentSessionUpdateV2: ConnectorIntegrationV2< SdkSessionUpdate, PaymentFlowData, SdkPaymentsSessionUpdateData, PaymentsResponseData, > { } ///trait PaymentPostSessionTokensV2 pub trait PaymentPostSessionTokensV2: ConnectorIntegrationV2< PostSessionTokens, PaymentFlowData, PaymentsPostSessionTokensData, PaymentsResponseData, > { } /// trait ConnectorCreateOrderV2 pub trait PaymentCreateOrderV2: ConnectorIntegrationV2<CreateOrder, PaymentFlowData, CreateOrderRequestData, PaymentsResponseData> { } /// trait PaymentUpdateMetadataV2 pub trait PaymentUpdateMetadataV2: ConnectorIntegrationV2< UpdateMetadata, PaymentFlowData, PaymentsUpdateMetadataData, PaymentsResponseData, > { } /// trait PaymentsCompleteAuthorizeV2 pub trait PaymentsCompleteAuthorizeV2: ConnectorIntegrationV2< CompleteAuthorize, PaymentFlowData, CompleteAuthorizeData, PaymentsResponseData, > { } /// trait PaymentTokenV2 pub trait PaymentTokenV2: ConnectorIntegrationV2< PaymentMethodToken, PaymentFlowData, PaymentMethodTokenizationData, PaymentsResponseData, > { } /// trait ConnectorCustomerV2 pub trait ConnectorCustomerV2: ConnectorIntegrationV2< CreateConnectorCustomer, PaymentFlowData, ConnectorCustomerData, PaymentsResponseData, > { } /// trait PaymentsPreProcessingV2 pub trait PaymentsPreProcessingV2: ConnectorIntegrationV2< PreProcessing, PaymentFlowData, PaymentsPreProcessingData, PaymentsResponseData, > { } /// trait PaymentsGiftCardBalanceCheckV2 pub trait PaymentsGiftCardBalanceCheckV2: ConnectorIntegrationV2< GiftCardBalanceCheck, GiftCardBalanceCheckFlowData, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData, > { } /// trait PaymentsPreAuthenticateV2 pub trait PaymentsPreAuthenticateV2: ConnectorIntegrationV2< PreAuthenticate, PaymentFlowData, PaymentsPreAuthenticateData, PaymentsResponseData, > { } /// trait PaymentsAuthenticateV2 pub trait PaymentsAuthenticateV2: ConnectorIntegrationV2< Authenticate, PaymentFlowData, PaymentsAuthenticateData, PaymentsResponseData, > { } /// trait PaymentsPostAuthenticateV2 pub trait PaymentsPostAuthenticateV2: ConnectorIntegrationV2< PostAuthenticate, PaymentFlowData, PaymentsPostAuthenticateData, PaymentsResponseData, > { } /// trait PaymentsPostProcessingV2 pub trait PaymentsPostProcessingV2: ConnectorIntegrationV2< PostProcessing, PaymentFlowData, PaymentsPostProcessingData, PaymentsResponseData, > { } /// trait ExternalVaultProxyPaymentsCreate pub trait ExternalVaultProxyPaymentsCreate: ConnectorIntegrationV2< ExternalVaultProxy, PaymentFlowData, ExternalVaultProxyPaymentsData, PaymentsResponseData, > { } /// trait PaymentV2 pub trait PaymentV2: ConnectorCommon + ConnectorSpecifications + ConnectorValidation + PaymentAuthorizeV2 + PaymentAuthorizeSessionTokenV2 + PaymentsCompleteAuthorizeV2 + PaymentSyncV2 + PaymentCaptureV2 + PaymentVoidV2 + PaymentPostCaptureVoidV2 + PaymentApproveV2 + PaymentRejectV2 + MandateSetupV2 + PaymentSessionV2 + PaymentTokenV2 + PaymentsPreProcessingV2 + PaymentsPostProcessingV2 + ConnectorCustomerV2 + PaymentIncrementalAuthorizationV2 + PaymentExtendAuthorizationV2 + TaxCalculationV2 + PaymentSessionUpdateV2 + PaymentPostSessionTokensV2 + PaymentUpdateMetadataV2 + PaymentCreateOrderV2 + ExternalVaultProxyPaymentsCreate + PaymentsGiftCardBalanceCheckV2 { }
crates/hyperswitch_interfaces/src/api/payments_v2.rs
hyperswitch_interfaces::src::api::payments_v2
1,776
true
// File: crates/hyperswitch_interfaces/src/api/revenue_recovery.rs // Module: hyperswitch_interfaces::src::api::revenue_recovery //! Revenue Recovery Interface use hyperswitch_domain_models::{ router_flow_types::{ BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, InvoiceRecordBack, }, router_request_types::revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, InvoiceRecordBackRequest, }, router_response_types::revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, InvoiceRecordBackResponse, }, }; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use super::ConnectorCommon; use super::ConnectorIntegration; /// trait RevenueRecovery #[cfg(all(feature = "v2", feature = "revenue_recovery"))] pub trait RevenueRecovery: ConnectorCommon + BillingConnectorPaymentsSyncIntegration + RevenueRecoveryRecordBack + BillingConnectorInvoiceSyncIntegration { } /// trait BillingConnectorPaymentsSyncIntegration pub trait BillingConnectorPaymentsSyncIntegration: ConnectorIntegration< BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, > { } /// trait RevenueRecoveryRecordBack pub trait RevenueRecoveryRecordBack: ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse> { } /// trait BillingConnectorInvoiceSyncIntegration pub trait BillingConnectorInvoiceSyncIntegration: ConnectorIntegration< BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, > { } #[cfg(not(all(feature = "v2", feature = "revenue_recovery")))] /// trait RevenueRecovery pub trait RevenueRecovery {}
crates/hyperswitch_interfaces/src/api/revenue_recovery.rs
hyperswitch_interfaces::src::api::revenue_recovery
365
true
// File: crates/hyperswitch_interfaces/src/api/authentication.rs // Module: hyperswitch_interfaces::src::api::authentication use hyperswitch_domain_models::{ router_flow_types::authentication::{ Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, }, router_request_types::authentication::{ ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData, PreAuthNRequestData, }, router_response_types::AuthenticationResponseData, }; use crate::api::ConnectorIntegration; /// trait ConnectorAuthentication pub trait ConnectorAuthentication: ConnectorIntegration<Authentication, ConnectorAuthenticationRequestData, AuthenticationResponseData> { } /// trait ConnectorPreAuthentication pub trait ConnectorPreAuthentication: ConnectorIntegration<PreAuthentication, PreAuthNRequestData, AuthenticationResponseData> { } /// trait ConnectorPreAuthenticationVersionCall pub trait ConnectorPreAuthenticationVersionCall: ConnectorIntegration<PreAuthenticationVersionCall, PreAuthNRequestData, AuthenticationResponseData> { } /// trait ConnectorPostAuthentication pub trait ConnectorPostAuthentication: ConnectorIntegration< PostAuthentication, ConnectorPostAuthenticationRequestData, AuthenticationResponseData, > { } /// trait ExternalAuthentication pub trait ExternalAuthentication: super::ConnectorCommon + ConnectorAuthentication + ConnectorPreAuthentication + ConnectorPreAuthenticationVersionCall + ConnectorPostAuthentication { }
crates/hyperswitch_interfaces/src/api/authentication.rs
hyperswitch_interfaces::src::api::authentication
275
true
// File: crates/hyperswitch_interfaces/src/api/files_v2.rs // Module: hyperswitch_interfaces::src::api::files_v2 //! Files V2 interface use hyperswitch_domain_models::{ router_data_v2::FilesFlowData, router_flow_types::{Retrieve, Upload}, router_request_types::{RetrieveFileRequestData, UploadFileRequestData}, router_response_types::{RetrieveFileResponse, UploadFileResponse}, }; use crate::api::{errors, files::FilePurpose, ConnectorCommon, ConnectorIntegrationV2}; /// trait UploadFileV2 pub trait UploadFileV2: ConnectorIntegrationV2<Upload, FilesFlowData, UploadFileRequestData, UploadFileResponse> { } /// trait RetrieveFileV2 pub trait RetrieveFileV2: ConnectorIntegrationV2<Retrieve, FilesFlowData, RetrieveFileRequestData, RetrieveFileResponse> { } /// trait FileUploadV2 pub trait FileUploadV2: ConnectorCommon + Sync + UploadFileV2 + RetrieveFileV2 { /// fn validate_file_upload_v2 fn validate_file_upload_v2( &self, _purpose: FilePurpose, _file_size: i32, _file_type: mime::Mime, ) -> common_utils::errors::CustomResult<(), errors::ConnectorError> { Err(errors::ConnectorError::FileValidationFailed { reason: "".to_owned(), } .into()) } }
crates/hyperswitch_interfaces/src/api/files_v2.rs
hyperswitch_interfaces::src::api::files_v2
305
true
// File: crates/hyperswitch_interfaces/src/api/vault.rs // Module: hyperswitch_interfaces::src::api::vault //! Vault interface use hyperswitch_domain_models::{ router_flow_types::vault::{ ExternalVaultCreateFlow, ExternalVaultDeleteFlow, ExternalVaultInsertFlow, ExternalVaultRetrieveFlow, }, router_request_types::VaultRequestData, router_response_types::VaultResponseData, }; use super::ConnectorCommon; use crate::api::ConnectorIntegration; /// trait ExternalVaultInsert pub trait ExternalVaultInsert: ConnectorIntegration<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData> { } /// trait ExternalVaultRetrieve pub trait ExternalVaultRetrieve: ConnectorIntegration<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData> { } /// trait ExternalVaultDelete pub trait ExternalVaultDelete: ConnectorIntegration<ExternalVaultDeleteFlow, VaultRequestData, VaultResponseData> { } /// trait ExternalVaultDelete pub trait ExternalVaultCreate: ConnectorIntegration<ExternalVaultCreateFlow, VaultRequestData, VaultResponseData> { } /// trait ExternalVault pub trait ExternalVault: ConnectorCommon + ExternalVaultInsert + ExternalVaultRetrieve + ExternalVaultDelete + ExternalVaultCreate { }
crates/hyperswitch_interfaces/src/api/vault.rs
hyperswitch_interfaces::src::api::vault
266
true
// File: crates/hyperswitch_interfaces/src/api/vault_v2.rs // Module: hyperswitch_interfaces::src::api::vault_v2 //! Vault V2 interface use hyperswitch_domain_models::{ router_data_v2::flow_common_types::VaultConnectorFlowData, router_flow_types::vault::{ ExternalVaultCreateFlow, ExternalVaultDeleteFlow, ExternalVaultInsertFlow, ExternalVaultRetrieveFlow, }, router_request_types::VaultRequestData, router_response_types::VaultResponseData, }; use super::ConnectorCommon; use crate::api::ConnectorIntegrationV2; /// trait ExternalVaultInsertV2 pub trait ExternalVaultInsertV2: ConnectorIntegrationV2< ExternalVaultInsertFlow, VaultConnectorFlowData, VaultRequestData, VaultResponseData, > { } /// trait ExternalVaultRetrieveV2 pub trait ExternalVaultRetrieveV2: ConnectorIntegrationV2< ExternalVaultRetrieveFlow, VaultConnectorFlowData, VaultRequestData, VaultResponseData, > { } /// trait ExternalVaultDeleteV2 pub trait ExternalVaultDeleteV2: ConnectorIntegrationV2< ExternalVaultDeleteFlow, VaultConnectorFlowData, VaultRequestData, VaultResponseData, > { } /// trait ExternalVaultDeleteV2 pub trait ExternalVaultCreateV2: ConnectorIntegrationV2< ExternalVaultCreateFlow, VaultConnectorFlowData, VaultRequestData, VaultResponseData, > { } /// trait ExternalVaultV2 pub trait ExternalVaultV2: ConnectorCommon + ExternalVaultInsertV2 + ExternalVaultRetrieveV2 + ExternalVaultDeleteV2 + ExternalVaultCreateV2 { }
crates/hyperswitch_interfaces/src/api/vault_v2.rs
hyperswitch_interfaces::src::api::vault_v2
365
true
// File: crates/hyperswitch_interfaces/src/events/routing_api_logs.rs // Module: hyperswitch_interfaces::src::events::routing_api_logs //! Routing API logs interface use std::fmt; use api_models::routing::RoutableConnectorChoice; use common_utils::request::Method; use router_env::tracing_actix_web::RequestId; use serde::Serialize; use serde_json::json; use time::OffsetDateTime; /// RoutingEngine enum #[derive(Debug, Clone, Copy, Serialize)] #[serde(rename_all = "snake_case")] pub enum RoutingEngine { /// Dynamo for routing IntelligentRouter, /// Decision engine for routing DecisionEngine, } /// Method type enum #[derive(Debug, Clone, Copy, Serialize)] #[serde(rename_all = "snake_case")] pub enum ApiMethod { /// grpc call Grpc, /// Rest call Rest(Method), } impl fmt::Display for ApiMethod { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Grpc => write!(f, "Grpc"), Self::Rest(method) => write!(f, "Rest ({method})"), } } } #[derive(Debug, Serialize)] /// RoutingEvent type pub struct RoutingEvent { tenant_id: common_utils::id_type::TenantId, routable_connectors: String, payment_connector: Option<String>, flow: String, request: String, response: Option<String>, error: Option<String>, url: String, method: String, payment_id: String, profile_id: common_utils::id_type::ProfileId, merchant_id: common_utils::id_type::MerchantId, created_at: i128, status_code: Option<u16>, request_id: String, routing_engine: RoutingEngine, routing_approach: Option<String>, } impl RoutingEvent { /// fn new RoutingEvent #[allow(clippy::too_many_arguments)] pub fn new( tenant_id: common_utils::id_type::TenantId, routable_connectors: String, flow: &str, request: serde_json::Value, url: String, method: ApiMethod, payment_id: String, profile_id: common_utils::id_type::ProfileId, merchant_id: common_utils::id_type::MerchantId, request_id: Option<RequestId>, routing_engine: RoutingEngine, ) -> Self { Self { tenant_id, routable_connectors, flow: flow.to_string(), request: request.to_string(), response: None, error: None, url, method: method.to_string(), payment_id, profile_id, merchant_id, created_at: OffsetDateTime::now_utc().unix_timestamp_nanos(), status_code: None, request_id: request_id .map(|i| i.as_hyphenated().to_string()) .unwrap_or("NO_REQUEST_ID".to_string()), routing_engine, payment_connector: None, routing_approach: None, } } /// fn set_response_body pub fn set_response_body<T: Serialize>(&mut self, response: &T) { match masking::masked_serialize(response) { Ok(masked) => { self.response = Some(masked.to_string()); } Err(er) => self.set_error(json!({"error": er.to_string()})), } } /// fn set_error_response_body pub fn set_error_response_body<T: Serialize>(&mut self, response: &T) { match masking::masked_serialize(response) { Ok(masked) => { self.error = Some(masked.to_string()); } Err(er) => self.set_error(json!({"error": er.to_string()})), } } /// fn set_error pub fn set_error(&mut self, error: serde_json::Value) { self.error = Some(error.to_string()); } /// set response status code pub fn set_status_code(&mut self, code: u16) { self.status_code = Some(code); } /// set response status code pub fn set_routable_connectors(&mut self, connectors: Vec<RoutableConnectorChoice>) { let connectors = connectors .into_iter() .map(|c| { format!( "{:?}:{:?}", c.connector, c.merchant_connector_id .map(|id| id.get_string_repr().to_string()) .unwrap_or(String::from("")) ) }) .collect::<Vec<_>>() .join(","); self.routable_connectors = connectors; } /// set payment connector pub fn set_payment_connector(&mut self, connector: RoutableConnectorChoice) { self.payment_connector = Some(format!( "{:?}:{:?}", connector.connector, connector .merchant_connector_id .map(|id| id.get_string_repr().to_string()) .unwrap_or(String::from("")) )); } /// set routing approach pub fn set_routing_approach(&mut self, approach: String) { self.routing_approach = Some(approach); } /// Returns the request ID of the event. pub fn get_request_id(&self) -> &str { &self.request_id } /// Returns the merchant ID of the event. pub fn get_merchant_id(&self) -> &str { self.merchant_id.get_string_repr() } /// Returns the payment ID of the event. pub fn get_payment_id(&self) -> &str { &self.payment_id } /// Returns the profile ID of the event. pub fn get_profile_id(&self) -> &str { self.profile_id.get_string_repr() } }
crates/hyperswitch_interfaces/src/events/routing_api_logs.rs
hyperswitch_interfaces::src::events::routing_api_logs
1,250
true
// File: crates/hyperswitch_interfaces/src/events/connector_api_logs.rs // Module: hyperswitch_interfaces::src::events::connector_api_logs //! Connector API logs interface use common_utils::request::Method; use router_env::tracing_actix_web::RequestId; use serde::Serialize; use serde_json::json; use time::OffsetDateTime; /// struct ConnectorEvent #[derive(Debug, Serialize)] pub struct ConnectorEvent { tenant_id: common_utils::id_type::TenantId, connector_name: String, flow: String, request: String, masked_response: Option<String>, error: Option<String>, url: String, method: String, payment_id: String, merchant_id: common_utils::id_type::MerchantId, created_at: i128, /// Connector Event Request ID pub request_id: String, latency: u128, refund_id: Option<String>, dispute_id: Option<String>, status_code: u16, } impl ConnectorEvent { /// fn new ConnectorEvent #[allow(clippy::too_many_arguments)] pub fn new( tenant_id: common_utils::id_type::TenantId, connector_name: String, flow: &str, request: serde_json::Value, url: String, method: Method, payment_id: String, merchant_id: common_utils::id_type::MerchantId, request_id: Option<&RequestId>, latency: u128, refund_id: Option<String>, dispute_id: Option<String>, status_code: u16, ) -> Self { Self { tenant_id, connector_name, flow: flow .rsplit_once("::") .map(|(_, s)| s) .unwrap_or(flow) .to_string(), request: request.to_string(), masked_response: None, error: None, url, method: method.to_string(), payment_id, merchant_id, created_at: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000, request_id: request_id .map(|i| i.as_hyphenated().to_string()) .unwrap_or("NO_REQUEST_ID".to_string()), latency, refund_id, dispute_id, status_code, } } /// fn set_response_body pub fn set_response_body<T: Serialize>(&mut self, response: &T) { match masking::masked_serialize(response) { Ok(masked) => { self.masked_response = Some(masked.to_string()); } Err(er) => self.set_error(json!({"error": er.to_string()})), } } /// fn set_error_response_body pub fn set_error_response_body<T: Serialize>(&mut self, response: &T) { match masking::masked_serialize(response) { Ok(masked) => { self.error = Some(masked.to_string()); } Err(er) => self.set_error(json!({"error": er.to_string()})), } } /// fn set_error pub fn set_error(&mut self, error: serde_json::Value) { self.error = Some(error.to_string()); } }
crates/hyperswitch_interfaces/src/events/connector_api_logs.rs
hyperswitch_interfaces::src::events::connector_api_logs
699
true
// File: crates/router/build.rs // Module: router::build fn main() { // Set thread stack size to 10 MiB for debug builds // Reference: https://doc.rust-lang.org/std/thread/#stack-size #[cfg(debug_assertions)] println!("cargo:rustc-env=RUST_MIN_STACK=10485760"); // 10 * 1024 * 1024 = 10 MiB #[cfg(feature = "vergen")] router_env::vergen::generate_cargo_instructions(); }
crates/router/build.rs
router::build
126
true
// File: crates/router/src/core.rs // Module: router::src::core pub mod admin; pub mod api_keys; pub mod api_locking; #[cfg(feature = "v1")] pub mod apple_pay_certificates_migration; pub mod authentication; #[cfg(feature = "v1")] pub mod blocklist; pub mod cache; pub mod card_testing_guard; pub mod cards_info; pub mod chat; pub mod conditional_config; pub mod configs; #[cfg(feature = "olap")] pub mod connector_onboarding; pub mod connector_validation; #[cfg(any(feature = "olap", feature = "oltp"))] pub mod currency; pub mod customers; #[cfg(feature = "v1")] pub mod debit_routing; pub mod disputes; pub mod encryption; pub mod errors; pub mod external_service_auth; pub mod files; #[cfg(feature = "frm")] pub mod fraud_check; #[cfg(feature = "v2")] pub mod gift_card; pub mod gsm; pub mod health_check; #[cfg(feature = "v1")] pub mod locker_migration; pub mod mandate; pub mod metrics; pub mod payment_link; pub mod payment_methods; pub mod payments; #[cfg(feature = "payouts")] pub mod payout_link; #[cfg(feature = "payouts")] pub mod payouts; pub mod pm_auth; pub mod poll; pub mod profile_acquirer; #[cfg(feature = "v2")] pub mod proxy; #[cfg(feature = "recon")] pub mod recon; #[cfg(feature = "v1")] pub mod refunds; #[cfg(feature = "v2")] pub mod refunds_v2; pub mod relay; #[cfg(feature = "v2")] pub mod revenue_recovery; #[cfg(feature = "v2")] pub mod revenue_recovery_data_backfill; pub mod routing; pub mod surcharge_decision_config; pub mod three_ds_decision_rule; pub mod tokenization; pub mod unified_authentication_service; pub mod unified_connector_service; #[cfg(feature = "olap")] pub mod user; #[cfg(feature = "olap")] pub mod user_role; pub mod utils; #[cfg(feature = "olap")] pub mod verification; #[cfg(feature = "olap")] pub mod verify_connector; pub mod webhooks;
crates/router/src/core.rs
router::src::core
461
true
// File: crates/router/src/consts.rs // Module: router::src::consts pub mod opensearch; #[cfg(feature = "olap")] pub mod user; pub mod user_role; use std::{collections::HashSet, str::FromStr, sync}; use api_models::enums::Country; use common_utils::{consts, id_type}; pub use hyperswitch_domain_models::consts::{ CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH, ROUTING_ENABLED_PAYMENT_METHODS, ROUTING_ENABLED_PAYMENT_METHOD_TYPES, }; pub use hyperswitch_interfaces::consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}; // ID generation pub(crate) const ID_LENGTH: usize = 20; pub(crate) const MAX_ID_LENGTH: usize = 64; #[rustfmt::skip] pub(crate) const ALPHABETS: [char; 62] = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ]; /// API client request timeout (in seconds) pub const REQUEST_TIME_OUT: u64 = 30; pub const REQUEST_TIMEOUT_ERROR_CODE: &str = "TIMEOUT"; pub const REQUEST_TIMEOUT_ERROR_MESSAGE: &str = "Connector did not respond in specified time"; pub const REQUEST_TIMEOUT_PAYMENT_NOT_FOUND: &str = "Timed out ,payment not found"; pub const REQUEST_TIMEOUT_ERROR_MESSAGE_FROM_PSYNC: &str = "This Payment has been moved to failed as there is no response from the connector"; ///Payment intent fulfillment default timeout (in seconds) pub const DEFAULT_FULFILLMENT_TIME: i64 = 15 * 60; /// Payment intent default client secret expiry (in seconds) pub const DEFAULT_SESSION_EXPIRY: i64 = 15 * 60; /// The length of a merchant fingerprint secret pub const FINGERPRINT_SECRET_LENGTH: usize = 64; pub const DEFAULT_LIST_API_LIMIT: u16 = 10; // String literals pub(crate) const UNSUPPORTED_ERROR_MESSAGE: &str = "Unsupported response type"; // General purpose base64 engines pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose = consts::BASE64_ENGINE; pub(crate) const API_KEY_LENGTH: usize = 64; // OID (Object Identifier) for the merchant ID field extension. pub(crate) const MERCHANT_ID_FIELD_EXTENSION_ID: &str = "1.2.840.113635.100.6.32"; pub const MAX_ROUTING_CONFIGS_PER_MERCHANT: usize = 100; pub const ROUTING_CONFIG_ID_LENGTH: usize = 10; pub const LOCKER_REDIS_PREFIX: &str = "LOCKER_PM_TOKEN"; pub const LOCKER_REDIS_EXPIRY_SECONDS: u32 = 60 * 15; // 15 minutes pub const JWT_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days // This should be one day, but it is causing issue while checking token in blacklist. // TODO: This should be fixed in future. pub const SINGLE_PURPOSE_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days pub const JWT_TOKEN_COOKIE_NAME: &str = "login_token"; pub const USER_BLACKLIST_PREFIX: &str = "BU_"; pub const ROLE_BLACKLIST_PREFIX: &str = "BR_"; #[cfg(feature = "email")] pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day #[cfg(feature = "email")] pub const EMAIL_TOKEN_BLACKLIST_PREFIX: &str = "BET_"; pub const EMAIL_SUBJECT_API_KEY_EXPIRY: &str = "API Key Expiry Notice"; pub const EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST: &str = "Dashboard Pro Feature Request by"; pub const EMAIL_SUBJECT_APPROVAL_RECON_REQUEST: &str = "Approval of Recon Request - Access Granted to Recon Dashboard"; pub const ROLE_INFO_CACHE_PREFIX: &str = "CR_INFO_"; pub const CARD_IP_BLOCKING_CACHE_KEY_PREFIX: &str = "CARD_IP_BLOCKING"; pub const GUEST_USER_CARD_BLOCKING_CACHE_KEY_PREFIX: &str = "GUEST_USER_CARD_BLOCKING"; pub const CUSTOMER_ID_BLOCKING_PREFIX: &str = "CUSTOMER_ID_BLOCKING"; #[cfg(feature = "olap")] pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify"; #[cfg(feature = "olap")] pub const VERIFY_CONNECTOR_MERCHANT_ID: &str = "test_merchant"; #[cfg(feature = "olap")] pub const CONNECTOR_ONBOARDING_CONFIG_PREFIX: &str = "onboarding"; /// Max payment session expiry pub const MAX_SESSION_EXPIRY: u32 = 7890000; /// Min payment session expiry pub const MIN_SESSION_EXPIRY: u32 = 60; /// Max payment intent fulfillment expiry pub const MAX_INTENT_FULFILLMENT_EXPIRY: u32 = 1800; /// Min payment intent fulfillment expiry pub const MIN_INTENT_FULFILLMENT_EXPIRY: u32 = 60; pub const LOCKER_HEALTH_CALL_PATH: &str = "/health"; pub const AUTHENTICATION_ID_PREFIX: &str = "authn"; // URL for checking the outgoing call pub const OUTGOING_CALL_URL: &str = "https://api.stripe.com/healthcheck"; // 15 minutes = 900 seconds pub const POLL_ID_TTL: i64 = 900; // Default Poll Config pub const DEFAULT_POLL_DELAY_IN_SECS: i8 = 2; pub const DEFAULT_POLL_FREQUENCY: i8 = 5; // Number of seconds to subtract from access token expiry pub(crate) const REDUCE_ACCESS_TOKEN_EXPIRY_TIME: u8 = 15; pub const CONNECTOR_CREDS_TOKEN_TTL: i64 = 900; //max_amount allowed is 999999999 in minor units pub const MAX_ALLOWED_AMOUNT: i64 = 999999999; //payment attempt default unified error code and unified error message pub const DEFAULT_UNIFIED_ERROR_CODE: &str = "UE_9000"; pub const DEFAULT_UNIFIED_ERROR_MESSAGE: &str = "Something went wrong"; // Recon's feature tag pub const RECON_FEATURE_TAG: &str = "RECONCILIATION AND SETTLEMENT"; /// Default allowed domains for payment links pub const DEFAULT_ALLOWED_DOMAINS: Option<HashSet<String>> = None; /// Default hide card nickname field pub const DEFAULT_HIDE_CARD_NICKNAME_FIELD: bool = false; /// Show card form by default for payment links pub const DEFAULT_SHOW_CARD_FORM: bool = true; /// Default bool for Display sdk only pub const DEFAULT_DISPLAY_SDK_ONLY: bool = false; /// Default bool to enable saved payment method pub const DEFAULT_ENABLE_SAVED_PAYMENT_METHOD: bool = false; /// [PaymentLink] Default bool for enabling button only when form is ready pub const DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY: bool = false; /// Default Merchant Logo Link pub const DEFAULT_MERCHANT_LOGO: &str = "https://live.hyperswitch.io/payment-link-assets/Merchant_placeholder.png"; /// Default Payment Link Background color pub const DEFAULT_BACKGROUND_COLOR: &str = "#212E46"; /// Default product Img Link pub const DEFAULT_PRODUCT_IMG: &str = "https://live.hyperswitch.io/payment-link-assets/cart_placeholder.png"; /// Default SDK Layout pub const DEFAULT_SDK_LAYOUT: &str = "tabs"; /// Vault Add request url #[cfg(feature = "v2")] pub const ADD_VAULT_REQUEST_URL: &str = "/api/v2/vault/add"; /// Vault Get Fingerprint request url #[cfg(feature = "v2")] pub const VAULT_FINGERPRINT_REQUEST_URL: &str = "/api/v2/vault/fingerprint"; /// Vault Retrieve request url #[cfg(feature = "v2")] pub const VAULT_RETRIEVE_REQUEST_URL: &str = "/api/v2/vault/retrieve"; /// Vault Delete request url #[cfg(feature = "v2")] pub const VAULT_DELETE_REQUEST_URL: &str = "/api/v2/vault/delete"; /// Vault Header content type #[cfg(feature = "v2")] pub const VAULT_HEADER_CONTENT_TYPE: &str = "application/json"; /// Vault Add flow type #[cfg(feature = "v2")] pub const VAULT_ADD_FLOW_TYPE: &str = "add_to_vault"; /// Vault Retrieve flow type #[cfg(feature = "v2")] pub const VAULT_RETRIEVE_FLOW_TYPE: &str = "retrieve_from_vault"; /// Vault Delete flow type #[cfg(feature = "v2")] pub const VAULT_DELETE_FLOW_TYPE: &str = "delete_from_vault"; /// Vault Fingerprint fetch flow type #[cfg(feature = "v2")] pub const VAULT_GET_FINGERPRINT_FLOW_TYPE: &str = "get_fingerprint_vault"; /// Max volume split for Dynamic routing pub const DYNAMIC_ROUTING_MAX_VOLUME: u8 = 100; /// Click To Pay pub const CLICK_TO_PAY: &str = "click_to_pay"; /// Merchant eligible for authentication service config pub const AUTHENTICATION_SERVICE_ELIGIBLE_CONFIG: &str = "merchants_eligible_for_authentication_service"; /// Refund flow identifier used for performing GSM operations pub const REFUND_FLOW_STR: &str = "refund_flow"; /// Minimum IBAN length (country-dependent), as per ISO 13616 standard pub const IBAN_MIN_LENGTH: usize = 15; /// Maximum IBAN length defined by the ISO 13616 standard (standard max) pub const IBAN_MAX_LENGTH: usize = 34; /// Minimum UK BACS account number length in digits pub const BACS_MIN_ACCOUNT_NUMBER_LENGTH: usize = 6; /// Maximum UK BACS account number length in digits pub const BACS_MAX_ACCOUNT_NUMBER_LENGTH: usize = 8; /// Fixed length of UK BACS sort code in digits (always 6) pub const BACS_SORT_CODE_LENGTH: usize = 6; /// Exact length of Polish Elixir system domestic account number (NRB) in digits pub const ELIXIR_ACCOUNT_NUMBER_LENGTH: usize = 26; /// Total length of Polish IBAN including country code and checksum (28 characters) pub const ELIXIR_IBAN_LENGTH: usize = 28; /// Minimum length of Swedish Bankgiro number in digits pub const BANKGIRO_MIN_LENGTH: usize = 7; /// Maximum length of Swedish Bankgiro number in digits pub const BANKGIRO_MAX_LENGTH: usize = 8; /// Minimum length of Swedish Plusgiro number in digits pub const PLUSGIRO_MIN_LENGTH: usize = 2; /// Maximum length of Swedish Plusgiro number in digits pub const PLUSGIRO_MAX_LENGTH: usize = 8; /// Default payment method session expiry pub const DEFAULT_PAYMENT_METHOD_SESSION_EXPIRY: u32 = 15 * 60; // 15 minutes /// Authorize flow identifier used for performing GSM operations pub const AUTHORIZE_FLOW_STR: &str = "Authorize"; /// Protocol Version for encrypted Google Pay Token pub(crate) const PROTOCOL: &str = "ECv2"; /// Sender ID for Google Pay Decryption pub(crate) const SENDER_ID: &[u8] = b"Google"; /// Default value for the number of attempts to retry fetching forex rates pub const DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS: u64 = 3; /// Default payment intent id pub const IRRELEVANT_PAYMENT_INTENT_ID: &str = "irrelevant_payment_intent_id"; /// Default payment attempt id pub const IRRELEVANT_PAYMENT_ATTEMPT_ID: &str = "irrelevant_payment_attempt_id"; pub static PROFILE_ID_UNAVAILABLE: sync::LazyLock<id_type::ProfileId> = sync::LazyLock::new(|| { #[allow(clippy::expect_used)] id_type::ProfileId::from_str("PROFILE_ID_UNAVAIABLE") .expect("Failed to parse PROFILE_ID_UNAVAIABLE") }); /// Default payment attempt id pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID: &str = "irrelevant_connector_request_reference_id"; // Default payment method storing TTL in redis in seconds pub const DEFAULT_PAYMENT_METHOD_STORE_TTL: i64 = 86400; // 1 day // List of countries that are part of the PSD2 region pub const PSD2_COUNTRIES: [Country; 27] = [ Country::Austria, Country::Belgium, Country::Bulgaria, Country::Croatia, Country::Cyprus, Country::Czechia, Country::Denmark, Country::Estonia, Country::Finland, Country::France, Country::Germany, Country::Greece, Country::Hungary, Country::Ireland, Country::Italy, Country::Latvia, Country::Lithuania, Country::Luxembourg, Country::Malta, Country::Netherlands, Country::Poland, Country::Portugal, Country::Romania, Country::Slovakia, Country::Slovenia, Country::Spain, Country::Sweden, ]; // Rollout percentage config prefix pub const UCS_ROLLOUT_PERCENT_CONFIG_PREFIX: &str = "ucs_rollout_config"; // UCS feature enabled config pub const UCS_ENABLED: &str = "ucs_enabled"; /// Header value indicating that signature-key-based authentication is used. pub const UCS_AUTH_SIGNATURE_KEY: &str = "signature-key"; /// Header value indicating that body-key-based authentication is used. pub const UCS_AUTH_BODY_KEY: &str = "body-key"; /// Header value indicating that header-key-based authentication is used. pub const UCS_AUTH_HEADER_KEY: &str = "header-key"; /// Header value indicating that currency-auth-key-based authentication is used. pub const UCS_AUTH_CURRENCY_AUTH_KEY: &str = "currency-auth-key"; /// Form field name for challenge request during creq submission pub const CREQ_CHALLENGE_REQUEST_KEY: &str = "creq"; /// Superposition configuration keys pub mod superposition { /// CVV requirement configuration key pub const REQUIRES_CVV: &str = "requires_cvv"; } #[cfg(test)] mod tests { #![allow(clippy::expect_used)] #[test] fn test_profile_id_unavailable_initialization() { // Just access the lazy static to ensure it doesn't panic during initialization let _profile_id = super::PROFILE_ID_UNAVAILABLE.clone(); // If we get here without panicking, the test passes } }
crates/router/src/consts.rs
router::src::consts
3,356
true
// File: crates/router/src/types.rs // Module: router::src::types // FIXME: Why were these data types grouped this way? // // Folder `types` is strange for Rust ecosystem, nevertheless it might be okay. // But folder `enum` is even more strange I unlikely okay. Why should not we introduce folders `type`, `structs` and `traits`? :) // Is it better to split data types according to business logic instead. // For example, customers/address/dispute/mandate is "models". // Separation of concerns instead of separation of forms. pub mod api; pub mod authentication; pub mod connector_transformers; pub mod domain; #[cfg(feature = "frm")] pub mod fraud_check; pub mod payment_methods; pub mod pm_auth; use masking::Secret; pub mod storage; pub mod transformers; use std::marker::PhantomData; pub use api_models::{enums::Connector, mandates}; #[cfg(feature = "payouts")] pub use api_models::{enums::PayoutConnectors, payouts as payout_types}; #[cfg(feature = "v2")] use common_utils::errors::CustomResult; pub use common_utils::{pii, pii::Email, request::RequestContent, types::MinorUnit}; #[cfg(feature = "v2")] use error_stack::ResultExt; #[cfg(feature = "frm")] pub use hyperswitch_domain_models::router_data_v2::FrmFlowData; use hyperswitch_domain_models::router_flow_types::{ self, access_token_auth::AccessTokenAuth, dispute::{Accept, Defend, Dsync, Evidence, Fetch}, files::{Retrieve, Upload}, mandate_revoke::MandateRevoke, payments::{ Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, ExtendAuthorization, ExternalVaultProxy, IncrementalAuthorization, InitPayment, PSync, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, refunds::{Execute, RSync}, webhooks::VerifyWebhookSource, }; pub use hyperswitch_domain_models::{ payment_address::PaymentAddress, router_data::{ AccessToken, AccessTokenAuthenticationResponse, AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, ErrorResponse, GooglePayPaymentMethodDetails, GooglePayPredecryptDataInternal, L2L3Data, PaymentMethodBalance, PaymentMethodToken, RecurringMandatePaymentData, RouterData, }, router_data_v2::{ AccessTokenFlowData, AuthenticationTokenFlowData, DisputesFlowData, ExternalAuthenticationFlowData, FilesFlowData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData, RouterDataV2, UasFlowData, WebhookSourceVerifyData, }, router_request_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, InvoiceRecordBackRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, BrowserInformation, ChargeRefunds, ChargeRefundsOptions, CompleteAuthorizeData, CompleteAuthorizeRedirectResponse, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, DestinationChargeRefund, DirectChargeRefund, DisputeSyncData, ExternalVaultProxyPaymentsData, FetchDisputesRequestData, MandateRevokeRequestData, MultipleCaptureRequestData, PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, ResponseId, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, SplitRefundsRequest, SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, InvoiceRecordBackResponse, }, AcceptDisputeResponse, CaptureSyncResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, MandateReference, MandateRevokeResponseData, PaymentsResponseData, PreprocessingResponseId, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, TaxCalculationResponseData, UploadFileResponse, VaultResponseData, VerifyWebhookSourceResponseData, VerifyWebhookStatus, }, }; #[cfg(feature = "payouts")] pub use hyperswitch_domain_models::{ router_data_v2::PayoutFlowData, router_request_types::PayoutsData, router_response_types::PayoutsResponseData, }; #[cfg(feature = "payouts")] pub use hyperswitch_interfaces::types::{ PayoutCancelType, PayoutCreateType, PayoutEligibilityType, PayoutFulfillType, PayoutQuoteType, PayoutRecipientAccountType, PayoutRecipientType, PayoutSyncType, }; pub use hyperswitch_interfaces::{ disputes::DisputePayload, types::{ AcceptDisputeType, ConnectorCustomerType, DefendDisputeType, FetchDisputesType, IncrementalAuthorizationType, MandateRevokeType, PaymentsAuthorizeType, PaymentsBalanceType, PaymentsCaptureType, PaymentsCompleteAuthorizeType, PaymentsInitType, PaymentsPostCaptureVoidType, PaymentsPostProcessingType, PaymentsPostSessionTokensType, PaymentsPreAuthorizeType, PaymentsPreProcessingType, PaymentsSessionType, PaymentsSyncType, PaymentsUpdateMetadataType, PaymentsVoidType, RefreshTokenType, RefundExecuteType, RefundSyncType, Response, RetrieveFileType, SdkSessionUpdateType, SetupMandateType, SubmitEvidenceType, TokenizationType, UploadFileType, VerifyWebhookSourceType, }, }; #[cfg(feature = "v2")] use crate::core::errors; pub use crate::core::payments::CustomerDetails; use crate::{ consts, core::payments::{OperationSessionGetters, PaymentData}, services, types::transformers::{ForeignFrom, ForeignTryFrom}, }; pub type PaymentsAuthorizeRouterData = RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>; pub type ExternalVaultProxyPaymentsRouterData = RouterData<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>; pub type PaymentsPreProcessingRouterData = RouterData<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; pub type PaymentsPostProcessingRouterData = RouterData<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>; pub type PaymentsAuthorizeSessionTokenRouterData = RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>; pub type PaymentsCompleteAuthorizeRouterData = RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>; pub type PaymentsInitRouterData = RouterData<InitPayment, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsBalanceRouterData = RouterData<Balance, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsIncrementalAuthorizationRouterData = RouterData< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, >; pub type PaymentsExtendAuthorizationRouterData = RouterData<ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData>; pub type PaymentsTaxCalculationRouterData = RouterData<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>; pub type CreateOrderRouterData = RouterData<CreateOrder, CreateOrderRequestData, PaymentsResponseData>; pub type SdkSessionUpdateRouterData = RouterData<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>; pub type PaymentsPostSessionTokensRouterData = RouterData<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>; pub type PaymentsUpdateMetadataRouterData = RouterData<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>; pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>; pub type PaymentsCancelPostCaptureRouterData = RouterData<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>; pub type PaymentsRejectRouterData = RouterData<Reject, PaymentsRejectData, PaymentsResponseData>; pub type PaymentsApproveRouterData = RouterData<Approve, PaymentsApproveData, PaymentsResponseData>; pub type PaymentsSessionRouterData = RouterData<Session, PaymentsSessionData, PaymentsResponseData>; pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>; pub type RefundExecuteRouterData = RouterData<Execute, RefundsData, RefundsResponseData>; pub type RefundSyncRouterData = RouterData<RSync, RefundsData, RefundsResponseData>; pub type TokenizationRouterData = RouterData< router_flow_types::PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData, >; pub type ConnectorCustomerRouterData = RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>; pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>; pub type PaymentsResponseRouterData<R> = ResponseRouterData<Authorize, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsCancelResponseRouterData<R> = ResponseRouterData<Void, R, PaymentsCancelData, PaymentsResponseData>; pub type PaymentsCancelPostCaptureResponseRouterData<R> = ResponseRouterData<PostCaptureVoid, R, PaymentsCancelPostCaptureData, PaymentsResponseData>; pub type PaymentsExtendAuthorizationResponseRouterData<R> = ResponseRouterData< ExtendAuthorization, R, PaymentsExtendAuthorizationData, PaymentsResponseData, >; pub type PaymentsBalanceResponseRouterData<R> = ResponseRouterData<Balance, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsSyncResponseRouterData<R> = ResponseRouterData<PSync, R, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsSessionResponseRouterData<R> = ResponseRouterData<Session, R, PaymentsSessionData, PaymentsResponseData>; pub type PaymentsInitResponseRouterData<R> = ResponseRouterData<InitPayment, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type SdkSessionUpdateResponseRouterData<R> = ResponseRouterData<SdkSessionUpdate, R, SdkPaymentsSessionUpdateData, PaymentsResponseData>; pub type PaymentsCaptureResponseRouterData<R> = ResponseRouterData<Capture, R, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsPreprocessingResponseRouterData<R> = ResponseRouterData<PreProcessing, R, PaymentsPreProcessingData, PaymentsResponseData>; pub type TokenizationResponseRouterData<R> = ResponseRouterData<PaymentMethodToken, R, PaymentMethodTokenizationData, PaymentsResponseData>; pub type ConnectorCustomerResponseRouterData<R> = ResponseRouterData<CreateConnectorCustomer, R, ConnectorCustomerData, PaymentsResponseData>; pub type RefundsResponseRouterData<F, R> = ResponseRouterData<F, R, RefundsData, RefundsResponseData>; pub type SetupMandateRouterData = RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>; pub type AcceptDisputeRouterData = RouterData<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>; pub type VerifyWebhookSourceRouterData = RouterData< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, >; pub type SubmitEvidenceRouterData = RouterData<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>; pub type UploadFileRouterData = RouterData<Upload, UploadFileRequestData, UploadFileResponse>; pub type RetrieveFileRouterData = RouterData<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>; pub type DefendDisputeRouterData = RouterData<Defend, DefendDisputeRequestData, DefendDisputeResponse>; pub type FetchDisputesRouterData = RouterData<Fetch, FetchDisputesRequestData, FetchDisputesResponse>; pub type DisputeSyncRouterData = RouterData<Dsync, DisputeSyncData, DisputeSyncResponse>; pub type MandateRevokeRouterData = RouterData<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>; #[cfg(feature = "payouts")] pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>; #[cfg(feature = "payouts")] pub type PayoutsResponseRouterData<F, R> = ResponseRouterData<F, R, PayoutsData, PayoutsResponseData>; #[cfg(feature = "payouts")] pub type PayoutActionData = Vec<( storage::Payouts, storage::PayoutAttempt, Option<domain::Customer>, Option<api_models::payments::Address>, )>; #[cfg(feature = "payouts")] pub trait PayoutIndividualDetailsExt { type Error; fn get_external_account_account_holder_type(&self) -> Result<String, Self::Error>; } pub trait Capturable { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, _payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { None } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _get_amount_capturable: Option<i64>, _attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { None } } #[cfg(feature = "v1")] impl Capturable for PaymentsAuthorizeData { fn get_captured_amount<F>( &self, amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { amount_captured.or(Some( payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(), )) } fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let amount_capturable_from_intent_status = match payment_data.get_capture_method().unwrap_or_default() { common_enums::CaptureMethod::Automatic | common_enums::CaptureMethod::SequentialAutomatic => { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::Processing => None, } }, common_enums::CaptureMethod::Manual => Some(payment_data.payment_attempt.get_total_amount().get_amount_as_i64()), // In case of manual multiple, amount capturable must be inferred from all captures. common_enums::CaptureMethod::ManualMultiple | // Scheduled capture is not supported as of now common_enums::CaptureMethod::Scheduled => None, }; amount_capturable .or(amount_capturable_from_intent_status) .or(Some( payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(), )) } } #[cfg(feature = "v1")] impl Capturable for PaymentsCaptureData { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, _payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { Some(self.amount_to_capture) } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Processing | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => None, } } } #[cfg(feature = "v1")] impl Capturable for CompleteAuthorizeData { fn get_captured_amount<F>( &self, amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { amount_captured.or(Some( payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(), )) } fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let amount_capturable_from_intent_status = match payment_data .get_capture_method() .unwrap_or_default() { common_enums::CaptureMethod::Automatic | common_enums::CaptureMethod::SequentialAutomatic => { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::Processing => None, } }, common_enums::CaptureMethod::Manual => Some(payment_data.payment_attempt.get_total_amount().get_amount_as_i64()), // In case of manual multiple, amount capturable must be inferred from all captures. common_enums::CaptureMethod::ManualMultiple | // Scheduled capture is not supported as of now common_enums::CaptureMethod::Scheduled => None, }; amount_capturable .or(amount_capturable_from_intent_status) .or(Some( payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(), )) } } impl Capturable for SetupMandateRequestData {} impl Capturable for PaymentsTaxCalculationData {} impl Capturable for SdkPaymentsSessionUpdateData {} impl Capturable for PaymentsPostSessionTokensData {} impl Capturable for PaymentsUpdateMetadataData {} impl Capturable for PaymentsCancelData { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // return previously captured amount payment_data .payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()) } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, } } } impl Capturable for PaymentsCancelPostCaptureData { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // return previously captured amount payment_data .payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()) } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::Processing | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => None, } } } impl Capturable for PaymentsApproveData {} impl Capturable for PaymentsRejectData {} impl Capturable for PaymentsSessionData {} impl Capturable for PaymentsIncrementalAuthorizationData { fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, amount_capturable: Option<i64>, _attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { amount_capturable.or(Some(self.total_amount)) } } impl Capturable for PaymentsSyncData { #[cfg(feature = "v1")] fn get_captured_amount<F>( &self, amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { payment_data .payment_attempt .amount_to_capture .or(payment_data.payment_intent.amount_captured) .or(amount_captured.map(MinorUnit::new)) .or_else(|| Some(payment_data.payment_attempt.get_total_amount())) .map(|amt| amt.get_amount_as_i64()) } #[cfg(feature = "v2")] fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // TODO: add a getter for this payment_data .payment_attempt .amount_details .get_amount_to_capture() .or_else(|| Some(payment_data.payment_attempt.get_total_amount())) .map(|amt| amt.get_amount_as_i64()) } #[cfg(feature = "v1")] fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { if attempt_status.is_terminal_status() { Some(0) } else { amount_capturable.or(Some(MinorUnit::get_amount_as_i64( payment_data.payment_attempt.amount_capturable, ))) } } #[cfg(feature = "v2")] fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { if attempt_status.is_terminal_status() { Some(0) } else { None } } } impl Capturable for PaymentsExtendAuthorizationData { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // return previously captured amount payment_data .payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()) } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Expired | common_enums::IntentStatus::Succeeded => Some(0), common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::Processing | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => None, } } } pub struct AddAccessTokenResult { pub access_token_result: Result<Option<AccessToken>, ErrorResponse>, pub connector_supports_access_token: bool, } pub struct PaymentMethodTokenResult { pub payment_method_token_result: Result<Option<String>, ErrorResponse>, pub is_payment_method_tokenization_performed: bool, pub connector_response: Option<ConnectorResponseData>, } #[derive(Clone)] pub struct CreateOrderResult { pub create_order_result: Result<String, ErrorResponse>, } pub struct PspTokenResult { pub token: Result<String, ErrorResponse>, } #[derive(Debug, Clone, Copy)] pub enum Redirection { Redirect, NoRedirect, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PollConfig { pub delay_in_secs: i8, pub frequency: i8, } impl PollConfig { pub fn get_poll_config_key(connector: String) -> String { format!("poll_config_external_three_ds_{connector}") } } impl Default for PollConfig { fn default() -> Self { Self { delay_in_secs: consts::DEFAULT_POLL_DELAY_IN_SECS, frequency: consts::DEFAULT_POLL_FREQUENCY, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub struct RedirectPaymentFlowResponse { pub payments_response: api_models::payments::PaymentsResponse, pub business_profile: domain::Profile, } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct RedirectPaymentFlowResponse<D> { pub payment_data: D, pub profile: domain::Profile, } #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub struct AuthenticatePaymentFlowResponse { pub payments_response: api_models::payments::PaymentsResponse, pub poll_config: PollConfig, pub business_profile: domain::Profile, } #[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)] pub struct ConnectorResponse { pub merchant_id: common_utils::id_type::MerchantId, pub connector: String, pub payment_id: common_utils::id_type::PaymentId, pub amount: i64, pub connector_transaction_id: String, pub return_url: Option<String>, pub three_ds_form: Option<services::RedirectForm>, } pub struct ResponseRouterData<Flow, R, Request, Response> { pub response: R, pub data: RouterData<Flow, Request, Response>, pub http_code: u16, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub enum RecipientIdType { ConnectorId(Secret<String>), LockerId(Secret<String>), } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum MerchantAccountData { Iban { iban: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, Bacs { account_number: Secret<String>, sort_code: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, FasterPayments { account_number: Secret<String>, sort_code: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, Sepa { iban: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, SepaInstant { iban: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, Elixir { account_number: Secret<String>, iban: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, Bankgiro { number: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, Plusgiro { number: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, } impl ForeignFrom<MerchantAccountData> for api_models::admin::MerchantAccountData { fn foreign_from(from: MerchantAccountData) -> Self { match from { MerchantAccountData::Iban { iban, name, connector_recipient_id, } => Self::Iban { iban, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::Bacs { account_number, sort_code, name, connector_recipient_id, } => Self::Bacs { account_number, sort_code, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::FasterPayments { account_number, sort_code, name, connector_recipient_id, } => Self::FasterPayments { account_number, sort_code, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::Sepa { iban, name, connector_recipient_id, } => Self::Sepa { iban, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::SepaInstant { iban, name, connector_recipient_id, } => Self::SepaInstant { iban, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::Elixir { account_number, iban, name, connector_recipient_id, } => Self::Elixir { account_number, iban, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::Bankgiro { number, name, connector_recipient_id, } => Self::Bankgiro { number, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::Plusgiro { number, name, connector_recipient_id, } => Self::Plusgiro { number, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, } } } impl From<api_models::admin::MerchantAccountData> for MerchantAccountData { fn from(from: api_models::admin::MerchantAccountData) -> Self { match from { api_models::admin::MerchantAccountData::Iban { iban, name, connector_recipient_id, } => Self::Iban { iban, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::Bacs { account_number, sort_code, name, connector_recipient_id, } => Self::Bacs { account_number, sort_code, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::FasterPayments { account_number, sort_code, name, connector_recipient_id, } => Self::FasterPayments { account_number, sort_code, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::Sepa { iban, name, connector_recipient_id, } => Self::Sepa { iban, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::SepaInstant { iban, name, connector_recipient_id, } => Self::SepaInstant { iban, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::Elixir { account_number, iban, name, connector_recipient_id, } => Self::Elixir { account_number, iban, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::Bankgiro { number, name, connector_recipient_id, } => Self::Bankgiro { number, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::Plusgiro { number, name, connector_recipient_id, } => Self::Plusgiro { number, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, } } } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum MerchantRecipientData { ConnectorRecipientId(Secret<String>), WalletId(Secret<String>), AccountData(MerchantAccountData), } impl ForeignFrom<MerchantRecipientData> for api_models::admin::MerchantRecipientData { fn foreign_from(value: MerchantRecipientData) -> Self { match value { MerchantRecipientData::ConnectorRecipientId(id) => Self::ConnectorRecipientId(id), MerchantRecipientData::WalletId(id) => Self::WalletId(id), MerchantRecipientData::AccountData(data) => { Self::AccountData(api_models::admin::MerchantAccountData::foreign_from(data)) } } } } impl From<api_models::admin::MerchantRecipientData> for MerchantRecipientData { fn from(value: api_models::admin::MerchantRecipientData) -> Self { match value { api_models::admin::MerchantRecipientData::ConnectorRecipientId(id) => { Self::ConnectorRecipientId(id) } api_models::admin::MerchantRecipientData::WalletId(id) => Self::WalletId(id), api_models::admin::MerchantRecipientData::AccountData(data) => { Self::AccountData(data.into()) } } } } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalMerchantData { OpenBankingRecipientData(MerchantRecipientData), } impl ForeignFrom<api_models::admin::AdditionalMerchantData> for AdditionalMerchantData { fn foreign_from(value: api_models::admin::AdditionalMerchantData) -> Self { match value { api_models::admin::AdditionalMerchantData::OpenBankingRecipientData(data) => { Self::OpenBankingRecipientData(MerchantRecipientData::from(data)) } } } } impl ForeignFrom<AdditionalMerchantData> for api_models::admin::AdditionalMerchantData { fn foreign_from(value: AdditionalMerchantData) -> Self { match value { AdditionalMerchantData::OpenBankingRecipientData(data) => { Self::OpenBankingRecipientData( api_models::admin::MerchantRecipientData::foreign_from(data), ) } } } } impl ForeignFrom<api_models::admin::ConnectorAuthType> for ConnectorAuthType { fn foreign_from(value: api_models::admin::ConnectorAuthType) -> Self { match value { api_models::admin::ConnectorAuthType::TemporaryAuth => Self::TemporaryAuth, api_models::admin::ConnectorAuthType::HeaderKey { api_key } => { Self::HeaderKey { api_key } } api_models::admin::ConnectorAuthType::BodyKey { api_key, key1 } => { Self::BodyKey { api_key, key1 } } api_models::admin::ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Self::SignatureKey { api_key, key1, api_secret, }, api_models::admin::ConnectorAuthType::MultiAuthKey { api_key, key1, api_secret, key2, } => Self::MultiAuthKey { api_key, key1, api_secret, key2, }, api_models::admin::ConnectorAuthType::CurrencyAuthKey { auth_key_map } => { Self::CurrencyAuthKey { auth_key_map } } api_models::admin::ConnectorAuthType::NoKey => Self::NoKey, api_models::admin::ConnectorAuthType::CertificateAuth { certificate, private_key, } => Self::CertificateAuth { certificate, private_key, }, } } } impl ForeignFrom<ConnectorAuthType> for api_models::admin::ConnectorAuthType { fn foreign_from(from: ConnectorAuthType) -> Self { match from { ConnectorAuthType::TemporaryAuth => Self::TemporaryAuth, ConnectorAuthType::HeaderKey { api_key } => Self::HeaderKey { api_key }, ConnectorAuthType::BodyKey { api_key, key1 } => Self::BodyKey { api_key, key1 }, ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Self::SignatureKey { api_key, key1, api_secret, }, ConnectorAuthType::MultiAuthKey { api_key, key1, api_secret, key2, } => Self::MultiAuthKey { api_key, key1, api_secret, key2, }, ConnectorAuthType::CurrencyAuthKey { auth_key_map } => { Self::CurrencyAuthKey { auth_key_map } } ConnectorAuthType::NoKey => Self::NoKey, ConnectorAuthType::CertificateAuth { certificate, private_key, } => Self::CertificateAuth { certificate, private_key, }, } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ConnectorsList { pub connectors: Vec<String>, } impl ForeignFrom<&PaymentsAuthorizeRouterData> for AuthorizeSessionTokenData { fn foreign_from(data: &PaymentsAuthorizeRouterData) -> Self { Self { amount_to_capture: data.amount_captured, currency: data.request.currency, connector_transaction_id: data.payment_id.clone(), amount: Some(data.request.amount), } } } impl ForeignFrom<&ExternalVaultProxyPaymentsRouterData> for AuthorizeSessionTokenData { fn foreign_from(data: &ExternalVaultProxyPaymentsRouterData) -> Self { Self { amount_to_capture: data.amount_captured, currency: data.request.currency, connector_transaction_id: data.payment_id.clone(), amount: Some(data.request.amount), } } } impl<'a> ForeignFrom<&'a SetupMandateRouterData> for AuthorizeSessionTokenData { fn foreign_from(data: &'a SetupMandateRouterData) -> Self { Self { amount_to_capture: data.request.amount, currency: data.request.currency, connector_transaction_id: data.payment_id.clone(), amount: data.request.amount, } } } pub trait Tokenizable { fn set_session_token(&mut self, token: Option<String>); } impl Tokenizable for SetupMandateRequestData { fn set_session_token(&mut self, _token: Option<String>) {} } impl Tokenizable for PaymentsAuthorizeData { fn set_session_token(&mut self, token: Option<String>) { self.session_token = token; } } impl Tokenizable for CompleteAuthorizeData { fn set_session_token(&mut self, _token: Option<String>) {} } impl Tokenizable for ExternalVaultProxyPaymentsData { fn set_session_token(&mut self, token: Option<String>) { self.session_token = token; } } impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData { fn foreign_from(data: &SetupMandateRouterData) -> Self { Self { currency: data.request.currency, payment_method_data: data.request.payment_method_data.clone(), confirm: data.request.confirm, statement_descriptor_suffix: data.request.statement_descriptor_suffix.clone(), mandate_id: data.request.mandate_id.clone(), setup_future_usage: data.request.setup_future_usage, off_session: data.request.off_session, setup_mandate_details: data.request.setup_mandate_details.clone(), router_return_url: data.request.router_return_url.clone(), email: data.request.email.clone(), customer_name: data.request.customer_name.clone(), amount: 0, order_tax_amount: Some(MinorUnit::zero()), minor_amount: MinorUnit::new(0), statement_descriptor: None, capture_method: None, webhook_url: None, complete_authorize_url: None, browser_info: data.request.browser_info.clone(), order_details: None, order_category: None, session_token: None, enrolled_for_3ds: true, related_transaction_id: None, payment_experience: None, payment_method_type: None, customer_id: None, surcharge_details: None, request_incremental_authorization: data.request.request_incremental_authorization, metadata: None, request_extended_authorization: None, authentication_data: None, customer_acceptance: data.request.customer_acceptance.clone(), split_payments: None, // TODO: allow charges on mandates? merchant_order_reference_id: None, integrity_object: None, additional_payment_method_data: None, shipping_cost: data.request.shipping_cost, merchant_account_id: None, merchant_config_currency: None, connector_testing_data: data.request.connector_testing_data.clone(), order_id: None, locale: None, payment_channel: None, enable_partial_authorization: data.request.enable_partial_authorization, enable_overcapture: None, is_stored_credential: data.request.is_stored_credential, mit_category: None, } } } impl<F1, F2, T1, T2> ForeignFrom<(&RouterData<F1, T1, PaymentsResponseData>, T2)> for RouterData<F2, T2, PaymentsResponseData> { fn foreign_from(item: (&RouterData<F1, T1, PaymentsResponseData>, T2)) -> Self { let data = item.0; let request = item.1; Self { flow: PhantomData, request, merchant_id: data.merchant_id.clone(), connector: data.connector.clone(), attempt_id: data.attempt_id.clone(), tenant_id: data.tenant_id.clone(), status: data.status, payment_method: data.payment_method, payment_method_type: data.payment_method_type, connector_auth_type: data.connector_auth_type.clone(), description: data.description.clone(), address: data.address.clone(), auth_type: data.auth_type, connector_meta_data: data.connector_meta_data.clone(), connector_wallets_details: data.connector_wallets_details.clone(), amount_captured: data.amount_captured, minor_amount_captured: data.minor_amount_captured, access_token: data.access_token.clone(), response: data.response.clone(), payment_id: data.payment_id.clone(), session_token: data.session_token.clone(), reference_id: data.reference_id.clone(), customer_id: data.customer_id.clone(), payment_method_token: None, preprocessing_id: None, connector_customer: data.connector_customer.clone(), recurring_mandate_payment_data: data.recurring_mandate_payment_data.clone(), connector_request_reference_id: data.connector_request_reference_id.clone(), #[cfg(feature = "payouts")] payout_method_data: data.payout_method_data.clone(), #[cfg(feature = "payouts")] quote_id: data.quote_id.clone(), test_mode: data.test_mode, payment_method_status: None, payment_method_balance: data.payment_method_balance.clone(), connector_api_version: data.connector_api_version.clone(), connector_http_status_code: data.connector_http_status_code, external_latency: data.external_latency, apple_pay_flow: data.apple_pay_flow.clone(), frm_metadata: data.frm_metadata.clone(), dispute_id: data.dispute_id.clone(), refund_id: data.refund_id.clone(), connector_response: data.connector_response.clone(), integrity_check: Ok(()), additional_merchant_data: data.additional_merchant_data.clone(), header_payload: data.header_payload.clone(), connector_mandate_request_reference_id: data .connector_mandate_request_reference_id .clone(), authentication_id: data.authentication_id.clone(), psd2_sca_exemption_type: data.psd2_sca_exemption_type, raw_connector_response: data.raw_connector_response.clone(), is_payment_id_from_merchant: data.is_payment_id_from_merchant, l2_l3_data: data.l2_l3_data.clone(), minor_amount_capturable: data.minor_amount_capturable, authorized_amount: data.authorized_amount, } } } #[cfg(feature = "payouts")] impl<F1, F2> ForeignFrom<( &RouterData<F1, PayoutsData, PayoutsResponseData>, PayoutsData, )> for RouterData<F2, PayoutsData, PayoutsResponseData> { fn foreign_from( item: ( &RouterData<F1, PayoutsData, PayoutsResponseData>, PayoutsData, ), ) -> Self { let data = item.0; let request = item.1; Self { flow: PhantomData, request, merchant_id: data.merchant_id.clone(), connector: data.connector.clone(), attempt_id: data.attempt_id.clone(), tenant_id: data.tenant_id.clone(), status: data.status, payment_method: data.payment_method, payment_method_type: data.payment_method_type, connector_auth_type: data.connector_auth_type.clone(), description: data.description.clone(), address: data.address.clone(), auth_type: data.auth_type, connector_meta_data: data.connector_meta_data.clone(), connector_wallets_details: data.connector_wallets_details.clone(), amount_captured: data.amount_captured, minor_amount_captured: data.minor_amount_captured, access_token: data.access_token.clone(), response: data.response.clone(), payment_id: data.payment_id.clone(), session_token: data.session_token.clone(), reference_id: data.reference_id.clone(), customer_id: data.customer_id.clone(), payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: None, connector_customer: data.connector_customer.clone(), connector_request_reference_id: data.connector_request_reference_id.clone(), payout_method_data: data.payout_method_data.clone(), quote_id: data.quote_id.clone(), test_mode: data.test_mode, payment_method_balance: None, payment_method_status: None, connector_api_version: None, connector_http_status_code: data.connector_http_status_code, external_latency: data.external_latency, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: data.connector_response.clone(), integrity_check: Ok(()), header_payload: data.header_payload.clone(), authentication_id: None, psd2_sca_exemption_type: None, additional_merchant_data: data.additional_merchant_data.clone(), connector_mandate_request_reference_id: None, raw_connector_response: None, is_payment_id_from_merchant: data.is_payment_id_from_merchant, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, } } } #[cfg(feature = "v2")] impl ForeignFrom<&domain::MerchantConnectorAccountFeatureMetadata> for api_models::admin::MerchantConnectorAccountFeatureMetadata { fn foreign_from(item: &domain::MerchantConnectorAccountFeatureMetadata) -> Self { let revenue_recovery = item .revenue_recovery .as_ref() .map( |revenue_recovery_metadata| api_models::admin::RevenueRecoveryMetadata { max_retry_count: revenue_recovery_metadata.max_retry_count, billing_connector_retry_threshold: revenue_recovery_metadata .billing_connector_retry_threshold, billing_account_reference: revenue_recovery_metadata .mca_reference .recovery_to_billing .clone(), }, ); Self { revenue_recovery } } } #[cfg(feature = "v2")] impl ForeignTryFrom<&api_models::admin::MerchantConnectorAccountFeatureMetadata> for domain::MerchantConnectorAccountFeatureMetadata { type Error = errors::ApiErrorResponse; fn foreign_try_from( feature_metadata: &api_models::admin::MerchantConnectorAccountFeatureMetadata, ) -> Result<Self, Self::Error> { let revenue_recovery = feature_metadata .revenue_recovery .as_ref() .map(|revenue_recovery_metadata| { domain::AccountReferenceMap::new( revenue_recovery_metadata.billing_account_reference.clone(), ) .map(|mca_reference| domain::RevenueRecoveryMetadata { max_retry_count: revenue_recovery_metadata.max_retry_count, billing_connector_retry_threshold: revenue_recovery_metadata .billing_connector_retry_threshold, mca_reference, }) }) .transpose()?; Ok(Self { revenue_recovery }) } }
crates/router/src/types.rs
router::src::types
11,898
true
// File: crates/router/src/events.rs // Module: router::src::events use std::collections::HashMap; use common_utils::types::TenantConfig; use error_stack::ResultExt; use events::{EventsError, Message, MessagingInterface}; use hyperswitch_interfaces::events as events_interfaces; use masking::ErasedMaskSerialize; use router_env::logger; use serde::{Deserialize, Serialize}; use storage_impl::errors::{ApplicationError, StorageError, StorageResult}; use time::PrimitiveDateTime; use crate::{ db::KafkaProducer, services::kafka::{KafkaMessage, KafkaSettings}, }; pub mod api_logs; pub mod audit_events; pub mod connector_api_logs; pub mod event_logger; pub mod outgoing_webhook_logs; pub mod routing_api_logs; #[derive(Debug, Serialize, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum EventType { PaymentIntent, FraudCheck, PaymentAttempt, Refund, ApiLogs, ConnectorApiLogs, OutgoingWebhookLogs, Dispute, AuditEvent, #[cfg(feature = "payouts")] Payout, Consolidated, Authentication, RoutingApiLogs, RevenueRecovery, } #[derive(Debug, Default, Deserialize, Clone)] #[serde(tag = "source")] #[serde(rename_all = "lowercase")] pub enum EventsConfig { Kafka { kafka: Box<KafkaSettings>, }, #[default] Logs, } #[allow(clippy::large_enum_variant)] #[derive(Debug, Clone)] pub enum EventsHandler { Kafka(KafkaProducer), Logs(event_logger::EventLogger), } impl Default for EventsHandler { fn default() -> Self { Self::Logs(event_logger::EventLogger {}) } } impl events_interfaces::EventHandlerInterface for EventsHandler { fn log_connector_event(&self, event: &events_interfaces::connector_api_logs::ConnectorEvent) { self.log_event(event); } } impl EventsConfig { pub async fn get_event_handler(&self) -> StorageResult<EventsHandler> { Ok(match self { Self::Kafka { kafka } => EventsHandler::Kafka( KafkaProducer::create(kafka) .await .change_context(StorageError::InitializationError)?, ), Self::Logs => EventsHandler::Logs(event_logger::EventLogger::default()), }) } pub fn validate(&self) -> Result<(), ApplicationError> { match self { Self::Kafka { kafka } => kafka.validate(), Self::Logs => Ok(()), } } } impl EventsHandler { pub fn log_event<T: KafkaMessage>(&self, event: &T) { match self { Self::Kafka(kafka) => kafka.log_event(event).unwrap_or_else(|e| { logger::error!("Failed to log event: {:?}", e); }), Self::Logs(logger) => logger.log_event(event), }; } pub fn add_tenant(&mut self, tenant_config: &dyn TenantConfig) { if let Self::Kafka(kafka_producer) = self { kafka_producer.set_tenancy(tenant_config); } } } impl MessagingInterface for EventsHandler { type MessageClass = EventType; fn send_message<T>( &self, data: T, metadata: HashMap<String, String>, timestamp: PrimitiveDateTime, ) -> error_stack::Result<(), EventsError> where T: Message<Class = Self::MessageClass> + ErasedMaskSerialize, { match self { Self::Kafka(a) => a.send_message(data, metadata, timestamp), Self::Logs(a) => a.send_message(data, metadata, timestamp), } } }
crates/router/src/events.rs
router::src::events
789
true
// File: crates/router/src/env.rs // Module: router::src::env #[doc(inline)] pub use router_env::*;
crates/router/src/env.rs
router::src::env
28
true
// File: crates/router/src/configs.rs // Module: router::src::configs use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret; pub(crate) mod defaults; pub mod secrets_transformers; pub mod settings; mod validations; pub type Settings = settings::Settings<RawSecret>;
crates/router/src/configs.rs
router::src::configs
64
true
// File: crates/router/src/lib.rs // Module: router::src::lib #[cfg(all(feature = "stripe", feature = "v1"))] pub mod compatibility; pub mod configs; pub mod connection; pub mod connector; pub mod consts; pub mod core; pub mod cors; pub mod db; pub mod env; pub mod locale; pub(crate) mod macros; pub mod routes; pub mod workflows; #[cfg(feature = "olap")] pub mod analytics; pub mod analytics_validator; pub mod events; pub mod middleware; pub mod services; pub mod types; pub mod utils; use actix_web::{ body::MessageBody, dev::{Server, ServerHandle, ServiceFactory, ServiceRequest}, middleware::ErrorHandlers, }; use http::StatusCode; use hyperswitch_interfaces::secrets_interface::secret_state::SecuredSecret; use router_env::tracing::Instrument; use routes::{AppState, SessionState}; use storage_impl::errors::ApplicationResult; use tokio::sync::{mpsc, oneshot}; pub use self::env::logger; pub(crate) use self::macros::*; use crate::{configs::settings, core::errors}; #[cfg(feature = "mimalloc")] #[global_allocator] static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc; // Import translate fn in root use crate::locale::{_rust_i18n_t, _rust_i18n_try_translate}; /// Header Constants pub mod headers { pub const ACCEPT: &str = "Accept"; pub const ACCEPT_LANGUAGE: &str = "Accept-Language"; pub const KEY: &str = "key"; pub const API_KEY: &str = "API-KEY"; pub const APIKEY: &str = "apikey"; pub const X_CC_API_KEY: &str = "X-CC-Api-Key"; pub const API_TOKEN: &str = "Api-Token"; pub const AUTHORIZATION: &str = "Authorization"; pub const CONTENT_TYPE: &str = "Content-Type"; pub const DATE: &str = "Date"; pub const IDEMPOTENCY_KEY: &str = "Idempotency-Key"; pub const NONCE: &str = "nonce"; pub const TIMESTAMP: &str = "Timestamp"; pub const TOKEN: &str = "token"; pub const USER_AGENT: &str = "User-Agent"; pub const X_API_KEY: &str = "X-API-KEY"; pub const X_API_VERSION: &str = "X-ApiVersion"; pub const X_FORWARDED_FOR: &str = "X-Forwarded-For"; pub const X_MERCHANT_ID: &str = "X-Merchant-Id"; pub const X_INTERNAL_API_KEY: &str = "X-Internal-Api-Key"; pub const X_ORGANIZATION_ID: &str = "X-Organization-Id"; pub const X_LOGIN: &str = "X-Login"; pub const X_TRANS_KEY: &str = "X-Trans-Key"; pub const X_VERSION: &str = "X-Version"; pub const X_CC_VERSION: &str = "X-CC-Version"; pub const X_ACCEPT_VERSION: &str = "X-Accept-Version"; pub const X_DATE: &str = "X-Date"; pub const X_WEBHOOK_SIGNATURE: &str = "X-Webhook-Signature-512"; pub const X_REQUEST_ID: &str = "X-Request-Id"; pub const X_PROFILE_ID: &str = "X-Profile-Id"; pub const STRIPE_COMPATIBLE_WEBHOOK_SIGNATURE: &str = "Stripe-Signature"; pub const STRIPE_COMPATIBLE_CONNECT_ACCOUNT: &str = "Stripe-Account"; pub const X_CLIENT_VERSION: &str = "X-Client-Version"; pub const X_CLIENT_SOURCE: &str = "X-Client-Source"; pub const X_PAYMENT_CONFIRM_SOURCE: &str = "X-Payment-Confirm-Source"; pub const CONTENT_LENGTH: &str = "Content-Length"; pub const BROWSER_NAME: &str = "x-browser-name"; pub const X_CLIENT_PLATFORM: &str = "x-client-platform"; pub const X_MERCHANT_DOMAIN: &str = "x-merchant-domain"; pub const X_APP_ID: &str = "x-app-id"; pub const X_REDIRECT_URI: &str = "x-redirect-uri"; pub const X_TENANT_ID: &str = "x-tenant-id"; pub const X_CLIENT_SECRET: &str = "X-Client-Secret"; pub const X_CUSTOMER_ID: &str = "X-Customer-Id"; pub const X_CONNECTED_MERCHANT_ID: &str = "x-connected-merchant-id"; // Header value for X_CONNECTOR_HTTP_STATUS_CODE differs by version. // Constant name is kept the same for consistency across versions. #[cfg(feature = "v1")] pub const X_CONNECTOR_HTTP_STATUS_CODE: &str = "connector_http_status_code"; #[cfg(feature = "v2")] pub const X_CONNECTOR_HTTP_STATUS_CODE: &str = "x-connector-http-status-code"; pub const X_REFERENCE_ID: &str = "X-Reference-Id"; } pub mod pii { //! Personal Identifiable Information protection. pub(crate) use common_utils::pii::Email; #[doc(inline)] pub use masking::*; } pub fn mk_app( state: AppState, request_body_limit: usize, ) -> actix_web::App< impl ServiceFactory< ServiceRequest, Config = (), Response = actix_web::dev::ServiceResponse<impl MessageBody>, Error = actix_web::Error, InitError = (), >, > { let mut server_app = get_application_builder(request_body_limit, state.conf.cors.clone()); #[cfg(feature = "dummy_connector")] { use routes::DummyConnector; server_app = server_app.service(DummyConnector::server(state.clone())); } #[cfg(any(feature = "olap", feature = "oltp"))] { #[cfg(feature = "olap")] { // This is a more specific route as compared to `MerchantConnectorAccount` // so it is registered before `MerchantConnectorAccount`. #[cfg(feature = "v1")] { server_app = server_app .service(routes::ProfileNew::server(state.clone())) .service(routes::Forex::server(state.clone())) .service(routes::ProfileAcquirer::server(state.clone())); } server_app = server_app.service(routes::Profile::server(state.clone())); } server_app = server_app .service(routes::Payments::server(state.clone())) .service(routes::Customers::server(state.clone())) .service(routes::Configs::server(state.clone())) .service(routes::MerchantConnectorAccount::server(state.clone())) .service(routes::RelayWebhooks::server(state.clone())) .service(routes::Webhooks::server(state.clone())) .service(routes::Hypersense::server(state.clone())) .service(routes::Relay::server(state.clone())) .service(routes::ThreeDsDecisionRule::server(state.clone())); #[cfg(feature = "oltp")] { server_app = server_app.service(routes::PaymentMethods::server(state.clone())); } #[cfg(all(feature = "v2", feature = "oltp"))] { server_app = server_app .service(routes::PaymentMethodSession::server(state.clone())) .service(routes::Refunds::server(state.clone())); } #[cfg(all(feature = "v2", feature = "oltp", feature = "tokenization_v2"))] { server_app = server_app.service(routes::Tokenization::server(state.clone())); } #[cfg(feature = "v1")] { server_app = server_app .service(routes::Refunds::server(state.clone())) .service(routes::Mandates::server(state.clone())) .service(routes::Authentication::server(state.clone())); } } #[cfg(all(feature = "oltp", any(feature = "v1", feature = "v2"),))] { server_app = server_app.service(routes::EphemeralKey::server(state.clone())) } #[cfg(all(feature = "oltp", feature = "v1"))] { server_app = server_app.service(routes::Poll::server(state.clone())) } #[cfg(feature = "olap")] { server_app = server_app .service(routes::Organization::server(state.clone())) .service(routes::MerchantAccount::server(state.clone())) .service(routes::User::server(state.clone())) .service(routes::ApiKeys::server(state.clone())) .service(routes::Routing::server(state.clone())) .service(routes::Chat::server(state.clone())); #[cfg(all(feature = "olap", any(feature = "v1", feature = "v2")))] { server_app = server_app.service(routes::Verify::server(state.clone())); } #[cfg(feature = "v1")] { server_app = server_app .service(routes::Files::server(state.clone())) .service(routes::Disputes::server(state.clone())) .service(routes::Blocklist::server(state.clone())) .service(routes::Subscription::server(state.clone())) .service(routes::Gsm::server(state.clone())) .service(routes::ApplePayCertificatesMigration::server(state.clone())) .service(routes::PaymentLink::server(state.clone())) .service(routes::ConnectorOnboarding::server(state.clone())) .service(routes::Analytics::server(state.clone())) .service(routes::WebhookEvents::server(state.clone())) .service(routes::FeatureMatrix::server(state.clone())); } #[cfg(feature = "v2")] { server_app = server_app .service(routes::UserDeprecated::server(state.clone())) .service(routes::ProcessTrackerDeprecated::server(state.clone())) .service(routes::ProcessTracker::server(state.clone())) .service(routes::Gsm::server(state.clone())) .service(routes::RecoveryDataBackfill::server(state.clone())); } } #[cfg(all(feature = "payouts", feature = "v1"))] { server_app = server_app .service(routes::Payouts::server(state.clone())) .service(routes::PayoutLink::server(state.clone())); } #[cfg(all(feature = "stripe", feature = "v1"))] { server_app = server_app .service(routes::StripeApis::server(state.clone())) .service(routes::Cards::server(state.clone())); } #[cfg(all(feature = "oltp", feature = "v2"))] { server_app = server_app.service(routes::Proxy::server(state.clone())); } #[cfg(all(feature = "recon", feature = "v1"))] { server_app = server_app.service(routes::Recon::server(state.clone())); } server_app = server_app.service(routes::Cache::server(state.clone())); server_app = server_app.service(routes::Health::server(state.clone())); server_app } /// Starts the server /// /// # Panics /// /// Unwrap used because without the value we can't start the server #[allow(clippy::expect_used, clippy::unwrap_used)] pub async fn start_server(conf: settings::Settings<SecuredSecret>) -> ApplicationResult<Server> { logger::debug!(startup_config=?conf); let server = conf.server.clone(); let (tx, rx) = oneshot::channel(); let api_client = Box::new(services::ProxyClient::new(&conf.proxy).map_err(|error| { errors::ApplicationError::ApiClientError(error.current_context().clone()) })?); let state = Box::pin(AppState::new(conf, tx, api_client)).await; let request_body_limit = server.request_body_limit; let server_builder = actix_web::HttpServer::new(move || mk_app(state.clone(), request_body_limit)) .bind((server.host.as_str(), server.port))? .workers(server.workers) .shutdown_timeout(server.shutdown_timeout); #[cfg(feature = "tls")] let server = match server.tls { None => server_builder.run(), Some(tls_conf) => { let cert_file = &mut std::io::BufReader::new(std::fs::File::open(tls_conf.certificate).map_err( |err| errors::ApplicationError::InvalidConfigurationValueError(err.to_string()), )?); let key_file = &mut std::io::BufReader::new(std::fs::File::open(tls_conf.private_key).map_err( |err| errors::ApplicationError::InvalidConfigurationValueError(err.to_string()), )?); let cert_chain = rustls_pemfile::certs(cert_file) .collect::<Result<Vec<_>, _>>() .map_err(|err| { errors::ApplicationError::InvalidConfigurationValueError(err.to_string()) })?; let mut keys = rustls_pemfile::pkcs8_private_keys(key_file) .map(|key| key.map(rustls::pki_types::PrivateKeyDer::Pkcs8)) .collect::<Result<Vec<_>, _>>() .map_err(|err| { errors::ApplicationError::InvalidConfigurationValueError(err.to_string()) })?; // exit if no keys could be parsed if keys.is_empty() { return Err(errors::ApplicationError::InvalidConfigurationValueError( "Could not locate PKCS8 private keys.".into(), )); } let config_builder = rustls::ServerConfig::builder().with_no_client_auth(); let config = config_builder .with_single_cert(cert_chain, keys.remove(0)) .map_err(|err| { errors::ApplicationError::InvalidConfigurationValueError(err.to_string()) })?; server_builder .bind_rustls_0_22( (tls_conf.host.unwrap_or(server.host).as_str(), tls_conf.port), config, )? .run() } }; #[cfg(not(feature = "tls"))] let server = server_builder.run(); let _task_handle = tokio::spawn(receiver_for_error(rx, server.handle()).in_current_span()); Ok(server) } pub async fn receiver_for_error(rx: oneshot::Receiver<()>, mut server: impl Stop) { match rx.await { Ok(_) => { logger::error!("The redis server failed "); server.stop_server().await; } Err(err) => { logger::error!("Channel receiver error: {err}"); } } } #[async_trait::async_trait] pub trait Stop { async fn stop_server(&mut self); } #[async_trait::async_trait] impl Stop for ServerHandle { async fn stop_server(&mut self) { let _ = self.stop(true).await; } } #[async_trait::async_trait] impl Stop for mpsc::Sender<()> { async fn stop_server(&mut self) { let _ = self.send(()).await.map_err(|err| logger::error!("{err}")); } } pub fn get_application_builder( request_body_limit: usize, cors: settings::CorsSettings, ) -> actix_web::App< impl ServiceFactory< ServiceRequest, Config = (), Response = actix_web::dev::ServiceResponse<impl MessageBody>, Error = actix_web::Error, InitError = (), >, > { let json_cfg = actix_web::web::JsonConfig::default() .limit(request_body_limit) .content_type_required(true) .error_handler(utils::error_parser::custom_json_error_handler); actix_web::App::new() .app_data(json_cfg) .wrap(ErrorHandlers::new().handler( StatusCode::NOT_FOUND, errors::error_handlers::custom_error_handlers, )) .wrap(ErrorHandlers::new().handler( StatusCode::METHOD_NOT_ALLOWED, errors::error_handlers::custom_error_handlers, )) .wrap(middleware::default_response_headers()) .wrap(middleware::RequestId) .wrap(cors::cors(cors)) // this middleware works only for Http1.1 requests .wrap(middleware::Http400RequestDetailsLogger) .wrap(middleware::AddAcceptLanguageHeader) .wrap(middleware::RequestResponseMetrics) .wrap(middleware::LogSpanInitializer) .wrap(router_env::tracing_actix_web::TracingLogger::default()) }
crates/router/src/lib.rs
router::src::lib
3,555
true
// File: crates/router/src/cors.rs // Module: router::src::cors // use actix_web::http::header; use crate::configs::settings; pub fn cors(config: settings::CorsSettings) -> actix_cors::Cors { let allowed_methods = config.allowed_methods.iter().map(|s| s.as_str()); let mut cors = actix_cors::Cors::default() .allowed_methods(allowed_methods) .allow_any_header() .expose_any_header() .max_age(config.max_age); if config.wildcard_origin { cors = cors.allow_any_origin() } else { for origin in &config.origins { cors = cors.allowed_origin(origin); } // Only allow this in case if it's not wildcard origins. ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials cors = cors.supports_credentials(); } cors }
crates/router/src/cors.rs
router::src::cors
204
true
// File: crates/router/src/services.rs // Module: router::src::services pub mod api; pub mod authentication; pub mod authorization; pub mod connector_integration_interface; #[cfg(feature = "email")] pub mod email; pub mod encryption; #[cfg(feature = "olap")] pub mod jwt; pub mod kafka; pub mod logger; pub mod pm_auth; pub mod card_testing_guard; #[cfg(feature = "olap")] pub mod openidconnect; use std::sync::Arc; use common_utils::types::TenantConfig; use error_stack::ResultExt; pub use hyperswitch_interfaces::connector_integration_v2::{ BoxedConnectorIntegrationV2, ConnectorIntegrationAnyV2, ConnectorIntegrationV2, }; use masking::{ExposeInterface, StrongSecret}; #[cfg(feature = "kv_store")] use storage_impl::kv_router_store::KVRouterStore; use storage_impl::{errors::StorageResult, redis::RedisStore, RouterStore}; use tokio::sync::oneshot; pub use self::{api::*, encryption::*}; use crate::{configs::Settings, core::errors}; #[cfg(not(feature = "olap"))] pub type StoreType = storage_impl::database::store::Store; #[cfg(feature = "olap")] pub type StoreType = storage_impl::database::store::ReplicaStore; #[cfg(not(feature = "kv_store"))] pub type Store = RouterStore<StoreType>; #[cfg(feature = "kv_store")] pub type Store = KVRouterStore<StoreType>; /// # Panics /// /// Will panic if hex decode of master key fails #[allow(clippy::expect_used)] pub async fn get_store( config: &Settings, tenant: &dyn TenantConfig, cache_store: Arc<RedisStore>, test_transaction: bool, ) -> StorageResult<Store> { let master_config = config.master_database.clone().into_inner(); #[cfg(feature = "olap")] let replica_config = config.replica_database.clone().into_inner(); #[allow(clippy::expect_used)] let master_enc_key = hex::decode(config.secrets.get_inner().master_enc_key.clone().expose()) .map(StrongSecret::new) .expect("Failed to decode master key from hex"); #[cfg(not(feature = "olap"))] let conf = master_config.into(); #[cfg(feature = "olap")] // this would get abstracted, for all cases #[allow(clippy::useless_conversion)] let conf = (master_config.into(), replica_config.into()); let store: RouterStore<StoreType> = if test_transaction { RouterStore::test_store(conf, tenant, &config.redis, master_enc_key).await? } else { RouterStore::from_config( conf, tenant, master_enc_key, cache_store, storage_impl::redis::cache::IMC_INVALIDATION_CHANNEL, ) .await? }; #[cfg(feature = "kv_store")] let store = KVRouterStore::from_store( store, config.drainer.stream_name.clone(), config.drainer.num_partitions, config.kv_config.ttl, config.kv_config.soft_kill, ); Ok(store) } #[allow(clippy::expect_used)] pub async fn get_cache_store( config: &Settings, shut_down_signal: oneshot::Sender<()>, _test_transaction: bool, ) -> StorageResult<Arc<RedisStore>> { RouterStore::<StoreType>::cache_store(&config.redis, shut_down_signal).await } #[inline] pub fn generate_aes256_key() -> errors::CustomResult<[u8; 32], common_utils::errors::CryptoError> { use ring::rand::SecureRandom; let rng = ring::rand::SystemRandom::new(); let mut key: [u8; 256 / 8] = [0_u8; 256 / 8]; rng.fill(&mut key) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(key) }
crates/router/src/services.rs
router::src::services
862
true
// File: crates/router/src/compatibility.rs // Module: router::src::compatibility pub mod stripe; pub mod wrap;
crates/router/src/compatibility.rs
router::src::compatibility
29
true
// File: crates/router/src/db.rs // Module: router::src::db pub mod address; pub mod api_keys; pub mod authentication; pub mod authorization; pub mod blocklist; pub mod blocklist_fingerprint; pub mod blocklist_lookup; pub mod business_profile; pub mod callback_mapper; pub mod capture; pub mod configs; pub mod customers; pub mod dashboard_metadata; pub mod dispute; pub mod dynamic_routing_stats; pub mod ephemeral_key; pub mod events; pub mod file; pub mod fraud_check; pub mod generic_link; pub mod gsm; pub mod health_check; pub mod hyperswitch_ai_interaction; pub mod kafka_store; pub mod locker_mock_up; pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; pub mod merchant_key_store; pub mod organization; pub mod payment_link; pub mod payment_method_session; pub mod refund; pub mod relay; pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; pub mod unified_translations; pub mod user; pub mod user_authentication_method; pub mod user_key_store; pub mod user_role; use ::payment_methods::state::PaymentMethodsStorageInterface; use common_utils::id_type; use diesel_models::{ fraud_check::{FraudCheck, FraudCheckUpdate}, organization::{Organization, OrganizationNew, OrganizationUpdate}, }; use error_stack::ResultExt; #[cfg(feature = "payouts")] use hyperswitch_domain_models::payouts::{ payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface, }; use hyperswitch_domain_models::{ cards_info::CardsInfoInterface, master_key::MasterKeyInterface, payment_methods::PaymentMethodInterface, payments::{payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface}, }; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; use redis_interface::errors::RedisError; use router_env::logger; use storage_impl::{ errors::StorageError, redis::kv_store::RedisConnInterface, tokenization, MockDb, }; pub use self::kafka_store::KafkaStore; use self::{fraud_check::FraudCheckInterface, organization::OrganizationInterface}; pub use crate::{ core::errors::{self, ProcessTrackerError}, errors::CustomResult, services::{ kafka::{KafkaError, KafkaProducer, MQResult}, Store, }, types::{ domain, storage::{self}, AccessToken, }, }; #[derive(PartialEq, Eq)] pub enum StorageImpl { Postgresql, PostgresqlTest, Mock, } #[async_trait::async_trait] pub trait StorageInterface: Send + Sync + dyn_clone::DynClone + address::AddressInterface + api_keys::ApiKeyInterface + blocklist_lookup::BlocklistLookupInterface + configs::ConfigInterface<Error = StorageError> + capture::CaptureInterface + customers::CustomerInterface<Error = StorageError> + dashboard_metadata::DashboardMetadataInterface + dispute::DisputeInterface + ephemeral_key::EphemeralKeyInterface + ephemeral_key::ClientSecretInterface + events::EventInterface + file::FileMetadataInterface + FraudCheckInterface + locker_mock_up::LockerMockUpInterface + mandate::MandateInterface + merchant_account::MerchantAccountInterface<Error = StorageError> + merchant_connector_account::ConnectorAccessToken + merchant_connector_account::MerchantConnectorAccountInterface<Error = StorageError> + PaymentAttemptInterface<Error = StorageError> + PaymentIntentInterface<Error = StorageError> + PaymentMethodInterface<Error = StorageError> + blocklist::BlocklistInterface + blocklist_fingerprint::BlocklistFingerprintInterface + dynamic_routing_stats::DynamicRoutingStatsInterface + scheduler::SchedulerInterface + PayoutAttemptInterface<Error = StorageError> + PayoutsInterface<Error = StorageError> + refund::RefundInterface + reverse_lookup::ReverseLookupInterface + CardsInfoInterface<Error = StorageError> + merchant_key_store::MerchantKeyStoreInterface<Error = StorageError> + MasterKeyInterface + payment_link::PaymentLinkInterface + RedisConnInterface + RequestIdStore + business_profile::ProfileInterface<Error = StorageError> + routing_algorithm::RoutingAlgorithmInterface + gsm::GsmInterface + unified_translations::UnifiedTranslationsInterface + authorization::AuthorizationInterface + user::sample_data::BatchSampleDataInterface + health_check::HealthCheckDbInterface + user_authentication_method::UserAuthenticationMethodInterface + hyperswitch_ai_interaction::HyperswitchAiInteractionInterface + authentication::AuthenticationInterface + generic_link::GenericLinkInterface + relay::RelayInterface + user::theme::ThemeInterface + payment_method_session::PaymentMethodsSessionInterface + tokenization::TokenizationInterface + callback_mapper::CallbackMapperInterface + storage_impl::subscription::SubscriptionInterface<Error = StorageError> + storage_impl::invoice::InvoiceInterface<Error = StorageError> + 'static { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>; fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface>; fn get_subscription_store(&self) -> Box<dyn subscriptions::state::SubscriptionStorageInterface>; fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static>; } #[async_trait::async_trait] pub trait GlobalStorageInterface: Send + Sync + dyn_clone::DynClone + user::UserInterface + user_role::UserRoleInterface + user_key_store::UserKeyStoreInterface + role::RoleInterface + RedisConnInterface + 'static { fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static>; } #[async_trait::async_trait] pub trait AccountsStorageInterface: Send + Sync + dyn_clone::DynClone + OrganizationInterface + merchant_account::MerchantAccountInterface<Error = StorageError> + business_profile::ProfileInterface<Error = StorageError> + merchant_connector_account::MerchantConnectorAccountInterface<Error = StorageError> + merchant_key_store::MerchantKeyStoreInterface<Error = StorageError> + dashboard_metadata::DashboardMetadataInterface + 'static { } pub trait CommonStorageInterface: StorageInterface + GlobalStorageInterface + AccountsStorageInterface + PaymentMethodsStorageInterface { fn get_storage_interface(&self) -> Box<dyn StorageInterface>; fn get_global_storage_interface(&self) -> Box<dyn GlobalStorageInterface>; fn get_accounts_storage_interface(&self) -> Box<dyn AccountsStorageInterface>; } #[async_trait::async_trait] impl StorageInterface for Store { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface> { Box::new(self.clone()) } fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface> { Box::new(self.clone()) } fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } fn get_subscription_store( &self, ) -> Box<dyn subscriptions::state::SubscriptionStorageInterface> { Box::new(self.clone()) } } #[async_trait::async_trait] impl GlobalStorageInterface for Store { fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } } impl AccountsStorageInterface for Store {} #[async_trait::async_trait] impl StorageInterface for MockDb { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface> { Box::new(self.clone()) } fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface> { Box::new(self.clone()) } fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } fn get_subscription_store( &self, ) -> Box<dyn subscriptions::state::SubscriptionStorageInterface> { Box::new(self.clone()) } } #[async_trait::async_trait] impl GlobalStorageInterface for MockDb { fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } } impl AccountsStorageInterface for MockDb {} impl CommonStorageInterface for MockDb { fn get_global_storage_interface(&self) -> Box<dyn GlobalStorageInterface> { Box::new(self.clone()) } fn get_storage_interface(&self) -> Box<dyn StorageInterface> { Box::new(self.clone()) } fn get_accounts_storage_interface(&self) -> Box<dyn AccountsStorageInterface> { Box::new(self.clone()) } } impl CommonStorageInterface for Store { fn get_global_storage_interface(&self) -> Box<dyn GlobalStorageInterface> { Box::new(self.clone()) } fn get_storage_interface(&self) -> Box<dyn StorageInterface> { Box::new(self.clone()) } fn get_accounts_storage_interface(&self) -> Box<dyn AccountsStorageInterface> { Box::new(self.clone()) } } pub trait RequestIdStore { fn add_request_id(&mut self, _request_id: String) {} fn get_request_id(&self) -> Option<String> { None } } impl RequestIdStore for MockDb {} impl RequestIdStore for Store { fn add_request_id(&mut self, request_id: String) { self.request_id = Some(request_id) } fn get_request_id(&self) -> Option<String> { self.request_id.clone() } } pub async fn get_and_deserialize_key<T>( db: &dyn StorageInterface, key: &str, type_name: &'static str, ) -> CustomResult<T, RedisError> where T: serde::de::DeserializeOwned, { use common_utils::ext_traits::ByteSliceExt; let bytes = db.get_key(key).await?; bytes .parse_struct(type_name) .change_context(RedisError::JsonDeserializationFailed) } dyn_clone::clone_trait_object!(StorageInterface); dyn_clone::clone_trait_object!(GlobalStorageInterface); dyn_clone::clone_trait_object!(AccountsStorageInterface); impl RequestIdStore for KafkaStore { fn add_request_id(&mut self, request_id: String) { self.diesel_store.add_request_id(request_id) } } #[async_trait::async_trait] impl FraudCheckInterface for KafkaStore { async fn insert_fraud_check_response( &self, new: storage::FraudCheckNew, ) -> CustomResult<FraudCheck, StorageError> { let frm = self.diesel_store.insert_fraud_check_response(new).await?; if let Err(er) = self .kafka_producer .log_fraud_check(&frm, None, self.tenant_id.clone()) .await { logger::error!(message = "Failed to log analytics event for fraud check", error_message = ?er); } Ok(frm) } async fn update_fraud_check_response_with_attempt_id( &self, this: FraudCheck, fraud_check: FraudCheckUpdate, ) -> CustomResult<FraudCheck, StorageError> { let frm = self .diesel_store .update_fraud_check_response_with_attempt_id(this, fraud_check) .await?; if let Err(er) = self .kafka_producer .log_fraud_check(&frm, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for fraud check {frm:?}", error_message=?er) } Ok(frm) } async fn find_fraud_check_by_payment_id( &self, payment_id: id_type::PaymentId, merchant_id: id_type::MerchantId, ) -> CustomResult<FraudCheck, StorageError> { let frm = self .diesel_store .find_fraud_check_by_payment_id(payment_id, merchant_id) .await?; if let Err(er) = self .kafka_producer .log_fraud_check(&frm, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for fraud check {frm:?}", error_message=?er) } Ok(frm) } async fn find_fraud_check_by_payment_id_if_present( &self, payment_id: id_type::PaymentId, merchant_id: id_type::MerchantId, ) -> CustomResult<Option<FraudCheck>, StorageError> { let frm = self .diesel_store .find_fraud_check_by_payment_id_if_present(payment_id, merchant_id) .await?; if let Some(fraud_check) = frm.clone() { if let Err(er) = self .kafka_producer .log_fraud_check(&fraud_check, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for frm {frm:?}", error_message=?er); } } Ok(frm) } } #[async_trait::async_trait] impl OrganizationInterface for KafkaStore { async fn insert_organization( &self, organization: OrganizationNew, ) -> CustomResult<Organization, StorageError> { self.diesel_store.insert_organization(organization).await } async fn find_organization_by_org_id( &self, org_id: &id_type::OrganizationId, ) -> CustomResult<Organization, StorageError> { self.diesel_store.find_organization_by_org_id(org_id).await } async fn update_organization_by_org_id( &self, org_id: &id_type::OrganizationId, update: OrganizationUpdate, ) -> CustomResult<Organization, StorageError> { self.diesel_store .update_organization_by_org_id(org_id, update) .await } }
crates/router/src/db.rs
router::src::db
3,072
true
// File: crates/router/src/routes.rs // Module: router::src::routes pub mod admin; pub mod api_keys; pub mod app; #[cfg(feature = "v1")] pub mod apple_pay_certificates_migration; pub mod authentication; #[cfg(all(feature = "olap", feature = "v1"))] pub mod blocklist; pub mod cache; pub mod cards_info; pub mod configs; #[cfg(feature = "olap")] pub mod connector_onboarding; #[cfg(any(feature = "olap", feature = "oltp"))] pub mod currency; pub mod customers; pub mod disputes; #[cfg(feature = "dummy_connector")] pub mod dummy_connector; pub mod ephemeral_key; pub mod feature_matrix; pub mod files; #[cfg(feature = "frm")] pub mod fraud_check; pub mod gsm; pub mod health; pub mod hypersense; pub mod lock_utils; #[cfg(feature = "v1")] pub mod locker_migration; pub mod mandates; pub mod metrics; #[cfg(feature = "v1")] pub mod payment_link; pub mod payment_methods; pub mod payments; #[cfg(feature = "payouts")] pub mod payout_link; #[cfg(feature = "payouts")] pub mod payouts; #[cfg(any(feature = "olap", feature = "oltp"))] pub mod pm_auth; pub mod poll; #[cfg(feature = "olap")] pub mod profile_acquirer; #[cfg(feature = "olap")] pub mod profiles; #[cfg(feature = "recon")] pub mod recon; pub mod refunds; #[cfg(feature = "v2")] pub mod revenue_recovery_data_backfill; #[cfg(feature = "v2")] pub mod revenue_recovery_redis; #[cfg(feature = "olap")] pub mod routing; #[cfg(feature = "v1")] pub mod subscription; pub mod three_ds_decision_rule; pub mod tokenization; #[cfg(feature = "olap")] pub mod user; #[cfg(feature = "olap")] pub mod user_role; #[cfg(feature = "olap")] pub mod verification; #[cfg(feature = "olap")] pub mod verify_connector; #[cfg(all(feature = "olap", feature = "v1"))] pub mod webhook_events; pub mod webhooks; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] pub mod recovery_webhooks; pub mod relay; #[cfg(feature = "olap")] pub mod process_tracker; #[cfg(feature = "v2")] pub mod proxy; pub mod chat; #[cfg(feature = "dummy_connector")] pub use self::app::DummyConnector; #[cfg(feature = "v2")] pub use self::app::PaymentMethodSession; #[cfg(all(feature = "oltp", feature = "v2"))] pub use self::app::Proxy; #[cfg(all(feature = "olap", feature = "recon", feature = "v1"))] pub use self::app::Recon; pub use self::app::{ ApiKeys, AppState, ApplePayCertificatesMigration, Authentication, Cache, Cards, Chat, Configs, ConnectorOnboarding, Customers, Disputes, EphemeralKey, FeatureMatrix, Files, Forex, Gsm, Health, Hypersense, Mandates, MerchantAccount, MerchantConnectorAccount, PaymentLink, PaymentMethods, Payments, Poll, ProcessTracker, ProcessTrackerDeprecated, Profile, ProfileAcquirer, ProfileNew, Refunds, Relay, RelayWebhooks, SessionState, ThreeDsDecisionRule, User, UserDeprecated, Webhooks, }; #[cfg(feature = "olap")] pub use self::app::{Blocklist, Organization, Routing, Subscription, Verify, WebhookEvents}; #[cfg(feature = "payouts")] pub use self::app::{PayoutLink, Payouts}; #[cfg(feature = "v2")] pub use self::app::{RecoveryDataBackfill, Tokenization}; #[cfg(all(feature = "stripe", feature = "v1"))] pub use super::compatibility::stripe::StripeApis; #[cfg(feature = "olap")] pub use crate::analytics::routes::{self as analytics, Analytics};
crates/router/src/routes.rs
router::src::routes
861
true
// File: crates/router/src/middleware.rs // Module: router::src::middleware use common_utils::consts::TENANT_HEADER; use futures::StreamExt; use router_env::{ logger, tracing::{field::Empty, Instrument}, }; use crate::{headers, routes::metrics}; /// Middleware to include request ID in response header. pub struct RequestId; impl<S, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for RequestId where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Transform = RequestIdMiddleware<S>; type InitError = (); type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { std::future::ready(Ok(RequestIdMiddleware { service })) } } pub struct RequestIdMiddleware<S> { service: S, } impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for RequestIdMiddleware<S> where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_web::dev::forward_ready!(service); fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future { let old_x_request_id = req.headers().get("x-request-id").cloned(); let mut req = req; let request_id_fut = req.extract::<router_env::tracing_actix_web::RequestId>(); let response_fut = self.service.call(req); Box::pin( async move { let request_id = request_id_fut.await?; let request_id = request_id.as_hyphenated().to_string(); if let Some(upstream_request_id) = old_x_request_id { router_env::logger::info!(?upstream_request_id); } let mut response = response_fut.await?; response.headers_mut().append( http::header::HeaderName::from_static("x-request-id"), http::HeaderValue::from_str(&request_id)?, ); Ok(response) } .in_current_span(), ) } } /// Middleware for attaching default response headers. Headers with the same key already set in a /// response will not be overwritten. pub fn default_response_headers() -> actix_web::middleware::DefaultHeaders { use actix_web::http::header; let default_headers_middleware = actix_web::middleware::DefaultHeaders::new(); #[cfg(feature = "vergen")] let default_headers_middleware = default_headers_middleware.add(("x-hyperswitch-version", router_env::git_tag!())); default_headers_middleware // Max age of 1 year in seconds, equal to `60 * 60 * 24 * 365` seconds. .add((header::STRICT_TRANSPORT_SECURITY, "max-age=31536000")) .add((header::VIA, "HyperSwitch")) } /// Middleware to build a TOP level domain span for each request. pub struct LogSpanInitializer; impl<S, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for LogSpanInitializer where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Transform = LogSpanInitializerMiddleware<S>; type InitError = (); type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { std::future::ready(Ok(LogSpanInitializerMiddleware { service })) } } pub struct LogSpanInitializerMiddleware<S> { service: S, } impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for LogSpanInitializerMiddleware<S> where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_web::dev::forward_ready!(service); // TODO: have a common source of truth for the list of top level fields // /crates/router_env/src/logger/storage.rs also has a list of fields called PERSISTENT_KEYS fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future { let tenant_id = req .headers() .get(TENANT_HEADER) .and_then(|i| i.to_str().ok()) .map(|s| s.to_owned()); let response_fut = self.service.call(req); let tenant_id_clone = tenant_id.clone(); Box::pin( async move { if let Some(tenant) = tenant_id_clone { router_env::tracing::Span::current().record("tenant_id", tenant); } let response = response_fut.await; router_env::tracing::Span::current().record("golden_log_line", true); response } .instrument( router_env::tracing::info_span!( "ROOT_SPAN", payment_id = Empty, merchant_id = Empty, connector_name = Empty, payment_method = Empty, status_code = Empty, flow = "UNKNOWN", golden_log_line = Empty, tenant_id = &tenant_id ) .or_current(), ), ) } } fn get_request_details_from_value(json_value: &serde_json::Value, parent_key: &str) -> String { match json_value { serde_json::Value::Null => format!("{parent_key}: null"), serde_json::Value::Bool(b) => format!("{parent_key}: {b}"), serde_json::Value::Number(num) => format!("{}: {}", parent_key, num.to_string().len()), serde_json::Value::String(s) => format!("{}: {}", parent_key, s.len()), serde_json::Value::Array(arr) => { let mut result = String::new(); for (index, value) in arr.iter().enumerate() { let child_key = format!("{parent_key}[{index}]"); result.push_str(&get_request_details_from_value(value, &child_key)); if index < arr.len() - 1 { result.push_str(", "); } } result } serde_json::Value::Object(obj) => { let mut result = String::new(); for (index, (key, value)) in obj.iter().enumerate() { let child_key = format!("{parent_key}[{key}]"); result.push_str(&get_request_details_from_value(value, &child_key)); if index < obj.len() - 1 { result.push_str(", "); } } result } } } /// Middleware for Logging request_details of HTTP 400 Bad Requests pub struct Http400RequestDetailsLogger; impl<S: 'static, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for Http400RequestDetailsLogger where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Transform = Http400RequestDetailsLoggerMiddleware<S>; type InitError = (); type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { std::future::ready(Ok(Http400RequestDetailsLoggerMiddleware { service: std::rc::Rc::new(service), })) } } pub struct Http400RequestDetailsLoggerMiddleware<S> { service: std::rc::Rc<S>, } impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for Http400RequestDetailsLoggerMiddleware<S> where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, > + 'static, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_web::dev::forward_ready!(service); fn call(&self, mut req: actix_web::dev::ServiceRequest) -> Self::Future { let svc = self.service.clone(); let request_id_fut = req.extract::<router_env::tracing_actix_web::RequestId>(); Box::pin(async move { let (http_req, payload) = req.into_parts(); let result_payload: Vec<Result<bytes::Bytes, actix_web::error::PayloadError>> = payload.collect().await; let payload = result_payload .into_iter() .collect::<Result<Vec<bytes::Bytes>, actix_web::error::PayloadError>>()?; let bytes = payload.clone().concat().to_vec(); let bytes_length = bytes.len(); // we are creating h1 payload manually from bytes, currently there's no way to create http2 payload with actix let (_, mut new_payload) = actix_http::h1::Payload::create(true); new_payload.unread_data(bytes.to_vec().clone().into()); let new_req = actix_web::dev::ServiceRequest::from_parts(http_req, new_payload.into()); let content_length_header = new_req .headers() .get(headers::CONTENT_LENGTH) .map(ToOwned::to_owned); let response_fut = svc.call(new_req); let response = response_fut.await?; // Log the request_details when we receive 400 status from the application if response.status() == 400 { let request_id = request_id_fut.await?.as_hyphenated().to_string(); let content_length_header_string = content_length_header .map(|content_length_header| { content_length_header.to_str().map(ToOwned::to_owned) }) .transpose() .inspect_err(|error| { logger::warn!("Could not convert content length to string {error:?}"); }) .ok() .flatten(); logger::info!("Content length from header: {content_length_header_string:?}, Bytes length: {bytes_length}"); if !bytes.is_empty() { let value_result: Result<serde_json::Value, serde_json::Error> = serde_json::from_slice(&bytes); match value_result { Ok(value) => { logger::info!( "request_id: {request_id}, request_details: {}", get_request_details_from_value(&value, "") ); } Err(err) => { logger::warn!("error while parsing the request in json value: {err}"); } } } else { logger::info!("request_id: {request_id}, request_details: Empty Body"); } } Ok(response) }) } } /// Middleware for Adding Accept-Language header based on query params pub struct AddAcceptLanguageHeader; impl<S: 'static, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for AddAcceptLanguageHeader where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Transform = AddAcceptLanguageHeaderMiddleware<S>; type InitError = (); type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { std::future::ready(Ok(AddAcceptLanguageHeaderMiddleware { service: std::rc::Rc::new(service), })) } } pub struct AddAcceptLanguageHeaderMiddleware<S> { service: std::rc::Rc<S>, } impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for AddAcceptLanguageHeaderMiddleware<S> where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, > + 'static, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_web::dev::forward_ready!(service); fn call(&self, mut req: actix_web::dev::ServiceRequest) -> Self::Future { let svc = self.service.clone(); Box::pin(async move { #[derive(serde::Deserialize)] struct LocaleQueryParam { locale: Option<String>, } let query_params = req.query_string(); let locale_param = serde_qs::from_str::<LocaleQueryParam>(query_params).map_err(|error| { actix_web::error::ErrorBadRequest(format!( "Could not convert query params to locale query parmas: {error:?}", )) })?; let accept_language_header = req.headers().get(http::header::ACCEPT_LANGUAGE); if let Some(locale) = locale_param.locale { req.headers_mut().insert( http::header::ACCEPT_LANGUAGE, http::HeaderValue::from_str(&locale)?, ); } else if accept_language_header.is_none() { req.headers_mut().insert( http::header::ACCEPT_LANGUAGE, http::HeaderValue::from_static("en"), ); } let response_fut = svc.call(req); let response = response_fut.await?; Ok(response) }) } } /// Middleware for recording request-response metrics pub struct RequestResponseMetrics; impl<S: 'static, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for RequestResponseMetrics where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Transform = RequestResponseMetricsMiddleware<S>; type InitError = (); type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { std::future::ready(Ok(RequestResponseMetricsMiddleware { service: std::rc::Rc::new(service), })) } } pub struct RequestResponseMetricsMiddleware<S> { service: std::rc::Rc<S>, } impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for RequestResponseMetricsMiddleware<S> where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, > + 'static, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_web::dev::forward_ready!(service); fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future { use std::borrow::Cow; let svc = self.service.clone(); let request_path = req .match_pattern() .map(Cow::<'static, str>::from) .unwrap_or_else(|| "UNKNOWN".into()); let request_method = Cow::<'static, str>::from(req.method().as_str().to_owned()); Box::pin(async move { let mut attributes = router_env::metric_attributes!(("path", request_path), ("method", request_method)) .to_vec(); let response_fut = svc.call(req); metrics::REQUESTS_RECEIVED.add(1, &attributes); let (response_result, request_duration) = common_utils::metrics::utils::time_future(response_fut).await; let response = response_result?; attributes.extend_from_slice(router_env::metric_attributes!(( "status_code", i64::from(response.status().as_u16()) ))); metrics::REQUEST_TIME.record(request_duration.as_secs_f64(), &attributes); Ok(response) }) } }
crates/router/src/middleware.rs
router::src::middleware
4,063
true
// File: crates/router/src/analytics.rs // Module: router::src::analytics pub use analytics::*; pub mod routes { use std::{ collections::{HashMap, HashSet}, sync::Arc, }; use actix_web::{web, Responder, Scope}; use analytics::{ api_event::api_events_core, connector_events::connector_events_core, enums::AuthInfo, errors::AnalyticsError, lambda_utils::invoke_lambda, opensearch::OpenSearchError, outgoing_webhook_event::outgoing_webhook_events_core, routing_events::routing_events_core, sdk_events::sdk_events_core, AnalyticsFlow, }; use api_models::analytics::{ api_event::QueryType, search::{ GetGlobalSearchRequest, GetSearchRequest, GetSearchRequestWithIndex, SearchIndex, }, AnalyticsRequest, GenerateReportRequest, GetActivePaymentsMetricRequest, GetApiEventFiltersRequest, GetApiEventMetricRequest, GetAuthEventFilterRequest, GetAuthEventMetricRequest, GetDisputeMetricRequest, GetFrmFilterRequest, GetFrmMetricRequest, GetPaymentFiltersRequest, GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, GetPaymentMetricRequest, GetRefundFilterRequest, GetRefundMetricRequest, GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest, }; use common_enums::EntityType; use common_utils::types::TimeRange; use error_stack::{report, ResultExt}; use futures::{stream::FuturesUnordered, StreamExt}; use crate::{ analytics_validator::request_validator, consts::opensearch::SEARCH_INDEXES, core::{api_locking, errors::user::UserErrors, verification::utils}, db::{user::UserInterface, user_role::ListUserRolesByUserIdPayload}, routes::AppState, services::{ api, authentication::{self as auth, AuthenticationData, UserFromToken}, authorization::{permissions::Permission, roles::RoleInfo}, ApplicationResponse, }, types::{domain::UserEmail, storage::UserRole}, }; pub struct Analytics; impl Analytics { #[cfg(feature = "v2")] pub fn server(state: AppState) -> Scope { web::scope("/analytics").app_data(web::Data::new(state)) } #[cfg(feature = "v1")] pub fn server(state: AppState) -> Scope { web::scope("/analytics") .app_data(web::Data::new(state)) .service( web::scope("/v1") .service( web::resource("metrics/payments") .route(web::post().to(get_merchant_payment_metrics)), ) .service( web::resource("metrics/routing") .route(web::post().to(get_merchant_payment_metrics)), ) .service( web::resource("metrics/refunds") .route(web::post().to(get_merchant_refund_metrics)), ) .service( web::resource("filters/payments") .route(web::post().to(get_merchant_payment_filters)), ) .service( web::resource("filters/routing") .route(web::post().to(get_merchant_payment_filters)), ) .service( web::resource("filters/frm").route(web::post().to(get_frm_filters)), ) .service( web::resource("filters/refunds") .route(web::post().to(get_merchant_refund_filters)), ) .service(web::resource("{domain}/info").route(web::get().to(get_info))) .service( web::resource("report/dispute") .route(web::post().to(generate_merchant_dispute_report)), ) .service( web::resource("report/refunds") .route(web::post().to(generate_merchant_refund_report)), ) .service( web::resource("report/payments") .route(web::post().to(generate_merchant_payment_report)), ) .service( web::resource("report/authentications") .route(web::post().to(generate_merchant_authentication_report)), ) .service( web::resource("metrics/sdk_events") .route(web::post().to(get_sdk_event_metrics)), ) .service( web::resource("metrics/active_payments") .route(web::post().to(get_active_payments_metrics)), ) .service( web::resource("filters/sdk_events") .route(web::post().to(get_sdk_event_filters)), ) .service( web::resource("metrics/auth_events") .route(web::post().to(get_merchant_auth_event_metrics)), ) .service( web::resource("filters/auth_events") .route(web::post().to(get_merchant_auth_events_filters)), ) .service( web::resource("metrics/frm").route(web::post().to(get_frm_metrics)), ) .service( web::resource("api_event_logs") .route(web::get().to(get_profile_api_events)), ) .service( web::resource("sdk_event_logs") .route(web::post().to(get_profile_sdk_events)), ) .service( web::resource("connector_event_logs") .route(web::get().to(get_profile_connector_events)), ) .service( web::resource("routing_event_logs") .route(web::get().to(get_profile_routing_events)), ) .service( web::resource("outgoing_webhook_event_logs") .route(web::get().to(get_profile_outgoing_webhook_events)), ) .service( web::resource("metrics/api_events") .route(web::post().to(get_merchant_api_events_metrics)), ) .service( web::resource("filters/api_events") .route(web::post().to(get_merchant_api_event_filters)), ) .service( web::resource("search") .route(web::post().to(get_global_search_results)), ) .service( web::resource("search/{domain}") .route(web::post().to(get_search_results)), ) .service( web::resource("metrics/disputes") .route(web::post().to(get_merchant_dispute_metrics)), ) .service( web::resource("filters/disputes") .route(web::post().to(get_merchant_dispute_filters)), ) .service( web::resource("metrics/sankey") .route(web::post().to(get_merchant_sankey)), ) .service( web::resource("metrics/auth_events/sankey") .route(web::post().to(get_merchant_auth_event_sankey)), ) .service( web::scope("/merchant") .service( web::resource("metrics/payments") .route(web::post().to(get_merchant_payment_metrics)), ) .service( web::resource("metrics/routing") .route(web::post().to(get_merchant_payment_metrics)), ) .service( web::resource("metrics/refunds") .route(web::post().to(get_merchant_refund_metrics)), ) .service( web::resource("metrics/auth_events") .route(web::post().to(get_merchant_auth_event_metrics)), ) .service( web::resource("filters/payments") .route(web::post().to(get_merchant_payment_filters)), ) .service( web::resource("filters/routing") .route(web::post().to(get_merchant_payment_filters)), ) .service( web::resource("filters/refunds") .route(web::post().to(get_merchant_refund_filters)), ) .service( web::resource("filters/auth_events") .route(web::post().to(get_merchant_auth_events_filters)), ) .service( web::resource("{domain}/info").route(web::get().to(get_info)), ) .service( web::resource("report/dispute") .route(web::post().to(generate_merchant_dispute_report)), ) .service( web::resource("report/refunds") .route(web::post().to(generate_merchant_refund_report)), ) .service( web::resource("report/payments") .route(web::post().to(generate_merchant_payment_report)), ) .service( web::resource("report/authentications").route( web::post().to(generate_merchant_authentication_report), ), ) .service( web::resource("metrics/api_events") .route(web::post().to(get_merchant_api_events_metrics)), ) .service( web::resource("filters/api_events") .route(web::post().to(get_merchant_api_event_filters)), ) .service( web::resource("metrics/disputes") .route(web::post().to(get_merchant_dispute_metrics)), ) .service( web::resource("filters/disputes") .route(web::post().to(get_merchant_dispute_filters)), ) .service( web::resource("metrics/sankey") .route(web::post().to(get_merchant_sankey)), ) .service( web::resource("metrics/auth_events/sankey") .route(web::post().to(get_merchant_auth_event_sankey)), ), ) .service( web::scope("/org") .service( web::resource("{domain}/info").route(web::get().to(get_info)), ) .service( web::resource("metrics/payments") .route(web::post().to(get_org_payment_metrics)), ) .service( web::resource("filters/payments") .route(web::post().to(get_org_payment_filters)), ) .service( web::resource("metrics/routing") .route(web::post().to(get_org_payment_metrics)), ) .service( web::resource("filters/routing") .route(web::post().to(get_org_payment_filters)), ) .service( web::resource("metrics/refunds") .route(web::post().to(get_org_refund_metrics)), ) .service( web::resource("filters/refunds") .route(web::post().to(get_org_refund_filters)), ) .service( web::resource("metrics/disputes") .route(web::post().to(get_org_dispute_metrics)), ) .service( web::resource("metrics/auth_events") .route(web::post().to(get_org_auth_event_metrics)), ) .service( web::resource("filters/disputes") .route(web::post().to(get_org_dispute_filters)), ) .service( web::resource("filters/auth_events") .route(web::post().to(get_org_auth_events_filters)), ) .service( web::resource("report/dispute") .route(web::post().to(generate_org_dispute_report)), ) .service( web::resource("report/refunds") .route(web::post().to(generate_org_refund_report)), ) .service( web::resource("report/payments") .route(web::post().to(generate_org_payment_report)), ) .service( web::resource("report/authentications") .route(web::post().to(generate_org_authentication_report)), ) .service( web::resource("metrics/sankey") .route(web::post().to(get_org_sankey)), ) .service( web::resource("metrics/auth_events/sankey") .route(web::post().to(get_org_auth_event_sankey)), ), ) .service( web::scope("/profile") .service( web::resource("{domain}/info").route(web::get().to(get_info)), ) .service( web::resource("metrics/payments") .route(web::post().to(get_profile_payment_metrics)), ) .service( web::resource("filters/payments") .route(web::post().to(get_profile_payment_filters)), ) .service( web::resource("metrics/routing") .route(web::post().to(get_profile_payment_metrics)), ) .service( web::resource("filters/routing") .route(web::post().to(get_profile_payment_filters)), ) .service( web::resource("metrics/refunds") .route(web::post().to(get_profile_refund_metrics)), ) .service( web::resource("filters/refunds") .route(web::post().to(get_profile_refund_filters)), ) .service( web::resource("metrics/disputes") .route(web::post().to(get_profile_dispute_metrics)), ) .service( web::resource("metrics/auth_events") .route(web::post().to(get_profile_auth_event_metrics)), ) .service( web::resource("filters/disputes") .route(web::post().to(get_profile_dispute_filters)), ) .service( web::resource("filters/auth_events") .route(web::post().to(get_profile_auth_events_filters)), ) .service( web::resource("connector_event_logs") .route(web::get().to(get_profile_connector_events)), ) .service( web::resource("routing_event_logs") .route(web::get().to(get_profile_routing_events)), ) .service( web::resource("outgoing_webhook_event_logs") .route(web::get().to(get_profile_outgoing_webhook_events)), ) .service( web::resource("report/dispute") .route(web::post().to(generate_profile_dispute_report)), ) .service( web::resource("report/refunds") .route(web::post().to(generate_profile_refund_report)), ) .service( web::resource("report/payments") .route(web::post().to(generate_profile_payment_report)), ) .service( web::resource("report/authentications").route( web::post().to(generate_profile_authentication_report), ), ) .service( web::resource("api_event_logs") .route(web::get().to(get_profile_api_events)), ) .service( web::resource("sdk_event_logs") .route(web::post().to(get_profile_sdk_events)), ) .service( web::resource("metrics/sankey") .route(web::post().to(get_profile_sankey)), ) .service( web::resource("metrics/auth_events/sankey") .route(web::post().to(get_profile_auth_event_sankey)), ), ), ) .service( web::scope("/v2") .service( web::resource("/metrics/payments") .route(web::post().to(get_merchant_payment_intent_metrics)), ) .service( web::resource("/filters/payments") .route(web::post().to(get_payment_intents_filters)), ) .service( web::scope("/merchant") .service( web::resource("/metrics/payments") .route(web::post().to(get_merchant_payment_intent_metrics)), ) .service( web::resource("/filters/payments") .route(web::post().to(get_payment_intents_filters)), ), ) .service( web::scope("/org").service( web::resource("/metrics/payments") .route(web::post().to(get_org_payment_intent_metrics)), ), ) .service( web::scope("/profile").service( web::resource("/metrics/payments") .route(web::post().to(get_profile_payment_intent_metrics)), ), ), ) } } pub async fn get_info( state: web::Data<AppState>, req: actix_web::HttpRequest, domain: web::Path<analytics::AnalyticsDomain>, ) -> impl Responder { let flow = AnalyticsFlow::GetInfo; Box::pin(api::server_wrap( flow, state, &req, domain.into_inner(), |_, _: (), domain: analytics::AnalyticsDomain, _| async { analytics::core::get_domain_info(domain) .await .map(ApplicationResponse::Json) }, &auth::NoAuth, api_locking::LockAction::NotApplicable, )) .await } /// # Panics /// /// Panics if `json_payload` array does not contain one `GetPaymentMetricRequest` element. pub async fn get_merchant_payment_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetPaymentMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetPaymentMetricRequest"); let flow = AnalyticsFlow::GetPaymentMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let auth: AuthInfo = AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; let validator_response = request_validator( AnalyticsRequest { payment_attempt: Some(req.clone()), ..Default::default() }, &state, ) .await?; let ex_rates = validator_response; analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// # Panics /// /// Panics if `json_payload` array does not contain one `GetPaymentMetricRequest` element. pub async fn get_org_payment_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetPaymentMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetPaymentMetricRequest"); let flow = AnalyticsFlow::GetPaymentMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; let validator_response = request_validator( AnalyticsRequest { payment_attempt: Some(req.clone()), ..Default::default() }, &state, ) .await?; let ex_rates = validator_response; analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: false, organization_id: None, }, &auth::JWTAuth { permission: Permission::OrganizationAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// # Panics /// /// Panics if `json_payload` array does not contain one `GetPaymentMetricRequest` element. pub async fn get_profile_payment_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetPaymentMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetPaymentMetricRequest"); let flow = AnalyticsFlow::GetPaymentMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let auth: AuthInfo = AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; let validator_response = request_validator( AnalyticsRequest { payment_attempt: Some(req.clone()), ..Default::default() }, &state, ) .await?; let ex_rates = validator_response; analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } /// # Panics /// /// Panics if `json_payload` array does not contain one `GetPaymentIntentMetricRequest` element. pub async fn get_merchant_payment_intent_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetPaymentIntentMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetPaymentIntentMetricRequest"); let flow = AnalyticsFlow::GetPaymentIntentMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let auth: AuthInfo = AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; let validator_response = request_validator( AnalyticsRequest { payment_intent: Some(req.clone()), ..Default::default() }, &state, ) .await?; let ex_rates = validator_response; analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// # Panics /// /// Panics if `json_payload` array does not contain one `GetPaymentIntentMetricRequest` element. pub async fn get_org_payment_intent_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetPaymentIntentMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetPaymentIntentMetricRequest"); let flow = AnalyticsFlow::GetPaymentIntentMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; let validator_response = request_validator( AnalyticsRequest { payment_intent: Some(req.clone()), ..Default::default() }, &state, ) .await?; let ex_rates = validator_response; analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: false, organization_id: None, }, &auth::JWTAuth { permission: Permission::OrganizationAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// # Panics /// /// Panics if `json_payload` array does not contain one `GetPaymentIntentMetricRequest` element. pub async fn get_profile_payment_intent_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetPaymentIntentMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetPaymentIntentMetricRequest"); let flow = AnalyticsFlow::GetPaymentIntentMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let auth: AuthInfo = AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; let validator_response = request_validator( AnalyticsRequest { payment_intent: Some(req.clone()), ..Default::default() }, &state, ) .await?; let ex_rates = validator_response; analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } /// # Panics /// /// Panics if `json_payload` array does not contain one `GetRefundMetricRequest` element. pub async fn get_merchant_refund_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetRefundMetricRequest; 1]>, ) -> impl Responder { #[allow(clippy::expect_used)] // safety: This shouldn't panic owing to the data type let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetRefundMetricRequest"); let flow = AnalyticsFlow::GetRefundsMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let auth: AuthInfo = AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; let validator_response = request_validator( AnalyticsRequest { refund: Some(req.clone()), ..Default::default() }, &state, ) .await?; let ex_rates = validator_response; analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// # Panics /// /// Panics if `json_payload` array does not contain one `GetRefundMetricRequest` element. pub async fn get_org_refund_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetRefundMetricRequest; 1]>, ) -> impl Responder { #[allow(clippy::expect_used)] // safety: This shouldn't panic owing to the data type let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetRefundMetricRequest"); let flow = AnalyticsFlow::GetRefundsMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; let validator_response = request_validator( AnalyticsRequest { refund: Some(req.clone()), ..Default::default() }, &state, ) .await?; let ex_rates = validator_response; analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: false, organization_id: None, }, &auth::JWTAuth { permission: Permission::OrganizationAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// # Panics /// /// Panics if `json_payload` array does not contain one `GetRefundMetricRequest` element. pub async fn get_profile_refund_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetRefundMetricRequest; 1]>, ) -> impl Responder { #[allow(clippy::expect_used)] // safety: This shouldn't panic owing to the data type let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetRefundMetricRequest"); let flow = AnalyticsFlow::GetRefundsMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let auth: AuthInfo = AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; let validator_response = request_validator( AnalyticsRequest { refund: Some(req.clone()), ..Default::default() }, &state, ) .await?; let ex_rates = validator_response; analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } /// # Panics /// /// Panics if `json_payload` array does not contain one `GetFrmMetricRequest` element. pub async fn get_frm_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetFrmMetricRequest; 1]>, ) -> impl Responder { #[allow(clippy::expect_used)] // safety: This shouldn't panic owing to the data type let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetFrmMetricRequest"); let flow = AnalyticsFlow::GetFrmMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { analytics::frm::get_metrics(&state.pool, auth.merchant_account.get_id(), req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// # Panics /// /// Panics if `json_payload` array does not contain one `GetSdkEventMetricRequest` element. pub async fn get_sdk_event_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetSdkEventMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetSdkEventMetricRequest"); let flow = AnalyticsFlow::GetSdkMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { analytics::sdk_events::get_metrics( &state.pool, &auth.merchant_account.publishable_key, req, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// # Panics /// /// Panics if `json_payload` array does not contain one `GetActivePaymentsMetricRequest` element. pub async fn get_active_payments_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetActivePaymentsMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetActivePaymentsMetricRequest"); let flow = AnalyticsFlow::GetActivePaymentsMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { analytics::active_payments::get_metrics( &state.pool, &auth.merchant_account.publishable_key, auth.merchant_account.get_id(), req, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// # Panics /// /// Panics if `json_payload` array does not contain one `GetAuthEventMetricRequest` element. pub async fn get_merchant_auth_event_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetAuthEventMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetAuthEventMetricRequest"); let flow = AnalyticsFlow::GetAuthMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let auth: AuthInfo = AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; analytics::auth_events::get_metrics(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// # Panics /// /// Panics if `json_payload` array does not contain one `GetAuthEventMetricRequest` element. pub async fn get_profile_auth_event_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetAuthEventMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetAuthEventMetricRequest"); let flow = AnalyticsFlow::GetAuthMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let auth: AuthInfo = AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; analytics::auth_events::get_metrics(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// # Panics /// /// Panics if `json_payload` array does not contain one `GetAuthEventMetricRequest` element. pub async fn get_org_auth_event_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetAuthEventMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetAuthEventMetricRequest"); let flow = AnalyticsFlow::GetAuthMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; analytics::auth_events::get_metrics(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: false, organization_id: None, }, &auth::JWTAuth { permission: Permission::OrganizationAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } pub async fn get_merchant_payment_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetPaymentFiltersRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetPaymentFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let auth: AuthInfo = AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; analytics::payments::get_filters(&state.pool, req, &auth) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_merchant_auth_events_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetAuthEventFilterRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetAuthEventFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let auth: AuthInfo = AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; analytics::auth_events::get_filters(&state.pool, req, &auth) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_org_auth_events_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetAuthEventFilterRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetAuthEventFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; analytics::auth_events::get_filters(&state.pool, req, &auth) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: false, organization_id: None, }, &auth::JWTAuth { permission: Permission::OrganizationAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_profile_auth_events_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetAuthEventFilterRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetAuthEventFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let auth: AuthInfo = AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; analytics::auth_events::get_filters(&state.pool, req, &auth) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_org_payment_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetPaymentFiltersRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetPaymentFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; analytics::payments::get_filters(&state.pool, req, &auth) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: false, organization_id: None, }, &auth::JWTAuth { permission: Permission::OrganizationAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_profile_payment_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetPaymentFiltersRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetPaymentFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let auth: AuthInfo = AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; analytics::payments::get_filters(&state.pool, req, &auth) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_payment_intents_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetPaymentIntentFiltersRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetPaymentIntentFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { analytics::payment_intents::get_filters( &state.pool, req, auth.merchant_account.get_id(), ) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: false, organization_id: None, }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } pub async fn get_merchant_refund_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetRefundFilterRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetRefundFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req: GetRefundFilterRequest, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let auth: AuthInfo = AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; analytics::refunds::get_filters(&state.pool, req, &auth) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_org_refund_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetRefundFilterRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetRefundFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req: GetRefundFilterRequest, _| async move { let org_id = auth.merchant_account.get_org_id(); let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; analytics::refunds::get_filters(&state.pool, req, &auth) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: false, organization_id: None, }, &auth::JWTAuth { permission: Permission::OrganizationAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_profile_refund_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetRefundFilterRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetRefundFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req: GetRefundFilterRequest, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let auth: AuthInfo = AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; analytics::refunds::get_filters(&state.pool, req, &auth) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_frm_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetFrmFilterRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetFrmFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req: GetFrmFilterRequest, _| async move { analytics::frm::get_filters(&state.pool, req, auth.merchant_account.get_id()) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_sdk_event_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetSdkEventFiltersRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetSdkEventFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { analytics::sdk_events::get_filters( &state.pool, req, &auth.merchant_account.publishable_key, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_profile_api_events( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Query<api_models::analytics::api_event::ApiLogsRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetApiEvents; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { let payment_id = match req.query_param.clone() { QueryType::Payment { payment_id } => payment_id, QueryType::Refund { payment_id, .. } => payment_id, QueryType::Dispute { payment_id, .. } => payment_id, }; utils::check_if_profile_id_is_present_in_payment_intent(payment_id, &state, &auth) .await .change_context(AnalyticsError::AccessForbiddenError)?; api_events_core(&state.pool, req, auth.merchant_account.get_id()) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_profile_outgoing_webhook_events( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Query< api_models::analytics::outgoing_webhook_event::OutgoingWebhookLogsRequest, >, ) -> impl Responder { let flow = AnalyticsFlow::GetOutgoingWebhookEvents; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { utils::check_if_profile_id_is_present_in_payment_intent( req.payment_id.clone(), &state, &auth, ) .await .change_context(AnalyticsError::AccessForbiddenError)?; outgoing_webhook_events_core(&state.pool, req, auth.merchant_account.get_id()) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_profile_sdk_events( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<api_models::analytics::sdk_events::SdkEventsRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetSdkEvents; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { utils::check_if_profile_id_is_present_in_payment_intent( req.payment_id.clone(), &state, &auth, ) .await .change_context(AnalyticsError::AccessForbiddenError)?; sdk_events_core(&state.pool, req, &auth.merchant_account.publishable_key) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .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 = UserInterface::find_user_by_id(&*state.global_store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; let user_email = UserEmail::from_pii_email(user.email) .change_context(AnalyticsError::UnknownError)? .get_secret(); let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let lambda_req = GenerateReportRequest { request: payload, merchant_id: Some(merchant_id.clone()), auth: AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }, email: user_email, }; let json_bytes = serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; invoke_lambda( &state.conf.report_download_config.refund_function, &state.conf.report_download_config.region, &json_bytes, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantReportRead, }, 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 = UserInterface::find_user_by_id(&*state.global_store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; let user_email = UserEmail::from_pii_email(user.email) .change_context(AnalyticsError::UnknownError)? .get_secret(); let org_id = auth.merchant_account.get_org_id(); let lambda_req = GenerateReportRequest { request: payload, merchant_id: None, auth: AuthInfo::OrgLevel { org_id: org_id.clone(), }, email: user_email, }; let json_bytes = serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; invoke_lambda( &state.conf.report_download_config.refund_function, &state.conf.report_download_config.region, &json_bytes, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::OrganizationReportRead, }, 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 = UserInterface::find_user_by_id(&*state.global_store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; let user_email = UserEmail::from_pii_email(user.email) .change_context(AnalyticsError::UnknownError)? .get_secret(); let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let lambda_req = GenerateReportRequest { request: payload, merchant_id: Some(merchant_id.clone()), auth: AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }, email: user_email, }; let json_bytes = serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; invoke_lambda( &state.conf.report_download_config.refund_function, &state.conf.report_download_config.region, &json_bytes, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileReportRead, }, 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 = UserInterface::find_user_by_id(&*state.global_store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; let user_email = UserEmail::from_pii_email(user.email) .change_context(AnalyticsError::UnknownError)? .get_secret(); let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let lambda_req = GenerateReportRequest { request: payload, merchant_id: Some(merchant_id.clone()), auth: AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }, email: user_email, }; let json_bytes = serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; invoke_lambda( &state.conf.report_download_config.dispute_function, &state.conf.report_download_config.region, &json_bytes, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantReportRead, }, 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 = UserInterface::find_user_by_id(&*state.global_store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; let user_email = UserEmail::from_pii_email(user.email) .change_context(AnalyticsError::UnknownError)? .get_secret(); let org_id = auth.merchant_account.get_org_id(); let lambda_req = GenerateReportRequest { request: payload, merchant_id: None, auth: AuthInfo::OrgLevel { org_id: org_id.clone(), }, email: user_email, }; let json_bytes = serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; invoke_lambda( &state.conf.report_download_config.dispute_function, &state.conf.report_download_config.region, &json_bytes, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::OrganizationReportRead, }, 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 = UserInterface::find_user_by_id(&*state.global_store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; let user_email = UserEmail::from_pii_email(user.email) .change_context(AnalyticsError::UnknownError)? .get_secret(); let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let lambda_req = GenerateReportRequest { request: payload, merchant_id: Some(merchant_id.clone()), auth: AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }, email: user_email, }; let json_bytes = serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; invoke_lambda( &state.conf.report_download_config.dispute_function, &state.conf.report_download_config.region, &json_bytes, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileReportRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] 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 = UserInterface::find_user_by_id(&*state.global_store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; let user_email = UserEmail::from_pii_email(user.email) .change_context(AnalyticsError::UnknownError)? .get_secret(); let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let lambda_req = GenerateReportRequest { request: payload, merchant_id: Some(merchant_id.clone()), auth: AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }, email: user_email, }; let json_bytes = serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; invoke_lambda( &state.conf.report_download_config.payment_function, &state.conf.report_download_config.region, &json_bytes, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantReportRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] 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 = UserInterface::find_user_by_id(&*state.global_store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; let user_email = UserEmail::from_pii_email(user.email) .change_context(AnalyticsError::UnknownError)? .get_secret(); let org_id = auth.merchant_account.get_org_id(); let lambda_req = GenerateReportRequest { request: payload, merchant_id: None, auth: AuthInfo::OrgLevel { org_id: org_id.clone(), }, email: user_email, }; let json_bytes = serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; invoke_lambda( &state.conf.report_download_config.payment_function, &state.conf.report_download_config.region, &json_bytes, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::OrganizationReportRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] 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 = UserInterface::find_user_by_id(&*state.global_store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; let user_email = UserEmail::from_pii_email(user.email) .change_context(AnalyticsError::UnknownError)? .get_secret(); let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let lambda_req = GenerateReportRequest { request: payload, merchant_id: Some(merchant_id.clone()), auth: AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }, email: user_email, }; let json_bytes = serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; invoke_lambda( &state.conf.report_download_config.payment_function, &state.conf.report_download_config.region, &json_bytes, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileReportRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn generate_merchant_authentication_report( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<ReportRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GenerateAuthenticationReport; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; let user_email = UserEmail::from_pii_email(user.email) .change_context(AnalyticsError::UnknownError)? .get_secret(); let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let lambda_req = GenerateReportRequest { request: payload, merchant_id: Some(merchant_id.clone()), auth: AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }, email: user_email, }; 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) }, &auth::JWTAuth { permission: Permission::MerchantReportRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn generate_org_authentication_report( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<ReportRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GenerateAuthenticationReport; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; let user_email = UserEmail::from_pii_email(user.email) .change_context(AnalyticsError::UnknownError)? .get_secret(); let org_id = auth.merchant_account.get_org_id(); let lambda_req = GenerateReportRequest { request: payload, merchant_id: None, auth: AuthInfo::OrgLevel { org_id: org_id.clone(), }, email: user_email, }; 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) }, &auth::JWTAuth { permission: Permission::OrganizationReportRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn generate_profile_authentication_report( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<ReportRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GenerateAuthenticationReport; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) .await .change_context(AnalyticsError::UnknownError)?; let user_email = UserEmail::from_pii_email(user.email) .change_context(AnalyticsError::UnknownError)? .get_secret(); let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let lambda_req = GenerateReportRequest { request: payload, merchant_id: Some(merchant_id.clone()), auth: AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }, email: user_email, }; 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) }, &auth::JWTAuth { permission: Permission::ProfileReportRead, }, api_locking::LockAction::NotApplicable, )) .await } /// # Panics /// /// Panics if `json_payload` array does not contain one `GetApiEventMetricRequest` element. pub async fn get_merchant_api_events_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetApiEventMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetApiEventMetricRequest"); let flow = AnalyticsFlow::GetApiEventMetrics; Box::pin(api::server_wrap( flow, state.clone(), &req, payload, |state, auth: AuthenticationData, req, _| async move { analytics::api_event::get_api_event_metrics( &state.pool, auth.merchant_account.get_id(), req, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_merchant_api_event_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetApiEventFiltersRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetApiEventFilters; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { analytics::api_event::get_filters(&state.pool, req, auth.merchant_account.get_id()) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_profile_connector_events( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Query<api_models::analytics::connector_events::ConnectorEventsRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetConnectorEvents; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { utils::check_if_profile_id_is_present_in_payment_intent( req.payment_id.clone(), &state, &auth, ) .await .change_context(AnalyticsError::AccessForbiddenError)?; connector_events_core(&state.pool, req, auth.merchant_account.get_id()) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_profile_routing_events( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Query<api_models::analytics::routing_events::RoutingEventsRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetRoutingEvents; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { utils::check_if_profile_id_is_present_in_payment_intent( req.payment_id.clone(), &state, &auth, ) .await .change_context(AnalyticsError::AccessForbiddenError)?; routing_events_core(&state.pool, req, auth.merchant_account.get_id()) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } pub async fn get_global_search_results( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetGlobalSearchRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetGlobalSearchResults; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, auth: UserFromToken, req, _| async move { let role_id = auth.role_id; let role_info = RoleInfo::from_role_id_org_id_tenant_id( &state, &role_id, &auth.org_id, auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError)?; let permission_groups = role_info.get_permission_groups(); if !permission_groups.contains(&common_enums::PermissionGroup::OperationsView) { return Err(OpenSearchError::AccessForbiddenError)?; } let user_roles: HashSet<UserRole> = match role_info.get_entity_type() { EntityType::Tenant => state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &auth.user_id, tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: None, limit: None, }) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError)? .into_iter() .collect(), EntityType::Organization | EntityType::Merchant | EntityType::Profile => state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &auth.user_id, tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), org_id: Some(&auth.org_id), merchant_id: None, profile_id: None, entity_id: None, version: None, status: None, limit: None, }) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError)? .into_iter() .collect(), }; let state = Arc::new(state); let role_info_map: HashMap<String, RoleInfo> = user_roles .iter() .map(|user_role| { let state = Arc::clone(&state); let role_id = user_role.role_id.clone(); let org_id = user_role.org_id.clone().unwrap_or_default(); let tenant_id = &user_role.tenant_id; async move { RoleInfo::from_role_id_org_id_tenant_id( &state, &role_id, &org_id, tenant_id, ) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError) .map(|role_info| (role_id, role_info)) } }) .collect::<FuturesUnordered<_>>() .collect::<Vec<_>>() .await .into_iter() .collect::<Result<HashMap<_, _>, _>>()?; let filtered_user_roles: Vec<&UserRole> = user_roles .iter() .filter(|user_role| { let user_role_id = &user_role.role_id; if let Some(role_info) = role_info_map.get(user_role_id) { let permissions = role_info.get_permission_groups(); permissions.contains(&common_enums::PermissionGroup::OperationsView) } else { false } }) .collect(); let search_params: Vec<AuthInfo> = filtered_user_roles .iter() .filter_map(|user_role| { user_role .get_entity_id_and_type() .and_then(|(_, entity_type)| match entity_type { EntityType::Profile => Some(AuthInfo::ProfileLevel { org_id: user_role.org_id.clone()?, merchant_id: user_role.merchant_id.clone()?, profile_ids: vec![user_role.profile_id.clone()?], }), EntityType::Merchant => Some(AuthInfo::MerchantLevel { org_id: user_role.org_id.clone()?, merchant_ids: vec![user_role.merchant_id.clone()?], }), EntityType::Organization => Some(AuthInfo::OrgLevel { org_id: user_role.org_id.clone()?, }), EntityType::Tenant => Some(AuthInfo::OrgLevel { org_id: auth.org_id.clone(), }), }) }) .collect(); analytics::search::msearch_results( state .opensearch_client .as_ref() .ok_or_else(|| error_stack::report!(OpenSearchError::NotEnabled))?, req, search_params, SEARCH_INDEXES.to_vec(), ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_search_results( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetSearchRequest>, index: web::Path<SearchIndex>, ) -> impl Responder { let index = index.into_inner(); let flow = AnalyticsFlow::GetSearchResults; let indexed_req = GetSearchRequestWithIndex { search_req: json_payload.into_inner(), index, }; Box::pin(api::server_wrap( flow, state.clone(), &req, indexed_req, |state, auth: UserFromToken, req, _| async move { let role_id = auth.role_id; let role_info = RoleInfo::from_role_id_org_id_tenant_id( &state, &role_id, &auth.org_id, auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError)?; let permission_groups = role_info.get_permission_groups(); if !permission_groups.contains(&common_enums::PermissionGroup::OperationsView) { return Err(OpenSearchError::AccessForbiddenError)?; } let user_roles: HashSet<UserRole> = match role_info.get_entity_type() { EntityType::Tenant => state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &auth.user_id, tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: None, limit: None, }) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError)? .into_iter() .collect(), EntityType::Organization | EntityType::Merchant | EntityType::Profile => state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &auth.user_id, tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), org_id: Some(&auth.org_id), merchant_id: None, profile_id: None, entity_id: None, version: None, status: None, limit: None, }) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError)? .into_iter() .collect(), }; let state = Arc::new(state); let role_info_map: HashMap<String, RoleInfo> = user_roles .iter() .map(|user_role| { let state = Arc::clone(&state); let role_id = user_role.role_id.clone(); let org_id = user_role.org_id.clone().unwrap_or_default(); let tenant_id = &user_role.tenant_id; async move { RoleInfo::from_role_id_org_id_tenant_id( &state, &role_id, &org_id, tenant_id, ) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError) .map(|role_info| (role_id, role_info)) } }) .collect::<FuturesUnordered<_>>() .collect::<Vec<_>>() .await .into_iter() .collect::<Result<HashMap<_, _>, _>>()?; let filtered_user_roles: Vec<&UserRole> = user_roles .iter() .filter(|user_role| { let user_role_id = &user_role.role_id; if let Some(role_info) = role_info_map.get(user_role_id) { let permissions = role_info.get_permission_groups(); permissions.contains(&common_enums::PermissionGroup::OperationsView) } else { false } }) .collect(); let search_params: Vec<AuthInfo> = filtered_user_roles .iter() .filter_map(|user_role| { user_role .get_entity_id_and_type() .and_then(|(_, entity_type)| match entity_type { EntityType::Profile => Some(AuthInfo::ProfileLevel { org_id: user_role.org_id.clone()?, merchant_id: user_role.merchant_id.clone()?, profile_ids: vec![user_role.profile_id.clone()?], }), EntityType::Merchant => Some(AuthInfo::MerchantLevel { org_id: user_role.org_id.clone()?, merchant_ids: vec![user_role.merchant_id.clone()?], }), EntityType::Organization => Some(AuthInfo::OrgLevel { org_id: user_role.org_id.clone()?, }), EntityType::Tenant => Some(AuthInfo::OrgLevel { org_id: auth.org_id.clone(), }), }) }) .collect(); analytics::search::search_results( state .opensearch_client .as_ref() .ok_or_else(|| error_stack::report!(OpenSearchError::NotEnabled))?, req, search_params, ) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_merchant_dispute_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<api_models::analytics::GetDisputeFilterRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetDisputeFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let auth: AuthInfo = AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; analytics::disputes::get_filters(&state.pool, req, &auth) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_profile_dispute_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<api_models::analytics::GetDisputeFilterRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetDisputeFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let auth: AuthInfo = AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; analytics::disputes::get_filters(&state.pool, req, &auth) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_org_dispute_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<api_models::analytics::GetDisputeFilterRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetDisputeFilters; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; analytics::disputes::get_filters(&state.pool, req, &auth) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: false, organization_id: None, }, &auth::JWTAuth { permission: Permission::OrganizationAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// # Panics /// /// Panics if `json_payload` array does not contain one `GetDisputeMetricRequest` element. pub async fn get_merchant_dispute_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetDisputeMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetDisputeMetricRequest"); let flow = AnalyticsFlow::GetDisputeMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let auth: AuthInfo = AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; analytics::disputes::get_metrics(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// # Panics /// /// Panics if `json_payload` array does not contain one `GetDisputeMetricRequest` element. pub async fn get_profile_dispute_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetDisputeMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetDisputeMetricRequest"); let flow = AnalyticsFlow::GetDisputeMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let auth: AuthInfo = AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; analytics::disputes::get_metrics(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// # Panics /// /// Panics if `json_payload` array does not contain one `GetDisputeMetricRequest` element. pub async fn get_org_dispute_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetDisputeMetricRequest; 1]>, ) -> impl Responder { // safety: This shouldn't panic owing to the data type #[allow(clippy::expect_used)] let payload = json_payload .into_inner() .to_vec() .pop() .expect("Couldn't get GetDisputeMetricRequest"); let flow = AnalyticsFlow::GetDisputeMetrics; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; analytics::disputes::get_metrics(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: false, organization_id: None, }, &auth::JWTAuth { permission: Permission::OrganizationAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } pub async fn get_merchant_sankey( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<TimeRange>, ) -> impl Responder { let flow = AnalyticsFlow::GetSankey; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let auth: AuthInfo = AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; analytics::payment_intents::get_sankey(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_merchant_auth_event_sankey( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<TimeRange>, ) -> impl Responder { let flow = AnalyticsFlow::GetSankey; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let auth: AuthInfo = AuthInfo::MerchantLevel { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; analytics::auth_events::get_sankey(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_org_auth_event_sankey( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<TimeRange>, ) -> impl Responder { let flow = AnalyticsFlow::GetSankey; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; analytics::auth_events::get_sankey(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: false, organization_id: None, }, &auth::JWTAuth { permission: Permission::OrganizationAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_profile_auth_event_sankey( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<TimeRange>, ) -> impl Responder { let flow = AnalyticsFlow::GetSankey; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let auth: AuthInfo = AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; analytics::auth_events::get_sankey(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_org_sankey( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<TimeRange>, ) -> impl Responder { let flow = AnalyticsFlow::GetSankey; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; analytics::payment_intents::get_sankey(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: false, organization_id: None, }, &auth::JWTAuth { permission: Permission::OrganizationAnalyticsRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_profile_sankey( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<TimeRange>, ) -> impl Responder { let flow = AnalyticsFlow::GetSankey; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state: crate::routes::SessionState, auth: AuthenticationData, req, _| async move { let org_id = auth.merchant_account.get_org_id(); let merchant_id = auth.merchant_account.get_id(); let profile_id = auth .profile_id .ok_or(report!(UserErrors::JwtProfileIdMissing)) .change_context(AnalyticsError::AccessForbiddenError)?; let auth: AuthInfo = AuthInfo::ProfileLevel { org_id: org_id.clone(), merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; analytics::payment_intents::get_sankey(&state.pool, &auth, req) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await } }
crates/router/src/analytics.rs
router::src::analytics
23,756
true
// File: crates/router/src/analytics_validator.rs // Module: router::src::analytics_validator use analytics::errors::AnalyticsError; use api_models::analytics::AnalyticsRequest; use common_utils::errors::CustomResult; use currency_conversion::types::ExchangeRates; use router_env::logger; use crate::core::currency::get_forex_exchange_rates; pub async fn request_validator( req_type: AnalyticsRequest, state: &crate::routes::SessionState, ) -> CustomResult<Option<ExchangeRates>, AnalyticsError> { let forex_enabled = state.conf.analytics.get_inner().get_forex_enabled(); let require_forex_functionality = req_type.requires_forex_functionality(); let ex_rates = if forex_enabled && require_forex_functionality { logger::info!("Fetching forex exchange rates"); Some(get_forex_exchange_rates(state.clone()).await?) } else { None }; Ok(ex_rates) }
crates/router/src/analytics_validator.rs
router::src::analytics_validator
196
true
// File: crates/router/src/macros.rs // Module: router::src::macros pub use common_utils::newtype; #[macro_export] macro_rules! get_payment_link_config_value_based_on_priority { ($config:expr, $business_config:expr, $field:ident, $default:expr) => { $config .as_ref() .and_then(|pc_config| pc_config.theme_config.$field.clone()) .or_else(|| { $business_config .as_ref() .and_then(|business_config| business_config.$field.clone()) }) .unwrap_or($default) }; } #[macro_export] macro_rules! get_payment_link_config_value { ($config:expr, $business_config:expr, $(($field:ident, $default:expr)),*) => { ( $(get_payment_link_config_value_based_on_priority!($config, $business_config, $field, $default)),* ) }; ($config:expr, $business_config:expr, $(($field:ident)),*) => { ( $( $config .as_ref() .and_then(|pc_config| pc_config.theme_config.$field.clone()) .or_else(|| { $business_config .as_ref() .and_then(|business_config| business_config.$field.clone()) }) ),* ) }; ($config:expr, $business_config:expr, $(($field:ident $(, $transform:expr)?)),* $(,)?) => { ( $( $config .as_ref() .and_then(|pc_config| pc_config.theme_config.$field.clone()) .or_else(|| { $business_config .as_ref() .and_then(|business_config| { let value = business_config.$field.clone(); $(let value = value.map($transform);)? value }) }) ),* ) }; }
crates/router/src/macros.rs
router::src::macros
405
true
// File: crates/router/src/workflows.rs // Module: router::src::workflows #[cfg(feature = "email")] pub mod api_key_expiry; #[cfg(feature = "payouts")] pub mod attach_payout_account_workflow; pub mod outgoing_webhook_retry; pub mod payment_method_status_update; pub mod payment_sync; pub mod refund_router; pub mod tokenized_data; pub mod revenue_recovery; pub mod process_dispute; pub mod dispute_list; pub mod invoice_sync;
crates/router/src/workflows.rs
router::src::workflows
101
true
// File: crates/router/src/locale.rs // Module: router::src::locale use rust_i18n::i18n; i18n!("locales", fallback = "en");
crates/router/src/locale.rs
router::src::locale
42
true
// File: crates/router/src/connector.rs // Module: router::src::connector pub mod utils; #[cfg(feature = "dummy_connector")] pub use hyperswitch_connectors::connectors::DummyConnector; pub use hyperswitch_connectors::connectors::{ aci, aci::Aci, adyen, adyen::Adyen, adyenplatform, adyenplatform::Adyenplatform, affirm, affirm::Affirm, airwallex, airwallex::Airwallex, amazonpay, amazonpay::Amazonpay, archipel, archipel::Archipel, authipay, authipay::Authipay, authorizedotnet, authorizedotnet::Authorizedotnet, bambora, bambora::Bambora, bamboraapac, bamboraapac::Bamboraapac, bankofamerica, bankofamerica::Bankofamerica, barclaycard, barclaycard::Barclaycard, billwerk, billwerk::Billwerk, bitpay, bitpay::Bitpay, blackhawknetwork, blackhawknetwork::Blackhawknetwork, bluesnap, bluesnap::Bluesnap, boku, boku::Boku, braintree, braintree::Braintree, breadpay, breadpay::Breadpay, calida, calida::Calida, cashtocode, cashtocode::Cashtocode, celero, celero::Celero, chargebee, chargebee::Chargebee, checkbook, checkbook::Checkbook, checkout, checkout::Checkout, coinbase, coinbase::Coinbase, coingate, coingate::Coingate, cryptopay, cryptopay::Cryptopay, ctp_mastercard, ctp_mastercard::CtpMastercard, custombilling, custombilling::Custombilling, cybersource, cybersource::Cybersource, datatrans, datatrans::Datatrans, deutschebank, deutschebank::Deutschebank, digitalvirgo, digitalvirgo::Digitalvirgo, dlocal, dlocal::Dlocal, dwolla, dwolla::Dwolla, ebanx, ebanx::Ebanx, elavon, elavon::Elavon, facilitapay, facilitapay::Facilitapay, finix, finix::Finix, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu, flexiti, flexiti::Flexiti, forte, forte::Forte, getnet, getnet::Getnet, gigadat, gigadat::Gigadat, globalpay, globalpay::Globalpay, globepay, globepay::Globepay, gocardless, gocardless::Gocardless, gpayments, gpayments::Gpayments, helcim, helcim::Helcim, hipay, hipay::Hipay, hyperswitch_vault, hyperswitch_vault::HyperswitchVault, hyperwallet, hyperwallet::Hyperwallet, iatapay, iatapay::Iatapay, inespay, inespay::Inespay, itaubank, itaubank::Itaubank, jpmorgan, jpmorgan::Jpmorgan, juspaythreedsserver, juspaythreedsserver::Juspaythreedsserver, katapult, katapult::Katapult, klarna, klarna::Klarna, loonio, loonio::Loonio, mifinity, mifinity::Mifinity, mollie, mollie::Mollie, moneris, moneris::Moneris, mpgs, mpgs::Mpgs, multisafepay, multisafepay::Multisafepay, netcetera, netcetera::Netcetera, nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nmi, nmi::Nmi, nomupay, nomupay::Nomupay, noon, noon::Noon, nordea, nordea::Nordea, novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode, opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payload, payload::Payload, payme, payme::Payme, payone, payone::Payone, paypal, paypal::Paypal, paysafe, paysafe::Paysafe, paystack, paystack::Paystack, paytm, paytm::Paytm, payu, payu::Payu, peachpayments, peachpayments::Peachpayments, phonepe, phonepe::Phonepe, placetopay, placetopay::Placetopay, plaid, plaid::Plaid, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly, recurly::Recurly, redsys, redsys::Redsys, riskified, riskified::Riskified, santander, santander::Santander, shift4, shift4::Shift4, sift, sift::Sift, signifyd, signifyd::Signifyd, silverflow, silverflow::Silverflow, square, square::Square, stax, stax::Stax, stripe, stripe::Stripe, stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, tesouro, tesouro::Tesouro, threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, tokenex, tokenex::Tokenex, tokenio, tokenio::Tokenio, trustpay, trustpay::Trustpay, trustpayments, trustpayments::Trustpayments, tsys, tsys::Tsys, unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, vgs, vgs::Vgs, volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, wellsfargopayout, wellsfargopayout::Wellsfargopayout, wise, wise::Wise, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, worldpayvantiv, worldpayvantiv::Worldpayvantiv, worldpayxml, worldpayxml::Worldpayxml, xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, };
crates/router/src/connector.rs
router::src::connector
1,484
true
// File: crates/router/src/connection.rs // Module: router::src::connection use bb8::PooledConnection; use diesel::PgConnection; use error_stack::ResultExt; use storage_impl::errors as storage_errors; use crate::errors; pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>; pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>; /// Creates a Redis connection pool for the specified Redis settings /// # Panics /// /// Panics if failed to create a redis pool #[allow(clippy::expect_used)] pub async fn redis_connection( conf: &crate::configs::Settings, ) -> redis_interface::RedisConnectionPool { redis_interface::RedisConnectionPool::new(&conf.redis) .await .expect("Failed to create Redis Connection Pool") } pub async fn pg_connection_read<T: storage_impl::DatabaseStore>( store: &T, ) -> errors::CustomResult< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, storage_errors::StorageError, > { // If only OLAP is enabled get replica pool. #[cfg(all(feature = "olap", not(feature = "oltp")))] let pool = store.get_replica_pool(); // If either one of these are true we need to get master pool. // 1. Only OLTP is enabled. // 2. Both OLAP and OLTP is enabled. // 3. Both OLAP and OLTP is disabled. #[cfg(any( all(not(feature = "olap"), feature = "oltp"), all(feature = "olap", feature = "oltp"), all(not(feature = "olap"), not(feature = "oltp")) ))] let pool = store.get_master_pool(); pool.get() .await .change_context(storage_errors::StorageError::DatabaseConnectionError) } pub async fn pg_accounts_connection_read<T: storage_impl::DatabaseStore>( store: &T, ) -> errors::CustomResult< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, storage_errors::StorageError, > { // If only OLAP is enabled get replica pool. #[cfg(all(feature = "olap", not(feature = "oltp")))] let pool = store.get_accounts_replica_pool(); // If either one of these are true we need to get master pool. // 1. Only OLTP is enabled. // 2. Both OLAP and OLTP is enabled. // 3. Both OLAP and OLTP is disabled. #[cfg(any( all(not(feature = "olap"), feature = "oltp"), all(feature = "olap", feature = "oltp"), all(not(feature = "olap"), not(feature = "oltp")) ))] let pool = store.get_accounts_master_pool(); pool.get() .await .change_context(storage_errors::StorageError::DatabaseConnectionError) } pub async fn pg_connection_write<T: storage_impl::DatabaseStore>( store: &T, ) -> errors::CustomResult< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, storage_errors::StorageError, > { // Since all writes should happen to master DB only choose master DB. let pool = store.get_master_pool(); pool.get() .await .change_context(storage_errors::StorageError::DatabaseConnectionError) } pub async fn pg_accounts_connection_write<T: storage_impl::DatabaseStore>( store: &T, ) -> errors::CustomResult< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, storage_errors::StorageError, > { // Since all writes should happen to master DB only choose master DB. let pool = store.get_accounts_master_pool(); pool.get() .await .change_context(storage_errors::StorageError::DatabaseConnectionError) }
crates/router/src/connection.rs
router::src::connection
866
true
// File: crates/router/src/utils.rs // Module: router::src::utils pub mod chat; #[cfg(feature = "olap")] pub mod connector_onboarding; pub mod currency; pub mod db_utils; pub mod ext_traits; #[cfg(feature = "kv_store")] pub mod storage_partitioning; #[cfg(feature = "olap")] pub mod user; #[cfg(feature = "olap")] pub mod user_role; #[cfg(feature = "olap")] pub mod verify_connector; use std::fmt::Debug; use api_models::{ enums, payments::{self}, webhooks, }; use common_utils::types::keymanager::KeyManagerState; pub use common_utils::{ crypto::{self, Encryptable}, ext_traits::{ByteSliceExt, BytesExt, Encode, StringExt, ValueExt}, fp_utils::when, id_type, pii, validation::validate_email, }; #[cfg(feature = "v1")] use common_utils::{ type_name, types::keymanager::{Identifier, ToEncryptable}, }; use error_stack::ResultExt; pub use hyperswitch_connectors::utils::QrImage; use hyperswitch_domain_models::payments::PaymentIntent; #[cfg(feature = "v1")] use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; use masking::{ExposeInterface, SwitchStrategy}; use nanoid::nanoid; use serde::de::DeserializeOwned; use serde_json::Value; #[cfg(feature = "v1")] use subscriptions::subscription_handler::SubscriptionHandler; use tracing_futures::Instrument; pub use self::ext_traits::{OptionExt, ValidateCall}; use crate::{ consts, core::{ authentication::types::ExternalThreeDSConnectorMetadata, errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments as payments_core, }, headers::ACCEPT_LANGUAGE, logger, routes::{metrics, SessionState}, services::{self, authentication::get_header_value_by_key}, types::{self, domain, transformers::ForeignInto}, }; #[cfg(feature = "v1")] use crate::{core::webhooks as webhooks_core, types::storage}; pub mod error_parser { use std::fmt::Display; use actix_web::{ error::{Error, JsonPayloadError}, http::StatusCode, HttpRequest, ResponseError, }; #[derive(Debug)] struct CustomJsonError { err: JsonPayloadError, } // Display is a requirement defined by the actix crate for implementing ResponseError trait impl Display for CustomJsonError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str( serde_json::to_string(&serde_json::json!({ "error": { "error_type": "invalid_request", "message": self.err.to_string(), "code": "IR_06", } })) .as_deref() .unwrap_or("Invalid Json Error"), ) } } impl ResponseError for CustomJsonError { fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> { use actix_web::http::header; actix_web::HttpResponseBuilder::new(self.status_code()) .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) .body(self.to_string()) } } pub fn custom_json_error_handler(err: JsonPayloadError, _req: &HttpRequest) -> Error { Error::from(CustomJsonError { err }) } } #[inline] pub fn generate_id(length: usize, prefix: &str) -> String { format!("{}_{}", prefix, nanoid!(length, &consts::ALPHABETS)) } pub trait ConnectorResponseExt: Sized { fn get_response(self) -> RouterResult<types::Response>; fn get_error_response(self) -> RouterResult<types::Response>; fn get_response_inner<T: DeserializeOwned>(self, type_name: &'static str) -> RouterResult<T> { self.get_response()? .response .parse_struct(type_name) .change_context(errors::ApiErrorResponse::InternalServerError) } } impl<E> ConnectorResponseExt for Result<Result<types::Response, types::Response>, error_stack::Report<E>> { fn get_error_response(self) -> RouterResult<types::Response> { self.map_err(|error| error.change_context(errors::ApiErrorResponse::InternalServerError)) .attach_printable("Error while receiving response") .and_then(|inner| match inner { Ok(res) => { logger::error!(response=?res); Err(errors::ApiErrorResponse::InternalServerError).attach_printable(format!( "Expecting error response, received response: {res:?}" )) } Err(err_res) => Ok(err_res), }) } fn get_response(self) -> RouterResult<types::Response> { self.map_err(|error| error.change_context(errors::ApiErrorResponse::InternalServerError)) .attach_printable("Error while receiving response") .and_then(|inner| match inner { Err(err_res) => { logger::error!(error_response=?err_res); Err(errors::ApiErrorResponse::InternalServerError).attach_printable(format!( "Expecting response, received error response: {err_res:?}" )) } Ok(res) => Ok(res), }) } } #[inline] pub fn get_payout_attempt_id(payout_id: &str, attempt_count: i16) -> String { format!("{payout_id}_{attempt_count}") } #[cfg(feature = "v1")] pub async fn find_payment_intent_from_payment_id_type( state: &SessionState, payment_id_type: payments::PaymentIdType, merchant_context: &domain::MerchantContext, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { let key_manager_state: KeyManagerState = state.into(); let db = &*state.store; match payment_id_type { payments::PaymentIdType::PaymentIntentId(payment_id) => db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound), payments::PaymentIdType::ConnectorTransactionId(connector_transaction_id) => { let attempt = db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_context.get_merchant_account().get_id(), &connector_transaction_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &attempt.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } payments::PaymentIdType::PaymentAttemptId(attempt_id) => { let attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &attempt_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &attempt.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } payments::PaymentIdType::PreprocessingId(_) => { Err(errors::ApiErrorResponse::PaymentNotFound)? } } } #[cfg(feature = "v1")] pub async fn find_payment_intent_from_refund_id_type( state: &SessionState, refund_id_type: webhooks::RefundIdType, merchant_context: &domain::MerchantContext, connector_name: &str, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { let db = &*state.store; let refund = match refund_id_type { webhooks::RefundIdType::RefundId(id) => db .find_refund_by_merchant_id_refund_id( merchant_context.get_merchant_account().get_id(), &id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?, webhooks::RefundIdType::ConnectorRefundId(id) => db .find_refund_by_merchant_id_connector_refund_id_connector( merchant_context.get_merchant_account().get_id(), &id, connector_name, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?, }; let attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &refund.attempt_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( &state.into(), &attempt.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } #[cfg(feature = "v1")] pub async fn find_payment_intent_from_mandate_id_type( state: &SessionState, mandate_id_type: webhooks::MandateIdType, merchant_context: &domain::MerchantContext, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { let db = &*state.store; let mandate = match mandate_id_type { webhooks::MandateIdType::MandateId(mandate_id) => db .find_mandate_by_merchant_id_mandate_id( merchant_context.get_merchant_account().get_id(), mandate_id.as_str(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, webhooks::MandateIdType::ConnectorMandateId(connector_mandate_id) => db .find_mandate_by_merchant_id_connector_mandate_id( merchant_context.get_merchant_account().get_id(), connector_mandate_id.as_str(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, }; db.find_payment_intent_by_payment_id_merchant_id( &state.into(), &mandate .original_payment_id .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("original_payment_id not present in mandate record")?, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } #[cfg(feature = "v1")] pub async fn find_mca_from_authentication_id_type( state: &SessionState, authentication_id_type: webhooks::AuthenticationIdType, merchant_context: &domain::MerchantContext, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; let authentication = match authentication_id_type { webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => db .find_authentication_by_merchant_id_authentication_id( merchant_context.get_merchant_account().get_id(), &authentication_id, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?, webhooks::AuthenticationIdType::ConnectorAuthenticationId(connector_authentication_id) => { db.find_authentication_by_merchant_id_connector_authentication_id( merchant_context.get_merchant_account().get_id().clone(), connector_authentication_id, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)? } }; #[cfg(feature = "v1")] { // raise error if merchant_connector_id is not present since it should we be present in the current flow let mca_id = authentication .merchant_connector_id .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("merchant_connector_id not present in authentication record")?; db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( &state.into(), merchant_context.get_merchant_account().get_id(), &mca_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: mca_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] //get mca using id { let _ = key_store; let _ = authentication; todo!() } } #[cfg(feature = "v1")] pub async fn get_mca_from_payment_intent( state: &SessionState, merchant_context: &domain::MerchantContext, payment_intent: PaymentIntent, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; let key_manager_state: &KeyManagerState = &state.into(); #[cfg(feature = "v1")] let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &payment_intent.active_attempt.get_id(), merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; #[cfg(feature = "v2")] let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( key_manager_state, key_store, &payment_intent.active_attempt.get_id(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; match payment_attempt.merchant_connector_id { Some(merchant_connector_id) => { #[cfg(feature = "v1")] { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_context.get_merchant_account().get_id(), &merchant_connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] { //get mca using id let _id = merchant_connector_id; let _ = key_store; let _ = key_manager_state; let _ = connector_name; todo!() } } None => { let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( key_manager_state, &profile_id, connector_name, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile_id {} and connector_name {connector_name}", profile_id.get_string_repr() ), }, ) } #[cfg(feature = "v2")] { //get mca using id let _ = profile_id; todo!() } } } } #[cfg(feature = "payouts")] pub async fn get_mca_from_payout_attempt( state: &SessionState, merchant_context: &domain::MerchantContext, payout_id_type: webhooks::PayoutIdType, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; let payout = match payout_id_type { webhooks::PayoutIdType::PayoutAttemptId(payout_attempt_id) => db .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_context.get_merchant_account().get_id(), &payout_attempt_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?, webhooks::PayoutIdType::ConnectorPayoutId(connector_payout_id) => db .find_payout_attempt_by_merchant_id_connector_payout_id( merchant_context.get_merchant_account().get_id(), &connector_payout_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?, }; let key_manager_state: &KeyManagerState = &state.into(); match payout.merchant_connector_id { Some(merchant_connector_id) => { #[cfg(feature = "v1")] { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_context.get_merchant_account().get_id(), &merchant_connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] { //get mca using id let _id = merchant_connector_id; let _ = merchant_context.get_merchant_key_store(); let _ = connector_name; let _ = key_manager_state; todo!() } } None => { #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( key_manager_state, &payout.profile_id, connector_name, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile_id {} and connector_name {}", payout.profile_id.get_string_repr(), connector_name ), }, ) } #[cfg(feature = "v2")] { todo!() } } } } #[cfg(feature = "v1")] pub async fn get_mca_from_object_reference_id( state: &SessionState, object_reference_id: webhooks::ObjectReferenceId, merchant_context: &domain::MerchantContext, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; #[cfg(feature = "v1")] let default_profile_id = merchant_context .get_merchant_account() .default_profile .as_ref(); #[cfg(feature = "v2")] let default_profile_id = Option::<&String>::None; match default_profile_id { Some(profile_id) => { #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( &state.into(), profile_id, connector_name, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile_id {} and connector_name {connector_name}", profile_id.get_string_repr() ), }, ) } #[cfg(feature = "v2")] { let _db = db; let _profile_id = profile_id; todo!() } } _ => match object_reference_id { webhooks::ObjectReferenceId::PaymentId(payment_id_type) => { get_mca_from_payment_intent( state, merchant_context, find_payment_intent_from_payment_id_type( state, payment_id_type, merchant_context, ) .await?, connector_name, ) .await } webhooks::ObjectReferenceId::RefundId(refund_id_type) => { get_mca_from_payment_intent( state, merchant_context, find_payment_intent_from_refund_id_type( state, refund_id_type, merchant_context, connector_name, ) .await?, connector_name, ) .await } webhooks::ObjectReferenceId::MandateId(mandate_id_type) => { get_mca_from_payment_intent( state, merchant_context, find_payment_intent_from_mandate_id_type( state, mandate_id_type, merchant_context, ) .await?, connector_name, ) .await } webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) => { find_mca_from_authentication_id_type( state, authentication_id_type, merchant_context, ) .await } webhooks::ObjectReferenceId::SubscriptionId(subscription_id_type) => { #[cfg(feature = "v1")] { let subscription_state = state.clone().into(); let subscription_handler = SubscriptionHandler::new(&subscription_state, merchant_context); let mut subscription_with_handler = subscription_handler .find_subscription(subscription_id_type) .await?; subscription_with_handler.get_mca(connector_name).await } #[cfg(feature = "v2")] { let _db = db; todo!() } } #[cfg(feature = "payouts")] webhooks::ObjectReferenceId::PayoutId(payout_id_type) => { get_mca_from_payout_attempt(state, merchant_context, payout_id_type, connector_name) .await } }, } } // validate json format for the error pub fn handle_json_response_deserialization_failure( res: types::Response, connector: &'static str, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { metrics::RESPONSE_DESERIALIZATION_FAILURE .add(1, router_env::metric_attributes!(("connector", connector))); let response_data = String::from_utf8(res.response.to_vec()) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; // check for whether the response is in json format match serde_json::from_str::<Value>(&response_data) { // in case of unexpected response but in json format Ok(_) => Err(errors::ConnectorError::ResponseDeserializationFailed)?, // in case of unexpected response but in html or string format Err(error_msg) => { logger::error!(deserialization_error=?error_msg); logger::error!("UNEXPECTED RESPONSE FROM CONNECTOR: {}", response_data); Ok(types::ErrorResponse { status_code: res.status_code, code: consts::NO_ERROR_CODE.to_string(), message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(), reason: Some(response_data), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } } pub fn get_http_status_code_type( status_code: u16, ) -> CustomResult<String, errors::ApiErrorResponse> { let status_code_type = match status_code { 100..=199 => "1xx", 200..=299 => "2xx", 300..=399 => "3xx", 400..=499 => "4xx", 500..=599 => "5xx", _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid http status code")?, }; Ok(status_code_type.to_string()) } pub fn add_connector_http_status_code_metrics(option_status_code: Option<u16>) { if let Some(status_code) = option_status_code { let status_code_type = get_http_status_code_type(status_code).ok(); match status_code_type.as_deref() { Some("1xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_1XX_COUNT.add(1, &[]), Some("2xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_2XX_COUNT.add(1, &[]), Some("3xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_3XX_COUNT.add(1, &[]), Some("4xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_4XX_COUNT.add(1, &[]), Some("5xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_5XX_COUNT.add(1, &[]), _ => logger::info!("Skip metrics as invalid http status code received from connector"), }; } else { logger::info!("Skip metrics as no http status code received from connector") } } #[cfg(feature = "v1")] #[async_trait::async_trait] pub trait CustomerAddress { async fn get_address_update( &self, state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, merchant_id: id_type::MerchantId, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError>; async fn get_domain_address( &self, state: &SessionState, address_details: payments::AddressDetails, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError>; } #[cfg(feature = "v1")] #[async_trait::async_trait] impl CustomerAddress for api_models::customers::CustomerRequest { async fn get_address_update( &self, state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, merchant_id: id_type::MerchantId, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(storage::AddressUpdate::Update { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }) } async fn get_domain_address( &self, state: &SessionState, address_details: payments::AddressDetails, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; let address = domain::Address { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), merchant_id: merchant_id.to_owned(), address_id: generate_id(consts::ID_LENGTH, "add"), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }; Ok(domain::CustomerAddress { address, customer_id: customer_id.to_owned(), }) } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl CustomerAddress for api_models::customers::CustomerUpdateRequest { async fn get_address_update( &self, state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, merchant_id: id_type::MerchantId, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(storage::AddressUpdate::Update { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }) } async fn get_domain_address( &self, state: &SessionState, address_details: payments::AddressDetails, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; let address = domain::Address { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), merchant_id: merchant_id.to_owned(), address_id: generate_id(consts::ID_LENGTH, "add"), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }; Ok(domain::CustomerAddress { address, customer_id: customer_id.to_owned(), }) } } pub fn add_apple_pay_flow_metrics( apple_pay_flow: &Option<domain::ApplePayFlow>, connector: Option<String>, merchant_id: id_type::MerchantId, ) { if let Some(flow) = apple_pay_flow { match flow { domain::ApplePayFlow::Simplified(_) => metrics::APPLE_PAY_SIMPLIFIED_FLOW.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ), domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ), } } } pub fn add_apple_pay_payment_status_metrics( payment_attempt_status: enums::AttemptStatus, apple_pay_flow: Option<domain::ApplePayFlow>, connector: Option<String>, merchant_id: id_type::MerchantId, ) { if payment_attempt_status == enums::AttemptStatus::Charged { if let Some(flow) = apple_pay_flow { match flow { domain::ApplePayFlow::Simplified(_) => { metrics::APPLE_PAY_SIMPLIFIED_FLOW_SUCCESSFUL_PAYMENT.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ) } domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_SUCCESSFUL_PAYMENT .add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ), } } } else if payment_attempt_status == enums::AttemptStatus::Failure { if let Some(flow) = apple_pay_flow { match flow { domain::ApplePayFlow::Simplified(_) => { metrics::APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ) } domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ), } } } } pub fn check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata( metadata: Option<Value>, ) -> bool { let external_three_ds_connector_metadata: Option<ExternalThreeDSConnectorMetadata> = metadata .parse_value("ExternalThreeDSConnectorMetadata") .map_err(|err| logger::warn!(parsing_error=?err,"Error while parsing ExternalThreeDSConnectorMetadata")) .ok(); external_three_ds_connector_metadata .and_then(|metadata| metadata.pull_mechanism_for_external_3ds_enabled) .unwrap_or(true) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn trigger_payments_webhook<F, Op, D>( merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: &domain::MerchantKeyStore, payment_data: D, customer: Option<domain::Customer>, state: &SessionState, operation: Op, ) -> RouterResult<()> where F: Send + Clone + Sync, Op: Debug, D: payments_core::OperationSessionGetters<F>, { todo!() } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn trigger_payments_webhook<F, Op, D>( merchant_context: domain::MerchantContext, business_profile: domain::Profile, payment_data: D, customer: Option<domain::Customer>, state: &SessionState, operation: Op, ) -> RouterResult<()> where F: Send + Clone + Sync, Op: Debug, D: payments_core::OperationSessionGetters<F>, { let status = payment_data.get_payment_intent().status; let should_trigger_webhook = business_profile .get_payment_webhook_statuses() .contains(&status); if should_trigger_webhook { let captures = payment_data .get_multiple_capture_data() .map(|multiple_capture_data| { multiple_capture_data .get_all_captures() .into_iter() .cloned() .collect() }); let payment_id = payment_data.get_payment_intent().get_id().to_owned(); let payments_response = crate::core::payments::transformers::payments_to_payments_response( payment_data, captures, customer, services::AuthFlow::Merchant, &state.base_url, &operation, &state.conf.connector_request_reference_id_config, None, None, None, )?; let event_type = status.into(); if let services::ApplicationResponse::JsonWithHeaders((payments_response_json, _)) = payments_response { let cloned_state = state.clone(); // This spawns this futures in a background thread, the exception inside this future won't affect // the current thread and the lifecycle of spawn thread is not handled by runtime. // So when server shutdown won't wait for this thread's completion. if let Some(event_type) = event_type { tokio::spawn( async move { let primary_object_created_at = payments_response_json.created; Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook( cloned_state, merchant_context.clone(), business_profile, event_type, diesel_models::enums::EventClass::Payments, payment_id.get_string_repr().to_owned(), diesel_models::enums::EventObjectType::PaymentDetails, webhooks::OutgoingWebhookContent::PaymentDetails(Box::new( payments_response_json, )), primary_object_created_at, )) .await } .in_current_span(), ); } else { logger::warn!( "Outgoing webhook not sent because of missing event type status mapping" ); } } } Ok(()) } type Handle<T> = tokio::task::JoinHandle<RouterResult<T>>; pub async fn flatten_join_error<T>(handle: Handle<T>) -> RouterResult<T> { match handle.await { Ok(Ok(t)) => Ok(t), Ok(Err(err)) => Err(err), Err(err) => Err(err) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Join Error"), } } #[cfg(feature = "v1")] pub async fn trigger_refund_outgoing_webhook( state: &SessionState, merchant_context: &domain::MerchantContext, refund: &diesel_models::Refund, profile_id: id_type::ProfileId, ) -> RouterResult<()> { let refund_status = refund.refund_status; let key_manager_state = &(state).into(); let business_profile = state .store .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let should_trigger_webhook = business_profile .get_refund_webhook_statuses() .contains(&refund_status); if should_trigger_webhook { let event_type = refund_status.into(); let refund_response: api_models::refunds::RefundResponse = refund.clone().foreign_into(); let refund_id = refund_response.refund_id.clone(); let cloned_state = state.clone(); let cloned_merchant_context = merchant_context.clone(); let primary_object_created_at = refund_response.created_at; if let Some(outgoing_event_type) = event_type { tokio::spawn( async move { Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook( cloned_state, cloned_merchant_context, business_profile, outgoing_event_type, diesel_models::enums::EventClass::Refunds, refund_id.to_string(), diesel_models::enums::EventObjectType::RefundDetails, webhooks::OutgoingWebhookContent::RefundDetails(Box::new(refund_response)), primary_object_created_at, )) .await } .in_current_span(), ); } else { logger::warn!("Outgoing webhook not sent because of missing event type status mapping"); }; } Ok(()) } #[cfg(feature = "v2")] pub async fn trigger_refund_outgoing_webhook( state: &SessionState, merchant_account: &domain::MerchantAccount, refund: &diesel_models::Refund, profile_id: id_type::ProfileId, key_store: &domain::MerchantKeyStore, ) -> RouterResult<()> { todo!() } pub fn get_locale_from_header(headers: &actix_web::http::header::HeaderMap) -> String { get_header_value_by_key(ACCEPT_LANGUAGE.into(), headers) .ok() .flatten() .map(|val| val.to_string()) .unwrap_or(common_utils::consts::DEFAULT_LOCALE.to_string()) } #[cfg(all(feature = "payouts", feature = "v1"))] pub async fn trigger_payouts_webhook( state: &SessionState, merchant_context: &domain::MerchantContext, payout_response: &api_models::payouts::PayoutCreateResponse, ) -> RouterResult<()> { let key_manager_state = &(state).into(); let profile_id = &payout_response.profile_id; let business_profile = state .store .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let status = &payout_response.status; let should_trigger_webhook = business_profile .get_payout_webhook_statuses() .contains(status); if should_trigger_webhook { let event_type = (*status).into(); if let Some(event_type) = event_type { let cloned_merchant_context = merchant_context.clone(); let cloned_state = state.clone(); let cloned_response = payout_response.clone(); // This spawns this futures in a background thread, the exception inside this future won't affect // the current thread and the lifecycle of spawn thread is not handled by runtime. // So when server shutdown won't wait for this thread's completion. tokio::spawn( async move { let primary_object_created_at = cloned_response.created; Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook( cloned_state, cloned_merchant_context, business_profile, event_type, diesel_models::enums::EventClass::Payouts, cloned_response.payout_id.get_string_repr().to_owned(), diesel_models::enums::EventObjectType::PayoutDetails, webhooks::OutgoingWebhookContent::PayoutDetails(Box::new(cloned_response)), primary_object_created_at, )) .await } .in_current_span(), ); } else { logger::warn!("Outgoing webhook not sent because of missing event type status mapping"); } } Ok(()) } #[cfg(all(feature = "payouts", feature = "v2"))] pub async fn trigger_payouts_webhook( state: &SessionState, merchant_context: &domain::MerchantContext, payout_response: &api_models::payouts::PayoutCreateResponse, ) -> RouterResult<()> { todo!() }
crates/router/src/utils.rs
router::src::utils
10,592
true
// File: crates/router/src/compatibility/wrap.rs // Module: router::src::compatibility::wrap use std::{future::Future, sync::Arc, time::Instant}; use actix_web::{HttpRequest, HttpResponse, Responder}; use common_utils::errors::{CustomResult, ErrorSwitch}; use router_env::{instrument, tracing, Tag}; use serde::Serialize; use crate::{ core::{api_locking, errors}, events::api_logs::ApiEventMetric, routes::{ app::{AppStateInfo, ReqState}, AppState, SessionState, }, services::{self, api, authentication as auth, logger}, }; #[instrument(skip(request, payload, state, func, api_authentication))] pub async fn compatibility_api_wrap<'a, 'b, U, T, Q, F, Fut, S, E, E2>( flow: impl router_env::types::FlowMetric, state: Arc<AppState>, request: &'a HttpRequest, payload: T, func: F, api_authentication: &dyn auth::AuthenticateAndFetch<U, SessionState>, lock_action: api_locking::LockAction, ) -> HttpResponse where F: Fn(SessionState, U, T, ReqState) -> Fut, Fut: Future<Output = CustomResult<api::ApplicationResponse<Q>, E2>>, E2: ErrorSwitch<E> + std::error::Error + Send + Sync + 'static, Q: Serialize + std::fmt::Debug + 'a + ApiEventMetric, S: TryFrom<Q> + Serialize, E: Serialize + error_stack::Context + actix_web::ResponseError + Clone, error_stack::Report<E>: services::EmbedError, errors::ApiErrorResponse: ErrorSwitch<E>, T: std::fmt::Debug + Serialize + ApiEventMetric, { let request_method = request.method().as_str(); let url_path = request.path(); tracing::Span::current().record("request_method", request_method); tracing::Span::current().record("request_url_path", url_path); let start_instant = Instant::now(); logger::info!(tag = ?Tag::BeginRequest, payload = ?payload); let server_wrap_util_res = api::server_wrap_util( &flow, state.clone().into(), request.headers(), request, payload, func, api_authentication, lock_action, ) .await .map(|response| { logger::info!(api_response =? response); response }); let res = match server_wrap_util_res { Ok(api::ApplicationResponse::Json(response)) => { let response = S::try_from(response); match response { Ok(response) => match serde_json::to_string(&response) { Ok(res) => api::http_response_json(res), Err(_) => api::http_response_err( r#"{ "error": { "message": "Error serializing response from connector" } }"#, ), }, Err(_) => api::http_response_err( r#"{ "error": { "message": "Error converting juspay response to stripe response" } }"#, ), } } Ok(api::ApplicationResponse::JsonWithHeaders((response, headers))) => { let response = S::try_from(response); match response { Ok(response) => match serde_json::to_string(&response) { Ok(res) => api::http_response_json_with_headers(res, headers, None, None), Err(_) => api::http_response_err( r#"{ "error": { "message": "Error serializing response from connector" } }"#, ), }, Err(_) => api::http_response_err( r#"{ "error": { "message": "Error converting juspay response to stripe response" } }"#, ), } } Ok(api::ApplicationResponse::StatusOk) => api::http_response_ok(), Ok(api::ApplicationResponse::TextPlain(text)) => api::http_response_plaintext(text), Ok(api::ApplicationResponse::FileData((file_data, content_type))) => { api::http_response_file_data(file_data, content_type) } Ok(api::ApplicationResponse::JsonForRedirection(response)) => { match serde_json::to_string(&response) { Ok(res) => api::http_redirect_response(res, response), Err(_) => api::http_response_err( r#"{ "error": { "message": "Error serializing response from connector" } }"#, ), } } Ok(api::ApplicationResponse::Form(redirection_data)) => { let config = state.conf(); api::build_redirection_form( &redirection_data.redirect_form, redirection_data.payment_method_data, redirection_data.amount, redirection_data.currency, config, ) .respond_to(request) .map_into_boxed_body() } Ok(api::ApplicationResponse::GenericLinkForm(boxed_generic_link_data)) => { let link_type = (boxed_generic_link_data).data.to_string(); match services::generic_link_response::build_generic_link_html( boxed_generic_link_data.data, boxed_generic_link_data.locale, ) { Ok(rendered_html) => api::http_response_html_data(rendered_html, None), Err(_) => { api::http_response_err(format!("Error while rendering {link_type} HTML page")) } } } Ok(api::ApplicationResponse::PaymentLinkForm(boxed_payment_link_data)) => { match *boxed_payment_link_data { api::PaymentLinkAction::PaymentLinkFormData(payment_link_data) => { match api::build_payment_link_html(payment_link_data) { Ok(rendered_html) => api::http_response_html_data(rendered_html, None), Err(_) => api::http_response_err( r#"{ "error": { "message": "Error while rendering payment link html page" } }"#, ), } } api::PaymentLinkAction::PaymentLinkStatus(payment_link_data) => { match api::get_payment_link_status(payment_link_data) { Ok(rendered_html) => api::http_response_html_data(rendered_html, None), Err(_) => api::http_response_err( r#"{ "error": { "message": "Error while rendering payment link status page" } }"#, ), } } } } Err(error) => api::log_and_return_error_response(error), }; let response_code = res.status().as_u16(); let end_instant = Instant::now(); let request_duration = end_instant.saturating_duration_since(start_instant); logger::info!( tag = ?Tag::EndRequest, status_code = response_code, time_taken_ms = request_duration.as_millis(), ); res }
crates/router/src/compatibility/wrap.rs
router::src::compatibility::wrap
1,490
true
// File: crates/router/src/compatibility/stripe.rs // Module: router::src::compatibility::stripe pub mod app; pub mod customers; pub mod payment_intents; pub mod refunds; pub mod setup_intents; pub mod webhooks; #[cfg(feature = "v1")] use actix_web::{web, Scope}; pub mod errors; #[cfg(feature = "v1")] use crate::routes; #[cfg(feature = "v1")] pub struct StripeApis; #[cfg(feature = "v1")] impl StripeApis { pub fn server(state: routes::AppState) -> Scope { let max_depth = 10; let strict = false; web::scope("/vs/v1") .app_data(web::Data::new(serde_qs::Config::new(max_depth, strict))) .service(app::SetupIntents::server(state.clone())) .service(app::PaymentIntents::server(state.clone())) .service(app::Refunds::server(state.clone())) .service(app::Customers::server(state.clone())) .service(app::Webhooks::server(state.clone())) .service(app::Mandates::server(state)) } }
crates/router/src/compatibility/stripe.rs
router::src::compatibility::stripe
247
true
// File: crates/router/src/compatibility/stripe/payment_intents.rs // Module: router::src::compatibility::stripe::payment_intents pub mod types; use actix_web::{web, HttpRequest, HttpResponse}; use api_models::payments as payment_types; #[cfg(feature = "v1")] use error_stack::report; #[cfg(feature = "v1")] use router_env::Tag; use router_env::{instrument, tracing, Flow}; use crate::{ compatibility::{stripe::errors, wrap}, core::payments, routes::{self}, services::{api, authentication as auth}, }; #[cfg(feature = "v1")] use crate::{ core::api_locking::GetLockingInput, logger, routes::payments::get_or_generate_payment_id, types::{api as api_types, domain}, }; #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCreate, payment_id))] pub async fn payment_intents_create( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { let payload: types::StripePaymentIntentRequest = match qs_config .deserialize_bytes(&form_payload) .map_err(|err| report!(errors::StripeErrorCode::from(err))) { Ok(p) => p, Err(err) => return api::log_and_return_error_response(err), }; tracing::Span::current().record( "payment_id", payload .id .as_ref() .map(|payment_id| payment_id.get_string_repr()) .unwrap_or_default(), ); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?payload); let mut create_payment_req: payment_types::PaymentsRequest = match payload.try_into() { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; if let Err(err) = get_or_generate_payment_id(&mut create_payment_req) { return api::log_and_return_error_response(err); } let flow = Flow::PaymentsCreate; let locking_action = create_payment_req.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, create_payment_req, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); let eligible_connectors = req.connector.clone(); payments::payments_core::< api_types::Authorize, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Authorize>, >( state, req_state, merchant_context, None, payments::PaymentCreate, req, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, eligible_connectors, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieveForceSync))] pub async fn payment_intents_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::PaymentId>, query_payload: web::Query<types::StripePaymentRetrieveBody>, ) -> HttpResponse { let payload = payment_types::PaymentsRetrieveRequest { resource_id: api_types::PaymentIdType::PaymentIntentId(path.into_inner()), merchant_id: None, force_sync: true, connector: None, param: None, merchant_connector_details: None, client_secret: query_payload.client_secret.clone(), expand_attempts: None, expand_captures: None, all_keys_required: None, }; let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let flow = Flow::PaymentsRetrieveForceSync; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, payload, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::PSync, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::PSync>, >( state, req_state, merchant_context, None, payments::PaymentStatus, payload, auth_flow, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &*auth_type, locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow))] pub async fn payment_intents_retrieve_with_gateway_creds( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { let json_payload: payment_types::PaymentRetrieveBodyWithCredentials = match qs_config .deserialize_bytes(&form_payload) .map_err(|err| report!(errors::StripeErrorCode::from(err))) { Ok(p) => p, Err(err) => return api::log_and_return_error_response(err), }; let payload = payment_types::PaymentsRetrieveRequest { resource_id: payment_types::PaymentIdType::PaymentIntentId(json_payload.payment_id), merchant_id: json_payload.merchant_id.clone(), force_sync: json_payload.force_sync.unwrap_or(false), merchant_connector_details: json_payload.merchant_connector_details.clone(), ..Default::default() }; let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, _auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let flow = match json_payload.force_sync { Some(true) => Flow::PaymentsRetrieveForceSync, _ => Flow::PaymentsRetrieve, }; tracing::Span::current().record("flow", flow.to_string()); let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::PSync, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::PSync>, >( state, req_state, merchant_context, None, payments::PaymentStatus, req, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &*auth_type, locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdate))] pub async fn payment_intents_update( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let payment_id = path.into_inner(); let stripe_payload: types::StripePaymentIntentRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; let mut payload: payment_types::PaymentsRequest = match stripe_payload.try_into() { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id)); let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let flow = Flow::PaymentsUpdate; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); let eligible_connectors = req.connector.clone(); payments::payments_core::< api_types::Authorize, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Authorize>, >( state, req_state, merchant_context, None, payments::PaymentUpdate, req, auth_flow, payments::CallConnectorAction::Trigger, eligible_connectors, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &*auth_type, locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm, payment_id))] pub async fn payment_intents_confirm( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let payment_id = path.into_inner(); let stripe_payload: types::StripePaymentIntentRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; tracing::Span::current().record( "payment_id", stripe_payload.id.as_ref().map(|id| id.get_string_repr()), ); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload); let mut payload: payment_types::PaymentsRequest = match stripe_payload.try_into() { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id)); payload.confirm = Some(true); let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; let flow = Flow::PaymentsConfirm; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); let eligible_connectors = req.connector.clone(); payments::payments_core::< api_types::Authorize, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Authorize>, >( state, req_state, merchant_context, None, payments::PaymentConfirm, req, auth_flow, payments::CallConnectorAction::Trigger, eligible_connectors, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &*auth_type, locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCapture, payment_id))] pub async fn payment_intents_capture( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let stripe_payload: payment_types::PaymentsCaptureRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; tracing::Span::current().record("payment_id", stripe_payload.payment_id.get_string_repr()); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload); let payload = payment_types::PaymentsCaptureRequest { payment_id: path.into_inner(), ..stripe_payload }; let flow = Flow::PaymentsCapture; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth: auth::AuthenticationData, payload, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::Capture, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Capture>, >( state, req_state, merchant_context, None, payments::PaymentCapture, payload, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCancel, payment_id))] pub async fn payment_intents_cancel( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let payment_id = path.into_inner(); let stripe_payload: types::StripePaymentCancelRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; tracing::Span::current().record("payment_id", payment_id.get_string_repr()); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload); let mut payload: payment_types::PaymentsCancelRequest = stripe_payload.into(); payload.payment_id = payment_id; let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let flow = Flow::PaymentsCancel; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::Void, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Void>, >( state, req_state, merchant_context, None, payments::PaymentCancel, req, auth_flow, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &*auth_type, locking_action, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PaymentsList))] #[cfg(feature = "olap")] pub async fn payment_intent_list( state: web::Data<routes::AppState>, req: HttpRequest, payload: web::Query<types::StripePaymentListConstraints>, ) -> HttpResponse { let payload = match payment_types::PaymentListConstraints::try_from(payload.into_inner()) { Ok(p) => p, Err(err) => return api::log_and_return_error_response(err), }; use crate::core::api_locking; let flow = Flow::PaymentsList; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentListResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::list_payments(state, merchant_context, None, req) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/compatibility/stripe/payment_intents.rs
router::src::compatibility::stripe::payment_intents
4,331
true
// File: crates/router/src/compatibility/stripe/refunds.rs // Module: router::src::compatibility::stripe::refunds pub mod types; use actix_web::{web, HttpRequest, HttpResponse}; use error_stack::report; use router_env::{instrument, tracing, Flow, Tag}; use crate::{ compatibility::{stripe::errors, wrap}, core::{api_locking, refunds}, db::domain, logger, routes, services::{api, authentication as auth}, types::api::refunds as refund_types, }; #[instrument(skip_all, fields(flow = ?Flow::RefundsCreate, payment_id))] pub async fn refund_create( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { let payload: types::StripeCreateRefundRequest = match qs_config .deserialize_bytes(&form_payload) .map_err(|err| report!(errors::StripeErrorCode::from(err))) { Ok(p) => p, Err(err) => return api::log_and_return_error_response(err), }; tracing::Span::current().record("payment_id", payload.payment_intent.get_string_repr()); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?payload); let create_refund_req: refund_types::RefundRequest = payload.into(); let flow = Flow::RefundsCreate; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeRefundResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, create_refund_req, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); refunds::refund_create_core(state, merchant_context, None, req) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow))] pub async fn refund_retrieve_with_gateway_creds( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { let refund_request: refund_types::RefundsRetrieveRequest = match qs_config .deserialize_bytes(&form_payload) .map_err(|err| report!(errors::StripeErrorCode::from(err))) { Ok(payload) => payload, Err(err) => return api::log_and_return_error_response(err), }; let flow = match refund_request.force_sync { Some(true) => Flow::RefundsRetrieveForceSync, _ => Flow::RefundsRetrieve, }; tracing::Span::current().record("flow", flow.to_string()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeRefundResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, refund_request, |state, auth: auth::AuthenticationData, refund_request, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); refunds::refund_response_wrapper( state, merchant_context, None, refund_request, refunds::refund_retrieve_core_with_refund_id, ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::RefundsRetrieveForceSync))] pub async fn refund_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let refund_request = refund_types::RefundsRetrieveRequest { refund_id: path.into_inner(), force_sync: Some(true), merchant_connector_details: None, }; let flow = Flow::RefundsRetrieveForceSync; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeRefundResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, refund_request, |state, auth: auth::AuthenticationData, refund_request, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); refunds::refund_response_wrapper( state, merchant_context, None, refund_request, refunds::refund_retrieve_core_with_refund_id, ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::RefundsUpdate))] pub async fn refund_update( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<String>, form_payload: web::Form<types::StripeUpdateRefundRequest>, ) -> HttpResponse { let mut payload = form_payload.into_inner(); payload.refund_id = path.into_inner(); let create_refund_update_req: refund_types::RefundUpdateRequest = payload.into(); let flow = Flow::RefundsUpdate; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeRefundResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, create_refund_update_req, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); refunds::refund_update_core(state, merchant_context, req) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/compatibility/stripe/refunds.rs
router::src::compatibility::stripe::refunds
1,441
true
// File: crates/router/src/compatibility/stripe/webhooks.rs // Module: router::src::compatibility::stripe::webhooks #[cfg(feature = "payouts")] use api_models::payouts as payout_models; use api_models::{ enums::{Currency, DisputeStatus, MandateStatus}, webhooks::{self as api}, }; use common_utils::{crypto::SignMessage, date_time, ext_traits::Encode}; #[cfg(feature = "payouts")] use common_utils::{ id_type, pii::{self, Email}, }; use error_stack::ResultExt; use router_env::logger; use serde::Serialize; use super::{ payment_intents::types::StripePaymentIntentResponse, refunds::types::StripeRefundResponse, }; use crate::{ core::{ errors, webhooks::types::{OutgoingWebhookPayloadWithSignature, OutgoingWebhookType}, }, headers, services::request::Maskable, }; #[derive(Serialize, Debug)] pub struct StripeOutgoingWebhook { id: String, #[serde(rename = "type")] stype: &'static str, object: &'static str, data: StripeWebhookObject, created: u64, // api_version: "2019-11-05", // not used } impl OutgoingWebhookType for StripeOutgoingWebhook { fn get_outgoing_webhooks_signature( &self, payment_response_hash_key: Option<impl AsRef<[u8]>>, ) -> errors::CustomResult<OutgoingWebhookPayloadWithSignature, errors::WebhooksFlowError> { let timestamp = self.created; let payment_response_hash_key = payment_response_hash_key .ok_or(errors::WebhooksFlowError::MerchantConfigNotFound) .attach_printable("For stripe compatibility payment_response_hash_key is mandatory")?; let webhook_signature_payload = self .encode_to_string_of_json() .change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed) .attach_printable("failed encoding outgoing webhook payload")?; let new_signature_payload = format!("{timestamp}.{webhook_signature_payload}"); let v1 = hex::encode( common_utils::crypto::HmacSha256::sign_message( &common_utils::crypto::HmacSha256, payment_response_hash_key.as_ref(), new_signature_payload.as_bytes(), ) .change_context(errors::WebhooksFlowError::OutgoingWebhookSigningFailed) .attach_printable("Failed to sign the message")?, ); let t = timestamp; let signature = Some(format!("t={t},v1={v1}")); Ok(OutgoingWebhookPayloadWithSignature { payload: webhook_signature_payload.into(), signature, }) } fn add_webhook_header(header: &mut Vec<(String, Maskable<String>)>, signature: String) { header.push(( headers::STRIPE_COMPATIBLE_WEBHOOK_SIGNATURE.to_string(), signature.into(), )) } } #[derive(Serialize, Debug)] #[serde(tag = "type", content = "object", rename_all = "snake_case")] pub enum StripeWebhookObject { PaymentIntent(Box<StripePaymentIntentResponse>), Refund(StripeRefundResponse), Dispute(StripeDisputeResponse), Mandate(StripeMandateResponse), #[cfg(feature = "payouts")] Payout(StripePayoutResponse), } #[derive(Serialize, Debug)] pub struct StripeDisputeResponse { pub id: String, pub amount: String, pub currency: Currency, pub payment_intent: id_type::PaymentId, pub reason: Option<String>, pub status: StripeDisputeStatus, } #[derive(Serialize, Debug)] pub struct StripeMandateResponse { pub mandate_id: String, pub status: StripeMandateStatus, pub payment_method_id: String, pub payment_method: String, } #[cfg(feature = "payouts")] #[derive(Clone, Serialize, Debug)] pub struct StripePayoutResponse { pub id: id_type::PayoutId, pub amount: i64, pub currency: String, pub payout_type: Option<common_enums::PayoutType>, pub status: StripePayoutStatus, pub name: Option<masking::Secret<String>>, pub email: Option<Email>, pub phone: Option<masking::Secret<String>>, pub phone_country_code: Option<String>, pub created: Option<i64>, pub metadata: Option<pii::SecretSerdeValue>, pub entity_type: common_enums::PayoutEntityType, pub recurring: bool, pub error_message: Option<String>, pub error_code: Option<String>, } #[cfg(feature = "payouts")] #[derive(Clone, Serialize, Debug)] #[serde(rename_all = "snake_case")] pub enum StripePayoutStatus { PayoutSuccess, PayoutFailure, PayoutProcessing, PayoutCancelled, PayoutInitiated, PayoutExpired, PayoutReversed, } #[cfg(feature = "payouts")] impl From<common_enums::PayoutStatus> for StripePayoutStatus { fn from(status: common_enums::PayoutStatus) -> Self { match status { common_enums::PayoutStatus::Success => Self::PayoutSuccess, common_enums::PayoutStatus::Failed => Self::PayoutFailure, common_enums::PayoutStatus::Cancelled => Self::PayoutCancelled, common_enums::PayoutStatus::Initiated => Self::PayoutInitiated, common_enums::PayoutStatus::Expired => Self::PayoutExpired, common_enums::PayoutStatus::Reversed => Self::PayoutReversed, common_enums::PayoutStatus::Pending | common_enums::PayoutStatus::Ineligible | common_enums::PayoutStatus::RequiresCreation | common_enums::PayoutStatus::RequiresFulfillment | common_enums::PayoutStatus::RequiresPayoutMethodData | common_enums::PayoutStatus::RequiresVendorAccountCreation | common_enums::PayoutStatus::RequiresConfirmation => Self::PayoutProcessing, } } } #[cfg(feature = "payouts")] impl From<payout_models::PayoutCreateResponse> for StripePayoutResponse { fn from(res: payout_models::PayoutCreateResponse) -> Self { let (name, email, phone, phone_country_code) = match res.customer { Some(customer) => ( customer.name, customer.email, customer.phone, customer.phone_country_code, ), None => (None, None, None, None), }; Self { id: res.payout_id, amount: res.amount.get_amount_as_i64(), currency: res.currency.to_string(), payout_type: res.payout_type, status: StripePayoutStatus::from(res.status), name, email, phone, phone_country_code, created: res.created.map(|t| t.assume_utc().unix_timestamp()), metadata: res.metadata, entity_type: res.entity_type, recurring: res.recurring, error_message: res.error_message, error_code: res.error_code, } } } #[derive(Serialize, Debug)] #[serde(rename_all = "snake_case")] pub enum StripeMandateStatus { Active, Inactive, Pending, } #[derive(Serialize, Debug)] #[serde(rename_all = "snake_case")] pub enum StripeDisputeStatus { WarningNeedsResponse, WarningUnderReview, WarningClosed, NeedsResponse, UnderReview, ChargeRefunded, Won, Lost, } impl From<api_models::disputes::DisputeResponse> for StripeDisputeResponse { fn from(res: api_models::disputes::DisputeResponse) -> Self { Self { id: res.dispute_id, amount: res.amount.to_string(), currency: res.currency, payment_intent: res.payment_id, reason: res.connector_reason, status: StripeDisputeStatus::from(res.dispute_status), } } } impl From<api_models::mandates::MandateResponse> for StripeMandateResponse { fn from(res: api_models::mandates::MandateResponse) -> Self { Self { mandate_id: res.mandate_id, payment_method: res.payment_method, payment_method_id: res.payment_method_id, status: StripeMandateStatus::from(res.status), } } } impl From<MandateStatus> for StripeMandateStatus { fn from(status: MandateStatus) -> Self { match status { MandateStatus::Active => Self::Active, MandateStatus::Inactive | MandateStatus::Revoked => Self::Inactive, MandateStatus::Pending => Self::Pending, } } } impl From<DisputeStatus> for StripeDisputeStatus { fn from(status: DisputeStatus) -> Self { match status { DisputeStatus::DisputeOpened => Self::WarningNeedsResponse, DisputeStatus::DisputeExpired => Self::Lost, DisputeStatus::DisputeAccepted => Self::Lost, DisputeStatus::DisputeCancelled => Self::WarningClosed, DisputeStatus::DisputeChallenged => Self::WarningUnderReview, DisputeStatus::DisputeWon => Self::Won, DisputeStatus::DisputeLost => Self::Lost, } } } fn get_stripe_event_type(event_type: api_models::enums::EventType) -> &'static str { match event_type { api_models::enums::EventType::PaymentSucceeded => "payment_intent.succeeded", api_models::enums::EventType::PaymentFailed => "payment_intent.payment_failed", api_models::enums::EventType::PaymentProcessing | api_models::enums::EventType::PaymentPartiallyAuthorized => "payment_intent.processing", api_models::enums::EventType::PaymentCancelled | api_models::enums::EventType::PaymentCancelledPostCapture | api_models::enums::EventType::PaymentExpired => "payment_intent.canceled", // the below are not really stripe compatible because stripe doesn't provide this api_models::enums::EventType::ActionRequired => "action.required", api_models::enums::EventType::RefundSucceeded => "refund.succeeded", api_models::enums::EventType::RefundFailed => "refund.failed", api_models::enums::EventType::DisputeOpened => "dispute.failed", api_models::enums::EventType::DisputeExpired => "dispute.expired", api_models::enums::EventType::DisputeAccepted => "dispute.accepted", api_models::enums::EventType::DisputeCancelled => "dispute.cancelled", api_models::enums::EventType::DisputeChallenged => "dispute.challenged", api_models::enums::EventType::DisputeWon => "dispute.won", api_models::enums::EventType::DisputeLost => "dispute.lost", api_models::enums::EventType::MandateActive => "mandate.active", api_models::enums::EventType::MandateRevoked => "mandate.revoked", // as per this doc https://stripe.com/docs/api/events/types#event_types-payment_intent.amount_capturable_updated api_models::enums::EventType::PaymentAuthorized => { "payment_intent.amount_capturable_updated" } // stripe treats partially captured payments as succeeded. api_models::enums::EventType::PaymentCaptured => "payment_intent.succeeded", api_models::enums::EventType::PayoutSuccess => "payout.paid", api_models::enums::EventType::PayoutFailed => "payout.failed", api_models::enums::EventType::PayoutInitiated => "payout.created", api_models::enums::EventType::PayoutCancelled => "payout.canceled", api_models::enums::EventType::PayoutProcessing => "payout.created", api_models::enums::EventType::PayoutExpired => "payout.failed", api_models::enums::EventType::PayoutReversed => "payout.reconciliation_completed", } } impl From<api::OutgoingWebhook> for StripeOutgoingWebhook { fn from(value: api::OutgoingWebhook) -> Self { Self { id: value.event_id, stype: get_stripe_event_type(value.event_type), data: StripeWebhookObject::from(value.content), object: "event", // put this conversion it into a function created: u64::try_from(value.timestamp.assume_utc().unix_timestamp()).unwrap_or_else( |error| { logger::error!( %error, "incorrect value for `webhook.timestamp` provided {}", value.timestamp ); // Current timestamp converted to Unix timestamp should have a positive value // for many years to come u64::try_from(date_time::now().assume_utc().unix_timestamp()) .unwrap_or_default() }, ), } } } impl From<api::OutgoingWebhookContent> for StripeWebhookObject { fn from(value: api::OutgoingWebhookContent) -> Self { match value { api::OutgoingWebhookContent::PaymentDetails(payment) => { Self::PaymentIntent(Box::new((*payment).into())) } api::OutgoingWebhookContent::RefundDetails(refund) => Self::Refund((*refund).into()), api::OutgoingWebhookContent::DisputeDetails(dispute) => { Self::Dispute((*dispute).into()) } api::OutgoingWebhookContent::MandateDetails(mandate) => { Self::Mandate((*mandate).into()) } #[cfg(feature = "payouts")] api::OutgoingWebhookContent::PayoutDetails(payout) => Self::Payout((*payout).into()), } } }
crates/router/src/compatibility/stripe/webhooks.rs
router::src::compatibility::stripe::webhooks
3,024
true
// File: crates/router/src/compatibility/stripe/errors.rs // Module: router::src::compatibility::stripe::errors use common_utils::{errors::ErrorSwitch, id_type}; use hyperswitch_domain_models::errors::api_error_response as errors; use crate::core::errors::CustomersErrorResponse; #[derive(Debug, router_derive::ApiError, Clone)] #[error(error_type_enum = StripeErrorType)] pub enum StripeErrorCode { /* "error": { "message": "Invalid API Key provided: sk_jkjgs****nlgs", "type": "invalid_request_error" } */ #[error( error_type = StripeErrorType::InvalidRequestError, code = "IR_01", message = "Invalid API Key provided" )] Unauthorized, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_02", message = "Unrecognized request URL.")] InvalidRequestUrl, #[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Missing required param: {field_name}.")] ParameterMissing { field_name: String, param: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "parameter_unknown", message = "{field_name} contains invalid data. Expected format is {expected_format}." )] ParameterUnknown { field_name: String, expected_format: String, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_06", message = "The refund amount exceeds the amount captured.")] RefundAmountExceedsPaymentAmount { param: String }, #[error(error_type = StripeErrorType::ApiError, code = "payment_intent_authentication_failure", message = "Payment failed while processing with connector. Retry payment.")] PaymentIntentAuthenticationFailure { data: Option<serde_json::Value> }, #[error(error_type = StripeErrorType::ApiError, code = "payment_intent_payment_attempt_failed", message = "Capture attempt failed while processing with connector.")] PaymentIntentPaymentAttemptFailed { data: Option<serde_json::Value> }, #[error(error_type = StripeErrorType::ApiError, code = "dispute_failure", message = "Dispute failed while processing with connector. Retry operation.")] DisputeFailed { data: Option<serde_json::Value> }, #[error(error_type = StripeErrorType::CardError, code = "expired_card", message = "Card Expired. Please use another card")] ExpiredCard, #[error(error_type = StripeErrorType::CardError, code = "invalid_card_type", message = "Card data is invalid")] InvalidCardType, #[error( error_type = StripeErrorType::ConnectorError, code = "invalid_wallet_token", message = "Invalid {wallet_name} wallet token" )] InvalidWalletToken { wallet_name: String }, #[error(error_type = StripeErrorType::ApiError, code = "refund_failed", message = "refund has failed")] RefundFailed, // stripe error code #[error(error_type = StripeErrorType::ApiError, code = "payout_failed", message = "payout has failed")] PayoutFailed, #[error(error_type = StripeErrorType::ApiError, code = "external_vault_failed", message = "external vault has failed")] ExternalVaultFailed, #[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")] InternalServerError, #[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")] DuplicateRefundRequest, #[error(error_type = StripeErrorType::InvalidRequestError, code = "active_mandate", message = "Customer has active mandate")] MandateActive, #[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_redacted", message = "Customer has redacted")] CustomerRedacted, #[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_already_exists", message = "Customer with the given customer_id already exists")] DuplicateCustomer, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such refund")] RefundNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "client_secret_invalid", message = "Expected client secret to be included in the request")] ClientSecretNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such customer")] CustomerNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such config")] ConfigNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "Duplicate config")] DuplicateConfig, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment")] PaymentNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment method")] PaymentMethodNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "{message}")] GenericNotFoundError { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "{message}")] GenericDuplicateError { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such merchant account")] MerchantAccountNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such resource ID")] ResourceIdNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "Merchant connector account does not exist in our records")] MerchantConnectorAccountNotFound { id: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "invalid_request", message = "The merchant connector account is disabled")] MerchantConnectorAccountDisabled, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such mandate")] MandateNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such API key")] ApiKeyNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payout")] PayoutNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such event")] EventNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "Duplicate payout request")] DuplicatePayout { payout_id: id_type::PayoutId }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Return url is not available")] ReturnUrlUnavailable, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate merchant account")] DuplicateMerchantAccount, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_label}' already exists in our records")] DuplicateMerchantConnectorAccount { profile_id: String, connector_label: String, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate payment method")] DuplicatePaymentMethod, #[error(error_type = StripeErrorType::InvalidRequestError, code = "" , message = "deserialization failed: {error_message}")] SerdeQsError { error_message: String, param: Option<String>, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_intent_invalid_parameter" , message = "The client_secret provided does not match the client_secret associated with the PaymentIntent.")] PaymentIntentInvalidParameter { param: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "IR_05", message = "{message}" )] InvalidRequestData { message: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "IR_10", message = "{message}" )] PreconditionFailed { message: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "", message = "The payment has not succeeded yet" )] PaymentFailed, #[error( error_type = StripeErrorType::InvalidRequestError, code = "", message = "The verification did not succeeded" )] VerificationFailed { data: Option<serde_json::Value> }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "", message = "Reached maximum refund attempts" )] MaximumRefundCount, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID.")] DuplicateMandate, #[error(error_type= StripeErrorType::InvalidRequestError, code = "", message = "Successful payment not found for the given payment id")] SuccessfulPaymentNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Address does not exist in our records.")] AddressNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "This PaymentIntent could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}.")] PaymentIntentUnexpectedState { current_flow: String, field_name: String, current_value: String, states: String, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The mandate information is invalid. {message}")] PaymentIntentMandateInvalid { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The payment with the specified payment_id already exists in our records.")] DuplicatePayment { payment_id: id_type::PaymentId }, #[error(error_type = StripeErrorType::ConnectorError, code = "", message = "{code}: {message}")] ExternalConnectorError { code: String, message: String, connector: String, status_code: u16, }, #[error(error_type = StripeErrorType::CardError, code = "", message = "{code}: {message}")] PaymentBlockedError { code: u16, message: String, status: String, reason: String, }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "The connector provided in the request is incorrect or not available")] IncorrectConnectorNameGiven, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "No such {object}: '{id}'")] ResourceMissing { object: String, id: String }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File validation failed")] FileValidationFailed, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not found in the request")] MissingFile, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File puropse not found in the request")] MissingFilePurpose, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File content type not found")] MissingFileContentType, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Dispute id not found in the request")] MissingDisputeId, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File does not exists in our records")] FileNotFound, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not available")] FileNotAvailable, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Not Supported because provider is not Router")] FileProviderNotSupported, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "There was an issue with processing webhooks")] WebhookProcessingError, #[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_method_unactivated", message = "The operation cannot be performed as the payment method used has not been activated. Activate the payment method in the Dashboard, then try again.")] PaymentMethodUnactivated, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "{message}")] HyperswitchUnprocessableEntity { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "{message}")] CurrencyNotSupported { message: String }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Payment Link does not exist in our records")] PaymentLinkNotFound, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Resource Busy. Please try again later")] LockTimeout, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Merchant connector account is configured with invalid {config}")] InvalidConnectorConfiguration { config: String }, #[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert currency to minor unit")] CurrencyConversionFailed, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")] PaymentMethodDeleteFailed, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Extended card info does not exist")] ExtendedCardInfoNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "not_configured", message = "{message}")] LinkConfigurationError { message: String }, #[error(error_type = StripeErrorType::ConnectorError, code = "CE", message = "{reason} as data mismatched for {field_names}")] IntegrityCheckFailed { reason: String, field_names: String, connector_transaction_id: Option<String>, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_28", message = "Invalid tenant")] InvalidTenant, #[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert amount to {amount_type} type")] AmountConversionFailed { amount_type: &'static str }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Bad Request")] PlatformBadRequest, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Unauthorized Request")] PlatformUnauthorizedRequest, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Profile Acquirer not found")] ProfileAcquirerNotFound, #[error(error_type = StripeErrorType::HyperswitchError, code = "Subscription Error", message = "Subscription operation: {operation} failed with connector")] SubscriptionError { operation: String }, // [#216]: https://github.com/juspay/hyperswitch/issues/216 // Implement the remaining stripe error codes /* AccountCountryInvalidAddress, AccountErrorCountryChangeRequiresAdditionalSteps, AccountInformationMismatch, AccountInvalid, AccountNumberInvalid, AcssDebitSessionIncomplete, AlipayUpgradeRequired, AmountTooLarge, AmountTooSmall, ApiKeyExpired, AuthenticationRequired, BalanceInsufficient, BankAccountBadRoutingNumbers, BankAccountDeclined, BankAccountExists, BankAccountUnusable, BankAccountUnverified, BankAccountVerificationFailed, BillingInvalidMandate, BitcoinUpgradeRequired, CardDeclineRateLimitExceeded, CardDeclined, CardholderPhoneNumberRequired, ChargeAlreadyCaptured, ChargeAlreadyRefunded, ChargeDisputed, ChargeExceedsSourceLimit, ChargeExpiredForCapture, ChargeInvalidParameter, ClearingCodeUnsupported, CountryCodeInvalid, CountryUnsupported, CouponExpired, CustomerMaxPaymentMethods, CustomerMaxSubscriptions, DebitNotAuthorized, EmailInvalid, ExpiredCard, IdempotencyKeyInUse, IncorrectAddress, IncorrectCvc, IncorrectNumber, IncorrectZip, InstantPayoutsConfigDisabled, InstantPayoutsCurrencyDisabled, InstantPayoutsLimitExceeded, InstantPayoutsUnsupported, InsufficientFunds, IntentInvalidState, IntentVerificationMethodMissing, InvalidCardType, InvalidCharacters, InvalidChargeAmount, InvalidCvc, InvalidExpiryMonth, InvalidExpiryYear, InvalidNumber, InvalidSourceUsage, InvoiceNoCustomerLineItems, InvoiceNoPaymentMethodTypes, InvoiceNoSubscriptionLineItems, InvoiceNotEditable, InvoiceOnBehalfOfNotEditable, InvoicePaymentIntentRequiresAction, InvoiceUpcomingNone, LivemodeMismatch, LockTimeout, Missing, NoAccount, NotAllowedOnStandardAccount, OutOfInventory, ParameterInvalidEmpty, ParameterInvalidInteger, ParameterInvalidStringBlank, ParameterInvalidStringEmpty, ParametersExclusive, PaymentIntentActionRequired, PaymentIntentIncompatiblePaymentMethod, PaymentIntentInvalidParameter, PaymentIntentKonbiniRejectedConfirmationNumber, PaymentIntentPaymentAttemptExpired, PaymentIntentUnexpectedState, PaymentMethodBankAccountAlreadyVerified, PaymentMethodBankAccountBlocked, PaymentMethodBillingDetailsAddressMissing, PaymentMethodCurrencyMismatch, PaymentMethodInvalidParameter, PaymentMethodInvalidParameterTestmode, PaymentMethodMicrodepositFailed, PaymentMethodMicrodepositVerificationAmountsInvalid, PaymentMethodMicrodepositVerificationAmountsMismatch, PaymentMethodMicrodepositVerificationAttemptsExceeded, PaymentMethodMicrodepositVerificationDescriptorCodeMismatch, PaymentMethodMicrodepositVerificationTimeout, PaymentMethodProviderDecline, PaymentMethodProviderTimeout, PaymentMethodUnexpectedState, PaymentMethodUnsupportedType, PayoutsNotAllowed, PlatformAccountRequired, PlatformApiKeyExpired, PostalCodeInvalid, ProcessingError, ProductInactive, RateLimit, ReferToCustomer, RefundDisputedPayment, ResourceAlreadyExists, ResourceMissing, ReturnIntentAlreadyProcessed, RoutingNumberInvalid, SecretKeyRequired, SepaUnsupportedAccount, SetupAttemptFailed, SetupIntentAuthenticationFailure, SetupIntentInvalidParameter, SetupIntentSetupAttemptExpired, SetupIntentUnexpectedState, ShippingCalculationFailed, SkuInactive, StateUnsupported, StatusTransitionInvalid, TaxIdInvalid, TaxesCalculationFailed, TerminalLocationCountryUnsupported, TestmodeChargesOnly, TlsVersionUnsupported, TokenInUse, TransferSourceBalanceParametersMismatch, TransfersNotAllowed, */ } impl ::core::fmt::Display for StripeErrorCode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{{\"error\": {}}}", serde_json::to_string(self).unwrap_or_else(|_| "API error response".to_string()) ) } } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] #[allow(clippy::enum_variant_names)] pub enum StripeErrorType { ApiError, CardError, InvalidRequestError, ConnectorError, HyperswitchError, } impl From<errors::ApiErrorResponse> for StripeErrorCode { fn from(value: errors::ApiErrorResponse) -> Self { match value { errors::ApiErrorResponse::Unauthorized | errors::ApiErrorResponse::InvalidJwtToken | errors::ApiErrorResponse::GenericUnauthorized { .. } | errors::ApiErrorResponse::AccessForbidden { .. } | errors::ApiErrorResponse::InvalidCookie | errors::ApiErrorResponse::InvalidEphemeralKey | errors::ApiErrorResponse::CookieNotFound => Self::Unauthorized, errors::ApiErrorResponse::InvalidRequestUrl | errors::ApiErrorResponse::InvalidHttpMethod | errors::ApiErrorResponse::InvalidCardIin | errors::ApiErrorResponse::InvalidCardIinLength => Self::InvalidRequestUrl, errors::ApiErrorResponse::MissingRequiredField { field_name } => { Self::ParameterMissing { field_name: field_name.to_string(), param: field_name.to_string(), } } errors::ApiErrorResponse::UnprocessableEntity { message } => { Self::HyperswitchUnprocessableEntity { message } } errors::ApiErrorResponse::MissingRequiredFields { field_names } => { // Instead of creating a new error variant in StripeErrorCode for MissingRequiredFields, converted vec<&str> to String Self::ParameterMissing { field_name: field_names.clone().join(", "), param: field_names.clone().join(", "), } } errors::ApiErrorResponse::GenericNotFoundError { message } => { Self::GenericNotFoundError { message } } errors::ApiErrorResponse::GenericDuplicateError { message } => { Self::GenericDuplicateError { message } } // parameter unknown, invalid request error // actually if we type wrong values in address we get this error. Stripe throws parameter unknown. I don't know if stripe is validating email and stuff errors::ApiErrorResponse::InvalidDataFormat { field_name, expected_format, } => Self::ParameterUnknown { field_name, expected_format, }, errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount => { Self::RefundAmountExceedsPaymentAmount { param: "amount".to_owned(), } } errors::ApiErrorResponse::PaymentAuthorizationFailed { data } | errors::ApiErrorResponse::PaymentAuthenticationFailed { data } => { Self::PaymentIntentAuthenticationFailure { data } } errors::ApiErrorResponse::VerificationFailed { data } => { Self::VerificationFailed { data } } errors::ApiErrorResponse::PaymentCaptureFailed { data } => { Self::PaymentIntentPaymentAttemptFailed { data } } errors::ApiErrorResponse::DisputeFailed { data } => Self::DisputeFailed { data }, errors::ApiErrorResponse::InvalidCardData { data: _ } => Self::InvalidCardType, // Maybe it is better to de generalize this router error errors::ApiErrorResponse::CardExpired { data: _ } => Self::ExpiredCard, errors::ApiErrorResponse::RefundNotPossible { connector: _ } => Self::RefundFailed, errors::ApiErrorResponse::RefundFailed { data: _ } => Self::RefundFailed, // Nothing at stripe to map errors::ApiErrorResponse::PayoutFailed { data: _ } => Self::PayoutFailed, errors::ApiErrorResponse::ExternalVaultFailed => Self::ExternalVaultFailed, errors::ApiErrorResponse::MandateUpdateFailed | errors::ApiErrorResponse::MandateSerializationFailed | errors::ApiErrorResponse::MandateDeserializationFailed | errors::ApiErrorResponse::InternalServerError | errors::ApiErrorResponse::HealthCheckError { .. } => Self::InternalServerError, // not a stripe code errors::ApiErrorResponse::ExternalConnectorError { code, message, connector, status_code, .. } => Self::ExternalConnectorError { code, message, connector, status_code, }, errors::ApiErrorResponse::IncorrectConnectorNameGiven => { Self::IncorrectConnectorNameGiven } errors::ApiErrorResponse::MandateActive => Self::MandateActive, //not a stripe code errors::ApiErrorResponse::CustomerRedacted => Self::CustomerRedacted, //not a stripe code errors::ApiErrorResponse::ConfigNotFound => Self::ConfigNotFound, // not a stripe code errors::ApiErrorResponse::DuplicateConfig => Self::DuplicateConfig, // not a stripe code errors::ApiErrorResponse::DuplicateRefundRequest => Self::DuplicateRefundRequest, errors::ApiErrorResponse::DuplicatePayout { payout_id } => { Self::DuplicatePayout { payout_id } } errors::ApiErrorResponse::RefundNotFound => Self::RefundNotFound, errors::ApiErrorResponse::CustomerNotFound => Self::CustomerNotFound, errors::ApiErrorResponse::PaymentNotFound => Self::PaymentNotFound, errors::ApiErrorResponse::PaymentMethodNotFound => Self::PaymentMethodNotFound, errors::ApiErrorResponse::ClientSecretNotGiven | errors::ApiErrorResponse::ClientSecretExpired => Self::ClientSecretNotFound, errors::ApiErrorResponse::MerchantAccountNotFound => Self::MerchantAccountNotFound, errors::ApiErrorResponse::PaymentLinkNotFound => Self::PaymentLinkNotFound, errors::ApiErrorResponse::ResourceIdNotFound => Self::ResourceIdNotFound, errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id } => { Self::MerchantConnectorAccountNotFound { id } } errors::ApiErrorResponse::MandateNotFound => Self::MandateNotFound, errors::ApiErrorResponse::ApiKeyNotFound => Self::ApiKeyNotFound, errors::ApiErrorResponse::PayoutNotFound => Self::PayoutNotFound, errors::ApiErrorResponse::EventNotFound => Self::EventNotFound, errors::ApiErrorResponse::MandateValidationFailed { reason } => { Self::PaymentIntentMandateInvalid { message: reason } } errors::ApiErrorResponse::ReturnUrlUnavailable => Self::ReturnUrlUnavailable, errors::ApiErrorResponse::DuplicateMerchantAccount => Self::DuplicateMerchantAccount, errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { profile_id, connector_label, } => Self::DuplicateMerchantConnectorAccount { profile_id, connector_label, }, errors::ApiErrorResponse::DuplicatePaymentMethod => Self::DuplicatePaymentMethod, errors::ApiErrorResponse::PaymentBlockedError { code, message, status, reason, } => Self::PaymentBlockedError { code, message, status, reason, }, errors::ApiErrorResponse::ClientSecretInvalid => Self::PaymentIntentInvalidParameter { param: "client_secret".to_owned(), }, errors::ApiErrorResponse::InvalidRequestData { message } => { Self::InvalidRequestData { message } } errors::ApiErrorResponse::PreconditionFailed { message } => { Self::PreconditionFailed { message } } errors::ApiErrorResponse::InvalidDataValue { field_name } => Self::ParameterMissing { field_name: field_name.to_string(), param: field_name.to_string(), }, errors::ApiErrorResponse::MaximumRefundCount => Self::MaximumRefundCount, errors::ApiErrorResponse::PaymentNotSucceeded => Self::PaymentFailed, errors::ApiErrorResponse::DuplicateMandate => Self::DuplicateMandate, errors::ApiErrorResponse::SuccessfulPaymentNotFound => Self::SuccessfulPaymentNotFound, errors::ApiErrorResponse::AddressNotFound => Self::AddressNotFound, errors::ApiErrorResponse::NotImplemented { .. } => Self::Unauthorized, errors::ApiErrorResponse::FlowNotSupported { .. } => Self::InternalServerError, errors::ApiErrorResponse::MandatePaymentDataMismatch { .. } => Self::PlatformBadRequest, errors::ApiErrorResponse::MaxFieldLengthViolated { .. } => Self::PlatformBadRequest, errors::ApiErrorResponse::PaymentUnexpectedState { current_flow, field_name, current_value, states, } => Self::PaymentIntentUnexpectedState { current_flow, field_name, current_value, states, }, errors::ApiErrorResponse::DuplicatePayment { payment_id } => { Self::DuplicatePayment { payment_id } } errors::ApiErrorResponse::DisputeNotFound { dispute_id } => Self::ResourceMissing { object: "dispute".to_owned(), id: dispute_id, }, errors::ApiErrorResponse::AuthenticationNotFound { id } => Self::ResourceMissing { object: "authentication".to_owned(), id, }, errors::ApiErrorResponse::ProfileNotFound { id } => Self::ResourceMissing { object: "business_profile".to_owned(), id, }, errors::ApiErrorResponse::PollNotFound { id } => Self::ResourceMissing { object: "poll".to_owned(), id, }, errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: _ } => { Self::InternalServerError } errors::ApiErrorResponse::FileValidationFailed { .. } => Self::FileValidationFailed, errors::ApiErrorResponse::MissingFile => Self::MissingFile, errors::ApiErrorResponse::MissingFilePurpose => Self::MissingFilePurpose, errors::ApiErrorResponse::MissingFileContentType => Self::MissingFileContentType, errors::ApiErrorResponse::MissingDisputeId => Self::MissingDisputeId, errors::ApiErrorResponse::FileNotFound => Self::FileNotFound, errors::ApiErrorResponse::FileNotAvailable => Self::FileNotAvailable, errors::ApiErrorResponse::MerchantConnectorAccountDisabled => { Self::MerchantConnectorAccountDisabled } errors::ApiErrorResponse::NotSupported { .. } => Self::InternalServerError, errors::ApiErrorResponse::CurrencyNotSupported { message } => { Self::CurrencyNotSupported { message } } errors::ApiErrorResponse::FileProviderNotSupported { .. } => { Self::FileProviderNotSupported } errors::ApiErrorResponse::WebhookBadRequest | errors::ApiErrorResponse::WebhookResourceNotFound | errors::ApiErrorResponse::WebhookProcessingFailure | errors::ApiErrorResponse::WebhookAuthenticationFailed | errors::ApiErrorResponse::WebhookUnprocessableEntity | errors::ApiErrorResponse::WebhookInvalidMerchantSecret => { Self::WebhookProcessingError } errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration => { Self::PaymentMethodUnactivated } errors::ApiErrorResponse::ResourceBusy => Self::PaymentMethodUnactivated, errors::ApiErrorResponse::InvalidConnectorConfiguration { config } => { Self::InvalidConnectorConfiguration { config } } errors::ApiErrorResponse::CurrencyConversionFailed => Self::CurrencyConversionFailed, errors::ApiErrorResponse::PaymentMethodDeleteFailed => Self::PaymentMethodDeleteFailed, errors::ApiErrorResponse::InvalidWalletToken { wallet_name } => { Self::InvalidWalletToken { wallet_name } } errors::ApiErrorResponse::ExtendedCardInfoNotFound => Self::ExtendedCardInfoNotFound, errors::ApiErrorResponse::LinkConfigurationError { message } => { Self::LinkConfigurationError { message } } errors::ApiErrorResponse::IntegrityCheckFailed { reason, field_names, connector_transaction_id, } => Self::IntegrityCheckFailed { reason, field_names, connector_transaction_id, }, errors::ApiErrorResponse::InvalidTenant { tenant_id: _ } | errors::ApiErrorResponse::MissingTenantId => Self::InvalidTenant, errors::ApiErrorResponse::AmountConversionFailed { amount_type } => { Self::AmountConversionFailed { amount_type } } errors::ApiErrorResponse::PlatformAccountAuthNotSupported => Self::PlatformBadRequest, errors::ApiErrorResponse::InvalidPlatformOperation => Self::PlatformUnauthorizedRequest, errors::ApiErrorResponse::ProfileAcquirerNotFound { .. } => { Self::ProfileAcquirerNotFound } errors::ApiErrorResponse::TokenizationRecordNotFound { id } => Self::ResourceMissing { object: "tokenization record".to_owned(), id, }, errors::ApiErrorResponse::SubscriptionError { operation } => { Self::SubscriptionError { operation } } } } } impl actix_web::ResponseError for StripeErrorCode { fn status_code(&self) -> reqwest::StatusCode { use reqwest::StatusCode; match self { Self::Unauthorized | Self::PlatformUnauthorizedRequest => StatusCode::UNAUTHORIZED, Self::InvalidRequestUrl | Self::GenericNotFoundError { .. } => StatusCode::NOT_FOUND, Self::ParameterUnknown { .. } | Self::HyperswitchUnprocessableEntity { .. } => { StatusCode::UNPROCESSABLE_ENTITY } Self::ParameterMissing { .. } | Self::RefundAmountExceedsPaymentAmount { .. } | Self::PaymentIntentAuthenticationFailure { .. } | Self::PaymentIntentPaymentAttemptFailed { .. } | Self::ExpiredCard | Self::InvalidCardType | Self::DuplicateRefundRequest | Self::DuplicatePayout { .. } | Self::RefundNotFound | Self::CustomerNotFound | Self::ConfigNotFound | Self::DuplicateConfig | Self::ClientSecretNotFound | Self::PaymentNotFound | Self::PaymentMethodNotFound | Self::MerchantAccountNotFound | Self::MerchantConnectorAccountNotFound { .. } | Self::MerchantConnectorAccountDisabled | Self::MandateNotFound | Self::ApiKeyNotFound | Self::PayoutNotFound | Self::EventNotFound | Self::DuplicateMerchantAccount | Self::DuplicateMerchantConnectorAccount { .. } | Self::DuplicatePaymentMethod | Self::PaymentFailed | Self::VerificationFailed { .. } | Self::DisputeFailed { .. } | Self::MaximumRefundCount | Self::PaymentIntentInvalidParameter { .. } | Self::SerdeQsError { .. } | Self::InvalidRequestData { .. } | Self::InvalidWalletToken { .. } | Self::PreconditionFailed { .. } | Self::DuplicateMandate | Self::SuccessfulPaymentNotFound | Self::AddressNotFound | Self::ResourceIdNotFound | Self::PaymentIntentMandateInvalid { .. } | Self::PaymentIntentUnexpectedState { .. } | Self::DuplicatePayment { .. } | Self::GenericDuplicateError { .. } | Self::IncorrectConnectorNameGiven | Self::ResourceMissing { .. } | Self::FileValidationFailed | Self::MissingFile | Self::MissingFileContentType | Self::MissingFilePurpose | Self::MissingDisputeId | Self::FileNotFound | Self::FileNotAvailable | Self::FileProviderNotSupported | Self::CurrencyNotSupported { .. } | Self::DuplicateCustomer | Self::PaymentMethodUnactivated | Self::InvalidConnectorConfiguration { .. } | Self::CurrencyConversionFailed | Self::PaymentMethodDeleteFailed | Self::ExtendedCardInfoNotFound | Self::PlatformBadRequest | Self::LinkConfigurationError { .. } => StatusCode::BAD_REQUEST, Self::RefundFailed | Self::PayoutFailed | Self::PaymentLinkNotFound | Self::InternalServerError | Self::MandateActive | Self::CustomerRedacted | Self::WebhookProcessingError | Self::InvalidTenant | Self::ExternalVaultFailed | Self::AmountConversionFailed { .. } | Self::SubscriptionError { .. } => StatusCode::INTERNAL_SERVER_ERROR, Self::ReturnUrlUnavailable => StatusCode::SERVICE_UNAVAILABLE, Self::ExternalConnectorError { status_code, .. } => { StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR) } Self::IntegrityCheckFailed { .. } => StatusCode::INTERNAL_SERVER_ERROR, Self::PaymentBlockedError { code, .. } => { StatusCode::from_u16(*code).unwrap_or(StatusCode::OK) } Self::LockTimeout => StatusCode::LOCKED, Self::ProfileAcquirerNotFound => StatusCode::NOT_FOUND, } } fn error_response(&self) -> actix_web::HttpResponse { use actix_web::http::header; actix_web::HttpResponseBuilder::new(self.status_code()) .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) .body(self.to_string()) } } impl From<serde_qs::Error> for StripeErrorCode { fn from(item: serde_qs::Error) -> Self { match item { serde_qs::Error::Custom(s) => Self::SerdeQsError { error_message: s, param: None, }, serde_qs::Error::Parse(param, position) => Self::SerdeQsError { error_message: format!( "parsing failed with error: '{param}' at position: {position}" ), param: Some(param), }, serde_qs::Error::Unsupported => Self::SerdeQsError { error_message: "Given request format is not supported".to_owned(), param: None, }, serde_qs::Error::FromUtf8(_) => Self::SerdeQsError { error_message: "Failed to parse request to from utf-8".to_owned(), param: None, }, serde_qs::Error::Io(_) => Self::SerdeQsError { error_message: "Failed to parse request".to_owned(), param: None, }, serde_qs::Error::ParseInt(_) => Self::SerdeQsError { error_message: "Failed to parse integer in request".to_owned(), param: None, }, serde_qs::Error::Utf8(_) => Self::SerdeQsError { error_message: "Failed to convert utf8 to string".to_owned(), param: None, }, } } } impl ErrorSwitch<StripeErrorCode> for errors::ApiErrorResponse { fn switch(&self) -> StripeErrorCode { self.clone().into() } } impl crate::services::EmbedError for error_stack::Report<StripeErrorCode> {} impl ErrorSwitch<StripeErrorCode> for CustomersErrorResponse { fn switch(&self) -> StripeErrorCode { use StripeErrorCode as SC; match self { Self::CustomerRedacted => SC::CustomerRedacted, Self::InternalServerError => SC::InternalServerError, Self::InvalidRequestData { message } => SC::InvalidRequestData { message: message.clone(), }, Self::MandateActive => SC::MandateActive, Self::CustomerNotFound => SC::CustomerNotFound, Self::CustomerAlreadyExists => SC::DuplicateCustomer, } } }
crates/router/src/compatibility/stripe/errors.rs
router::src::compatibility::stripe::errors
8,333
true
// File: crates/router/src/compatibility/stripe/customers.rs // Module: router::src::compatibility::stripe::customers pub mod types; #[cfg(feature = "v1")] use actix_web::{web, HttpRequest, HttpResponse}; #[cfg(feature = "v1")] use common_utils::id_type; #[cfg(feature = "v1")] use error_stack::report; #[cfg(feature = "v1")] use router_env::{instrument, tracing, Flow}; #[cfg(feature = "v1")] use crate::{ compatibility::{stripe::errors, wrap}, core::{api_locking, customers, payment_methods::cards}, routes, services::{api, authentication as auth}, types::{ api::{customers as customer_types, payment_methods}, domain, }, }; #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))] pub async fn customer_create( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { let payload: types::CreateCustomerRequest = match qs_config.deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; let create_cust_req: customer_types::CustomerRequest = payload.into(); let flow = Flow::CustomersCreate; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::CreateCustomerResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, create_cust_req, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); customers::create_customer(state, merchant_context, req, None) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::CustomersRetrieve))] pub async fn customer_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<id_type::CustomerId>, ) -> HttpResponse { let customer_id = path.into_inner(); let flow = Flow::CustomersRetrieve; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::CustomerRetrieveResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, customer_id, |state, auth: auth::AuthenticationData, customer_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); customers::retrieve_customer(state, merchant_context, None, customer_id) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::CustomersUpdate))] pub async fn customer_update( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, path: web::Path<id_type::CustomerId>, form_payload: web::Bytes, ) -> HttpResponse { let payload: types::CustomerUpdateRequest = match qs_config.deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; let customer_id = path.into_inner().clone(); let request = customer_types::CustomerUpdateRequest::from(payload); let request_internal = customer_types::CustomerUpdateRequestInternal { customer_id, request, }; let flow = Flow::CustomersUpdate; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::CustomerUpdateResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, request_internal, |state, auth: auth::AuthenticationData, request_internal, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); customers::update_customer(state, merchant_context, request_internal) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::CustomersDelete))] pub async fn customer_delete( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<id_type::CustomerId>, ) -> HttpResponse { let customer_id = path.into_inner(); let flow = Flow::CustomersDelete; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::CustomerDeleteResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, customer_id, |state, auth: auth::AuthenticationData, customer_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); customers::delete_customer(state, merchant_context, customer_id) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))] pub async fn list_customer_payment_method_api( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<id_type::CustomerId>, json_payload: web::Query<payment_methods::PaymentMethodListRequest>, ) -> HttpResponse { let payload = json_payload.into_inner(); let customer_id = path.into_inner(); let flow = Flow::CustomerPaymentMethodsList; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::CustomerPaymentMethodListResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); cards::do_list_customer_pm_fetch_customer_if_not_passed( state, merchant_context, Some(req), Some(&customer_id), None, ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/compatibility/stripe/customers.rs
router::src::compatibility::stripe::customers
1,654
true
// File: crates/router/src/compatibility/stripe/setup_intents.rs // Module: router::src::compatibility::stripe::setup_intents pub mod types; #[cfg(feature = "v1")] use actix_web::{web, HttpRequest, HttpResponse}; #[cfg(feature = "v1")] use api_models::payments as payment_types; #[cfg(feature = "v1")] use error_stack::report; #[cfg(feature = "v1")] use router_env::{instrument, tracing, Flow}; #[cfg(feature = "v1")] use crate::{ compatibility::{ stripe::{errors, payment_intents::types as stripe_payment_types}, wrap, }, core::{api_locking, payments}, routes, services::{api, authentication as auth}, types::{api as api_types, domain}, }; #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCreate))] pub async fn setup_intents_create( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { let payload: types::StripeSetupIntentRequest = match qs_config.deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; let create_payment_req: payment_types::PaymentsRequest = match payment_types::PaymentsRequest::try_from(payload) { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; let flow = Flow::PaymentsCreate; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeSetupIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, create_payment_req, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::SetupMandate, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::SetupMandate>, >( state, req_state, merchant_context, None, payments::PaymentCreate, req, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieveForceSync))] pub async fn setup_intents_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::PaymentId>, query_payload: web::Query<stripe_payment_types::StripePaymentRetrieveBody>, ) -> HttpResponse { let payload = payment_types::PaymentsRetrieveRequest { resource_id: api_types::PaymentIdType::PaymentIntentId(path.into_inner()), merchant_id: None, force_sync: true, connector: None, param: None, merchant_connector_details: None, client_secret: query_payload.client_secret.clone(), expand_attempts: None, expand_captures: None, all_keys_required: None, }; let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let flow = Flow::PaymentsRetrieveForceSync; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeSetupIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, payload, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::PSync, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::PSync>, >( state, req_state, merchant_context, None, payments::PaymentStatus, payload, auth_flow, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &*auth_type, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdate))] pub async fn setup_intents_update( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let setup_id = path.into_inner(); let stripe_payload: types::StripeSetupIntentRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; let mut payload: payment_types::PaymentsRequest = match payment_types::PaymentsRequest::try_from(stripe_payload) { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id)); let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; let flow = Flow::PaymentsUpdate; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeSetupIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::SetupMandate, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::SetupMandate>, >( state, req_state, merchant_context, None, payments::PaymentUpdate, req, auth_flow, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &*auth_type, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm))] pub async fn setup_intents_confirm( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let setup_id = path.into_inner(); let stripe_payload: types::StripeSetupIntentRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; let mut payload: payment_types::PaymentsRequest = match payment_types::PaymentsRequest::try_from(stripe_payload) { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id)); payload.confirm = Some(true); let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; let flow = Flow::PaymentsConfirm; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeSetupIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::SetupMandate, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::SetupMandate>, >( state, req_state, merchant_context, None, payments::PaymentConfirm, req, auth_flow, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &*auth_type, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/compatibility/stripe/setup_intents.rs
router::src::compatibility::stripe::setup_intents
2,240
true
// File: crates/router/src/compatibility/stripe/app.rs // Module: router::src::compatibility::stripe::app use actix_web::{web, Scope}; #[cfg(feature = "v1")] use super::{customers::*, payment_intents::*, setup_intents::*}; use super::{refunds::*, webhooks::*}; use crate::routes::{self, mandates, webhooks}; pub struct PaymentIntents; #[cfg(feature = "v1")] impl PaymentIntents { pub fn server(state: routes::AppState) -> Scope { let mut route = web::scope("/payment_intents").app_data(web::Data::new(state)); #[cfg(feature = "olap")] { route = route.service(web::resource("/list").route(web::get().to(payment_intent_list))) } route = route .service(web::resource("").route(web::post().to(payment_intents_create))) .service( web::resource("/sync") .route(web::post().to(payment_intents_retrieve_with_gateway_creds)), ) .service( web::resource("/{payment_id}") .route(web::get().to(payment_intents_retrieve)) .route(web::post().to(payment_intents_update)), ) .service( web::resource("/{payment_id}/confirm") .route(web::post().to(payment_intents_confirm)), ) .service( web::resource("/{payment_id}/capture") .route(web::post().to(payment_intents_capture)), ) .service( web::resource("/{payment_id}/cancel").route(web::post().to(payment_intents_cancel)), ); route } } pub struct SetupIntents; #[cfg(feature = "v1")] impl SetupIntents { pub fn server(state: routes::AppState) -> Scope { web::scope("/setup_intents") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(setup_intents_create))) .service( web::resource("/{setup_id}") .route(web::get().to(setup_intents_retrieve)) .route(web::post().to(setup_intents_update)), ) .service( web::resource("/{setup_id}/confirm").route(web::post().to(setup_intents_confirm)), ) } } pub struct Refunds; impl Refunds { pub fn server(config: routes::AppState) -> Scope { web::scope("/refunds") .app_data(web::Data::new(config)) .service(web::resource("").route(web::post().to(refund_create))) .service( web::resource("/sync").route(web::post().to(refund_retrieve_with_gateway_creds)), ) .service( web::resource("/{refund_id}") .route(web::get().to(refund_retrieve)) .route(web::post().to(refund_update)), ) } } pub struct Customers; #[cfg(feature = "v1")] impl Customers { pub fn server(config: routes::AppState) -> Scope { web::scope("/customers") .app_data(web::Data::new(config)) .service(web::resource("").route(web::post().to(customer_create))) .service( web::resource("/{customer_id}") .route(web::get().to(customer_retrieve)) .route(web::post().to(customer_update)) .route(web::delete().to(customer_delete)), ) .service( web::resource("/{customer_id}/payment_methods") .route(web::get().to(list_customer_payment_method_api)), ) } } pub struct Webhooks; impl Webhooks { pub fn server(config: routes::AppState) -> Scope { web::scope("/webhooks") .app_data(web::Data::new(config)) .service( web::resource("/{merchant_id}/{connector_name}") .route( web::post().to(webhooks::receive_incoming_webhook::<StripeOutgoingWebhook>), ) .route( web::get().to(webhooks::receive_incoming_webhook::<StripeOutgoingWebhook>), ), ) } } pub struct Mandates; impl Mandates { pub fn server(config: routes::AppState) -> Scope { web::scope("/payment_methods") .app_data(web::Data::new(config)) .service(web::resource("/{id}/detach").route(web::post().to(mandates::revoke_mandate))) } }
crates/router/src/compatibility/stripe/app.rs
router::src::compatibility::stripe::app
963
true
// File: crates/router/src/compatibility/stripe/customers/types.rs // Module: router::src::compatibility::stripe::customers::types use std::{convert::From, default::Default}; #[cfg(feature = "v1")] use api_models::payment_methods as api_types; use api_models::payments; #[cfg(feature = "v1")] use common_utils::{crypto::Encryptable, date_time}; use common_utils::{ id_type, pii::{self, Email}, types::Description, }; use serde::{Deserialize, Serialize}; #[cfg(feature = "v1")] use crate::logger; use crate::types::{api, api::enums as api_enums}; #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct Shipping { pub address: StripeAddressDetails, pub name: Option<masking::Secret<String>>, pub carrier: Option<String>, pub phone: Option<masking::Secret<String>>, pub tracking_number: Option<masking::Secret<String>>, } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct StripeAddressDetails { pub city: Option<String>, pub country: Option<api_enums::CountryAlpha2>, pub line1: Option<masking::Secret<String>>, pub line2: Option<masking::Secret<String>>, pub postal_code: Option<masking::Secret<String>>, pub state: Option<masking::Secret<String>>, } #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct CreateCustomerRequest { pub email: Option<Email>, pub invoice_prefix: Option<String>, pub name: Option<masking::Secret<String>>, pub phone: Option<masking::Secret<String>>, pub address: Option<StripeAddressDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub description: Option<Description>, pub shipping: Option<Shipping>, pub payment_method: Option<String>, // not used pub balance: Option<i64>, // not used pub cash_balance: Option<pii::SecretSerdeValue>, // not used pub coupon: Option<String>, // not used pub invoice_settings: Option<pii::SecretSerdeValue>, // not used pub next_invoice_sequence: Option<String>, // not used pub preferred_locales: Option<String>, // not used pub promotion_code: Option<String>, // not used pub source: Option<String>, // not used pub tax: Option<pii::SecretSerdeValue>, // not used pub tax_exempt: Option<String>, // not used pub tax_id_data: Option<String>, // not used pub test_clock: Option<String>, // not used } #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct CustomerUpdateRequest { pub description: Option<Description>, pub email: Option<Email>, pub phone: Option<masking::Secret<String, masking::WithType>>, pub name: Option<masking::Secret<String>>, pub address: Option<StripeAddressDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub shipping: Option<Shipping>, pub payment_method: Option<String>, // not used pub balance: Option<i64>, // not used pub cash_balance: Option<pii::SecretSerdeValue>, // not used pub coupon: Option<String>, // not used pub default_source: Option<String>, // not used pub invoice_settings: Option<pii::SecretSerdeValue>, // not used pub next_invoice_sequence: Option<String>, // not used pub preferred_locales: Option<String>, // not used pub promotion_code: Option<String>, // not used pub source: Option<String>, // not used pub tax: Option<pii::SecretSerdeValue>, // not used pub tax_exempt: Option<String>, // not used } #[derive(Serialize, PartialEq, Eq)] pub struct CreateCustomerResponse { pub id: id_type::CustomerId, pub object: String, pub created: u64, pub description: Option<Description>, pub email: Option<Email>, pub metadata: Option<pii::SecretSerdeValue>, pub name: Option<masking::Secret<String>>, pub phone: Option<masking::Secret<String, masking::WithType>>, } pub type CustomerRetrieveResponse = CreateCustomerResponse; pub type CustomerUpdateResponse = CreateCustomerResponse; #[derive(Serialize, PartialEq, Eq)] pub struct CustomerDeleteResponse { pub id: id_type::CustomerId, pub deleted: bool, } impl From<StripeAddressDetails> for payments::AddressDetails { fn from(address: StripeAddressDetails) -> Self { Self { city: address.city, country: address.country, line1: address.line1, line2: address.line2, zip: address.postal_code, state: address.state, first_name: None, line3: None, last_name: None, origin_zip: None, } } } #[cfg(feature = "v1")] impl From<CreateCustomerRequest> for api::CustomerRequest { fn from(req: CreateCustomerRequest) -> Self { Self { customer_id: Some(common_utils::generate_customer_id_of_default_length()), name: req.name, phone: req.phone, email: req.email, description: req.description, metadata: req.metadata, address: req.address.map(|s| s.into()), ..Default::default() } } } #[cfg(feature = "v1")] impl From<CustomerUpdateRequest> for api::CustomerUpdateRequest { fn from(req: CustomerUpdateRequest) -> Self { Self { name: req.name, phone: req.phone, email: req.email, description: req.description, metadata: req.metadata, address: req.address.map(|s| s.into()), ..Default::default() } } } #[cfg(feature = "v1")] impl From<api::CustomerResponse> for CreateCustomerResponse { fn from(cust: api::CustomerResponse) -> Self { let cust = cust.into_inner(); Self { id: cust.customer_id, object: "customer".to_owned(), created: u64::try_from(cust.created_at.assume_utc().unix_timestamp()).unwrap_or_else( |error| { logger::error!( %error, "incorrect value for `customer.created_at` provided {}", cust.created_at ); // Current timestamp converted to Unix timestamp should have a positive value // for many years to come u64::try_from(date_time::now().assume_utc().unix_timestamp()) .unwrap_or_default() }, ), description: cust.description, email: cust.email.map(|inner| inner.into()), metadata: cust.metadata, name: cust.name.map(Encryptable::into_inner), phone: cust.phone.map(Encryptable::into_inner), } } } #[cfg(feature = "v1")] impl From<api::CustomerDeleteResponse> for CustomerDeleteResponse { fn from(cust: api::CustomerDeleteResponse) -> Self { Self { id: cust.customer_id, deleted: cust.customer_deleted, } } } #[derive(Default, Serialize, PartialEq, Eq)] pub struct CustomerPaymentMethodListResponse { pub object: &'static str, pub data: Vec<PaymentMethodData>, } #[derive(Default, Serialize, PartialEq, Eq)] pub struct PaymentMethodData { pub id: Option<String>, pub object: &'static str, pub card: Option<CardDetails>, pub created: Option<time::PrimitiveDateTime>, } #[derive(Default, Serialize, PartialEq, Eq)] pub struct CardDetails { pub country: Option<String>, pub last4: Option<String>, pub exp_month: Option<masking::Secret<String>>, pub exp_year: Option<masking::Secret<String>>, pub fingerprint: Option<masking::Secret<String>>, } #[cfg(feature = "v1")] impl From<api::CustomerPaymentMethodsListResponse> for CustomerPaymentMethodListResponse { fn from(item: api::CustomerPaymentMethodsListResponse) -> Self { let customer_payment_methods = item.customer_payment_methods; let data = customer_payment_methods .into_iter() .map(From::from) .collect(); Self { object: "list", data, } } } #[cfg(feature = "v1")] impl From<api_types::CustomerPaymentMethod> for PaymentMethodData { fn from(item: api_types::CustomerPaymentMethod) -> Self { let card = item.card.map(From::from); Self { id: Some(item.payment_token), object: "payment_method", card, created: item.created, } } } #[cfg(feature = "v1")] impl From<api_types::CardDetailFromLocker> for CardDetails { fn from(item: api_types::CardDetailFromLocker) -> Self { Self { country: item.issuer_country, last4: item.last4_digits, exp_month: item.expiry_month, exp_year: item.expiry_year, fingerprint: item.card_fingerprint, } } }
crates/router/src/compatibility/stripe/customers/types.rs
router::src::compatibility::stripe::customers::types
2,006
true
// File: crates/router/src/compatibility/stripe/payment_intents/types.rs // Module: router::src::compatibility::stripe::payment_intents::types use std::str::FromStr; use api_models::payments; use common_types::payments as common_payments_types; use common_utils::{ crypto::Encryptable, date_time, ext_traits::StringExt, id_type, pii::{IpAddress, SecretSerdeValue, UpiVpaMaskingStrategy}, types::MinorUnit, }; use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{ compatibility::stripe::refunds::types as stripe_refunds, connector::utils::AddressData, consts, core::errors, pii::{Email, PeekInterface}, types::{ api::{admin, enums as api_enums}, transformers::{ForeignFrom, ForeignTryFrom}, }, }; #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripeBillingDetails { pub address: Option<AddressDetails>, pub email: Option<Email>, pub name: Option<String>, pub phone: Option<masking::Secret<String>>, } impl From<StripeBillingDetails> for payments::Address { fn from(details: StripeBillingDetails) -> Self { Self { phone: Some(payments::PhoneDetails { number: details.phone, country_code: details.address.as_ref().and_then(|address| { address.country.as_ref().map(|country| country.to_string()) }), }), email: details.email, address: details.address.map(|address| payments::AddressDetails { city: address.city, country: address.country, line1: address.line1, line2: address.line2, zip: address.postal_code, state: address.state, first_name: None, line3: None, last_name: None, origin_zip: None, }), } } } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripeCard { pub number: cards::CardNumber, pub exp_month: masking::Secret<String>, pub exp_year: masking::Secret<String>, pub cvc: masking::Secret<String>, pub holder_name: Option<masking::Secret<String>>, } // ApplePay wallet param is not available in stripe Docs #[derive(Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum StripeWallet { ApplePay(payments::ApplePayWalletData), } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripeUpi { pub vpa_id: masking::Secret<String, UpiVpaMaskingStrategy>, } #[derive(Debug, Default, Serialize, PartialEq, Eq, Deserialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodType { #[default] Card, Wallet, Upi, BankRedirect, RealTimePayment, } impl From<StripePaymentMethodType> for api_enums::PaymentMethod { fn from(item: StripePaymentMethodType) -> Self { match item { StripePaymentMethodType::Card => Self::Card, StripePaymentMethodType::Wallet => Self::Wallet, StripePaymentMethodType::Upi => Self::Upi, StripePaymentMethodType::BankRedirect => Self::BankRedirect, StripePaymentMethodType::RealTimePayment => Self::RealTimePayment, } } } #[derive(Default, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripePaymentMethodData { #[serde(rename = "type")] pub stype: StripePaymentMethodType, pub billing_details: Option<StripeBillingDetails>, #[serde(flatten)] pub payment_method_details: Option<StripePaymentMethodDetails>, // enum pub metadata: Option<SecretSerdeValue>, } #[derive(PartialEq, Eq, Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodDetails { Card(StripeCard), Wallet(StripeWallet), Upi(StripeUpi), } impl From<StripeCard> for payments::Card { fn from(card: StripeCard) -> Self { Self { card_number: card.number, card_exp_month: card.exp_month, card_exp_year: card.exp_year, card_holder_name: card.holder_name, card_cvc: card.cvc, card_issuer: None, card_network: None, bank_code: None, card_issuing_country: None, card_type: None, nick_name: None, } } } impl From<StripeWallet> for payments::WalletData { fn from(wallet: StripeWallet) -> Self { match wallet { StripeWallet::ApplePay(data) => Self::ApplePay(data), } } } impl From<StripeUpi> for payments::UpiData { fn from(upi_data: StripeUpi) -> Self { Self::UpiCollect(payments::UpiCollectData { vpa_id: Some(upi_data.vpa_id), }) } } impl From<StripePaymentMethodDetails> for payments::PaymentMethodData { fn from(item: StripePaymentMethodDetails) -> Self { match item { StripePaymentMethodDetails::Card(card) => Self::Card(payments::Card::from(card)), StripePaymentMethodDetails::Wallet(wallet) => { Self::Wallet(payments::WalletData::from(wallet)) } StripePaymentMethodDetails::Upi(upi) => Self::Upi(payments::UpiData::from(upi)), } } } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct Shipping { pub address: AddressDetails, pub name: Option<masking::Secret<String>>, pub carrier: Option<String>, pub phone: Option<masking::Secret<String>>, pub tracking_number: Option<masking::Secret<String>>, } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct AddressDetails { pub city: Option<String>, pub country: Option<api_enums::CountryAlpha2>, pub line1: Option<masking::Secret<String>>, pub line2: Option<masking::Secret<String>>, pub postal_code: Option<masking::Secret<String>>, pub state: Option<masking::Secret<String>>, } impl From<Shipping> for payments::Address { fn from(details: Shipping) -> Self { Self { phone: Some(payments::PhoneDetails { number: details.phone, country_code: details.address.country.map(|country| country.to_string()), }), email: None, address: Some(payments::AddressDetails { city: details.address.city, country: details.address.country, line1: details.address.line1, line2: details.address.line2, zip: details.address.postal_code, state: details.address.state, first_name: details.name, line3: None, last_name: None, origin_zip: None, }), } } } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct MandateData { pub customer_acceptance: CustomerAcceptance, pub mandate_type: Option<StripeMandateType>, pub amount: Option<i64>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub start_date: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub end_date: Option<PrimitiveDateTime>, } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct CustomerAcceptance { #[serde(rename = "type")] pub acceptance_type: Option<AcceptanceType>, pub accepted_at: Option<PrimitiveDateTime>, pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone)] #[serde(rename_all = "lowercase")] pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { pub ip_address: masking::Secret<String, IpAddress>, pub user_agent: String, } #[derive(Deserialize, Clone, Debug)] pub struct StripePaymentIntentRequest { pub id: Option<id_type::PaymentId>, pub amount: Option<i64>, // amount in cents, hence passed as integer pub connector: Option<Vec<api_enums::RoutableConnectors>>, pub currency: Option<String>, #[serde(rename = "amount_to_capture")] pub amount_capturable: Option<i64>, pub confirm: Option<bool>, pub capture_method: Option<api_enums::CaptureMethod>, pub customer: Option<id_type::CustomerId>, pub description: Option<String>, pub payment_method_data: Option<StripePaymentMethodData>, pub receipt_email: Option<Email>, pub return_url: Option<url::Url>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub shipping: Option<Shipping>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, pub metadata: Option<serde_json::Value>, pub client_secret: Option<masking::Secret<String>>, pub payment_method_options: Option<StripePaymentMethodOptions>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, pub mandate: Option<String>, pub off_session: Option<bool>, pub payment_method_types: Option<api_enums::PaymentMethodType>, pub receipt_ipaddress: Option<String>, pub user_agent: Option<String>, pub mandate_data: Option<MandateData>, pub automatic_payment_methods: Option<SecretSerdeValue>, // not used pub payment_method: Option<String>, // not used pub confirmation_method: Option<String>, // not used pub error_on_requires_action: Option<String>, // not used pub radar_options: Option<SecretSerdeValue>, // not used pub connector_metadata: Option<payments::ConnectorMetadata>, } impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentIntentRequest) -> errors::RouterResult<Self> { let routable_connector: Option<api_enums::RoutableConnectors> = item.connector.and_then(|v| v.into_iter().next()); let routing = routable_connector .map(|connector| { api_models::routing::StaticRoutingAlgorithm::Single(Box::new( api_models::routing::RoutableConnectorChoice { choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, connector, merchant_connector_id: None, }, )) }) .map(|r| { serde_json::to_value(r) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("converting to routing failed") }) .transpose()?; let ip_address = item .receipt_ipaddress .map(|ip| std::net::IpAddr::from_str(ip.as_str())) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "receipt_ipaddress".to_string(), expected_format: "127.0.0.1".to_string(), })?; let amount = item.amount.map(|amount| MinorUnit::new(amount).into()); let payment_method_data = item.payment_method_data.as_ref().map(|pmd| { let billing = pmd.billing_details.clone().map(payments::Address::from); let payment_method_data = match pmd.payment_method_details.as_ref() { Some(spmd) => Some(payments::PaymentMethodData::from(spmd.to_owned())), None => get_pmd_based_on_payment_method_type( item.payment_method_types, billing.clone().map(From::from), ), }; payments::PaymentMethodDataRequest { payment_method_data, billing, } }); let request = Ok(Self { payment_id: item.id.map(payments::PaymentIdType::PaymentIntentId), amount, currency: item .currency .as_ref() .map(|c| c.to_uppercase().parse_enum("currency")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "currency", })?, capture_method: item.capture_method, amount_to_capture: item.amount_capturable.map(MinorUnit::new), confirm: item.confirm, customer_id: item.customer, email: item.receipt_email, phone: item.shipping.as_ref().and_then(|s| s.phone.clone()), description: item.description, return_url: item.return_url, payment_method_data, payment_method: item .payment_method_data .as_ref() .map(|pmd| api_enums::PaymentMethod::from(pmd.stype.to_owned())), shipping: item .shipping .as_ref() .map(|s| payments::Address::from(s.to_owned())), billing: item .payment_method_data .and_then(|pmd| pmd.billing_details.map(payments::Address::from)), statement_descriptor_name: item.statement_descriptor, statement_descriptor_suffix: item.statement_descriptor_suffix, metadata: item.metadata, client_secret: item.client_secret.map(|s| s.peek().clone()), authentication_type: match item.payment_method_options { Some(pmo) => { let StripePaymentMethodOptions::Card { request_three_d_secure, }: StripePaymentMethodOptions = pmo; Some(api_enums::AuthenticationType::foreign_from( request_three_d_secure, )) } None => None, }, mandate_data: ForeignTryFrom::foreign_try_from(( item.mandate_data, item.currency.to_owned(), ))?, merchant_connector_details: item.merchant_connector_details, setup_future_usage: item.setup_future_usage, mandate_id: item.mandate, off_session: item.off_session, payment_method_type: item.payment_method_types, routing, browser_info: Some( serde_json::to_value(crate::types::BrowserInformation { ip_address, user_agent: item.user_agent, ..Default::default() }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("convert to browser info failed")?, ), connector_metadata: item.connector_metadata, ..Self::default() }); request } } #[derive(Clone, Default, Eq, PartialEq, Serialize, Deserialize, Debug)] #[serde(rename_all = "snake_case")] pub enum StripePaymentStatus { Succeeded, Canceled, #[default] Processing, RequiresAction, RequiresPaymentMethod, RequiresConfirmation, RequiresCapture, } impl From<api_enums::IntentStatus> for StripePaymentStatus { fn from(item: api_enums::IntentStatus) -> Self { match item { api_enums::IntentStatus::Succeeded | api_enums::IntentStatus::PartiallyCaptured => { Self::Succeeded } api_enums::IntentStatus::Failed | api_enums::IntentStatus::Expired => Self::Canceled, api_enums::IntentStatus::Processing => Self::Processing, api_enums::IntentStatus::RequiresCustomerAction | api_enums::IntentStatus::RequiresMerchantAction | api_enums::IntentStatus::Conflicted => Self::RequiresAction, api_enums::IntentStatus::RequiresPaymentMethod => Self::RequiresPaymentMethod, api_enums::IntentStatus::RequiresConfirmation => Self::RequiresConfirmation, api_enums::IntentStatus::RequiresCapture | api_enums::IntentStatus::PartiallyCapturedAndCapturable | api_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { Self::RequiresCapture } api_enums::IntentStatus::Cancelled | api_enums::IntentStatus::CancelledPostCapture => { Self::Canceled } } } } #[derive(Debug, Serialize, Deserialize, Copy, Clone, strum::Display)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CancellationReason { Duplicate, Fraudulent, RequestedByCustomer, Abandoned, } #[derive(Debug, Deserialize, Serialize, Copy, Clone)] pub struct StripePaymentCancelRequest { cancellation_reason: Option<CancellationReason>, } impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest { fn from(item: StripePaymentCancelRequest) -> Self { Self { cancellation_reason: item.cancellation_reason.map(|c| c.to_string()), ..Self::default() } } } #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct StripePaymentIntentResponse { pub id: id_type::PaymentId, pub object: &'static str, pub amount: i64, pub amount_received: Option<i64>, pub amount_capturable: i64, pub currency: String, pub status: StripePaymentStatus, pub client_secret: Option<masking::Secret<String>>, pub created: Option<i64>, pub customer: Option<id_type::CustomerId>, pub refunds: Option<Vec<stripe_refunds::StripeRefundResponse>>, pub mandate: Option<String>, pub metadata: Option<serde_json::Value>, pub charges: Charges, pub connector: Option<String>, pub description: Option<String>, pub mandate_data: Option<payments::MandateData>, pub setup_future_usage: Option<api_models::enums::FutureUsage>, pub off_session: Option<bool>, pub authentication_type: Option<api_models::enums::AuthenticationType>, pub next_action: Option<StripeNextAction>, pub cancellation_reason: Option<String>, pub payment_method: Option<api_models::enums::PaymentMethod>, pub payment_method_data: Option<payments::PaymentMethodDataResponse>, pub shipping: Option<payments::Address>, pub billing: Option<payments::Address>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub capture_on: Option<PrimitiveDateTime>, pub payment_token: Option<String>, pub email: Option<Email>, pub phone: Option<masking::Secret<String>>, pub statement_descriptor_suffix: Option<String>, pub statement_descriptor_name: Option<String>, pub capture_method: Option<api_models::enums::CaptureMethod>, pub name: Option<masking::Secret<String>>, pub last_payment_error: Option<LastPaymentError>, pub connector_transaction_id: Option<String>, } #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct LastPaymentError { charge: Option<String>, code: Option<String>, decline_code: Option<String>, message: String, param: Option<String>, payment_method: StripePaymentMethod, #[serde(rename = "type")] error_type: String, } impl From<payments::PaymentsResponse> for StripePaymentIntentResponse { fn from(resp: payments::PaymentsResponse) -> Self { Self { object: "payment_intent", id: resp.payment_id, status: StripePaymentStatus::from(resp.status), amount: resp.amount.get_amount_as_i64(), amount_capturable: resp.amount_capturable.get_amount_as_i64(), amount_received: resp.amount_received.map(|amt| amt.get_amount_as_i64()), connector: resp.connector, client_secret: resp.client_secret, created: resp.created.map(|t| t.assume_utc().unix_timestamp()), currency: resp.currency.to_lowercase(), customer: resp.customer_id, description: resp.description, refunds: resp .refunds .map(|a| a.into_iter().map(Into::into).collect()), mandate: resp.mandate_id, mandate_data: resp.mandate_data, setup_future_usage: resp.setup_future_usage, off_session: resp.off_session, capture_on: resp.capture_on, capture_method: resp.capture_method, payment_method: resp.payment_method, payment_method_data: resp .payment_method_data .and_then(|pmd| pmd.payment_method_data), payment_token: resp.payment_token, shipping: resp.shipping, billing: resp.billing, email: resp.email.map(|inner| inner.into()), name: resp.name.map(Encryptable::into_inner), phone: resp.phone.map(Encryptable::into_inner), authentication_type: resp.authentication_type, statement_descriptor_name: resp.statement_descriptor_name, statement_descriptor_suffix: resp.statement_descriptor_suffix, next_action: into_stripe_next_action(resp.next_action, resp.return_url), cancellation_reason: resp.cancellation_reason, metadata: resp.metadata, charges: Charges::new(), last_payment_error: resp.error_code.map(|code| LastPaymentError { charge: None, code: Some(code.to_owned()), decline_code: None, message: resp .error_message .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), param: None, payment_method: StripePaymentMethod { payment_method_id: "place_holder_id".to_string(), object: "payment_method", card: None, created: u64::try_from(date_time::now().assume_utc().unix_timestamp()) .unwrap_or_default(), method_type: "card".to_string(), livemode: false, }, error_type: code, }), connector_transaction_id: resp.connector_transaction_id, } } } #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct StripePaymentMethod { #[serde(rename = "id")] payment_method_id: String, object: &'static str, card: Option<StripeCard>, created: u64, #[serde(rename = "type")] method_type: String, livemode: bool, } #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct Charges { object: &'static str, data: Vec<String>, has_more: bool, total_count: i32, url: String, } impl Charges { pub fn new() -> Self { Self { object: "list", data: vec![], has_more: false, total_count: 0, url: "http://placeholder".to_string(), } } } #[derive(Clone, Debug, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct StripePaymentListConstraints { pub customer: Option<id_type::CustomerId>, pub starting_after: Option<id_type::PaymentId>, pub ending_before: Option<id_type::PaymentId>, #[serde(default = "default_limit")] pub limit: u32, pub created: Option<i64>, #[serde(rename = "created[lt]")] pub created_lt: Option<i64>, #[serde(rename = "created[gt]")] pub created_gt: Option<i64>, #[serde(rename = "created[lte]")] pub created_lte: Option<i64>, #[serde(rename = "created[gte]")] pub created_gte: Option<i64>, } fn default_limit() -> u32 { 10 } impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentListConstraints) -> Result<Self, Self::Error> { Ok(Self { customer_id: item.customer, starting_after: item.starting_after, ending_before: item.ending_before, limit: item.limit, created: from_timestamp_to_datetime(item.created)?, created_lt: from_timestamp_to_datetime(item.created_lt)?, created_gt: from_timestamp_to_datetime(item.created_gt)?, created_lte: from_timestamp_to_datetime(item.created_lte)?, created_gte: from_timestamp_to_datetime(item.created_gte)?, }) } } #[inline] fn from_timestamp_to_datetime( time: Option<i64>, ) -> Result<Option<PrimitiveDateTime>, errors::ApiErrorResponse> { if let Some(time) = time { let time = time::OffsetDateTime::from_unix_timestamp(time).map_err(|_| { errors::ApiErrorResponse::InvalidRequestData { message: "Error while converting timestamp".to_string(), } })?; Ok(Some(PrimitiveDateTime::new(time.date(), time.time()))) } else { Ok(None) } } #[derive(Default, Eq, PartialEq, Serialize)] pub struct StripePaymentIntentListResponse { pub object: String, pub url: String, pub has_more: bool, pub data: Vec<StripePaymentIntentResponse>, } impl From<payments::PaymentListResponse> for StripePaymentIntentListResponse { fn from(it: payments::PaymentListResponse) -> Self { Self { object: "list".to_string(), url: "/v1/payment_intents".to_string(), has_more: false, data: it.data.into_iter().map(Into::into).collect(), } } } #[derive(PartialEq, Eq, Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodOptions { Card { request_three_d_secure: Option<Request3DS>, }, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripeMandateType { SingleUse, MultiUse, } #[derive(PartialEq, Eq, Clone, Default, Deserialize, Serialize, Debug)] pub struct MandateOption { #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub accepted_at: Option<PrimitiveDateTime>, pub user_agent: Option<String>, pub ip_address: Option<masking::Secret<String, IpAddress>>, pub mandate_type: Option<StripeMandateType>, pub amount: Option<i64>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub start_date: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub end_date: Option<PrimitiveDateTime>, } impl ForeignTryFrom<(Option<MandateData>, Option<String>)> for Option<payments::MandateData> { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( (mandate_data, currency): (Option<MandateData>, Option<String>), ) -> errors::RouterResult<Self> { let currency = currency .ok_or( errors::ApiErrorResponse::MissingRequiredField { field_name: "currency", } .into(), ) .and_then(|c| { c.to_uppercase().parse_enum("currency").change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "currency", }, ) })?; let mandate_data = mandate_data.map(|mandate| payments::MandateData { mandate_type: match mandate.mandate_type { Some(item) => match item { StripeMandateType::SingleUse => Some(payments::MandateType::SingleUse( payments::MandateAmountData { amount: MinorUnit::new(mandate.amount.unwrap_or_default()), currency, start_date: mandate.start_date, end_date: mandate.end_date, metadata: None, }, )), StripeMandateType::MultiUse => Some(payments::MandateType::MultiUse(Some( payments::MandateAmountData { amount: MinorUnit::new(mandate.amount.unwrap_or_default()), currency, start_date: mandate.start_date, end_date: mandate.end_date, metadata: None, }, ))), }, None => Some(payments::MandateType::MultiUse(Some( payments::MandateAmountData { amount: MinorUnit::new(mandate.amount.unwrap_or_default()), currency, start_date: mandate.start_date, end_date: mandate.end_date, metadata: None, }, ))), }, customer_acceptance: Some(common_payments_types::CustomerAcceptance { acceptance_type: common_payments_types::AcceptanceType::Online, accepted_at: mandate.customer_acceptance.accepted_at, online: mandate.customer_acceptance.online.map(|online| { common_payments_types::OnlineMandate { ip_address: Some(online.ip_address), user_agent: online.user_agent, } }), }), update_mandate_id: None, }); Ok(mandate_data) } } #[derive(Default, Eq, PartialEq, Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum Request3DS { #[default] Automatic, Any, } impl ForeignFrom<Option<Request3DS>> for api_models::enums::AuthenticationType { fn foreign_from(item: Option<Request3DS>) -> Self { match item.unwrap_or_default() { Request3DS::Automatic => Self::NoThreeDs, Request3DS::Any => Self::ThreeDs, } } } #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct RedirectUrl { pub return_url: Option<String>, pub url: Option<String>, } #[derive(Eq, PartialEq, serde::Serialize, Debug)] #[serde(tag = "type", rename_all = "snake_case")] pub enum StripeNextAction { RedirectToUrl { redirect_to_url: RedirectUrl, }, DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: payments::BankTransferNextStepsData, }, ThirdPartySdkSessionToken { session_token: Option<payments::SessionToken>, }, QrCodeInformation { image_data_url: Option<url::Url>, display_to_timestamp: Option<i64>, qr_code_url: Option<url::Url>, border_color: Option<String>, display_text: Option<String>, }, FetchQrCodeInformation { qr_code_fetch_url: url::Url, }, DisplayVoucherInformation { voucher_details: payments::VoucherNextStepData, }, WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, poll_config: Option<payments::PollConfig>, }, InvokeSdkClient { next_action_data: payments::SdkNextActionData, }, CollectOtp { consent_data_required: payments::MobilePaymentConsent, }, InvokeHiddenIframe { iframe_data: payments::IframeData, }, SdkUpiIntentInformation { sdk_uri: url::Url, }, } pub(crate) fn into_stripe_next_action( next_action: Option<payments::NextActionData>, return_url: Option<String>, ) -> Option<StripeNextAction> { next_action.map(|next_action_data| match next_action_data { payments::NextActionData::RedirectToUrl { redirect_to_url } => { StripeNextAction::RedirectToUrl { redirect_to_url: RedirectUrl { return_url, url: Some(redirect_to_url), }, } } payments::NextActionData::RedirectInsidePopup { popup_url, .. } => { StripeNextAction::RedirectToUrl { redirect_to_url: RedirectUrl { return_url, url: Some(popup_url), }, } } payments::NextActionData::DisplayBankTransferInformation { bank_transfer_steps_and_charges_details, } => StripeNextAction::DisplayBankTransferInformation { bank_transfer_steps_and_charges_details, }, payments::NextActionData::ThirdPartySdkSessionToken { session_token } => { StripeNextAction::ThirdPartySdkSessionToken { session_token } } payments::NextActionData::QrCodeInformation { image_data_url, display_to_timestamp, qr_code_url, border_color, display_text, } => StripeNextAction::QrCodeInformation { image_data_url, display_to_timestamp, qr_code_url, border_color, display_text, }, payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url } => { StripeNextAction::FetchQrCodeInformation { qr_code_fetch_url } } payments::NextActionData::DisplayVoucherInformation { voucher_details } => { StripeNextAction::DisplayVoucherInformation { voucher_details } } payments::NextActionData::WaitScreenInformation { display_from_timestamp, display_to_timestamp, poll_config: _, } => StripeNextAction::WaitScreenInformation { display_from_timestamp, display_to_timestamp, poll_config: None, }, payments::NextActionData::ThreeDsInvoke { .. } => StripeNextAction::RedirectToUrl { redirect_to_url: RedirectUrl { return_url: None, url: None, }, }, payments::NextActionData::InvokeSdkClient { next_action_data } => { StripeNextAction::InvokeSdkClient { next_action_data } } payments::NextActionData::CollectOtp { consent_data_required, } => StripeNextAction::CollectOtp { consent_data_required, }, payments::NextActionData::InvokeHiddenIframe { iframe_data } => { StripeNextAction::InvokeHiddenIframe { iframe_data } } payments::NextActionData::SdkUpiIntentInformation { sdk_uri } => { StripeNextAction::SdkUpiIntentInformation { sdk_uri } } }) } #[derive(Deserialize, Clone)] pub struct StripePaymentRetrieveBody { pub client_secret: Option<String>, } //To handle payment types that have empty payment method data fn get_pmd_based_on_payment_method_type( payment_method_type: Option<api_enums::PaymentMethodType>, billing_details: Option<hyperswitch_domain_models::address::Address>, ) -> Option<payments::PaymentMethodData> { match payment_method_type { Some(api_enums::PaymentMethodType::UpiIntent) => Some(payments::PaymentMethodData::Upi( payments::UpiData::UpiIntent(payments::UpiIntentData {}), )), Some(api_enums::PaymentMethodType::Fps) => { Some(payments::PaymentMethodData::RealTimePayment(Box::new( payments::RealTimePaymentData::Fps {}, ))) } Some(api_enums::PaymentMethodType::DuitNow) => { Some(payments::PaymentMethodData::RealTimePayment(Box::new( payments::RealTimePaymentData::DuitNow {}, ))) } Some(api_enums::PaymentMethodType::PromptPay) => { Some(payments::PaymentMethodData::RealTimePayment(Box::new( payments::RealTimePaymentData::PromptPay {}, ))) } Some(api_enums::PaymentMethodType::VietQr) => { Some(payments::PaymentMethodData::RealTimePayment(Box::new( payments::RealTimePaymentData::VietQr {}, ))) } Some(api_enums::PaymentMethodType::Ideal) => Some( payments::PaymentMethodData::BankRedirect(payments::BankRedirectData::Ideal { billing_details: billing_details.as_ref().map(|billing_data| { payments::BankRedirectBilling { billing_name: billing_data.get_optional_full_name(), email: billing_data.email.clone(), } }), bank_name: None, country: billing_details .as_ref() .and_then(|billing_data| billing_data.get_optional_country()), }), ), Some(api_enums::PaymentMethodType::LocalBankRedirect) => { Some(payments::PaymentMethodData::BankRedirect( payments::BankRedirectData::LocalBankRedirect {}, )) } _ => None, } }
crates/router/src/compatibility/stripe/payment_intents/types.rs
router::src::compatibility::stripe::payment_intents::types
7,855
true