text
stringlengths 65
57.3k
| file_path
stringlengths 22
92
| module
stringclasses 38
values | type
stringclasses 7
values | struct_name
stringlengths 3
60
⌀ | impl_count
int64 0
60
⌀ | traits
listlengths 0
59
⌀ | tokens
int64 16
8.19k
| function_name
stringlengths 3
85
⌀ | type_name
stringlengths 1
67
⌀ | trait_name
stringclasses 573
values | method_count
int64 0
31
⌀ | public_method_count
int64 0
19
⌀ | submodule_count
int64 0
56
⌀ | export_count
int64 0
9
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/payu.rs
// Module: hyperswitch_connectors
// Public submodules:
pub mod transformers;
|
crates/hyperswitch_connectors/src/connectors/payu.rs
|
hyperswitch_connectors
|
module_structure
| null | null | null | 38
| null | null | null | null | null | 1
| 0
|
// Struct: GetnetErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct GetnetErrorResponse
|
crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
GetnetErrorResponse
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Implementation: impl Organization
// File: crates/router/src/routes/app.rs
// Module: router
// Methods: 1 total (1 public)
impl Organization
|
crates/router/src/routes/app.rs
|
router
|
impl_block
| null | null | null | 33
| null |
Organization
| null | 1
| 1
| null | null |
// Module Structure
// File: crates/router/src/core/disputes.rs
// Module: router
// Public submodules:
pub mod transformers;
|
crates/router/src/core/disputes.rs
|
router
|
module_structure
| null | null | null | 30
| null | null | null | null | null | 1
| 0
|
// Struct: MandatePaymentRequest
// File: crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct MandatePaymentRequest
|
crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
MandatePaymentRequest
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Function: get_webhook_delivery_retry_schedule_time
// File: crates/router/src/workflows/outgoing_webhook_retry.rs
// Module: router
pub fn get_webhook_delivery_retry_schedule_time(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
retry_count: i32,
) -> Option<time::PrimitiveDateTime>
|
crates/router/src/workflows/outgoing_webhook_retry.rs
|
router
|
function_signature
| null | null | null | 77
|
get_webhook_delivery_retry_schedule_time
| null | null | null | null | null | null |
// Implementation: impl ConnectorErrorTypeMapping for for Paypal
// File: crates/hyperswitch_connectors/src/connectors/paypal.rs
// Module: hyperswitch_connectors
// Methods: 1 total (0 public)
impl ConnectorErrorTypeMapping for for Paypal
|
crates/hyperswitch_connectors/src/connectors/paypal.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 55
| null |
Paypal
|
ConnectorErrorTypeMapping for
| 1
| 0
| null | null |
// Struct: PaymentIntentCreate
// File: crates/router/src/core/payments/operations/payment_create_intent.rs
// Module: router
// Implementations: 0
pub struct PaymentIntentCreate
|
crates/router/src/core/payments/operations/payment_create_intent.rs
|
router
|
struct_definition
|
PaymentIntentCreate
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Struct: PaymentMethodCollectLinkRenderRequest
// File: crates/api_models/src/payment_methods.rs
// Module: api_models
// Implementations: 0
pub struct PaymentMethodCollectLinkRenderRequest
|
crates/api_models/src/payment_methods.rs
|
api_models
|
struct_definition
|
PaymentMethodCollectLinkRenderRequest
| 0
|
[] | 42
| null | null | null | null | null | null | null |
// Struct: RedirectUrl
// File: crates/router/src/compatibility/stripe/payment_intents/types.rs
// Module: router
// Implementations: 0
pub struct RedirectUrl
|
crates/router/src/compatibility/stripe/payment_intents/types.rs
|
router
|
struct_definition
|
RedirectUrl
| 0
|
[] | 39
| null | null | null | null | null | null | null |
// Struct: PayoutFlowData
// File: crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct PayoutFlowData
|
crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
|
hyperswitch_domain_models
|
struct_definition
|
PayoutFlowData
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Struct: IdealRedirectionResponse
// File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct IdealRedirectionResponse
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
IdealRedirectionResponse
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Struct: ZenApplePay
// File: crates/connector_configs/src/common_config.rs
// Module: connector_configs
// Implementations: 0
pub struct ZenApplePay
|
crates/connector_configs/src/common_config.rs
|
connector_configs
|
struct_definition
|
ZenApplePay
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// Struct: Worldpayvantiv
// File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
// Module: hyperswitch_connectors
// Implementations: 26
// Traits: api::Payment, api::PaymentSession, api::ConnectorAccessToken, api::MandateSetup, api::PaymentAuthorize, api::PaymentSync, api::PaymentCapture, api::PaymentVoid, api::Refund, api::RefundExecute, api::RefundSync, api::PaymentToken, api::PaymentPostCaptureVoid, ConnectorCommon, ConnectorValidation, Dispute, FetchDisputes, DisputeSync, SubmitEvidence, AcceptDispute, UploadFile, RetrieveFile, webhooks::IncomingWebhook, FileUpload, ConnectorSpecifications
pub struct Worldpayvantiv
|
crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
|
hyperswitch_connectors
|
struct_definition
|
Worldpayvantiv
| 26
|
[
"api::Payment",
"api::PaymentSession",
"api::ConnectorAccessToken",
"api::MandateSetup",
"api::PaymentAuthorize",
"api::PaymentSync",
"api::PaymentCapture",
"api::PaymentVoid",
"api::Refund",
"api::RefundExecute",
"api::RefundSync",
"api::PaymentToken",
"api::PaymentPostCaptureVoid",
"ConnectorCommon",
"ConnectorValidation",
"Dispute",
"FetchDisputes",
"DisputeSync",
"SubmitEvidence",
"AcceptDispute",
"UploadFile",
"RetrieveFile",
"webhooks::IncomingWebhook",
"FileUpload",
"ConnectorSpecifications"
] | 166
| null | null | null | null | null | null | null |
// Implementation: impl super::payments::distribution::PaymentDistributionAnalytics for for ClickhouseClient
// File: crates/analytics/src/clickhouse.rs
// Module: analytics
// Methods: 0 total (0 public)
impl super::payments::distribution::PaymentDistributionAnalytics for for ClickhouseClient
|
crates/analytics/src/clickhouse.rs
|
analytics
|
impl_block
| null | null | null | 61
| null |
ClickhouseClient
|
super::payments::distribution::PaymentDistributionAnalytics for
| 0
| 0
| null | null |
// Implementation: impl api::PaymentSync for for Forte
// File: crates/hyperswitch_connectors/src/connectors/forte.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSync for for Forte
|
crates/hyperswitch_connectors/src/connectors/forte.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Forte
|
api::PaymentSync for
| 0
| 0
| null | null |
// Function: get_order_id
// File: crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
// Module: hyperswitch_connectors
pub fn get_order_id(
meta: &NexinetsPaymentsMetadata,
) -> Result<String, error_stack::Report<errors::ConnectorError>>
|
crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 69
|
get_order_id
| null | null | null | null | null | null |
// Struct: ExternalMpi
// File: crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ExternalMpi
|
crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ExternalMpi
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Struct: AuthenticationTokenFlowData
// File: crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct AuthenticationTokenFlowData
|
crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
|
hyperswitch_domain_models
|
struct_definition
|
AuthenticationTokenFlowData
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Struct: MultipleCaptureData
// File: crates/router/src/core/payments/types.rs
// Module: router
// Implementations: 1
pub struct MultipleCaptureData
|
crates/router/src/core/payments/types.rs
|
router
|
struct_definition
|
MultipleCaptureData
| 1
|
[] | 36
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentAuthorize for for Paysafe
// File: crates/hyperswitch_connectors/src/connectors/paysafe.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentAuthorize for for Paysafe
|
crates/hyperswitch_connectors/src/connectors/paysafe.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Paysafe
|
api::PaymentAuthorize for
| 0
| 0
| null | null |
// File: crates/api_models/src/user/dashboard_metadata.rs
// Module: api_models
// Public structs: 12
use common_enums::{CountryAlpha2, MerchantProductType};
use common_utils::{id_type, pii};
use masking::Secret;
use strum::EnumString;
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub enum SetMetaDataRequest {
ProductionAgreement(ProductionAgreementRequest),
SetupProcessor(SetupProcessor),
ConfigureEndpoint,
SetupComplete,
FirstProcessorConnected(ProcessorConnected),
SecondProcessorConnected(ProcessorConnected),
ConfiguredRouting(ConfiguredRouting),
TestPayment(TestPayment),
IntegrationMethod(IntegrationMethod),
ConfigurationType(ConfigurationType),
IntegrationCompleted,
SPRoutingConfigured(ConfiguredRouting),
Feedback(Feedback),
ProdIntent(ProdIntent),
SPTestPayment,
DownloadWoocom,
ConfigureWoocom,
SetupWoocomWebhook,
IsMultipleConfiguration,
#[serde(skip)]
IsChangePasswordRequired,
OnboardingSurvey(OnboardingSurvey),
ReconStatus(ReconStatus),
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ProductionAgreementRequest {
pub version: String,
#[serde(skip_deserializing)]
pub ip_address: Option<Secret<String, pii::IpAddress>>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct SetupProcessor {
pub connector_id: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ProcessorConnected {
pub processor_id: id_type::MerchantConnectorAccountId,
pub processor_name: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct OnboardingSurvey {
pub designation: Option<String>,
pub about_business: Option<String>,
pub business_website: Option<String>,
pub hyperswitch_req: Option<String>,
pub major_markets: Option<Vec<String>>,
pub business_size: Option<String>,
pub required_features: Option<Vec<String>>,
pub required_processors: Option<Vec<String>>,
pub planned_live_date: Option<String>,
pub miscellaneous: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ConfiguredRouting {
pub routing_id: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct TestPayment {
pub payment_id: id_type::PaymentId,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct IntegrationMethod {
pub integration_type: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub enum ConfigurationType {
Single,
Multiple,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct Feedback {
pub email: pii::Email,
pub description: Option<String>,
pub rating: Option<i32>,
pub category: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct ProdIntent {
pub legal_business_name: Option<String>,
pub business_label: Option<String>,
pub business_location: Option<CountryAlpha2>,
pub display_name: Option<String>,
pub poc_email: Option<Secret<String>>,
pub business_type: Option<String>,
pub business_identifier: Option<String>,
pub business_website: Option<String>,
pub poc_name: Option<Secret<String>>,
pub poc_contact: Option<Secret<String>>,
pub comments: Option<String>,
pub is_completed: bool,
#[serde(default)]
pub product_type: MerchantProductType,
pub business_country_name: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct ReconStatus {
pub is_order_data_set: bool,
pub is_processor_data_set: bool,
}
#[derive(Debug, serde::Deserialize, EnumString, serde::Serialize)]
pub enum GetMetaDataRequest {
ProductionAgreement,
SetupProcessor,
ConfigureEndpoint,
SetupComplete,
FirstProcessorConnected,
SecondProcessorConnected,
ConfiguredRouting,
TestPayment,
IntegrationMethod,
ConfigurationType,
IntegrationCompleted,
StripeConnected,
PaypalConnected,
SPRoutingConfigured,
Feedback,
ProdIntent,
SPTestPayment,
DownloadWoocom,
ConfigureWoocom,
SetupWoocomWebhook,
IsMultipleConfiguration,
IsChangePasswordRequired,
OnboardingSurvey,
ReconStatus,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(transparent)]
pub struct GetMultipleMetaDataPayload {
pub results: Vec<GetMetaDataRequest>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct GetMultipleMetaDataRequest {
pub keys: String,
}
#[derive(Debug, serde::Serialize)]
pub enum GetMetaDataResponse {
ProductionAgreement(bool),
SetupProcessor(Option<SetupProcessor>),
ConfigureEndpoint(bool),
SetupComplete(bool),
FirstProcessorConnected(Option<ProcessorConnected>),
SecondProcessorConnected(Option<ProcessorConnected>),
ConfiguredRouting(Option<ConfiguredRouting>),
TestPayment(Option<TestPayment>),
IntegrationMethod(Option<IntegrationMethod>),
ConfigurationType(Option<ConfigurationType>),
IntegrationCompleted(bool),
StripeConnected(Option<ProcessorConnected>),
PaypalConnected(Option<ProcessorConnected>),
SPRoutingConfigured(Option<ConfiguredRouting>),
Feedback(Option<Feedback>),
ProdIntent(Option<ProdIntent>),
SPTestPayment(bool),
DownloadWoocom(bool),
ConfigureWoocom(bool),
SetupWoocomWebhook(bool),
IsMultipleConfiguration(bool),
IsChangePasswordRequired(bool),
OnboardingSurvey(Option<OnboardingSurvey>),
ReconStatus(Option<ReconStatus>),
}
|
crates/api_models/src/user/dashboard_metadata.rs
|
api_models
|
full_file
| null | null | null | 1,199
| null | null | null | null | null | null | null |
// File: crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs
// Module: analytics
use std::collections::HashSet;
use api_models::{
analytics::{
payment_intents::{
PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier,
},
Granularity, TimeRange,
},
enums::IntentStatus,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::PaymentIntentMetricRow;
use crate::{
enums::AuthInfo,
query::{
Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql,
Window,
},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(crate) struct SuccessfulSmartRetries;
#[async_trait::async_trait]
impl<T> super::PaymentIntentMetric<T> for SuccessfulSmartRetries
where
T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[PaymentIntentDimensions],
auth: &AuthInfo,
filters: &PaymentIntentFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>
{
let mut query_builder: QueryBuilder<T> =
QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized);
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()?;
query_builder
.add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt)
.switch()?;
query_builder
.add_custom_filter_clause("status", IntentStatus::Succeeded, FilterTypes::Equal)
.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::<PaymentIntentMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
PaymentIntentMetricsBucketIdentifier::new(
i.status.as_ref().map(|i| i.0),
i.currency.as_ref().map(|i| i.0),
i.profile_id.clone(),
i.connector.clone(),
i.authentication_type.as_ref().map(|i| i.0),
i.payment_method.clone(),
i.payment_method_type.clone(),
i.card_network.clone(),
i.merchant_id.clone(),
i.card_last_4.clone(),
i.card_issuer.clone(),
i.error_reason.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<
HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>,
crate::query::PostProcessingError,
>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
|
crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs
|
analytics
|
full_file
| null | null | null | 1,001
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentToken for for Mifinity
// File: crates/hyperswitch_connectors/src/connectors/mifinity.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentToken for for Mifinity
|
crates/hyperswitch_connectors/src/connectors/mifinity.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Mifinity
|
api::PaymentToken for
| 0
| 0
| null | null |
// File: crates/router/src/routes/locker_migration.rs
// Module: router
// Public functions: 1
use actix_web::{web, HttpRequest, HttpResponse};
use router_env::Flow;
use super::AppState;
use crate::{
core::{api_locking, locker_migration},
services::{api, authentication as auth},
};
pub async fn rust_locker_migration(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::RustLockerMigration;
let merchant_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
&merchant_id,
|state, _, _, _| locker_migration::rust_locker_migration(state, &merchant_id),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/locker_migration.rs
|
router
|
full_file
| null | null | null | 202
| null | null | null | null | null | null | null |
// Implementation: impl api::Refund for for Helcim
// File: crates/hyperswitch_connectors/src/connectors/helcim.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Refund for for Helcim
|
crates/hyperswitch_connectors/src/connectors/helcim.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Helcim
|
api::Refund for
| 0
| 0
| null | null |
// Struct: PreAuthentication
// File: crates/hyperswitch_domain_models/src/router_flow_types/authentication.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct PreAuthentication
|
crates/hyperswitch_domain_models/src/router_flow_types/authentication.rs
|
hyperswitch_domain_models
|
struct_definition
|
PreAuthentication
| 0
|
[] | 42
| null | null | null | null | null | null | null |
// Struct: GlobalpayAuthType
// File: crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct GlobalpayAuthType
|
crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
GlobalpayAuthType
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Struct: VoidResponse
// File: crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct VoidResponse
|
crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
VoidResponse
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// Struct: AuthenticationData
// File: crates/router/src/services/authentication.rs
// Module: router
// Implementations: 2
// Traits: AuthInfo, AuthInfo
pub struct AuthenticationData
|
crates/router/src/services/authentication.rs
|
router
|
struct_definition
|
AuthenticationData
| 2
|
[
"AuthInfo",
"AuthInfo"
] | 41
| null | null | null | null | null | null | null |
// File: crates/router/src/analytics.rs
// Module: router
// Public functions: 63
// Public structs: 1
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(),
|
crates/router/src/analytics.rs#chunk0
|
router
|
chunk
| null | null | null | 8,191
| null | null | null | null | null | null | null |
// Struct: BankAccountCredentialsResponse
// File: crates/pm_auth/src/types.rs
// Module: pm_auth
// Implementations: 0
pub struct BankAccountCredentialsResponse
|
crates/pm_auth/src/types.rs
|
pm_auth
|
struct_definition
|
BankAccountCredentialsResponse
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// File: crates/router/src/core/payments/operations/payment_cancel.rs
// Module: router
// Public structs: 1
use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
use router_derive;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{helpers, operations, PaymentData},
},
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
self as core_types,
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, router_derive::PaymentOperation)]
#[operation(operations = "all", flow = "cancel")]
pub struct PaymentCancel;
type PaymentCancelOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsCancelRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
for PaymentCancel
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsCancelRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<'a, F, api::PaymentsCancelRequest, PaymentData<F>>,
> {
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
enums::IntentStatus::Failed,
enums::IntentStatus::Succeeded,
enums::IntentStatus::Cancelled,
enums::IntentStatus::Processing,
enums::IntentStatus::RequiresMerchantAction,
],
"cancel",
)?;
let mut payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
payment_attempt
.cancellation_reason
.clone_from(&request.cancellation_reason);
let creds_identifier = request
.merchant_connector_details
.as_ref()
.map(|mcd| mcd.creds_identifier.to_owned());
request
.merchant_connector_details
.to_owned()
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(
db,
merchant_context.get_merchant_account().get_id(),
mcd,
)
.await
})
.await
.transpose()?;
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = db
.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 payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
token_data: None,
address: core_types::PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
confirm: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
for PaymentCancel
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentCancelOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
let cancellation_reason = payment_data.payment_attempt.cancellation_reason.clone();
let (intent_status_update, attempt_status_update) =
if payment_data.payment_intent.status != enums::IntentStatus::RequiresCapture {
let payment_intent_update = storage::PaymentIntentUpdate::PGStatusUpdate {
status: enums::IntentStatus::Cancelled,
updated_by: storage_scheme.to_string(),
incremental_authorization_allowed: None,
feature_metadata: payment_data
.payment_intent
.feature_metadata
.clone()
.map(masking::Secret::new),
};
(Some(payment_intent_update), enums::AttemptStatus::Voided)
} else {
(None, enums::AttemptStatus::VoidInitiated)
};
if let Some(payment_intent_update) = intent_status_update {
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
state
.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt.clone(),
storage::PaymentAttemptUpdate::VoidUpdate {
status: attempt_status_update,
cancellation_reason: cancellation_reason.clone(),
updated_by: storage_scheme.to_string(),
},
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentCancelled {
cancellation_reason,
}))
.with(payment_data.to_event())
.emit();
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsCancelRequest, PaymentData<F>>
for PaymentCancel
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsCancelRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentCancelOperation<'b, F>, operations::ValidateResult)> {
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
|
crates/router/src/core/payments/operations/payment_cancel.rs
|
router
|
full_file
| null | null | null | 2,276
| null | null | null | null | null | null | null |
// Function: routing_unlink_config
// File: crates/router/src/routes/routing.rs
// Module: router
pub fn routing_unlink_config(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<routing_types::RoutingConfigRequest>,
transaction_type: Option<enums::TransactionType>,
) -> impl Responder
|
crates/router/src/routes/routing.rs
|
router
|
function_signature
| null | null | null | 75
|
routing_unlink_config
| null | null | null | null | null | null |
// Struct: JWTAuthOrganizationFromRoute
// File: crates/router/src/services/authentication.rs
// Module: router
// Implementations: 0
pub struct JWTAuthOrganizationFromRoute
|
crates/router/src/services/authentication.rs
|
router
|
struct_definition
|
JWTAuthOrganizationFromRoute
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// File: crates/diesel_models/src/query/mandate.rs
// Module: diesel_models
// Public functions: 6
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table};
use error_stack::report;
use super::generics;
use crate::{errors, mandate::*, schema::mandate::dsl, PgPooledConn, StorageResult};
impl MandateNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Mandate> {
generics::generic_insert(conn, self).await
}
}
impl Mandate {
pub async fn find_by_merchant_id_mandate_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
mandate_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::mandate_id.eq(mandate_id.to_owned())),
)
.await
}
pub async fn find_by_merchant_id_connector_mandate_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
connector_mandate_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::connector_mandate_id.eq(connector_mandate_id.to_owned())),
)
.await
}
pub async fn find_by_merchant_id_customer_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
customer_id: &common_utils::id_type::CustomerId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as Table>::PrimaryKey,
_,
>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::customer_id.eq(customer_id.to_owned())),
None,
None,
None,
)
.await
}
//Fix this function once V2 mandate is schema is being built
#[cfg(feature = "v2")]
pub async fn find_by_global_customer_id(
conn: &PgPooledConn,
customer_id: &common_utils::id_type::GlobalCustomerId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as Table>::PrimaryKey,
_,
>(
conn,
dsl::customer_id.eq(customer_id.to_owned()),
None,
None,
None,
)
.await
}
pub async fn update_by_merchant_id_mandate_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
mandate_id: &str,
mandate: MandateUpdateInternal,
) -> StorageResult<Self> {
generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::mandate_id.eq(mandate_id.to_owned())),
mandate,
)
.await?
.first()
.cloned()
.ok_or_else(|| {
report!(errors::DatabaseError::NotFound)
.attach_printable("Error while updating mandate")
})
}
}
|
crates/diesel_models/src/query/mandate.rs
|
diesel_models
|
full_file
| null | null | null | 810
| null | null | null | null | null | null | null |
// Trait: PaymentMethodExt
// File: crates/router/src/core/payment_methods.rs
// Module: router
pub trait PaymentMethodExt
|
crates/router/src/core/payment_methods.rs
|
router
|
trait_definition
| null | null | null | 28
| null | null |
PaymentMethodExt
| null | null | null | null |
// Implementation: impl api::PaymentVoid for for Gocardless
// File: crates/hyperswitch_connectors/src/connectors/gocardless.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Gocardless
|
crates/hyperswitch_connectors/src/connectors/gocardless.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Gocardless
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Struct: PoQuote
// File: crates/hyperswitch_domain_models/src/router_flow_types/payouts.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct PoQuote
|
crates/hyperswitch_domain_models/src/router_flow_types/payouts.rs
|
hyperswitch_domain_models
|
struct_definition
|
PoQuote
| 0
|
[] | 44
| null | null | null | null | null | null | null |
// Struct: Cards
// File: crates/router/src/routes/app.rs
// Module: router
// Implementations: 1
pub struct Cards
|
crates/router/src/routes/app.rs
|
router
|
struct_definition
|
Cards
| 1
|
[] | 30
| null | null | null | null | null | null | null |
// Implementation: impl api::PayoutSync for for Nomupay
// File: crates/hyperswitch_connectors/src/connectors/nomupay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PayoutSync for for Nomupay
|
crates/hyperswitch_connectors/src/connectors/nomupay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 63
| null |
Nomupay
|
api::PayoutSync for
| 0
| 0
| null | null |
// Implementation: impl ConnectorValidation for for Digitalvirgo
// File: crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs
// Module: hyperswitch_connectors
// Methods: 1 total (0 public)
impl ConnectorValidation for for Digitalvirgo
|
crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Digitalvirgo
|
ConnectorValidation for
| 1
| 0
| null | null |
// Struct: CashtocodeErrors
// File: crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CashtocodeErrors
|
crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CashtocodeErrors
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Implementation: impl api::ConnectorAccessToken for for Placetopay
// File: crates/hyperswitch_connectors/src/connectors/placetopay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::ConnectorAccessToken for for Placetopay
|
crates/hyperswitch_connectors/src/connectors/placetopay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 63
| null |
Placetopay
|
api::ConnectorAccessToken for
| 0
| 0
| null | null |
// Implementation: impl EventClass
// File: crates/common_enums/src/enums.rs
// Module: common_enums
// Methods: 1 total (1 public)
impl EventClass
|
crates/common_enums/src/enums.rs
|
common_enums
|
impl_block
| null | null | null | 39
| null |
EventClass
| null | 1
| 1
| null | null |
// Struct: PaymentRequest
// File: crates/router_derive/src/lib.rs
// Module: router_derive
// Implementations: 0
pub struct PaymentRequest
|
crates/router_derive/src/lib.rs
|
router_derive
|
struct_definition
|
PaymentRequest
| 0
|
[] | 35
| null | null | null | null | null | null | null |
// Implementation: impl Responder
// File: crates/router/src/routes/routing.rs
// Module: router
// Methods: 0 total (0 public)
impl Responder
|
crates/router/src/routes/routing.rs
|
router
|
impl_block
| null | null | null | 36
| null |
Responder
| null | 0
| 0
| null | null |
// File: crates/router/src/core/webhooks/recovery_incoming.rs
// Module: router
// Public functions: 10
// Public structs: 8
use std::{collections::HashMap, marker::PhantomData, str::FromStr};
use api_models::{enums as api_enums, payments as api_payments, webhooks};
use common_utils::{
ext_traits::{AsyncExt, ValueExt},
id_type,
};
use diesel_models::process_tracker as storage;
use error_stack::{report, ResultExt};
use futures::stream::SelectNextSome;
use hyperswitch_domain_models::{
payments as domain_payments,
revenue_recovery::{self, RecoveryPaymentIntent},
router_data_v2::flow_common_types,
router_flow_types,
router_request_types::revenue_recovery as revenue_recovery_request,
router_response_types::revenue_recovery as revenue_recovery_response,
types as router_types,
};
use hyperswitch_interfaces::webhooks as interface_webhooks;
use masking::{PeekInterface, Secret};
use router_env::{instrument, logger, tracing};
use services::kafka;
use storage::business_status;
use crate::{
core::{
self, admin,
errors::{self, CustomResult},
payments::{self, helpers},
},
db::{errors::RevenueRecoveryError, StorageInterface},
routes::{app::ReqState, metrics, SessionState},
services::{
self,
connector_integration_interface::{self, RouterDataConversion},
},
types::{
self, api, domain,
storage::{
revenue_recovery as storage_revenue_recovery,
revenue_recovery_redis_operation::{
PaymentProcessorTokenDetails, PaymentProcessorTokenStatus, RedisTokenManager,
},
},
transformers::ForeignFrom,
},
workflows::revenue_recovery as revenue_recovery_flow,
};
#[cfg(feature = "v2")]
pub const REVENUE_RECOVERY: &str = "revenue_recovery";
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
#[cfg(feature = "revenue_recovery")]
pub async fn recovery_incoming_webhook_flow(
state: SessionState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
source_verified: bool,
connector_enum: &connector_integration_interface::ConnectorEnum,
billing_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
event_type: webhooks::IncomingWebhookEvent,
req_state: ReqState,
object_ref_id: &webhooks::ObjectReferenceId,
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
// Source verification is necessary for revenue recovery webhooks flow since We don't have payment intent/attempt object created before in our system.
common_utils::fp_utils::when(!source_verified, || {
Err(report!(
errors::RevenueRecoveryError::WebhookAuthenticationFailed
))
})?;
let connector = api_enums::Connector::from_str(connector_name)
.change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed)
.attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?;
let billing_connectors_with_invoice_sync_call = &state.conf.billing_connectors_invoice_sync;
let should_billing_connector_invoice_api_called = billing_connectors_with_invoice_sync_call
.billing_connectors_which_requires_invoice_sync_call
.contains(&connector);
let billing_connectors_with_payment_sync_call = &state.conf.billing_connectors_payment_sync;
let should_billing_connector_payment_api_called = billing_connectors_with_payment_sync_call
.billing_connectors_which_require_payment_sync
.contains(&connector);
let billing_connector_payment_details =
BillingConnectorPaymentsSyncResponseData::get_billing_connector_payment_details(
should_billing_connector_payment_api_called,
&state,
&merchant_context,
&billing_connector_account,
connector_name,
object_ref_id,
)
.await?;
let invoice_id = billing_connector_payment_details
.clone()
.map(|data| data.merchant_reference_id);
let billing_connector_invoice_details =
BillingConnectorInvoiceSyncResponseData::get_billing_connector_invoice_details(
should_billing_connector_invoice_api_called,
&state,
&merchant_context,
&billing_connector_account,
connector_name,
invoice_id,
)
.await?;
// Checks whether we have data in billing_connector_invoice_details , if it is there then we construct revenue recovery invoice from it else it takes from webhook
let invoice_details = RevenueRecoveryInvoice::get_recovery_invoice_details(
connector_enum,
request_details,
billing_connector_invoice_details.as_ref(),
)?;
// Fetch the intent using merchant reference id, if not found create new intent.
let payment_intent = invoice_details
.get_payment_intent(&state, &req_state, &merchant_context, &business_profile)
.await
.transpose()
.async_unwrap_or_else(|| async {
invoice_details
.create_payment_intent(&state, &req_state, &merchant_context, &business_profile)
.await
})
.await?;
let is_event_recovery_transaction_event = event_type.is_recovery_transaction_event();
let (recovery_attempt_from_payment_attempt, recovery_intent_from_payment_attempt) =
RevenueRecoveryAttempt::get_recovery_payment_attempt(
is_event_recovery_transaction_event,
&billing_connector_account,
&state,
connector_enum,
&req_state,
billing_connector_payment_details.as_ref(),
request_details,
&merchant_context,
&business_profile,
&payment_intent,
&invoice_details.0,
)
.await?;
// Publish event to Kafka
if let Some(ref attempt) = recovery_attempt_from_payment_attempt {
// Passing `merchant_context` here
let recovery_payment_tuple =
&RecoveryPaymentTuple::new(&recovery_intent_from_payment_attempt, attempt);
if let Err(e) = RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
&state,
recovery_payment_tuple,
None,
)
.await
{
logger::error!(
"Failed to publish revenue recovery event to kafka : {:?}",
e
);
};
}
let attempt_triggered_by = recovery_attempt_from_payment_attempt
.as_ref()
.and_then(|attempt| attempt.get_attempt_triggered_by());
let recovery_action = RecoveryAction {
action: RecoveryAction::get_action(event_type, attempt_triggered_by),
};
let mca_retry_threshold = billing_connector_account
.get_retry_threshold()
.ok_or(report!(
errors::RevenueRecoveryError::BillingThresholdRetryCountFetchFailed
))?;
let intent_retry_count = recovery_intent_from_payment_attempt
.feature_metadata
.as_ref()
.and_then(|metadata| metadata.get_retry_count())
.ok_or(report!(errors::RevenueRecoveryError::RetryCountFetchFailed))?;
logger::info!("Intent retry count: {:?}", intent_retry_count);
recovery_action
.handle_action(
&state,
&business_profile,
&merchant_context,
&billing_connector_account,
mca_retry_threshold,
intent_retry_count,
&(
recovery_attempt_from_payment_attempt,
recovery_intent_from_payment_attempt,
),
)
.await
}
async fn handle_monitoring_threshold(
state: &SessionState,
business_profile: &domain::Profile,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
let db = &*state.store;
let key_manager_state = &(state).into();
let monitoring_threshold_config = state.conf.revenue_recovery.monitoring_threshold_in_seconds;
let retry_algorithm_type = state.conf.revenue_recovery.retry_algorithm_type;
let revenue_recovery_retry_algorithm = business_profile
.revenue_recovery_retry_algorithm_data
.clone()
.ok_or(report!(
errors::RevenueRecoveryError::RetryAlgorithmTypeNotFound
))?;
if revenue_recovery_retry_algorithm
.has_exceeded_monitoring_threshold(monitoring_threshold_config)
{
let profile_wrapper = admin::ProfileWrapper::new(business_profile.clone());
profile_wrapper
.update_revenue_recovery_algorithm_under_profile(
db,
key_manager_state,
key_store,
retry_algorithm_type,
)
.await
.change_context(errors::RevenueRecoveryError::RetryAlgorithmUpdationFailed)?;
}
Ok(webhooks::WebhookResponseTracker::NoEffect)
}
#[allow(clippy::too_many_arguments)]
async fn handle_schedule_failed_payment(
billing_connector_account: &domain::MerchantConnectorAccount,
intent_retry_count: u16,
mca_retry_threshold: u16,
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_attempt_with_recovery_intent: &(
Option<revenue_recovery::RecoveryPaymentAttempt>,
revenue_recovery::RecoveryPaymentIntent,
),
business_profile: &domain::Profile,
revenue_recovery_retry: api_enums::RevenueRecoveryAlgorithmType,
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
let (recovery_attempt_from_payment_attempt, recovery_intent_from_payment_attempt) =
payment_attempt_with_recovery_intent;
// When intent_retry_count is less than or equal to threshold
(intent_retry_count <= mca_retry_threshold)
.then(|| {
logger::error!(
"Payment retry count {} is less than threshold {}",
intent_retry_count,
mca_retry_threshold
);
Ok(webhooks::WebhookResponseTracker::NoEffect)
})
.async_unwrap_or_else(|| async {
// Call calculate_job
core::revenue_recovery::upsert_calculate_pcr_task(
billing_connector_account,
state,
merchant_context,
recovery_intent_from_payment_attempt,
business_profile,
intent_retry_count,
recovery_attempt_from_payment_attempt
.as_ref()
.map(|attempt| attempt.attempt_id.clone()),
storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,
revenue_recovery_retry,
)
.await
})
.await
}
#[derive(Debug)]
pub struct RevenueRecoveryInvoice(revenue_recovery::RevenueRecoveryInvoiceData);
#[derive(Debug)]
pub struct RevenueRecoveryAttempt(revenue_recovery::RevenueRecoveryAttemptData);
impl RevenueRecoveryInvoice {
pub async fn get_or_create_custom_recovery_intent(
data: api_models::payments::RecoveryPaymentsCreate,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
) -> CustomResult<revenue_recovery::RecoveryPaymentIntent, errors::RevenueRecoveryError> {
let recovery_intent = Self(revenue_recovery::RevenueRecoveryInvoiceData::foreign_from(
data,
));
recovery_intent
.get_payment_intent(state, req_state, merchant_context, profile)
.await
.transpose()
.async_unwrap_or_else(|| async {
recovery_intent
.create_payment_intent(state, req_state, merchant_context, profile)
.await
})
.await
}
fn get_recovery_invoice_details(
connector_enum: &connector_integration_interface::ConnectorEnum,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
billing_connector_invoice_details: Option<
&revenue_recovery_response::BillingConnectorInvoiceSyncResponse,
>,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
billing_connector_invoice_details.map_or_else(
|| {
interface_webhooks::IncomingWebhook::get_revenue_recovery_invoice_details(
connector_enum,
request_details,
)
.change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed)
.attach_printable("Failed while getting revenue recovery invoice details")
.map(RevenueRecoveryInvoice)
},
|data| {
Ok(Self(revenue_recovery::RevenueRecoveryInvoiceData::from(
data,
)))
},
)
}
async fn get_payment_intent(
&self,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
) -> CustomResult<Option<revenue_recovery::RecoveryPaymentIntent>, errors::RevenueRecoveryError>
{
let payment_response = Box::pin(payments::payments_get_intent_using_merchant_reference(
state.clone(),
merchant_context.clone(),
profile.clone(),
req_state.clone(),
&self.0.merchant_reference_id,
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await;
let response = match payment_response {
Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => {
let payment_id = payments_response.id.clone();
let status = payments_response.status;
let feature_metadata = payments_response.feature_metadata;
let merchant_id = merchant_context.get_merchant_account().get_id().clone();
let revenue_recovery_invoice_data = &self.0;
Ok(Some(revenue_recovery::RecoveryPaymentIntent {
payment_id,
status,
feature_metadata,
merchant_id,
merchant_reference_id: Some(
revenue_recovery_invoice_data.merchant_reference_id.clone(),
),
invoice_amount: revenue_recovery_invoice_data.amount,
invoice_currency: revenue_recovery_invoice_data.currency,
created_at: revenue_recovery_invoice_data.billing_started_at,
billing_address: revenue_recovery_invoice_data.billing_address.clone(),
}))
}
Err(err)
if matches!(
err.current_context(),
&errors::ApiErrorResponse::PaymentNotFound
) =>
{
Ok(None)
}
Ok(_) => Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed)
.attach_printable("Unexpected response from payment intent core"),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed)
.attach_printable("failed to fetch payment intent recovery webhook flow")
}
}?;
Ok(response)
}
async fn create_payment_intent(
&self,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
) -> CustomResult<revenue_recovery::RecoveryPaymentIntent, errors::RevenueRecoveryError> {
let payload = api_payments::PaymentsCreateIntentRequest::from(&self.0);
let global_payment_id = id_type::GlobalPaymentId::generate(&state.conf.cell_information.id);
let create_intent_response = Box::pin(payments::payments_intent_core::<
router_flow_types::payments::PaymentCreateIntent,
api_payments::PaymentsIntentResponse,
_,
_,
hyperswitch_domain_models::payments::PaymentIntentData<
router_flow_types::payments::PaymentCreateIntent,
>,
>(
state.clone(),
req_state.clone(),
merchant_context.clone(),
profile.clone(),
payments::operations::PaymentIntentCreate,
payload,
global_payment_id,
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await
.change_context(errors::RevenueRecoveryError::PaymentIntentCreateFailed)?;
let response = create_intent_response
.get_json_body()
.change_context(errors::RevenueRecoveryError::PaymentIntentCreateFailed)
.attach_printable("expected json response")?;
let merchant_id = merchant_context.get_merchant_account().get_id().clone();
let revenue_recovery_invoice_data = &self.0;
Ok(revenue_recovery::RecoveryPaymentIntent {
payment_id: response.id,
status: response.status,
feature_metadata: response.feature_metadata,
merchant_id,
merchant_reference_id: Some(
revenue_recovery_invoice_data.merchant_reference_id.clone(),
),
invoice_amount: revenue_recovery_invoice_data.amount,
invoice_currency: revenue_recovery_invoice_data.currency,
created_at: revenue_recovery_invoice_data.billing_started_at,
billing_address: revenue_recovery_invoice_data.billing_address.clone(),
})
}
}
impl RevenueRecoveryAttempt {
pub async fn load_recovery_attempt_from_api(
data: api_models::payments::RecoveryPaymentsCreate,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
payment_intent: revenue_recovery::RecoveryPaymentIntent,
payment_merchant_connector_account: domain::MerchantConnectorAccount,
) -> CustomResult<
(
revenue_recovery::RecoveryPaymentAttempt,
revenue_recovery::RecoveryPaymentIntent,
),
errors::RevenueRecoveryError,
> {
let recovery_attempt = Self(revenue_recovery::RevenueRecoveryAttemptData::foreign_from(
&data,
));
recovery_attempt
.get_payment_attempt(state, req_state, merchant_context, profile, &payment_intent)
.await
.transpose()
.async_unwrap_or_else(|| async {
recovery_attempt
.record_payment_attempt(
state,
req_state,
merchant_context,
profile,
&payment_intent,
&data.billing_merchant_connector_id,
Some(payment_merchant_connector_account),
)
.await
})
.await
}
fn get_recovery_invoice_transaction_details(
connector_enum: &connector_integration_interface::ConnectorEnum,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
billing_connector_payment_details: Option<
&revenue_recovery_response::BillingConnectorPaymentsSyncResponse,
>,
billing_connector_invoice_details: &revenue_recovery::RevenueRecoveryInvoiceData,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
billing_connector_payment_details.map_or_else(
|| {
interface_webhooks::IncomingWebhook::get_revenue_recovery_attempt_details(
connector_enum,
request_details,
)
.change_context(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed)
.attach_printable(
"Failed to get recovery attempt details from the billing connector",
)
.map(RevenueRecoveryAttempt)
},
|data| {
Ok(Self(revenue_recovery::RevenueRecoveryAttemptData::from((
data,
billing_connector_invoice_details,
))))
},
)
}
pub fn get_revenue_recovery_attempt(
payment_intent: &domain_payments::PaymentIntent,
revenue_recovery_metadata: &api_payments::PaymentRevenueRecoveryMetadata,
billing_connector_account: &domain::MerchantConnectorAccount,
card_info: api_payments::AdditionalCardInfo,
payment_processor_token: &str,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
let revenue_recovery_data = payment_intent
.create_revenue_recovery_attempt_data(
revenue_recovery_metadata.clone(),
billing_connector_account,
card_info,
payment_processor_token,
)
.change_context(errors::RevenueRecoveryError::RevenueRecoveryAttemptDataCreateFailed)
.attach_printable("Failed to build recovery attempt data")?;
Ok(Self(revenue_recovery_data))
}
async fn get_payment_attempt(
&self,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
payment_intent: &revenue_recovery::RecoveryPaymentIntent,
) -> CustomResult<
Option<(
revenue_recovery::RecoveryPaymentAttempt,
revenue_recovery::RecoveryPaymentIntent,
)>,
errors::RevenueRecoveryError,
> {
let attempt_response =
Box::pin(payments::payments_list_attempts_using_payment_intent_id::<
payments::operations::PaymentGetListAttempts,
api_payments::PaymentAttemptListResponse,
_,
payments::operations::payment_attempt_list::PaymentGetListAttempts,
hyperswitch_domain_models::payments::PaymentAttemptListData<
payments::operations::PaymentGetListAttempts,
>,
>(
state.clone(),
req_state.clone(),
merchant_context.clone(),
profile.clone(),
payments::operations::PaymentGetListAttempts,
api_payments::PaymentAttemptListRequest {
payment_intent_id: payment_intent.payment_id.clone(),
},
payment_intent.payment_id.clone(),
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await;
let response = match attempt_response {
Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => {
let final_attempt = self
.0
.charge_id
.as_ref()
.map(|charge_id| {
payments_response
.find_attempt_in_attempts_list_using_charge_id(charge_id.clone())
})
.unwrap_or_else(|| {
self.0
.connector_transaction_id
.as_ref()
.and_then(|transaction_id| {
payments_response
.find_attempt_in_attempts_list_using_connector_transaction_id(
transaction_id,
)
})
});
let payment_attempt =
final_attempt.map(|res| revenue_recovery::RecoveryPaymentAttempt {
attempt_id: res.id.to_owned(),
attempt_status: res.status.to_owned(),
feature_metadata: res.feature_metadata.to_owned(),
amount: res.amount.net_amount,
network_advice_code: res.error.clone().and_then(|e| e.network_advice_code), // Placeholder, to be populated if available
network_decline_code: res
.error
.clone()
.and_then(|e| e.network_decline_code), // Placeholder, to be populated if available
error_code: res.error.clone().map(|error| error.code),
created_at: res.created_at,
});
// If we have an attempt, combine it with payment_intent in a tuple.
let res_with_payment_intent_and_attempt =
payment_attempt.map(|attempt| (attempt, (*payment_intent).clone()));
Ok(res_with_payment_intent_and_attempt)
}
Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("Unexpected response from payment intent core"),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("failed to fetch payment attempt in recovery webhook flow")
}
}?;
Ok(response)
}
#[allow(clippy::too_many_arguments)]
async fn record_payment_attempt(
&self,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
payment_intent: &revenue_recovery::RecoveryPaymentIntent,
billing_connector_account_id: &id_type::MerchantConnectorAccountId,
payment_connector_account: Option<domain::MerchantConnectorAccount>,
) -> CustomResult<
(
revenue_recovery::RecoveryPaymentAttempt,
revenue_recovery::RecoveryPaymentIntent,
),
errors::RevenueRecoveryError,
> {
let payment_connector_id = payment_connector_account.as_ref().map(|account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount| account.id.clone());
let payment_connector_name = payment_connector_account
.as_ref()
.map(|account| account.connector_name);
let request_payload: api_payments::PaymentsAttemptRecordRequest = self
.create_payment_record_request(
state,
billing_connector_account_id,
payment_connector_id,
payment_connector_name,
common_enums::TriggeredBy::External,
)
.await?;
let attempt_response = Box::pin(payments::record_attempt_core(
state.clone(),
req_state.clone(),
merchant_context.clone(),
profile.clone(),
request_payload,
payment_intent.payment_id.clone(),
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await;
let (recovery_attempt, updated_recovery_intent) = match attempt_response {
Ok(services::ApplicationResponse::JsonWithHeaders((attempt_response, _))) => {
Ok((
revenue_recovery::RecoveryPaymentAttempt {
attempt_id: attempt_response.id.clone(),
attempt_status: attempt_response.status,
feature_metadata: attempt_response.payment_attempt_feature_metadata,
amount: attempt_response.amount,
network_advice_code: attempt_response
.error_details
.clone()
.and_then(|error| error.network_decline_code), // Placeholder, to be populated if available
network_decline_code: attempt_response
.error_details
.clone()
.and_then(|error| error.network_decline_code), // Placeholder, to be populated if available
error_code: attempt_response
.error_details
.clone()
.map(|error| error.code),
created_at: attempt_response.created_at,
},
revenue_recovery::RecoveryPaymentIntent {
payment_id: payment_intent.payment_id.clone(),
status: attempt_response.status.into(), // Using status from attempt_response
feature_metadata: attempt_response.payment_intent_feature_metadata, // Using feature_metadata from attempt_response
merchant_id: payment_intent.merchant_id.clone(),
merchant_reference_id: payment_intent.merchant_reference_id.clone(),
invoice_amount: payment_intent.invoice_amount,
invoice_currency: payment_intent.invoice_currency,
created_at: payment_intent.created_at,
billing_address: payment_intent.billing_address.clone(),
},
))
}
Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("Unexpected response from record attempt core"),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("failed to record attempt in recovery webhook flow")
}
}?;
let response = (recovery_attempt, updated_recovery_intent);
self.store_payment_processor_tokens_in_redis(state, &response.0, payment_connector_name)
.await
.map_err(|e| {
router_env::logger::error!(
"Failed to store payment processor tokens in Redis: {:?}",
e
);
errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed
})?;
Ok(response)
}
pub async fn create_payment_record_request(
&self,
state: &SessionState,
billing_merchant_connector_account_id: &id_type::MerchantConnectorAccountId,
payment_merchant_connector_account_id: Option<id_type::MerchantConnectorAccountId>,
payment_connector: Option<common_enums::connector_enums::Connector>,
triggered_by: common_enums::TriggeredBy,
) -> CustomResult<api_payments::PaymentsAttemptRecordRequest, errors::RevenueRecoveryError>
{
let revenue_recovery_attempt_data = &self.0;
let amount_details =
api_payments::PaymentAttemptAmountDetails::from(revenue_recovery_attempt_data);
let feature_metadata = api_payments::PaymentAttemptFeatureMetadata {
revenue_recovery: Some(api_payments::PaymentAttemptRevenueRecoveryData {
// Since we are recording the external paymenmt attempt, this is hardcoded to External
attempt_triggered_by: triggered_by,
charge_id: self.0.charge_id.clone(),
}),
};
let card_info = revenue_recovery_attempt_data
.card_info
.card_isin
.clone()
.async_and_then(|isin| async move {
let issuer_identifier_number = isin.clone();
state
.store
.get_card_info(issuer_identifier_number.as_str())
.await
.map_err(|error| services::logger::warn!(card_info_error=?error))
.ok()
})
.await
.flatten();
let payment_method_data = api_models::payments::RecordAttemptPaymentMethodDataRequest {
payment_method_data: api_models::payments::AdditionalPaymentData::Card(Box::new(
revenue_recovery_attempt_data.card_info.clone(),
)),
billing: None,
};
let card_issuer = revenue_recovery_attempt_data.card_info.card_issuer.clone();
let error =
Option::<api_payments::RecordAttemptErrorDetails>::from(revenue_recovery_attempt_data);
Ok(api_payments::PaymentsAttemptRecordRequest {
amount_details,
status: revenue_recovery_attempt_data.status,
billing: None,
shipping: None,
connector: payment_connector,
payment_merchant_connector_id: payment_merchant_connector_account_id,
error,
description: None,
connector_transaction_id: revenue_recovery_attempt_data
.connector_transaction_id
.clone(),
payment_method_type: revenue_recovery_attempt_data.payment_method_type,
billing_connector_id: billing_merchant_connector_account_id.clone(),
payment_method_subtype: revenue_recovery_attempt_data.payment_method_sub_type,
payment_method_data: Some(payment_method_data),
metadata: None,
feature_metadata: Some(feature_metadata),
transaction_created_at: revenue_recovery_attempt_data.transaction_created_at,
processor_payment_method_token: revenue_recovery_attempt_data
.processor_payment_method_token
.clone(),
connector_customer_id: revenue_recovery_attempt_data.connector_customer_id.clone(),
retry_count: revenue_recovery_attempt_data.retry_count,
invoice_next_billing_time: revenue_recovery_attempt_data.invoice_next_billing_time,
invoice_billing_started_at_time: revenue_recovery_attempt_data
.invoice_billing_started_at_time,
triggered_by,
card_network: revenue_recovery_attempt_data.card_info.card_network.clone(),
card_issuer,
})
}
pub async fn find_payment_merchant_connector_account(
&self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
billing_connector_account: &domain::MerchantConnectorAccount,
) -> CustomResult<Option<domain::MerchantConnectorAccount>, errors::RevenueRecoveryError> {
let payment_merchant_connector_account_id = billing_connector_account
.get_payment_merchant_connector_account_id_using_account_reference_id(
self.0.connector_account_reference_id.clone(),
);
let db = &*state.store;
let key_manager_state = &(state).into();
let payment_merchant_connector_account = payment_merchant_connector_account_id
.as_ref()
.async_map(|mca_id| async move {
db.find_merchant_connector_account_by_id(key_manager_state, mca_id, key_store)
.await
})
.await
.transpose()
.change_context(errors::RevenueRecoveryError::PaymentMerchantConnectorAccountNotFound)
.attach_printable(
"failed to fetch payment merchant connector id using account reference id",
)?;
Ok(payment_merchant_connector_account)
}
#[allow(clippy::too_many_arguments)]
async fn get_recovery_payment_attempt(
is_recovery_transaction_event: bool,
billing_connector_account: &domain::MerchantConnectorAccount,
state: &SessionState,
connector_enum: &connector_integration_interface::ConnectorEnum,
req_state: &ReqState,
billing_connector_payment_details: Option<
&revenue_recovery_response::BillingConnectorPaymentsSyncResponse,
>,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
payment_intent: &revenue_recovery::RecoveryPaymentIntent,
invoice_details: &revenue_recovery::RevenueRecoveryInvoiceData,
) -> CustomResult<
(
Option<revenue_recovery::RecoveryPaymentAttempt>,
revenue_recovery::RecoveryPaymentIntent,
),
errors::RevenueRecoveryError,
> {
let payment_attempt_with_recovery_intent = match is_recovery_transaction_event {
true => {
let invoice_transaction_details = Self::get_recovery_invoice_transaction_details(
connector_enum,
request_details,
billing_connector_payment_details,
invoice_details,
)?;
// Find the payment merchant connector ID at the top level to avoid multiple DB calls.
let payment_merchant_connector_account = invoice_transaction_details
.find_payment_merchant_connector_account(
state,
merchant_context.get_merchant_key_store(),
billing_connector_account,
)
.await?;
let (payment_attempt, updated_payment_intent) = invoice_transaction_details
.get_payment_attempt(
state,
req_state,
merchant_context,
business_profile,
payment_intent,
)
.await
.transpose()
.async_unwrap_or_else(|| async {
invoice_transaction_details
.record_payment_attempt(
state,
req_state,
merchant_context,
business_profile,
payment_intent,
&billing_connector_account.get_id(),
payment_merchant_connector_account,
)
.await
})
.await?;
(Some(payment_attempt), updated_payment_intent)
}
false => (None, payment_intent.clone()),
};
Ok(payment_attempt_with_recovery_intent)
}
/// Store payment processor tokens in Redis for retry management
async fn store_payment_processor_tokens_in_redis(
&self,
state: &SessionState,
recovery_attempt: &revenue_recovery::RecoveryPaymentAttempt,
payment_connector_name: Option<common_enums::connector_enums::Connector>,
) -> CustomResult<(), errors::RevenueRecoveryError> {
let revenue_recovery_attempt_data = &self.0;
let error_code = revenue_recovery_attempt_data.error_code.clone();
let error_message = revenue_recovery_attempt_data.error_message.clone();
let connector_name = payment_connector_name
.ok_or(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed)
.attach_printable("unable to derive payment connector")?
.to_string();
let gsm_record = helpers::get_gsm_record(
state,
error_code.clone(),
error_message,
connector_name,
REVENUE_RECOVERY.to_string(),
)
.await;
let is_hard_decline = gsm_record
.and_then(|record| record.error_category)
.map(|category| category == common_enums::ErrorCategory::HardDecline)
.unwrap_or(false);
// Extract required fields from the revenue recovery attempt data
let connector_customer_id = revenue_recovery_attempt_data.connector_customer_id.clone();
let attempt_id = recovery_attempt.attempt_id.clone();
let token_unit = PaymentProcessorTokenStatus {
error_code,
inserted_by_attempt_id: attempt_id.clone(),
daily_retry_history: HashMap::from([(recovery_attempt.created_at.date(), 1)]),
scheduled_at: None,
is_hard_decline: Some(is_hard_decline),
payment_processor_token_details: PaymentProcessorTokenDetails {
payment_processor_token: revenue_recovery_attempt_data
.processor_payment_method_token
.clone(),
expiry_month: revenue_recovery_attempt_data
.card_info
.card_exp_month
.clone(),
expiry_year: revenue_recovery_attempt_data
.card_info
.card_exp_year
.clone(),
card_issuer: revenue_recovery_attempt_data.card_info.card_issuer.clone(),
last_four_digits: revenue_recovery_attempt_data.card_info.last4.clone(),
card_network: revenue_recovery_attempt_data.card_info.card_network.clone(),
card_type: revenue_recovery_attempt_data.card_info.card_type.clone(),
},
};
// Make the Redis call to store tokens
RedisTokenManager::upsert_payment_processor_token(
state,
&connector_customer_id,
token_unit,
)
.await
.change_context(errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed)
.attach_printable("Failed to store payment processor tokens in Redis")?;
Ok(())
}
}
pub struct BillingConnectorPaymentsSyncResponseData(
revenue_recovery_response::BillingConnectorPaymentsSyncResponse,
);
pub struct BillingConnectorPaymentsSyncFlowRouterData(
router_types::BillingConnectorPaymentsSyncRouterData,
);
impl BillingConnectorPaymentsSyncResponseData {
async fn handle_billing_connector_payment_sync_call(
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
id: &str,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
None,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("invalid connector name received in payment attempt")?;
let connector_integration: services::BoxedBillingConnectorPaymentsSyncIntegrationInterface<
router_flow_types::BillingConnectorPaymentsSync,
revenue_recovery_request::BillingConnectorPaymentsSyncRequest,
revenue_recovery_response::BillingConnectorPaymentsSyncResponse,
> = connector_data.connector.get_connector_integration();
let router_data =
BillingConnectorPaymentsSyncFlowRouterData::construct_router_data_for_billing_connector_payment_sync_call(
state,
connector_name,
merchant_connector_account,
merchant_context,
id,
)
.await
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable(
"Failed while constructing router data for billing connector psync call",
)?
.inner();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("Failed while fetching billing connector payment details")?;
let additional_recovery_details = match response.response {
Ok(response) => Ok(response),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("Failed while fetching billing connector payment details")
}
}?;
Ok(Self(additional_recovery_details))
}
async fn get_billing_connector_payment_details(
should_billing_connector_payment_api_called: bool,
state: &SessionState,
merchant_context: &domain::MerchantContext,
billing_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
object_ref_id: &webhooks::ObjectReferenceId,
) -> CustomResult<
Option<revenue_recovery_response::BillingConnectorPaymentsSyncResponse>,
|
crates/router/src/core/webhooks/recovery_incoming.rs#chunk0
|
router
|
chunk
| null | null | null | 8,189
| null | null | null | null | null | null | null |
// Struct: RelayRefundData
// File: crates/hyperswitch_domain_models/src/relay.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct RelayRefundData
|
crates/hyperswitch_domain_models/src/relay.rs
|
hyperswitch_domain_models
|
struct_definition
|
RelayRefundData
| 0
|
[] | 44
| null | null | null | null | null | null | null |
// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/tsys.rs
// Module: hyperswitch_connectors
// Public submodules:
pub mod transformers;
|
crates/hyperswitch_connectors/src/connectors/tsys.rs
|
hyperswitch_connectors
|
module_structure
| null | null | null | 38
| null | null | null | null | null | 1
| 0
|
// Struct: AdyenPlatformRouterData
// File: crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct AdyenPlatformRouterData<T>
|
crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
AdyenPlatformRouterData
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/dlocal.rs
// Module: hyperswitch_connectors
// Public functions: 1
// Public structs: 1
pub mod transformers;
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::enums;
use common_utils::{
crypto::{self, SignMessage},
date_time,
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hex::encode;
use hyperswitch_domain_models::{
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use lazy_static::lazy_static;
use masking::{Mask, Maskable, PeekInterface};
use transformers as dlocal;
use crate::{
connectors::dlocal::transformers::DlocalRouterData, constants::headers,
types::ResponseRouterData, utils::convert_amount,
};
#[derive(Clone)]
pub struct Dlocal {
amount_convertor: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Dlocal {
pub fn new() -> &'static Self {
&Self {
amount_convertor: &MinorUnitForConnector,
}
}
}
impl api::Payment for Dlocal {}
impl api::PaymentToken for Dlocal {}
impl api::PaymentSession for Dlocal {}
impl api::ConnectorAccessToken for Dlocal {}
impl api::MandateSetup for Dlocal {}
impl api::PaymentAuthorize for Dlocal {}
impl api::PaymentSync for Dlocal {}
impl api::PaymentCapture for Dlocal {}
impl api::PaymentVoid for Dlocal {}
impl api::Refund for Dlocal {}
impl api::RefundExecute for Dlocal {}
impl api::RefundSync for Dlocal {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Dlocal
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let dlocal_req = self.get_request_body(req, connectors)?;
let date = date_time::date_as_yyyymmddthhmmssmmmz()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let auth = dlocal::DlocalAuthType::try_from(&req.connector_auth_type)?;
let sign_req: String = format!(
"{}{}{}",
auth.x_login.peek(),
date,
dlocal_req.get_inner_value().peek().to_owned()
);
let authz = crypto::HmacSha256::sign_message(
&crypto::HmacSha256,
auth.secret.peek().as_bytes(),
sign_req.as_bytes(),
)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to sign the message")?;
let auth_string: String = format!("V2-HMAC-SHA256, Signature: {}", encode(authz));
let headers = vec![
(
headers::AUTHORIZATION.to_string(),
auth_string.into_masked(),
),
(headers::X_LOGIN.to_string(), auth.x_login.into_masked()),
(
headers::X_TRANS_KEY.to_string(),
auth.x_trans_key.into_masked(),
),
(headers::X_VERSION.to_string(), "2.1".to_string().into()),
(headers::X_DATE.to_string(), date.into()),
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
];
Ok(headers)
}
}
impl ConnectorCommon for Dlocal {
fn id(&self) -> &'static str {
"dlocal"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.dlocal.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: dlocal::DlocalErrorResponse = res
.response
.parse_struct("Dlocal ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i: &mut ConnectorEvent| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code.to_string(),
message: response.message,
reason: response.param,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Dlocal {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Dlocal
{
// Not Implemented (R)
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Dlocal {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Dlocal {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Dlocal {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Dlocal".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Dlocal {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}secure_payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = DlocalRouterData::try_from((amount, req))?;
let connector_req = dlocal::DlocalPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
router_env::logger::debug!(dlocal_payments_authorize_response=?res);
let response: dlocal::DlocalPaymentsResponse = res
.response
.parse_struct("Dlocal PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Dlocal {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let sync_data = dlocal::DlocalPaymentsSyncRequest::try_from(req)?;
Ok(format!(
"{}payments/{}/status",
self.base_url(connectors),
sync_data.authz_id,
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
router_env::logger::debug!(dlocal_payment_sync_response=?res);
let response: dlocal::DlocalPaymentsResponse = res
.response
.parse_struct("Dlocal PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Dlocal {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = dlocal::DlocalPaymentsCaptureRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
router_env::logger::debug!(dlocal_payments_capture_response=?res);
let response: dlocal::DlocalPaymentsResponse = res
.response
.parse_struct("Dlocal PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Dlocal {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let cancel_data = dlocal::DlocalPaymentsCancelRequest::try_from(req)?;
Ok(format!(
"{}payments/{}/cancel",
self.base_url(connectors),
cancel_data.cancel_id
))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
router_env::logger::debug!(dlocal_payments_cancel_response=?res);
let response: dlocal::DlocalPaymentsResponse = res
.response
.parse_struct("Dlocal PaymentsCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Dlocal {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}refunds", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = DlocalRouterData::try_from((amount, req))?;
let connector_req = dlocal::DlocalRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
router_env::logger::debug!(dlocal_refund_response=?res);
let response: dlocal::RefundResponse =
res.response
.parse_struct("Dlocal RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Dlocal {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let sync_data = dlocal::DlocalRefundsSyncRequest::try_from(req)?;
Ok(format!(
"{}refunds/{}/status",
self.base_url(connectors),
sync_data.refund_id,
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
router_env::logger::debug!(dlocal_refund_sync_response=?res);
let response: dlocal::RefundResponse = res
.response
.parse_struct("Dlocal RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Dlocal {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
Ok(IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
lazy_static! {
static ref DLOCAL_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::CartesBancaires,
];
let mut dlocal_supported_payment_methods = SupportedPaymentMethods::new();
dlocal_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
dlocal_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
dlocal_supported_payment_methods
};
static ref DLOCAL_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "DLOCAL",
description:
"Dlocal is a cross-border payment processor enabling businesses to accept and send payments in emerging markets worldwide.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static ref DLOCAL_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
}
impl ConnectorSpecifications for Dlocal {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*DLOCAL_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*DLOCAL_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*DLOCAL_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/dlocal.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 5,888
| null | null | null | null | null | null | null |
// Struct: RedisValue
// File: crates/redis_interface/src/types.rs
// Module: redis_interface
// Implementations: 2
// Traits: std::ops::Deref
pub struct RedisValue
|
crates/redis_interface/src/types.rs
|
redis_interface
|
struct_definition
|
RedisValue
| 2
|
[
"std::ops::Deref"
] | 44
| null | null | null | null | null | null | null |
// Implementation: impl Responder
// File: crates/router/src/analytics.rs
// Module: router
// Methods: 0 total (0 public)
impl Responder
|
crates/router/src/analytics.rs
|
router
|
impl_block
| null | null | null | 35
| null |
Responder
| null | 0
| 0
| null | null |
// Function: get_connector_choice
// File: crates/router/src/core/payments.rs
// Module: router
pub fn get_connector_choice<F, Req, D>(
operation: &BoxedOperation<'_, F, Req, D>,
state: &SessionState,
req: &Req,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
payment_data: &mut D,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<Option<ConnectorCallType>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
|
crates/router/src/core/payments.rs
|
router
|
function_signature
| null | null | null | 161
|
get_connector_choice
| null | null | null | null | null | null |
// File: crates/router/tests/connectors/mollie.rs
// Module: router
use router::types;
use crate::{
connector_auth,
utils::{self, ConnectorActions},
};
#[allow(dead_code)]
#[derive(Clone, Copy)]
struct MollieTest;
impl ConnectorActions for MollieTest {}
impl utils::Connector for MollieTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Mollie;
utils::construct_connector_data_old(
Box::new(Mollie::new()),
types::Connector::Mollie,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.mollie
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"mollie".to_string()
}
}
|
crates/router/tests/connectors/mollie.rs
|
router
|
full_file
| null | null | null | 221
| null | null | null | null | null | null | null |
// File: crates/router/src/macros.rs
// Module: router
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
|
full_file
| null | null | null | 401
| null | null | null | null | null | null | null |
// File: crates/analytics/src/disputes/filters.rs
// Module: analytics
// Public functions: 1
// Public structs: 1
use api_models::analytics::{disputes::DisputeDimensions, Granularity, TimeRange};
use common_utils::errors::ReportSwitchExt;
use diesel_models::enums::Currency;
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 DisputeFilterAnalytics: LoadRow<DisputeFilterRow> {}
pub async fn get_dispute_filter_for_dimension<T>(
dimension: DisputeDimensions,
auth: &AuthInfo,
time_range: &TimeRange,
pool: &T,
) -> FiltersResult<Vec<DisputeFilterRow>>
where
T: AnalyticsDataSource + DisputeFilterAnalytics,
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::Dispute);
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::<DisputeFilterRow, _>(pool)
.await
.change_context(FiltersError::QueryBuildingError)?
.change_context(FiltersError::QueryExecutionFailure)
}
#[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub struct DisputeFilterRow {
pub connector: Option<String>,
pub dispute_status: Option<String>,
pub connector_status: Option<String>,
pub dispute_stage: Option<String>,
pub currency: Option<DBEnumWrapper<Currency>>,
}
|
crates/analytics/src/disputes/filters.rs
|
analytics
|
full_file
| null | null | null | 464
| null | null | null | null | null | null | null |
// Struct: BluesnapRouterData
// File: crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct BluesnapRouterData<T>
|
crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
BluesnapRouterData
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Struct: CybersourceErrorInformation
// File: crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CybersourceErrorInformation
|
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CybersourceErrorInformation
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Trait: TransitionTo
// File: crates/router/src/core/cards_info.rs
// Module: router
pub trait TransitionTo<S: State>
|
crates/router/src/core/cards_info.rs
|
router
|
trait_definition
| null | null | null | 30
| null | null |
TransitionTo
| null | null | null | null |
// File: crates/api_models/src/events/external_service_auth.rs
// Module: api_models
use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::external_service_auth::{
ExternalSignoutTokenRequest, ExternalTokenResponse, ExternalVerifyTokenRequest,
ExternalVerifyTokenResponse,
};
impl ApiEventMetric for ExternalTokenResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ExternalServiceAuth)
}
}
impl ApiEventMetric for ExternalVerifyTokenRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ExternalServiceAuth)
}
}
impl ApiEventMetric for ExternalVerifyTokenResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ExternalServiceAuth)
}
}
impl ApiEventMetric for ExternalSignoutTokenRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ExternalServiceAuth)
}
}
|
crates/api_models/src/events/external_service_auth.rs
|
api_models
|
full_file
| null | null | null | 224
| null | null | null | null | null | null | null |
// Struct: Mpgs
// File: crates/hyperswitch_connectors/src/connectors/mpgs.rs
// Module: hyperswitch_connectors
// Implementations: 17
// Traits: api::Payment, api::PaymentSession, api::ConnectorAccessToken, api::MandateSetup, api::PaymentAuthorize, api::PaymentSync, api::PaymentCapture, api::PaymentVoid, api::Refund, api::RefundExecute, api::RefundSync, api::PaymentToken, ConnectorCommon, ConnectorValidation, webhooks::IncomingWebhook, ConnectorSpecifications
pub struct Mpgs
|
crates/hyperswitch_connectors/src/connectors/mpgs.rs
|
hyperswitch_connectors
|
struct_definition
|
Mpgs
| 17
|
[
"api::Payment",
"api::PaymentSession",
"api::ConnectorAccessToken",
"api::MandateSetup",
"api::PaymentAuthorize",
"api::PaymentSync",
"api::PaymentCapture",
"api::PaymentVoid",
"api::Refund",
"api::RefundExecute",
"api::RefundSync",
"api::PaymentToken",
"ConnectorCommon",
"ConnectorValidation",
"webhooks::IncomingWebhook",
"ConnectorSpecifications"
] | 127
| null | null | null | null | null | null | null |
// Function: retrieve_file_from_theme_bucket
// File: crates/router/src/utils/user/theme.rs
// Module: router
pub fn retrieve_file_from_theme_bucket(
state: &SessionState,
path: &PathBuf,
) -> UserResult<Vec<u8>>
|
crates/router/src/utils/user/theme.rs
|
router
|
function_signature
| null | null | null | 55
|
retrieve_file_from_theme_bucket
| null | null | null | null | null | null |
// Implementation: impl AwsFileStorageClient
// File: crates/external_services/src/file_storage/aws_s3.rs
// Module: external_services
// Methods: 4 total (0 public)
impl AwsFileStorageClient
|
crates/external_services/src/file_storage/aws_s3.rs
|
external_services
|
impl_block
| null | null | null | 45
| null |
AwsFileStorageClient
| null | 4
| 0
| null | null |
// Function: to_merchant_connector_info
// File: crates/api_models/src/admin.rs
// Module: api_models
pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo
|
crates/api_models/src/admin.rs
|
api_models
|
function_signature
| null | null | null | 45
|
to_merchant_connector_info
| null | null | null | null | null | null |
// Function: insert_merchant_scoped_metadata_to_db
// File: crates/router/src/utils/user/dashboard_metadata.rs
// Module: router
pub fn insert_merchant_scoped_metadata_to_db(
state: &SessionState,
user_id: String,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
metadata_key: DBEnum,
metadata_value: impl serde::Serialize,
) -> UserResult<DashboardMetadata>
|
crates/router/src/utils/user/dashboard_metadata.rs
|
router
|
function_signature
| null | null | null | 97
|
insert_merchant_scoped_metadata_to_db
| null | null | null | null | null | null |
// Struct: OrderAmount
// File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct OrderAmount
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
OrderAmount
| 0
|
[] | 45
| null | null | null | null | null | null | null |
"Pietà" => Ok(Self::Pietà),
"Qala" => Ok(Self::Qala),
"Qormi" => Ok(Self::Qormi),
"Qrendi" => Ok(Self::Qrendi),
"Rabat" => Ok(Self::Rabat),
"Saint Lawrence" => Ok(Self::SaintLawrence),
"San Ġwann" => Ok(Self::SanĠwann),
"Sannat" => Ok(Self::Sannat),
"Santa Luċija" => Ok(Self::SantaLuċija),
"Santa Venera" => Ok(Self::SantaVenera),
"Siġġiewi" => Ok(Self::Siġġiewi),
"Sliema" => Ok(Self::Sliema),
"St. Julian's" => Ok(Self::StJulians),
"St. Paul's Bay" => Ok(Self::StPaulsBay),
"Swieqi" => Ok(Self::Swieqi),
"Ta' Xbiex" => Ok(Self::TaXbiex),
"Tarxien" => Ok(Self::Tarxien),
"Valletta" => Ok(Self::Valletta),
"Victoria" => Ok(Self::Victoria),
"Xagħra" => Ok(Self::Xagħra),
"Xewkija" => Ok(Self::Xewkija),
"Xgħajra" => Ok(Self::Xgħajra),
"Żabbar" => Ok(Self::Żabbar),
"Żebbuġ Gozo" => Ok(Self::ŻebbuġGozo),
"Żebbuġ Malta" => Ok(Self::ŻebbuġMalta),
"Żejtun" => Ok(Self::Żejtun),
"Żurrieq" => Ok(Self::Żurrieq),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for BelarusStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "BelarusStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Brest Region" => Ok(Self::BrestRegion),
"Gomel Region" => Ok(Self::GomelRegion),
"Grodno Region" => Ok(Self::GrodnoRegion),
"Minsk" => Ok(Self::Minsk),
"Minsk Region" => Ok(Self::MinskRegion),
"Mogilev Region" => Ok(Self::MogilevRegion),
"Vitebsk Region" => Ok(Self::VitebskRegion),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for IrelandStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "IrelandStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Connacht" => Ok(Self::Connacht),
"County Carlow" => Ok(Self::CountyCarlow),
"County Cavan" => Ok(Self::CountyCavan),
"County Clare" => Ok(Self::CountyClare),
"County Cork" => Ok(Self::CountyCork),
"County Donegal" => Ok(Self::CountyDonegal),
"County Dublin" => Ok(Self::CountyDublin),
"County Galway" => Ok(Self::CountyGalway),
"County Kerry" => Ok(Self::CountyKerry),
"County Kildare" => Ok(Self::CountyKildare),
"County Kilkenny" => Ok(Self::CountyKilkenny),
"County Laois" => Ok(Self::CountyLaois),
"County Limerick" => Ok(Self::CountyLimerick),
"County Longford" => Ok(Self::CountyLongford),
"County Louth" => Ok(Self::CountyLouth),
"County Mayo" => Ok(Self::CountyMayo),
"County Meath" => Ok(Self::CountyMeath),
"County Monaghan" => Ok(Self::CountyMonaghan),
"County Offaly" => Ok(Self::CountyOffaly),
"County Roscommon" => Ok(Self::CountyRoscommon),
"County Sligo" => Ok(Self::CountySligo),
"County Tipperary" => Ok(Self::CountyTipperary),
"County Waterford" => Ok(Self::CountyWaterford),
"County Westmeath" => Ok(Self::CountyWestmeath),
"County Wexford" => Ok(Self::CountyWexford),
"County Wicklow" => Ok(Self::CountyWicklow),
"Leinster" => Ok(Self::Leinster),
"Munster" => Ok(Self::Munster),
"Ulster" => Ok(Self::Ulster),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for IcelandStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "IcelandStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Capital Region" => Ok(Self::CapitalRegion),
"Eastern Region" => Ok(Self::EasternRegion),
"Northeastern Region" => Ok(Self::NortheasternRegion),
"Northwestern Region" => Ok(Self::NorthwesternRegion),
"Southern Peninsula Region" => Ok(Self::SouthernPeninsulaRegion),
"Southern Region" => Ok(Self::SouthernRegion),
"Western Region" => Ok(Self::WesternRegion),
"Westfjords" => Ok(Self::Westfjords),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for HungaryStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "HungaryStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Baranya County" => Ok(Self::BaranyaCounty),
"Borsod-Abaúj-Zemplén County" => Ok(Self::BorsodAbaujZemplenCounty),
"Budapest" => Ok(Self::Budapest),
"Bács-Kiskun County" => Ok(Self::BacsKiskunCounty),
"Békés County" => Ok(Self::BekesCounty),
"Békéscsaba" => Ok(Self::Bekescsaba),
"Csongrád County" => Ok(Self::CsongradCounty),
"Debrecen" => Ok(Self::Debrecen),
"Dunaújváros" => Ok(Self::Dunaujvaros),
"Eger" => Ok(Self::Eger),
"Fejér County" => Ok(Self::FejerCounty),
"Győr" => Ok(Self::Gyor),
"Győr-Moson-Sopron County" => Ok(Self::GyorMosonSopronCounty),
"Hajdú-Bihar County" => Ok(Self::HajduBiharCounty),
"Heves County" => Ok(Self::HevesCounty),
"Hódmezővásárhely" => Ok(Self::Hodmezovasarhely),
"Jász-Nagykun-Szolnok County" => Ok(Self::JaszNagykunSzolnokCounty),
"Kaposvár" => Ok(Self::Kaposvar),
"Kecskemét" => Ok(Self::Kecskemet),
"Miskolc" => Ok(Self::Miskolc),
"Nagykanizsa" => Ok(Self::Nagykanizsa),
"Nyíregyháza" => Ok(Self::Nyiregyhaza),
"Nógrád County" => Ok(Self::NogradCounty),
"Pest County" => Ok(Self::PestCounty),
"Pécs" => Ok(Self::Pecs),
"Salgótarján" => Ok(Self::Salgotarjan),
"Somogy County" => Ok(Self::SomogyCounty),
"Sopron" => Ok(Self::Sopron),
"Szabolcs-Szatmár-Bereg County" => Ok(Self::SzabolcsSzatmarBeregCounty),
"Szeged" => Ok(Self::Szeged),
"Szekszárd" => Ok(Self::Szekszard),
"Szolnok" => Ok(Self::Szolnok),
"Szombathely" => Ok(Self::Szombathely),
"Székesfehérvár" => Ok(Self::Szekesfehervar),
"Tatabánya" => Ok(Self::Tatabanya),
"Tolna County" => Ok(Self::TolnaCounty),
"Vas County" => Ok(Self::VasCounty),
"Veszprém" => Ok(Self::Veszprem),
"Veszprém County" => Ok(Self::VeszpremCounty),
"Zala County" => Ok(Self::ZalaCounty),
"Zalaegerszeg" => Ok(Self::Zalaegerszeg),
"Érd" => Ok(Self::Erd),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for GreeceStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "GreeceStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Achaea Regional Unit" => Ok(Self::AchaeaRegionalUnit),
"Aetolia-Acarnania Regional Unit" => Ok(Self::AetoliaAcarnaniaRegionalUnit),
"Arcadia Prefecture" => Ok(Self::ArcadiaPrefecture),
"Argolis Regional Unit" => Ok(Self::ArgolisRegionalUnit),
"Attica Region" => Ok(Self::AtticaRegion),
"Boeotia Regional Unit" => Ok(Self::BoeotiaRegionalUnit),
"Central Greece Region" => Ok(Self::CentralGreeceRegion),
"Central Macedonia" => Ok(Self::CentralMacedonia),
"Chania Regional Unit" => Ok(Self::ChaniaRegionalUnit),
"Corfu Prefecture" => Ok(Self::CorfuPrefecture),
"Corinthia Regional Unit" => Ok(Self::CorinthiaRegionalUnit),
"Crete Region" => Ok(Self::CreteRegion),
"Drama Regional Unit" => Ok(Self::DramaRegionalUnit),
"East Attica Regional Unit" => Ok(Self::EastAtticaRegionalUnit),
"East Macedonia and Thrace" => Ok(Self::EastMacedoniaAndThrace),
"Epirus Region" => Ok(Self::EpirusRegion),
"Euboea" => Ok(Self::Euboea),
"Grevena Prefecture" => Ok(Self::GrevenaPrefecture),
"Imathia Regional Unit" => Ok(Self::ImathiaRegionalUnit),
"Ioannina Regional Unit" => Ok(Self::IoanninaRegionalUnit),
"Ionian Islands Region" => Ok(Self::IonianIslandsRegion),
"Karditsa Regional Unit" => Ok(Self::KarditsaRegionalUnit),
"Kastoria Regional Unit" => Ok(Self::KastoriaRegionalUnit),
"Kefalonia Prefecture" => Ok(Self::KefaloniaPrefecture),
"Kilkis Regional Unit" => Ok(Self::KilkisRegionalUnit),
"Kozani Prefecture" => Ok(Self::KozaniPrefecture),
"Laconia" => Ok(Self::Laconia),
"Larissa Prefecture" => Ok(Self::LarissaPrefecture),
"Lefkada Regional Unit" => Ok(Self::LefkadaRegionalUnit),
"Pella Regional Unit" => Ok(Self::PellaRegionalUnit),
"Peloponnese Region" => Ok(Self::PeloponneseRegion),
"Phthiotis Prefecture" => Ok(Self::PhthiotisPrefecture),
"Preveza Prefecture" => Ok(Self::PrevezaPrefecture),
"Serres Prefecture" => Ok(Self::SerresPrefecture),
"South Aegean" => Ok(Self::SouthAegean),
"Thessaloniki Regional Unit" => Ok(Self::ThessalonikiRegionalUnit),
"West Greece Region" => Ok(Self::WestGreeceRegion),
"West Macedonia Region" => Ok(Self::WestMacedoniaRegion),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for FinlandStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "FinlandStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Central Finland" => Ok(Self::CentralFinland),
"Central Ostrobothnia" => Ok(Self::CentralOstrobothnia),
"Eastern Finland Province" => Ok(Self::EasternFinlandProvince),
"Finland Proper" => Ok(Self::FinlandProper),
"Kainuu" => Ok(Self::Kainuu),
"Kymenlaakso" => Ok(Self::Kymenlaakso),
"Lapland" => Ok(Self::Lapland),
"North Karelia" => Ok(Self::NorthKarelia),
"Northern Ostrobothnia" => Ok(Self::NorthernOstrobothnia),
"Northern Savonia" => Ok(Self::NorthernSavonia),
"Ostrobothnia" => Ok(Self::Ostrobothnia),
"Oulu Province" => Ok(Self::OuluProvince),
"Pirkanmaa" => Ok(Self::Pirkanmaa),
"Päijänne Tavastia" => Ok(Self::PaijanneTavastia),
"Satakunta" => Ok(Self::Satakunta),
"South Karelia" => Ok(Self::SouthKarelia),
"Southern Ostrobothnia" => Ok(Self::SouthernOstrobothnia),
"Southern Savonia" => Ok(Self::SouthernSavonia),
"Tavastia Proper" => Ok(Self::TavastiaProper),
"Uusimaa" => Ok(Self::Uusimaa),
"Åland Islands" => Ok(Self::AlandIslands),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for DenmarkStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "DenmarkStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Capital Region of Denmark" => Ok(Self::CapitalRegionOfDenmark),
"Central Denmark Region" => Ok(Self::CentralDenmarkRegion),
"North Denmark Region" => Ok(Self::NorthDenmarkRegion),
"Region Zealand" => Ok(Self::RegionZealand),
"Region of Southern Denmark" => Ok(Self::RegionOfSouthernDenmark),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for CzechRepublicStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "CzechRepublicStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Benešov District" => Ok(Self::BenesovDistrict),
"Beroun District" => Ok(Self::BerounDistrict),
"Blansko District" => Ok(Self::BlanskoDistrict),
"Brno-City District" => Ok(Self::BrnoCityDistrict),
"Brno-Country District" => Ok(Self::BrnoCountryDistrict),
"Bruntál District" => Ok(Self::BruntalDistrict),
"Břeclav District" => Ok(Self::BreclavDistrict),
"Central Bohemian Region" => Ok(Self::CentralBohemianRegion),
"Cheb District" => Ok(Self::ChebDistrict),
"Chomutov District" => Ok(Self::ChomutovDistrict),
"Chrudim District" => Ok(Self::ChrudimDistrict),
"Domažlice Distric" => Ok(Self::DomazliceDistrict),
"Děčín District" => Ok(Self::DecinDistrict),
"Frýdek-Místek District" => Ok(Self::FrydekMistekDistrict),
"Havlíčkův Brod District" => Ok(Self::HavlickuvBrodDistrict),
"Hodonín District" => Ok(Self::HodoninDistrict),
"Horní Počernice" => Ok(Self::HorniPocernice),
"Hradec Králové District" => Ok(Self::HradecKraloveDistrict),
"Hradec Králové Region" => Ok(Self::HradecKraloveRegion),
"Jablonec nad Nisou District" => Ok(Self::JablonecNadNisouDistrict),
"Jeseník District" => Ok(Self::JesenikDistrict),
"Jihlava District" => Ok(Self::JihlavaDistrict),
"Jindřichův Hradec District" => Ok(Self::JindrichuvHradecDistrict),
"Jičín District" => Ok(Self::JicinDistrict),
"Karlovy Vary District" => Ok(Self::KarlovyVaryDistrict),
"Karlovy Vary Region" => Ok(Self::KarlovyVaryRegion),
"Karviná District" => Ok(Self::KarvinaDistrict),
"Kladno District" => Ok(Self::KladnoDistrict),
"Klatovy District" => Ok(Self::KlatovyDistrict),
"Kolín District" => Ok(Self::KolinDistrict),
"Kroměříž District" => Ok(Self::KromerizDistrict),
"Liberec District" => Ok(Self::LiberecDistrict),
"Liberec Region" => Ok(Self::LiberecRegion),
"Litoměřice District" => Ok(Self::LitomericeDistrict),
"Louny District" => Ok(Self::LounyDistrict),
"Mladá Boleslav District" => Ok(Self::MladaBoleslavDistrict),
"Moravian-Silesian Region" => Ok(Self::MoravianSilesianRegion),
"Most District" => Ok(Self::MostDistrict),
"Mělník District" => Ok(Self::MelnikDistrict),
"Nový Jičín District" => Ok(Self::NovyJicinDistrict),
"Nymburk District" => Ok(Self::NymburkDistrict),
"Náchod District" => Ok(Self::NachodDistrict),
"Olomouc District" => Ok(Self::OlomoucDistrict),
"Olomouc Region" => Ok(Self::OlomoucRegion),
"Opava District" => Ok(Self::OpavaDistrict),
"Ostrava-City District" => Ok(Self::OstravaCityDistrict),
"Pardubice District" => Ok(Self::PardubiceDistrict),
"Pardubice Region" => Ok(Self::PardubiceRegion),
"Pelhřimov District" => Ok(Self::PelhrimovDistrict),
"Plzeň Region" => Ok(Self::PlzenRegion),
"Plzeň-City District" => Ok(Self::PlzenCityDistrict),
"Plzeň-North District" => Ok(Self::PlzenNorthDistrict),
"Plzeň-South District" => Ok(Self::PlzenSouthDistrict),
"Prachatice District" => Ok(Self::PrachaticeDistrict),
"Prague" => Ok(Self::Prague),
"Prague 1" => Ok(Self::Prague1),
"Prague 10" => Ok(Self::Prague10),
"Prague 11" => Ok(Self::Prague11),
"Prague 12" => Ok(Self::Prague12),
"Prague 13" => Ok(Self::Prague13),
"Prague 14" => Ok(Self::Prague14),
"Prague 15" => Ok(Self::Prague15),
"Prague 16" => Ok(Self::Prague16),
"Prague 2" => Ok(Self::Prague2),
"Prague 21" => Ok(Self::Prague21),
"Prague 3" => Ok(Self::Prague3),
"Prague 4" => Ok(Self::Prague4),
"Prague 5" => Ok(Self::Prague5),
"Prague 6" => Ok(Self::Prague6),
"Prague 7" => Ok(Self::Prague7),
"Prague 8" => Ok(Self::Prague8),
"Prague 9" => Ok(Self::Prague9),
"Prague-East District" => Ok(Self::PragueEastDistrict),
"Prague-West District" => Ok(Self::PragueWestDistrict),
"Prostějov District" => Ok(Self::ProstejovDistrict),
"Písek District" => Ok(Self::PisekDistrict),
"Přerov District" => Ok(Self::PrerovDistrict),
"Příbram District" => Ok(Self::PribramDistrict),
"Rakovník District" => Ok(Self::RakovnikDistrict),
"Rokycany District" => Ok(Self::RokycanyDistrict),
"Rychnov nad Kněžnou District" => Ok(Self::RychnovNadKneznouDistrict),
"Semily District" => Ok(Self::SemilyDistrict),
"Sokolov District" => Ok(Self::SokolovDistrict),
"South Bohemian Region" => Ok(Self::SouthBohemianRegion),
"South Moravian Region" => Ok(Self::SouthMoravianRegion),
"Strakonice District" => Ok(Self::StrakoniceDistrict),
"Svitavy District" => Ok(Self::SvitavyDistrict),
"Tachov District" => Ok(Self::TachovDistrict),
"Teplice District" => Ok(Self::TepliceDistrict),
"Trutnov District" => Ok(Self::TrutnovDistrict),
"Tábor District" => Ok(Self::TaborDistrict),
"Třebíč District" => Ok(Self::TrebicDistrict),
"Uherské Hradiště District" => Ok(Self::UherskeHradisteDistrict),
"Vsetín District" => Ok(Self::VsetinDistrict),
"Vysočina Region" => Ok(Self::VysocinaRegion),
"Vyškov District" => Ok(Self::VyskovDistrict),
"Zlín District" => Ok(Self::ZlinDistrict),
"Zlín Region" => Ok(Self::ZlinRegion),
"Znojmo District" => Ok(Self::ZnojmoDistrict),
"Ústí nad Labem District" => Ok(Self::UstiNadLabemDistrict),
"Ústí nad Labem Region" => Ok(Self::UstiNadLabemRegion),
"Ústí nad Orlicí District" => Ok(Self::UstiNadOrliciDistrict),
"Česká Lípa District" => Ok(Self::CeskaLipaDistrict),
"České Budějovice District" => Ok(Self::CeskeBudejoviceDistrict),
"Český Krumlov District" => Ok(Self::CeskyKrumlovDistrict),
"Šumperk District" => Ok(Self::SumperkDistrict),
"Žďár nad Sázavou District" => Ok(Self::ZdarNadSazavouDistrict),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for CroatiaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "CroatiaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Bjelovar-Bilogora County" => Ok(Self::BjelovarBilogoraCounty),
"Brod-Posavina County" => Ok(Self::BrodPosavinaCounty),
"Dubrovnik-Neretva County" => Ok(Self::DubrovnikNeretvaCounty),
"Istria County" => Ok(Self::IstriaCounty),
"Koprivnica-Križevci County" => Ok(Self::KoprivnicaKrizevciCounty),
"Krapina-Zagorje County" => Ok(Self::KrapinaZagorjeCounty),
"Lika-Senj County" => Ok(Self::LikaSenjCounty),
"Međimurje County" => Ok(Self::MedimurjeCounty),
"Osijek-Baranja County" => Ok(Self::OsijekBaranjaCounty),
"Požega-Slavonia County" => Ok(Self::PozegaSlavoniaCounty),
"Primorje-Gorski Kotar County" => Ok(Self::PrimorjeGorskiKotarCounty),
"Sisak-Moslavina County" => Ok(Self::SisakMoslavinaCounty),
"Split-Dalmatia County" => Ok(Self::SplitDalmatiaCounty),
"Varaždin County" => Ok(Self::VarazdinCounty),
"Virovitica-Podravina County" => Ok(Self::ViroviticaPodravinaCounty),
"Vukovar-Syrmia County" => Ok(Self::VukovarSyrmiaCounty),
"Zadar County" => Ok(Self::ZadarCounty),
"Zagreb" => Ok(Self::Zagreb),
"Zagreb County" => Ok(Self::ZagrebCounty),
"Šibenik-Knin County" => Ok(Self::SibenikKninCounty),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for BulgariaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "BulgariaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Blagoevgrad Province" => Ok(Self::BlagoevgradProvince),
"Burgas Province" => Ok(Self::BurgasProvince),
"Dobrich Province" => Ok(Self::DobrichProvince),
"Gabrovo Province" => Ok(Self::GabrovoProvince),
"Haskovo Province" => Ok(Self::HaskovoProvince),
"Kardzhali Province" => Ok(Self::KardzhaliProvince),
"Kyustendil Province" => Ok(Self::KyustendilProvince),
"Lovech Province" => Ok(Self::LovechProvince),
"Montana Province" => Ok(Self::MontanaProvince),
"Pazardzhik Province" => Ok(Self::PazardzhikProvince),
"Pernik Province" => Ok(Self::PernikProvince),
"Pleven Province" => Ok(Self::PlevenProvince),
"Plovdiv Province" => Ok(Self::PlovdivProvince),
"Razgrad Province" => Ok(Self::RazgradProvince),
"Ruse Province" => Ok(Self::RuseProvince),
"Shumen" => Ok(Self::Shumen),
"Silistra Province" => Ok(Self::SilistraProvince),
"Sliven Province" => Ok(Self::SlivenProvince),
"Smolyan Province" => Ok(Self::SmolyanProvince),
"Sofia City Province" => Ok(Self::SofiaCityProvince),
"Sofia Province" => Ok(Self::SofiaProvince),
"Stara Zagora Province" => Ok(Self::StaraZagoraProvince),
"Targovishte Provinc" => Ok(Self::TargovishteProvince),
"Varna Province" => Ok(Self::VarnaProvince),
"Veliko Tarnovo Province" => Ok(Self::VelikoTarnovoProvince),
"Vidin Province" => Ok(Self::VidinProvince),
"Vratsa Province" => Ok(Self::VratsaProvince),
"Yambol Province" => Ok(Self::YambolProvince),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for BosniaAndHerzegovinaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "BosniaAndHerzegovinaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Bosnian Podrinje Canton" => Ok(Self::BosnianPodrinjeCanton),
"Brčko District" => Ok(Self::BrckoDistrict),
"Canton 10" => Ok(Self::Canton10),
"Central Bosnia Canton" => Ok(Self::CentralBosniaCanton),
"Federation of Bosnia and Herzegovina" => {
Ok(Self::FederationOfBosniaAndHerzegovina)
}
"Herzegovina-Neretva Canton" => Ok(Self::HerzegovinaNeretvaCanton),
"Posavina Canton" => Ok(Self::PosavinaCanton),
"Republika Srpska" => Ok(Self::RepublikaSrpska),
"Sarajevo Canton" => Ok(Self::SarajevoCanton),
"Tuzla Canton" => Ok(Self::TuzlaCanton),
"Una-Sana Canton" => Ok(Self::UnaSanaCanton),
"West Herzegovina Canton" => Ok(Self::WestHerzegovinaCanton),
"Zenica-Doboj Canton" => Ok(Self::ZenicaDobojCanton),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for UnitedKingdomStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "UnitedKingdomStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Aberdeen" => Ok(Self::Aberdeen),
"Aberdeenshire" => Ok(Self::Aberdeenshire),
"Angus" => Ok(Self::Angus),
"Antrim" => Ok(Self::Antrim),
"Antrim and Newtownabbey" => Ok(Self::AntrimAndNewtownabbey),
"Ards" => Ok(Self::Ards),
"Ards and North Down" => Ok(Self::ArdsAndNorthDown),
"Argyll and Bute" => Ok(Self::ArgyllAndBute),
"Armagh City and District Council" => Ok(Self::ArmaghCityAndDistrictCouncil),
"Armagh, Banbridge and Craigavon" => Ok(Self::ArmaghBanbridgeAndCraigavon),
"Ascension Island" => Ok(Self::AscensionIsland),
"Ballymena Borough" => Ok(Self::BallymenaBorough),
"Ballymoney" => Ok(Self::Ballymoney),
"Banbridge" => Ok(Self::Banbridge),
"Barnsley" => Ok(Self::Barnsley),
"Bath and North East Somerset" => Ok(Self::BathAndNorthEastSomerset),
"Bedford" => Ok(Self::Bedford),
"Belfast district" => Ok(Self::BelfastDistrict),
"Birmingham" => Ok(Self::Birmingham),
"Blackburn with Darwen" => Ok(Self::BlackburnWithDarwen),
"Blackpool" => Ok(Self::Blackpool),
"Blaenau Gwent County Borough" => Ok(Self::BlaenauGwentCountyBorough),
"Bolton" => Ok(Self::Bolton),
"Bournemouth" => Ok(Self::Bournemouth),
"Bracknell Forest" => Ok(Self::BracknellForest),
"Bradford" => Ok(Self::Bradford),
"Bridgend County Borough" => Ok(Self::BridgendCountyBorough),
"Brighton and Hove" => Ok(Self::BrightonAndHove),
"Buckinghamshire" => Ok(Self::Buckinghamshire),
"Bury" => Ok(Self::Bury),
"Caerphilly County Borough" => Ok(Self::CaerphillyCountyBorough),
"Calderdale" => Ok(Self::Calderdale),
"Cambridgeshire" => Ok(Self::Cambridgeshire),
"Carmarthenshire" => Ok(Self::Carmarthenshire),
"Carrickfergus Borough Council" => Ok(Self::CarrickfergusBoroughCouncil),
"Castlereagh" => Ok(Self::Castlereagh),
"Causeway Coast and Glens" => Ok(Self::CausewayCoastAndGlens),
"Central Bedfordshire" => Ok(Self::CentralBedfordshire),
"Ceredigion" => Ok(Self::Ceredigion),
|
crates/hyperswitch_connectors/src/utils.rs#chunk6
|
hyperswitch_connectors
|
chunk
| null | null | null | 8,188
| null | null | null | null | null | null | null |
// Function: profile_delete
// File: crates/openapi/src/routes/profile.rs
// Module: openapi
pub fn profile_delete()
|
crates/openapi/src/routes/profile.rs
|
openapi
|
function_signature
| null | null | null | 28
|
profile_delete
| null | null | null | null | null | null |
// Struct: AirwallexCard
// File: crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct AirwallexCard
|
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
AirwallexCard
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Struct: BraintreeWebhookResponse
// File: crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct BraintreeWebhookResponse
|
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
BraintreeWebhookResponse
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentPostCaptureVoid for for Worldpayvantiv
// File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentPostCaptureVoid for for Worldpayvantiv
|
crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 67
| null |
Worldpayvantiv
|
api::PaymentPostCaptureVoid for
| 0
| 0
| null | null |
// Struct: AmazonpayRefundRequest
// File: crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct AmazonpayRefundRequest
|
crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
AmazonpayRefundRequest
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentVoid for for Deutschebank
// File: crates/hyperswitch_connectors/src/connectors/deutschebank.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Deutschebank
|
crates/hyperswitch_connectors/src/connectors/deutschebank.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Deutschebank
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Function: find_by_merchant_id_payment_id_address_id
// File: crates/diesel_models/src/query/address.rs
// Module: diesel_models
pub fn find_by_merchant_id_payment_id_address_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
address_id: &str,
) -> StorageResult<Self>
|
crates/diesel_models/src/query/address.rs
|
diesel_models
|
function_signature
| null | null | null | 94
|
find_by_merchant_id_payment_id_address_id
| null | null | null | null | null | null |
// Struct: MerchantAdvice
// File: crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct MerchantAdvice
|
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
MerchantAdvice
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// File: crates/analytics/src/payments/core.rs
// Module: analytics
// Public functions: 2
#![allow(dead_code)]
use std::collections::{HashMap, HashSet};
use api_models::analytics::{
payments::{
MetricsBucketResponse, PaymentDimensions, PaymentDistributions, PaymentMetrics,
PaymentMetricsBucketIdentifier,
},
FilterValue, GetPaymentFiltersRequest, GetPaymentMetricRequest, PaymentFiltersResponse,
PaymentsAnalyticsMetadata, PaymentsMetricsResponse,
};
use bigdecimal::ToPrimitive;
use common_enums::Currency;
use common_utils::errors::CustomResult;
use currency_conversion::{conversion::convert, types::ExchangeRates};
use error_stack::ResultExt;
use router_env::{
instrument, logger,
tracing::{self, Instrument},
};
use super::{
distribution::PaymentDistributionRow,
filters::{get_payment_filter_for_dimension, PaymentFilterRow},
metrics::PaymentMetricRow,
PaymentMetricsAccumulator,
};
use crate::{
enums::AuthInfo,
errors::{AnalyticsError, AnalyticsResult},
metrics,
payments::{PaymentDistributionAccumulator, PaymentMetricAccumulator},
AnalyticsProvider,
};
#[derive(Debug)]
pub enum TaskType {
MetricTask(
PaymentMetrics,
CustomResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, AnalyticsError>,
),
DistributionTask(
PaymentDistributions,
CustomResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>, AnalyticsError>,
),
}
#[instrument(skip_all)]
pub async fn get_metrics(
pool: &AnalyticsProvider,
ex_rates: &Option<ExchangeRates>,
auth: &AuthInfo,
req: GetPaymentMetricRequest,
) -> AnalyticsResult<PaymentsMetricsResponse<MetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<
PaymentMetricsBucketIdentifier,
PaymentMetricsAccumulator,
> = HashMap::new();
let mut set = tokio::task::JoinSet::new();
for metric_type in req.metrics.iter().cloned() {
let req = req.clone();
let pool = pool.clone();
let task_span = tracing::debug_span!(
"analytics_payments_metrics_query",
payment_metric = metric_type.as_ref()
);
// TODO: lifetime issues with joinset,
// can be optimized away if joinset lifetime requirements are relaxed
let auth_scoped = auth.to_owned();
set.spawn(
async move {
let data = pool
.get_payment_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_payments_distribution_query",
payment_distribution = distribution.distribution_for.as_ref()
);
let auth_scoped = auth.to_owned();
set.spawn(
async move {
let data = pool
.get_payment_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 {
PaymentMetrics::PaymentSuccessRate
| PaymentMetrics::SessionizedPaymentSuccessRate => metrics_builder
.payment_success_rate
.add_metrics_bucket(&value),
PaymentMetrics::PaymentCount | PaymentMetrics::SessionizedPaymentCount => {
metrics_builder.payment_count.add_metrics_bucket(&value)
}
PaymentMetrics::PaymentSuccessCount
| PaymentMetrics::SessionizedPaymentSuccessCount => {
metrics_builder.payment_success.add_metrics_bucket(&value)
}
PaymentMetrics::PaymentProcessedAmount
| PaymentMetrics::SessionizedPaymentProcessedAmount => {
metrics_builder.processed_amount.add_metrics_bucket(&value)
}
PaymentMetrics::AvgTicketSize
| PaymentMetrics::SessionizedAvgTicketSize => {
metrics_builder.avg_ticket_size.add_metrics_bucket(&value)
}
PaymentMetrics::RetriesCount | PaymentMetrics::SessionizedRetriesCount => {
metrics_builder.retries_count.add_metrics_bucket(&value);
metrics_builder
.retries_amount_processed
.add_metrics_bucket(&value)
}
PaymentMetrics::ConnectorSuccessRate
| PaymentMetrics::SessionizedConnectorSuccessRate => {
metrics_builder
.connector_success_rate
.add_metrics_bucket(&value);
}
PaymentMetrics::DebitRouting | PaymentMetrics::SessionizedDebitRouting => {
metrics_builder.debit_routing.add_metrics_bucket(&value);
}
PaymentMetrics::PaymentsDistribution => {
metrics_builder
.payments_distribution
.add_metrics_bucket(&value);
}
PaymentMetrics::FailureReasons => {
metrics_builder
.failure_reasons_distribution
.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_accumulator = metrics_accumulator.entry(id).or_default();
match distribution {
PaymentDistributions::PaymentErrorMessage => metrics_accumulator
.payment_error_message
.add_distribution_bucket(&value),
}
}
logger::debug!(
"Analytics Accumulated Results: distribution: {}, results: {:#?}",
distribution,
metrics_accumulator
);
}
}
}
let mut total_payment_processed_amount = 0;
let mut total_payment_processed_count = 0;
let mut total_payment_processed_amount_without_smart_retries = 0;
let mut total_payment_processed_count_without_smart_retries = 0;
let mut total_failure_reasons_count = 0;
let mut total_failure_reasons_count_without_smart_retries = 0;
let mut total_payment_processed_amount_in_usd = 0;
let mut total_payment_processed_amount_without_smart_retries_usd = 0;
let query_data: Vec<MetricsBucketResponse> = metrics_accumulator
.into_iter()
.map(|(id, val)| {
let mut collected_values = val.collect();
if let Some(amount) = collected_values.payment_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.payment_processed_amount_in_usd = amount_in_usd;
total_payment_processed_amount += amount;
total_payment_processed_amount_in_usd += amount_in_usd.unwrap_or(0);
}
if let Some(count) = collected_values.payment_processed_count {
total_payment_processed_count += count;
}
if let Some(amount) = collected_values.payment_processed_amount_without_smart_retries {
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.payment_processed_amount_without_smart_retries_usd = amount_in_usd;
total_payment_processed_amount_without_smart_retries += amount;
total_payment_processed_amount_without_smart_retries_usd +=
amount_in_usd.unwrap_or(0);
}
if let Some(count) = collected_values.payment_processed_count_without_smart_retries {
total_payment_processed_count_without_smart_retries += count;
}
if let Some(count) = collected_values.failure_reason_count {
total_failure_reasons_count += count;
}
if let Some(count) = collected_values.failure_reason_count_without_smart_retries {
total_failure_reasons_count_without_smart_retries += count;
}
if let Some(savings) = collected_values.debit_routing_savings {
let savings_in_usd = if let Some(ex_rates) = ex_rates {
id.currency
.and_then(|currency| {
i64::try_from(savings)
.inspect_err(|e| {
logger::error!(
"Debit Routing savings conversion error: {:?}",
e
)
})
.ok()
.and_then(|savings_i64| {
convert(ex_rates, currency, Currency::USD, savings_i64)
.inspect_err(|e| {
logger::error!("Currency conversion error: {:?}", e)
})
.ok()
})
})
.map(|savings| (savings * rust_decimal::Decimal::new(100, 0)).to_u64())
.unwrap_or_default()
} else {
None
};
collected_values.debit_routing_savings_in_usd = savings_in_usd;
}
MetricsBucketResponse {
values: collected_values,
dimensions: id,
}
})
.collect();
Ok(PaymentsMetricsResponse {
query_data,
meta_data: [PaymentsAnalyticsMetadata {
total_payment_processed_amount: Some(total_payment_processed_amount),
total_payment_processed_amount_in_usd: if ex_rates.is_some() {
Some(total_payment_processed_amount_in_usd)
} else {
None
},
total_payment_processed_amount_without_smart_retries: Some(
total_payment_processed_amount_without_smart_retries,
),
total_payment_processed_amount_without_smart_retries_usd: if ex_rates.is_some() {
Some(total_payment_processed_amount_without_smart_retries_usd)
} else {
None
},
total_payment_processed_count: Some(total_payment_processed_count),
total_payment_processed_count_without_smart_retries: Some(
total_payment_processed_count_without_smart_retries,
),
total_failure_reasons_count: Some(total_failure_reasons_count),
total_failure_reasons_count_without_smart_retries: Some(
total_failure_reasons_count_without_smart_retries,
),
}],
})
}
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetPaymentFiltersRequest,
auth: &AuthInfo,
) -> AnalyticsResult<PaymentFiltersResponse> {
let mut res = PaymentFiltersResponse::default();
for dim in req.group_by_names {
let values = match pool {
AnalyticsProvider::Sqlx(pool) => {
get_payment_filter_for_dimension(dim, auth, &req.time_range, pool)
.await
}
AnalyticsProvider::Clickhouse(pool) => {
get_payment_filter_for_dimension(dim, auth, &req.time_range, pool)
.await
}
AnalyticsProvider::CombinedCkh(sqlx_poll, ckh_pool) => {
let ckh_result = get_payment_filter_for_dimension(
dim,
auth,
&req.time_range,
ckh_pool,
)
.await;
let sqlx_result = get_payment_filter_for_dimension(
dim,
auth,
&req.time_range,
sqlx_poll,
)
.await;
match (&sqlx_result, &ckh_result) {
(Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics filters")
},
_ => {}
};
ckh_result
}
AnalyticsProvider::CombinedSqlx(sqlx_poll, ckh_pool) => {
let ckh_result = get_payment_filter_for_dimension(
dim,
auth,
&req.time_range,
ckh_pool,
)
.await;
let sqlx_result = get_payment_filter_for_dimension(
dim,
auth,
&req.time_range,
sqlx_poll,
)
.await;
match (&sqlx_result, &ckh_result) {
(Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics filters")
},
_ => {}
};
sqlx_result
}
}
.change_context(AnalyticsError::UnknownError)?
.into_iter()
.filter_map(|fil: PaymentFilterRow| match dim {
PaymentDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()),
PaymentDimensions::PaymentStatus => fil.status.map(|i| i.as_ref().to_string()),
PaymentDimensions::Connector => fil.connector,
PaymentDimensions::AuthType => fil.authentication_type.map(|i| i.as_ref().to_string()),
PaymentDimensions::PaymentMethod => fil.payment_method,
PaymentDimensions::PaymentMethodType => fil.payment_method_type,
PaymentDimensions::ClientSource => fil.client_source,
PaymentDimensions::ClientVersion => fil.client_version,
PaymentDimensions::ProfileId => fil.profile_id,
PaymentDimensions::CardNetwork => fil.card_network,
PaymentDimensions::MerchantId => fil.merchant_id,
PaymentDimensions::CardLast4 => fil.card_last_4,
PaymentDimensions::CardIssuer => fil.card_issuer,
PaymentDimensions::ErrorReason => fil.error_reason,
PaymentDimensions::RoutingApproach => fil.routing_approach.map(|i| i.as_ref().to_string()),
PaymentDimensions::SignatureNetwork => fil.signature_network,
PaymentDimensions::IsIssuerRegulated => fil.is_issuer_regulated.map(|b| b.to_string()),
PaymentDimensions::IsDebitRouted => fil.is_debit_routed.map(|b| b.to_string())
})
.collect::<Vec<String>>();
res.query_data.push(FilterValue {
dimension: dim,
values,
})
}
Ok(res)
}
|
crates/analytics/src/payments/core.rs
|
analytics
|
full_file
| null | null | null | 3,540
| null | null | null | null | null | null | null |
// Function: create_jwe_body_for_vault
// File: crates/router/src/core/payment_methods/transformers.rs
// Module: router
pub fn create_jwe_body_for_vault(
jwekey: &settings::Jwekey,
jws: &str,
) -> CustomResult<encryption::JweBody, errors::VaultError>
|
crates/router/src/core/payment_methods/transformers.rs
|
router
|
function_signature
| null | null | null | 75
|
create_jwe_body_for_vault
| null | null | null | null | null | null |
// Function: set_token_details
// File: crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
// Module: router
pub fn set_token_details(
self,
network_token: &'a NetworkTokenizationResponse,
) -> NetworkTokenizationBuilder<'a, PmTokenized>
|
crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
|
router
|
function_signature
| null | null | null | 63
|
set_token_details
| null | null | null | null | null | null |
// Implementation: impl RevenueRecoveryDataBackfillForm
// File: crates/api_models/src/revenue_recovery_data_backfill.rs
// Module: api_models
// Methods: 1 total (1 public)
impl RevenueRecoveryDataBackfillForm
|
crates/api_models/src/revenue_recovery_data_backfill.rs
|
api_models
|
impl_block
| null | null | null | 51
| null |
RevenueRecoveryDataBackfillForm
| null | 1
| 1
| null | null |
// Implementation: impl ConnectorValidation for for Mpgs
// File: crates/hyperswitch_connectors/src/connectors/mpgs.rs
// Module: hyperswitch_connectors
// Methods: 2 total (0 public)
impl ConnectorValidation for for Mpgs
|
crates/hyperswitch_connectors/src/connectors/mpgs.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 55
| null |
Mpgs
|
ConnectorValidation for
| 2
| 0
| null | null |
// Function: migrate_cards_info
// File: crates/router/src/core/cards_info.rs
// Module: router
pub fn migrate_cards_info(
state: routes::SessionState,
card_info_records: Vec<cards_info_api_types::CardInfoUpdateRequest>,
) -> RouterResponse<Vec<cards_info_api_types::CardInfoMigrationResponse>>
|
crates/router/src/core/cards_info.rs
|
router
|
function_signature
| null | null | null | 70
|
migrate_cards_info
| null | null | null | null | null | null |
// Implementation: impl api::PaymentAuthorize for for Paytm
// File: crates/hyperswitch_connectors/src/connectors/paytm.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentAuthorize for for Paytm
|
crates/hyperswitch_connectors/src/connectors/paytm.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Paytm
|
api::PaymentAuthorize for
| 0
| 0
| null | null |
// Function: from_storage
// File: crates/router/src/services/kafka/refund_event.rs
// Module: router
pub fn from_storage(refund: &'a Refund) -> Self
|
crates/router/src/services/kafka/refund_event.rs
|
router
|
function_signature
| null | null | null | 39
|
from_storage
| null | null | null | null | null | null |
// Struct: PaypalVaultResponse
// File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaypalVaultResponse
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaypalVaultResponse
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Function: submit_evidence
// File: crates/router/src/core/disputes.rs
// Module: router
pub fn submit_evidence(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: Option<common_utils::id_type::ProfileId>,
req: dispute_models::SubmitEvidenceRequest,
) -> RouterResponse<dispute_models::DisputeResponse>
|
crates/router/src/core/disputes.rs
|
router
|
function_signature
| null | null | null | 83
|
submit_evidence
| null | null | null | null | null | null |
// Implementation: impl ConnectorRedirectResponse for for Airwallex
// File: crates/hyperswitch_connectors/src/connectors/airwallex.rs
// Module: hyperswitch_connectors
// Methods: 1 total (0 public)
impl ConnectorRedirectResponse for for Airwallex
|
crates/hyperswitch_connectors/src/connectors/airwallex.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Airwallex
|
ConnectorRedirectResponse for
| 1
| 0
| null | null |
// Implementation: impl VaultingInterface for for VaultRetrieve
// File: crates/router/src/types/payment_methods.rs
// Module: router
// Methods: 2 total (0 public)
impl VaultingInterface for for VaultRetrieve
|
crates/router/src/types/payment_methods.rs
|
router
|
impl_block
| null | null | null | 46
| null |
VaultRetrieve
|
VaultingInterface for
| 2
| 0
| null | null |
// Function: is_confirm_operation
// File: crates/hyperswitch_domain_models/src/payments/payment_intent.rs
// Module: hyperswitch_domain_models
pub fn is_confirm_operation(&self) -> bool
|
crates/hyperswitch_domain_models/src/payments/payment_intent.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 42
|
is_confirm_operation
| null | null | null | null | null | null |
// Implementation: impl api::PaymentSession for for Wise
// File: crates/hyperswitch_connectors/src/connectors/wise.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSession for for Wise
|
crates/hyperswitch_connectors/src/connectors/wise.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 55
| null |
Wise
|
api::PaymentSession for
| 0
| 0
| null | null |
// Implementation: impl SecretState for for RawSecret
// File: crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs
// Module: hyperswitch_interfaces
// Methods: 0 total (0 public)
impl SecretState for for RawSecret
|
crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs
|
hyperswitch_interfaces
|
impl_block
| null | null | null | 53
| null |
RawSecret
|
SecretState for
| 0
| 0
| null | null |
// Implementation: impl IncomingWebhook for for Razorpay
// File: crates/hyperswitch_connectors/src/connectors/razorpay.rs
// Module: hyperswitch_connectors
// Methods: 4 total (0 public)
impl IncomingWebhook for for Razorpay
|
crates/hyperswitch_connectors/src/connectors/razorpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Razorpay
|
IncomingWebhook for
| 4
| 0
| null | null |
// Struct: HipayMaintenanceResponse
// File: crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct HipayMaintenanceResponse<S>
|
crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
HipayMaintenanceResponse
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Function: connector_selection
// File: crates/router/src/core/payments.rs
// Module: router
pub fn connector_selection<F, D>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
payment_data: &mut D,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
|
crates/router/src/core/payments.rs
|
router
|
function_signature
| null | null | null | 119
|
connector_selection
| null | null | null | null | null | null |
// Implementation: impl Responder
// File: crates/router/src/routes/configs.rs
// Module: router
// Methods: 0 total (0 public)
impl Responder
|
crates/router/src/routes/configs.rs
|
router
|
impl_block
| null | null | null | 36
| null |
Responder
| null | 0
| 0
| null | null |
if base.contains("{{merchant_endpoint_prefix}}") || base.contains('$') {
return Err(errors::ConnectorError::InvalidConnectorConfig {
config: "Chargebee base_url has an unresolved placeholder (expected `$` or `{{merchant_endpoint_prefix}}`).",
}
.into());
}
if !base.ends_with('/') {
base.push('/');
}
let url = format!("{base}v2/item_prices{query_params}");
Ok(url)
}
// check if get_content_type is required
fn build_request(
&self,
req: &GetSubscriptionPlanPricesRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::GetSubscriptionPlanPricesType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::GetSubscriptionPlanPricesType::get_headers(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &GetSubscriptionPlanPricesRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<GetSubscriptionPlanPricesRouterData, errors::ConnectorError> {
let response: ChargebeeGetPlanPricesResponse = res
.response
.parse_struct("chargebee ChargebeeGetPlanPricesResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl GetSubscriptionPlanPricesV2 for Chargebee {}
impl
ConnectorIntegrationV2<
GetSubscriptionPlanPrices,
hyperswitch_domain_models::router_data_v2::flow_common_types::GetSubscriptionPlanPricesData,
GetSubscriptionPlanPricesRequest,
GetSubscriptionPlanPricesResponse,
> for Chargebee
{
// TODO: implement functions when support enabled
}
impl api::subscriptions::GetSubscriptionEstimateFlow for Chargebee {}
impl
ConnectorIntegration<
GetSubscriptionEstimate,
GetSubscriptionEstimateRequest,
GetSubscriptionEstimateResponse,
> for Chargebee
{
fn get_headers(
&self,
req: &GetSubscriptionEstimateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &GetSubscriptionEstimateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let metadata: chargebee::ChargebeeMetadata =
utils::to_connector_meta_from_secret(req.connector_meta_data.clone())?;
let url = self
.base_url(connectors)
.to_string()
.replace("{{merchant_endpoint_prefix}}", metadata.site.peek());
Ok(format!("{url}v2/estimates/create_subscription_for_items"))
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_request_body(
&self,
req: &GetSubscriptionEstimateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = chargebee::ChargebeeSubscriptionEstimateRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &GetSubscriptionEstimateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::GetSubscriptionEstimateType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::GetSubscriptionEstimateType::get_headers(
self, req, connectors,
)?)
.set_body(types::GetSubscriptionEstimateType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &GetSubscriptionEstimateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<GetSubscriptionEstimateRouterData, errors::ConnectorError> {
let response: chargebee::SubscriptionEstimateResponse = res
.response
.parse_struct("chargebee SubscriptionEstimateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Chargebee {
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature = utils::get_header_key_value("authorization", request.headers)?;
let signature = base64_signature.as_bytes().to_owned();
Ok(signature)
}
async fn verify_webhook_source(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_label,
connector_webhook_details,
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let password = connector_webhook_secrets
.additional_secret
.ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Failed to get additional secrets")?;
let username = String::from_utf8(connector_webhook_secrets.secret.to_vec())
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Could not convert secret to UTF-8")?;
let secret_auth = format!(
"Basic {}",
base64::engine::general_purpose::STANDARD.encode(format!(
"{}:{}",
username,
password.peek()
))
);
let signature_auth = String::from_utf8(signature.to_vec())
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Could not convert secret to UTF-8")?;
Ok(signature_auth == secret_auth)
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook =
chargebee::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api_models::webhooks::ObjectReferenceId::InvoiceId(
api_models::webhooks::InvoiceIdType::ConnectorInvoiceId(webhook.content.invoice.id),
))
}
#[cfg(any(feature = "v1", not(all(feature = "revenue_recovery", feature = "v2"))))]
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let webhook =
chargebee::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
let event = api_models::webhooks::IncomingWebhookEvent::from(webhook.event_type);
Ok(event)
}
#[cfg(any(feature = "v1", not(all(feature = "revenue_recovery", feature = "v2"))))]
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook =
chargebee::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(webhook))
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
fn get_revenue_recovery_attempt_details(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<revenue_recovery::RevenueRecoveryAttemptData, errors::ConnectorError> {
let webhook =
transformers::ChargebeeWebhookBody::get_webhook_object_from_body(request.body)?;
revenue_recovery::RevenueRecoveryAttemptData::try_from(webhook)
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
fn get_revenue_recovery_invoice_details(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<revenue_recovery::RevenueRecoveryInvoiceData, errors::ConnectorError> {
let webhook =
transformers::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)?;
revenue_recovery::RevenueRecoveryInvoiceData::try_from(webhook)
}
}
static CHARGEBEE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Chargebee",
description: "Chargebee is a Revenue Growth Management (RGM) platform that helps subscription businesses manage subscriptions, billing, revenue recognition, collections, and customer retention, essentially streamlining the entire subscription lifecycle.",
connector_type: enums::HyperswitchConnectorCategory::RevenueGrowthManagementPlatform,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static CHARGEBEE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];
impl ConnectorSpecifications for Chargebee {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&CHARGEBEE_CONNECTOR_INFO)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&CHARGEBEE_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/chargebee.rs#chunk1
|
hyperswitch_connectors
|
chunk
| null | null | null | 2,698
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentAuthorize for for Stax
// File: crates/hyperswitch_connectors/src/connectors/stax.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentAuthorize for for Stax
|
crates/hyperswitch_connectors/src/connectors/stax.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Stax
|
api::PaymentAuthorize for
| 0
| 0
| null | null |
// Implementation: impl SerializableSecret for for u8
// File: crates/masking/src/serde.rs
// Module: masking
// Methods: 0 total (0 public)
impl SerializableSecret for for u8
|
crates/masking/src/serde.rs
|
masking
|
impl_block
| null | null | null | 44
| null |
u8
|
SerializableSecret for
| 0
| 0
| null | null |
// File: crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs
// Module: hyperswitch_connectors
// Public structs: 14
use api_models;
use common_enums::{enums, Currency};
use common_utils::{ext_traits::OptionExt as _, pii::Email};
use error_stack::ResultExt;
use hyperswitch_domain_models::types::{PayoutsResponseData, PayoutsRouterData};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use super::ErrorDetails;
use crate::{
types::{PayoutIndividualDetailsExt as _, PayoutsResponseRouterData},
utils::{CustomerDetails as _, PayoutsData as _, RouterData},
};
type Error = error_stack::Report<errors::ConnectorError>;
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StripeConnectPayoutStatus {
Canceled,
Failed,
InTransit,
Paid,
Pending,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StripeConnectErrorResponse {
pub error: ErrorDetails,
}
// Payouts
#[derive(Clone, Debug, Serialize)]
pub struct StripeConnectPayoutCreateRequest {
amount: i64,
currency: Currency,
destination: String,
transfer_group: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StripeConnectPayoutCreateResponse {
id: String,
description: Option<String>,
source_transaction: Option<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct TransferReversals {
object: String,
has_more: bool,
total_count: i32,
url: String,
}
#[derive(Clone, Debug, Serialize)]
pub struct StripeConnectPayoutFulfillRequest {
amount: i64,
currency: Currency,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StripeConnectPayoutFulfillResponse {
id: String,
currency: String,
description: Option<String>,
failure_balance_transaction: Option<String>,
failure_code: Option<String>,
failure_message: Option<String>,
original_payout: Option<String>,
reversed_by: Option<String>,
statement_descriptor: Option<String>,
status: StripeConnectPayoutStatus,
}
#[derive(Clone, Debug, Serialize)]
pub struct StripeConnectReversalRequest {
amount: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StripeConnectReversalResponse {
id: String,
source_refund: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
pub struct StripeConnectRecipientCreateRequest {
#[serde(rename = "type")]
account_type: String,
country: Option<enums::CountryAlpha2>,
email: Option<Email>,
#[serde(rename = "capabilities[card_payments][requested]")]
capabilities_card_payments: Option<bool>,
#[serde(rename = "capabilities[transfers][requested]")]
capabilities_transfers: Option<bool>,
#[serde(rename = "tos_acceptance[date]")]
tos_acceptance_date: Option<i64>,
#[serde(rename = "tos_acceptance[ip]")]
tos_acceptance_ip: Option<Secret<String>>,
business_type: String,
#[serde(rename = "business_profile[mcc]")]
business_profile_mcc: Option<i32>,
#[serde(rename = "business_profile[url]")]
business_profile_url: Option<String>,
#[serde(rename = "business_profile[name]")]
business_profile_name: Option<Secret<String>>,
#[serde(rename = "company[name]")]
company_name: Option<Secret<String>>,
#[serde(rename = "company[address][line1]")]
company_address_line1: Option<Secret<String>>,
#[serde(rename = "company[address][line2]")]
company_address_line2: Option<Secret<String>>,
#[serde(rename = "company[address][postal_code]")]
company_address_postal_code: Option<Secret<String>>,
#[serde(rename = "company[address][city]")]
company_address_city: Option<Secret<String>>,
#[serde(rename = "company[address][state]")]
company_address_state: Option<Secret<String>>,
#[serde(rename = "company[phone]")]
company_phone: Option<Secret<String>>,
#[serde(rename = "company[tax_id]")]
company_tax_id: Option<Secret<String>>,
#[serde(rename = "company[owners_provided]")]
company_owners_provided: Option<bool>,
#[serde(rename = "individual[first_name]")]
individual_first_name: Option<Secret<String>>,
#[serde(rename = "individual[last_name]")]
individual_last_name: Option<Secret<String>>,
#[serde(rename = "individual[dob][day]")]
individual_dob_day: Option<Secret<String>>,
#[serde(rename = "individual[dob][month]")]
individual_dob_month: Option<Secret<String>>,
#[serde(rename = "individual[dob][year]")]
individual_dob_year: Option<Secret<String>>,
#[serde(rename = "individual[address][line1]")]
individual_address_line1: Option<Secret<String>>,
#[serde(rename = "individual[address][line2]")]
individual_address_line2: Option<Secret<String>>,
#[serde(rename = "individual[address][postal_code]")]
individual_address_postal_code: Option<Secret<String>>,
#[serde(rename = "individual[address][city]")]
individual_address_city: Option<String>,
#[serde(rename = "individual[address][state]")]
individual_address_state: Option<Secret<String>>,
#[serde(rename = "individual[email]")]
individual_email: Option<Email>,
#[serde(rename = "individual[phone]")]
individual_phone: Option<Secret<String>>,
#[serde(rename = "individual[id_number]")]
individual_id_number: Option<Secret<String>>,
#[serde(rename = "individual[ssn_last_4]")]
individual_ssn_last_4: Option<Secret<String>>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct StripeConnectRecipientCreateResponse {
id: String,
}
#[derive(Clone, Debug, Serialize)]
#[serde(untagged)]
pub enum StripeConnectRecipientAccountCreateRequest {
Bank(RecipientBankAccountRequest),
Card(RecipientCardAccountRequest),
Token(RecipientTokenRequest),
}
#[derive(Clone, Debug, Serialize)]
pub struct RecipientTokenRequest {
external_account: String,
}
#[derive(Clone, Debug, Serialize)]
pub struct RecipientCardAccountRequest {
#[serde(rename = "external_account[object]")]
external_account_object: String,
#[serde(rename = "external_account[number]")]
external_account_number: Secret<String>,
#[serde(rename = "external_account[exp_month]")]
external_account_exp_month: Secret<String>,
#[serde(rename = "external_account[exp_year]")]
external_account_exp_year: Secret<String>,
}
#[derive(Clone, Debug, Serialize)]
pub struct RecipientBankAccountRequest {
#[serde(rename = "external_account[object]")]
external_account_object: String,
#[serde(rename = "external_account[country]")]
external_account_country: enums::CountryAlpha2,
#[serde(rename = "external_account[currency]")]
external_account_currency: Currency,
#[serde(rename = "external_account[account_holder_name]")]
external_account_account_holder_name: Secret<String>,
#[serde(rename = "external_account[account_number]")]
external_account_account_number: Secret<String>,
#[serde(rename = "external_account[account_holder_type]")]
external_account_account_holder_type: String,
#[serde(rename = "external_account[routing_number]")]
external_account_routing_number: Secret<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StripeConnectRecipientAccountCreateResponse {
id: String,
}
// Payouts create/transfer request transform
impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectPayoutCreateRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
let connector_customer_id = item.get_connector_customer_id()?;
Ok(Self {
amount: request.amount,
currency: request.destination_currency,
destination: connector_customer_id,
transfer_group: item.connector_request_reference_id.clone(),
})
}
}
// Payouts create response transform
impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectPayoutCreateResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, StripeConnectPayoutCreateResponse>,
) -> Result<Self, Self::Error> {
let response: StripeConnectPayoutCreateResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::RequiresFulfillment),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
}),
..item.data
})
}
}
// Payouts fulfill request transform
impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectPayoutFulfillRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
Ok(Self {
amount: request.amount,
currency: request.destination_currency,
})
}
}
// Payouts fulfill response transform
impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectPayoutFulfillResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, StripeConnectPayoutFulfillResponse>,
) -> Result<Self, Self::Error> {
let response: StripeConnectPayoutFulfillResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::from(response.status)),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
}),
..item.data
})
}
}
// Payouts reversal request transform
impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectReversalRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.request.amount,
})
}
}
// Payouts reversal response transform
impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectReversalResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, StripeConnectReversalResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::Cancelled),
connector_payout_id: item.data.request.connector_payout_id.clone(),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
}),
..item.data
})
}
}
// Recipient creation request transform
impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectRecipientCreateRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
let customer_details = request.get_customer_details()?;
let customer_email = customer_details.get_customer_email()?;
let address = item.get_billing_address()?.clone();
let payout_vendor_details = request.get_vendor_details()?;
let (vendor_details, individual_details) = (
payout_vendor_details.vendor_details,
payout_vendor_details.individual_details,
);
Ok(Self {
account_type: vendor_details.account_type,
country: address.country,
email: Some(customer_email.clone()),
capabilities_card_payments: vendor_details.capabilities_card_payments,
capabilities_transfers: vendor_details.capabilities_transfers,
tos_acceptance_date: individual_details.tos_acceptance_date,
tos_acceptance_ip: individual_details.tos_acceptance_ip,
business_type: vendor_details.business_type,
business_profile_mcc: vendor_details.business_profile_mcc,
business_profile_url: vendor_details.business_profile_url,
business_profile_name: vendor_details.business_profile_name.clone(),
company_name: vendor_details.business_profile_name,
company_address_line1: vendor_details.company_address_line1,
company_address_line2: vendor_details.company_address_line2,
company_address_postal_code: vendor_details.company_address_postal_code,
company_address_city: vendor_details.company_address_city,
company_address_state: vendor_details.company_address_state,
company_phone: vendor_details.company_phone,
company_tax_id: vendor_details.company_tax_id,
company_owners_provided: vendor_details.company_owners_provided,
individual_first_name: address.first_name,
individual_last_name: address.last_name,
individual_dob_day: individual_details.individual_dob_day,
individual_dob_month: individual_details.individual_dob_month,
individual_dob_year: individual_details.individual_dob_year,
individual_address_line1: address.line1,
individual_address_line2: address.line2,
individual_address_postal_code: address.zip,
individual_address_city: address.city,
individual_address_state: address.state,
individual_email: Some(customer_email),
individual_phone: customer_details.phone,
individual_id_number: individual_details.individual_id_number,
individual_ssn_last_4: individual_details.individual_ssn_last_4,
})
}
}
// Recipient creation response transform
impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectRecipientCreateResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, StripeConnectRecipientCreateResponse>,
) -> Result<Self, Self::Error> {
let response: StripeConnectRecipientCreateResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::RequiresVendorAccountCreation),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: true,
error_code: None,
error_message: None,
}),
..item.data
})
}
}
// Recipient account's creation request
impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectRecipientAccountCreateRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
let payout_method_data = item.get_payout_method_data()?;
let customer_details = request.get_customer_details()?;
let customer_name = customer_details.get_customer_name()?;
let payout_vendor_details = request.get_vendor_details()?;
match payout_method_data {
api_models::payouts::PayoutMethodData::Card(_) => {
Ok(Self::Token(RecipientTokenRequest {
external_account: "tok_visa_debit".to_string(),
}))
}
api_models::payouts::PayoutMethodData::Bank(bank) => match bank {
api_models::payouts::Bank::Ach(bank_details) => {
Ok(Self::Bank(RecipientBankAccountRequest {
external_account_object: "bank_account".to_string(),
external_account_country: bank_details
.bank_country_code
.get_required_value("bank_country_code")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "bank_country_code",
})?,
external_account_currency: request.destination_currency.to_owned(),
external_account_account_holder_name: customer_name,
external_account_account_holder_type: payout_vendor_details
.individual_details
.get_external_account_account_holder_type()?,
external_account_account_number: bank_details.bank_account_number,
external_account_routing_number: bank_details.bank_routing_number,
}))
}
api_models::payouts::Bank::Bacs(_) => Err(errors::ConnectorError::NotSupported {
message: "BACS payouts are not supported".to_string(),
connector: "stripe",
}
.into()),
api_models::payouts::Bank::Sepa(_) => Err(errors::ConnectorError::NotSupported {
message: "SEPA payouts are not supported".to_string(),
connector: "stripe",
}
.into()),
api_models::payouts::Bank::Pix(_) => Err(errors::ConnectorError::NotSupported {
message: "PIX payouts are not supported".to_string(),
connector: "stripe",
}
.into()),
},
api_models::payouts::PayoutMethodData::Wallet(_) => {
Err(errors::ConnectorError::NotSupported {
message: "Payouts via wallets are not supported".to_string(),
connector: "stripe",
}
.into())
}
}
}
}
// Recipient account's creation response
impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectRecipientAccountCreateResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, StripeConnectRecipientAccountCreateResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::RequiresCreation),
connector_payout_id: item.data.request.connector_payout_id.clone(),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
}),
..item.data
})
}
}
impl From<StripeConnectPayoutStatus> for enums::PayoutStatus {
fn from(stripe_connect_status: StripeConnectPayoutStatus) -> Self {
match stripe_connect_status {
StripeConnectPayoutStatus::Paid => Self::Success,
StripeConnectPayoutStatus::Failed => Self::Failed,
StripeConnectPayoutStatus::Canceled => Self::Cancelled,
StripeConnectPayoutStatus::Pending | StripeConnectPayoutStatus::InTransit => {
Self::Pending
}
}
}
}
|
crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 3,956
| null | null | null | null | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.