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
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
// Struct: Authorize
// File: crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct Authorize
|
crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
|
hyperswitch_domain_models
|
struct_definition
|
Authorize
| 0
|
[] | 43
| null | null | null | null | null | null | null |
// Struct: PriorityLogicData
// File: crates/api_models/src/open_router.rs
// Module: api_models
// Implementations: 0
pub struct PriorityLogicData
|
crates/api_models/src/open_router.rs
|
api_models
|
struct_definition
|
PriorityLogicData
| 0
|
[] | 36
| null | null | null | null | null | null | null |
// File: crates/injector/src/vault_metadata.rs
// Module: injector
// Public functions: 2
// Public structs: 2
use std::collections::HashMap;
use base64::Engine;
use masking::{ExposeInterface, Secret};
use router_env::logger;
use url::Url;
use crate::{consts::EXTERNAL_VAULT_METADATA_HEADER, types::ConnectionConfig, VaultConnectors};
const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
/// Trait for different vault metadata processors
pub trait VaultMetadataProcessor: Send + Sync {
/// Process vault metadata and return connection configuration updates
fn process_metadata(
&self,
connection_config: &mut ConnectionConfig,
) -> Result<(), VaultMetadataError>;
/// Get the vault connector type
fn vault_connector(&self) -> VaultConnectors;
}
/// Comprehensive errors related to vault metadata processing
#[derive(Debug, thiserror::Error)]
pub enum VaultMetadataError {
#[error("Failed to decode base64 vault metadata: {0}")]
Base64DecodingFailed(String),
#[error("Failed to parse vault metadata JSON: {0}")]
JsonParsingFailed(String),
#[error("Unsupported vault connector: {0}")]
UnsupportedVaultConnector(String),
#[error("Invalid URL in vault metadata: {0}")]
InvalidUrl(String),
#[error("Missing required field in vault metadata: {0}")]
MissingRequiredField(String),
#[error("Invalid certificate format: {0}")]
InvalidCertificateFormat(String),
#[error("Vault metadata header is empty or malformed")]
EmptyOrMalformedHeader,
#[error("URL validation failed for {field}: {url} - {reason}")]
UrlValidationFailed {
field: String,
url: String,
reason: String,
},
#[error("Certificate validation failed: {0}")]
CertificateValidationFailed(String),
#[error("Vault metadata processing failed for connector {connector}: {reason}")]
ProcessingFailed { connector: String, reason: String },
}
impl VaultMetadataError {
/// Create a URL validation error with context
pub fn url_validation_failed(field: &str, url: &str, reason: impl Into<String>) -> Self {
Self::UrlValidationFailed {
field: field.to_string(),
url: url.to_string(),
reason: reason.into(),
}
}
}
/// External vault proxy metadata (moved from external_services)
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum ExternalVaultProxyMetadata {
/// VGS proxy data variant
VgsMetadata(VgsMetadata),
}
/// VGS proxy data (moved from external_services)
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct VgsMetadata {
/// External vault url
pub proxy_url: Url,
/// CA certificates to verify the vault server
pub certificate: Secret<String>,
}
impl VaultMetadataProcessor for VgsMetadata {
fn process_metadata(
&self,
connection_config: &mut ConnectionConfig,
) -> Result<(), VaultMetadataError> {
// Validate and set proxy URL from VGS metadata
let proxy_url_str = self.proxy_url.as_str().to_string();
connection_config.proxy_url = Some(Secret::new(proxy_url_str.clone()));
// Validate and decode certificate from VGS metadata
let cert_content = self.certificate.clone().expose();
// Check if certificate is base64 encoded and decode if necessary
let decoded_cert = if cert_content.starts_with("-----BEGIN") {
cert_content
} else {
match BASE64_ENGINE.decode(&cert_content) {
Ok(decoded_bytes) => String::from_utf8(decoded_bytes).map_err(|e| {
VaultMetadataError::CertificateValidationFailed(format!(
"Certificate is not valid UTF-8 after base64 decoding: {e}"
))
})?,
Err(e) => {
logger::error!(
error = %e,
"Failed to decode base64 certificate"
);
return Err(VaultMetadataError::CertificateValidationFailed(format!(
"Failed to decode base64 certificate: {e}"
)));
}
}
};
connection_config.ca_cert = Some(Secret::new(decoded_cert.clone()));
Ok(())
}
fn vault_connector(&self) -> VaultConnectors {
VaultConnectors::VGS
}
}
impl VaultMetadataProcessor for ExternalVaultProxyMetadata {
fn process_metadata(
&self,
connection_config: &mut ConnectionConfig,
) -> Result<(), VaultMetadataError> {
match self {
Self::VgsMetadata(vgs_metadata) => vgs_metadata.process_metadata(connection_config),
}
}
fn vault_connector(&self) -> VaultConnectors {
match self {
Self::VgsMetadata(vgs_metadata) => vgs_metadata.vault_connector(),
}
}
}
/// Factory for creating vault metadata processors from different sources
pub struct VaultMetadataFactory;
impl VaultMetadataFactory {
/// Create a vault metadata processor from base64 encoded header value with comprehensive validation
pub fn from_base64_header(
base64_value: &str,
) -> Result<Box<dyn VaultMetadataProcessor>, VaultMetadataError> {
// Validate input
if base64_value.trim().is_empty() {
return Err(VaultMetadataError::EmptyOrMalformedHeader);
}
// Decode base64 with detailed error context
let decoded_bytes = BASE64_ENGINE.decode(base64_value.trim()).map_err(|e| {
logger::error!(
error = %e,
"Failed to decode base64 vault metadata header"
);
VaultMetadataError::Base64DecodingFailed(format!("Invalid base64 encoding: {e}"))
})?;
// Validate decoded size
if decoded_bytes.is_empty() {
return Err(VaultMetadataError::EmptyOrMalformedHeader);
}
if decoded_bytes.len() > 1_000_000 {
return Err(VaultMetadataError::JsonParsingFailed(
"Decoded vault metadata is too large (>1MB)".to_string(),
));
}
// Parse JSON with detailed error context
let metadata: ExternalVaultProxyMetadata =
serde_json::from_slice(&decoded_bytes).map_err(|e| {
logger::error!(
error = %e,
"Failed to parse vault metadata JSON"
);
VaultMetadataError::JsonParsingFailed(format!("Invalid JSON structure: {e}"))
})?;
logger::info!(
vault_connector = ?metadata.vault_connector(),
"Successfully parsed vault metadata from header"
);
Ok(Box::new(metadata))
}
}
/// Trait for extracting vault metadata from various sources
pub trait VaultMetadataExtractor {
/// Extract vault metadata from headers and apply to connection config
fn extract_and_apply_vault_metadata(
&mut self,
headers: &HashMap<String, Secret<String>>,
) -> Result<(), VaultMetadataError>;
}
impl VaultMetadataExtractor for ConnectionConfig {
fn extract_and_apply_vault_metadata(
&mut self,
headers: &HashMap<String, Secret<String>>,
) -> Result<(), VaultMetadataError> {
if let Some(vault_metadata_header) = headers.get(EXTERNAL_VAULT_METADATA_HEADER) {
let processor =
VaultMetadataFactory::from_base64_header(&vault_metadata_header.clone().expose())
.map_err(|e| {
logger::error!(
error = %e,
"Failed to create vault metadata processor from header"
);
e
})?;
processor.process_metadata(self).map_err(|e| {
logger::error!(
error = %e,
vault_connector = ?processor.vault_connector(),
"Failed to apply vault metadata to connection config"
);
e
})?;
logger::info!(
vault_connector = ?processor.vault_connector(),
proxy_url_applied = self.proxy_url.is_some(),
ca_cert_applied = self.ca_cert.is_some(),
client_cert_applied = self.client_cert.is_some(),
"Successfully applied vault metadata to connection configuration"
);
}
Ok(())
}
}
/// Extended trait for graceful fallback handling
pub trait VaultMetadataExtractorExt {
/// Extract vault metadata with graceful fallback (doesn't fail the entire request)
fn extract_and_apply_vault_metadata_with_fallback(
&mut self,
headers: &HashMap<String, Secret<String>>,
) -> bool;
/// Extract vault metadata from a single header value with graceful fallback
fn extract_and_apply_vault_metadata_with_fallback_from_header(
&mut self,
header_value: &str,
) -> bool;
}
impl VaultMetadataExtractorExt for ConnectionConfig {
fn extract_and_apply_vault_metadata_with_fallback(
&mut self,
headers: &HashMap<String, Secret<String>>,
) -> bool {
match self.extract_and_apply_vault_metadata(headers) {
Ok(()) => {
logger::info!(
proxy_url_set = self.proxy_url.is_some(),
ca_cert_set = self.ca_cert.is_some(),
client_cert_set = self.client_cert.is_some(),
"Vault metadata processing completed successfully"
);
true
}
Err(error) => {
logger::warn!(
error = %error,
proxy_url_set = self.proxy_url.is_some(),
ca_cert_set = self.ca_cert.is_some(),
"Vault metadata processing failed, continuing without vault configuration"
);
false
}
}
}
fn extract_and_apply_vault_metadata_with_fallback_from_header(
&mut self,
header_value: &str,
) -> bool {
let mut temp_headers = HashMap::new();
temp_headers.insert(
EXTERNAL_VAULT_METADATA_HEADER.to_string(),
Secret::new(header_value.to_string()),
);
self.extract_and_apply_vault_metadata_with_fallback(&temp_headers)
}
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use std::collections::HashMap;
use base64::Engine;
use common_utils::pii::SecretSerdeValue;
use super::*;
use crate::types::{HttpMethod, InjectorRequest, TokenData, VaultConnectors};
#[test]
fn test_vault_metadata_processing() {
// Create test VGS metadata with base64 encoded certificate
let vgs_metadata = VgsMetadata {
proxy_url: "https://vgs-proxy.example.com:8443"
.parse()
.expect("Valid test URL"),
certificate: Secret::new("cert".to_string()),
};
let metadata = ExternalVaultProxyMetadata::VgsMetadata(vgs_metadata);
// Serialize and base64 encode (as it would come from the header)
let metadata_json =
serde_json::to_vec(&metadata).expect("Metadata serialization should succeed");
let base64_metadata = BASE64_ENGINE.encode(&metadata_json);
// Create headers with vault metadata
let mut headers = HashMap::new();
headers.insert(
"Content-Type".to_string(),
Secret::new("application/json".to_string()),
);
headers.insert(
"Authorization".to_string(),
Secret::new("Bearer token123".to_string()),
);
headers.insert(
EXTERNAL_VAULT_METADATA_HEADER.to_string(),
Secret::new(base64_metadata),
);
// Test the amazing automatic processing with the unified API!
let injector_request = InjectorRequest::new(
"https://api.example.com/v1/payments".to_string(),
HttpMethod::POST,
"amount={{$amount}}¤cy={{$currency}}".to_string(),
TokenData {
vault_connector: VaultConnectors::VGS,
specific_token_data: SecretSerdeValue::new(serde_json::json!({
"amount": "1000",
"currency": "USD"
})),
},
Some(headers),
None, // No fallback proxy needed - vault metadata provides it
None, // No fallback client cert
None, // No fallback client key
None, // No fallback CA cert
);
// Verify vault metadata was automatically applied!
assert!(injector_request.connection_config.proxy_url.is_some());
assert!(injector_request.connection_config.ca_cert.is_some());
assert_eq!(
injector_request
.connection_config
.proxy_url
.as_ref()
.expect("Proxy URL should be set")
.clone()
.expose(),
"https://vgs-proxy.example.com:8443/"
);
// Verify vault metadata header was removed from regular headers
assert!(!injector_request
.connection_config
.headers
.contains_key(EXTERNAL_VAULT_METADATA_HEADER));
// Verify other headers are preserved
assert!(injector_request
.connection_config
.headers
.contains_key("Content-Type"));
assert!(injector_request
.connection_config
.headers
.contains_key("Authorization"));
}
#[test]
fn test_vault_metadata_factory() {
let vgs_metadata = VgsMetadata {
proxy_url: "https://vgs-proxy.example.com:8443"
.parse()
.expect("Valid test URL"),
certificate: Secret::new("cert".to_string()),
};
let metadata = ExternalVaultProxyMetadata::VgsMetadata(vgs_metadata);
let metadata_json =
serde_json::to_vec(&metadata).expect("Metadata serialization should succeed");
let base64_metadata = BASE64_ENGINE.encode(&metadata_json);
// Test factory creation from base64
let processor = VaultMetadataFactory::from_base64_header(&base64_metadata)
.expect("Base64 decoding should succeed");
assert_eq!(processor.vault_connector(), VaultConnectors::VGS);
// Test processor creation was successful
assert!(processor.vault_connector() == VaultConnectors::VGS);
}
}
|
crates/injector/src/vault_metadata.rs
|
injector
|
full_file
| null | null | null | 2,974
| null | null | null | null | null | null | null |
// Implementation: impl api::MandateSetup for for Moneris
// File: crates/hyperswitch_connectors/src/connectors/moneris.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::MandateSetup for for Moneris
|
crates/hyperswitch_connectors/src/connectors/moneris.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 65
| null |
Moneris
|
api::MandateSetup for
| 0
| 0
| null | null |
// Implementation: impl ProcessTrackerInterface for for KafkaStore
// File: crates/router/src/db/kafka_store.rs
// Module: router
// Methods: 9 total (0 public)
impl ProcessTrackerInterface for for KafkaStore
|
crates/router/src/db/kafka_store.rs
|
router
|
impl_block
| null | null | null | 47
| null |
KafkaStore
|
ProcessTrackerInterface for
| 9
| 0
| null | null |
// Implementation: impl api::PaymentVoid for for Nuvei
// File: crates/hyperswitch_connectors/src/connectors/nuvei.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Nuvei
|
crates/hyperswitch_connectors/src/connectors/nuvei.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Nuvei
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Struct: Taxjar
// File: crates/hyperswitch_connectors/src/connectors/taxjar.rs
// Module: hyperswitch_connectors
// Implementations: 18
// 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::TaxCalculation, ConnectorCommon, ConnectorValidation, webhooks::IncomingWebhook, ConnectorSpecifications
pub struct Taxjar
|
crates/hyperswitch_connectors/src/connectors/taxjar.rs
|
hyperswitch_connectors
|
struct_definition
|
Taxjar
| 18
|
[
"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::TaxCalculation",
"ConnectorCommon",
"ConnectorValidation",
"webhooks::IncomingWebhook",
"ConnectorSpecifications"
] | 132
| null | null | null | null | null | null | null |
// Struct: ChargebeeSubscriptionDetails
// File: crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ChargebeeSubscriptionDetails
|
crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ChargebeeSubscriptionDetails
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Struct: PaymentsRequest
// File: crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 1
// Traits: SignatureCalculationData
pub struct PaymentsRequest
|
crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaymentsRequest
| 1
|
[
"SignatureCalculationData"
] | 53
| null | null | null | null | null | null | null |
// Struct: PaystackPaymentsRequest
// File: crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaystackPaymentsRequest
|
crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaystackPaymentsRequest
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Function: revoke_mandate
// File: crates/router/src/core/mandate.rs
// Module: router
pub fn revoke_mandate(
state: SessionState,
merchant_context: domain::MerchantContext,
req: mandates::MandateId,
) -> RouterResponse<mandates::MandateRevokedResponse>
|
crates/router/src/core/mandate.rs
|
router
|
function_signature
| null | null | null | 72
|
revoke_mandate
| null | null | null | null | null | null |
// Implementation: impl webhooks::IncomingWebhook for for Worldline
// File: crates/hyperswitch_connectors/src/connectors/worldline.rs
// Module: hyperswitch_connectors
// Methods: 7 total (0 public)
impl webhooks::IncomingWebhook for for Worldline
|
crates/hyperswitch_connectors/src/connectors/worldline.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Worldline
|
webhooks::IncomingWebhook for
| 7
| 0
| null | null |
// Struct: Card
// File: crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Card
|
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
Card
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Function: new
// File: crates/diesel_models/src/organization.rs
// Module: diesel_models
pub fn new(
id: id_type::OrganizationId,
organization_type: common_enums::OrganizationType,
organization_name: Option<String>,
) -> Self
|
crates/diesel_models/src/organization.rs
|
diesel_models
|
function_signature
| null | null | null | 58
|
new
| null | null | null | null | null | null |
// File: crates/external_services/src/grpc_client/dynamic_routing/elimination_based_client.rs
// Module: external_services
use api_models::routing::{
EliminationAnalyserConfig as EliminationConfig, RoutableConnectorChoice,
RoutableConnectorChoiceWithBucketName,
};
use common_utils::{ext_traits::OptionExt, transformers::ForeignTryFrom};
pub use elimination_rate::{
elimination_analyser_client::EliminationAnalyserClient, EliminationBucketConfig,
EliminationRequest, EliminationResponse, InvalidateBucketRequest, InvalidateBucketResponse,
LabelWithBucketName, UpdateEliminationBucketRequest, UpdateEliminationBucketResponse,
};
use error_stack::ResultExt;
use router_env::{instrument, logger, tracing};
#[allow(
missing_docs,
unused_qualifications,
clippy::unwrap_used,
clippy::as_conversions,
clippy::use_self
)]
pub mod elimination_rate {
tonic::include_proto!("elimination");
}
use super::{Client, DynamicRoutingError, DynamicRoutingResult};
use crate::grpc_client::{self, GrpcHeaders};
/// The trait Elimination Based Routing would have the functions required to support performance, calculation and invalidation bucket
#[async_trait::async_trait]
pub trait EliminationBasedRouting: dyn_clone::DynClone + Send + Sync {
/// To perform the elimination based routing for the list of connectors
async fn perform_elimination_routing(
&self,
id: String,
params: String,
labels: Vec<RoutableConnectorChoice>,
configs: Option<EliminationConfig>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<EliminationResponse>;
/// To update the bucket size and ttl for list of connectors with its respective bucket name
async fn update_elimination_bucket_config(
&self,
id: String,
params: String,
report: Vec<RoutableConnectorChoiceWithBucketName>,
config: Option<EliminationConfig>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateEliminationBucketResponse>;
/// To invalidate the previous id's bucket
async fn invalidate_elimination_bucket(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateBucketResponse>;
}
#[async_trait::async_trait]
impl EliminationBasedRouting for EliminationAnalyserClient<Client> {
#[instrument(skip_all)]
async fn perform_elimination_routing(
&self,
id: String,
params: String,
label_input: Vec<RoutableConnectorChoice>,
configs: Option<EliminationConfig>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<EliminationResponse> {
let labels = label_input
.into_iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>();
let config = configs.map(ForeignTryFrom::foreign_try_from).transpose()?;
let request = grpc_client::create_grpc_request(
EliminationRequest {
id,
params,
labels,
config,
},
headers,
);
let response = self
.clone()
.get_elimination_status(request)
.await
.change_context(DynamicRoutingError::EliminationRateRoutingFailure(
"Failed to perform the elimination analysis".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
#[instrument(skip_all)]
async fn update_elimination_bucket_config(
&self,
id: String,
params: String,
report: Vec<RoutableConnectorChoiceWithBucketName>,
configs: Option<EliminationConfig>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateEliminationBucketResponse> {
let config = configs.map(ForeignTryFrom::foreign_try_from).transpose()?;
let labels_with_bucket_name = report
.into_iter()
.map(|conn_choice_with_bucket| LabelWithBucketName {
label: conn_choice_with_bucket
.routable_connector_choice
.to_string(),
bucket_name: conn_choice_with_bucket.bucket_name,
})
.collect::<Vec<_>>();
let request = grpc_client::create_grpc_request(
UpdateEliminationBucketRequest {
id,
params,
labels_with_bucket_name,
config,
},
headers,
);
let response = self
.clone()
.update_elimination_bucket(request)
.await
.change_context(DynamicRoutingError::EliminationRateRoutingFailure(
"Failed to update the elimination bucket".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
#[instrument(skip_all)]
async fn invalidate_elimination_bucket(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateBucketResponse> {
let request = grpc_client::create_grpc_request(InvalidateBucketRequest { id }, headers);
let response = self
.clone()
.invalidate_bucket(request)
.await
.change_context(DynamicRoutingError::EliminationRateRoutingFailure(
"Failed to invalidate the elimination bucket".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
}
impl ForeignTryFrom<EliminationConfig> for EliminationBucketConfig {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(config: EliminationConfig) -> Result<Self, Self::Error> {
Ok(Self {
bucket_size: config
.bucket_size
.get_required_value("bucket_size")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "bucket_size".to_string(),
})?,
bucket_leak_interval_in_secs: config
.bucket_leak_interval_in_secs
.get_required_value("bucket_leak_interval_in_secs")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "bucket_leak_interval_in_secs".to_string(),
})?,
})
}
}
|
crates/external_services/src/grpc_client/dynamic_routing/elimination_based_client.rs
|
external_services
|
full_file
| null | null | null | 1,299
| null | null | null | null | null | null | null |
// Struct: Amount
// File: crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Amount
|
crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
Amount
| 0
|
[] | 44
| null | null | null | null | null | null | null |
// Implementation: impl PaymentIntentNew
// File: crates/diesel_models/src/query/payment_intent.rs
// Module: diesel_models
// Methods: 1 total (0 public)
impl PaymentIntentNew
|
crates/diesel_models/src/query/payment_intent.rs
|
diesel_models
|
impl_block
| null | null | null | 41
| null |
PaymentIntentNew
| null | 1
| 0
| null | null |
// Struct: PaymentAccountFeatureInformation
// File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaymentAccountFeatureInformation
|
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaymentAccountFeatureInformation
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Function: find_by_lookup_id
// File: crates/diesel_models/src/query/reverse_lookup.rs
// Module: diesel_models
pub fn find_by_lookup_id(lookup_id: &str, conn: &PgPooledConn) -> StorageResult<Self>
|
crates/diesel_models/src/query/reverse_lookup.rs
|
diesel_models
|
function_signature
| null | null | null | 54
|
find_by_lookup_id
| null | null | null | null | null | null |
// Function: server
// File: crates/router/src/routes/app.rs
// Module: router
pub fn server(config: AppState) -> Scope
|
crates/router/src/routes/app.rs
|
router
|
function_signature
| null | null | null | 29
|
server
| null | null | null | null | null | null |
// File: crates/router/src/types/api/ephemeral_key.rs
// Module: router
pub use api_models::ephemeral_key::*;
|
crates/router/src/types/api/ephemeral_key.rs
|
router
|
full_file
| null | null | null | 30
| null | null | null | null | null | null | null |
// File: crates/router/src/types/api/bank_accounts.rs
// Module: router
|
crates/router/src/types/api/bank_accounts.rs
|
router
|
full_file
| null | null | null | 18
| null | null | null | null | null | null | null |
// File: crates/router/src/routes/payment_methods.rs
// Module: router
// Public functions: 39
// Public structs: 2
use ::payment_methods::{
controller::PaymentMethodsController,
core::{migration, migration::payment_methods::migrate_payment_method},
};
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpRequest, HttpResponse};
use common_utils::{errors::CustomResult, id_type, transformers::ForeignFrom};
use diesel_models::enums::IntentStatus;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
bulk_tokenization::CardNetworkTokenizeRequest, merchant_key_store::MerchantKeyStore,
payment_methods::PaymentMethodCustomerMigrate, transformers::ForeignTryFrom,
};
use router_env::{instrument, logger, tracing, Flow};
use super::app::{AppState, SessionState};
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
use crate::core::{customers, payment_methods::tokenize};
use crate::{
core::{
api_locking,
errors::{self, utils::StorageErrorExt},
payment_methods::{self as payment_methods_routes, cards, migration as update_migration},
},
services::{self, api, authentication as auth, authorization::permissions::Permission},
types::{
api::payment_methods::{self, PaymentMethodId},
domain,
storage::payment_method::PaymentTokenData,
},
};
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
pub async fn create_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCreate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| async move {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
Box::pin(cards::get_client_secret_or_add_payment_method(
&state,
req,
&merchant_context,
))
.await
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
pub async fn create_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCreate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, req_state| async move {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
Box::pin(payment_methods_routes::create_payment_method(
&state,
&req_state,
req,
&merchant_context,
&auth.profile,
))
.await
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
pub async fn create_payment_method_intent_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodIntentCreate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| async move {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
Box::pin(payment_methods_routes::payment_method_intent_create(
&state,
req,
&merchant_context,
))
.await
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
/// This struct is used internally only
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct PaymentMethodIntentConfirmInternal {
pub id: id_type::GlobalPaymentMethodId,
pub request: payment_methods::PaymentMethodIntentConfirm,
}
#[cfg(feature = "v2")]
impl From<PaymentMethodIntentConfirmInternal> for payment_methods::PaymentMethodIntentConfirm {
fn from(item: PaymentMethodIntentConfirmInternal) -> Self {
item.request
}
}
#[cfg(feature = "v2")]
impl common_utils::events::ApiEventMetric for PaymentMethodIntentConfirmInternal {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::PaymentMethod {
payment_method_id: self.id.clone(),
payment_method_type: Some(self.request.payment_method_type),
payment_method_subtype: Some(self.request.payment_method_subtype),
})
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))]
pub async fn payment_method_update_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodId>,
json_payload: web::Json<payment_methods::PaymentMethodUpdate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsUpdate;
let payment_method_id = path.into_inner();
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::update_payment_method(
state,
merchant_context,
auth.profile,
req,
&payment_method_id,
)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsRetrieve))]
pub async fn payment_method_retrieve_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsRetrieve;
let payload = web::Json(PaymentMethodId {
payment_method_id: path.into_inner(),
})
.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, pm, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::retrieve_payment_method(state, pm, merchant_context)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsDelete))]
pub async fn payment_method_delete_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsDelete;
let payload = web::Json(PaymentMethodId {
payment_method_id: path.into_inner(),
})
.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, pm, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::delete_payment_method(state, pm, merchant_context, auth.profile)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))]
pub async fn migrate_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodMigrate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsMigrate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| async move {
let merchant_id = req.merchant_id.clone();
let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(merchant_account, key_store),
));
Box::pin(migrate_payment_method(
&(&state).into(),
req,
&merchant_id,
&merchant_context,
&cards::PmCards {
state: &state,
merchant_context: &merchant_context,
},
))
.await
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
async fn get_merchant_account(
state: &SessionState,
merchant_id: &id_type::MerchantId,
) -> CustomResult<(MerchantKeyStore, domain::MerchantAccount), errors::ApiErrorResponse> {
let key_manager_state = &state.into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
Ok((key_store, merchant_account))
}
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))]
pub async fn migrate_payment_methods(
state: web::Data<AppState>,
req: HttpRequest,
MultipartForm(form): MultipartForm<migration::PaymentMethodsMigrateForm>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsMigrate;
let (merchant_id, records, merchant_connector_ids) =
match form.validate_and_get_payment_method_records() {
Ok((merchant_id, records, merchant_connector_ids)) => {
(merchant_id, records, merchant_connector_ids)
}
Err(e) => return api::log_and_return_error_response(e.into()),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
records,
|state, _, req, _| {
let merchant_id = merchant_id.clone();
let merchant_connector_ids = merchant_connector_ids.clone();
async move {
let (key_store, merchant_account) =
get_merchant_account(&state, &merchant_id).await?;
// Create customers if they are not already present
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(merchant_account.clone(), key_store.clone()),
));
let mut mca_cache = std::collections::HashMap::new();
let customers = Vec::<PaymentMethodCustomerMigrate>::foreign_try_from((
&req,
merchant_id.clone(),
))
.map_err(|e| errors::ApiErrorResponse::InvalidRequestData {
message: e.to_string(),
})?;
for record in &customers {
if let Some(connector_customer_details) = &record.connector_customer_details {
for connector_customer in connector_customer_details {
if !mca_cache.contains_key(&connector_customer.merchant_connector_id) {
let mca = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&(&state).into(),
&merchant_id,
&connector_customer.merchant_connector_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_customer.merchant_connector_id.get_string_repr().to_string(),
},
)?;
mca_cache
.insert(connector_customer.merchant_connector_id.clone(), mca);
}
}
}
}
customers::migrate_customers(state.clone(), customers, merchant_context.clone())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let controller = cards::PmCards {
state: &state,
merchant_context: &merchant_context,
};
Box::pin(migration::migrate_payment_methods(
&(&state).into(),
req,
&merchant_id,
&merchant_context,
merchant_connector_ids,
&controller,
))
.await
}
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsBatchUpdate))]
pub async fn update_payment_methods(
state: web::Data<AppState>,
req: HttpRequest,
MultipartForm(form): MultipartForm<update_migration::PaymentMethodsUpdateForm>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsBatchUpdate;
let (merchant_id, records) = match form.validate_and_get_payment_method_records() {
Ok((merchant_id, records)) => (merchant_id, records),
Err(e) => return api::log_and_return_error_response(e.into()),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
records,
|state, _, req, _| {
let merchant_id = merchant_id.clone();
async move {
let (key_store, merchant_account) =
get_merchant_account(&state, &merchant_id).await?;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(merchant_account.clone(), key_store.clone()),
));
Box::pin(update_migration::update_payment_methods(
&state,
req,
&merchant_id,
&merchant_context,
))
.await
}
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSave))]
pub async fn save_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCreate>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSave;
let payload = json_payload.into_inner();
let pm_id = path.into_inner();
let api_auth = auth::ApiKeyAuth::default();
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth)
{
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
Box::pin(cards::add_payment_method_data(
state,
req,
merchant_context,
pm_id.clone(),
))
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))]
pub async fn list_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Query<payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsList;
let payload = json_payload.into_inner();
let api_auth = auth::ApiKeyAuth::default();
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth)
{
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
// TODO (#7195): Fill platform_merchant_account in the client secret auth and pass it here.
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
cards::list_payment_methods(state, merchant_context, req)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// List payment methods for a Customer
///
/// To filter and list the applicable payment methods for a particular Customer ID
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_api(
state: web::Data<AppState>,
customer_id: web::Path<(id_type::CustomerId,)>,
req: HttpRequest,
query_payload: web::Query<payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
let flow = Flow::CustomerPaymentMethodsList;
let payload = query_payload.into_inner();
let customer_id = customer_id.into_inner().0;
let api_auth = auth::ApiKeyAuth::default();
let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
cards::do_list_customer_pm_fetch_customer_if_not_passed(
state,
merchant_context,
Some(req),
Some(&customer_id),
None,
)
},
&*ephemeral_auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// List payment methods for a Customer
///
/// To filter and list the applicable payment methods for a particular Customer ID
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_api_client(
state: web::Data<AppState>,
req: HttpRequest,
query_payload: web::Query<payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
let flow = Flow::CustomerPaymentMethodsList;
let payload = query_payload.into_inner();
let api_key = auth::get_api_key(req.headers()).ok();
let api_auth = auth::ApiKeyAuth::default();
let (auth, _, is_ephemeral_auth) =
match auth::get_ephemeral_or_other_auth(req.headers(), false, Some(&payload), api_auth)
.await
{
Ok((auth, _auth_flow, is_ephemeral_auth)) => (auth, _auth_flow, is_ephemeral_auth),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
cards::do_list_customer_pm_fetch_customer_if_not_passed(
state,
merchant_context,
Some(req),
None,
is_ephemeral_auth.then_some(api_key).flatten(),
)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
/// Generate a form link for collecting payment methods for a customer
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodCollectLink))]
pub async fn initiate_pm_collect_link_flow(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCollectLinkRequest>,
) -> HttpResponse {
let flow = Flow::PaymentMethodCollectLink;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::initiate_pm_collect_link(state, merchant_context, req)
},
&auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_api(
state: web::Data<AppState>,
customer_id: web::Path<id_type::GlobalCustomerId>,
req: HttpRequest,
query_payload: web::Query<api_models::payment_methods::ListMethodsForPaymentMethodsRequest>,
) -> HttpResponse {
let flow = Flow::CustomerPaymentMethodsList;
let payload = query_payload.into_inner();
let customer_id = customer_id.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, _, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::list_saved_payment_methods_for_customer(
state,
merchant_context,
customer_id.clone(),
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::GetPaymentMethodTokenData))]
pub async fn get_payment_method_token_data(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodId>,
json_payload: web::Json<api_models::payment_methods::GetTokenDataRequest>,
) -> HttpResponse {
let flow = Flow::GetPaymentMethodTokenData;
let payment_method_id = path.into_inner();
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payment_methods_routes::get_token_data_for_payment_method(
state,
auth.merchant_account,
auth.key_store,
auth.profile,
req,
payment_method_id.clone(),
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::TotalPaymentMethodCount))]
pub async fn get_total_payment_method_count(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::TotalPaymentMethodCount;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::get_total_saved_payment_methods_for_merchant(
state,
merchant_context,
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Generate a form link for collecting payment methods for a customer
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodCollectLink))]
pub async fn render_pm_collect_link(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(id_type::MerchantId, String)>,
) -> HttpResponse {
let flow = Flow::PaymentMethodCollectLink;
let (merchant_id, pm_collect_link_id) = path.into_inner();
let payload = payment_methods::PaymentMethodCollectLinkRenderRequest {
merchant_id: merchant_id.clone(),
pm_collect_link_id,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::render_pm_collect_link(state, merchant_context, req)
},
&auth::MerchantIdAuth(merchant_id),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsRetrieve))]
pub async fn payment_method_retrieve_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsRetrieve;
let payload = web::Json(PaymentMethodId {
payment_method_id: path.into_inner(),
})
.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, pm, _| async move {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
cards::PmCards {
state: &state,
merchant_context: &merchant_context,
}
.retrieve_payment_method(pm)
.await
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))]
pub async fn payment_method_update_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
json_payload: web::Json<payment_methods::PaymentMethodUpdate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsUpdate;
let payment_method_id = path.into_inner();
let payload = json_payload.into_inner();
let api_auth = auth::ApiKeyAuth::default();
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth)
{
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
cards::update_customer_payment_method(state, merchant_context, req, &payment_method_id)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsDelete))]
pub async fn payment_method_delete_api(
state: web::Data<AppState>,
req: HttpRequest,
payment_method_id: web::Path<(String,)>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsDelete;
let pm = PaymentMethodId {
payment_method_id: payment_method_id.into_inner().0,
};
let api_auth = auth::ApiKeyAuth::default();
let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
pm,
|state, auth: auth::AuthenticationData, req, _| async move {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
cards::PmCards {
state: &state,
merchant_context: &merchant_context,
}
.delete_payment_method(req)
.await
},
&*ephemeral_auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::ListCountriesCurrencies))]
pub async fn list_countries_currencies_for_connector_payment_method(
state: web::Data<AppState>,
req: HttpRequest,
query_payload: web::Query<payment_methods::ListCountriesCurrenciesRequest>,
) -> HttpResponse {
let flow = Flow::ListCountriesCurrencies;
let payload = query_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
cards::list_countries_currencies_for_connector_payment_method(
state,
req,
auth.profile_id,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileConnectorWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::ProfileConnectorWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::ListCountriesCurrencies))]
pub async fn list_countries_currencies_for_connector_payment_method(
state: web::Data<AppState>,
req: HttpRequest,
query_payload: web::Query<payment_methods::ListCountriesCurrenciesRequest>,
) -> HttpResponse {
let flow = Flow::ListCountriesCurrencies;
let payload = query_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
cards::list_countries_currencies_for_connector_payment_method(
state,
req,
Some(auth.profile.get_id().clone()),
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileConnectorRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::ProfileConnectorRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::DefaultPaymentMethodsSet))]
pub async fn default_payment_method_set_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<payment_methods::DefaultPaymentMethod>,
) -> HttpResponse {
let flow = Flow::DefaultPaymentMethodsSet;
let payload = path.into_inner();
let pc = payload.clone();
let customer_id = &pc.customer_id;
let api_auth = auth::ApiKeyAuth::default();
let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, default_payment_method, _| async move {
let merchant_id = auth.merchant_account.get_id();
cards::PmCards {
state: &state,
merchant_context: &domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account.clone(), auth.key_store),
)),
}
.set_default_payment_method(
merchant_id,
customer_id,
default_payment_method.payment_method_id,
)
.await
},
&*ephemeral_auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use api_models::payment_methods::PaymentMethodListRequest;
use super::*;
// #[test]
// fn test_custom_list_deserialization() {
// let dummy_data = "amount=120&recurring_enabled=true&installment_payment_enabled=true";
// let de_query: web::Query<PaymentMethodListRequest> =
// web::Query::from_query(dummy_data).unwrap();
// let de_struct = de_query.into_inner();
// assert_eq!(de_struct.installment_payment_enabled, Some(true))
// }
#[test]
fn test_custom_list_deserialization_multi_amount() {
let dummy_data = "amount=120&recurring_enabled=true&amount=1000";
let de_query: Result<web::Query<PaymentMethodListRequest>, _> =
web::Query::from_query(dummy_data);
assert!(de_query.is_err())
}
}
#[derive(Clone)]
pub struct ParentPaymentMethodToken {
key_for_token: String,
}
impl ParentPaymentMethodToken {
pub fn create_key_for_token(
(parent_pm_token, payment_method): (&String, api_models::enums::PaymentMethod),
) -> Self {
Self {
key_for_token: format!("pm_token_{parent_pm_token}_{payment_method}_hyperswitch"),
}
}
#[cfg(feature = "v2")]
pub fn return_key_for_token(
(parent_pm_token, payment_method): (&String, api_models::enums::PaymentMethod),
) -> String {
format!("pm_token_{parent_pm_token}_{payment_method}_hyperswitch")
}
pub async fn insert(
&self,
fulfillment_time: i64,
token: PaymentTokenData,
state: &SessionState,
) -> CustomResult<(), errors::ApiErrorResponse> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
redis_conn
.serialize_and_set_key_with_expiry(
&self.key_for_token.as_str().into(),
token,
fulfillment_time,
)
.await
.change_context(errors::StorageError::KVError)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add token in redis")?;
Ok(())
}
pub fn should_delete_payment_method_token(&self, status: IntentStatus) -> bool {
|
crates/router/src/routes/payment_methods.rs#chunk0
|
router
|
chunk
| null | null | null | 8,177
| null | null | null | null | null | null | null |
// Struct: Score
// File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Score
|
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
Score
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Implementation: impl ObjectReferenceId
// File: crates/api_models/src/webhooks.rs
// Module: api_models
// Methods: 1 total (1 public)
impl ObjectReferenceId
|
crates/api_models/src/webhooks.rs
|
api_models
|
impl_block
| null | null | null | 39
| null |
ObjectReferenceId
| null | 1
| 1
| null | null |
// Function: create_new_authentication
// File: crates/router/src/core/authentication/utils.rs
// Module: router
pub fn create_new_authentication(
state: &SessionState,
merchant_id: common_utils::id_type::MerchantId,
authentication_connector: String,
token: String,
profile_id: common_utils::id_type::ProfileId,
payment_id: common_utils::id_type::PaymentId,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
organization_id: common_utils::id_type::OrganizationId,
force_3ds_challenge: Option<bool>,
psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
) -> RouterResult<storage::Authentication>
|
crates/router/src/core/authentication/utils.rs
|
router
|
function_signature
| null | null | null | 155
|
create_new_authentication
| null | null | null | null | null | null |
// Struct: PeachpaymentsPaymentsResponse
// File: crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PeachpaymentsPaymentsResponse
|
crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PeachpaymentsPaymentsResponse
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Implementation: impl api::RefundExecute for for Shift4
// File: crates/hyperswitch_connectors/src/connectors/shift4.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Shift4
|
crates/hyperswitch_connectors/src/connectors/shift4.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Shift4
|
api::RefundExecute for
| 0
| 0
| null | null |
// Implementation: impl super::sdk_events::events::SdkEventsFilterAnalytics for for ClickhouseClient
// File: crates/analytics/src/clickhouse.rs
// Module: analytics
// Methods: 0 total (0 public)
impl super::sdk_events::events::SdkEventsFilterAnalytics for for ClickhouseClient
|
crates/analytics/src/clickhouse.rs
|
analytics
|
impl_block
| null | null | null | 65
| null |
ClickhouseClient
|
super::sdk_events::events::SdkEventsFilterAnalytics for
| 0
| 0
| null | null |
// Implementation: impl api::RefundExecute for for Worldpay
// File: crates/hyperswitch_connectors/src/connectors/worldpay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Worldpay
|
crates/hyperswitch_connectors/src/connectors/worldpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Worldpay
|
api::RefundExecute for
| 0
| 0
| null | null |
// Function: add_access_token_for_payout
// File: crates/router/src/core/payouts/access_token.rs
// Module: router
pub fn add_access_token_for_payout<F: Clone + 'static>(
state: &SessionState,
connector: &api_types::ConnectorData,
merchant_context: &domain::MerchantContext,
router_data: &types::PayoutsRouterData<F>,
payout_type: Option<enums::PayoutType>,
) -> RouterResult<types::AddAccessTokenResult>
|
crates/router/src/core/payouts/access_token.rs
|
router
|
function_signature
| null | null | null | 108
|
add_access_token_for_payout
| null | null | null | null | null | null |
// Struct: PaymentGetIntent
// File: crates/router/src/core/payments/operations/payment_get_intent.rs
// Module: router
// Implementations: 0
pub struct PaymentGetIntent
|
crates/router/src/core/payments/operations/payment_get_intent.rs
|
router
|
struct_definition
|
PaymentGetIntent
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Implementation: impl TransactionStatus
// File: crates/common_enums/src/enums.rs
// Module: common_enums
// Methods: 2 total (2 public)
impl TransactionStatus
|
crates/common_enums/src/enums.rs
|
common_enums
|
impl_block
| null | null | null | 39
| null |
TransactionStatus
| null | 2
| 2
| null | null |
// File: crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs
// Module: external_services
use api_models::routing::{
CurrentBlockThreshold, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,
SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody, SuccessRateSpecificityLevel,
};
use common_utils::{ext_traits::OptionExt, transformers::ForeignTryFrom};
use error_stack::ResultExt;
use router_env::{instrument, logger, tracing};
pub use success_rate::{
success_rate_calculator_client::SuccessRateCalculatorClient, CalGlobalSuccessRateConfig,
CalGlobalSuccessRateRequest, CalGlobalSuccessRateResponse, CalSuccessRateConfig,
CalSuccessRateRequest, CalSuccessRateResponse,
CurrentBlockThreshold as DynamicCurrentThreshold, InvalidateWindowsRequest,
InvalidateWindowsResponse, LabelWithStatus,
SuccessRateSpecificityLevel as ProtoSpecificityLevel, UpdateSuccessRateWindowConfig,
UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse,
};
#[allow(
missing_docs,
unused_qualifications,
clippy::unwrap_used,
clippy::as_conversions,
clippy::use_self
)]
pub mod success_rate {
tonic::include_proto!("success_rate");
}
use super::{Client, DynamicRoutingError, DynamicRoutingResult};
use crate::grpc_client::{self, GrpcHeaders};
/// The trait Success Based Dynamic Routing would have the functions required to support the calculation and updation window
#[async_trait::async_trait]
pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {
/// To calculate the success rate for the list of chosen connectors
async fn calculate_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalSuccessRateResponse>;
/// To update the success rate with the given label
async fn update_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
response: Vec<RoutableConnectorChoiceWithStatus>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse>;
/// To invalidates the success rate routing keys
async fn invalidate_success_rate_routing_keys(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateWindowsResponse>;
/// To calculate both global and merchant specific success rate for the list of chosen connectors
async fn calculate_entity_and_global_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalGlobalSuccessRateResponse>;
}
#[async_trait::async_trait]
impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> {
#[instrument(skip_all)]
async fn calculate_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalSuccessRateResponse> {
let labels = label_input
.into_iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>();
let config = success_rate_based_config
.config
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
let request = grpc_client::create_grpc_request(
CalSuccessRateRequest {
id,
params,
labels,
config,
},
headers,
);
let response = self
.clone()
.fetch_success_rate(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
"Failed to fetch the success rate".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
#[instrument(skip_all)]
async fn update_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoiceWithStatus>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse> {
let config = success_rate_based_config
.config
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
let labels_with_status = label_input
.clone()
.into_iter()
.map(|conn_choice| LabelWithStatus {
label: conn_choice.routable_connector_choice.to_string(),
status: conn_choice.status,
})
.collect();
let global_labels_with_status = label_input
.into_iter()
.map(|conn_choice| LabelWithStatus {
label: conn_choice.routable_connector_choice.connector.to_string(),
status: conn_choice.status,
})
.collect();
let request = grpc_client::create_grpc_request(
UpdateSuccessRateWindowRequest {
id,
params,
labels_with_status,
config,
global_labels_with_status,
},
headers,
);
let response = self
.clone()
.update_success_rate_window(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
"Failed to update the success rate window".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
#[instrument(skip_all)]
async fn invalidate_success_rate_routing_keys(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateWindowsResponse> {
let request = grpc_client::create_grpc_request(InvalidateWindowsRequest { id }, headers);
let response = self
.clone()
.invalidate_windows(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
"Failed to invalidate the success rate routing keys".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
async fn calculate_entity_and_global_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalGlobalSuccessRateResponse> {
let labels = label_input
.clone()
.into_iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>();
let global_labels = label_input
.into_iter()
.map(|conn_choice| conn_choice.connector.to_string())
.collect::<Vec<_>>();
let config = success_rate_based_config
.config
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
let request = grpc_client::create_grpc_request(
CalGlobalSuccessRateRequest {
entity_id: id,
entity_params: params,
entity_labels: labels,
global_labels,
config,
},
headers,
);
let response = self
.clone()
.fetch_entity_and_global_success_rate(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
"Failed to fetch the entity and global success rate".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
}
impl ForeignTryFrom<CurrentBlockThreshold> for DynamicCurrentThreshold {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(current_threshold: CurrentBlockThreshold) -> Result<Self, Self::Error> {
Ok(Self {
duration_in_mins: current_threshold.duration_in_mins,
max_total_count: current_threshold
.max_total_count
.get_required_value("max_total_count")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "max_total_count".to_string(),
})?,
})
}
}
impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for UpdateSuccessRateWindowConfig {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> {
Ok(Self {
max_aggregates_size: config
.max_aggregates_size
.get_required_value("max_aggregate_size")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "max_aggregates_size".to_string(),
})?,
current_block_threshold: config
.current_block_threshold
.map(ForeignTryFrom::foreign_try_from)
.transpose()?,
})
}
}
impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalSuccessRateConfig {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> {
Ok(Self {
min_aggregates_size: config
.min_aggregates_size
.get_required_value("min_aggregate_size")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "min_aggregates_size".to_string(),
})?,
default_success_rate: config
.default_success_rate
.get_required_value("default_success_rate")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "default_success_rate".to_string(),
})?,
specificity_level: match config.specificity_level {
SuccessRateSpecificityLevel::Merchant => Some(ProtoSpecificityLevel::Entity.into()),
SuccessRateSpecificityLevel::Global => Some(ProtoSpecificityLevel::Global.into()),
},
exploration_percent: config.exploration_percent,
shuffle_on_tie_during_exploitation: config.shuffle_on_tie_during_exploitation,
})
}
}
impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalGlobalSuccessRateConfig {
type Error = error_stack::Report<DynamicRoutingError>;
fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> {
Ok(Self {
entity_min_aggregates_size: config
.min_aggregates_size
.get_required_value("min_aggregate_size")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "min_aggregates_size".to_string(),
})?,
entity_default_success_rate: config
.default_success_rate
.get_required_value("default_success_rate")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "default_success_rate".to_string(),
})?,
})
}
}
|
crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs
|
external_services
|
full_file
| null | null | null | 2,332
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentCapture for for Phonepe
// File: crates/hyperswitch_connectors/src/connectors/phonepe.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentCapture for for Phonepe
|
crates/hyperswitch_connectors/src/connectors/phonepe.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Phonepe
|
api::PaymentCapture for
| 0
| 0
| null | null |
// Function: list_user_authentication_methods
// File: crates/router/src/core/user.rs
// Module: router
pub fn list_user_authentication_methods(
state: SessionState,
req: user_api::GetUserAuthenticationMethodsRequest,
) -> UserResponse<Vec<user_api::UserAuthenticationMethodResponse>>
|
crates/router/src/core/user.rs
|
router
|
function_signature
| null | null | null | 62
|
list_user_authentication_methods
| null | null | null | null | null | null |
// Struct: GocardlessCustomer
// File: crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct GocardlessCustomer
|
crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
GocardlessCustomer
| 0
|
[] | 50
| null | null | null | null | null | null | null |
payment_method_data::WalletData::GooglePay(_) => Self::GooglePay,
payment_method_data::WalletData::BluecodeRedirect {} => Self::Bluecode,
payment_method_data::WalletData::GooglePayRedirect(_) => Self::GooglePayRedirect,
payment_method_data::WalletData::GooglePayThirdPartySdk(_) => {
Self::GooglePayThirdPartySdk
}
payment_method_data::WalletData::MbWayRedirect(_) => Self::MbWayRedirect,
payment_method_data::WalletData::MobilePayRedirect(_) => Self::MobilePayRedirect,
payment_method_data::WalletData::PaypalRedirect(_) => Self::PaypalRedirect,
payment_method_data::WalletData::PaypalSdk(_) => Self::PaypalSdk,
payment_method_data::WalletData::Paze(_) => Self::Paze,
payment_method_data::WalletData::SamsungPay(_) => Self::SamsungPay,
payment_method_data::WalletData::TwintRedirect {} => Self::TwintRedirect,
payment_method_data::WalletData::VippsRedirect {} => Self::VippsRedirect,
payment_method_data::WalletData::TouchNGoRedirect(_) => Self::TouchNGoRedirect,
payment_method_data::WalletData::WeChatPayRedirect(_) => Self::WeChatPayRedirect,
payment_method_data::WalletData::WeChatPayQr(_) => Self::WeChatPayQr,
payment_method_data::WalletData::CashappQr(_) => Self::CashappQr,
payment_method_data::WalletData::SwishQr(_) => Self::SwishQr,
payment_method_data::WalletData::Mifinity(_) => Self::Mifinity,
payment_method_data::WalletData::RevolutPay(_) => Self::RevolutPay,
},
PaymentMethodData::PayLater(pay_later_data) => match pay_later_data {
payment_method_data::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect,
payment_method_data::PayLaterData::KlarnaSdk { .. } => Self::KlarnaSdk,
payment_method_data::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect,
payment_method_data::PayLaterData::AfterpayClearpayRedirect { .. } => {
Self::AfterpayClearpayRedirect
}
payment_method_data::PayLaterData::FlexitiRedirect { .. } => Self::FlexitiRedirect,
payment_method_data::PayLaterData::PayBrightRedirect {} => Self::PayBrightRedirect,
payment_method_data::PayLaterData::WalleyRedirect {} => Self::WalleyRedirect,
payment_method_data::PayLaterData::AlmaRedirect {} => Self::AlmaRedirect,
payment_method_data::PayLaterData::AtomeRedirect {} => Self::AtomeRedirect,
payment_method_data::PayLaterData::BreadpayRedirect {} => Self::Breadpay,
},
PaymentMethodData::BankRedirect(bank_redirect_data) => match bank_redirect_data {
payment_method_data::BankRedirectData::BancontactCard { .. } => {
Self::BancontactCard
}
payment_method_data::BankRedirectData::Bizum {} => Self::Bizum,
payment_method_data::BankRedirectData::Blik { .. } => Self::Blik,
payment_method_data::BankRedirectData::Eft { .. } => Self::Eft,
payment_method_data::BankRedirectData::Eps { .. } => Self::Eps,
payment_method_data::BankRedirectData::Giropay { .. } => Self::Giropay,
payment_method_data::BankRedirectData::Ideal { .. } => Self::Ideal,
payment_method_data::BankRedirectData::Interac { .. } => Self::Interac,
payment_method_data::BankRedirectData::OnlineBankingCzechRepublic { .. } => {
Self::OnlineBankingCzechRepublic
}
payment_method_data::BankRedirectData::OnlineBankingFinland { .. } => {
Self::OnlineBankingFinland
}
payment_method_data::BankRedirectData::OnlineBankingPoland { .. } => {
Self::OnlineBankingPoland
}
payment_method_data::BankRedirectData::OnlineBankingSlovakia { .. } => {
Self::OnlineBankingSlovakia
}
payment_method_data::BankRedirectData::OpenBankingUk { .. } => Self::OpenBankingUk,
payment_method_data::BankRedirectData::Przelewy24 { .. } => Self::Przelewy24,
payment_method_data::BankRedirectData::Sofort { .. } => Self::Sofort,
payment_method_data::BankRedirectData::Trustly { .. } => Self::Trustly,
payment_method_data::BankRedirectData::OnlineBankingFpx { .. } => {
Self::OnlineBankingFpx
}
payment_method_data::BankRedirectData::OnlineBankingThailand { .. } => {
Self::OnlineBankingThailand
}
payment_method_data::BankRedirectData::LocalBankRedirect {} => {
Self::LocalBankRedirect
}
},
PaymentMethodData::BankDebit(bank_debit_data) => match bank_debit_data {
payment_method_data::BankDebitData::AchBankDebit { .. } => Self::AchBankDebit,
payment_method_data::BankDebitData::SepaBankDebit { .. } => Self::SepaBankDebit,
payment_method_data::BankDebitData::BecsBankDebit { .. } => Self::BecsBankDebit,
payment_method_data::BankDebitData::BacsBankDebit { .. } => Self::BacsBankDebit,
},
PaymentMethodData::BankTransfer(bank_transfer_data) => match *bank_transfer_data {
payment_method_data::BankTransferData::AchBankTransfer { .. } => {
Self::AchBankTransfer
}
payment_method_data::BankTransferData::SepaBankTransfer { .. } => {
Self::SepaBankTransfer
}
payment_method_data::BankTransferData::BacsBankTransfer { .. } => {
Self::BacsBankTransfer
}
payment_method_data::BankTransferData::MultibancoBankTransfer { .. } => {
Self::MultibancoBankTransfer
}
payment_method_data::BankTransferData::PermataBankTransfer { .. } => {
Self::PermataBankTransfer
}
payment_method_data::BankTransferData::BcaBankTransfer { .. } => {
Self::BcaBankTransfer
}
payment_method_data::BankTransferData::BniVaBankTransfer { .. } => {
Self::BniVaBankTransfer
}
payment_method_data::BankTransferData::BriVaBankTransfer { .. } => {
Self::BriVaBankTransfer
}
payment_method_data::BankTransferData::CimbVaBankTransfer { .. } => {
Self::CimbVaBankTransfer
}
payment_method_data::BankTransferData::DanamonVaBankTransfer { .. } => {
Self::DanamonVaBankTransfer
}
payment_method_data::BankTransferData::MandiriVaBankTransfer { .. } => {
Self::MandiriVaBankTransfer
}
payment_method_data::BankTransferData::Pix { .. } => Self::Pix,
payment_method_data::BankTransferData::Pse {} => Self::Pse,
payment_method_data::BankTransferData::LocalBankTransfer { .. } => {
Self::LocalBankTransfer
}
payment_method_data::BankTransferData::InstantBankTransfer {} => {
Self::InstantBankTransfer
}
payment_method_data::BankTransferData::InstantBankTransferFinland {} => {
Self::InstantBankTransferFinland
}
payment_method_data::BankTransferData::InstantBankTransferPoland {} => {
Self::InstantBankTransferPoland
}
payment_method_data::BankTransferData::IndonesianBankTransfer { .. } => {
Self::IndonesianBankTransfer
}
},
PaymentMethodData::Crypto(_) => Self::Crypto,
PaymentMethodData::MandatePayment => Self::MandatePayment,
PaymentMethodData::Reward => Self::Reward,
PaymentMethodData::Upi(_) => Self::Upi,
PaymentMethodData::Voucher(voucher_data) => match voucher_data {
payment_method_data::VoucherData::Boleto(_) => Self::Boleto,
payment_method_data::VoucherData::Efecty => Self::Efecty,
payment_method_data::VoucherData::PagoEfectivo => Self::PagoEfectivo,
payment_method_data::VoucherData::RedCompra => Self::RedCompra,
payment_method_data::VoucherData::RedPagos => Self::RedPagos,
payment_method_data::VoucherData::Alfamart(_) => Self::Alfamart,
payment_method_data::VoucherData::Indomaret(_) => Self::Indomaret,
payment_method_data::VoucherData::Oxxo => Self::Oxxo,
payment_method_data::VoucherData::SevenEleven(_) => Self::SevenEleven,
payment_method_data::VoucherData::Lawson(_) => Self::Lawson,
payment_method_data::VoucherData::MiniStop(_) => Self::MiniStop,
payment_method_data::VoucherData::FamilyMart(_) => Self::FamilyMart,
payment_method_data::VoucherData::Seicomart(_) => Self::Seicomart,
payment_method_data::VoucherData::PayEasy(_) => Self::PayEasy,
},
PaymentMethodData::RealTimePayment(real_time_payment_data) => {
match *real_time_payment_data {
payment_method_data::RealTimePaymentData::DuitNow {} => Self::DuitNow,
payment_method_data::RealTimePaymentData::Fps {} => Self::Fps,
payment_method_data::RealTimePaymentData::PromptPay {} => Self::PromptPay,
payment_method_data::RealTimePaymentData::VietQr {} => Self::VietQr,
}
}
PaymentMethodData::GiftCard(gift_card_data) => match *gift_card_data {
payment_method_data::GiftCardData::Givex(_) => Self::Givex,
payment_method_data::GiftCardData::PaySafeCard {} => Self::PaySafeCar,
payment_method_data::GiftCardData::BhnCardNetwork(_) => Self::BhnCardNetwork,
},
PaymentMethodData::CardToken(_) => Self::CardToken,
PaymentMethodData::OpenBanking(data) => match data {
payment_method_data::OpenBankingData::OpenBankingPIS {} => Self::OpenBanking,
},
PaymentMethodData::MobilePayment(mobile_payment_data) => match mobile_payment_data {
payment_method_data::MobilePaymentData::DirectCarrierBilling { .. } => {
Self::DirectCarrierBilling
}
},
}
}
}
pub trait GooglePay {
fn get_googlepay_encrypted_payment_data(&self) -> Result<Secret<String>, Error>;
}
impl GooglePay for payment_method_data::GooglePayWalletData {
fn get_googlepay_encrypted_payment_data(&self) -> Result<Secret<String>, Error> {
let encrypted_data = self
.tokenization_data
.get_encrypted_google_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Google Pay".to_string(),
})?;
Ok(Secret::new(encrypted_data.token.clone()))
}
}
pub trait ApplePay {
fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error>;
}
impl ApplePay for payment_method_data::ApplePayWalletData {
fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error> {
let apple_pay_encrypted_data = self
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
let token = Secret::new(
String::from_utf8(
BASE64_ENGINE
.decode(apple_pay_encrypted_data)
.change_context(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?,
)
.change_context(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?,
);
Ok(token)
}
}
pub trait WalletData {
fn get_wallet_token(&self) -> Result<Secret<String>, Error>;
fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error>
where
T: serde::de::DeserializeOwned;
fn get_encoded_wallet_token(&self) -> Result<String, Error>;
}
impl WalletData for payment_method_data::WalletData {
fn get_wallet_token(&self) -> Result<Secret<String>, Error> {
match self {
Self::GooglePay(data) => Ok(data.get_googlepay_encrypted_payment_data()?),
Self::ApplePay(data) => Ok(data.get_applepay_decoded_payment_data()?),
Self::PaypalSdk(data) => Ok(Secret::new(data.token.clone())),
_ => Err(errors::ConnectorError::InvalidWallet.into()),
}
}
fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
serde_json::from_str::<T>(self.get_wallet_token()?.peek())
.change_context(errors::ConnectorError::InvalidWalletToken { wallet_name })
}
fn get_encoded_wallet_token(&self) -> Result<String, Error> {
match self {
Self::GooglePay(_) => {
let json_token: Value = self.get_wallet_token_as_json("Google Pay".to_owned())?;
let token_as_vec = serde_json::to_vec(&json_token).change_context(
errors::ConnectorError::InvalidWalletToken {
wallet_name: "Google Pay".to_string(),
},
)?;
let encoded_token = BASE64_ENGINE.encode(token_as_vec);
Ok(encoded_token)
}
_ => Err(
errors::ConnectorError::NotImplemented("SELECTED PAYMENT METHOD".to_owned()).into(),
),
}
}
}
pub fn deserialize_xml_to_struct<T: serde::de::DeserializeOwned>(
xml_data: &[u8],
) -> Result<T, errors::ConnectorError> {
let response_str = std::str::from_utf8(xml_data)
.map_err(|e| {
router_env::logger::error!("Error converting response data to UTF-8: {:?}", e);
errors::ConnectorError::ResponseDeserializationFailed
})?
.trim();
let result: T = quick_xml::de::from_str(response_str).map_err(|e| {
router_env::logger::error!("Error deserializing XML response: {:?}", e);
errors::ConnectorError::ResponseDeserializationFailed
})?;
Ok(result)
}
pub fn is_html_response(response: &str) -> bool {
response.starts_with("<html>") || response.starts_with("<!DOCTYPE html>")
}
#[cfg(feature = "payouts")]
pub trait PayoutsData {
fn get_transfer_id(&self) -> Result<String, Error>;
fn get_customer_details(
&self,
) -> Result<hyperswitch_domain_models::router_request_types::CustomerDetails, Error>;
fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error>;
fn get_payout_type(&self) -> Result<enums::PayoutType, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
}
#[cfg(feature = "payouts")]
impl PayoutsData for hyperswitch_domain_models::router_request_types::PayoutsData {
fn get_transfer_id(&self) -> Result<String, Error> {
self.connector_payout_id
.clone()
.ok_or_else(missing_field_err("transfer_id"))
}
fn get_customer_details(
&self,
) -> Result<hyperswitch_domain_models::router_request_types::CustomerDetails, Error> {
self.customer_details
.clone()
.ok_or_else(missing_field_err("customer_details"))
}
fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error> {
self.vendor_details
.clone()
.ok_or_else(missing_field_err("vendor_details"))
}
fn get_payout_type(&self) -> Result<enums::PayoutType, Error> {
self.payout_type
.to_owned()
.ok_or_else(missing_field_err("payout_type"))
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.to_owned()
.ok_or_else(missing_field_err("webhook_url"))
}
}
pub trait RevokeMandateRequestData {
fn get_connector_mandate_id(&self) -> Result<String, Error>;
}
impl RevokeMandateRequestData for MandateRevokeRequestData {
fn get_connector_mandate_id(&self) -> Result<String, Error> {
self.connector_mandate_id
.clone()
.ok_or_else(missing_field_err("connector_mandate_id"))
}
}
pub trait RecurringMandateData {
fn get_original_payment_amount(&self) -> Result<i64, Error>;
fn get_original_payment_currency(&self) -> Result<enums::Currency, Error>;
}
impl RecurringMandateData for RecurringMandatePaymentData {
fn get_original_payment_amount(&self) -> Result<i64, Error> {
self.original_payment_authorized_amount
.ok_or_else(missing_field_err("original_payment_authorized_amount"))
}
fn get_original_payment_currency(&self) -> Result<enums::Currency, Error> {
self.original_payment_authorized_currency
.ok_or_else(missing_field_err("original_payment_authorized_currency"))
}
}
#[cfg(feature = "payouts")]
impl CardData for api_models::payouts::CardPayout {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.expiry_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
fn get_card_expiry_month_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let exp_month = self
.expiry_month
.peek()
.to_string()
.parse::<u8>()
.map_err(|_| errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
})?;
let month = ::cards::CardExpirationMonth::try_from(exp_month).map_err(|_| {
errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
}
})?;
Ok(Secret::new(month.two_digits()))
}
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.card_number.peek())
}
fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.expiry_month.peek(),
delimiter,
year.peek()
)))
}
fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
year.peek(),
delimiter,
self.expiry_month.peek()
))
}
fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
self.expiry_month.peek(),
delimiter,
year.peek()
))
}
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.expiry_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.expiry_month.clone().expose();
Ok(Secret::new(format!("{year}{month}")))
}
fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
self.expiry_month
.peek()
.clone()
.parse::<i8>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> {
self.expiry_year
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.expiry_month.clone().expose();
Ok(Secret::new(format!("{month}{year}")))
}
fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error> {
self.get_expiry_year_4_digit()
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_cardholder_name(&self) -> Result<Secret<String>, Error> {
self.card_holder_name
.clone()
.ok_or_else(missing_field_err("card.card_holder_name"))
}
}
pub trait NetworkTokenData {
fn get_card_issuer(&self) -> Result<CardIssuer, Error>;
fn get_expiry_year_4_digit(&self) -> Secret<String>;
fn get_network_token(&self) -> NetworkTokenNumber;
fn get_network_token_expiry_month(&self) -> Secret<String>;
fn get_network_token_expiry_year(&self) -> Secret<String>;
fn get_cryptogram(&self) -> Option<Secret<String>>;
fn get_token_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>;
fn get_token_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError>;
}
impl NetworkTokenData for payment_method_data::NetworkTokenData {
#[cfg(feature = "v1")]
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.token_number.peek())
}
#[cfg(feature = "v2")]
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.network_token.peek())
}
#[cfg(feature = "v1")]
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.token_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
#[cfg(feature = "v2")]
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.network_token_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
#[cfg(feature = "v1")]
fn get_network_token(&self) -> NetworkTokenNumber {
self.token_number.clone()
}
#[cfg(feature = "v2")]
fn get_network_token(&self) -> NetworkTokenNumber {
self.network_token.clone()
}
#[cfg(feature = "v1")]
fn get_network_token_expiry_month(&self) -> Secret<String> {
self.token_exp_month.clone()
}
#[cfg(feature = "v2")]
fn get_network_token_expiry_month(&self) -> Secret<String> {
self.network_token_exp_month.clone()
}
#[cfg(feature = "v1")]
fn get_network_token_expiry_year(&self) -> Secret<String> {
self.token_exp_year.clone()
}
#[cfg(feature = "v2")]
fn get_network_token_expiry_year(&self) -> Secret<String> {
self.network_token_exp_year.clone()
}
#[cfg(feature = "v1")]
fn get_cryptogram(&self) -> Option<Secret<String>> {
self.token_cryptogram.clone()
}
#[cfg(feature = "v2")]
fn get_cryptogram(&self) -> Option<Secret<String>> {
self.cryptogram.clone()
}
#[cfg(feature = "v1")]
fn get_token_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.token_exp_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
#[cfg(feature = "v2")]
fn get_token_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.network_token_exp_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
#[cfg(feature = "v1")]
fn get_token_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_token_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.token_exp_month.peek(),
delimiter,
year.peek()
)))
}
#[cfg(feature = "v2")]
fn get_token_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_token_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.network_token_exp_month.peek(),
delimiter,
year.peek()
)))
}
}
pub fn convert_uppercase<'de, D, T>(v: D) -> Result<T, D::Error>
where
D: serde::Deserializer<'de>,
T: FromStr,
<T as FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error,
{
use serde::de::Error;
let output = <&str>::deserialize(v)?;
output.to_uppercase().parse::<T>().map_err(D::Error::custom)
}
pub(crate) fn convert_setup_mandate_router_data_to_authorize_router_data(
data: &SetupMandateRouterData,
) -> PaymentsAuthorizeData {
PaymentsAuthorizeData {
currency: data.request.currency,
payment_method_data: data.request.payment_method_data.clone(),
confirm: data.request.confirm,
statement_descriptor_suffix: data.request.statement_descriptor_suffix.clone(),
mandate_id: data.request.mandate_id.clone(),
setup_future_usage: data.request.setup_future_usage,
off_session: data.request.off_session,
setup_mandate_details: data.request.setup_mandate_details.clone(),
router_return_url: data.request.router_return_url.clone(),
email: data.request.email.clone(),
customer_name: data.request.customer_name.clone(),
amount: 0,
order_tax_amount: Some(MinorUnit::zero()),
minor_amount: MinorUnit::new(0),
statement_descriptor: None,
capture_method: data.request.capture_method,
webhook_url: None,
complete_authorize_url: None,
browser_info: data.request.browser_info.clone(),
order_details: None,
order_category: None,
session_token: None,
enrolled_for_3ds: true,
related_transaction_id: None,
payment_experience: None,
payment_method_type: None,
customer_id: None,
surcharge_details: None,
request_extended_authorization: None,
request_incremental_authorization: data.request.request_incremental_authorization,
metadata: None,
authentication_data: None,
customer_acceptance: data.request.customer_acceptance.clone(),
split_payments: None, // TODO: allow charges on mandates?
merchant_order_reference_id: None,
integrity_object: None,
additional_payment_method_data: None,
shipping_cost: data.request.shipping_cost,
merchant_account_id: None,
merchant_config_currency: None,
connector_testing_data: data.request.connector_testing_data.clone(),
order_id: None,
locale: None,
payment_channel: data.request.payment_channel.clone(),
enable_partial_authorization: data.request.enable_partial_authorization,
enable_overcapture: None,
is_stored_credential: data.request.is_stored_credential,
}
}
pub(crate) fn convert_payment_authorize_router_response<F1, F2, T1, T2>(
item: (&ConnectorRouterData<F1, T1, PaymentsResponseData>, T2),
) -> ConnectorRouterData<F2, T2, PaymentsResponseData> {
let data = item.0;
let request = item.1;
ConnectorRouterData {
flow: PhantomData,
request,
merchant_id: data.merchant_id.clone(),
connector: data.connector.clone(),
attempt_id: data.attempt_id.clone(),
tenant_id: data.tenant_id.clone(),
status: data.status,
payment_method: data.payment_method,
connector_auth_type: data.connector_auth_type.clone(),
description: data.description.clone(),
address: data.address.clone(),
auth_type: data.auth_type,
connector_meta_data: data.connector_meta_data.clone(),
connector_wallets_details: data.connector_wallets_details.clone(),
amount_captured: data.amount_captured,
minor_amount_captured: data.minor_amount_captured,
access_token: data.access_token.clone(),
response: data.response.clone(),
payment_id: data.payment_id.clone(),
session_token: data.session_token.clone(),
reference_id: data.reference_id.clone(),
customer_id: data.customer_id.clone(),
payment_method_token: None,
preprocessing_id: None,
connector_customer: data.connector_customer.clone(),
recurring_mandate_payment_data: data.recurring_mandate_payment_data.clone(),
connector_request_reference_id: data.connector_request_reference_id.clone(),
#[cfg(feature = "payouts")]
payout_method_data: data.payout_method_data.clone(),
#[cfg(feature = "payouts")]
quote_id: data.quote_id.clone(),
test_mode: data.test_mode,
payment_method_status: None,
payment_method_balance: data.payment_method_balance.clone(),
connector_api_version: data.connector_api_version.clone(),
connector_http_status_code: data.connector_http_status_code,
external_latency: data.external_latency,
apple_pay_flow: data.apple_pay_flow.clone(),
frm_metadata: data.frm_metadata.clone(),
dispute_id: data.dispute_id.clone(),
refund_id: data.refund_id.clone(),
connector_response: data.connector_response.clone(),
integrity_check: Ok(()),
additional_merchant_data: data.additional_merchant_data.clone(),
header_payload: data.header_payload.clone(),
connector_mandate_request_reference_id: data.connector_mandate_request_reference_id.clone(),
authentication_id: data.authentication_id.clone(),
psd2_sca_exemption_type: data.psd2_sca_exemption_type,
raw_connector_response: data.raw_connector_response.clone(),
is_payment_id_from_merchant: data.is_payment_id_from_merchant,
l2_l3_data: data.l2_l3_data.clone(),
minor_amount_capturable: data.minor_amount_capturable,
}
}
pub fn generate_12_digit_number() -> u64 {
let mut rng = rand::thread_rng();
rng.gen_range(100_000_000_000..=999_999_999_999)
}
/// Normalizes a string by converting to lowercase, performing NFKD normalization(https://unicode.org/reports/tr15/#Description_Norm),and removing special characters and spaces.
pub fn normalize_string(value: String) -> Result<String, regex::Error> {
let nfkd_value = value.nfkd().collect::<String>();
let lowercase_value = nfkd_value.to_lowercase();
static REGEX: LazyLock<Result<Regex, regex::Error>> =
LazyLock::new(|| Regex::new(r"[^a-z0-9]"));
let regex = REGEX.as_ref().map_err(|e| e.clone())?;
let normalized = regex.replace_all(&lowercase_value, "").to_string();
Ok(normalized)
}
fn normalize_state(value: String) -> Result<String, error_stack::Report<errors::ConnectorError>> {
normalize_string(value).map_err(|_e| {
error_stack::Report::new(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
})
})
}
pub fn parse_state_enum<T>(
value: String,
enum_name: &'static str,
field_name: &'static str,
) -> Result<String, error_stack::Report<errors::ConnectorError>>
where
T: FromStr,
<T as FromStr>::Err: std::error::Error + Send + Sync + 'static,
{
match StringExt::<T>::parse_enum(value.clone(), enum_name) {
Ok(_) => Ok(value),
Err(_) => normalize_state(value).map_err(|_e| {
error_stack::Report::new(errors::ConnectorError::InvalidDataFormat { field_name })
}),
}
}
#[cfg(feature = "frm")]
pub trait FrmTransactionRouterDataRequest {
fn is_payment_successful(&self) -> Option<bool>;
}
#[cfg(feature = "frm")]
impl FrmTransactionRouterDataRequest for FrmTransactionRouterData {
fn is_payment_successful(&self) -> Option<bool> {
match self.status {
AttemptStatus::AuthenticationFailed
| AttemptStatus::RouterDeclined
| AttemptStatus::AuthorizationFailed
| AttemptStatus::Voided
| AttemptStatus::VoidedPostCharge
| AttemptStatus::CaptureFailed
| AttemptStatus::Failure
| AttemptStatus::AutoRefunded
| AttemptStatus::Expired => Some(false),
AttemptStatus::AuthenticationSuccessful
| AttemptStatus::PartialChargedAndChargeable
| AttemptStatus::Authorized
| AttemptStatus::Charged
| AttemptStatus::IntegrityFailure
| AttemptStatus::PartiallyAuthorized => Some(true),
AttemptStatus::Started
| AttemptStatus::AuthenticationPending
| AttemptStatus::Authorizing
| AttemptStatus::CodInitiated
| AttemptStatus::VoidInitiated
| AttemptStatus::CaptureInitiated
| AttemptStatus::VoidFailed
| AttemptStatus::PartialCharged
| AttemptStatus::Unresolved
| AttemptStatus::Pending
| AttemptStatus::PaymentMethodAwaited
| AttemptStatus::ConfirmationAwaited
| AttemptStatus::DeviceDataCollectionPending => None,
}
}
}
#[cfg(feature = "frm")]
pub trait FraudCheckCheckoutRequest {
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>;
}
#[cfg(feature = "frm")]
impl FraudCheckCheckoutRequest for FraudCheckCheckoutData {
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> {
self.order_details
.clone()
.ok_or_else(missing_field_err("order_details"))
}
}
#[cfg(feature = "frm")]
pub trait FraudCheckTransactionRequest {
fn get_currency(&self) -> Result<enums::Currency, Error>;
}
#[cfg(feature = "frm")]
impl FraudCheckTransactionRequest for FraudCheckTransactionData {
fn get_currency(&self) -> Result<enums::Currency, Error> {
self.currency.ok_or_else(missing_field_err("currency"))
}
}
/// Custom deserializer for Option<Currency> that treats empty strings as None
pub fn deserialize_optional_currency<'de, D>(
deserializer: D,
) -> Result<Option<enums::Currency>, D::Error>
where
D: serde::Deserializer<'de>,
{
let string_data: Option<String> = Option::deserialize(deserializer)?;
match string_data {
Some(ref value) if !value.is_empty() => value
.clone()
.parse_enum("Currency")
.map(Some)
.map_err(|_| serde::de::Error::custom(format!("Invalid currency code: {value}"))),
_ => Ok(None),
}
}
#[cfg(feature = "payouts")]
pub trait CustomerDetails {
fn get_customer_id(&self) -> Result<id_type::CustomerId, errors::ConnectorError>;
fn get_customer_name(
&self,
|
crates/hyperswitch_connectors/src/utils.rs#chunk9
|
hyperswitch_connectors
|
chunk
| null | null | null | 8,186
| null | null | null | null | null | null | null |
// Function: server
// File: crates/router/src/routes/app.rs
// Module: router
pub fn server(state: AppState) -> Scope
|
crates/router/src/routes/app.rs
|
router
|
function_signature
| null | null | null | 29
|
server
| null | null | null | null | null | null |
// Function: signout_external_token
// File: crates/router/src/core/external_service_auth.rs
// Module: router
pub fn signout_external_token(
state: SessionState,
json_payload: external_service_auth_api::ExternalSignoutTokenRequest,
) -> RouterResponse<()>
|
crates/router/src/core/external_service_auth.rs
|
router
|
function_signature
| null | null | null | 59
|
signout_external_token
| null | null | null | null | null | null |
// Struct: MerchantAccountNew
// File: crates/diesel_models/src/merchant_account.rs
// Module: diesel_models
// Implementations: 0
pub struct MerchantAccountNew
|
crates/diesel_models/src/merchant_account.rs
|
diesel_models
|
struct_definition
|
MerchantAccountNew
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// Function: delete_entry_from_blocklist
// File: crates/router/src/core/blocklist/utils.rs
// Module: router
pub fn delete_entry_from_blocklist(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
request: api_blocklist::DeleteFromBlocklistRequest,
) -> RouterResult<api_blocklist::DeleteFromBlocklistResponse>
|
crates/router/src/core/blocklist/utils.rs
|
router
|
function_signature
| null | null | null | 83
|
delete_entry_from_blocklist
| null | null | null | null | null | null |
// Struct: BancontactBankRedirectAdditionalData
// File: crates/api_models/src/payments/additional_info.rs
// Module: api_models
// Implementations: 0
pub struct BancontactBankRedirectAdditionalData
|
crates/api_models/src/payments/additional_info.rs
|
api_models
|
struct_definition
|
BancontactBankRedirectAdditionalData
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Struct: Globepay
// File: crates/hyperswitch_connectors/src/connectors/globepay.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 Globepay
|
crates/hyperswitch_connectors/src/connectors/globepay.rs
|
hyperswitch_connectors
|
struct_definition
|
Globepay
| 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"
] | 129
| null | null | null | null | null | null | null |
// Struct: EphemeralKeyNew
// File: crates/diesel_models/src/ephemeral_key.rs
// Module: diesel_models
// Implementations: 0
pub struct EphemeralKeyNew
|
crates/diesel_models/src/ephemeral_key.rs
|
diesel_models
|
struct_definition
|
EphemeralKeyNew
| 0
|
[] | 44
| null | null | null | null | null | null | null |
// Struct: NordeaFailures
// File: crates/hyperswitch_connectors/src/connectors/nordea/responses.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NordeaFailures
|
crates/hyperswitch_connectors/src/connectors/nordea/responses.rs
|
hyperswitch_connectors
|
struct_definition
|
NordeaFailures
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Trait: GetRoutableConnectorsForChoice
// File: crates/router/src/core/routing.rs
// Module: router
pub trait GetRoutableConnectorsForChoice
|
crates/router/src/core/routing.rs
|
router
|
trait_definition
| null | null | null | 38
| null | null |
GetRoutableConnectorsForChoice
| null | null | null | null |
// Struct: RefundSyncBody
// File: crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RefundSyncBody
|
crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RefundSyncBody
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Function: connector_update
// File: crates/router/src/routes/admin.rs
// Module: router
pub fn connector_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantConnectorAccountId>,
json_payload: web::Json<api_models::admin::MerchantConnectorUpdate>,
) -> HttpResponse
|
crates/router/src/routes/admin.rs
|
router
|
function_signature
| null | null | null | 77
|
connector_update
| null | null | null | null | null | null |
// Function: from_conf
// File: crates/analytics/src/sqlx.rs
// Module: analytics
pub fn from_conf(conf: &Database, schema: &str) -> Self
|
crates/analytics/src/sqlx.rs
|
analytics
|
function_signature
| null | null | null | 38
|
from_conf
| null | null | null | null | null | null |
// File: crates/router/src/routes/customers.rs
// Module: router
// Public functions: 11
use actix_web::{web, HttpRequest, HttpResponse, Responder};
use common_utils::id_type;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{api_locking, customers::*},
services::{api, authentication as auth, authorization::permissions::Permission},
types::{api::customers, domain},
};
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))]
pub async fn customers_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<customers::CustomerRequest>,
) -> HttpResponse {
let flow = Flow::CustomersCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
create_customer(state, merchant_context, req, None)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))]
pub async fn customers_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<customers::CustomerRequest>,
) -> HttpResponse {
let flow = Flow::CustomersCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
create_customer(state, merchant_context, req, None)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersRetrieve))]
pub async fn customers_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::CustomerId>,
) -> HttpResponse {
let flow = Flow::CustomersRetrieve;
let customer_id = path.into_inner();
let auth = if auth::is_jwt_auth(req.headers()) {
Box::new(auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
})
} else {
let api_auth = auth::ApiKeyAuth::default();
match auth::is_ephemeral_auth(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
}
};
Box::pin(api::server_wrap(
flow,
state,
&req,
customer_id,
|state, auth: auth::AuthenticationData, customer_id, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
retrieve_customer(state, merchant_context, auth.profile_id, customer_id)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersRetrieve))]
pub async fn customers_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalCustomerId>,
) -> HttpResponse {
use crate::services::authentication::api_or_client_auth;
let flow = Flow::CustomersRetrieve;
let id = path.into_inner();
let v2_client_auth = auth::V2ClientAuth(
common_utils::types::authentication::ResourceId::Customer(id.clone()),
);
let auth = if auth::is_jwt_auth(req.headers()) {
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
}
} else {
api_or_client_auth(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&v2_client_auth,
req.headers(),
)
};
Box::pin(api::server_wrap(
flow,
state,
&req,
id,
|state, auth: auth::AuthenticationData, id, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
retrieve_customer(state, merchant_context, id)
},
auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersList))]
pub async fn customers_list(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<customers::CustomerListRequest>,
) -> HttpResponse {
let flow = Flow::CustomersList;
let payload = query.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, request, _| {
list_customers(
state,
auth.merchant_account.get_id().to_owned(),
None,
auth.key_store,
request,
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersList))]
pub async fn customers_list(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<customers::CustomerListRequest>,
) -> HttpResponse {
let flow = Flow::CustomersList;
let payload = query.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, request, _| {
list_customers(
state,
auth.merchant_account.get_id().to_owned(),
None,
auth.key_store,
request,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersUpdate))]
pub async fn customers_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::CustomerId>,
json_payload: web::Json<customers::CustomerUpdateRequest>,
) -> HttpResponse {
let flow = Flow::CustomersUpdate;
let customer_id = path.into_inner();
let request = json_payload.into_inner();
let request_internal = customers::CustomerUpdateRequestInternal {
customer_id,
request,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
request_internal,
|state, auth: auth::AuthenticationData, request_internal, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
update_customer(state, merchant_context, request_internal)
},
auth::auth_type(
&auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersUpdate))]
pub async fn customers_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalCustomerId>,
json_payload: web::Json<customers::CustomerUpdateRequest>,
) -> HttpResponse {
let flow = Flow::CustomersUpdate;
let id = path.into_inner();
let request = json_payload.into_inner();
let request_internal = customers::CustomerUpdateRequestInternal { id, request };
Box::pin(api::server_wrap(
flow,
state,
&req,
request_internal,
|state, auth: auth::AuthenticationData, request_internal, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
update_customer(state, merchant_context, request_internal)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersDelete))]
pub async fn customers_delete(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalCustomerId>,
) -> impl Responder {
let flow = Flow::CustomersDelete;
let id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
id,
|state, auth: auth::AuthenticationData, id, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
delete_customer(state, merchant_context, id)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersDelete))]
pub async fn customers_delete(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::CustomerId>,
) -> impl Responder {
let flow = Flow::CustomersDelete;
let customer_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
customer_id,
|state, auth: auth::AuthenticationData, customer_id, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
delete_customer(state, merchant_context, customer_id)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersGetMandates))]
pub async fn get_customer_mandates(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::CustomerId>,
) -> impl Responder {
let flow = Flow::CustomersGetMandates;
let customer_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
customer_id,
|state, auth: auth::AuthenticationData, customer_id, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
crate::core::mandate::get_customer_mandates(state, merchant_context, customer_id)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantMandateRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/customers.rs
|
router
|
full_file
| null | null | null | 2,858
| null | null | null | null | null | null | null |
// Implementation: impl api::UasAuthentication for for Juspaythreedsserver
// File: crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::UasAuthentication for for Juspaythreedsserver
|
crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 74
| null |
Juspaythreedsserver
|
api::UasAuthentication for
| 0
| 0
| null | null |
// Struct: PaymentRedirectCompleteAuthorize
// File: crates/router/src/core/payments.rs
// Module: router
// Implementations: 1
// Traits: PaymentRedirectFlow
pub struct PaymentRedirectCompleteAuthorize
|
crates/router/src/core/payments.rs
|
router
|
struct_definition
|
PaymentRedirectCompleteAuthorize
| 1
|
[
"PaymentRedirectFlow"
] | 44
| null | null | null | null | null | null | null |
// Implementation: impl RefundSync for for Cybersource
// File: crates/hyperswitch_connectors/src/connectors/cybersource.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl RefundSync for for Cybersource
|
crates/hyperswitch_connectors/src/connectors/cybersource.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Cybersource
|
RefundSync for
| 0
| 0
| null | null |
// Struct: DisputeTransaction
// File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct DisputeTransaction
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
DisputeTransaction
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Function: find_by_algorithm_id_merchant_id
// File: crates/diesel_models/src/query/routing_algorithm.rs
// Module: diesel_models
pub fn find_by_algorithm_id_merchant_id(
conn: &PgPooledConn,
algorithm_id: &common_utils::id_type::RoutingId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self>
|
crates/diesel_models/src/query/routing_algorithm.rs
|
diesel_models
|
function_signature
| null | null | null | 85
|
find_by_algorithm_id_merchant_id
| null | null | null | null | null | null |
// File: crates/diesel_models/src/query/events.rs
// Module: diesel_models
// Public functions: 11
use std::collections::HashSet;
use diesel::{
associations::HasTable, BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods,
};
use super::generics;
use crate::{
events::{Event, EventNew, EventUpdateInternal},
schema::events::dsl,
PgPooledConn, StorageResult,
};
impl EventNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Event> {
generics::generic_insert(conn, self).await
}
}
impl Event {
pub async fn find_by_merchant_id_event_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::event_id.eq(event_id.to_owned())),
)
.await
}
pub async fn find_by_merchant_id_idempotent_event_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
idempotent_event_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::idempotent_event_id.eq(idempotent_event_id.to_owned())),
)
.await
}
pub async fn list_initial_attempts_by_merchant_id_primary_object_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::event_id
.nullable()
.eq(dsl::initial_attempt_id) // Filter initial attempts only
.and(dsl::merchant_id.eq(merchant_id.to_owned()))
.and(dsl::primary_object_id.eq(primary_object_id.to_owned())),
None,
None,
Some(dsl::created_at.desc()),
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn list_initial_attempts_by_merchant_id_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> StorageResult<Vec<Self>> {
use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{debug_query, pg::Pg, QueryDsl};
use error_stack::ResultExt;
use router_env::logger;
use super::generics::db_metrics::{track_database_call, DatabaseOperation};
use crate::errors::DatabaseError;
let mut query = Self::table()
.filter(
dsl::event_id
.nullable()
.eq(dsl::initial_attempt_id) // Filter initial attempts only
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
)
.order(dsl::created_at.desc())
.into_boxed();
query = Self::apply_filters(
query,
None,
(dsl::created_at, created_after, created_before),
limit,
offset,
event_types,
is_delivered,
);
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
.await
.change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
.attach_printable("Error filtering events by constraints")
}
pub async fn list_by_merchant_id_initial_attempt_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())),
None,
None,
Some(dsl::created_at.desc()),
)
.await
}
pub async fn list_initial_attempts_by_profile_id_primary_object_id(
conn: &PgPooledConn,
profile_id: &common_utils::id_type::ProfileId,
primary_object_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::event_id
.nullable()
.eq(dsl::initial_attempt_id) // Filter initial attempts only
.and(dsl::business_profile_id.eq(profile_id.to_owned()))
.and(dsl::primary_object_id.eq(primary_object_id.to_owned())),
None,
None,
Some(dsl::created_at.desc()),
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn list_initial_attempts_by_profile_id_constraints(
conn: &PgPooledConn,
profile_id: &common_utils::id_type::ProfileId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> StorageResult<Vec<Self>> {
use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{debug_query, pg::Pg, QueryDsl};
use error_stack::ResultExt;
use router_env::logger;
use super::generics::db_metrics::{track_database_call, DatabaseOperation};
use crate::errors::DatabaseError;
let mut query = Self::table()
.filter(
dsl::event_id
.nullable()
.eq(dsl::initial_attempt_id) // Filter initial attempts only
.and(dsl::business_profile_id.eq(profile_id.to_owned())),
)
.order(dsl::created_at.desc())
.into_boxed();
query = Self::apply_filters(
query,
None,
(dsl::created_at, created_after, created_before),
limit,
offset,
event_types,
is_delivered,
);
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
.await
.change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
.attach_printable("Error filtering events by constraints")
}
pub async fn list_by_profile_id_initial_attempt_id(
conn: &PgPooledConn,
profile_id: &common_utils::id_type::ProfileId,
initial_attempt_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::business_profile_id
.eq(profile_id.to_owned())
.and(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())),
None,
None,
Some(dsl::created_at.desc()),
)
.await
}
pub async fn update_by_merchant_id_event_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
event: EventUpdateInternal,
) -> StorageResult<Self> {
generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::event_id.eq(event_id.to_owned())),
event,
)
.await
}
fn apply_filters<T>(
mut query: T,
profile_id: Option<common_utils::id_type::ProfileId>,
(column, created_after, created_before): (
dsl::created_at,
time::PrimitiveDateTime,
time::PrimitiveDateTime,
),
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> T
where
T: diesel::query_dsl::methods::LimitDsl<Output = T>
+ diesel::query_dsl::methods::OffsetDsl<Output = T>,
T: diesel::query_dsl::methods::FilterDsl<
diesel::dsl::GtEq<dsl::created_at, time::PrimitiveDateTime>,
Output = T,
>,
T: diesel::query_dsl::methods::FilterDsl<
diesel::dsl::LtEq<dsl::created_at, time::PrimitiveDateTime>,
Output = T,
>,
T: diesel::query_dsl::methods::FilterDsl<
diesel::dsl::Eq<dsl::business_profile_id, common_utils::id_type::ProfileId>,
Output = T,
>,
T: diesel::query_dsl::methods::FilterDsl<
diesel::dsl::EqAny<dsl::event_type, HashSet<common_enums::EventType>>,
Output = T,
>,
T: diesel::query_dsl::methods::FilterDsl<
diesel::dsl::Eq<dsl::is_overall_delivery_successful, bool>,
Output = T,
>,
{
if let Some(profile_id) = profile_id {
query = query.filter(dsl::business_profile_id.eq(profile_id));
}
query = query
.filter(column.ge(created_after))
.filter(column.le(created_before));
if let Some(limit) = limit {
query = query.limit(limit);
}
if let Some(offset) = offset {
query = query.offset(offset);
}
if !event_types.is_empty() {
query = query.filter(dsl::event_type.eq_any(event_types));
}
if let Some(is_delivered) = is_delivered {
query = query.filter(dsl::is_overall_delivery_successful.eq(is_delivered));
}
query
}
pub async fn count_initial_attempts_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: Option<common_utils::id_type::ProfileId>,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> StorageResult<i64> {
use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{debug_query, pg::Pg, QueryDsl};
use error_stack::ResultExt;
use router_env::logger;
use super::generics::db_metrics::{track_database_call, DatabaseOperation};
use crate::errors::DatabaseError;
let mut query = Self::table()
.count()
.filter(
dsl::event_id
.nullable()
.eq(dsl::initial_attempt_id) // Filter initial attempts only
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
)
.into_boxed();
query = Self::apply_filters(
query,
profile_id,
(dsl::created_at, created_after, created_before),
None,
None,
event_types,
is_delivered,
);
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<Self, _, _>(
query.get_result_async::<i64>(conn),
DatabaseOperation::Count,
)
.await
.change_context(DatabaseError::Others)
.attach_printable("Error counting events by constraints")
}
}
|
crates/diesel_models/src/query/events.rs
|
diesel_models
|
full_file
| null | null | null | 2,676
| null | null | null | null | null | null | null |
// Struct: PaymentMethodId
// File: crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaymentMethodId
|
crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaymentMethodId
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Implementation: impl Deref for for ExtendedAuthorizationAppliedBool
// File: crates/common_types/src/primitive_wrappers.rs
// Module: common_types
// Methods: 1 total (0 public)
impl Deref for for ExtendedAuthorizationAppliedBool
|
crates/common_types/src/primitive_wrappers.rs
|
common_types
|
impl_block
| null | null | null | 51
| null |
ExtendedAuthorizationAppliedBool
|
Deref for
| 1
| 0
| null | null |
// Function: list_by_merchant_id_initial_attempt_id
// File: crates/diesel_models/src/query/events.rs
// Module: diesel_models
pub fn list_by_merchant_id_initial_attempt_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
) -> StorageResult<Vec<Self>>
|
crates/diesel_models/src/query/events.rs
|
diesel_models
|
function_signature
| null | null | null | 80
|
list_by_merchant_id_initial_attempt_id
| null | null | null | null | null | null |
// Struct: EligiblePaymentMethods
// File: crates/payment_methods/src/configs/settings.rs
// Module: payment_methods
// Implementations: 0
pub struct EligiblePaymentMethods
|
crates/payment_methods/src/configs/settings.rs
|
payment_methods
|
struct_definition
|
EligiblePaymentMethods
| 0
|
[] | 39
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_domain_models/src/chat.rs
// Module: hyperswitch_domain_models
// Public structs: 2
use common_utils::id_type;
use masking::Secret;
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct GetDataMessage {
pub message: Secret<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct HyperswitchAiDataRequest {
pub merchant_id: id_type::MerchantId,
pub profile_id: id_type::ProfileId,
pub org_id: id_type::OrganizationId,
pub query: GetDataMessage,
pub entity_type: common_enums::EntityType,
}
|
crates/hyperswitch_domain_models/src/chat.rs
|
hyperswitch_domain_models
|
full_file
| null | null | null | 143
| null | null | null | null | null | null | null |
// Implementation: impl NewUser
// File: crates/router/src/types/domain/user.rs
// Module: router
// Methods: 10 total (6 public)
impl NewUser
|
crates/router/src/types/domain/user.rs
|
router
|
impl_block
| null | null | null | 37
| null |
NewUser
| null | 10
| 6
| null | null |
// File: crates/payment_methods/src/configs/payment_connector_required_fields.rs
// Module: payment_methods
// Public functions: 3
use std::collections::{HashMap, HashSet};
use api_models::{
enums::{self, Connector, FieldType},
payment_methods::RequiredFieldInfo,
};
use crate::configs::settings::{
BankRedirectConfig, ConnectorFields, Mandates, RequiredFieldFinal,
SupportedConnectorsForMandate, SupportedPaymentMethodTypesForMandate,
SupportedPaymentMethodsForMandate, ZeroMandates,
};
#[cfg(feature = "v1")]
use crate::configs::settings::{PaymentMethodType, RequiredFields};
impl Default for ZeroMandates {
fn default() -> Self {
Self {
supported_payment_methods: SupportedPaymentMethodsForMandate(HashMap::new()),
}
}
}
impl Default for Mandates {
fn default() -> Self {
Self {
supported_payment_methods: SupportedPaymentMethodsForMandate(HashMap::from([
(
enums::PaymentMethod::PayLater,
SupportedPaymentMethodTypesForMandate(HashMap::from([(
enums::PaymentMethodType::Klarna,
SupportedConnectorsForMandate {
connector_list: HashSet::from([Connector::Adyen]),
},
)])),
),
(
enums::PaymentMethod::Wallet,
SupportedPaymentMethodTypesForMandate(HashMap::from([
(
enums::PaymentMethodType::GooglePay,
SupportedConnectorsForMandate {
connector_list: HashSet::from([
Connector::Stripe,
Connector::Adyen,
Connector::Globalpay,
Connector::Multisafepay,
Connector::Bankofamerica,
Connector::Novalnet,
Connector::Noon,
Connector::Cybersource,
Connector::Wellsfargo,
]),
},
),
(
enums::PaymentMethodType::ApplePay,
SupportedConnectorsForMandate {
connector_list: HashSet::from([
Connector::Stripe,
Connector::Adyen,
Connector::Bankofamerica,
Connector::Cybersource,
Connector::Novalnet,
Connector::Wellsfargo,
]),
},
),
(
enums::PaymentMethodType::SamsungPay,
SupportedConnectorsForMandate {
connector_list: HashSet::from([Connector::Cybersource]),
},
),
])),
),
(
enums::PaymentMethod::Card,
SupportedPaymentMethodTypesForMandate(HashMap::from([
(
enums::PaymentMethodType::Credit,
SupportedConnectorsForMandate {
connector_list: HashSet::from([
Connector::Aci,
Connector::Adyen,
Connector::Authorizedotnet,
Connector::Globalpay,
Connector::Worldpay,
Connector::Fiuu,
Connector::Multisafepay,
Connector::Nexinets,
Connector::Noon,
Connector::Novalnet,
Connector::Payme,
Connector::Stripe,
Connector::Bankofamerica,
Connector::Cybersource,
Connector::Wellsfargo,
]),
},
),
(
enums::PaymentMethodType::Debit,
SupportedConnectorsForMandate {
connector_list: HashSet::from([
Connector::Aci,
Connector::Adyen,
Connector::Authorizedotnet,
Connector::Globalpay,
Connector::Worldpay,
Connector::Fiuu,
Connector::Multisafepay,
Connector::Nexinets,
Connector::Noon,
Connector::Novalnet,
Connector::Payme,
Connector::Stripe,
]),
},
),
])),
),
])),
update_mandate_supported: SupportedPaymentMethodsForMandate(HashMap::default()),
}
}
}
#[derive(Clone, serde::Serialize)]
#[cfg_attr(feature = "v2", allow(dead_code))] // multiple variants are never constructed for v2
enum RequiredField {
CardNumber,
CardExpMonth,
CardExpYear,
CardCvc,
CardNetwork,
BillingUserFirstName,
BillingUserLastName,
/// display name and field type for billing first name
BillingFirstName(&'static str, FieldType),
/// display name and field type for billing last name
BillingLastName(&'static str, FieldType),
BillingEmail,
Email,
BillingPhone,
BillingPhoneCountryCode,
BillingAddressLine1,
BillingAddressLine2,
BillingAddressCity,
BillingAddressState,
BillingAddressZip,
BillingCountries(Vec<&'static str>),
BillingAddressCountries(Vec<&'static str>),
ShippingFirstName,
ShippingLastName,
ShippingAddressCity,
ShippingAddressState,
ShippingAddressZip,
ShippingCountries(Vec<&'static str>),
ShippingAddressCountries(Vec<&'static str>),
ShippingAddressLine1,
ShippingAddressLine2,
ShippingPhone,
ShippingPhoneCountryCode,
ShippingEmail,
OpenBankingUkIssuer,
OpenBankingCzechRepublicIssuer,
OpenBankingPolandIssuer,
OpenBankingSlovakiaIssuer,
OpenBankingFpxIssuer,
OpenBankingThailandIssuer,
BanContactCardNumber,
BanContactCardExpMonth,
BanContactCardExpYear,
IdealBankName,
EpsBankName,
EpsBankOptions(HashSet<enums::BankNames>),
BlikCode,
MifinityDateOfBirth,
MifinityLanguagePreference(Vec<&'static str>),
CryptoNetwork,
CyptoPayCurrency(Vec<&'static str>),
BoletoSocialSecurityNumber,
UpiCollectVpaId,
AchBankDebitAccountNumber,
AchBankDebitRoutingNumber,
AchBankDebitBankType(Vec<enums::BankType>),
AchBankDebitBankAccountHolderName,
SepaBankDebitIban,
BacsBankDebitAccountNumber,
BacsBankDebitSortCode,
BecsBankDebitAccountNumber,
BecsBankDebitBsbNumber,
BecsBankDebitSortCode,
PixKey,
PixCnpj,
PixCpf,
PixSourceBankAccountId,
GiftCardNumber,
GiftCardCvc,
DcbMsisdn,
DcbClientUid,
OrderDetailsProductName,
Description,
}
impl RequiredField {
fn to_tuple(&self) -> (String, RequiredFieldInfo) {
match self {
Self::CardNumber => (
"payment_method_data.card.card_number".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.card.card_number".to_string(),
display_name: "card_number".to_string(),
field_type: FieldType::UserCardNumber,
value: None,
},
),
Self::CardExpMonth => (
"payment_method_data.card.card_exp_month".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.card.card_exp_month".to_string(),
display_name: "card_exp_month".to_string(),
field_type: FieldType::UserCardExpiryMonth,
value: None,
},
),
Self::CardExpYear => (
"payment_method_data.card.card_exp_year".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.card.card_exp_year".to_string(),
display_name: "card_exp_year".to_string(),
field_type: FieldType::UserCardExpiryYear,
value: None,
},
),
Self::CardCvc => (
"payment_method_data.card.card_cvc".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.card.card_cvc".to_string(),
display_name: "card_cvc".to_string(),
field_type: FieldType::UserCardCvc,
value: None,
},
),
Self::CardNetwork => (
"payment_method_data.card.card_network".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.card.card_network".to_string(),
display_name: "card_network".to_string(),
field_type: FieldType::UserCardNetwork,
value: None,
},
),
Self::BillingUserFirstName => (
"billing.address.first_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.first_name".to_string(),
display_name: "card_holder_name".to_string(),
field_type: FieldType::UserFullName,
value: None,
},
),
Self::BillingUserLastName => (
"billing.address.last_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.last_name".to_string(),
display_name: "card_holder_name".to_string(),
field_type: FieldType::UserFullName,
value: None,
},
),
Self::BillingFirstName(display_name, field_type) => (
"billing.address.first_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.first_name".to_string(),
display_name: display_name.to_string(),
field_type: field_type.clone(),
value: None,
},
),
Self::BillingLastName(display_name, field_type) => (
"billing.address.last_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.last_name".to_string(),
display_name: display_name.to_string(),
field_type: field_type.clone(),
value: None,
},
),
Self::Email => (
"email".to_string(),
RequiredFieldInfo {
required_field: "email".to_string(),
display_name: "email".to_string(),
field_type: FieldType::UserEmailAddress,
value: None,
},
),
Self::BillingEmail => (
"billing.email".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.email".to_string(),
display_name: "email".to_string(),
field_type: FieldType::UserEmailAddress,
value: None,
},
),
Self::BillingPhone => (
"billing.phone.number".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.phone.number".to_string(),
display_name: "phone".to_string(),
field_type: FieldType::UserPhoneNumber,
value: None,
},
),
Self::BillingPhoneCountryCode => (
"billing.phone.country_code".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.phone.country_code".to_string(),
display_name: "dialing_code".to_string(),
field_type: FieldType::UserPhoneNumberCountryCode,
value: None,
},
),
Self::BillingAddressLine1 => (
"billing.address.line1".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.line1".to_string(),
display_name: "line1".to_string(),
field_type: FieldType::UserAddressLine1,
value: None,
},
),
Self::BillingAddressLine2 => (
"billing.address.line2".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.line2".to_string(),
display_name: "line2".to_string(),
field_type: FieldType::UserAddressLine2,
value: None,
},
),
Self::BillingAddressCity => (
"billing.address.city".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.city".to_string(),
display_name: "city".to_string(),
field_type: FieldType::UserAddressCity,
value: None,
},
),
Self::BillingAddressState => (
"billing.address.state".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.state".to_string(),
display_name: "state".to_string(),
field_type: FieldType::UserAddressState,
value: None,
},
),
Self::BillingAddressZip => (
"billing.address.zip".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.zip".to_string(),
display_name: "zip".to_string(),
field_type: FieldType::UserAddressPincode,
value: None,
},
),
Self::BillingCountries(countries) => (
"billing.address.country".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.country".to_string(),
display_name: "country".to_string(),
field_type: FieldType::UserCountry {
options: countries.iter().map(|c| c.to_string()).collect(),
},
value: None,
},
),
Self::BillingAddressCountries(countries) => (
"billing.address.country".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.country".to_string(),
display_name: "country".to_string(),
field_type: FieldType::UserAddressCountry {
options: countries.iter().map(|c| c.to_string()).collect(),
},
value: None,
},
),
Self::ShippingFirstName => (
"shipping.address.first_name".to_string(),
RequiredFieldInfo {
required_field: "shipping.address.first_name".to_string(),
display_name: "shipping_first_name".to_string(),
field_type: FieldType::UserShippingName,
value: None,
},
),
Self::ShippingLastName => (
"shipping.address.last_name".to_string(),
RequiredFieldInfo {
required_field: "shipping.address.last_name".to_string(),
display_name: "shipping_last_name".to_string(),
field_type: FieldType::UserShippingName,
value: None,
},
),
Self::ShippingAddressCity => (
"shipping.address.city".to_string(),
RequiredFieldInfo {
required_field: "shipping.address.city".to_string(),
display_name: "city".to_string(),
field_type: FieldType::UserShippingAddressCity,
value: None,
},
),
Self::ShippingAddressState => (
"shipping.address.state".to_string(),
RequiredFieldInfo {
required_field: "shipping.address.state".to_string(),
display_name: "state".to_string(),
field_type: FieldType::UserShippingAddressState,
value: None,
},
),
Self::ShippingAddressZip => (
"shipping.address.zip".to_string(),
RequiredFieldInfo {
required_field: "shipping.address.zip".to_string(),
display_name: "zip".to_string(),
field_type: FieldType::UserShippingAddressPincode,
value: None,
},
),
Self::ShippingCountries(countries) => (
"shipping.address.country".to_string(),
RequiredFieldInfo {
required_field: "shipping.address.country".to_string(),
display_name: "country".to_string(),
field_type: FieldType::UserCountry {
options: countries.iter().map(|c| c.to_string()).collect(),
},
value: None,
},
),
Self::ShippingAddressCountries(countries) => (
"shipping.address.country".to_string(),
RequiredFieldInfo {
required_field: "shipping.address.country".to_string(),
display_name: "country".to_string(),
field_type: FieldType::UserShippingAddressCountry {
options: countries.iter().map(|c| c.to_string()).collect(),
},
value: None,
},
),
Self::ShippingAddressLine1 => (
"shipping.address.line1".to_string(),
RequiredFieldInfo {
required_field: "shipping.address.line1".to_string(),
display_name: "line1".to_string(),
field_type: FieldType::UserShippingAddressLine1,
value: None,
},
),
Self::ShippingAddressLine2 => (
"shipping.address.line2".to_string(),
RequiredFieldInfo {
required_field: "shipping.address.line2".to_string(),
display_name: "line2".to_string(),
field_type: FieldType::UserShippingAddressLine2,
value: None,
},
),
Self::ShippingPhone => (
"shipping.phone.number".to_string(),
RequiredFieldInfo {
required_field: "shipping.phone.number".to_string(),
display_name: "phone_number".to_string(),
field_type: FieldType::UserPhoneNumber,
value: None,
},
),
Self::ShippingPhoneCountryCode => (
"shipping.phone.country_code".to_string(),
RequiredFieldInfo {
required_field: "shipping.phone.country_code".to_string(),
display_name: "dialing_code".to_string(),
field_type: FieldType::UserPhoneNumberCountryCode,
value: None,
},
),
Self::ShippingEmail => (
"shipping.email".to_string(),
RequiredFieldInfo {
required_field: "shipping.email".to_string(),
display_name: "email".to_string(),
field_type: FieldType::UserEmailAddress,
value: None,
},
),
Self::OpenBankingUkIssuer => (
"payment_method_data.bank_redirect.open_banking_uk.issuer".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_redirect.open_banking_uk.issuer"
.to_string(),
display_name: "issuer".to_string(),
field_type: FieldType::UserBank,
value: None,
},
),
Self::OpenBankingCzechRepublicIssuer => (
"payment_method_data.bank_redirect.open_banking_czech_republic.issuer".to_string(),
RequiredFieldInfo {
required_field:
"payment_method_data.bank_redirect.open_banking_czech_republic.issuer"
.to_string(),
display_name: "issuer".to_string(),
field_type: FieldType::UserBank,
value: None,
},
),
Self::OpenBankingPolandIssuer => (
"payment_method_data.bank_redirect.online_banking_poland.issuer".to_string(),
RequiredFieldInfo {
required_field:
"payment_method_data.bank_redirect.online_banking_poland.issuer".to_string(),
display_name: "issuer".to_string(),
field_type: FieldType::UserBank,
value: None,
},
),
Self::OpenBankingSlovakiaIssuer => (
"payment_method_data.bank_redirect.open_banking_slovakia.issuer".to_string(),
RequiredFieldInfo {
required_field:
"payment_method_data.bank_redirect.open_banking_slovakia.issuer".to_string(),
display_name: "issuer".to_string(),
field_type: FieldType::UserBank,
value: None,
},
),
Self::OpenBankingFpxIssuer => (
"payment_method_data.bank_redirect.open_banking_fpx.issuer".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_redirect.open_banking_fpx.issuer"
.to_string(),
display_name: "issuer".to_string(),
field_type: FieldType::UserBank,
value: None,
},
),
Self::OpenBankingThailandIssuer => (
"payment_method_data.bank_redirect.open_banking_thailand.issuer".to_string(),
RequiredFieldInfo {
required_field:
"payment_method_data.bank_redirect.open_banking_thailand.issuer".to_string(),
display_name: "issuer".to_string(),
field_type: FieldType::UserBank,
value: None,
},
),
Self::BanContactCardNumber => (
"payment_method_data.bank_redirect.bancontact_card.card_number".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_redirect.bancontact_card.card_number"
.to_string(),
display_name: "card_number".to_string(),
field_type: FieldType::UserCardNumber,
value: None,
},
),
Self::BanContactCardExpMonth => (
"payment_method_data.bank_redirect.bancontact_card.card_exp_month".to_string(),
RequiredFieldInfo {
required_field:
"payment_method_data.bank_redirect.bancontact_card.card_exp_month"
.to_string(),
display_name: "card_exp_month".to_string(),
field_type: FieldType::UserCardExpiryMonth,
value: None,
},
),
Self::BanContactCardExpYear => (
"payment_method_data.bank_redirect.bancontact_card.card_exp_year".to_string(),
RequiredFieldInfo {
required_field:
"payment_method_data.bank_redirect.bancontact_card.card_exp_year"
.to_string(),
display_name: "card_exp_year".to_string(),
field_type: FieldType::UserCardExpiryYear,
value: None,
},
),
Self::IdealBankName => (
"payment_method_data.bank_redirect.ideal.bank_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_redirect.ideal.bank_name".to_string(),
display_name: "bank_name".to_string(),
field_type: FieldType::UserBank,
value: None,
},
),
Self::EpsBankName => (
"payment_method_data.bank_redirect.eps.bank_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_redirect.eps.bank_name".to_string(),
display_name: "bank_name".to_string(),
field_type: FieldType::UserBank,
value: None,
},
),
Self::EpsBankOptions(bank) => (
"payment_method_data.bank_redirect.eps.bank_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_redirect.eps.bank_name".to_string(),
display_name: "bank_name".to_string(),
field_type: FieldType::UserBankOptions {
options: bank.iter().map(|bank| bank.to_string()).collect(),
},
value: None,
},
),
Self::BlikCode => (
"payment_method_data.bank_redirect.blik.blik_code".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_redirect.blik.blik_code".to_string(),
display_name: "blik_code".to_string(),
field_type: FieldType::UserBlikCode,
value: None,
},
),
Self::MifinityDateOfBirth => (
"payment_method_data.wallet.mifinity.date_of_birth".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.wallet.mifinity.date_of_birth".to_string(),
display_name: "date_of_birth".to_string(),
field_type: FieldType::UserDateOfBirth,
value: None,
},
),
Self::MifinityLanguagePreference(languages) => (
"payment_method_data.wallet.mifinity.language_preference".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.wallet.mifinity.language_preference"
.to_string(),
display_name: "language_preference".to_string(),
field_type: FieldType::LanguagePreference {
options: languages.iter().map(|l| l.to_string()).collect(),
},
value: None,
},
),
Self::CryptoNetwork => (
"payment_method_data.crypto.network".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.crypto.network".to_string(),
display_name: "network".to_string(),
field_type: FieldType::UserCryptoCurrencyNetwork,
value: None,
},
),
Self::CyptoPayCurrency(currencies) => (
"payment_method_data.crypto.pay_currency".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.crypto.pay_currency".to_string(),
display_name: "currency".to_string(),
field_type: FieldType::UserCurrency {
options: currencies.iter().map(|c| c.to_string()).collect(),
},
value: None,
},
),
Self::BoletoSocialSecurityNumber => (
"payment_method_data.voucher.boleto.social_security_number".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.voucher.boleto.social_security_number"
.to_string(),
display_name: "social_security_number".to_string(),
field_type: FieldType::UserSocialSecurityNumber,
value: None,
},
),
Self::UpiCollectVpaId => (
"payment_method_data.upi.upi_collect.vpa_id".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.upi.upi_collect.vpa_id".to_string(),
display_name: "vpa_id".to_string(),
field_type: FieldType::UserVpaId,
value: None,
},
),
Self::AchBankDebitAccountNumber => (
"payment_method_data.bank_debit.ach_bank_debit.account_number".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_debit.ach_bank_debit.account_number"
.to_string(),
display_name: "bank_account_number".to_string(),
field_type: FieldType::UserBankAccountNumber,
value: None,
},
),
Self::AchBankDebitRoutingNumber => (
"payment_method_data.bank_debit.ach_bank_debit.routing_number".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_debit.ach_bank_debit.routing_number"
.to_string(),
display_name: "bank_routing_number".to_string(),
field_type: FieldType::UserBankRoutingNumber,
value: None,
},
),
Self::AchBankDebitBankType(bank_type) => (
"payment_method_data.bank_debit.ach_bank_debit.bank_type".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_debit.ach_bank_debit.bank_type"
.to_string(),
display_name: "bank_type".to_string(),
field_type: FieldType::UserBankType {
options: bank_type.iter().map(|bt| bt.to_string()).collect(),
},
value: None,
},
),
Self::AchBankDebitBankAccountHolderName => (
"payment_method_data.bank_debit.ach_bank_debit.bank_account_holder_name"
.to_string(),
RequiredFieldInfo {
required_field:
"payment_method_data.bank_debit.ach_bank_debit.bank_account_holder_name"
.to_string(),
display_name: "bank_account_holder_name".to_string(),
field_type: FieldType::UserBankAccountHolderName,
value: None,
},
),
Self::SepaBankDebitIban => (
"payment_method_data.bank_debit.sepa_bank_debit.iban".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_debit.sepa_bank_debit.iban"
.to_string(),
display_name: "iban".to_string(),
field_type: FieldType::UserIban,
value: None,
},
),
Self::BacsBankDebitAccountNumber => (
"payment_method_data.bank_debit.bacs_bank_debit.account_number".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_debit.bacs_bank_debit.account_number"
.to_string(),
display_name: "bank_account_number".to_string(),
field_type: FieldType::UserBankAccountNumber,
value: None,
},
),
Self::BacsBankDebitSortCode => (
"payment_method_data.bank_debit.bacs_bank_debit.sort_code".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_debit.bacs_bank_debit.sort_code"
.to_string(),
display_name: "bank_sort_code".to_string(),
field_type: FieldType::UserBankSortCode,
value: None,
},
),
Self::BecsBankDebitAccountNumber => (
"payment_method_data.bank_debit.becs_bank_debit.account_number".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_debit.becs_bank_debit.account_number"
.to_string(),
display_name: "bank_account_number".to_string(),
field_type: FieldType::UserBankAccountNumber,
value: None,
},
),
Self::BecsBankDebitBsbNumber => (
"payment_method_data.bank_debit.becs_bank_debit.bsb_number".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_debit.becs_bank_debit.bsb_number"
.to_string(),
display_name: "bsb_number".to_string(),
field_type: FieldType::UserBsbNumber,
value: None,
},
),
Self::BecsBankDebitSortCode => (
"payment_method_data.bank_debit.becs_bank_debit.sort_code".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_debit.becs_bank_debit.sort_code"
.to_string(),
display_name: "bank_sort_code".to_string(),
field_type: FieldType::UserBankSortCode,
value: None,
},
),
Self::PixKey => (
"payment_method_data.bank_transfer.pix.pix_key".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_transfer.pix.pix_key".to_string(),
display_name: "pix_key".to_string(),
field_type: FieldType::UserPixKey,
value: None,
},
),
Self::PixCnpj => (
"payment_method_data.bank_transfer.pix.cnpj".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_transfer.pix.cnpj".to_string(),
display_name: "cnpj".to_string(),
field_type: FieldType::UserCnpj,
value: None,
},
),
Self::PixCpf => (
"payment_method_data.bank_transfer.pix.cpf".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_transfer.pix.cpf".to_string(),
display_name: "cpf".to_string(),
field_type: FieldType::UserCpf,
value: None,
},
),
Self::PixSourceBankAccountId => (
"payment_method_data.bank_transfer.pix.source_bank_account_id".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.bank_transfer.pix.source_bank_account_id"
.to_string(),
display_name: "source_bank_account_id".to_string(),
field_type: FieldType::UserSourceBankAccountId,
value: None,
},
),
Self::GiftCardNumber => (
"payment_method_data.gift_card.number".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.gift_card.givex.number".to_string(),
display_name: "gift_card_number".to_string(),
field_type: FieldType::UserCardNumber,
value: None,
},
),
Self::GiftCardCvc => (
"payment_method_data.gift_card.cvc".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.gift_card.givex.cvc".to_string(),
display_name: "gift_card_cvc".to_string(),
field_type: FieldType::UserCardCvc,
value: None,
},
),
Self::DcbMsisdn => (
"payment_method_data.mobile_payment.direct_carrier_billing.msisdn".to_string(),
RequiredFieldInfo {
required_field:
"payment_method_data.mobile_payment.direct_carrier_billing.msisdn"
.to_string(),
display_name: "mobile_number".to_string(),
field_type: FieldType::UserMsisdn,
value: None,
},
),
Self::DcbClientUid => (
"payment_method_data.mobile_payment.direct_carrier_billing.client_uid".to_string(),
RequiredFieldInfo {
required_field:
"payment_method_data.mobile_payment.direct_carrier_billing.client_uid"
.to_string(),
display_name: "client_identifier".to_string(),
field_type: FieldType::UserClientIdentifier,
value: None,
},
),
Self::OrderDetailsProductName => (
"order_details.0.product_name".to_string(),
RequiredFieldInfo {
required_field: "order_details.0.product_name".to_string(),
display_name: "product_name".to_string(),
field_type: FieldType::OrderDetailsProductName,
value: None,
},
),
Self::Description => (
"description".to_string(),
RequiredFieldInfo {
required_field: "description".to_string(),
display_name: "description".to_string(),
field_type: FieldType::Text,
value: None,
},
),
}
}
}
// Define helper functions for common field groups
#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn card_basic() -> Vec<RequiredField> {
vec![
RequiredField::CardNumber,
RequiredField::CardExpMonth,
RequiredField::CardExpYear,
RequiredField::CardCvc,
]
}
#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn full_name() -> Vec<RequiredField> {
vec![
RequiredField::BillingUserFirstName,
RequiredField::BillingUserLastName,
]
}
#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn billing_name() -> Vec<RequiredField> {
vec![
RequiredField::BillingFirstName("billing_first_name", FieldType::UserBillingName),
RequiredField::BillingLastName("billing_last_name", FieldType::UserBillingName),
]
}
#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn billing_email_billing_name() -> Vec<RequiredField> {
vec![
RequiredField::BillingEmail,
RequiredField::BillingFirstName("billing_first_name", FieldType::UserBillingName),
RequiredField::BillingLastName("billing_last_name", FieldType::UserBillingName),
]
}
#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn billing_email_billing_name_phone() -> Vec<RequiredField> {
vec![
RequiredField::BillingFirstName("billing_first_name", FieldType::UserBillingName),
RequiredField::BillingLastName("billing_last_name", FieldType::UserBillingName),
RequiredField::BillingEmail,
RequiredField::BillingPhone,
RequiredField::BillingPhoneCountryCode,
]
}
#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn email() -> Vec<RequiredField> {
[RequiredField::Email].to_vec()
}
#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn billing_email() -> Vec<RequiredField> {
[RequiredField::BillingEmail].to_vec()
}
#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn card_with_name() -> Vec<RequiredField> {
[card_basic(), full_name()].concat()
}
#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn billing_email_name() -> Vec<RequiredField> {
vec![
RequiredField::BillingEmail,
RequiredField::BillingUserFirstName,
RequiredField::BillingUserLastName,
]
}
#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn billing_address() -> Vec<RequiredField> {
vec![
RequiredField::BillingAddressCity,
RequiredField::BillingAddressState,
RequiredField::BillingAddressZip,
RequiredField::BillingAddressCountries(vec!["ALL"]),
RequiredField::BillingAddressLine1,
]
}
/// Define the mandate, non-mandate, and common required fields for a connector
/// Eg: fields(vec![RequiredField::CardNumber], vec![RequiredField::BillingEmail], vec![RequiredField::BillingAddressCity])
#[cfg(feature = "v1")]
fn fields(
mandate: Vec<RequiredField>,
non_mandate: Vec<RequiredField>,
common: Vec<RequiredField>,
) -> RequiredFieldFinal {
let mandate_fields: HashMap<_, _> = mandate.iter().map(|f| f.to_tuple()).collect();
let non_mandate_fields: HashMap<_, _> = non_mandate.iter().map(|f| f.to_tuple()).collect();
let common_fields: HashMap<_, _> = common.iter().map(|f| f.to_tuple()).collect();
RequiredFieldFinal {
mandate: mandate_fields,
non_mandate: non_mandate_fields,
common: common_fields,
}
}
#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn connectors(connectors: Vec<(Connector, RequiredFieldFinal)>) -> ConnectorFields {
ConnectorFields {
fields: connectors.into_iter().collect(),
}
}
pub fn get_billing_required_fields() -> HashMap<String, RequiredFieldInfo> {
HashMap::from([
RequiredField::BillingFirstName("billing_first_name", FieldType::UserBillingName)
.to_tuple(),
RequiredField::BillingLastName("billing_last_name", FieldType::UserBillingName).to_tuple(),
RequiredField::BillingAddressCity.to_tuple(),
RequiredField::BillingAddressState.to_tuple(),
RequiredField::BillingAddressZip.to_tuple(),
RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(),
RequiredField::BillingAddressLine1.to_tuple(),
RequiredField::BillingAddressLine2.to_tuple(),
RequiredField::BillingPhone.to_tuple(),
RequiredField::BillingPhoneCountryCode.to_tuple(),
RequiredField::BillingEmail.to_tuple(),
])
}
pub fn get_shipping_required_fields() -> HashMap<String, RequiredFieldInfo> {
HashMap::from([
RequiredField::ShippingFirstName.to_tuple(),
RequiredField::ShippingLastName.to_tuple(),
RequiredField::ShippingAddressCity.to_tuple(),
RequiredField::ShippingAddressState.to_tuple(),
RequiredField::ShippingAddressZip.to_tuple(),
RequiredField::ShippingAddressCountries(vec!["ALL"]).to_tuple(),
RequiredField::ShippingAddressLine1.to_tuple(),
RequiredField::ShippingPhone.to_tuple(),
|
crates/payment_methods/src/configs/payment_connector_required_fields.rs#chunk0
|
payment_methods
|
chunk
| null | null | null | 8,189
| null | null | null | null | null | null | null |
// Function: perform_session_token_routing
// File: crates/router/src/core/payments.rs
// Module: router
pub fn perform_session_token_routing<F, D>(
state: SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
payment_data: &mut D,
connectors: api::SessionConnectorDatas,
) -> RouterResult<api::SessionConnectorDatas>
where
F: Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F>,
|
crates/router/src/core/payments.rs
|
router
|
function_signature
| null | null | null | 110
|
perform_session_token_routing
| null | null | null | null | null | null |
// Struct: NestedErrorStack
// File: crates/router/src/core/errors.rs
// Module: router
// Implementations: 0
pub struct NestedErrorStack<'a>
|
crates/router/src/core/errors.rs
|
router
|
struct_definition
|
NestedErrorStack
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorValidation for for Facilitapay
// File: crates/hyperswitch_connectors/src/connectors/facilitapay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl ConnectorValidation for for Facilitapay
|
crates/hyperswitch_connectors/src/connectors/facilitapay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Facilitapay
|
ConnectorValidation for
| 0
| 0
| null | null |
// Struct: CurrentFlow
// File: crates/router/src/types/domain/user/decision_manager.rs
// Module: router
// Implementations: 1
pub struct CurrentFlow
|
crates/router/src/types/domain/user/decision_manager.rs
|
router
|
struct_definition
|
CurrentFlow
| 1
|
[] | 36
| null | null | null | null | null | null | null |
// Struct: EncryptedJsonType
// File: crates/hyperswitch_domain_models/src/type_encryption.rs
// Module: hyperswitch_domain_models
// Implementations: 3
// Traits: std::ops::Deref
pub struct EncryptedJsonType<T>
|
crates/hyperswitch_domain_models/src/type_encryption.rs
|
hyperswitch_domain_models
|
struct_definition
|
EncryptedJsonType
| 3
|
[
"std::ops::Deref"
] | 57
| null | null | null | null | null | null | null |
// Implementation: impl masking::SerializableSecret for for OrderDetailsWithAmount
// File: crates/diesel_models/src/types.rs
// Module: diesel_models
// Methods: 0 total (0 public)
impl masking::SerializableSecret for for OrderDetailsWithAmount
|
crates/diesel_models/src/types.rs
|
diesel_models
|
impl_block
| null | null | null | 53
| null |
OrderDetailsWithAmount
|
masking::SerializableSecret for
| 0
| 0
| null | null |
// Implementation: impl SessionState
// File: crates/router/src/routes/app.rs
// Module: router
// Methods: 4 total (4 public)
impl SessionState
|
crates/router/src/routes/app.rs
|
router
|
impl_block
| null | null | null | 35
| null |
SessionState
| null | 4
| 4
| null | null |
// Function: update_conditional_config_id
// File: crates/api_models/src/routing.rs
// Module: api_models
pub fn update_conditional_config_id(&mut self, ids: String)
|
crates/api_models/src/routing.rs
|
api_models
|
function_signature
| null | null | null | 41
|
update_conditional_config_id
| null | null | null | null | null | null |
// Implementation: impl OrganizationBridge for for Organization
// File: crates/diesel_models/src/organization.rs
// Module: diesel_models
// Methods: 3 total (0 public)
impl OrganizationBridge for for Organization
|
crates/diesel_models/src/organization.rs
|
diesel_models
|
impl_block
| null | null | null | 44
| null |
Organization
|
OrganizationBridge for
| 3
| 0
| null | null |
// Struct: NetceteraAuthenticationSuccessResponse
// File: crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NetceteraAuthenticationSuccessResponse
|
crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
NetceteraAuthenticationSuccessResponse
| 0
|
[] | 57
| null | null | null | null | null | null | null |
// Function: create
// File: crates/analytics/src/opensearch.rs
// Module: analytics
pub fn create(conf: &OpenSearchConfig) -> CustomResult<Self, OpenSearchError>
|
crates/analytics/src/opensearch.rs
|
analytics
|
function_signature
| null | null | null | 41
|
create
| null | null | null | null | null | null |
// Implementation: impl api::PaymentsPreProcessing for for Trustpay
// File: crates/hyperswitch_connectors/src/connectors/trustpay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentsPreProcessing for for Trustpay
|
crates/hyperswitch_connectors/src/connectors/trustpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Trustpay
|
api::PaymentsPreProcessing for
| 0
| 0
| null | null |
// Function: get_profile_outgoing_webhook_events
// File: crates/router/src/analytics.rs
// Module: router
pub fn get_profile_outgoing_webhook_events(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Query<
api_models::analytics::outgoing_webhook_event::OutgoingWebhookLogsRequest,
>,
) -> impl Responder
|
crates/router/src/analytics.rs
|
router
|
function_signature
| null | null | null | 90
|
get_profile_outgoing_webhook_events
| null | null | null | null | null | null |
// Struct: NoonCard
// File: crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NoonCard
|
crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
NoonCard
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Function: apply_changeset
// File: crates/diesel_models/src/business_profile.rs
// Module: diesel_models
pub fn apply_changeset(self, source: Profile) -> Profile
|
crates/diesel_models/src/business_profile.rs
|
diesel_models
|
function_signature
| null | null | null | 38
|
apply_changeset
| null | null | null | null | null | null |
// Function: customers_list
// File: crates/router/src/routes/customers.rs
// Module: router
pub fn customers_list(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<customers::CustomerListRequest>,
) -> HttpResponse
|
crates/router/src/routes/customers.rs
|
router
|
function_signature
| null | null | null | 57
|
customers_list
| null | null | null | null | null | null |
// Function: insert
// File: crates/diesel_models/src/query/user_role.rs
// Module: diesel_models
pub fn insert(self, conn: &PgPooledConn) -> StorageResult<UserRole>
|
crates/diesel_models/src/query/user_role.rs
|
diesel_models
|
function_signature
| null | null | null | 43
|
insert
| null | null | null | null | null | null |
// Struct: PaymentOptions
// File: crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaymentOptions
|
crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaymentOptions
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Module Structure
// File: crates/router/src/core/user.rs
// Module: router
// Public submodules:
pub mod dashboard_metadata;
pub mod sample_data;
pub mod theme;
|
crates/router/src/core/user.rs
|
router
|
module_structure
| null | null | null | 38
| null | null | null | null | null | 3
| 0
|
// Implementation: impl api::PaymentCapture for for Inespay
// File: crates/hyperswitch_connectors/src/connectors/inespay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentCapture for for Inespay
|
crates/hyperswitch_connectors/src/connectors/inespay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Inespay
|
api::PaymentCapture for
| 0
| 0
| null | null |
// Implementation: impl api::PaymentVoid for for Paysafe
// File: crates/hyperswitch_connectors/src/connectors/paysafe.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Paysafe
|
crates/hyperswitch_connectors/src/connectors/paysafe.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Paysafe
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Function: deep_health_check
// File: crates/drainer/src/health_check.rs
// Module: drainer
pub fn deep_health_check(
conf: web::Data<Settings>,
stores: web::Data<HashMap<String, Arc<Store>>>,
) -> impl actix_web::Responder
|
crates/drainer/src/health_check.rs
|
drainer
|
function_signature
| null | null | null | 62
|
deep_health_check
| null | null | null | null | null | null |
// File: crates/api_models/src/user_role.rs
// Module: api_models
// Public structs: 9
use common_enums::{ParentGroup, PermissionGroup};
use common_utils::pii;
use masking::Secret;
pub mod role;
#[derive(Debug, serde::Serialize)]
pub struct AuthorizationInfoResponse(pub Vec<AuthorizationInfo>);
#[derive(Debug, serde::Serialize)]
#[serde(untagged)]
pub enum AuthorizationInfo {
Group(GroupInfo),
GroupWithTag(ParentInfo),
}
// TODO: To be deprecated
#[derive(Debug, serde::Serialize)]
pub struct GroupInfo {
pub group: PermissionGroup,
pub description: &'static str,
}
#[derive(Debug, serde::Serialize, Clone)]
pub struct ParentInfo {
pub name: ParentGroup,
pub description: &'static str,
pub groups: Vec<PermissionGroup>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UpdateUserRoleRequest {
pub email: pii::Email,
pub role_id: String,
}
#[derive(Debug, serde::Serialize)]
pub enum UserStatus {
Active,
InvitationSent,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct DeleteUserRoleRequest {
pub email: pii::Email,
}
#[derive(Debug, serde::Serialize)]
pub struct ListUsersInEntityResponse {
pub email: pii::Email,
pub roles: Vec<role::MinimalRoleInfo>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ListInvitationForUserResponse {
pub entity_id: String,
pub entity_type: common_enums::EntityType,
pub entity_name: Option<Secret<String>>,
pub role_id: String,
}
pub type AcceptInvitationsV2Request = Vec<Entity>;
pub type AcceptInvitationsPreAuthRequest = Vec<Entity>;
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct Entity {
pub entity_id: String,
pub entity_type: common_enums::EntityType,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ListUsersInEntityRequest {
pub entity_type: Option<common_enums::EntityType>,
}
|
crates/api_models/src/user_role.rs
|
api_models
|
full_file
| null | null | null | 447
| null | null | null | null | null | null | null |
// Implementation: impl api::RefundExecute for for Paytm
// File: crates/hyperswitch_connectors/src/connectors/paytm.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Paytm
|
crates/hyperswitch_connectors/src/connectors/paytm.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Paytm
|
api::RefundExecute for
| 0
| 0
| null | null |
// Implementation: impl api::PaymentVoid for for Checkout
// File: crates/hyperswitch_connectors/src/connectors/checkout.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Checkout
|
crates/hyperswitch_connectors/src/connectors/checkout.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 55
| null |
Checkout
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Implementation: impl OrganizationBridge for for OrganizationNew
// File: crates/diesel_models/src/organization.rs
// Module: diesel_models
// Methods: 3 total (0 public)
impl OrganizationBridge for for OrganizationNew
|
crates/diesel_models/src/organization.rs
|
diesel_models
|
impl_block
| null | null | null | 46
| null |
OrganizationNew
|
OrganizationBridge for
| 3
| 0
| null | null |
// File: crates/router/src/core/routing/helpers.rs
// Module: router
// Public functions: 32
// Public structs: 5
//! Analysis for usage of all helper functions for use case of routing
//!
//! Functions that are used to perform the retrieval of merchant's
//! routing dict, configs, defaults
use std::fmt::Debug;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use std::str::FromStr;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use std::sync::Arc;
#[cfg(feature = "v1")]
use api_models::open_router;
use api_models::routing as routing_types;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use common_utils::ext_traits::ValueExt;
use common_utils::{ext_traits::Encode, id_type, types::keymanager::KeyManagerState};
use diesel_models::configs;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use diesel_models::dynamic_routing_stats::{DynamicRoutingStatsNew, DynamicRoutingStatsUpdate};
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use diesel_models::routing_algorithm;
use error_stack::ResultExt;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use external_services::grpc_client::dynamic_routing::{
contract_routing_client::ContractBasedDynamicRouting,
elimination_based_client::EliminationBasedRouting,
success_rate_client::SuccessBasedDynamicRouting,
};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use hyperswitch_domain_models::api::ApplicationResponse;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use hyperswitch_interfaces::events::routing_api_logs as routing_events;
#[cfg(feature = "v1")]
use router_env::logger;
#[cfg(feature = "v1")]
use router_env::{instrument, tracing};
use rustc_hash::FxHashSet;
use storage_impl::redis::cache;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use storage_impl::redis::cache::Cacheable;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use crate::db::errors::StorageErrorExt;
#[cfg(feature = "v2")]
use crate::types::domain::MerchantConnectorAccount;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use crate::types::transformers::ForeignFrom;
use crate::{
core::errors::{self, RouterResult},
db::StorageInterface,
routes::SessionState,
types::{domain, storage},
utils::StringExt,
};
#[cfg(feature = "v1")]
use crate::{
core::payments::{
routing::utils::{self as routing_utils, DecisionEngineApiHandler},
OperationSessionGetters, OperationSessionSetters,
},
services,
};
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use crate::{
core::{metrics as core_metrics, routing},
routes::app::SessionStateInfo,
types::transformers::ForeignInto,
};
pub const SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM: &str =
"Success rate based dynamic routing algorithm";
pub const ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM: &str =
"Elimination based dynamic routing algorithm";
pub const CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM: &str =
"Contract based dynamic routing algorithm";
pub const DECISION_ENGINE_RULE_CREATE_ENDPOINT: &str = "rule/create";
pub const DECISION_ENGINE_RULE_UPDATE_ENDPOINT: &str = "rule/update";
pub const DECISION_ENGINE_RULE_GET_ENDPOINT: &str = "rule/get";
pub const DECISION_ENGINE_RULE_DELETE_ENDPOINT: &str = "rule/delete";
pub const DECISION_ENGINE_MERCHANT_BASE_ENDPOINT: &str = "merchant-account";
pub const DECISION_ENGINE_MERCHANT_CREATE_ENDPOINT: &str = "merchant-account/create";
/// Provides us with all the configured configs of the Merchant in the ascending time configured
/// manner and chooses the first of them
pub async fn get_merchant_default_config(
db: &dyn StorageInterface,
// Cannot make this as merchant id domain type because, we are passing profile id also here
merchant_id: &str,
transaction_type: &storage::enums::TransactionType,
) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> {
let key = get_default_config_key(merchant_id, transaction_type);
let maybe_config = db.find_config_by_key(&key).await;
match maybe_config {
Ok(config) => config
.config
.parse_struct("Vec<RoutableConnectors>")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant default config has invalid structure"),
Err(e) if e.current_context().is_db_not_found() => {
let new_config_conns = Vec::<routing_types::RoutableConnectorChoice>::new();
let serialized = new_config_conns
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Error while creating and serializing new merchant default config",
)?;
let new_config = configs::ConfigNew {
key,
config: serialized,
};
db.insert_config(new_config)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error inserting new default routing config into DB")?;
Ok(new_config_conns)
}
Err(e) => Err(e)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error fetching default config for merchant"),
}
}
/// Merchant's already created config can be updated and this change will be reflected
/// in DB as well for the particular updated config
pub async fn update_merchant_default_config(
db: &dyn StorageInterface,
merchant_id: &str,
connectors: Vec<routing_types::RoutableConnectorChoice>,
transaction_type: &storage::enums::TransactionType,
) -> RouterResult<()> {
let key = get_default_config_key(merchant_id, transaction_type);
let config_str = connectors
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize merchant default routing config during update")?;
let config_update = configs::ConfigUpdate::Update {
config: Some(config_str),
};
db.update_config_by_key(&key, config_update)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating the default routing config in DB")?;
Ok(())
}
pub async fn update_merchant_routing_dictionary(
db: &dyn StorageInterface,
merchant_id: &str,
dictionary: routing_types::RoutingDictionary,
) -> RouterResult<()> {
let key = get_routing_dictionary_key(merchant_id);
let dictionary_str = dictionary
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize routing dictionary during update")?;
let config_update = configs::ConfigUpdate::Update {
config: Some(dictionary_str),
};
db.update_config_by_key(&key, config_update)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error saving routing dictionary to DB")?;
Ok(())
}
/// This will help make one of all configured algorithms to be in active state for a particular
/// merchant
#[cfg(feature = "v1")]
pub async fn update_merchant_active_algorithm_ref(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
config_key: cache::CacheKind<'_>,
algorithm_id: routing_types::RoutingAlgorithmRef,
) -> RouterResult<()> {
let ref_value = algorithm_id
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed converting routing algorithm ref to json value")?;
let merchant_account_update = storage::MerchantAccountUpdate::Update {
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
locker_id: None,
metadata: None,
routing_algorithm: Some(ref_value),
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
default_profile: None,
payment_link_config: None,
pm_collect_link_config: None,
};
let db = &*state.store;
db.update_specific_fields_in_merchant(
&state.into(),
&key_store.merchant_id,
merchant_account_update,
key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref in merchant account")?;
cache::redact_from_redis_and_publish(db.get_cache_store().as_ref(), [config_key])
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate the config cache")?;
Ok(())
}
#[cfg(feature = "v1")]
pub async fn update_profile_active_algorithm_ref(
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
current_business_profile: domain::Profile,
algorithm_id: routing_types::RoutingAlgorithmRef,
transaction_type: &storage::enums::TransactionType,
) -> RouterResult<()> {
let ref_val = algorithm_id
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert routing ref to value")?;
let merchant_id = current_business_profile.merchant_id.clone();
let profile_id = current_business_profile.get_id().to_owned();
let (routing_algorithm, payout_routing_algorithm, three_ds_decision_rule_algorithm) =
match transaction_type {
storage::enums::TransactionType::Payment => (Some(ref_val), None, None),
#[cfg(feature = "payouts")]
storage::enums::TransactionType::Payout => (None, Some(ref_val), None),
storage::enums::TransactionType::ThreeDsAuthentication => (None, None, Some(ref_val)),
};
let business_profile_update = domain::ProfileUpdate::RoutingAlgorithmUpdate {
routing_algorithm,
payout_routing_algorithm,
three_ds_decision_rule_algorithm,
};
db.update_profile_by_profile_id(
key_manager_state,
merchant_key_store,
current_business_profile,
business_profile_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref in business profile")?;
// Invalidate the routing cache for Payments and Payouts transaction types
if !transaction_type.is_three_ds_authentication() {
let routing_cache_key = cache::CacheKind::Routing(
format!(
"routing_config_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
)
.into(),
);
cache::redact_from_redis_and_publish(db.get_cache_store().as_ref(), [routing_cache_key])
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate routing cache")?;
}
Ok(())
}
#[cfg(feature = "v1")]
pub async fn update_business_profile_active_dynamic_algorithm_ref(
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
current_business_profile: domain::Profile,
dynamic_routing_algorithm_ref: routing_types::DynamicRoutingAlgorithmRef,
) -> RouterResult<()> {
let ref_val = dynamic_routing_algorithm_ref
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert dynamic routing ref to value")?;
let business_profile_update = domain::ProfileUpdate::DynamicRoutingAlgorithmUpdate {
dynamic_routing_algorithm: Some(ref_val),
};
db.update_profile_by_profile_id(
key_manager_state,
merchant_key_store,
current_business_profile,
business_profile_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update dynamic routing algorithm ref in business profile")?;
Ok(())
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct RoutingAlgorithmHelpers<'h> {
pub name_mca_id_set: ConnectNameAndMCAIdForProfile<'h>,
pub name_set: ConnectNameForProfile<'h>,
pub routing_algorithm: &'h routing_types::StaticRoutingAlgorithm,
}
#[cfg(feature = "v1")]
pub enum RoutingDecisionData {
DebitRouting(DebitRoutingDecisionData),
}
#[cfg(feature = "v1")]
pub struct DebitRoutingDecisionData {
pub card_network: common_enums::enums::CardNetwork,
pub debit_routing_result: Option<open_router::DebitRoutingOutput>,
}
#[cfg(feature = "v1")]
impl RoutingDecisionData {
pub fn apply_routing_decision<F, D>(&self, payment_data: &mut D)
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
match self {
Self::DebitRouting(data) => data.apply_debit_routing_decision(payment_data),
}
}
pub fn get_debit_routing_decision_data(
network: common_enums::enums::CardNetwork,
debit_routing_result: Option<open_router::DebitRoutingOutput>,
) -> Self {
Self::DebitRouting(DebitRoutingDecisionData {
card_network: network,
debit_routing_result,
})
}
}
#[cfg(feature = "v1")]
impl DebitRoutingDecisionData {
pub fn apply_debit_routing_decision<F, D>(&self, payment_data: &mut D)
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
payment_data.set_card_network(self.card_network.clone());
self.debit_routing_result
.as_ref()
.map(|data| payment_data.set_co_badged_card_data(data));
}
}
#[derive(Clone, Debug)]
pub struct ConnectNameAndMCAIdForProfile<'a>(
pub FxHashSet<(
&'a common_enums::connector_enums::Connector,
id_type::MerchantConnectorAccountId,
)>,
);
#[derive(Clone, Debug)]
pub struct ConnectNameForProfile<'a>(pub FxHashSet<&'a common_enums::connector_enums::Connector>);
#[cfg(feature = "v2")]
impl RoutingAlgorithmHelpers<'_> {
fn connector_choice(
&self,
choice: &routing_types::RoutableConnectorChoice,
) -> RouterResult<()> {
if let Some(ref mca_id) = choice.merchant_connector_id {
let connector_choice = common_enums::connector_enums::Connector::from(choice.connector);
error_stack::ensure!(
self.name_mca_id_set.0.contains(&(&connector_choice, mca_id.clone())),
errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector with name '{connector_choice}' and merchant connector account id '{mca_id:?}' not found for the given profile",
)
}
);
} else {
let connector_choice = common_enums::connector_enums::Connector::from(choice.connector);
error_stack::ensure!(
self.name_set.0.contains(&connector_choice),
errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector with name '{connector_choice}' not found for the given profile",
)
}
);
};
Ok(())
}
pub fn validate_connectors_in_routing_config(&self) -> RouterResult<()> {
match self.routing_algorithm {
routing_types::StaticRoutingAlgorithm::Single(choice) => {
self.connector_choice(choice)?;
}
routing_types::StaticRoutingAlgorithm::Priority(list) => {
for choice in list {
self.connector_choice(choice)?;
}
}
routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => {
for split in splits {
self.connector_choice(&split.connector)?;
}
}
routing_types::StaticRoutingAlgorithm::Advanced(program) => {
let check_connector_selection =
|selection: &routing_types::ConnectorSelection| -> RouterResult<()> {
match selection {
routing_types::ConnectorSelection::VolumeSplit(splits) => {
for split in splits {
self.connector_choice(&split.connector)?;
}
}
routing_types::ConnectorSelection::Priority(list) => {
for choice in list {
self.connector_choice(choice)?;
}
}
}
Ok(())
};
check_connector_selection(&program.default_selection)?;
for rule in &program.rules {
check_connector_selection(&rule.connector_selection)?;
}
}
routing_types::StaticRoutingAlgorithm::ThreeDsDecisionRule(_) => {
return Err(errors::ApiErrorResponse::InternalServerError).attach_printable(
"Invalid routing algorithm three_ds decision rule received",
)?;
}
}
Ok(())
}
}
#[cfg(feature = "v1")]
pub async fn validate_connectors_in_routing_config(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
routing_algorithm: &routing_types::StaticRoutingAlgorithm,
) -> RouterResult<()> {
let all_mcas = state
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
merchant_id,
true,
key_store,
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_id.get_string_repr().to_owned(),
})?;
let name_mca_id_set = all_mcas
.iter()
.filter(|mca| mca.profile_id == *profile_id)
.map(|mca| (&mca.connector_name, mca.get_id()))
.collect::<FxHashSet<_>>();
let name_set = all_mcas
.iter()
.filter(|mca| mca.profile_id == *profile_id)
.map(|mca| &mca.connector_name)
.collect::<FxHashSet<_>>();
let connector_choice = |choice: &routing_types::RoutableConnectorChoice| {
if let Some(ref mca_id) = choice.merchant_connector_id {
error_stack::ensure!(
name_mca_id_set.contains(&(&choice.connector.to_string(), mca_id.clone())),
errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector with name '{}' and merchant connector account id '{:?}' not found for the given profile",
choice.connector,
mca_id,
)
}
);
} else {
error_stack::ensure!(
name_set.contains(&choice.connector.to_string()),
errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector with name '{}' not found for the given profile",
choice.connector,
)
}
);
}
Ok(())
};
match routing_algorithm {
routing_types::StaticRoutingAlgorithm::Single(choice) => {
connector_choice(choice)?;
}
routing_types::StaticRoutingAlgorithm::Priority(list) => {
for choice in list {
connector_choice(choice)?;
}
}
routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => {
for split in splits {
connector_choice(&split.connector)?;
}
}
routing_types::StaticRoutingAlgorithm::Advanced(program) => {
let check_connector_selection =
|selection: &routing_types::ConnectorSelection| -> RouterResult<()> {
match selection {
routing_types::ConnectorSelection::VolumeSplit(splits) => {
for split in splits {
connector_choice(&split.connector)?;
}
}
routing_types::ConnectorSelection::Priority(list) => {
for choice in list {
connector_choice(choice)?;
}
}
}
Ok(())
};
check_connector_selection(&program.default_selection)?;
for rule in &program.rules {
check_connector_selection(&rule.connector_selection)?;
}
}
routing_types::StaticRoutingAlgorithm::ThreeDsDecisionRule(_) => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid routing algorithm three_ds decision rule received")?
}
}
Ok(())
}
/// Provides the identifier for the specific merchant's routing_dictionary_key
#[inline(always)]
pub fn get_routing_dictionary_key(merchant_id: &str) -> String {
format!("routing_dict_{merchant_id}")
}
/// Provides the identifier for the specific merchant's default_config
#[inline(always)]
pub fn get_default_config_key(
merchant_id: &str,
transaction_type: &storage::enums::TransactionType,
) -> String {
match transaction_type {
storage::enums::TransactionType::Payment => format!("routing_default_{merchant_id}"),
#[cfg(feature = "payouts")]
storage::enums::TransactionType::Payout => format!("routing_default_po_{merchant_id}"),
storage::enums::TransactionType::ThreeDsAuthentication => {
format!("three_ds_authentication_{merchant_id}")
}
}
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[async_trait::async_trait]
pub trait DynamicRoutingCache {
async fn get_cached_dynamic_routing_config_for_profile(
state: &SessionState,
key: &str,
) -> Option<Arc<Self>>;
async fn refresh_dynamic_routing_cache<T, F, Fut>(
state: &SessionState,
key: &str,
func: F,
) -> RouterResult<T>
where
F: FnOnce() -> Fut + Send,
T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send;
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[async_trait::async_trait]
impl DynamicRoutingCache for routing_types::SuccessBasedRoutingConfig {
async fn get_cached_dynamic_routing_config_for_profile(
state: &SessionState,
key: &str,
) -> Option<Arc<Self>> {
cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
.get_val::<Arc<Self>>(cache::CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
})
.await
}
async fn refresh_dynamic_routing_cache<T, F, Fut>(
state: &SessionState,
key: &str,
func: F,
) -> RouterResult<T>
where
F: FnOnce() -> Fut + Send,
T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send,
{
cache::get_or_populate_in_memory(
state.store.get_cache_store().as_ref(),
key,
func,
&cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to populate SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE")
}
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[async_trait::async_trait]
impl DynamicRoutingCache for routing_types::ContractBasedRoutingConfig {
async fn get_cached_dynamic_routing_config_for_profile(
state: &SessionState,
key: &str,
) -> Option<Arc<Self>> {
cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE
.get_val::<Arc<Self>>(cache::CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
})
.await
}
async fn refresh_dynamic_routing_cache<T, F, Fut>(
state: &SessionState,
key: &str,
func: F,
) -> RouterResult<T>
where
F: FnOnce() -> Fut + Send,
T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send,
{
cache::get_or_populate_in_memory(
state.store.get_cache_store().as_ref(),
key,
func,
&cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to populate CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE")
}
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[async_trait::async_trait]
impl DynamicRoutingCache for routing_types::EliminationRoutingConfig {
async fn get_cached_dynamic_routing_config_for_profile(
state: &SessionState,
key: &str,
) -> Option<Arc<Self>> {
cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE
.get_val::<Arc<Self>>(cache::CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
})
.await
}
async fn refresh_dynamic_routing_cache<T, F, Fut>(
state: &SessionState,
key: &str,
func: F,
) -> RouterResult<T>
where
F: FnOnce() -> Fut + Send,
T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send,
{
cache::get_or_populate_in_memory(
state.store.get_cache_store().as_ref(),
key,
func,
&cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to populate ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE")
}
}
/// Cfetch dynamic routing configs
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn fetch_dynamic_routing_configs<T>(
state: &SessionState,
profile_id: &id_type::ProfileId,
routing_id: id_type::RoutingId,
) -> RouterResult<T>
where
T: serde::de::DeserializeOwned
+ Clone
+ DynamicRoutingCache
+ Cacheable
+ serde::Serialize
+ Debug,
{
let key = format!(
"{}_{}",
profile_id.get_string_repr(),
routing_id.get_string_repr()
);
if let Some(config) =
T::get_cached_dynamic_routing_config_for_profile(state, key.as_str()).await
{
Ok(config.as_ref().clone())
} else {
let func = || async {
let routing_algorithm = state
.store
.find_routing_algorithm_by_profile_id_algorithm_id(profile_id, &routing_id)
.await
.change_context(errors::StorageError::ValueNotFound(
"RoutingAlgorithm".to_string(),
))
.attach_printable("unable to retrieve routing_algorithm for profile from db")?;
let dynamic_routing_config = routing_algorithm
.algorithm_data
.parse_value::<T>("dynamic_routing_config")
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("unable to parse dynamic_routing_config")?;
Ok(dynamic_routing_config)
};
let dynamic_routing_config =
T::refresh_dynamic_routing_cache(state, key.as_str(), func).await?;
Ok(dynamic_routing_config)
}
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn update_gateway_score_helper_with_open_router(
state: &SessionState,
payment_attempt: &storage::PaymentAttempt,
profile_id: &id_type::ProfileId,
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
) -> RouterResult<()> {
let is_success_rate_routing_enabled =
dynamic_routing_algo_ref.is_success_rate_routing_enabled();
let is_elimination_enabled = dynamic_routing_algo_ref.is_elimination_enabled();
if is_success_rate_routing_enabled || is_elimination_enabled {
let payment_connector = &payment_attempt.connector.clone().ok_or(
errors::ApiErrorResponse::GenericNotFoundError {
message: "unable to derive payment connector from payment attempt".to_string(),
},
)?;
let routable_connector = routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(payment_connector.as_str())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to infer routable_connector from connector")?,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
};
logger::debug!(
"performing update-gateway-score for gateway with id {} in open_router for profile: {}",
routable_connector,
profile_id.get_string_repr()
);
routing::payments_routing::update_gateway_score_with_open_router(
state,
routable_connector.clone(),
profile_id,
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
payment_attempt.status,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to update gateway score in open_router service")?;
}
Ok(())
}
/// metrics for success based dynamic routing
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn push_metrics_with_update_window_for_success_based_routing(
state: &SessionState,
payment_attempt: &storage::PaymentAttempt,
routable_connectors: Vec<routing_types::RoutableConnectorChoice>,
profile_id: &id_type::ProfileId,
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,
) -> RouterResult<()> {
if let Some(success_based_algo_ref) = dynamic_routing_algo_ref.success_based_algorithm {
if success_based_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "dynamic routing gRPC client not found".to_string(),
})?
.success_rate_client;
let payment_connector = &payment_attempt.connector.clone().ok_or(
errors::ApiErrorResponse::GenericNotFoundError {
message: "unable to derive payment connector from payment attempt".to_string(),
},
)?;
let routable_connector = routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(payment_connector.as_str())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to infer routable_connector from connector")?,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
};
let payment_status_attribute =
get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status);
let success_based_routing_configs = fetch_dynamic_routing_configs::<
routing_types::SuccessBasedRoutingConfig,
>(
state,
profile_id,
success_based_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "success_rate algorithm_id not found".to_string(),
})
.attach_printable(
"success_based_routing_algorithm_id not found in business_profile",
)?,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "success_rate based dynamic routing configs not found".to_string(),
})
.attach_printable("unable to retrieve success_rate based dynamic routing configs")?;
let success_based_routing_config_params = dynamic_routing_config_params_interpolator
.get_string_val(
success_based_routing_configs
.params
.as_ref()
.ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)
.change_context(errors::ApiErrorResponse::InternalServerError)?,
);
let success_based_connectors = client
.calculate_entity_and_global_success_rate(
profile_id.get_string_repr().into(),
success_based_routing_configs.clone(),
success_based_routing_config_params.clone(),
routable_connectors.clone(),
state.get_grpc_headers(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to calculate/fetch success rate from dynamic routing service",
)?;
let first_merchant_success_based_connector = &success_based_connectors
.entity_scores_with_labels
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to fetch the first connector from list of connectors obtained from dynamic routing service",
)?;
let (first_merchant_success_based_connector_label, _) = first_merchant_success_based_connector.label
.split_once(':')
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service",
first_merchant_success_based_connector.label
))?;
let first_global_success_based_connector = &success_based_connectors
.global_scores_with_labels
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to fetch the first global connector from list of connectors obtained from dynamic routing service",
)?;
let outcome = get_dynamic_routing_based_metrics_outcome_for_payment(
payment_status_attribute,
payment_connector.to_string(),
first_merchant_success_based_connector_label.to_string(),
);
core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add(
1,
router_env::metric_attributes!(
(
"tenant",
state.tenant.tenant_id.get_string_repr().to_owned(),
),
(
"merchant_profile_id",
format!(
"{}:{}",
payment_attempt.merchant_id.get_string_repr(),
payment_attempt.profile_id.get_string_repr()
),
),
(
"merchant_specific_success_based_routing_connector",
first_merchant_success_based_connector_label.to_string(),
),
(
"merchant_specific_success_based_routing_connector_score",
first_merchant_success_based_connector.score.to_string(),
),
(
"global_success_based_routing_connector",
first_global_success_based_connector.label.to_string(),
),
(
"global_success_based_routing_connector_score",
first_global_success_based_connector.score.to_string(),
),
("payment_connector", payment_connector.to_string()),
(
"currency",
payment_attempt
.currency
.map_or_else(|| "None".to_string(), |currency| currency.to_string()),
),
(
"payment_method",
payment_attempt.payment_method.map_or_else(
|| "None".to_string(),
|payment_method| payment_method.to_string(),
),
),
(
"payment_method_type",
payment_attempt.payment_method_type.map_or_else(
|| "None".to_string(),
|payment_method_type| payment_method_type.to_string(),
),
),
(
"capture_method",
payment_attempt.capture_method.map_or_else(
|| "None".to_string(),
|capture_method| capture_method.to_string(),
),
),
(
"authentication_type",
payment_attempt.authentication_type.map_or_else(
|| "None".to_string(),
|authentication_type| authentication_type.to_string(),
),
),
("payment_status", payment_attempt.status.to_string()),
("conclusive_classification", outcome.to_string()),
),
);
logger::debug!("successfully pushed success_based_routing metrics");
let duplicate_stats = state
.store
.find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
payment_attempt.attempt_id.clone(),
&payment_attempt.merchant_id.to_owned(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch dynamic_routing_stats entry")?;
if duplicate_stats.is_some() {
let dynamic_routing_update = DynamicRoutingStatsUpdate {
amount: payment_attempt.get_total_amount(),
success_based_routing_connector: first_merchant_success_based_connector_label
.to_string(),
payment_connector: payment_connector.to_string(),
payment_method_type: payment_attempt.payment_method_type,
currency: payment_attempt.currency,
payment_method: payment_attempt.payment_method,
capture_method: payment_attempt.capture_method,
authentication_type: payment_attempt.authentication_type,
payment_status: payment_attempt.status,
conclusive_classification: outcome,
global_success_based_connector: Some(
first_global_success_based_connector.label.to_string(),
),
};
state
.store
.update_dynamic_routing_stats(
payment_attempt.attempt_id.clone(),
&payment_attempt.merchant_id.to_owned(),
dynamic_routing_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update dynamic routing stats to db")?;
} else {
let dynamic_routing_stats = DynamicRoutingStatsNew {
payment_id: payment_attempt.payment_id.to_owned(),
attempt_id: payment_attempt.attempt_id.clone(),
merchant_id: payment_attempt.merchant_id.to_owned(),
profile_id: payment_attempt.profile_id.to_owned(),
amount: payment_attempt.get_total_amount(),
success_based_routing_connector: first_merchant_success_based_connector_label
.to_string(),
payment_connector: payment_connector.to_string(),
payment_method_type: payment_attempt.payment_method_type,
|
crates/router/src/core/routing/helpers.rs#chunk0
|
router
|
chunk
| null | null | null | 8,192
| null | null | null | null | null | null | null |
// Struct: Chat
// File: crates/router/src/routes/app.rs
// Module: router
// Implementations: 1
pub struct Chat
|
crates/router/src/routes/app.rs
|
router
|
struct_definition
|
Chat
| 1
|
[] | 30
| null | null | null | null | null | null | null |
// Struct: PayboxAuthType
// File: crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PayboxAuthType
|
crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PayboxAuthType
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Implementation: impl MerchantConnectorAccountNew
// File: crates/diesel_models/src/query/merchant_connector_account.rs
// Module: diesel_models
// Methods: 1 total (0 public)
impl MerchantConnectorAccountNew
|
crates/diesel_models/src/query/merchant_connector_account.rs
|
diesel_models
|
impl_block
| null | null | null | 45
| null |
MerchantConnectorAccountNew
| null | 1
| 0
| null | null |
// Implementation: impl api::PaymentVoid for for Bamboraapac
// File: crates/hyperswitch_connectors/src/connectors/bamboraapac.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Bamboraapac
|
crates/hyperswitch_connectors/src/connectors/bamboraapac.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 66
| null |
Bamboraapac
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Implementation: impl api::PaymentAuthorize for for Digitalvirgo
// File: crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentAuthorize for for Digitalvirgo
|
crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Digitalvirgo
|
api::PaymentAuthorize for
| 0
| 0
| null | null |
// Implementation: impl ConnectorValidation for for Santander
// File: crates/hyperswitch_connectors/src/connectors/santander.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl ConnectorValidation for for Santander
|
crates/hyperswitch_connectors/src/connectors/santander.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 54
| null |
Santander
|
ConnectorValidation for
| 0
| 0
| null | null |
// Implementation: impl api::ConnectorMandateRevoke for for Cybersource
// File: crates/hyperswitch_connectors/src/connectors/cybersource.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::ConnectorMandateRevoke for for Cybersource
|
crates/hyperswitch_connectors/src/connectors/cybersource.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 69
| null |
Cybersource
|
api::ConnectorMandateRevoke for
| 0
| 0
| null | null |
// Implementation: impl SecretStateContainer
// File: crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs
// Module: hyperswitch_interfaces
// Methods: 2 total (2 public)
impl SecretStateContainer
|
crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs
|
hyperswitch_interfaces
|
impl_block
| null | null | null | 47
| null |
SecretStateContainer
| null | 2
| 2
| null | null |
// Function: build
// File: crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
// Module: router
pub fn build(self) -> api::CardNetworkTokenizeResponse
|
crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
|
router
|
function_signature
| null | null | null | 39
|
build
| 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.