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
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
// Implementation: impl PayoutsInterface for for RouterStore
// File: crates/storage_impl/src/lib.rs
// Module: storage_impl
// Methods: 0 total (0 public)
impl PayoutsInterface for for RouterStore
|
crates/storage_impl/src/lib.rs
|
storage_impl
|
impl_block
| null | null | null | 48
| null |
RouterStore
|
PayoutsInterface for
| 0
| 0
| null | null |
// Struct: PhonepeRefundRequest
// File: crates/hyperswitch_connectors/src/connectors/phonepe/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PhonepeRefundRequest
|
crates/hyperswitch_connectors/src/connectors/phonepe/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PhonepeRefundRequest
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/razorpay.rs
// Module: hyperswitch_connectors
// Public submodules:
pub mod transformers;
|
crates/hyperswitch_connectors/src/connectors/razorpay.rs
|
hyperswitch_connectors
|
module_structure
| null | null | null | 40
| null | null | null | null | null | 1
| 0
|
// Struct: Rapyd
// File: crates/hyperswitch_connectors/src/connectors/rapyd.rs
// Module: hyperswitch_connectors
// Implementations: 18
// Traits: ConnectorCommon, ConnectorValidation, api::ConnectorAccessToken, api::PaymentToken, api::PaymentAuthorize, api::Payment, api::MandateSetup, api::PaymentVoid, api::PaymentSync, api::PaymentCapture, api::PaymentSession, api::Refund, api::RefundExecute, api::RefundSync, IncomingWebhook, ConnectorSpecifications
pub struct Rapyd
|
crates/hyperswitch_connectors/src/connectors/rapyd.rs
|
hyperswitch_connectors
|
struct_definition
|
Rapyd
| 18
|
[
"ConnectorCommon",
"ConnectorValidation",
"api::ConnectorAccessToken",
"api::PaymentToken",
"api::PaymentAuthorize",
"api::Payment",
"api::MandateSetup",
"api::PaymentVoid",
"api::PaymentSync",
"api::PaymentCapture",
"api::PaymentSession",
"api::Refund",
"api::RefundExecute",
"api::RefundSync",
"IncomingWebhook",
"ConnectorSpecifications"
] | 125
| null | null | null | null | null | null | null |
// Struct: ArchipelWalletInformation
// File: crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ArchipelWalletInformation
|
crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ArchipelWalletInformation
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// File: crates/router/src/core/payments/operations/payment_confirm.rs
// Module: router
// Public structs: 1
use std::marker::PhantomData;
#[cfg(feature = "v1")]
use api_models::payment_methods::PaymentMethodsData;
use api_models::{
admin::ExtendedCardInfoConfig,
enums::FrmSuggestion,
payments::{ConnectorMandateReferenceId, ExtendedCardInfo, GetAddressFromPaymentMethodData},
};
use async_trait::async_trait;
use common_utils::ext_traits::{AsyncExt, Encode, StringExt, ValueExt};
use diesel_models::payment_attempt::ConnectorMandateReferenceId as DieselConnectorMandateReferenceId;
use error_stack::{report, ResultExt};
use futures::FutureExt;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdateFields;
use hyperswitch_domain_models::router_request_types::unified_authentication_service;
use masking::{ExposeInterface, PeekInterface};
use router_derive::PaymentOperation;
use router_env::{instrument, logger, tracing};
use tracing_futures::Instrument;
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
#[cfg(feature = "v1")]
use crate::{
consts,
core::payment_methods::cards::create_encrypted_data,
events::audit_events::{AuditEvent, AuditEventType},
};
use crate::{
core::{
authentication,
blocklist::utils as blocklist_utils,
card_testing_guard::utils as card_testing_guard_utils,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payments::{
self, helpers, operations,
operations::payment_confirm::unified_authentication_service::ThreeDsMetaData,
populate_surcharge_details, CustomerDetails, PaymentAddress, PaymentData,
},
three_ds_decision_rule,
unified_authentication_service::{
self as uas_utils,
types::{ClickToPay, UnifiedAuthenticationService},
},
utils as core_utils,
},
routes::{app::ReqState, SessionState},
services,
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
domain::{self},
storage::{self, enums as storage_enums},
transformers::{ForeignFrom, ForeignInto},
},
utils::{self, OptionExt},
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
#[operation(operations = "all", flow = "authorize")]
pub struct PaymentConfirm;
type PaymentConfirmOperation<'b, F> = BoxedOperation<'b, F, api::PaymentsRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
for PaymentConfirm
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsRequest,
merchant_context: &domain::MerchantContext,
auth_flow: services::AuthFlow,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>
{
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let (currency, amount);
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
// Stage 1
let store = &*state.store;
let m_merchant_id = merchant_id.clone();
// Parallel calls - level 0
let mut payment_intent = store
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
&m_merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
// TODO (#7195): Add platform merchant account validation once client_secret auth is solved
if let Some(order_details) = &request.order_details {
helpers::validate_order_details_amount(
order_details.to_owned(),
payment_intent.amount,
false,
)?;
}
helpers::validate_customer_access(&payment_intent, auth_flow, request)?;
if [
Some(common_enums::PaymentSource::Webhook),
Some(common_enums::PaymentSource::ExternalAuthenticator),
]
.contains(&header_payload.payment_confirm_source)
{
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
storage_enums::IntentStatus::Cancelled,
storage_enums::IntentStatus::Succeeded,
storage_enums::IntentStatus::Processing,
storage_enums::IntentStatus::RequiresCapture,
storage_enums::IntentStatus::RequiresMerchantAction,
],
"confirm",
)?;
} else {
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
storage_enums::IntentStatus::Cancelled,
storage_enums::IntentStatus::Succeeded,
storage_enums::IntentStatus::Processing,
storage_enums::IntentStatus::RequiresCapture,
storage_enums::IntentStatus::RequiresMerchantAction,
storage_enums::IntentStatus::RequiresCustomerAction,
],
"confirm",
)?;
}
helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
let customer_details = helpers::get_customer_details_from_request(request);
// Stage 2
let attempt_id = payment_intent.active_attempt.get_id();
let profile_id = payment_intent
.profile_id
.clone()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let store = state.store.clone();
let key_manager_state_clone = key_manager_state.clone();
let key_store_clone = merchant_context.get_merchant_key_store().clone();
let business_profile_fut = tokio::spawn(
async move {
store
.find_business_profile_by_profile_id(
&key_manager_state_clone,
&key_store_clone,
&profile_id,
)
.map(|business_profile_result| {
business_profile_result.to_not_found_response(
errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
},
)
})
.await
}
.in_current_span(),
);
let store = state.store.clone();
let m_payment_id = payment_intent.payment_id.clone();
let m_merchant_id = merchant_id.clone();
let payment_attempt_fut = tokio::spawn(
async move {
store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&m_payment_id,
&m_merchant_id,
attempt_id.as_str(),
storage_scheme,
)
.map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))
.await
}
.in_current_span(),
);
let m_merchant_id = merchant_id.clone();
let m_request_shipping = request.shipping.clone();
let m_payment_intent_shipping_address_id = payment_intent.shipping_address_id.clone();
let m_payment_intent_payment_id = payment_intent.payment_id.clone();
let m_customer_details_customer_id = customer_details.customer_id.clone();
let m_payment_intent_customer_id = payment_intent.customer_id.clone();
let m_key_store = merchant_context.get_merchant_key_store().clone();
let session_state = state.clone();
let shipping_address_fut = tokio::spawn(
async move {
helpers::create_or_update_address_for_payment_by_request(
&session_state,
m_request_shipping.as_ref(),
m_payment_intent_shipping_address_id.as_deref(),
&m_merchant_id,
m_payment_intent_customer_id
.as_ref()
.or(m_customer_details_customer_id.as_ref()),
&m_key_store,
&m_payment_intent_payment_id,
storage_scheme,
)
.await
}
.in_current_span(),
);
let m_merchant_id = merchant_id.clone();
let m_request_billing = request.billing.clone();
let m_customer_details_customer_id = customer_details.customer_id.clone();
let m_payment_intent_customer_id = payment_intent.customer_id.clone();
let m_payment_intent_billing_address_id = payment_intent.billing_address_id.clone();
let m_payment_intent_payment_id = payment_intent.payment_id.clone();
let m_key_store = merchant_context.get_merchant_key_store().clone();
let session_state = state.clone();
let billing_address_fut = tokio::spawn(
async move {
helpers::create_or_update_address_for_payment_by_request(
&session_state,
m_request_billing.as_ref(),
m_payment_intent_billing_address_id.as_deref(),
&m_merchant_id,
m_payment_intent_customer_id
.as_ref()
.or(m_customer_details_customer_id.as_ref()),
&m_key_store,
&m_payment_intent_payment_id,
storage_scheme,
)
.await
}
.in_current_span(),
);
let m_merchant_id = merchant_id.clone();
let store = state.clone().store;
let m_request_merchant_connector_details = request.merchant_connector_details.clone();
let config_update_fut = tokio::spawn(
async move {
m_request_merchant_connector_details
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(
store.as_ref(),
&m_merchant_id,
mcd,
)
.await
})
.map(|x| x.transpose())
.await
}
.in_current_span(),
);
// Based on whether a retry can be performed or not, fetch relevant entities
let (mut payment_attempt, shipping_address, billing_address, business_profile) =
match payment_intent.status {
api_models::enums::IntentStatus::RequiresCustomerAction
| api_models::enums::IntentStatus::RequiresMerchantAction
| api_models::enums::IntentStatus::RequiresPaymentMethod
| api_models::enums::IntentStatus::RequiresConfirmation => {
// Normal payment
// Parallel calls - level 1
let (payment_attempt, shipping_address, billing_address, business_profile, _) =
tokio::try_join!(
utils::flatten_join_error(payment_attempt_fut),
utils::flatten_join_error(shipping_address_fut),
utils::flatten_join_error(billing_address_fut),
utils::flatten_join_error(business_profile_fut),
utils::flatten_join_error(config_update_fut)
)?;
(
payment_attempt,
shipping_address,
billing_address,
business_profile,
)
}
_ => {
// Retry payment
let (
mut payment_attempt,
shipping_address,
billing_address,
business_profile,
_,
) = tokio::try_join!(
utils::flatten_join_error(payment_attempt_fut),
utils::flatten_join_error(shipping_address_fut),
utils::flatten_join_error(billing_address_fut),
utils::flatten_join_error(business_profile_fut),
utils::flatten_join_error(config_update_fut)
)?;
let attempt_type = helpers::get_attempt_type(
&payment_intent,
&payment_attempt,
business_profile.is_manual_retry_enabled,
"confirm",
)?;
// 3
(payment_intent, payment_attempt) = attempt_type
.modify_payment_intent_and_payment_attempt(
request,
payment_intent,
payment_attempt,
state,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await?;
(
payment_attempt,
shipping_address,
billing_address,
business_profile,
)
}
};
payment_intent.order_details = request
.get_order_details_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert order details to value")?
.or(payment_intent.order_details);
payment_intent.setup_future_usage = request
.setup_future_usage
.or(payment_intent.setup_future_usage);
payment_intent.psd2_sca_exemption_type = request
.psd2_sca_exemption_type
.or(payment_intent.psd2_sca_exemption_type);
let browser_info = request
.browser_info
.clone()
.or(payment_attempt.browser_info)
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let customer_acceptance = request.customer_acceptance.clone().or(payment_attempt
.customer_acceptance
.clone()
.map(|customer_acceptance| {
customer_acceptance
.expose()
.parse_value("CustomerAcceptance")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while deserializing customer_acceptance")
})
.transpose()?);
let recurring_details = request.recurring_details.clone();
helpers::validate_card_data(
request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone()),
)?;
payment_attempt.browser_info = browser_info;
payment_attempt.payment_experience = request
.payment_experience
.or(payment_attempt.payment_experience);
payment_attempt.capture_method = request.capture_method.or(payment_attempt.capture_method);
payment_attempt.customer_acceptance = request
.customer_acceptance
.clone()
.map(|customer_acceptance| customer_acceptance.encode_to_value())
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encoding customer_acceptance to value")?
.map(masking::Secret::new)
.or(payment_attempt.customer_acceptance);
currency = payment_attempt.currency.get_required_value("currency")?;
amount = payment_attempt.get_total_amount().into();
helpers::validate_customer_id_mandatory_cases(
request.setup_future_usage.is_some(),
payment_intent
.customer_id
.as_ref()
.or(customer_details.customer_id.as_ref()),
)?;
let creds_identifier = request
.merchant_connector_details
.as_ref()
.map(|mcd| mcd.creds_identifier.to_owned());
payment_intent.shipping_address_id =
shipping_address.as_ref().map(|i| i.address_id.clone());
payment_intent.billing_address_id = billing_address.as_ref().map(|i| i.address_id.clone());
payment_intent.return_url = request
.return_url
.as_ref()
.map(|a| a.to_string())
.or(payment_intent.return_url);
payment_intent.allowed_payment_method_types = request
.get_allowed_payment_method_types_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting allowed_payment_types to Value")?
.or(payment_intent.allowed_payment_method_types);
payment_intent.connector_metadata = request
.get_connector_metadata_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting connector_metadata to Value")?
.or(payment_intent.connector_metadata);
payment_intent.feature_metadata = request
.get_feature_metadata_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting feature_metadata to Value")?
.or(payment_intent.feature_metadata);
payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata);
payment_intent.frm_metadata = request.frm_metadata.clone().or(payment_intent.frm_metadata);
payment_intent.request_incremental_authorization = request
.request_incremental_authorization
.map(|request_incremental_authorization| {
core_utils::get_request_incremental_authorization_value(
Some(request_incremental_authorization),
payment_attempt.capture_method,
)
})
.unwrap_or(Ok(payment_intent.request_incremental_authorization))?;
payment_intent.enable_partial_authorization = request
.enable_partial_authorization
.or(payment_intent.enable_partial_authorization);
payment_attempt.business_sub_label = request
.business_sub_label
.clone()
.or(payment_attempt.business_sub_label);
let n_request_payment_method_data = request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone());
let store = state.clone().store;
let profile_id = payment_intent
.profile_id
.clone()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let additional_pm_data_fut = tokio::spawn(
async move {
Ok(n_request_payment_method_data
.async_map(|payment_method_data| async move {
helpers::get_additional_payment_data(
&payment_method_data.into(),
store.as_ref(),
&profile_id,
)
.await
})
.await)
}
.in_current_span(),
);
let n_payment_method_billing_address_id =
payment_attempt.payment_method_billing_address_id.clone();
let n_request_payment_method_billing_address = request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.billing.clone());
let m_payment_intent_customer_id = payment_intent.customer_id.clone();
let m_payment_intent_payment_id = payment_intent.payment_id.clone();
let m_key_store = merchant_context.get_merchant_key_store().clone();
let m_customer_details_customer_id = customer_details.customer_id.clone();
let m_merchant_id = merchant_id.clone();
let session_state = state.clone();
let payment_method_billing_future = tokio::spawn(
async move {
helpers::create_or_update_address_for_payment_by_request(
&session_state,
n_request_payment_method_billing_address.as_ref(),
n_payment_method_billing_address_id.as_deref(),
&m_merchant_id,
m_payment_intent_customer_id
.as_ref()
.or(m_customer_details_customer_id.as_ref()),
&m_key_store,
&m_payment_intent_payment_id,
storage_scheme,
)
.await
}
.in_current_span(),
);
let mandate_type = m_helpers::get_mandate_type(
request.mandate_data.clone(),
request.off_session,
payment_intent.setup_future_usage,
request.customer_acceptance.clone(),
request.payment_token.clone(),
payment_attempt.payment_method.or(request.payment_method),
)
.change_context(errors::ApiErrorResponse::MandateValidationFailed {
reason: "Expected one out of recurring_details and mandate_data but got both".into(),
})?;
let m_state = state.clone();
let m_mandate_type = mandate_type;
let m_merchant_context = merchant_context.clone();
let m_request = request.clone();
let payment_intent_customer_id = payment_intent.customer_id.clone();
let mandate_details_fut = tokio::spawn(
async move {
Box::pin(helpers::get_token_pm_type_mandate_details(
&m_state,
&m_request,
m_mandate_type,
&m_merchant_context,
None,
payment_intent_customer_id.as_ref(),
))
.await
}
.in_current_span(),
);
// Parallel calls - level 2
let (mandate_details, additional_pm_info, payment_method_billing) = tokio::try_join!(
utils::flatten_join_error(mandate_details_fut),
utils::flatten_join_error(additional_pm_data_fut),
utils::flatten_join_error(payment_method_billing_future),
)?;
let additional_pm_data = additional_pm_info.transpose()?.flatten();
let m_helpers::MandateGenericData {
token,
payment_method,
payment_method_type,
mandate_data,
recurring_mandate_payment_data,
mandate_connector,
payment_method_info,
} = mandate_details;
let token = token.or_else(|| payment_attempt.payment_token.clone());
helpers::validate_pm_or_token_given(
&request.payment_method,
&request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone()),
&request.payment_method_type,
&mandate_type,
&token,
&request.ctp_service_details,
)?;
let (token_data, payment_method_info) = if let Some(token) = token.clone() {
let token_data = helpers::retrieve_payment_token_data(
state,
token,
payment_method.or(payment_attempt.payment_method),
)
.await?;
let payment_method_info = helpers::retrieve_payment_method_from_db_with_token_data(
state,
merchant_context.get_merchant_key_store(),
&token_data,
storage_scheme,
)
.await?;
(Some(token_data), payment_method_info)
} else {
(None, payment_method_info)
};
let additional_pm_data_from_locker = if let Some(ref pm) = payment_method_info {
let card_detail_from_locker: Option<api::CardDetailFromLocker> = pm
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|v| {
v.parse_value("PaymentMethodsData")
.map_err(|err| {
router_env::logger::info!(
"PaymentMethodsData deserialization failed: {:?}",
err
)
})
.ok()
})
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
_ => None,
});
card_detail_from_locker.map(|card_details| {
let additional_data = card_details.into();
api_models::payments::AdditionalPaymentData::Card(Box::new(additional_data))
})
} else {
None
};
// Only set `payment_attempt.payment_method_data` if `additional_pm_data_from_locker` is not None
if let Some(additional_pm_data) = additional_pm_data_from_locker.as_ref() {
payment_attempt.payment_method_data = Some(
Encode::encode_to_value(additional_pm_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?,
);
}
payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method);
let payment_method_type = Option::<api_models::enums::PaymentMethodType>::foreign_from((
payment_method_type,
additional_pm_data.as_ref(),
payment_method,
));
payment_attempt.payment_method_type = payment_method_type
.or(payment_attempt.payment_method_type)
.or(payment_method_info
.as_ref()
.and_then(|pm_info| pm_info.get_payment_method_subtype()));
// The operation merges mandate data from both request and payment_attempt
let setup_mandate = mandate_data.map(|mut sm| {
sm.mandate_type = payment_attempt.mandate_details.clone().or(sm.mandate_type);
sm.update_mandate_id = payment_attempt
.mandate_data
.clone()
.and_then(|mandate| mandate.update_mandate_id)
.or(sm.update_mandate_id);
sm
});
let mandate_details_present =
payment_attempt.mandate_details.is_some() || request.mandate_data.is_some();
helpers::validate_mandate_data_and_future_usage(
payment_intent.setup_future_usage,
mandate_details_present,
)?;
let payment_method_data_after_card_bin_call = request
.payment_method_data
.as_ref()
.and_then(|request_payment_method_data| {
request_payment_method_data.payment_method_data.as_ref()
})
.zip(additional_pm_data)
.map(|(payment_method_data, additional_payment_data)| {
payment_method_data.apply_additional_payment_data(additional_payment_data)
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Card cobadge check failed due to an invalid card network regex")?;
payment_attempt.payment_method_billing_address_id = payment_method_billing
.as_ref()
.map(|payment_method_billing| payment_method_billing.address_id.clone());
let address = PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
);
let payment_method_data_billing = request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.as_ref())
.and_then(|payment_method_data_billing| {
payment_method_data_billing.get_billing_address()
})
.map(From::from);
let unified_address =
address.unify_with_payment_method_data_billing(payment_method_data_billing);
// If processor_payment_token is passed in request then populating the same in PaymentData
let mandate_id = request
.recurring_details
.as_ref()
.and_then(|recurring_details| match recurring_details {
api_models::mandates::RecurringDetails::ProcessorPaymentToken(token) => {
payment_intent.is_payment_processor_token_flow = Some(true);
Some(api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::ConnectorMandateId(
ConnectorMandateReferenceId::new(
Some(token.processor_payment_token.clone()), // connector_mandate_id
None, // payment_method_id
None, // update_history
None, // mandate_metadata
None, // connector_mandate_request_reference_id
),
),
),
})
}
_ => None,
});
let pmt_order_tax_amount = payment_intent.tax_details.clone().and_then(|tax| {
if tax.payment_method_type.clone().map(|a| a.pmt) == payment_attempt.payment_method_type
{
tax.payment_method_type.map(|a| a.order_tax_amount)
} else {
None
}
});
let order_tax_amount = pmt_order_tax_amount.or_else(|| {
payment_intent
.tax_details
.clone()
.and_then(|tax| tax.default.map(|a| a.order_tax_amount))
});
payment_attempt
.net_amount
.set_order_tax_amount(order_tax_amount);
payment_attempt.connector_mandate_detail = Some(
DieselConnectorMandateReferenceId::foreign_from(ConnectorMandateReferenceId::new(
None,
None,
None, // update_history
None, // mandate_metadata
Some(common_utils::generate_id_with_len(
consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH,
)), // connector_mandate_request_reference_id
)),
);
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: request.email.clone(),
mandate_id: mandate_id.clone(),
mandate_connector,
setup_mandate,
customer_acceptance,
token,
address: unified_address,
token_data,
confirm: request.confirm,
payment_method_data: payment_method_data_after_card_bin_call.map(Into::into),
payment_method_token: None,
payment_method_info,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: request.card_cvc.clone(),
creds_identifier,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details,
poll_config: None,
tax_data: None,
session_id: None,
service_details: request.ctp_service_details.clone(),
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: business_profile.is_manual_retry_enabled,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: Some(customer_details),
payment_data,
business_profile,
mandate_type,
};
Ok(get_trackers_response)
}
async fn validate_request_with_state(
&self,
state: &SessionState,
request: &api::PaymentsRequest,
payment_data: &mut PaymentData<F>,
business_profile: &domain::Profile,
) -> RouterResult<()> {
let payment_method_data: Option<&api_models::payments::PaymentMethodData> = request
.payment_method_data
.as_ref()
.and_then(|request_payment_method_data| {
request_payment_method_data.payment_method_data.as_ref()
});
let customer_id = &payment_data.payment_intent.customer_id;
match payment_method_data {
Some(api_models::payments::PaymentMethodData::Card(_card)) => {
payment_data.card_testing_guard_data =
card_testing_guard_utils::validate_card_testing_guard_checks(
state,
request,
payment_method_data,
customer_id,
business_profile,
)
.await?;
Ok(())
}
_ => Ok(()),
}
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for PaymentConfirm {
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(PaymentConfirmOperation<'a, F>, Option<domain::Customer>),
errors::StorageError,
> {
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: storage_enums::MerchantStorageScheme,
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
PaymentConfirmOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
let (op, payment_method_data, pm_id) = Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await?;
utils::when(payment_method_data.is_none(), || {
Err(errors::ApiErrorResponse::PaymentMethodNotFound)
})?;
Ok((op, payment_method_data, pm_id))
}
#[instrument(skip_all)]
async fn add_task_to_process_tracker<'a>(
&'a self,
state: &'a SessionState,
payment_attempt: &storage::PaymentAttempt,
requeue: bool,
schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
// This spawns this futures in a background thread, the exception inside this future won't affect
// the current thread and the lifecycle of spawn thread is not handled by runtime.
// So when server shutdown won't wait for this thread's completion.
let m_payment_attempt = payment_attempt.clone();
let m_state = state.clone();
let m_self = *self;
tokio::spawn(
async move {
helpers::add_domain_task_to_pt(
&m_self,
&m_state,
&m_payment_attempt,
requeue,
schedule_time,
)
.await
}
.in_current_span(),
);
Ok(())
}
async fn get_connector<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
state: &SessionState,
request: &api::PaymentsRequest,
_payment_intent: &storage::PaymentIntent,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
// Use a new connector in the confirm call or use the same one which was passed when
// creating the payment or if none is passed then use the routing algorithm
helpers::get_connector_default(state, request.routing.clone()).await
}
#[instrument(skip_all)]
async fn populate_payment_data<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
_merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
connector_data: &api::ConnectorData,
) -> CustomResult<(), errors::ApiErrorResponse> {
populate_surcharge_details(state, payment_data).await?;
payment_data.payment_attempt.request_extended_authorization = payment_data
.payment_intent
.get_request_extended_authorization_bool_if_connector_supports(
connector_data.connector_name,
business_profile.always_request_extended_authorization,
payment_data.payment_attempt.payment_method,
payment_data.payment_attempt.payment_method_type,
);
payment_data.payment_intent.enable_overcapture = payment_data
.payment_intent
.get_enable_overcapture_bool_if_connector_supports(
connector_data.connector_name,
business_profile.always_enable_overcapture,
&payment_data.payment_attempt.capture_method,
);
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn call_external_three_ds_authentication_if_eligible<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
should_continue_confirm_transaction: &mut bool,
connector_call_type: &ConnectorCallType,
business_profile: &domain::Profile,
key_store: &domain::MerchantKeyStore,
mandate_type: Option<api_models::payments::MandateTransactionType>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let external_authentication_flow =
helpers::get_payment_external_authentication_flow_during_confirm(
state,
key_store,
business_profile,
payment_data,
connector_call_type,
mandate_type,
)
.await?;
payment_data.authentication = match external_authentication_flow {
Some(helpers::PaymentExternalAuthenticationFlow::PreAuthenticationFlow {
acquirer_details,
card,
token,
}) => {
let authentication_store = Box::pin(authentication::perform_pre_authentication(
state,
key_store,
*card,
token,
business_profile,
acquirer_details,
payment_data.payment_attempt.payment_id.clone(),
payment_data.payment_attempt.organization_id.clone(),
payment_data.payment_intent.force_3ds_challenge,
payment_data.payment_intent.psd2_sca_exemption_type,
))
.await?;
if authentication_store
.authentication
.is_separate_authn_required()
|| authentication_store
.authentication
.authentication_status
.is_failed()
{
*should_continue_confirm_transaction = false;
let default_poll_config = types::PollConfig::default();
let default_config_str = default_poll_config
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while stringifying default poll config")?;
// raise error if authentication_connector is not present since it should we be present in the current flow
let authentication_connector = authentication_store
.authentication
.authentication_connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"authentication_connector not present in authentication record",
)?;
let poll_config = state
.store
.find_config_by_key_unwrap_or(
&types::PollConfig::get_poll_config_key(authentication_connector),
Some(default_config_str),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The poll config was not found in the DB")?;
let poll_config: types::PollConfig = poll_config
.config
.parse_struct("PollConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing PollConfig")?;
payment_data.poll_config = Some(poll_config)
}
Some(authentication_store)
}
Some(helpers::PaymentExternalAuthenticationFlow::PostAuthenticationFlow {
authentication_id,
}) => {
let authentication_store = Box::pin(authentication::perform_post_authentication(
state,
key_store,
business_profile.clone(),
authentication_id.clone(),
&payment_data.payment_intent.payment_id,
))
.await?;
//If authentication is not successful, skip the payment connector flows and mark the payment as failure
if authentication_store.authentication.authentication_status
!= api_models::enums::AuthenticationStatus::Success
{
*should_continue_confirm_transaction = false;
}
Some(authentication_store)
}
None => None,
};
Ok(())
}
async fn apply_three_ds_authentication_strategy<'a>(
&'a self,
state: &SessionState,
|
crates/router/src/core/payments/operations/payment_confirm.rs#chunk0
|
router
|
chunk
| null | null | null | 8,187
| null | null | null | null | null | null | null |
// Function: payouts_update
// File: crates/router/src/routes/payouts.rs
// Module: router
pub fn payouts_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::PayoutId>,
json_payload: web::Json<payout_types::PayoutCreateRequest>,
) -> HttpResponse
|
crates/router/src/routes/payouts.rs
|
router
|
function_signature
| null | null | null | 75
|
payouts_update
| null | null | null | null | null | null |
// Implementation: impl FileStorageConfig
// File: crates/external_services/src/file_storage.rs
// Module: external_services
// Methods: 2 total (1 public)
impl FileStorageConfig
|
crates/external_services/src/file_storage.rs
|
external_services
|
impl_block
| null | null | null | 40
| null |
FileStorageConfig
| null | 2
| 1
| null | null |
// Implementation: impl std::fmt::Display for for TrustpaymentsCredentialsOnFile
// File: crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
// Module: hyperswitch_connectors
// Methods: 1 total (0 public)
impl std::fmt::Display for for TrustpaymentsCredentialsOnFile
|
crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 69
| null |
TrustpaymentsCredentialsOnFile
|
std::fmt::Display for
| 1
| 0
| null | null |
// Struct: StaxWebhookBody
// File: crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct StaxWebhookBody
|
crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
StaxWebhookBody
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Function: new
// File: crates/hyperswitch_connectors/src/connectors/affirm.rs
// Module: hyperswitch_connectors
pub fn new() -> &'static Self
|
crates/hyperswitch_connectors/src/connectors/affirm.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 39
|
new
| null | null | null | null | null | null |
// Struct: NoonRevokeMandateResult
// File: crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NoonRevokeMandateResult
|
crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
NoonRevokeMandateResult
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// Implementation: impl GetRoutableConnectorsForChoice for for StraightThroughAlgorithmTypeSingle
// File: crates/router/src/core/routing.rs
// Module: router
// Methods: 1 total (0 public)
impl GetRoutableConnectorsForChoice for for StraightThroughAlgorithmTypeSingle
|
crates/router/src/core/routing.rs
|
router
|
impl_block
| null | null | null | 62
| null |
StraightThroughAlgorithmTypeSingle
|
GetRoutableConnectorsForChoice for
| 1
| 0
| null | null |
// Function: get_theme_using_lineage
// File: crates/router/src/core/user/theme.rs
// Module: router
pub fn get_theme_using_lineage(
state: SessionState,
lineage: ThemeLineage,
) -> UserResponse<theme_api::GetThemeResponse>
|
crates/router/src/core/user/theme.rs
|
router
|
function_signature
| null | null | null | 58
|
get_theme_using_lineage
| null | null | null | null | null | null |
// Trait: CommonStorageInterface
// File: crates/router/src/db.rs
// Module: router
pub trait CommonStorageInterface: StorageInterface
+ GlobalStorageInterface
+ AccountsStorageInterface
+ PaymentMethodsStorageInterface
|
crates/router/src/db.rs
|
router
|
trait_definition
| null | null | null | 48
| null | null |
CommonStorageInterface
| null | null | null | null |
// Struct: ApplePayTokenPaymentInformation
// File: crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ApplePayTokenPaymentInformation
|
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ApplePayTokenPaymentInformation
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// File: crates/router/src/compatibility/stripe/errors.rs
// Module: router
use common_utils::{errors::ErrorSwitch, id_type};
use hyperswitch_domain_models::errors::api_error_response as errors;
use crate::core::errors::CustomersErrorResponse;
#[derive(Debug, router_derive::ApiError, Clone)]
#[error(error_type_enum = StripeErrorType)]
pub enum StripeErrorCode {
/*
"error": {
"message": "Invalid API Key provided: sk_jkjgs****nlgs",
"type": "invalid_request_error"
}
*/
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "IR_01",
message = "Invalid API Key provided"
)]
Unauthorized,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_02", message = "Unrecognized request URL.")]
InvalidRequestUrl,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Missing required param: {field_name}.")]
ParameterMissing { field_name: String, param: String },
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "parameter_unknown",
message = "{field_name} contains invalid data. Expected format is {expected_format}."
)]
ParameterUnknown {
field_name: String,
expected_format: String,
},
#[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_06", message = "The refund amount exceeds the amount captured.")]
RefundAmountExceedsPaymentAmount { param: String },
#[error(error_type = StripeErrorType::ApiError, code = "payment_intent_authentication_failure", message = "Payment failed while processing with connector. Retry payment.")]
PaymentIntentAuthenticationFailure { data: Option<serde_json::Value> },
#[error(error_type = StripeErrorType::ApiError, code = "payment_intent_payment_attempt_failed", message = "Capture attempt failed while processing with connector.")]
PaymentIntentPaymentAttemptFailed { data: Option<serde_json::Value> },
#[error(error_type = StripeErrorType::ApiError, code = "dispute_failure", message = "Dispute failed while processing with connector. Retry operation.")]
DisputeFailed { data: Option<serde_json::Value> },
#[error(error_type = StripeErrorType::CardError, code = "expired_card", message = "Card Expired. Please use another card")]
ExpiredCard,
#[error(error_type = StripeErrorType::CardError, code = "invalid_card_type", message = "Card data is invalid")]
InvalidCardType,
#[error(
error_type = StripeErrorType::ConnectorError, code = "invalid_wallet_token",
message = "Invalid {wallet_name} wallet token"
)]
InvalidWalletToken { wallet_name: String },
#[error(error_type = StripeErrorType::ApiError, code = "refund_failed", message = "refund has failed")]
RefundFailed, // stripe error code
#[error(error_type = StripeErrorType::ApiError, code = "payout_failed", message = "payout has failed")]
PayoutFailed,
#[error(error_type = StripeErrorType::ApiError, code = "external_vault_failed", message = "external vault has failed")]
ExternalVaultFailed,
#[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")]
InternalServerError,
#[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")]
DuplicateRefundRequest,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "active_mandate", message = "Customer has active mandate")]
MandateActive,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_redacted", message = "Customer has redacted")]
CustomerRedacted,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_already_exists", message = "Customer with the given customer_id already exists")]
DuplicateCustomer,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such refund")]
RefundNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "client_secret_invalid", message = "Expected client secret to be included in the request")]
ClientSecretNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such customer")]
CustomerNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such config")]
ConfigNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "Duplicate config")]
DuplicateConfig,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment")]
PaymentNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment method")]
PaymentMethodNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "{message}")]
GenericNotFoundError { message: String },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "{message}")]
GenericDuplicateError { message: String },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such merchant account")]
MerchantAccountNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such resource ID")]
ResourceIdNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "Merchant connector account does not exist in our records")]
MerchantConnectorAccountNotFound { id: String },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "invalid_request", message = "The merchant connector account is disabled")]
MerchantConnectorAccountDisabled,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such mandate")]
MandateNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such API key")]
ApiKeyNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payout")]
PayoutNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such event")]
EventNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "Duplicate payout request")]
DuplicatePayout { payout_id: id_type::PayoutId },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Return url is not available")]
ReturnUrlUnavailable,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate merchant account")]
DuplicateMerchantAccount,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_label}' already exists in our records")]
DuplicateMerchantConnectorAccount {
profile_id: String,
connector_label: String,
},
#[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate payment method")]
DuplicatePaymentMethod,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "" , message = "deserialization failed: {error_message}")]
SerdeQsError {
error_message: String,
param: Option<String>,
},
#[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_intent_invalid_parameter" , message = "The client_secret provided does not match the client_secret associated with the PaymentIntent.")]
PaymentIntentInvalidParameter { param: String },
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "IR_05",
message = "{message}"
)]
InvalidRequestData { message: String },
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "IR_10",
message = "{message}"
)]
PreconditionFailed { message: String },
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "",
message = "The payment has not succeeded yet"
)]
PaymentFailed,
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "",
message = "The verification did not succeeded"
)]
VerificationFailed { data: Option<serde_json::Value> },
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "",
message = "Reached maximum refund attempts"
)]
MaximumRefundCount,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID.")]
DuplicateMandate,
#[error(error_type= StripeErrorType::InvalidRequestError, code = "", message = "Successful payment not found for the given payment id")]
SuccessfulPaymentNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Address does not exist in our records.")]
AddressNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "This PaymentIntent could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}.")]
PaymentIntentUnexpectedState {
current_flow: String,
field_name: String,
current_value: String,
states: String,
},
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The mandate information is invalid. {message}")]
PaymentIntentMandateInvalid { message: String },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The payment with the specified payment_id already exists in our records.")]
DuplicatePayment { payment_id: id_type::PaymentId },
#[error(error_type = StripeErrorType::ConnectorError, code = "", message = "{code}: {message}")]
ExternalConnectorError {
code: String,
message: String,
connector: String,
status_code: u16,
},
#[error(error_type = StripeErrorType::CardError, code = "", message = "{code}: {message}")]
PaymentBlockedError {
code: u16,
message: String,
status: String,
reason: String,
},
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "The connector provided in the request is incorrect or not available")]
IncorrectConnectorNameGiven,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "No such {object}: '{id}'")]
ResourceMissing { object: String, id: String },
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File validation failed")]
FileValidationFailed,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not found in the request")]
MissingFile,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File puropse not found in the request")]
MissingFilePurpose,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File content type not found")]
MissingFileContentType,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Dispute id not found in the request")]
MissingDisputeId,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File does not exists in our records")]
FileNotFound,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not available")]
FileNotAvailable,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Not Supported because provider is not Router")]
FileProviderNotSupported,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "There was an issue with processing webhooks")]
WebhookProcessingError,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_method_unactivated", message = "The operation cannot be performed as the payment method used has not been activated. Activate the payment method in the Dashboard, then try again.")]
PaymentMethodUnactivated,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "{message}")]
HyperswitchUnprocessableEntity { message: String },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "{message}")]
CurrencyNotSupported { message: String },
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Payment Link does not exist in our records")]
PaymentLinkNotFound,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Resource Busy. Please try again later")]
LockTimeout,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Merchant connector account is configured with invalid {config}")]
InvalidConnectorConfiguration { config: String },
#[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert currency to minor unit")]
CurrencyConversionFailed,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")]
PaymentMethodDeleteFailed,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Extended card info does not exist")]
ExtendedCardInfoNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "not_configured", message = "{message}")]
LinkConfigurationError { message: String },
#[error(error_type = StripeErrorType::ConnectorError, code = "CE", message = "{reason} as data mismatched for {field_names}")]
IntegrityCheckFailed {
reason: String,
field_names: String,
connector_transaction_id: Option<String>,
},
#[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_28", message = "Invalid tenant")]
InvalidTenant,
#[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert amount to {amount_type} type")]
AmountConversionFailed { amount_type: &'static str },
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Bad Request")]
PlatformBadRequest,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Unauthorized Request")]
PlatformUnauthorizedRequest,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Profile Acquirer not found")]
ProfileAcquirerNotFound,
#[error(error_type = StripeErrorType::HyperswitchError, code = "Subscription Error", message = "Subscription operation: {operation} failed with connector")]
SubscriptionError { operation: String },
// [#216]: https://github.com/juspay/hyperswitch/issues/216
// Implement the remaining stripe error codes
/*
AccountCountryInvalidAddress,
AccountErrorCountryChangeRequiresAdditionalSteps,
AccountInformationMismatch,
AccountInvalid,
AccountNumberInvalid,
AcssDebitSessionIncomplete,
AlipayUpgradeRequired,
AmountTooLarge,
AmountTooSmall,
ApiKeyExpired,
AuthenticationRequired,
BalanceInsufficient,
BankAccountBadRoutingNumbers,
BankAccountDeclined,
BankAccountExists,
BankAccountUnusable,
BankAccountUnverified,
BankAccountVerificationFailed,
BillingInvalidMandate,
BitcoinUpgradeRequired,
CardDeclineRateLimitExceeded,
CardDeclined,
CardholderPhoneNumberRequired,
ChargeAlreadyCaptured,
ChargeAlreadyRefunded,
ChargeDisputed,
ChargeExceedsSourceLimit,
ChargeExpiredForCapture,
ChargeInvalidParameter,
ClearingCodeUnsupported,
CountryCodeInvalid,
CountryUnsupported,
CouponExpired,
CustomerMaxPaymentMethods,
CustomerMaxSubscriptions,
DebitNotAuthorized,
EmailInvalid,
ExpiredCard,
IdempotencyKeyInUse,
IncorrectAddress,
IncorrectCvc,
IncorrectNumber,
IncorrectZip,
InstantPayoutsConfigDisabled,
InstantPayoutsCurrencyDisabled,
InstantPayoutsLimitExceeded,
InstantPayoutsUnsupported,
InsufficientFunds,
IntentInvalidState,
IntentVerificationMethodMissing,
InvalidCardType,
InvalidCharacters,
InvalidChargeAmount,
InvalidCvc,
InvalidExpiryMonth,
InvalidExpiryYear,
InvalidNumber,
InvalidSourceUsage,
InvoiceNoCustomerLineItems,
InvoiceNoPaymentMethodTypes,
InvoiceNoSubscriptionLineItems,
InvoiceNotEditable,
InvoiceOnBehalfOfNotEditable,
InvoicePaymentIntentRequiresAction,
InvoiceUpcomingNone,
LivemodeMismatch,
LockTimeout,
Missing,
NoAccount,
NotAllowedOnStandardAccount,
OutOfInventory,
ParameterInvalidEmpty,
ParameterInvalidInteger,
ParameterInvalidStringBlank,
ParameterInvalidStringEmpty,
ParametersExclusive,
PaymentIntentActionRequired,
PaymentIntentIncompatiblePaymentMethod,
PaymentIntentInvalidParameter,
PaymentIntentKonbiniRejectedConfirmationNumber,
PaymentIntentPaymentAttemptExpired,
PaymentIntentUnexpectedState,
PaymentMethodBankAccountAlreadyVerified,
PaymentMethodBankAccountBlocked,
PaymentMethodBillingDetailsAddressMissing,
PaymentMethodCurrencyMismatch,
PaymentMethodInvalidParameter,
PaymentMethodInvalidParameterTestmode,
PaymentMethodMicrodepositFailed,
PaymentMethodMicrodepositVerificationAmountsInvalid,
PaymentMethodMicrodepositVerificationAmountsMismatch,
PaymentMethodMicrodepositVerificationAttemptsExceeded,
PaymentMethodMicrodepositVerificationDescriptorCodeMismatch,
PaymentMethodMicrodepositVerificationTimeout,
PaymentMethodProviderDecline,
PaymentMethodProviderTimeout,
PaymentMethodUnexpectedState,
PaymentMethodUnsupportedType,
PayoutsNotAllowed,
PlatformAccountRequired,
PlatformApiKeyExpired,
PostalCodeInvalid,
ProcessingError,
ProductInactive,
RateLimit,
ReferToCustomer,
RefundDisputedPayment,
ResourceAlreadyExists,
ResourceMissing,
ReturnIntentAlreadyProcessed,
RoutingNumberInvalid,
SecretKeyRequired,
SepaUnsupportedAccount,
SetupAttemptFailed,
SetupIntentAuthenticationFailure,
SetupIntentInvalidParameter,
SetupIntentSetupAttemptExpired,
SetupIntentUnexpectedState,
ShippingCalculationFailed,
SkuInactive,
StateUnsupported,
StatusTransitionInvalid,
TaxIdInvalid,
TaxesCalculationFailed,
TerminalLocationCountryUnsupported,
TestmodeChargesOnly,
TlsVersionUnsupported,
TokenInUse,
TransferSourceBalanceParametersMismatch,
TransfersNotAllowed,
*/
}
impl ::core::fmt::Display for StripeErrorCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{{\"error\": {}}}",
serde_json::to_string(self).unwrap_or_else(|_| "API error response".to_string())
)
}
}
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::enum_variant_names)]
pub enum StripeErrorType {
ApiError,
CardError,
InvalidRequestError,
ConnectorError,
HyperswitchError,
}
impl From<errors::ApiErrorResponse> for StripeErrorCode {
fn from(value: errors::ApiErrorResponse) -> Self {
match value {
errors::ApiErrorResponse::Unauthorized
| errors::ApiErrorResponse::InvalidJwtToken
| errors::ApiErrorResponse::GenericUnauthorized { .. }
| errors::ApiErrorResponse::AccessForbidden { .. }
| errors::ApiErrorResponse::InvalidCookie
| errors::ApiErrorResponse::InvalidEphemeralKey
| errors::ApiErrorResponse::CookieNotFound => Self::Unauthorized,
errors::ApiErrorResponse::InvalidRequestUrl
| errors::ApiErrorResponse::InvalidHttpMethod
| errors::ApiErrorResponse::InvalidCardIin
| errors::ApiErrorResponse::InvalidCardIinLength => Self::InvalidRequestUrl,
errors::ApiErrorResponse::MissingRequiredField { field_name } => {
Self::ParameterMissing {
field_name: field_name.to_string(),
param: field_name.to_string(),
}
}
errors::ApiErrorResponse::UnprocessableEntity { message } => {
Self::HyperswitchUnprocessableEntity { message }
}
errors::ApiErrorResponse::MissingRequiredFields { field_names } => {
// Instead of creating a new error variant in StripeErrorCode for MissingRequiredFields, converted vec<&str> to String
Self::ParameterMissing {
field_name: field_names.clone().join(", "),
param: field_names.clone().join(", "),
}
}
errors::ApiErrorResponse::GenericNotFoundError { message } => {
Self::GenericNotFoundError { message }
}
errors::ApiErrorResponse::GenericDuplicateError { message } => {
Self::GenericDuplicateError { message }
}
// parameter unknown, invalid request error // actually if we type wrong values in address we get this error. Stripe throws parameter unknown. I don't know if stripe is validating email and stuff
errors::ApiErrorResponse::InvalidDataFormat {
field_name,
expected_format,
} => Self::ParameterUnknown {
field_name,
expected_format,
},
errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount => {
Self::RefundAmountExceedsPaymentAmount {
param: "amount".to_owned(),
}
}
errors::ApiErrorResponse::PaymentAuthorizationFailed { data }
| errors::ApiErrorResponse::PaymentAuthenticationFailed { data } => {
Self::PaymentIntentAuthenticationFailure { data }
}
errors::ApiErrorResponse::VerificationFailed { data } => {
Self::VerificationFailed { data }
}
errors::ApiErrorResponse::PaymentCaptureFailed { data } => {
Self::PaymentIntentPaymentAttemptFailed { data }
}
errors::ApiErrorResponse::DisputeFailed { data } => Self::DisputeFailed { data },
errors::ApiErrorResponse::InvalidCardData { data: _ } => Self::InvalidCardType, // Maybe it is better to de generalize this router error
errors::ApiErrorResponse::CardExpired { data: _ } => Self::ExpiredCard,
errors::ApiErrorResponse::RefundNotPossible { connector: _ } => Self::RefundFailed,
errors::ApiErrorResponse::RefundFailed { data: _ } => Self::RefundFailed, // Nothing at stripe to map
errors::ApiErrorResponse::PayoutFailed { data: _ } => Self::PayoutFailed,
errors::ApiErrorResponse::ExternalVaultFailed => Self::ExternalVaultFailed,
errors::ApiErrorResponse::MandateUpdateFailed
| errors::ApiErrorResponse::MandateSerializationFailed
| errors::ApiErrorResponse::MandateDeserializationFailed
| errors::ApiErrorResponse::InternalServerError
| errors::ApiErrorResponse::HealthCheckError { .. } => Self::InternalServerError, // not a stripe code
errors::ApiErrorResponse::ExternalConnectorError {
code,
message,
connector,
status_code,
..
} => Self::ExternalConnectorError {
code,
message,
connector,
status_code,
},
errors::ApiErrorResponse::IncorrectConnectorNameGiven => {
Self::IncorrectConnectorNameGiven
}
errors::ApiErrorResponse::MandateActive => Self::MandateActive, //not a stripe code
errors::ApiErrorResponse::CustomerRedacted => Self::CustomerRedacted, //not a stripe code
errors::ApiErrorResponse::ConfigNotFound => Self::ConfigNotFound, // not a stripe code
errors::ApiErrorResponse::DuplicateConfig => Self::DuplicateConfig, // not a stripe code
errors::ApiErrorResponse::DuplicateRefundRequest => Self::DuplicateRefundRequest,
errors::ApiErrorResponse::DuplicatePayout { payout_id } => {
Self::DuplicatePayout { payout_id }
}
errors::ApiErrorResponse::RefundNotFound => Self::RefundNotFound,
errors::ApiErrorResponse::CustomerNotFound => Self::CustomerNotFound,
errors::ApiErrorResponse::PaymentNotFound => Self::PaymentNotFound,
errors::ApiErrorResponse::PaymentMethodNotFound => Self::PaymentMethodNotFound,
errors::ApiErrorResponse::ClientSecretNotGiven
| errors::ApiErrorResponse::ClientSecretExpired => Self::ClientSecretNotFound,
errors::ApiErrorResponse::MerchantAccountNotFound => Self::MerchantAccountNotFound,
errors::ApiErrorResponse::PaymentLinkNotFound => Self::PaymentLinkNotFound,
errors::ApiErrorResponse::ResourceIdNotFound => Self::ResourceIdNotFound,
errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id } => {
Self::MerchantConnectorAccountNotFound { id }
}
errors::ApiErrorResponse::MandateNotFound => Self::MandateNotFound,
errors::ApiErrorResponse::ApiKeyNotFound => Self::ApiKeyNotFound,
errors::ApiErrorResponse::PayoutNotFound => Self::PayoutNotFound,
errors::ApiErrorResponse::EventNotFound => Self::EventNotFound,
errors::ApiErrorResponse::MandateValidationFailed { reason } => {
Self::PaymentIntentMandateInvalid { message: reason }
}
errors::ApiErrorResponse::ReturnUrlUnavailable => Self::ReturnUrlUnavailable,
errors::ApiErrorResponse::DuplicateMerchantAccount => Self::DuplicateMerchantAccount,
errors::ApiErrorResponse::DuplicateMerchantConnectorAccount {
profile_id,
connector_label,
} => Self::DuplicateMerchantConnectorAccount {
profile_id,
connector_label,
},
errors::ApiErrorResponse::DuplicatePaymentMethod => Self::DuplicatePaymentMethod,
errors::ApiErrorResponse::PaymentBlockedError {
code,
message,
status,
reason,
} => Self::PaymentBlockedError {
code,
message,
status,
reason,
},
errors::ApiErrorResponse::ClientSecretInvalid => Self::PaymentIntentInvalidParameter {
param: "client_secret".to_owned(),
},
errors::ApiErrorResponse::InvalidRequestData { message } => {
Self::InvalidRequestData { message }
}
errors::ApiErrorResponse::PreconditionFailed { message } => {
Self::PreconditionFailed { message }
}
errors::ApiErrorResponse::InvalidDataValue { field_name } => Self::ParameterMissing {
field_name: field_name.to_string(),
param: field_name.to_string(),
},
errors::ApiErrorResponse::MaximumRefundCount => Self::MaximumRefundCount,
errors::ApiErrorResponse::PaymentNotSucceeded => Self::PaymentFailed,
errors::ApiErrorResponse::DuplicateMandate => Self::DuplicateMandate,
errors::ApiErrorResponse::SuccessfulPaymentNotFound => Self::SuccessfulPaymentNotFound,
errors::ApiErrorResponse::AddressNotFound => Self::AddressNotFound,
errors::ApiErrorResponse::NotImplemented { .. } => Self::Unauthorized,
errors::ApiErrorResponse::FlowNotSupported { .. } => Self::InternalServerError,
errors::ApiErrorResponse::MandatePaymentDataMismatch { .. } => Self::PlatformBadRequest,
errors::ApiErrorResponse::MaxFieldLengthViolated { .. } => Self::PlatformBadRequest,
errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow,
field_name,
current_value,
states,
} => Self::PaymentIntentUnexpectedState {
current_flow,
field_name,
current_value,
states,
},
errors::ApiErrorResponse::DuplicatePayment { payment_id } => {
Self::DuplicatePayment { payment_id }
}
errors::ApiErrorResponse::DisputeNotFound { dispute_id } => Self::ResourceMissing {
object: "dispute".to_owned(),
id: dispute_id,
},
errors::ApiErrorResponse::AuthenticationNotFound { id } => Self::ResourceMissing {
object: "authentication".to_owned(),
id,
},
errors::ApiErrorResponse::ProfileNotFound { id } => Self::ResourceMissing {
object: "business_profile".to_owned(),
id,
},
errors::ApiErrorResponse::PollNotFound { id } => Self::ResourceMissing {
object: "poll".to_owned(),
id,
},
errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: _ } => {
Self::InternalServerError
}
errors::ApiErrorResponse::FileValidationFailed { .. } => Self::FileValidationFailed,
errors::ApiErrorResponse::MissingFile => Self::MissingFile,
errors::ApiErrorResponse::MissingFilePurpose => Self::MissingFilePurpose,
errors::ApiErrorResponse::MissingFileContentType => Self::MissingFileContentType,
errors::ApiErrorResponse::MissingDisputeId => Self::MissingDisputeId,
errors::ApiErrorResponse::FileNotFound => Self::FileNotFound,
errors::ApiErrorResponse::FileNotAvailable => Self::FileNotAvailable,
errors::ApiErrorResponse::MerchantConnectorAccountDisabled => {
Self::MerchantConnectorAccountDisabled
}
errors::ApiErrorResponse::NotSupported { .. } => Self::InternalServerError,
errors::ApiErrorResponse::CurrencyNotSupported { message } => {
Self::CurrencyNotSupported { message }
}
errors::ApiErrorResponse::FileProviderNotSupported { .. } => {
Self::FileProviderNotSupported
}
errors::ApiErrorResponse::WebhookBadRequest
| errors::ApiErrorResponse::WebhookResourceNotFound
| errors::ApiErrorResponse::WebhookProcessingFailure
| errors::ApiErrorResponse::WebhookAuthenticationFailed
| errors::ApiErrorResponse::WebhookUnprocessableEntity
| errors::ApiErrorResponse::WebhookInvalidMerchantSecret => {
Self::WebhookProcessingError
}
errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration => {
Self::PaymentMethodUnactivated
}
errors::ApiErrorResponse::ResourceBusy => Self::PaymentMethodUnactivated,
errors::ApiErrorResponse::InvalidConnectorConfiguration { config } => {
Self::InvalidConnectorConfiguration { config }
}
errors::ApiErrorResponse::CurrencyConversionFailed => Self::CurrencyConversionFailed,
errors::ApiErrorResponse::PaymentMethodDeleteFailed => Self::PaymentMethodDeleteFailed,
errors::ApiErrorResponse::InvalidWalletToken { wallet_name } => {
Self::InvalidWalletToken { wallet_name }
}
errors::ApiErrorResponse::ExtendedCardInfoNotFound => Self::ExtendedCardInfoNotFound,
errors::ApiErrorResponse::LinkConfigurationError { message } => {
Self::LinkConfigurationError { message }
}
errors::ApiErrorResponse::IntegrityCheckFailed {
reason,
field_names,
connector_transaction_id,
} => Self::IntegrityCheckFailed {
reason,
field_names,
connector_transaction_id,
},
errors::ApiErrorResponse::InvalidTenant { tenant_id: _ }
| errors::ApiErrorResponse::MissingTenantId => Self::InvalidTenant,
errors::ApiErrorResponse::AmountConversionFailed { amount_type } => {
Self::AmountConversionFailed { amount_type }
}
errors::ApiErrorResponse::PlatformAccountAuthNotSupported => Self::PlatformBadRequest,
errors::ApiErrorResponse::InvalidPlatformOperation => Self::PlatformUnauthorizedRequest,
errors::ApiErrorResponse::ProfileAcquirerNotFound { .. } => {
Self::ProfileAcquirerNotFound
}
errors::ApiErrorResponse::TokenizationRecordNotFound { id } => Self::ResourceMissing {
object: "tokenization record".to_owned(),
id,
},
errors::ApiErrorResponse::SubscriptionError { operation } => {
Self::SubscriptionError { operation }
}
}
}
}
impl actix_web::ResponseError for StripeErrorCode {
fn status_code(&self) -> reqwest::StatusCode {
use reqwest::StatusCode;
match self {
Self::Unauthorized | Self::PlatformUnauthorizedRequest => StatusCode::UNAUTHORIZED,
Self::InvalidRequestUrl | Self::GenericNotFoundError { .. } => StatusCode::NOT_FOUND,
Self::ParameterUnknown { .. } | Self::HyperswitchUnprocessableEntity { .. } => {
StatusCode::UNPROCESSABLE_ENTITY
}
Self::ParameterMissing { .. }
| Self::RefundAmountExceedsPaymentAmount { .. }
| Self::PaymentIntentAuthenticationFailure { .. }
| Self::PaymentIntentPaymentAttemptFailed { .. }
| Self::ExpiredCard
| Self::InvalidCardType
| Self::DuplicateRefundRequest
| Self::DuplicatePayout { .. }
| Self::RefundNotFound
| Self::CustomerNotFound
| Self::ConfigNotFound
| Self::DuplicateConfig
| Self::ClientSecretNotFound
| Self::PaymentNotFound
| Self::PaymentMethodNotFound
| Self::MerchantAccountNotFound
| Self::MerchantConnectorAccountNotFound { .. }
| Self::MerchantConnectorAccountDisabled
| Self::MandateNotFound
| Self::ApiKeyNotFound
| Self::PayoutNotFound
| Self::EventNotFound
| Self::DuplicateMerchantAccount
| Self::DuplicateMerchantConnectorAccount { .. }
| Self::DuplicatePaymentMethod
| Self::PaymentFailed
| Self::VerificationFailed { .. }
| Self::DisputeFailed { .. }
| Self::MaximumRefundCount
| Self::PaymentIntentInvalidParameter { .. }
| Self::SerdeQsError { .. }
| Self::InvalidRequestData { .. }
| Self::InvalidWalletToken { .. }
| Self::PreconditionFailed { .. }
| Self::DuplicateMandate
| Self::SuccessfulPaymentNotFound
| Self::AddressNotFound
| Self::ResourceIdNotFound
| Self::PaymentIntentMandateInvalid { .. }
| Self::PaymentIntentUnexpectedState { .. }
| Self::DuplicatePayment { .. }
| Self::GenericDuplicateError { .. }
| Self::IncorrectConnectorNameGiven
| Self::ResourceMissing { .. }
| Self::FileValidationFailed
| Self::MissingFile
| Self::MissingFileContentType
| Self::MissingFilePurpose
| Self::MissingDisputeId
| Self::FileNotFound
| Self::FileNotAvailable
| Self::FileProviderNotSupported
| Self::CurrencyNotSupported { .. }
| Self::DuplicateCustomer
| Self::PaymentMethodUnactivated
| Self::InvalidConnectorConfiguration { .. }
| Self::CurrencyConversionFailed
| Self::PaymentMethodDeleteFailed
| Self::ExtendedCardInfoNotFound
| Self::PlatformBadRequest
| Self::LinkConfigurationError { .. } => StatusCode::BAD_REQUEST,
Self::RefundFailed
| Self::PayoutFailed
| Self::PaymentLinkNotFound
| Self::InternalServerError
| Self::MandateActive
| Self::CustomerRedacted
| Self::WebhookProcessingError
| Self::InvalidTenant
| Self::ExternalVaultFailed
| Self::AmountConversionFailed { .. }
| Self::SubscriptionError { .. } => StatusCode::INTERNAL_SERVER_ERROR,
Self::ReturnUrlUnavailable => StatusCode::SERVICE_UNAVAILABLE,
Self::ExternalConnectorError { status_code, .. } => {
StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
}
Self::IntegrityCheckFailed { .. } => StatusCode::INTERNAL_SERVER_ERROR,
Self::PaymentBlockedError { code, .. } => {
StatusCode::from_u16(*code).unwrap_or(StatusCode::OK)
}
Self::LockTimeout => StatusCode::LOCKED,
Self::ProfileAcquirerNotFound => StatusCode::NOT_FOUND,
}
}
fn error_response(&self) -> actix_web::HttpResponse {
use actix_web::http::header;
actix_web::HttpResponseBuilder::new(self.status_code())
.insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON))
.body(self.to_string())
}
}
impl From<serde_qs::Error> for StripeErrorCode {
fn from(item: serde_qs::Error) -> Self {
match item {
serde_qs::Error::Custom(s) => Self::SerdeQsError {
error_message: s,
param: None,
},
serde_qs::Error::Parse(param, position) => Self::SerdeQsError {
error_message: format!(
"parsing failed with error: '{param}' at position: {position}"
),
param: Some(param),
},
serde_qs::Error::Unsupported => Self::SerdeQsError {
error_message: "Given request format is not supported".to_owned(),
param: None,
},
serde_qs::Error::FromUtf8(_) => Self::SerdeQsError {
error_message: "Failed to parse request to from utf-8".to_owned(),
param: None,
},
serde_qs::Error::Io(_) => Self::SerdeQsError {
error_message: "Failed to parse request".to_owned(),
param: None,
},
serde_qs::Error::ParseInt(_) => Self::SerdeQsError {
error_message: "Failed to parse integer in request".to_owned(),
param: None,
},
|
crates/router/src/compatibility/stripe/errors.rs#chunk0
|
router
|
chunk
| null | null | null | 8,176
| null | null | null | null | null | null | null |
// Struct: TriggeredAttemptsAccumulator
// File: crates/analytics/src/frm/accumulator.rs
// Module: analytics
// Implementations: 1
// Traits: FrmMetricAccumulator
pub struct TriggeredAttemptsAccumulator
|
crates/analytics/src/frm/accumulator.rs
|
analytics
|
struct_definition
|
TriggeredAttemptsAccumulator
| 1
|
[
"FrmMetricAccumulator"
] | 52
| null | null | null | null | null | null | null |
// File: crates/euclid/src/dssa/graph.rs
// Module: euclid
// Public functions: 3
// Public structs: 1
use std::{fmt::Debug, sync::Weak};
use hyperswitch_constraint_graph as cgraph;
use rustc_hash::{FxHashMap, FxHashSet};
use crate::{
dssa::types,
frontend::dir,
types::{DataType, Metadata},
};
pub mod euclid_graph_prelude {
pub use hyperswitch_constraint_graph as cgraph;
pub use rustc_hash::{FxHashMap, FxHashSet};
pub use strum::EnumIter;
pub use crate::{
dssa::graph::*,
frontend::dir::{enums::*, DirKey, DirKeyKind, DirValue},
types::*,
};
}
impl cgraph::KeyNode for dir::DirKey {}
impl cgraph::NodeViz for dir::DirKey {
fn viz(&self) -> String {
self.kind.to_string()
}
}
impl cgraph::ValueNode for dir::DirValue {
type Key = dir::DirKey;
fn get_key(&self) -> Self::Key {
Self::get_key(self)
}
}
impl cgraph::NodeViz for dir::DirValue {
fn viz(&self) -> String {
match self {
Self::PaymentMethod(pm) => pm.to_string(),
Self::CardBin(bin) => bin.value.clone(),
Self::CardType(ct) => ct.to_string(),
Self::CardNetwork(cn) => cn.to_string(),
Self::PayLaterType(plt) => plt.to_string(),
Self::WalletType(wt) => wt.to_string(),
Self::UpiType(ut) => ut.to_string(),
Self::BankTransferType(btt) => btt.to_string(),
Self::BankRedirectType(brt) => brt.to_string(),
Self::BankDebitType(bdt) => bdt.to_string(),
Self::CryptoType(ct) => ct.to_string(),
Self::RewardType(rt) => rt.to_string(),
Self::PaymentAmount(amt) => amt.number.to_string(),
Self::PaymentCurrency(curr) => curr.to_string(),
Self::AuthenticationType(at) => at.to_string(),
Self::CaptureMethod(cm) => cm.to_string(),
Self::BusinessCountry(bc) => bc.to_string(),
Self::BillingCountry(bc) => bc.to_string(),
Self::Connector(conn) => conn.connector.to_string(),
Self::MetaData(mv) => format!("[{} = {}]", mv.key, mv.value),
Self::MandateAcceptanceType(mat) => mat.to_string(),
Self::MandateType(mt) => mt.to_string(),
Self::PaymentType(pt) => pt.to_string(),
Self::VoucherType(vt) => vt.to_string(),
Self::GiftCardType(gct) => gct.to_string(),
Self::BusinessLabel(bl) => bl.value.to_string(),
Self::SetupFutureUsage(sfu) => sfu.to_string(),
Self::CardRedirectType(crt) => crt.to_string(),
Self::RealTimePaymentType(rtpt) => rtpt.to_string(),
Self::OpenBankingType(ob) => ob.to_string(),
Self::MobilePaymentType(mpt) => mpt.to_string(),
Self::IssuerName(issuer_name) => issuer_name.value.clone(),
Self::IssuerCountry(issuer_country) => issuer_country.to_string(),
Self::CustomerDevicePlatform(customer_device_platform) => {
customer_device_platform.to_string()
}
Self::CustomerDeviceType(customer_device_type) => customer_device_type.to_string(),
Self::CustomerDeviceDisplaySize(customer_device_display_size) => {
customer_device_display_size.to_string()
}
Self::AcquirerCountry(acquirer_country) => acquirer_country.to_string(),
Self::AcquirerFraudRate(acquirer_fraud_rate) => acquirer_fraud_rate.number.to_string(),
}
}
}
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "type", content = "details", rename_all = "snake_case")]
pub enum AnalysisError<V: cgraph::ValueNode> {
Graph(cgraph::GraphError<V>),
AssertionTrace {
trace: Weak<cgraph::AnalysisTrace<V>>,
metadata: Metadata,
},
NegationTrace {
trace: Weak<cgraph::AnalysisTrace<V>>,
metadata: Vec<Metadata>,
},
}
impl<V: cgraph::ValueNode> AnalysisError<V> {
fn assertion_from_graph_error(metadata: &Metadata, graph_error: cgraph::GraphError<V>) -> Self {
match graph_error {
cgraph::GraphError::AnalysisError(trace) => Self::AssertionTrace {
trace,
metadata: metadata.clone(),
},
other => Self::Graph(other),
}
}
fn negation_from_graph_error(
metadata: Vec<&Metadata>,
graph_error: cgraph::GraphError<V>,
) -> Self {
match graph_error {
cgraph::GraphError::AnalysisError(trace) => Self::NegationTrace {
trace,
metadata: metadata.iter().map(|m| (*m).clone()).collect(),
},
other => Self::Graph(other),
}
}
}
#[derive(Debug)]
pub struct AnalysisContext {
keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>>,
}
impl AnalysisContext {
pub fn from_dir_values(vals: impl IntoIterator<Item = dir::DirValue>) -> Self {
let mut keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>> =
FxHashMap::default();
for dir_val in vals {
let key = dir_val.get_key();
let set = keywise_values.entry(key).or_default();
set.insert(dir_val);
}
Self { keywise_values }
}
pub fn insert(&mut self, value: dir::DirValue) {
self.keywise_values
.entry(value.get_key())
.or_default()
.insert(value);
}
pub fn remove(&mut self, value: dir::DirValue) {
let set = self.keywise_values.entry(value.get_key()).or_default();
set.remove(&value);
if set.is_empty() {
self.keywise_values.remove(&value.get_key());
}
}
}
impl cgraph::CheckingContext for AnalysisContext {
type Value = dir::DirValue;
fn from_node_values<L>(vals: impl IntoIterator<Item = L>) -> Self
where
L: Into<Self::Value>,
{
let mut keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>> =
FxHashMap::default();
for dir_val in vals.into_iter().map(L::into) {
let key = dir_val.get_key();
let set = keywise_values.entry(key).or_default();
set.insert(dir_val);
}
Self { keywise_values }
}
fn check_presence(
&self,
value: &cgraph::NodeValue<dir::DirValue>,
strength: cgraph::Strength,
) -> bool {
match value {
cgraph::NodeValue::Key(k) => {
self.keywise_values.contains_key(k) || matches!(strength, cgraph::Strength::Weak)
}
cgraph::NodeValue::Value(val) => {
let key = val.get_key();
let value_set = if let Some(set) = self.keywise_values.get(&key) {
set
} else {
return matches!(strength, cgraph::Strength::Weak);
};
match key.kind.get_type() {
DataType::EnumVariant | DataType::StrValue | DataType::MetadataValue => {
value_set.contains(val)
}
DataType::Number => val.get_num_value().is_some_and(|num_val| {
value_set.iter().any(|ctx_val| {
ctx_val
.get_num_value()
.is_some_and(|ctx_num_val| num_val.fits(&ctx_num_val))
})
}),
}
}
}
}
fn get_values_by_key(
&self,
key: &<Self::Value as cgraph::ValueNode>::Key,
) -> Option<Vec<Self::Value>> {
self.keywise_values
.get(key)
.map(|set| set.iter().cloned().collect())
}
}
pub trait CgraphExt {
fn key_analysis(
&self,
key: dir::DirKey,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>>;
fn value_analysis(
&self,
val: dir::DirValue,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>>;
fn check_value_validity(
&self,
val: dir::DirValue,
analysis_ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<bool, cgraph::GraphError<dir::DirValue>>;
fn key_value_analysis(
&self,
val: dir::DirValue,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>>;
fn assertion_analysis(
&self,
positive_ctx: &[(&dir::DirValue, &Metadata)],
analysis_ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>>;
fn negation_analysis(
&self,
negative_ctx: &[(&[dir::DirValue], &Metadata)],
analysis_ctx: &mut AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>>;
fn perform_context_analysis(
&self,
ctx: &types::ConjunctiveContext<'_>,
memo: &mut cgraph::Memoization<dir::DirValue>,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>>;
}
impl CgraphExt for cgraph::ConstraintGraph<dir::DirValue> {
fn key_analysis(
&self,
key: dir::DirKey,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>> {
self.value_map
.get(&cgraph::NodeValue::Key(key))
.map_or(Ok(()), |node_id| {
self.check_node(
ctx,
*node_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
memo,
cycle_map,
domains,
)
})
}
fn value_analysis(
&self,
val: dir::DirValue,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>> {
self.value_map
.get(&cgraph::NodeValue::Value(val))
.map_or(Ok(()), |node_id| {
self.check_node(
ctx,
*node_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
memo,
cycle_map,
domains,
)
})
}
fn check_value_validity(
&self,
val: dir::DirValue,
analysis_ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<bool, cgraph::GraphError<dir::DirValue>> {
let maybe_node_id = self.value_map.get(&cgraph::NodeValue::Value(val));
let node_id = if let Some(nid) = maybe_node_id {
nid
} else {
return Ok(false);
};
let result = self.check_node(
analysis_ctx,
*node_id,
cgraph::Relation::Positive,
cgraph::Strength::Weak,
memo,
cycle_map,
domains,
);
match result {
Ok(_) => Ok(true),
Err(e) => {
e.get_analysis_trace()?;
Ok(false)
}
}
}
fn key_value_analysis(
&self,
val: dir::DirValue,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>> {
self.key_analysis(val.get_key(), ctx, memo, cycle_map, domains)
.and_then(|_| self.value_analysis(val, ctx, memo, cycle_map, domains))
}
fn assertion_analysis(
&self,
positive_ctx: &[(&dir::DirValue, &Metadata)],
analysis_ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>> {
positive_ctx.iter().try_for_each(|(value, metadata)| {
self.key_value_analysis((*value).clone(), analysis_ctx, memo, cycle_map, domains)
.map_err(|e| AnalysisError::assertion_from_graph_error(metadata, e))
})
}
fn negation_analysis(
&self,
negative_ctx: &[(&[dir::DirValue], &Metadata)],
analysis_ctx: &mut AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>> {
let mut keywise_metadata: FxHashMap<dir::DirKey, Vec<&Metadata>> = FxHashMap::default();
let mut keywise_negation: FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>> =
FxHashMap::default();
for (values, metadata) in negative_ctx {
let mut metadata_added = false;
for dir_value in *values {
if !metadata_added {
keywise_metadata
.entry(dir_value.get_key())
.or_default()
.push(metadata);
metadata_added = true;
}
keywise_negation
.entry(dir_value.get_key())
.or_default()
.insert(dir_value);
}
}
for (key, negation_set) in keywise_negation {
let all_metadata = keywise_metadata.remove(&key).unwrap_or_default();
let first_metadata = all_metadata.first().copied().cloned().unwrap_or_default();
self.key_analysis(key.clone(), analysis_ctx, memo, cycle_map, domains)
.map_err(|e| AnalysisError::assertion_from_graph_error(&first_metadata, e))?;
let mut value_set = if let Some(set) = key.kind.get_value_set() {
set
} else {
continue;
};
value_set.retain(|v| !negation_set.contains(v));
for value in value_set {
analysis_ctx.insert(value.clone());
self.value_analysis(value.clone(), analysis_ctx, memo, cycle_map, domains)
.map_err(|e| {
AnalysisError::negation_from_graph_error(all_metadata.clone(), e)
})?;
analysis_ctx.remove(value);
}
}
Ok(())
}
fn perform_context_analysis(
&self,
ctx: &types::ConjunctiveContext<'_>,
memo: &mut cgraph::Memoization<dir::DirValue>,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>> {
let mut analysis_ctx = AnalysisContext::from_dir_values(
ctx.iter()
.filter_map(|ctx_val| ctx_val.value.get_assertion().cloned()),
);
let positive_ctx = ctx
.iter()
.filter_map(|ctx_val| {
ctx_val
.value
.get_assertion()
.map(|val| (val, ctx_val.metadata))
})
.collect::<Vec<_>>();
self.assertion_analysis(
&positive_ctx,
&analysis_ctx,
memo,
&mut cgraph::CycleCheck::new(),
domains,
)?;
let negative_ctx = ctx
.iter()
.filter_map(|ctx_val| {
ctx_val
.value
.get_negation()
.map(|vals| (vals, ctx_val.metadata))
})
.collect::<Vec<_>>();
self.negation_analysis(
&negative_ctx,
&mut analysis_ctx,
memo,
&mut cgraph::CycleCheck::new(),
domains,
)?;
Ok(())
}
}
#[cfg(test)]
mod test {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::ops::Deref;
use euclid_macros::knowledge;
use hyperswitch_constraint_graph::CycleCheck;
use super::*;
use crate::{dirval, frontend::dir::enums};
#[test]
fn test_strong_positive_relation_success() {
let graph = knowledge! {
PaymentMethod(Card) ->> CaptureMethod(Automatic);
PaymentMethod(not Wallet)
& PaymentMethod(not PayLater) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Card),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_strong_positive_relation_failure() {
let graph = knowledge! {
PaymentMethod(Card) ->> CaptureMethod(Automatic);
PaymentMethod(not Wallet) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([dirval!(CaptureMethod = Automatic)]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_strong_negative_relation_success() {
let graph = knowledge! {
PaymentMethod(Card) -> CaptureMethod(Automatic);
PaymentMethod(not Wallet) ->> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Card),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_strong_negative_relation_failure() {
let graph = knowledge! {
PaymentMethod(Card) -> CaptureMethod(Automatic);
PaymentMethod(not Wallet) ->> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Wallet),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_normal_one_of_failure() {
let graph = knowledge! {
PaymentMethod(Card) -> CaptureMethod(Automatic);
PaymentMethod(Wallet) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = PayLater),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(matches!(
*Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap())
.expect("Expected Arc"),
cgraph::AnalysisTrace::Value {
predecessors: Some(cgraph::error::ValueTracePredecessor::OneOf(_)),
..
}
));
}
#[test]
fn test_all_aggregator_success() {
let graph = knowledge! {
PaymentMethod(Card) & PaymentMethod(not Wallet) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(PaymentMethod = Card),
dirval!(CaptureMethod = Automatic),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_all_aggregator_failure() {
let graph = knowledge! {
PaymentMethod(Card) & PaymentMethod(not Wallet) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = PayLater),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_all_aggregator_mandatory_failure() {
let graph = knowledge! {
PaymentMethod(Card) & PaymentMethod(not Wallet) ->> CaptureMethod(Automatic);
};
let mut memo = cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = PayLater),
]),
&mut memo,
&mut CycleCheck::new(),
None,
);
assert!(matches!(
*Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap())
.expect("Expected Arc"),
cgraph::AnalysisTrace::Value {
predecessors: Some(cgraph::error::ValueTracePredecessor::Mandatory(_)),
..
}
));
}
#[test]
fn test_in_aggregator_success() {
let graph = knowledge! {
PaymentMethod(in [Card, Wallet]) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Wallet),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_in_aggregator_failure() {
let graph = knowledge! {
PaymentMethod(in [Card, Wallet]) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = PayLater),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_not_in_aggregator_success() {
let graph = knowledge! {
PaymentMethod(not in [Card, Wallet]) ->> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = PayLater),
dirval!(PaymentMethod = BankRedirect),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_not_in_aggregator_failure() {
let graph = knowledge! {
PaymentMethod(not in [Card, Wallet]) ->> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = PayLater),
dirval!(PaymentMethod = BankRedirect),
dirval!(PaymentMethod = Card),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_in_aggregator_failure_trace() {
let graph = knowledge! {
PaymentMethod(in [Card, Wallet]) ->> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = PayLater),
]),
memo,
&mut CycleCheck::new(),
None,
);
if let cgraph::AnalysisTrace::Value {
predecessors: Some(cgraph::error::ValueTracePredecessor::Mandatory(agg_error)),
..
} = Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap())
.expect("Expected arc")
.deref()
{
assert!(matches!(
*Weak::upgrade(agg_error.deref()).expect("Expected Arc"),
cgraph::AnalysisTrace::InAggregation {
found: Some(dir::DirValue::PaymentMethod(enums::PaymentMethod::PayLater)),
..
}
));
} else {
panic!("Failed unwrapping OnlyInAggregation trace from AnalysisTrace");
}
}
#[test]
fn test_memoization_in_kgraph() {
let mut builder = cgraph::ConstraintGraphBuilder::new();
let _node_1 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)),
None,
None::<()>,
);
let _node_2 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::BillingCountry(enums::BillingCountry::India)),
None,
None::<()>,
);
let _node_3 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::BusinessCountry(
enums::BusinessCountry::UnitedStatesOfAmerica,
)),
None,
None::<()>,
);
let mut memo = cgraph::Memoization::new();
let mut cycle_map = CycleCheck::new();
let _edge_1 = builder
.make_edge(
_node_1,
_node_2,
cgraph::Strength::Strong,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_2 = builder
.make_edge(
_node_2,
_node_3,
cgraph::Strength::Strong,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to an edge");
let graph = builder.build();
let _result = graph.key_value_analysis(
dirval!(BusinessCountry = UnitedStatesOfAmerica),
&AnalysisContext::from_dir_values([
dirval!(PaymentMethod = Wallet),
dirval!(BillingCountry = India),
dirval!(BusinessCountry = UnitedStatesOfAmerica),
]),
&mut memo,
&mut cycle_map,
None,
);
let _answer = memo
.get(&(
_node_3,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
))
.expect("Memoization not workng");
matches!(_answer, Ok(()));
}
#[test]
fn test_cycle_resolution_in_graph() {
let mut builder = cgraph::ConstraintGraphBuilder::new();
let _node_1 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)),
None,
None::<()>,
);
let _node_2 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)),
None,
None::<()>,
);
let mut memo = cgraph::Memoization::new();
let mut cycle_map = CycleCheck::new();
let _edge_1 = builder
.make_edge(
_node_1,
_node_2,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_2 = builder
.make_edge(
_node_2,
_node_1,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to an edge");
let graph = builder.build();
let _result = graph.key_value_analysis(
dirval!(PaymentMethod = Wallet),
&AnalysisContext::from_dir_values([
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = Card),
]),
&mut memo,
&mut cycle_map,
None,
);
assert!(_result.is_ok());
}
#[test]
fn test_cycle_resolution_in_graph1() {
let mut builder = cgraph::ConstraintGraphBuilder::new();
let _node_1 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(
enums::CaptureMethod::Automatic,
)),
None,
None::<()>,
);
let _node_2 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)),
None,
None::<()>,
);
let _node_3 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)),
None,
None::<()>,
);
let mut memo = cgraph::Memoization::new();
let mut cycle_map = CycleCheck::new();
let _edge_1 = builder
.make_edge(
_node_1,
_node_2,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_2 = builder
.make_edge(
_node_1,
_node_3,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_3 = builder
.make_edge(
_node_2,
_node_1,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_4 = builder
.make_edge(
_node_3,
_node_1,
cgraph::Strength::Strong,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let graph = builder.build();
let _result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Wallet),
dirval!(CaptureMethod = Automatic),
]),
&mut memo,
&mut cycle_map,
None,
);
assert!(_result.is_ok());
}
#[test]
fn test_cycle_resolution_in_graph2() {
let mut builder = cgraph::ConstraintGraphBuilder::new();
let _node_0 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::BillingCountry(
enums::BillingCountry::Afghanistan,
)),
None,
None::<()>,
);
let _node_1 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(
enums::CaptureMethod::Automatic,
)),
None,
None::<()>,
);
let _node_2 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)),
None,
None::<()>,
);
let _node_3 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)),
None,
None::<()>,
);
let _node_4 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentCurrency(enums::PaymentCurrency::USD)),
None,
None::<()>,
);
let mut memo = cgraph::Memoization::new();
let mut cycle_map = CycleCheck::new();
let _edge_1 = builder
.make_edge(
_node_0,
_node_1,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_2 = builder
.make_edge(
_node_1,
_node_2,
cgraph::Strength::Normal,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_3 = builder
.make_edge(
_node_1,
_node_3,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_4 = builder
.make_edge(
_node_3,
_node_4,
cgraph::Strength::Normal,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_5 = builder
.make_edge(
_node_2,
_node_4,
cgraph::Strength::Normal,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_6 = builder
.make_edge(
_node_4,
_node_1,
cgraph::Strength::Normal,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_7 = builder
.make_edge(
_node_4,
_node_0,
cgraph::Strength::Normal,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let graph = builder.build();
let _result = graph.key_value_analysis(
dirval!(BillingCountry = Afghanistan),
&AnalysisContext::from_dir_values([
dirval!(PaymentCurrency = USD),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Wallet),
dirval!(CaptureMethod = Automatic),
dirval!(BillingCountry = Afghanistan),
]),
&mut memo,
&mut cycle_map,
None,
);
assert!(_result.is_ok());
}
}
|
crates/euclid/src/dssa/graph.rs
|
euclid
|
full_file
| null | null | null | 8,135
| null | null | null | null | null | null | null |
// Function: filter_payment_methods
// File: crates/router/src/core/payments/payment_methods.rs
// Module: router
pub fn filter_payment_methods(
payment_method_type_details: hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector,
req: &api_models::payments::ListMethodsForPaymentsRequest,
resp: &mut Vec<
hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector,
>,
payment_intent: Option<&storage::PaymentIntent>,
address: Option<&hyperswitch_domain_models::address::AddressDetails>,
configs: &settings::Settings<RawSecret>,
) -> errors::CustomResult<(), errors::ApiErrorResponse>
|
crates/router/src/core/payments/payment_methods.rs
|
router
|
function_signature
| null | null | null | 143
|
filter_payment_methods
| null | null | null | null | null | null |
// File: crates/router/src/core/locker_migration.rs
// Module: router
// Public functions: 4
use ::payment_methods::controller::PaymentMethodsController;
#[cfg(feature = "v1")]
use api_models::enums as api_enums;
use api_models::locker_migration::MigrateCardResponse;
use common_utils::{errors::CustomResult, id_type};
#[cfg(feature = "v1")]
use diesel_models::enums as storage_enums;
#[cfg(feature = "v1")]
use error_stack::FutureExt;
use error_stack::ResultExt;
#[cfg(feature = "v1")]
use futures::TryFutureExt;
#[cfg(feature = "v1")]
use super::{errors::StorageErrorExt, payment_methods::cards};
use crate::{errors, routes::SessionState, services, types::domain};
#[cfg(feature = "v1")]
use crate::{services::logger, types::api};
#[cfg(feature = "v2")]
pub async fn rust_locker_migration(
_state: SessionState,
_merchant_id: &id_type::MerchantId,
) -> CustomResult<services::ApplicationResponse<MigrateCardResponse>, errors::ApiErrorResponse> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn rust_locker_migration(
state: SessionState,
merchant_id: &id_type::MerchantId,
) -> CustomResult<services::ApplicationResponse<MigrateCardResponse>, errors::ApiErrorResponse> {
use crate::db::customers::CustomerListConstraints;
let db = state.store.as_ref();
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
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let merchant_account = db
.find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
// Handle cases where the number of customers is greater than the limit
let constraints = CustomerListConstraints {
limit: u16::MAX,
offset: None,
};
let domain_customers = db
.list_customers_by_merchant_id(key_manager_state, merchant_id, &key_store, constraints)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let mut customers_moved = 0;
let mut cards_moved = 0;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
merchant_account.clone(),
key_store.clone(),
)));
for customer in domain_customers {
let result = db
.find_payment_method_by_customer_id_merchant_id_list(
key_manager_state,
&key_store,
&customer.customer_id,
merchant_id,
None,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.and_then(|pm| {
call_to_locker(
&state,
pm,
&customer.customer_id,
merchant_id,
&merchant_context,
)
})
.await?;
customers_moved += 1;
cards_moved += result;
}
Ok(services::api::ApplicationResponse::Json(
MigrateCardResponse {
status_code: "200".to_string(),
status_message: "Card migration completed".to_string(),
customers_moved,
cards_moved,
},
))
}
#[cfg(feature = "v1")]
pub async fn call_to_locker(
state: &SessionState,
payment_methods: Vec<domain::PaymentMethod>,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
merchant_context: &domain::MerchantContext,
) -> CustomResult<usize, errors::ApiErrorResponse> {
let mut cards_moved = 0;
for pm in payment_methods.into_iter().filter(|pm| {
matches!(
pm.get_payment_method_type(),
Some(storage_enums::PaymentMethod::Card)
)
}) {
let card = cards::get_card_from_locker(
state,
customer_id,
merchant_id,
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await;
let card = match card {
Ok(card) => card,
Err(err) => {
logger::error!("Failed to fetch card from Basilisk HS locker : {:?}", err);
continue;
}
};
let card_details = api::CardDetail {
card_number: card.card_number,
card_exp_month: card.card_exp_month,
card_exp_year: card.card_exp_year,
card_holder_name: card.name_on_card,
nick_name: card.nick_name.map(masking::Secret::new),
card_issuing_country: None,
card_network: None,
card_issuer: None,
card_type: None,
};
let pm_create = api::PaymentMethodCreate {
payment_method: pm.get_payment_method_type(),
payment_method_type: pm.get_payment_method_subtype(),
payment_method_issuer: pm.payment_method_issuer,
payment_method_issuer_code: pm.payment_method_issuer_code,
card: Some(card_details.clone()),
#[cfg(feature = "payouts")]
wallet: None,
#[cfg(feature = "payouts")]
bank_transfer: None,
metadata: pm.metadata,
customer_id: Some(pm.customer_id),
card_network: card.card_brand,
client_secret: None,
payment_method_data: None,
billing: None,
connector_mandate_details: None,
network_transaction_id: None,
};
let add_card_result = cards::PmCards{
state,
merchant_context,
}.add_card_hs(
pm_create,
&card_details,
customer_id,
api_enums::LockerChoice::HyperswitchCardVault,
Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Card migration failed for merchant_id: {merchant_id:?}, customer_id: {customer_id:?}, payment_method_id: {} ",
pm.payment_method_id
));
let (_add_card_rs_resp, _is_duplicate) = match add_card_result {
Ok(output) => output,
Err(err) => {
logger::error!("Failed to add card to Rust locker : {:?}", err);
continue;
}
};
cards_moved += 1;
logger::info!(
"Card migrated for merchant_id: {merchant_id:?}, customer_id: {customer_id:?}, payment_method_id: {} ",
pm.payment_method_id
);
}
Ok(cards_moved)
}
#[cfg(feature = "v2")]
pub async fn call_to_locker(
_state: &SessionState,
_payment_methods: Vec<domain::PaymentMethod>,
_customer_id: &id_type::CustomerId,
_merchant_id: &id_type::MerchantId,
_merchant_context: &domain::MerchantContext,
) -> CustomResult<usize, errors::ApiErrorResponse> {
todo!()
}
|
crates/router/src/core/locker_migration.rs
|
router
|
full_file
| null | null | null | 1,567
| null | null | null | null | null | null | null |
// Struct: BluesnapThreeDSecureInfo
// File: crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct BluesnapThreeDSecureInfo
|
crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
BluesnapThreeDSecureInfo
| 0
|
[] | 54
| null | null | null | null | null | null | null |
// Implementation: impl api::RefundExecute for for Coingate
// File: crates/hyperswitch_connectors/src/connectors/coingate.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Coingate
|
crates/hyperswitch_connectors/src/connectors/coingate.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 62
| null |
Coingate
|
api::RefundExecute for
| 0
| 0
| null | null |
// Implementation: impl api::revenue_recovery::BillingConnectorPaymentsSyncIntegration for for Stripebilling
// File: crates/hyperswitch_connectors/src/connectors/stripebilling.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::revenue_recovery::BillingConnectorPaymentsSyncIntegration for for Stripebilling
|
crates/hyperswitch_connectors/src/connectors/stripebilling.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 72
| null |
Stripebilling
|
api::revenue_recovery::BillingConnectorPaymentsSyncIntegration for
| 0
| 0
| null | null |
// Function: switch_profile_for_user_in_org_and_merchant
// File: crates/router/src/core/user.rs
// Module: router
pub fn switch_profile_for_user_in_org_and_merchant(
state: SessionState,
request: user_api::SwitchProfileRequest,
user_from_token: auth::UserFromToken,
) -> UserResponse<user_api::TokenResponse>
|
crates/router/src/core/user.rs
|
router
|
function_signature
| null | null | null | 78
|
switch_profile_for_user_in_org_and_merchant
| null | null | null | null | null | null |
// Implementation: impl SubmitEvidence for for Worldpayvantiv
// File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl SubmitEvidence for for Worldpayvantiv
|
crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Worldpayvantiv
|
SubmitEvidence for
| 0
| 0
| null | null |
// Implementation: impl api::PaymentSession for for Digitalvirgo
// File: crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSession for for Digitalvirgo
|
crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Digitalvirgo
|
api::PaymentSession for
| 0
| 0
| null | null |
// Struct: MifinityConnectorMetadataObject
// File: crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct MifinityConnectorMetadataObject
|
crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
MifinityConnectorMetadataObject
| 0
|
[] | 54
| null | null | null | null | null | null | null |
// Struct: GetPaymentIntentMetricRequest
// File: crates/api_models/src/analytics.rs
// Module: api_models
// Implementations: 0
pub struct GetPaymentIntentMetricRequest
|
crates/api_models/src/analytics.rs
|
api_models
|
struct_definition
|
GetPaymentIntentMetricRequest
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Implementation: impl TaxCalculationOverride
// File: crates/common_enums/src/enums.rs
// Module: common_enums
// Methods: 1 total (1 public)
impl TaxCalculationOverride
|
crates/common_enums/src/enums.rs
|
common_enums
|
impl_block
| null | null | null | 43
| null |
TaxCalculationOverride
| null | 1
| 1
| null | null |
// Implementation: impl ExternalAuthentication for for Threedsecureio
// File: crates/hyperswitch_connectors/src/connectors/threedsecureio.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl ExternalAuthentication for for Threedsecureio
|
crates/hyperswitch_connectors/src/connectors/threedsecureio.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Threedsecureio
|
ExternalAuthentication for
| 0
| 0
| null | null |
// Struct: WiseBankDetails
// File: crates/hyperswitch_connectors/src/connectors/wise/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct WiseBankDetails
|
crates/hyperswitch_connectors/src/connectors/wise/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
WiseBankDetails
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Implementation: impl api::RefundSync for for Boku
// File: crates/hyperswitch_connectors/src/connectors/boku.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundSync for for Boku
|
crates/hyperswitch_connectors/src/connectors/boku.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Boku
|
api::RefundSync for
| 0
| 0
| null | null |
// Struct: Authentication
// File: crates/hyperswitch_domain_models/src/authentication.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct Authentication
|
crates/hyperswitch_domain_models/src/authentication.rs
|
hyperswitch_domain_models
|
struct_definition
|
Authentication
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// Struct: AccessToken
// File: crates/hyperswitch_domain_models/src/router_data.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct AccessToken
|
crates/hyperswitch_domain_models/src/router_data.rs
|
hyperswitch_domain_models
|
struct_definition
|
AccessToken
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// Function: routing_retrieve_config
// File: crates/router/src/routes/routing.rs
// Module: router
pub fn routing_retrieve_config(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::RoutingId>,
) -> impl Responder
|
crates/router/src/routes/routing.rs
|
router
|
function_signature
| null | null | null | 66
|
routing_retrieve_config
| 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 |
// Struct: ContractBasedRoutingConfig
// File: crates/api_models/src/routing.rs
// Module: api_models
// Implementations: 2
// Traits: Default
pub struct ContractBasedRoutingConfig
|
crates/api_models/src/routing.rs
|
api_models
|
struct_definition
|
ContractBasedRoutingConfig
| 2
|
[
"Default"
] | 43
| null | null | null | null | null | null | null |
// Struct: CreateCustomerPaymentProfileRequest
// File: crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CreateCustomerPaymentProfileRequest
|
crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CreateCustomerPaymentProfileRequest
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Struct: Order
// File: crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Order
|
crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
Order
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Struct: FeesType
// File: crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct FeesType
|
crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
FeesType
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Function: log_payout
// File: crates/router/src/services/kafka.rs
// Module: router
pub fn log_payout(
&self,
payout: &KafkaPayout<'_>,
old_payout: Option<KafkaPayout<'_>>,
tenant_id: TenantID,
) -> MQResult<()>
|
crates/router/src/services/kafka.rs
|
router
|
function_signature
| null | null | null | 70
|
log_payout
| null | null | null | null | null | null |
// Implementation: impl api::PaymentAuthorize for for Razorpay
// File: crates/hyperswitch_connectors/src/connectors/razorpay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentAuthorize for for Razorpay
|
crates/hyperswitch_connectors/src/connectors/razorpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Razorpay
|
api::PaymentAuthorize for
| 0
| 0
| null | null |
// File: crates/smithy/src/lib.rs
// Module: smithy
// Public functions: 1
// crates/smithy/lib.rs - Fixed with proper optional type handling in flattening
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use smithy_core::{SmithyConstraint, SmithyEnumVariant, SmithyField};
use syn::{parse_macro_input, Attribute, DeriveInput, Fields, Lit, Meta, Variant};
/// Derive macro for generating Smithy models from Rust structs and enums
#[proc_macro_derive(SmithyModel, attributes(smithy))]
pub fn derive_smithy_model(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
match generate_smithy_impl(&input) {
Ok(tokens) => tokens.into(),
Err(err) => err.to_compile_error().into(),
}
}
fn generate_smithy_impl(input: &DeriveInput) -> syn::Result<TokenStream2> {
let name = &input.ident;
let (namespace, is_mixin) = extract_namespace_and_mixin(&input.attrs)?;
match &input.data {
syn::Data::Struct(data_struct) => {
generate_struct_impl(name, &namespace, data_struct, &input.attrs, is_mixin)
}
syn::Data::Enum(data_enum) => generate_enum_impl(name, &namespace, data_enum, &input.attrs),
_ => Err(syn::Error::new_spanned(
input,
"SmithyModel can only be derived for structs and enums",
)),
}
}
fn generate_struct_impl(
name: &syn::Ident,
namespace: &str,
data_struct: &syn::DataStruct,
attrs: &[Attribute],
is_mixin: bool,
) -> syn::Result<TokenStream2> {
let fields = extract_fields(&data_struct.fields)?;
let struct_doc = extract_documentation(attrs);
let struct_doc_expr = struct_doc
.as_ref()
.map(|doc| quote! { Some(#doc.to_string()) })
.unwrap_or(quote! { None });
let field_implementations = fields.iter().map(|field| {
let field_name = &field.name;
let value_type = &field.value_type;
let documentation = &field.documentation;
let constraints = &field.constraints;
let optional = field.optional;
let flatten = field.flatten;
if flatten {
// Extract the inner type from Option<T> if it's an optional type
let inner_type = if value_type.starts_with("Option<") && value_type.ends_with('>') {
let start_idx = "Option<".len();
let end_idx = value_type.len() - 1;
&value_type[start_idx..end_idx]
} else {
value_type
};
let inner_type_ident = syn::parse_str::<syn::Type>(inner_type).unwrap();
// For flattened fields, we merge the fields from the inner type
// but we don't add the field itself to the structure
quote! {
{
let flattened_model = <#inner_type_ident as smithy_core::SmithyModelGenerator>::generate_smithy_model();
let flattened_struct_name = stringify!(#inner_type_ident).to_string();
for (shape_name, shape) in flattened_model.shapes {
if shape_name == flattened_struct_name {
match shape {
smithy_core::SmithyShape::Structure { members: flattened_members, .. } |
smithy_core::SmithyShape::Union { members: flattened_members, .. } => {
members.extend(flattened_members);
}
_ => {
// Potentially handle other shapes or log a warning
}
}
} else {
shapes.insert(shape_name, shape);
}
}
}
}
} else {
let field_doc = documentation
.as_ref()
.map(|doc| quote! { Some(#doc.to_string()) })
.unwrap_or(quote! { None });
let mut all_constraints = constraints.clone();
if !optional && !all_constraints.iter().any(|c| matches!(c, SmithyConstraint::Required)) {
all_constraints.push(SmithyConstraint::Required);
}
let traits = if all_constraints.is_empty() {
quote! { vec![] }
} else {
let trait_tokens = all_constraints
.iter()
.map(|constraint| match constraint {
SmithyConstraint::Pattern(pattern) => quote! {
smithy_core::SmithyTrait::Pattern { pattern: #pattern.to_string() }
},
SmithyConstraint::Range(min, max) => {
let min_expr = min.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None });
let max_expr = max.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None });
quote! {
smithy_core::SmithyTrait::Range {
min: #min_expr,
max: #max_expr
}
}
},
SmithyConstraint::Length(min, max) => {
let min_expr = min.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None });
let max_expr = max.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None });
quote! {
smithy_core::SmithyTrait::Length {
min: #min_expr,
max: #max_expr
}
}
},
SmithyConstraint::Required => quote! {
smithy_core::SmithyTrait::Required
},
SmithyConstraint::HttpLabel => quote! {
smithy_core::SmithyTrait::HttpLabel
},
SmithyConstraint::HttpQuery(name) => quote! {
smithy_core::SmithyTrait::HttpQuery { name: #name.to_string() }
},
})
.collect::<Vec<_>>();
quote! { vec![#(#trait_tokens),*] }
};
quote! {
{
let (target_type, new_shapes) = smithy_core::types::resolve_type_and_generate_shapes(#value_type, &mut shapes).unwrap();
shapes.extend(new_shapes);
members.insert(#field_name.to_string(), smithy_core::SmithyMember {
target: target_type,
documentation: #field_doc,
traits: #traits,
});
}
}
}
});
let traits_expr = if is_mixin {
quote! { vec![smithy_core::SmithyTrait::Mixin] }
} else {
quote! { vec![] }
};
let expanded = quote! {
impl smithy_core::SmithyModelGenerator for #name {
fn generate_smithy_model() -> smithy_core::SmithyModel {
let mut shapes = std::collections::HashMap::new();
let mut members = std::collections::HashMap::new();
#(#field_implementations;)*
let shape = smithy_core::SmithyShape::Structure {
members,
documentation: #struct_doc_expr,
traits: #traits_expr
};
shapes.insert(stringify!(#name).to_string(), shape);
smithy_core::SmithyModel {
namespace: #namespace.to_string(),
shapes
}
}
}
};
Ok(expanded)
}
fn generate_enum_impl(
name: &syn::Ident,
namespace: &str,
data_enum: &syn::DataEnum,
attrs: &[Attribute],
) -> syn::Result<TokenStream2> {
let variants = extract_enum_variants(&data_enum.variants)?;
let serde_enum_attrs = parse_serde_enum_attributes(attrs)?;
let enum_doc = extract_documentation(attrs);
let enum_doc_expr = enum_doc
.as_ref()
.map(|doc| quote! { Some(#doc.to_string()) })
.unwrap_or(quote! { None });
// Check if this is a string enum (all variants are unit variants) or a union
let is_string_enum = variants.iter().all(|v| v.fields.is_empty());
if is_string_enum {
// Generate as Smithy enum
let variant_implementations = variants
.iter()
.map(|variant| {
let variant_name = &variant.name;
let variant_doc = variant
.documentation
.as_ref()
.map(|doc| quote! { Some(#doc.to_string()) })
.unwrap_or(quote! { None });
// Apply serde rename transformation if specified
let rename_all = serde_enum_attrs.rename_all.as_deref();
let transformed_name = if let Some(rename_pattern) = rename_all {
// Generate the transformation at compile time
let transformed = transform_variant_name(variant_name, Some(rename_pattern));
quote! { #transformed.to_string() }
} else {
quote! { #variant_name.to_string() }
};
quote! {
enum_values.insert(#transformed_name, smithy_core::SmithyEnumValue {
name: #transformed_name,
documentation: #variant_doc,
is_default: false,
});
}
})
.collect::<Vec<_>>();
let expanded = quote! {
impl smithy_core::SmithyModelGenerator for #name {
fn generate_smithy_model() -> smithy_core::SmithyModel {
let mut shapes = std::collections::HashMap::new();
let mut enum_values = std::collections::HashMap::new();
#(#variant_implementations)*
let shape = smithy_core::SmithyShape::Enum {
values: enum_values,
documentation: #enum_doc_expr,
traits: vec![]
};
shapes.insert(stringify!(#name).to_string(), shape);
smithy_core::SmithyModel {
namespace: #namespace.to_string(),
shapes
}
}
}
};
Ok(expanded)
} else {
// Generate as Smithy union
let variant_implementations = variants
.iter()
.filter_map(|variant| {
let variant_name = &variant.name;
let variant_doc = variant
.documentation
.as_ref()
.map(|doc| quote! { Some(#doc.to_string()) })
.unwrap_or(quote! { None });
let target_type_expr = if variant.fields.is_empty() {
// If there are no fields with `value_type`, this variant should be skipped.
return None;
} else if variant.fields.len() == 1 {
// Single field - reference the type directly instead of creating a wrapper
let field = &variant.fields[0];
let field_value_type = &field.value_type;
if field_value_type.is_empty() {
return None;
}
quote! {
{
let (target_type, new_shapes) = smithy_core::types::resolve_type_and_generate_shapes(#field_value_type, &mut shapes).unwrap();
shapes.extend(new_shapes);
target_type
}
}
} else {
// Multiple fields - create an inline structure
let inline_struct_members = variant.fields.iter().map(|field| {
let field_name = &field.name;
let field_value_type = &field.value_type;
let field_doc = field
.documentation
.as_ref()
.map(|doc| quote! { Some(#doc.to_string()) })
.unwrap_or(quote! { None });
let mut field_constraints = field.constraints.clone();
if !field.optional && !field_constraints.iter().any(|c| matches!(c, SmithyConstraint::Required)) {
field_constraints.push(SmithyConstraint::Required);
}
let field_traits = if field_constraints.is_empty() {
quote! { vec![] }
} else {
let trait_tokens = field_constraints
.iter()
.map(|constraint| match constraint {
SmithyConstraint::Pattern(pattern) => quote! {
smithy_core::SmithyTrait::Pattern { pattern: #pattern.to_string() }
},
SmithyConstraint::Range(min, max) => {
let min_expr = min.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None });
let max_expr = max.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None });
quote! {
smithy_core::SmithyTrait::Range {
min: #min_expr,
max: #max_expr
}
}
},
SmithyConstraint::Length(min, max) => {
let min_expr = min.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None });
let max_expr = max.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None });
quote! {
smithy_core::SmithyTrait::Length {
min: #min_expr,
max: #max_expr
}
}
},
SmithyConstraint::Required => quote! {
smithy_core::SmithyTrait::Required
},
SmithyConstraint::HttpLabel => quote! {
smithy_core::SmithyTrait::HttpLabel
},
SmithyConstraint::HttpQuery(name) => quote! {
smithy_core::SmithyTrait::HttpQuery { name: #name.to_string() }
},
})
.collect::<Vec<_>>();
quote! { vec![#(#trait_tokens),*] }
};
quote! {
{
let (field_target, field_shapes) = smithy_core::types::resolve_type_and_generate_shapes(#field_value_type, &mut shapes).unwrap();
shapes.extend(field_shapes);
inline_members.insert(#field_name.to_string(), smithy_core::SmithyMember {
target: field_target,
documentation: #field_doc,
traits: #field_traits,
});
}
}
});
quote! {
{
let inline_struct_name = format!("{}{}Data", stringify!(#name), #variant_name);
let mut inline_members = std::collections::HashMap::new();
#(#inline_struct_members)*
let inline_shape = smithy_core::SmithyShape::Structure {
members: inline_members,
documentation: None,
traits: vec![],
};
shapes.insert(inline_struct_name.clone(), inline_shape);
inline_struct_name
}
}
};
// Apply serde rename transformation if specified
let rename_all = serde_enum_attrs.rename_all.as_deref();
let transformed_name = if let Some(rename_pattern) = rename_all {
// Generate the transformation at compile time
let transformed = transform_variant_name(variant_name, Some(rename_pattern));
quote! { #transformed.to_string() }
} else {
quote! { #variant_name.to_string() }
};
Some(quote! {
let target_type = #target_type_expr;
members.insert(#transformed_name, smithy_core::SmithyMember {
target: target_type,
documentation: #variant_doc,
traits: vec![]
});
})
})
.collect::<Vec<_>>();
let expanded = quote! {
impl smithy_core::SmithyModelGenerator for #name {
fn generate_smithy_model() -> smithy_core::SmithyModel {
let mut shapes = std::collections::HashMap::new();
let mut members = std::collections::HashMap::new();
#(#variant_implementations;)*
let shape = smithy_core::SmithyShape::Union {
members,
documentation: #enum_doc_expr,
traits: vec![]
};
shapes.insert(stringify!(#name).to_string(), shape);
smithy_core::SmithyModel {
namespace: #namespace.to_string(),
shapes
}
}
}
};
Ok(expanded)
}
}
fn extract_namespace_and_mixin(attrs: &[Attribute]) -> syn::Result<(String, bool)> {
for attr in attrs {
if attr.path().is_ident("smithy") {
let mut namespace = None;
let mut mixin = false;
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("namespace") {
if let Ok(value) = meta.value() {
if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() {
namespace = Some(lit_str.value());
}
}
} else if meta.path.is_ident("mixin") {
if let Ok(value) = meta.value() {
if let Ok(Lit::Bool(lit_bool)) = value.parse::<Lit>() {
mixin = lit_bool.value;
}
}
}
Ok(())
})?; // Propagate parsing errors
return Ok((
namespace.unwrap_or_else(|| "com.hyperswitch.default".to_string()),
mixin,
));
}
}
Ok(("com.hyperswitch.default".to_string(), false))
}
fn extract_fields(fields: &Fields) -> syn::Result<Vec<SmithyField>> {
let mut smithy_fields = Vec::new();
match fields {
Fields::Named(fields_named) => {
for field in &fields_named.named {
let field_name = field.ident.as_ref().unwrap().to_string();
let field_attrs = parse_smithy_field_attributes(&field.attrs)?;
let serde_attrs = parse_serde_attributes(&field.attrs)?;
if let Some(value_type) = field_attrs.value_type {
let documentation = extract_documentation(&field.attrs);
let optional = value_type.trim().starts_with("Option<");
smithy_fields.push(SmithyField {
name: field_name,
value_type,
constraints: field_attrs.constraints,
documentation,
optional,
flatten: serde_attrs.flatten,
});
}
}
}
_ => {
return Err(syn::Error::new_spanned(
fields,
"Only named fields are supported",
))
}
}
Ok(smithy_fields)
}
fn extract_enum_variants(
variants: &syn::punctuated::Punctuated<Variant, syn::token::Comma>,
) -> syn::Result<Vec<SmithyEnumVariant>> {
let mut smithy_variants = Vec::new();
for variant in variants {
let variant_name = variant.ident.to_string();
let documentation = extract_documentation(&variant.attrs);
let variant_attrs = parse_smithy_field_attributes(&variant.attrs)?;
// Extract fields from the variant
let fields = match &variant.fields {
Fields::Unit => Vec::new(),
Fields::Named(fields_named) => {
let mut variant_fields = Vec::new();
for field in &fields_named.named {
let field_name = field.ident.as_ref().unwrap().to_string();
let field_attrs = parse_smithy_field_attributes(&field.attrs)?;
if let Some(value_type) = field_attrs.value_type {
let field_documentation = extract_documentation(&field.attrs);
let optional = value_type.trim().starts_with("Option<");
variant_fields.push(SmithyField {
name: field_name,
value_type,
constraints: field_attrs.constraints,
documentation: field_documentation,
optional,
flatten: false,
});
}
}
variant_fields
}
Fields::Unnamed(fields_unnamed) => {
let mut variant_fields = Vec::new();
for (index, field) in fields_unnamed.unnamed.iter().enumerate() {
let field_name = format!("field_{}", index);
let field_attrs = parse_smithy_field_attributes(&field.attrs)?;
// For single unnamed fields, use the variant attribute if field doesn't have one
let value_type = field_attrs
.value_type
.or_else(|| variant_attrs.value_type.clone());
if let Some(value_type) = value_type {
let field_documentation = extract_documentation(&field.attrs);
let optional = value_type.trim().starts_with("Option<");
variant_fields.push(SmithyField {
name: field_name,
value_type,
constraints: field_attrs.constraints,
documentation: field_documentation,
optional,
flatten: false,
});
}
}
variant_fields
}
};
smithy_variants.push(SmithyEnumVariant {
name: variant_name,
fields,
constraints: variant_attrs.constraints,
documentation,
});
}
Ok(smithy_variants)
}
#[derive(Default)]
struct SmithyFieldAttributes {
value_type: Option<String>,
constraints: Vec<SmithyConstraint>,
}
#[derive(Default)]
struct SerdeAttributes {
flatten: bool,
}
#[derive(Default)]
struct SerdeEnumAttributes {
rename_all: Option<String>,
}
fn parse_serde_attributes(attrs: &[Attribute]) -> syn::Result<SerdeAttributes> {
let mut serde_attributes = SerdeAttributes::default();
for attr in attrs {
if attr.path().is_ident("serde") {
if let Ok(list) = attr.meta.require_list() {
if list.path.is_ident("serde") {
for item in list.tokens.clone() {
if let Some(ident) = item.to_string().split_whitespace().next() {
if ident == "flatten" {
serde_attributes.flatten = true;
}
}
}
}
}
}
}
Ok(serde_attributes)
}
fn parse_serde_enum_attributes(attrs: &[Attribute]) -> syn::Result<SerdeEnumAttributes> {
let mut serde_enum_attributes = SerdeEnumAttributes::default();
for attr in attrs {
if attr.path().is_ident("serde") {
// Use more robust parsing that handles all serde attributes
let parse_result = attr.parse_nested_meta(|meta| {
if meta.path.is_ident("rename_all") {
if let Ok(value) = meta.value() {
if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() {
serde_enum_attributes.rename_all = Some(lit_str.value());
}
}
} else if meta.path.is_ident("tag") {
// Parse and ignore the tag attribute
if let Ok(value) = meta.value() {
let _ = value.parse::<Lit>();
}
} else if meta.path.is_ident("content") {
// Parse and ignore the content attribute
if let Ok(value) = meta.value() {
let _ = value.parse::<Lit>();
}
} else if meta.path.is_ident("rename") {
// Parse and ignore the rename attribute (used for enum renaming)
if let Ok(value) = meta.value() {
let _ = value.parse::<Lit>();
}
} else if meta.path.is_ident("deny_unknown_fields") {
// Handle deny_unknown_fields (no value needed)
// This is a flag attribute with no value
} else if meta.path.is_ident("skip_serializing") {
// Handle skip_serializing
} else if meta.path.is_ident("skip_deserializing") {
// Handle skip_deserializing
} else if meta.path.is_ident("skip_serializing_if") {
// Handle skip_serializing_if
if let Ok(value) = meta.value() {
let _ = value.parse::<syn::Expr>();
}
} else if meta.path.is_ident("default") {
// Handle default attribute
// Could have a value or be a flag
if meta.value().is_ok() {
let _ = meta.value().and_then(|v| v.parse::<syn::Expr>());
}
} else if meta.path.is_ident("flatten") {
// Handle flatten (flag attribute)
} else if meta.path.is_ident("untagged") {
// Handle untagged (flag attribute)
} else if meta.path.is_ident("bound") {
// Handle bound attribute
if let Ok(value) = meta.value() {
let _ = value.parse::<Lit>();
}
}
// Silently ignore any other serde attributes to prevent parsing errors
Ok(())
});
// If parsing failed, provide a more helpful error message
if let Err(e) = parse_result {
return Err(syn::Error::new_spanned(
attr,
format!("Failed to parse serde attribute: {}. This may be due to multiple serde attributes on separate lines. Consider consolidating them into a single #[serde(...)] attribute.", e)
));
}
}
}
Ok(serde_enum_attributes)
}
fn transform_variant_name(name: &str, rename_all: Option<&str>) -> String {
match rename_all {
Some("snake_case") => to_snake_case(name),
Some("camelCase") => to_camel_case(name),
Some("kebab-case") => to_kebab_case(name),
Some("PascalCase") => name.to_string(), // No change for PascalCase
Some("SCREAMING_SNAKE_CASE") => to_screaming_snake_case(name),
Some("lowercase") => name.to_lowercase(),
Some("UPPERCASE") => name.to_uppercase(),
_ => name.to_string(), // No transformation if no rename_all or unknown pattern
}
}
fn to_snake_case(input: &str) -> String {
let mut result = String::new();
let chars = input.chars();
for ch in chars {
if ch.is_uppercase() && !result.is_empty() {
// Add underscore before uppercase letters (except the first character)
result.push('_');
}
result.push(ch.to_lowercase().next().unwrap());
}
result
}
fn to_camel_case(input: &str) -> String {
let mut result = String::new();
let mut chars = input.chars();
// First character should be lowercase
if let Some(ch) = chars.next() {
result.push(ch.to_lowercase().next().unwrap());
}
// Rest of the characters remain the same
for ch in chars {
result.push(ch);
}
result
}
fn to_kebab_case(input: &str) -> String {
let mut result = String::new();
for ch in input.chars() {
if ch.is_uppercase() && !result.is_empty() {
// Add hyphen before uppercase letters (except the first character)
result.push('-');
}
result.push(ch.to_lowercase().next().unwrap());
}
result
}
fn to_screaming_snake_case(input: &str) -> String {
let mut result = String::new();
for ch in input.chars() {
if ch.is_uppercase() && !result.is_empty() {
// Add underscore before uppercase letters (except the first character)
result.push('_');
}
result.push(ch.to_uppercase().next().unwrap());
}
result
}
fn parse_smithy_field_attributes(attrs: &[Attribute]) -> syn::Result<SmithyFieldAttributes> {
let mut field_attributes = SmithyFieldAttributes::default();
for attr in attrs {
if attr.path().is_ident("smithy") {
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("value_type") {
if let Ok(value) = meta.value() {
if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() {
field_attributes.value_type = Some(lit_str.value());
}
}
} else if meta.path.is_ident("pattern") {
if let Ok(value) = meta.value() {
if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() {
field_attributes
.constraints
.push(SmithyConstraint::Pattern(lit_str.value()));
}
}
} else if meta.path.is_ident("range") {
if let Ok(value) = meta.value() {
if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() {
let range_str = lit_str.value();
match parse_range(&range_str) {
Ok((min, max)) => {
field_attributes
.constraints
.push(SmithyConstraint::Range(min, max));
}
Err(e) => {
return Err(syn::Error::new_spanned(
&meta.path,
format!("Invalid range: {}", e),
));
}
}
}
}
} else if meta.path.is_ident("length") {
if let Ok(value) = meta.value() {
if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() {
let length_str = lit_str.value();
match parse_length(&length_str) {
Ok((min, max)) => {
field_attributes
.constraints
.push(SmithyConstraint::Length(min, max));
}
Err(e) => {
return Err(syn::Error::new_spanned(
&meta.path,
format!("Invalid length: {}", e),
));
}
}
}
}
} else if meta.path.is_ident("required") {
field_attributes
.constraints
.push(SmithyConstraint::Required);
} else if meta.path.is_ident("http_label") {
field_attributes
.constraints
.push(SmithyConstraint::HttpLabel);
} else if meta.path.is_ident("http_query") {
if let Ok(value) = meta.value() {
if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() {
field_attributes
.constraints
.push(SmithyConstraint::HttpQuery(lit_str.value()));
}
}
}
Ok(())
})?;
}
}
// Automatically add Required for http_label fields
if field_attributes
.constraints
.iter()
.any(|c| matches!(c, SmithyConstraint::HttpLabel))
&& !field_attributes
.constraints
.iter()
.any(|c| matches!(c, SmithyConstraint::Required))
{
field_attributes
.constraints
.push(SmithyConstraint::Required);
}
Ok(field_attributes)
}
fn extract_documentation(attrs: &[Attribute]) -> Option<String> {
let mut docs = Vec::new();
for attr in attrs {
if attr.path().is_ident("doc") {
if let Meta::NameValue(meta_name_value) = &attr.meta {
if let syn::Expr::Lit(expr_lit) = &meta_name_value.value {
if let Lit::Str(lit_str) = &expr_lit.lit {
docs.push(lit_str.value().trim().to_string());
}
}
}
}
}
if docs.is_empty() {
None
} else {
Some(docs.join(" "))
}
}
fn parse_range(range_str: &str) -> Result<(Option<i64>, Option<i64>), String> {
if range_str.contains("..=") {
let parts: Vec<&str> = range_str.split("..=").collect();
if parts.len() != 2 {
return Err(
"Invalid range format: must be 'min..=max', '..=max', or 'min..='".to_string(),
);
}
let min = if parts[0].is_empty() {
None
} else {
Some(
parts[0]
.parse()
.map_err(|_| format!("Invalid range min: '{}'", parts[0]))?,
)
};
let max = if parts[1].is_empty() {
None
} else {
Some(
parts[1]
.parse()
.map_err(|_| format!("Invalid range max: '{}'", parts[1]))?,
)
};
Ok((min, max))
} else if range_str.contains("..") {
let parts: Vec<&str> = range_str.split("..").collect();
if parts.len() != 2 {
return Err(
"Invalid range format: must be 'min..max', '..max', or 'min..'".to_string(),
);
}
let min = if parts[0].is_empty() {
None
} else {
Some(
parts[0]
.parse()
.map_err(|_| format!("Invalid range min: '{}'", parts[0]))?,
)
};
let max = if parts[1].is_empty() {
None
} else {
Some(
parts[1]
.parse::<i64>()
.map_err(|_| format!("Invalid range max: '{}'", parts[1]))?
- 1,
)
};
Ok((min, max))
} else {
Err("Invalid range format: must contain '..' or '..='".to_string())
}
}
fn parse_length(length_str: &str) -> Result<(Option<u64>, Option<u64>), String> {
if length_str.contains("..=") {
let parts: Vec<&str> = length_str.split("..=").collect();
if parts.len() != 2 {
return Err(
"Invalid length format: must be 'min..=max', '..=max', or 'min..='".to_string(),
);
}
let min = if parts[0].is_empty() {
None
} else {
Some(
parts[0]
.parse()
.map_err(|_| format!("Invalid length min: '{}'", parts[0]))?,
)
};
let max = if parts[1].is_empty() {
None
} else {
Some(
parts[1]
.parse()
.map_err(|_| format!("Invalid length max: '{}'", parts[1]))?,
)
};
Ok((min, max))
} else if length_str.contains("..") {
let parts: Vec<&str> = length_str.split("..").collect();
if parts.len() != 2 {
return Err(
"Invalid length format: must be 'min..max', '..max', or 'min..'".to_string(),
);
}
let min = if parts[0].is_empty() {
None
} else {
Some(
parts[0]
.parse()
.map_err(|_| format!("Invalid length min: '{}'", parts[0]))?,
)
};
let max = if parts[1].is_empty() {
None
} else {
Some(
parts[1]
.parse::<u64>()
.map_err(|_| format!("Invalid length max: '{}'", parts[1]))?
- 1,
)
};
Ok((min, max))
} else {
Err("Invalid length format: must contain '..' or '..='".to_string())
}
}
|
crates/smithy/src/lib.rs
|
smithy
|
full_file
| null | null | null | 7,389
| null | null | null | null | null | null | null |
// Struct: CreditCardData
// File: crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CreditCardData
|
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CreditCardData
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// Function: get_dispute_filter_for_dimension
// File: crates/analytics/src/disputes/filters.rs
// Module: analytics
pub fn get_dispute_filter_for_dimension<T>(
dimension: DisputeDimensions,
auth: &AuthInfo,
time_range: &TimeRange,
pool: &T,
) -> FiltersResult<Vec<DisputeFilterRow>>
where
T: AnalyticsDataSource + DisputeFilterAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
|
crates/analytics/src/disputes/filters.rs
|
analytics
|
function_signature
| null | null | null | 138
|
get_dispute_filter_for_dimension
| null | null | null | null | null | null |
// File: crates/diesel_models/src/role.rs
// Module: diesel_models
// Public structs: 3
use common_utils::id_type;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
use crate::{enums, schema::roles};
#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]
#[diesel(table_name = roles, primary_key(role_id), check_for_backend(diesel::pg::Pg))]
pub struct Role {
pub role_name: String,
pub role_id: String,
pub merchant_id: Option<id_type::MerchantId>,
pub org_id: id_type::OrganizationId,
#[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)]
pub groups: Vec<enums::PermissionGroup>,
pub scope: enums::RoleScope,
pub created_at: PrimitiveDateTime,
pub created_by: String,
pub last_modified_at: PrimitiveDateTime,
pub last_modified_by: String,
pub entity_type: enums::EntityType,
pub profile_id: Option<id_type::ProfileId>,
pub tenant_id: id_type::TenantId,
}
#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = roles)]
pub struct RoleNew {
pub role_name: String,
pub role_id: String,
pub merchant_id: Option<id_type::MerchantId>,
pub org_id: id_type::OrganizationId,
#[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)]
pub groups: Vec<enums::PermissionGroup>,
pub scope: enums::RoleScope,
pub created_at: PrimitiveDateTime,
pub created_by: String,
pub last_modified_at: PrimitiveDateTime,
pub last_modified_by: String,
pub entity_type: enums::EntityType,
pub profile_id: Option<id_type::ProfileId>,
pub tenant_id: id_type::TenantId,
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = roles)]
pub struct RoleUpdateInternal {
groups: Option<Vec<enums::PermissionGroup>>,
role_name: Option<String>,
last_modified_by: String,
last_modified_at: PrimitiveDateTime,
}
pub enum RoleUpdate {
UpdateDetails {
groups: Option<Vec<enums::PermissionGroup>>,
role_name: Option<String>,
last_modified_at: PrimitiveDateTime,
last_modified_by: String,
},
}
impl From<RoleUpdate> for RoleUpdateInternal {
fn from(value: RoleUpdate) -> Self {
match value {
RoleUpdate::UpdateDetails {
groups,
role_name,
last_modified_by,
last_modified_at,
} => Self {
groups,
role_name,
last_modified_at,
last_modified_by,
},
}
}
}
#[derive(Clone, Debug)]
pub enum ListRolesByEntityPayload {
Profile(id_type::MerchantId, id_type::ProfileId),
Merchant(id_type::MerchantId),
Organization,
}
|
crates/diesel_models/src/role.rs
|
diesel_models
|
full_file
| null | null | null | 661
| null | null | null | null | null | null | null |
// Function: get_three_ds_decision_rule_keys
// File: crates/euclid_wasm/src/lib.rs
// Module: euclid_wasm
pub fn get_three_ds_decision_rule_keys() -> JsResult
|
crates/euclid_wasm/src/lib.rs
|
euclid_wasm
|
function_signature
| null | null | null | 43
|
get_three_ds_decision_rule_keys
| null | null | null | null | null | null |
// Function: update_resource
// File: crates/storage_impl/src/kv_router_store.rs
// Module: storage_impl
pub fn update_resource<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
update_resource_fut: R,
updated_resource: M,
UpdateResourceParams {
updateable,
operation,
}: UpdateResourceParams<'_>,
) -> error_stack::Result<D, errors::StorageError>
where
D: Debug + Sync + Conversion,
M: StorageModel<D>,
R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send,
|
crates/storage_impl/src/kv_router_store.rs
|
storage_impl
|
function_signature
| null | null | null | 152
|
update_resource
| null | null | null | null | null | null |
// Function: find_optional_by_address_id
// File: crates/diesel_models/src/query/address.rs
// Module: diesel_models
pub fn find_optional_by_address_id(
conn: &PgPooledConn,
address_id: &str,
) -> StorageResult<Option<Self>>
|
crates/diesel_models/src/query/address.rs
|
diesel_models
|
function_signature
| null | null | null | 59
|
find_optional_by_address_id
| null | null | null | null | null | null |
// Struct: ThreeDs
// File: crates/hyperswitch_connectors/src/connectors/payme/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ThreeDs
|
crates/hyperswitch_connectors/src/connectors/payme/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ThreeDs
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Function: find_by_merchant_id_fingerprint_id
// File: crates/diesel_models/src/query/blocklist_fingerprint.rs
// Module: diesel_models
pub fn find_by_merchant_id_fingerprint_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> StorageResult<Self>
|
crates/diesel_models/src/query/blocklist_fingerprint.rs
|
diesel_models
|
function_signature
| null | null | null | 81
|
find_by_merchant_id_fingerprint_id
| null | null | null | null | null | null |
// Struct: CoingateRouterData
// File: crates/hyperswitch_connectors/src/connectors/coingate/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CoingateRouterData<T>
|
crates/hyperswitch_connectors/src/connectors/coingate/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CoingateRouterData
| 0
|
[] | 54
| null | null | null | null | null | null | null |
pub id: String,
pub amount: i64,
pub currency: String,
pub charge: String,
pub status: Shift4RefundStatus,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Shift4RefundStatus {
Successful,
Processing,
#[default]
Failed,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
..item.data
})
}
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct ErrorResponse {
pub error: ApiErrorResponse,
}
#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq, Serialize)]
pub struct ApiErrorResponse {
pub code: Option<String>,
pub message: String,
}
pub fn is_transaction_event(event: &Shift4WebhookEvent) -> bool {
matches!(
event,
Shift4WebhookEvent::ChargeCaptured
| Shift4WebhookEvent::ChargeFailed
| Shift4WebhookEvent::ChargeSucceeded
| Shift4WebhookEvent::ChargeUpdated
)
}
pub fn is_refund_event(event: &Shift4WebhookEvent) -> bool {
matches!(event, Shift4WebhookEvent::ChargeRefunded)
}
impl From<Shift4WebhookEvent> for IncomingWebhookEvent {
fn from(event: Shift4WebhookEvent) -> Self {
match event {
Shift4WebhookEvent::ChargeSucceeded | Shift4WebhookEvent::ChargeUpdated => {
//reference : https://dev.shift4.com/docs/api#event-types
Self::PaymentIntentProcessing
}
Shift4WebhookEvent::ChargeCaptured => Self::PaymentIntentSuccess,
Shift4WebhookEvent::ChargeFailed => Self::PaymentIntentFailure,
Shift4WebhookEvent::ChargeRefunded => Self::RefundSuccess,
Shift4WebhookEvent::Unknown => Self::EventNotSupported,
}
}
}
|
crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs#chunk1
|
hyperswitch_connectors
|
chunk
| null | null | null | 641
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_interfaces/src/api.rs
// Module: hyperswitch_interfaces
//! API interface
/// authentication module
pub mod authentication;
/// authentication_v2 module
pub mod authentication_v2;
pub mod disputes;
pub mod disputes_v2;
pub mod files;
pub mod files_v2;
#[cfg(feature = "frm")]
pub mod fraud_check;
#[cfg(feature = "frm")]
pub mod fraud_check_v2;
pub mod payments;
pub mod payments_v2;
#[cfg(feature = "payouts")]
pub mod payouts;
#[cfg(feature = "payouts")]
pub mod payouts_v2;
pub mod refunds;
pub mod refunds_v2;
pub mod revenue_recovery;
pub mod revenue_recovery_v2;
pub mod subscriptions;
pub mod subscriptions_v2;
pub mod vault;
pub mod vault_v2;
use std::fmt::Debug;
use common_enums::{
enums::{CallConnectorAction, CaptureMethod, EventClass, PaymentAction, PaymentMethodType},
PaymentMethod,
};
use common_utils::{
errors::CustomResult,
request::{Method, Request, RequestContent},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
connector_endpoints::Connectors,
errors::api_error_response::ApiErrorResponse,
payment_method_data::PaymentMethodData,
router_data::{
AccessToken, AccessTokenAuthenticationResponse, ConnectorAuthType, ErrorResponse,
RouterData,
},
router_data_v2::{
flow_common_types::{AuthenticationTokenFlowData, WebhookSourceVerifyData},
AccessTokenFlowData, MandateRevokeFlowData, UasFlowData,
},
router_flow_types::{
mandate_revoke::MandateRevoke, AccessTokenAuth, AccessTokenAuthentication, Authenticate,
AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, VerifyWebhookSource,
},
router_request_types::{
unified_authentication_service::{
UasAuthenticationRequestData, UasAuthenticationResponseData,
UasConfirmationRequestData, UasPostAuthenticationRequestData,
UasPreAuthenticationRequestData,
},
AccessTokenAuthenticationRequestData, AccessTokenRequestData, MandateRevokeRequestData,
VerifyWebhookSourceRequestData,
},
router_response_types::{
ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, SupportedPaymentMethods,
VerifyWebhookSourceResponseData,
},
};
use masking::Maskable;
use serde_json::json;
#[cfg(feature = "frm")]
pub use self::fraud_check::*;
#[cfg(feature = "frm")]
pub use self::fraud_check_v2::*;
#[cfg(feature = "payouts")]
pub use self::payouts::*;
#[cfg(feature = "payouts")]
pub use self::payouts_v2::*;
pub use self::{payments::*, refunds::*, vault::*, vault_v2::*};
use crate::{
api::subscriptions::Subscriptions, connector_integration_v2::ConnectorIntegrationV2, consts,
errors, events::connector_api_logs::ConnectorEvent, metrics, types, webhooks,
};
/// Connector trait
pub trait Connector:
Send
+ Refund
+ Payment
+ ConnectorRedirectResponse
+ webhooks::IncomingWebhook
+ ConnectorAccessToken
+ ConnectorAuthenticationToken
+ disputes::Dispute
+ files::FileUpload
+ ConnectorTransactionId
+ Payouts
+ ConnectorVerifyWebhookSource
+ FraudCheck
+ ConnectorMandateRevoke
+ authentication::ExternalAuthentication
+ TaxCalculation
+ UnifiedAuthenticationService
+ revenue_recovery::RevenueRecovery
+ ExternalVault
+ Subscriptions
{
}
impl<
T: Refund
+ Payment
+ ConnectorRedirectResponse
+ Send
+ webhooks::IncomingWebhook
+ ConnectorAccessToken
+ ConnectorAuthenticationToken
+ disputes::Dispute
+ files::FileUpload
+ ConnectorTransactionId
+ Payouts
+ ConnectorVerifyWebhookSource
+ FraudCheck
+ ConnectorMandateRevoke
+ authentication::ExternalAuthentication
+ TaxCalculation
+ UnifiedAuthenticationService
+ revenue_recovery::RevenueRecovery
+ ExternalVault
+ Subscriptions,
> Connector for T
{
}
/// Alias for Box<&'static (dyn Connector + Sync)>
pub type BoxedConnector = Box<&'static (dyn Connector + Sync)>;
/// type BoxedConnectorIntegration
pub type BoxedConnectorIntegration<'a, T, Req, Resp> =
Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>;
/// trait ConnectorIntegrationAny
pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static {
/// fn get_connector_integration
fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>;
}
impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S
where
S: ConnectorIntegration<T, Req, Resp> + Send + Sync,
{
fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp> {
Box::new(self)
}
}
/// trait ConnectorIntegration
pub trait ConnectorIntegration<T, Req, Resp>:
ConnectorIntegrationAny<T, Req, Resp> + Sync + ConnectorCommon
{
/// fn get_headers
fn get_headers(
&self,
_req: &RouterData<T, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(vec![])
}
/// fn get_content_type
fn get_content_type(&self) -> &'static str {
mime::APPLICATION_JSON.essence_str()
}
/// fn get_content_type
fn get_accept_type(&self) -> &'static str {
mime::APPLICATION_JSON.essence_str()
}
/// primarily used when creating signature based on request method of payment flow
fn get_http_method(&self) -> Method {
Method::Post
}
/// fn get_url
fn get_url(
&self,
_req: &RouterData<T, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(String::new())
}
/// fn get_request_body
fn get_request_body(
&self,
_req: &RouterData<T, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Ok(RequestContent::Json(Box::new(json!(r#"{}"#))))
}
/// fn get_request_form_data
fn get_request_form_data(
&self,
_req: &RouterData<T, Req, Resp>,
) -> CustomResult<Option<reqwest::multipart::Form>, errors::ConnectorError> {
Ok(None)
}
/// fn build_request
fn build_request(
&self,
req: &RouterData<T, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
metrics::UNIMPLEMENTED_FLOW.add(
1,
router_env::metric_attributes!(("connector", req.connector.clone())),
);
Ok(None)
}
/// fn handle_response
fn handle_response(
&self,
data: &RouterData<T, Req, Resp>,
event_builder: Option<&mut ConnectorEvent>,
_res: types::Response,
) -> CustomResult<RouterData<T, Req, Resp>, errors::ConnectorError>
where
T: Clone,
Req: Clone,
Resp: Clone,
{
event_builder.map(|e| e.set_error(json!({"error": "Not Implemented"})));
Ok(data.clone())
}
/// fn get_error_response
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
Ok(ErrorResponse::get_not_implemented())
}
/// fn get_5xx_error_response
fn get_5xx_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
let error_message = match res.status_code {
500 => "internal_server_error",
501 => "not_implemented",
502 => "bad_gateway",
503 => "service_unavailable",
504 => "gateway_timeout",
505 => "http_version_not_supported",
506 => "variant_also_negotiates",
507 => "insufficient_storage",
508 => "loop_detected",
510 => "not_extended",
511 => "network_authentication_required",
_ => "unknown_error",
};
Ok(ErrorResponse {
code: res.status_code.to_string(),
message: error_message.to_string(),
reason: String::from_utf8(res.response.to_vec()).ok(),
status_code: res.status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
/// whenever capture sync is implemented at the connector side, this method should be overridden
fn get_multiple_capture_sync_method(
&self,
) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("multiple capture sync".into()).into())
}
/// fn get_certificate
fn get_certificate(
&self,
_req: &RouterData<T, Req, Resp>,
) -> CustomResult<Option<String>, errors::ConnectorError> {
Ok(None)
}
/// fn get_certificate_key
fn get_certificate_key(
&self,
_req: &RouterData<T, Req, Resp>,
) -> CustomResult<Option<String>, errors::ConnectorError> {
Ok(None)
}
}
/// Sync Methods for multiple captures
#[derive(Debug)]
pub enum CaptureSyncMethod {
/// For syncing multiple captures individually
Individual,
/// For syncing multiple captures together
Bulk,
}
/// Connector accepted currency unit as either "Base" or "Minor"
#[derive(Debug)]
pub enum CurrencyUnit {
/// Base currency unit
Base,
/// Minor currency unit
Minor,
}
/// The trait that provides the common
pub trait ConnectorCommon {
/// Name of the connector (in lowercase).
fn id(&self) -> &'static str;
/// Connector accepted currency unit as either "Base" or "Minor"
fn get_currency_unit(&self) -> CurrencyUnit {
CurrencyUnit::Minor // Default implementation should be remove once it is implemented in all connectors
}
/// HTTP header used for authorization.
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(Vec::new())
}
/// HTTP `Content-Type` to be used for POST requests.
/// Defaults to `application/json`.
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
// FIXME write doc - think about this
// fn headers(&self) -> Vec<(&str, &str)>;
/// The base URL for interacting with the connector's API.
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str;
/// common error response for a connector if it is same in all case
fn build_error_response(
&self,
res: types::Response,
_event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
Ok(ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
message: consts::NO_ERROR_MESSAGE.to_string(),
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
/// The trait that provides specifications about the connector
pub trait ConnectorSpecifications {
/// Details related to payment method supported by the connector
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
None
}
/// Supported webhooks flows
fn get_supported_webhook_flows(&self) -> Option<&'static [EventClass]> {
None
}
/// About the connector
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
None
}
/// Check if connector should make another request to create an access token
/// Connectors should override this method if they require an authentication token to create a new access token
fn authentication_token_for_token_creation(&self) -> bool {
false
}
/// Check if connector should make another request to create an customer
/// Connectors should override this method if they require to create a connector customer
fn should_call_connector_customer(
&self,
_payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> bool {
false
}
#[cfg(not(feature = "v2"))]
/// Generate connector request reference ID
fn generate_connector_request_reference_id(
&self,
_payment_intent: &hyperswitch_domain_models::payments::PaymentIntent,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
is_config_enabled_to_send_payment_id_as_connector_request_id: bool,
) -> String {
// Send payment_id if config is enabled for a merchant, else send attempt_id
if is_config_enabled_to_send_payment_id_as_connector_request_id {
payment_attempt.payment_id.get_string_repr().to_owned()
} else {
payment_attempt.attempt_id.to_owned()
}
}
#[cfg(feature = "v2")]
/// Generate connector request reference ID
fn generate_connector_request_reference_id(
&self,
payment_intent: &hyperswitch_domain_models::payments::PaymentIntent,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> String {
payment_intent
.merchant_reference_id
.as_ref()
.map(|id| id.get_string_repr().to_owned())
.unwrap_or_else(|| payment_attempt.id.get_string_repr().to_owned())
}
}
/// Extended trait for connector common to allow functions with generic type
pub trait ConnectorCommonExt<Flow, Req, Resp>:
ConnectorCommon + ConnectorIntegration<Flow, Req, Resp>
{
/// common header builder when every request for the connector have same headers
fn build_headers(
&self,
_req: &RouterData<Flow, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(Vec::new())
}
}
/// trait ConnectorMandateRevoke
pub trait ConnectorMandateRevoke:
ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>
{
}
/// trait ConnectorMandateRevokeV2
pub trait ConnectorMandateRevokeV2:
ConnectorIntegrationV2<
MandateRevoke,
MandateRevokeFlowData,
MandateRevokeRequestData,
MandateRevokeResponseData,
>
{
}
/// trait ConnectorAuthenticationToken
pub trait ConnectorAuthenticationToken:
ConnectorIntegration<
AccessTokenAuthentication,
AccessTokenAuthenticationRequestData,
AccessTokenAuthenticationResponse,
>
{
}
/// trait ConnectorAuthenticationTokenV2
pub trait ConnectorAuthenticationTokenV2:
ConnectorIntegrationV2<
AccessTokenAuthentication,
AuthenticationTokenFlowData,
AccessTokenAuthenticationRequestData,
AccessTokenAuthenticationResponse,
>
{
}
/// trait ConnectorAccessToken
pub trait ConnectorAccessToken:
ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
{
}
/// trait ConnectorAccessTokenV2
pub trait ConnectorAccessTokenV2:
ConnectorIntegrationV2<AccessTokenAuth, AccessTokenFlowData, AccessTokenRequestData, AccessToken>
{
}
/// trait ConnectorVerifyWebhookSource
pub trait ConnectorVerifyWebhookSource:
ConnectorIntegration<
VerifyWebhookSource,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
>
{
}
/// trait ConnectorVerifyWebhookSourceV2
pub trait ConnectorVerifyWebhookSourceV2:
ConnectorIntegrationV2<
VerifyWebhookSource,
WebhookSourceVerifyData,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
>
{
}
/// trait UnifiedAuthenticationService
pub trait UnifiedAuthenticationService:
ConnectorCommon
+ UasPreAuthentication
+ UasPostAuthentication
+ UasAuthenticationConfirmation
+ UasAuthentication
{
}
/// trait UasPreAuthentication
pub trait UasPreAuthentication:
ConnectorIntegration<
PreAuthenticate,
UasPreAuthenticationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasPostAuthentication
pub trait UasPostAuthentication:
ConnectorIntegration<
PostAuthenticate,
UasPostAuthenticationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasAuthenticationConfirmation
pub trait UasAuthenticationConfirmation:
ConnectorIntegration<
AuthenticationConfirmation,
UasConfirmationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasAuthentication
pub trait UasAuthentication:
ConnectorIntegration<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData>
{
}
/// trait UnifiedAuthenticationServiceV2
pub trait UnifiedAuthenticationServiceV2:
ConnectorCommon
+ UasPreAuthenticationV2
+ UasPostAuthenticationV2
+ UasAuthenticationV2
+ UasAuthenticationConfirmationV2
{
}
///trait UasPreAuthenticationV2
pub trait UasPreAuthenticationV2:
ConnectorIntegrationV2<
PreAuthenticate,
UasFlowData,
UasPreAuthenticationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasPostAuthenticationV2
pub trait UasPostAuthenticationV2:
ConnectorIntegrationV2<
PostAuthenticate,
UasFlowData,
UasPostAuthenticationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasAuthenticationConfirmationV2
pub trait UasAuthenticationConfirmationV2:
ConnectorIntegrationV2<
AuthenticationConfirmation,
UasFlowData,
UasConfirmationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasAuthenticationV2
pub trait UasAuthenticationV2:
ConnectorIntegrationV2<
Authenticate,
UasFlowData,
UasAuthenticationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait ConnectorValidation
pub trait ConnectorValidation: ConnectorCommon + ConnectorSpecifications {
/// Validate, the payment request against the connector supported features
fn validate_connector_against_payment_request(
&self,
capture_method: Option<CaptureMethod>,
payment_method: PaymentMethod,
pmt: Option<PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
let is_default_capture_method =
[CaptureMethod::Automatic, CaptureMethod::SequentialAutomatic]
.contains(&capture_method);
let is_feature_supported = match self.get_supported_payment_methods() {
Some(supported_payment_methods) => {
let connector_payment_method_type_info = get_connector_payment_method_type_info(
supported_payment_methods,
payment_method,
pmt,
self.id(),
)?;
connector_payment_method_type_info
.map(|payment_method_type_info| {
payment_method_type_info
.supported_capture_methods
.contains(&capture_method)
})
.unwrap_or(true)
}
None => is_default_capture_method,
};
if is_feature_supported {
Ok(())
} else {
Err(errors::ConnectorError::NotSupported {
message: capture_method.to_string(),
connector: self.id(),
}
.into())
}
}
/// fn validate_mandate_payment
fn validate_mandate_payment(
&self,
pm_type: Option<PaymentMethodType>,
_pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let connector = self.id();
match pm_type {
Some(pm_type) => Err(errors::ConnectorError::NotSupported {
message: format!("{pm_type} mandate payment"),
connector,
}
.into()),
None => Err(errors::ConnectorError::NotSupported {
message: " mandate payment".to_string(),
connector,
}
.into()),
}
}
/// fn validate_psync_reference_id
fn validate_psync_reference_id(
&self,
data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData,
_is_three_ds: bool,
_status: common_enums::enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
data.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)
.map(|_| ())
}
/// fn is_webhook_source_verification_mandatory
fn is_webhook_source_verification_mandatory(&self) -> bool {
false
}
}
/// trait ConnectorRedirectResponse
pub trait ConnectorRedirectResponse {
/// fn get_flow_type
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
_action: PaymentAction,
) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
Ok(CallConnectorAction::Avoid)
}
}
/// Empty trait for when payouts feature is disabled
#[cfg(not(feature = "payouts"))]
pub trait Payouts {}
/// Empty trait for when payouts feature is disabled
#[cfg(not(feature = "payouts"))]
pub trait PayoutsV2 {}
/// Empty trait for when frm feature is disabled
#[cfg(not(feature = "frm"))]
pub trait FraudCheck {}
/// Empty trait for when frm feature is disabled
#[cfg(not(feature = "frm"))]
pub trait FraudCheckV2 {}
fn get_connector_payment_method_type_info(
supported_payment_method: &SupportedPaymentMethods,
payment_method: PaymentMethod,
payment_method_type: Option<PaymentMethodType>,
connector: &'static str,
) -> CustomResult<Option<PaymentMethodDetails>, errors::ConnectorError> {
let payment_method_details =
supported_payment_method
.get(&payment_method)
.ok_or_else(|| errors::ConnectorError::NotSupported {
message: payment_method.to_string(),
connector,
})?;
payment_method_type
.map(|pmt| {
payment_method_details.get(&pmt).cloned().ok_or_else(|| {
errors::ConnectorError::NotSupported {
message: format!("{payment_method} {pmt}"),
connector,
}
.into()
})
})
.transpose()
}
/// ConnectorTransactionId trait
pub trait ConnectorTransactionId: ConnectorCommon + Sync {
/// fn connector_transaction_id
fn connector_transaction_id(
&self,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> Result<Option<String>, ApiErrorResponse> {
Ok(payment_attempt
.get_connector_payment_id()
.map(ToString::to_string))
}
}
|
crates/hyperswitch_interfaces/src/api.rs
|
hyperswitch_interfaces
|
full_file
| null | null | null | 5,157
| null | null | null | null | null | null | null |
// Struct: RoutingLinkWrapper
// File: crates/api_models/src/routing.rs
// Module: api_models
// Implementations: 0
pub struct RoutingLinkWrapper
|
crates/api_models/src/routing.rs
|
api_models
|
struct_definition
|
RoutingLinkWrapper
| 0
|
[] | 36
| null | null | null | null | null | null | null |
// Struct: Details
// File: crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Details
|
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
Details
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// Struct: ExternalTokenResponse
// File: crates/api_models/src/external_service_auth.rs
// Module: api_models
// Implementations: 0
pub struct ExternalTokenResponse
|
crates/api_models/src/external_service_auth.rs
|
api_models
|
struct_definition
|
ExternalTokenResponse
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// Struct: Balances
// File: crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Balances
|
crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
Balances
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/utils.rs
// Module: hyperswitch_connectors
// Public functions: 24
// Public structs: 6
use std::{
collections::{HashMap, HashSet},
marker::PhantomData,
str::FromStr,
sync::LazyLock,
};
use api_models::payments;
#[cfg(feature = "payouts")]
use api_models::payouts::PayoutVendorAccountDetails;
use base64::Engine;
use common_enums::{
enums,
enums::{
AlbaniaStatesAbbreviation, AndorraStatesAbbreviation, AttemptStatus,
AustraliaStatesAbbreviation, AustriaStatesAbbreviation, BelarusStatesAbbreviation,
BelgiumStatesAbbreviation, BosniaAndHerzegovinaStatesAbbreviation,
BrazilStatesAbbreviation, BulgariaStatesAbbreviation, CanadaStatesAbbreviation,
CroatiaStatesAbbreviation, CzechRepublicStatesAbbreviation, DenmarkStatesAbbreviation,
FinlandStatesAbbreviation, FranceStatesAbbreviation, FutureUsage,
GermanyStatesAbbreviation, GreeceStatesAbbreviation, HungaryStatesAbbreviation,
IcelandStatesAbbreviation, IndiaStatesAbbreviation, IrelandStatesAbbreviation,
ItalyStatesAbbreviation, JapanStatesAbbreviation, LatviaStatesAbbreviation,
LiechtensteinStatesAbbreviation, LithuaniaStatesAbbreviation, LuxembourgStatesAbbreviation,
MaltaStatesAbbreviation, MoldovaStatesAbbreviation, MonacoStatesAbbreviation,
MontenegroStatesAbbreviation, NetherlandsStatesAbbreviation, NewZealandStatesAbbreviation,
NorthMacedoniaStatesAbbreviation, NorwayStatesAbbreviation, PhilippinesStatesAbbreviation,
PolandStatesAbbreviation, PortugalStatesAbbreviation, RomaniaStatesAbbreviation,
RussiaStatesAbbreviation, SanMarinoStatesAbbreviation, SerbiaStatesAbbreviation,
SingaporeStatesAbbreviation, SlovakiaStatesAbbreviation, SloveniaStatesAbbreviation,
SpainStatesAbbreviation, SwedenStatesAbbreviation, SwitzerlandStatesAbbreviation,
ThailandStatesAbbreviation, UkraineStatesAbbreviation, UnitedKingdomStatesAbbreviation,
UsStatesAbbreviation,
},
};
use common_utils::{
consts::BASE64_ENGINE,
errors::{CustomResult, ParsingError, ReportSwitchExt},
ext_traits::{OptionExt, StringExt, ValueExt},
id_type,
pii::{self, Email, IpAddress},
types::{AmountConvertor, MinorUnit},
};
use error_stack::{report, ResultExt};
#[cfg(feature = "frm")]
use hyperswitch_domain_models::router_request_types::fraud_check::{
FraudCheckCheckoutData, FraudCheckRecordReturnData, FraudCheckSaleData,
FraudCheckTransactionData,
};
use hyperswitch_domain_models::{
address::{Address, AddressDetails, PhoneDetails},
mandates,
network_tokenization::NetworkTokenNumber,
payment_method_data::{self, Card, CardDetailsForNetworkTransactionId, PaymentMethodData},
router_data::{
ErrorResponse, L2L3Data, PaymentMethodToken, RecurringMandatePaymentData,
RouterData as ConnectorRouterData,
},
router_request_types::{
AuthenticationData, AuthoriseIntegrityObject, BrowserInformation, CaptureIntegrityObject,
CompleteAuthorizeData, ConnectorCustomerData, ExternalVaultProxyPaymentsData,
MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsPostSessionTokensData,
PaymentsPreProcessingData, PaymentsSyncData, RefundIntegrityObject, RefundsData,
ResponseId, SetupMandateRequestData, SyncIntegrityObject,
},
router_response_types::{CaptureSyncResponse, PaymentsResponseData},
types::{OrderDetailsWithAmount, SetupMandateRouterData},
};
use hyperswitch_interfaces::{api, consts, errors, types::Response};
use image::{DynamicImage, ImageBuffer, ImageFormat, Luma, Rgba};
use masking::{ExposeInterface, PeekInterface, Secret};
use quick_xml::{
events::{BytesDecl, BytesText, Event},
Writer,
};
use rand::Rng;
use regex::Regex;
use router_env::logger;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use time::PrimitiveDateTime;
use unicode_normalization::UnicodeNormalization;
#[cfg(feature = "frm")]
use crate::types::FrmTransactionRouterData;
use crate::{constants::UNSUPPORTED_ERROR_MESSAGE, types::RefreshTokenRouterData};
type Error = error_stack::Report<errors::ConnectorError>;
pub(crate) fn construct_not_supported_error_report(
capture_method: enums::CaptureMethod,
connector_name: &'static str,
) -> error_stack::Report<errors::ConnectorError> {
errors::ConnectorError::NotSupported {
message: capture_method.to_string(),
connector: connector_name,
}
.into()
}
pub(crate) fn to_currency_base_unit_with_zero_decimal_check(
amount: i64,
currency: enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
currency
.to_currency_base_unit_with_zero_decimal_check(amount)
.change_context(errors::ConnectorError::RequestEncodingFailed)
}
pub(crate) fn get_timestamp_in_milliseconds(datetime: &PrimitiveDateTime) -> i64 {
let utc_datetime = datetime.assume_utc();
utc_datetime.unix_timestamp() * 1000
}
pub(crate) fn get_amount_as_string(
currency_unit: &api::CurrencyUnit,
amount: i64,
currency: enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
let amount = match currency_unit {
api::CurrencyUnit::Minor => amount.to_string(),
api::CurrencyUnit::Base => to_currency_base_unit(amount, currency)?,
};
Ok(amount)
}
pub(crate) fn base64_decode(data: String) -> Result<Vec<u8>, Error> {
BASE64_ENGINE
.decode(data)
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
}
pub(crate) fn to_currency_base_unit(
amount: i64,
currency: enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
currency
.to_currency_base_unit(amount)
.change_context(errors::ConnectorError::ParsingFailed)
}
pub trait ConnectorErrorTypeMapping {
fn get_connector_error_type(
&self,
_error_code: String,
_error_message: String,
) -> ConnectorErrorType {
ConnectorErrorType::UnknownError
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ErrorCodeAndMessage {
pub error_code: String,
pub error_message: String,
}
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
//Priority of connector_error_type
pub enum ConnectorErrorType {
UserError = 2,
BusinessError = 3,
TechnicalError = 4,
UnknownError = 1,
}
pub(crate) fn get_error_code_error_message_based_on_priority(
connector: impl ConnectorErrorTypeMapping,
error_list: Vec<ErrorCodeAndMessage>,
) -> Option<ErrorCodeAndMessage> {
let error_type_list = error_list
.iter()
.map(|error| {
connector
.get_connector_error_type(error.error_code.clone(), error.error_message.clone())
})
.collect::<Vec<ConnectorErrorType>>();
let mut error_zip_list = error_list
.iter()
.zip(error_type_list.iter())
.collect::<Vec<(&ErrorCodeAndMessage, &ConnectorErrorType)>>();
error_zip_list.sort_by_key(|&(_, error_type)| error_type);
error_zip_list
.first()
.map(|&(error_code_message, _)| error_code_message)
.cloned()
}
pub trait MultipleCaptureSyncResponse {
fn get_connector_capture_id(&self) -> String;
fn get_capture_attempt_status(&self) -> AttemptStatus;
fn is_capture_response(&self) -> bool;
fn get_connector_reference_id(&self) -> Option<String> {
None
}
fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>>;
}
pub(crate) fn construct_captures_response_hashmap<T>(
capture_sync_response_list: Vec<T>,
) -> CustomResult<HashMap<String, CaptureSyncResponse>, errors::ConnectorError>
where
T: MultipleCaptureSyncResponse,
{
let mut hashmap = HashMap::new();
for capture_sync_response in capture_sync_response_list {
let connector_capture_id = capture_sync_response.get_connector_capture_id();
if capture_sync_response.is_capture_response() {
hashmap.insert(
connector_capture_id.clone(),
CaptureSyncResponse::Success {
resource_id: ResponseId::ConnectorTransactionId(connector_capture_id),
status: capture_sync_response.get_capture_attempt_status(),
connector_response_reference_id: capture_sync_response
.get_connector_reference_id(),
amount: capture_sync_response
.get_amount_captured()
.change_context(errors::ConnectorError::AmountConversionFailed)
.attach_printable(
"failed to convert back captured response amount to minor unit",
)?,
},
);
}
}
Ok(hashmap)
}
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayWalletData {
#[serde(rename = "type")]
pub pm_type: String,
pub description: String,
pub info: GooglePayPaymentMethodInfo,
pub tokenization_data: common_types::payments::GpayTokenizationData,
}
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPaymentMethodInfo {
pub card_network: String,
pub card_details: String,
}
#[derive(Debug, Serialize)]
pub struct CardMandateInfo {
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
}
impl TryFrom<payment_method_data::GooglePayWalletData> for GooglePayWalletData {
type Error = common_utils::errors::ValidationError;
fn try_from(data: payment_method_data::GooglePayWalletData) -> Result<Self, Self::Error> {
let tokenization_data = match data.tokenization_data {
common_types::payments::GpayTokenizationData::Encrypted(encrypted_data) => {
common_types::payments::GpayTokenizationData::Encrypted(
common_types::payments::GpayEcryptedTokenizationData {
token_type: encrypted_data.token_type,
token: encrypted_data.token,
},
)
}
common_types::payments::GpayTokenizationData::Decrypted(_) => {
return Err(common_utils::errors::ValidationError::InvalidValue {
message: "Expected encrypted tokenization data, got decrypted".to_string(),
});
}
};
Ok(Self {
pm_type: data.pm_type,
description: data.description,
info: GooglePayPaymentMethodInfo {
card_network: data.info.card_network,
card_details: data.info.card_details,
},
tokenization_data,
})
}
}
pub(crate) fn get_amount_as_f64(
currency_unit: &api::CurrencyUnit,
amount: i64,
currency: enums::Currency,
) -> Result<f64, error_stack::Report<errors::ConnectorError>> {
let amount = match currency_unit {
api::CurrencyUnit::Base => to_currency_base_unit_asf64(amount, currency)?,
api::CurrencyUnit::Minor => u32::try_from(amount)
.change_context(errors::ConnectorError::ParsingFailed)?
.into(),
};
Ok(amount)
}
pub(crate) fn to_currency_base_unit_asf64(
amount: i64,
currency: enums::Currency,
) -> Result<f64, error_stack::Report<errors::ConnectorError>> {
currency
.to_currency_base_unit_asf64(amount)
.change_context(errors::ConnectorError::ParsingFailed)
}
pub(crate) fn to_connector_meta_from_secret<T>(
connector_meta: Option<Secret<Value>>,
) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
let connector_meta_secret =
connector_meta.ok_or_else(missing_field_err("connector_meta_data"))?;
let json = connector_meta_secret.expose();
json.parse_value(std::any::type_name::<T>()).switch()
}
pub(crate) fn is_manual_capture(capture_method: Option<enums::CaptureMethod>) -> bool {
capture_method == Some(enums::CaptureMethod::Manual)
|| capture_method == Some(enums::CaptureMethod::ManualMultiple)
}
pub(crate) fn generate_random_bytes(length: usize) -> Vec<u8> {
// returns random bytes of length n
let mut rng = rand::thread_rng();
(0..length).map(|_| Rng::gen(&mut rng)).collect()
}
pub(crate) fn missing_field_err(
message: &'static str,
) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + 'static> {
Box::new(move || {
errors::ConnectorError::MissingRequiredField {
field_name: message,
}
.into()
})
}
pub(crate) fn handle_json_response_deserialization_failure(
res: Response,
connector: &'static str,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
crate::metrics::CONNECTOR_RESPONSE_DESERIALIZATION_FAILURE
.add(1, router_env::metric_attributes!(("connector", connector)));
let response_data = String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
// check for whether the response is in json format
match serde_json::from_str::<Value>(&response_data) {
// in case of unexpected response but in json format
Ok(_) => Err(errors::ConnectorError::ResponseDeserializationFailed)?,
// in case of unexpected response but in html or string format
Err(error_msg) => {
logger::error!(deserialization_error=?error_msg);
logger::error!("UNEXPECTED RESPONSE FROM CONNECTOR: {}", response_data);
Ok(ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
message: UNSUPPORTED_ERROR_MESSAGE.to_string(),
reason: Some(response_data),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
}
pub(crate) fn construct_not_implemented_error_report(
capture_method: enums::CaptureMethod,
connector_name: &str,
) -> error_stack::Report<errors::ConnectorError> {
errors::ConnectorError::NotImplemented(format!("{capture_method} for {connector_name}")).into()
}
pub(crate) const SELECTED_PAYMENT_METHOD: &str = "Selected payment method";
pub(crate) fn get_unimplemented_payment_method_error_message(connector: &str) -> String {
format!("{SELECTED_PAYMENT_METHOD} through {connector}")
}
pub(crate) fn to_connector_meta<T>(connector_meta: Option<Value>) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
let json = connector_meta.ok_or_else(missing_field_err("connector_meta_data"))?;
json.parse_value(std::any::type_name::<T>()).switch()
}
pub(crate) fn convert_amount<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<T, error_stack::Report<errors::ConnectorError>> {
amount_convertor
.convert(amount, currency)
.change_context(errors::ConnectorError::AmountConversionFailed)
}
pub(crate) fn validate_currency(
request_currency: enums::Currency,
merchant_config_currency: Option<enums::Currency>,
) -> Result<(), errors::ConnectorError> {
let merchant_config_currency =
merchant_config_currency.ok_or(errors::ConnectorError::NoConnectorMetaData)?;
if request_currency != merchant_config_currency {
Err(errors::ConnectorError::NotSupported {
message: format!(
"currency {request_currency} is not supported for this merchant account",
),
connector: "Braintree",
})?
}
Ok(())
}
pub(crate) fn convert_back_amount_to_minor_units<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
amount: T,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>> {
amount_convertor
.convert_back(amount, currency)
.change_context(errors::ConnectorError::AmountConversionFailed)
}
pub(crate) fn is_payment_failure(status: AttemptStatus) -> bool {
match status {
AttemptStatus::AuthenticationFailed
| AttemptStatus::AuthorizationFailed
| AttemptStatus::CaptureFailed
| AttemptStatus::VoidFailed
| AttemptStatus::Failure
| AttemptStatus::Expired => true,
AttemptStatus::Started
| AttemptStatus::RouterDeclined
| AttemptStatus::AuthenticationPending
| AttemptStatus::AuthenticationSuccessful
| AttemptStatus::Authorized
| AttemptStatus::Charged
| AttemptStatus::Authorizing
| AttemptStatus::CodInitiated
| AttemptStatus::Voided
| AttemptStatus::VoidedPostCharge
| AttemptStatus::VoidInitiated
| AttemptStatus::CaptureInitiated
| AttemptStatus::AutoRefunded
| AttemptStatus::PartialCharged
| AttemptStatus::PartialChargedAndChargeable
| AttemptStatus::Unresolved
| AttemptStatus::Pending
| AttemptStatus::PaymentMethodAwaited
| AttemptStatus::ConfirmationAwaited
| AttemptStatus::DeviceDataCollectionPending
| AttemptStatus::IntegrityFailure
| AttemptStatus::PartiallyAuthorized => false,
}
}
pub fn is_refund_failure(status: enums::RefundStatus) -> bool {
match status {
common_enums::RefundStatus::Failure | common_enums::RefundStatus::TransactionFailure => {
true
}
common_enums::RefundStatus::ManualReview
| common_enums::RefundStatus::Pending
| common_enums::RefundStatus::Success => false,
}
}
// TODO: Make all traits as `pub(crate) trait` once all connectors are moved.
pub trait RouterData {
fn get_billing(&self) -> Result<&Address, Error>;
fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error>;
fn get_billing_phone(&self) -> Result<&PhoneDetails, Error>;
fn get_description(&self) -> Result<String, Error>;
fn get_billing_address(&self) -> Result<&AddressDetails, Error>;
fn get_shipping_address(&self) -> Result<&AddressDetails, Error>;
fn get_shipping_address_with_phone_number(&self) -> Result<&Address, Error>;
fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error>;
fn get_session_token(&self) -> Result<String, Error>;
fn get_billing_first_name(&self) -> Result<Secret<String>, Error>;
fn get_billing_full_name(&self) -> Result<Secret<String>, Error>;
fn get_billing_last_name(&self) -> Result<Secret<String>, Error>;
fn get_billing_line1(&self) -> Result<Secret<String>, Error>;
fn get_billing_line2(&self) -> Result<Secret<String>, Error>;
fn get_billing_zip(&self) -> Result<Secret<String>, Error>;
fn get_billing_state(&self) -> Result<Secret<String>, Error>;
fn get_billing_state_code(&self) -> Result<Secret<String>, Error>;
fn get_billing_city(&self) -> Result<String, Error>;
fn get_billing_email(&self) -> Result<Email, Error>;
fn get_billing_phone_number(&self) -> Result<Secret<String>, Error>;
fn to_connector_meta<T>(&self) -> Result<T, Error>
where
T: serde::de::DeserializeOwned;
fn is_three_ds(&self) -> bool;
fn get_payment_method_token(&self) -> Result<PaymentMethodToken, Error>;
fn get_customer_id(&self) -> Result<id_type::CustomerId, Error>;
fn get_optional_customer_id(&self) -> Option<id_type::CustomerId>;
fn get_connector_customer_id(&self) -> Result<String, Error>;
fn get_preprocessing_id(&self) -> Result<String, Error>;
fn get_recurring_mandate_payment_data(&self) -> Result<RecurringMandatePaymentData, Error>;
#[cfg(feature = "payouts")]
fn get_payout_method_data(&self) -> Result<api_models::payouts::PayoutMethodData, Error>;
#[cfg(feature = "payouts")]
fn get_quote_id(&self) -> Result<String, Error>;
fn get_optional_billing(&self) -> Option<&Address>;
fn get_optional_shipping(&self) -> Option<&Address>;
fn get_optional_shipping_line1(&self) -> Option<Secret<String>>;
fn get_optional_shipping_line2(&self) -> Option<Secret<String>>;
fn get_optional_shipping_line3(&self) -> Option<Secret<String>>;
fn get_optional_shipping_city(&self) -> Option<String>;
fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2>;
fn get_optional_shipping_zip(&self) -> Option<Secret<String>>;
fn get_optional_shipping_state(&self) -> Option<Secret<String>>;
fn get_optional_shipping_first_name(&self) -> Option<Secret<String>>;
fn get_optional_shipping_last_name(&self) -> Option<Secret<String>>;
fn get_optional_shipping_full_name(&self) -> Option<Secret<String>>;
fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>>;
fn get_optional_shipping_phone_number_without_country_code(&self) -> Option<Secret<String>>;
fn get_optional_shipping_email(&self) -> Option<Email>;
fn get_required_shipping_full_name(&self) -> Result<Secret<String>, Error>;
fn get_required_shipping_line1(&self) -> Result<Secret<String>, Error>;
fn get_required_shipping_city(&self) -> Result<String, Error>;
fn get_required_shipping_state(&self) -> Result<Secret<String>, Error>;
fn get_required_shipping_zip(&self) -> Result<Secret<String>, Error>;
fn get_required_shipping_phone_number(&self) -> Result<Secret<String>, Error>;
fn get_optional_billing_full_name(&self) -> Option<Secret<String>>;
fn get_optional_billing_line1(&self) -> Option<Secret<String>>;
fn get_optional_billing_line3(&self) -> Option<Secret<String>>;
fn get_optional_billing_line2(&self) -> Option<Secret<String>>;
fn get_optional_billing_city(&self) -> Option<String>;
fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2>;
fn get_optional_billing_zip(&self) -> Option<Secret<String>>;
fn get_optional_billing_state(&self) -> Option<Secret<String>>;
fn get_optional_billing_state_2_digit(&self) -> Option<Secret<String>>;
fn get_optional_billing_first_name(&self) -> Option<Secret<String>>;
fn get_optional_billing_last_name(&self) -> Option<Secret<String>>;
fn get_optional_billing_phone_number(&self) -> Option<Secret<String>>;
fn get_optional_billing_email(&self) -> Option<Email>;
fn get_optional_l2_l3_data(&self) -> Option<L2L3Data>;
}
impl<Flow, Request, Response> RouterData
for hyperswitch_domain_models::router_data::RouterData<Flow, Request, Response>
{
fn get_billing(&self) -> Result<&Address, Error> {
self.address
.get_payment_method_billing()
.ok_or_else(missing_field_err("billing"))
}
fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error> {
self.address
.get_payment_method_billing()
.and_then(|a| a.address.as_ref())
.and_then(|ad| ad.country)
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.country",
))
}
fn get_billing_phone(&self) -> Result<&PhoneDetails, Error> {
self.address
.get_payment_method_billing()
.and_then(|a| a.phone.as_ref())
.ok_or_else(missing_field_err("billing.phone"))
}
fn get_optional_billing(&self) -> Option<&Address> {
self.address.get_payment_method_billing()
}
fn get_optional_shipping(&self) -> Option<&Address> {
self.address.get_shipping()
}
fn get_optional_shipping_first_name(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.first_name)
})
}
fn get_optional_shipping_last_name(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.last_name)
})
}
fn get_optional_shipping_full_name(&self) -> Option<Secret<String>> {
self.get_optional_shipping()
.and_then(|shipping_details| shipping_details.address.as_ref())
.and_then(|shipping_address| shipping_address.get_optional_full_name())
}
fn get_optional_shipping_line1(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.line1)
})
}
fn get_optional_shipping_line2(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.line2)
})
}
fn get_optional_shipping_line3(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.line3)
})
}
fn get_optional_shipping_city(&self) -> Option<String> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.city)
})
}
fn get_optional_shipping_state(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.state)
})
}
fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.country)
})
}
fn get_optional_shipping_zip(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.zip)
})
}
fn get_optional_shipping_email(&self) -> Option<Email> {
self.address
.get_shipping()
.and_then(|shipping_address| shipping_address.clone().email)
}
fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>> {
self.address
.get_shipping()
.and_then(|shipping_address| shipping_address.clone().phone)
.and_then(|phone_details| phone_details.get_number_with_country_code().ok())
}
fn get_optional_shipping_phone_number_without_country_code(&self) -> Option<Secret<String>> {
self.address
.get_shipping()
.and_then(|shipping_address| shipping_address.clone().phone)
.and_then(|phone_details| phone_details.get_number().ok())
}
fn get_description(&self) -> Result<String, Error> {
self.description
.clone()
.ok_or_else(missing_field_err("description"))
}
fn get_billing_address(&self) -> Result<&AddressDetails, Error> {
self.address
.get_payment_method_billing()
.as_ref()
.and_then(|a| a.address.as_ref())
.ok_or_else(missing_field_err("billing.address"))
}
fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error> {
self.connector_meta_data
.clone()
.ok_or_else(missing_field_err("connector_meta_data"))
}
fn get_session_token(&self) -> Result<String, Error> {
self.session_token
.clone()
.ok_or_else(missing_field_err("session_token"))
}
fn get_billing_first_name(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.first_name.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.first_name",
))
}
fn get_billing_full_name(&self) -> Result<Secret<String>, Error> {
self.get_optional_billing()
.and_then(|billing_details| billing_details.address.as_ref())
.and_then(|billing_address| billing_address.get_optional_full_name())
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.first_name",
))
}
fn get_billing_last_name(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.last_name.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.last_name",
))
}
fn get_billing_line1(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line1.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.line1",
))
}
fn get_billing_line2(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line2.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.line2",
))
}
fn get_billing_zip(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.zip.clone())
})
.ok_or_else(missing_field_err("payment_method_data.billing.address.zip"))
}
fn get_billing_state(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.state.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.state",
))
}
fn get_billing_state_code(&self) -> Result<Secret<String>, Error> {
let country = self.get_billing_country()?;
let state = self.get_billing_state()?;
match country {
api_models::enums::CountryAlpha2::US => Ok(Secret::new(
UsStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::CA => Ok(Secret::new(
CanadaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
_ => Ok(state.clone()),
}
}
fn get_billing_city(&self) -> Result<String, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.city)
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.city",
))
}
fn get_billing_email(&self) -> Result<Email, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| billing_address.email.clone())
.ok_or_else(missing_field_err("payment_method_data.billing.email"))
}
fn get_billing_phone_number(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| billing_address.clone().phone)
.map(|phone_details| phone_details.get_number_with_country_code())
.transpose()?
.ok_or_else(missing_field_err("payment_method_data.billing.phone"))
}
fn get_optional_billing_line1(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line1)
})
}
fn get_optional_billing_line2(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line2)
})
}
fn get_optional_billing_line3(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line3)
})
}
fn get_optional_billing_city(&self) -> Option<String> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.city)
})
}
fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.country)
})
}
fn get_optional_billing_zip(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.zip)
})
}
fn get_optional_billing_state(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.state)
})
}
fn get_optional_billing_state_2_digit(&self) -> Option<Secret<String>> {
self.get_optional_billing_state().and_then(|state| {
if state.clone().expose().len() != 2 {
None
} else {
Some(state)
}
})
}
fn get_optional_billing_first_name(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.first_name)
})
}
fn get_optional_billing_last_name(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.last_name)
})
}
fn get_optional_billing_phone_number(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.phone
.and_then(|phone_data| phone_data.number)
})
}
fn get_optional_billing_email(&self) -> Option<Email> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| billing_address.clone().email)
}
fn to_connector_meta<T>(&self) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
self.get_connector_meta()?
.parse_value(std::any::type_name::<T>())
.change_context(errors::ConnectorError::NoConnectorMetaData)
}
fn is_three_ds(&self) -> bool {
matches!(self.auth_type, enums::AuthenticationType::ThreeDs)
}
fn get_shipping_address(&self) -> Result<&AddressDetails, Error> {
self.address
.get_shipping()
.and_then(|a| a.address.as_ref())
.ok_or_else(missing_field_err("shipping.address"))
}
|
crates/hyperswitch_connectors/src/utils.rs#chunk0
|
hyperswitch_connectors
|
chunk
| null | null | null | 8,183
| null | null | null | null | null | null | null |
// Implementation: impl Clone for for PIISerializer
// File: crates/masking/src/serde.rs
// Module: masking
// Methods: 1 total (0 public)
impl Clone for for PIISerializer
|
crates/masking/src/serde.rs
|
masking
|
impl_block
| null | null | null | 44
| null |
PIISerializer
|
Clone for
| 1
| 0
| null | null |
// Struct: KlarnaData
// File: crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct KlarnaData
|
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
KlarnaData
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Struct: PlaidBankAccountCredentialsAccounts
// File: crates/pm_auth/src/connector/plaid/transformers.rs
// Module: pm_auth
// Implementations: 0
pub struct PlaidBankAccountCredentialsAccounts
|
crates/pm_auth/src/connector/plaid/transformers.rs
|
pm_auth
|
struct_definition
|
PlaidBankAccountCredentialsAccounts
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Function: remove_quotes_for_integer_values
// File: crates/test_utils/src/newman_runner.rs
// Module: test_utils
pub fn remove_quotes_for_integer_values(
connector_name: &str,
) -> Result<(&str, Option<String>), io::Error>
|
crates/test_utils/src/newman_runner.rs
|
test_utils
|
function_signature
| null | null | null | 57
|
remove_quotes_for_integer_values
| 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 |
// Struct: CheckoutRefundResponse
// File: crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CheckoutRefundResponse
|
crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CheckoutRefundResponse
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Struct: SubsequentAuthInformation
// File: crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SubsequentAuthInformation
|
crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
SubsequentAuthInformation
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentToken for for Paybox
// File: crates/hyperswitch_connectors/src/connectors/paybox.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentToken for for Paybox
|
crates/hyperswitch_connectors/src/connectors/paybox.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Paybox
|
api::PaymentToken for
| 0
| 0
| null | null |
// Implementation: impl api::PaymentAuthorize for for Coingate
// File: crates/hyperswitch_connectors/src/connectors/coingate.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentAuthorize for for Coingate
|
crates/hyperswitch_connectors/src/connectors/coingate.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Coingate
|
api::PaymentAuthorize for
| 0
| 0
| null | null |
// Implementation: impl webhooks::IncomingWebhook for for Peachpayments
// File: crates/hyperswitch_connectors/src/connectors/peachpayments.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)
impl webhooks::IncomingWebhook for for Peachpayments
|
crates/hyperswitch_connectors/src/connectors/peachpayments.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 63
| null |
Peachpayments
|
webhooks::IncomingWebhook for
| 3
| 0
| null | null |
// Struct: PaymentIntentMetricsBucketIdentifier
// File: crates/api_models/src/analytics/payment_intents.rs
// Module: api_models
// Implementations: 3
// Traits: Hash, PartialEq
pub struct PaymentIntentMetricsBucketIdentifier
|
crates/api_models/src/analytics/payment_intents.rs
|
api_models
|
struct_definition
|
PaymentIntentMetricsBucketIdentifier
| 3
|
[
"Hash",
"PartialEq"
] | 50
| null | null | null | null | null | null | null |
// Function: get_network_token_resource_object
// File: crates/router/src/core/webhooks/network_tokenization_incoming.rs
// Module: router
pub fn get_network_token_resource_object(
request_details: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::NetworkTokenizationError>
|
crates/router/src/core/webhooks/network_tokenization_incoming.rs
|
router
|
function_signature
| null | null | null | 73
|
get_network_token_resource_object
| null | null | null | null | null | null |
// Struct: GetTokenizePayloadRequest
// File: crates/api_models/src/payment_methods.rs
// Module: api_models
// Implementations: 0
pub struct GetTokenizePayloadRequest
|
crates/api_models/src/payment_methods.rs
|
api_models
|
struct_definition
|
GetTokenizePayloadRequest
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Function: list_payment_attempts
// File: crates/router/src/routes/payments.rs
// Module: router
pub fn list_payment_attempts(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder
|
crates/router/src/routes/payments.rs
|
router
|
function_signature
| null | null | null | 71
|
list_payment_attempts
| null | null | null | null | null | null |
// Struct: PaymentsCapture
// File: crates/router/src/core/payments/operations/payment_capture_v2.rs
// Module: router
// Implementations: 1
// Traits: ValidateStatusForOperation
pub struct PaymentsCapture
|
crates/router/src/core/payments/operations/payment_capture_v2.rs
|
router
|
struct_definition
|
PaymentsCapture
| 1
|
[
"ValidateStatusForOperation"
] | 47
| null | null | null | null | null | null | null |
// Trait: ValueNode
// File: crates/hyperswitch_constraint_graph/src/types.rs
// Module: hyperswitch_constraint_graph
pub trait ValueNode: fmt::Debug + Clone + hash::Hash + serde::Serialize + PartialEq + Eq
|
crates/hyperswitch_constraint_graph/src/types.rs
|
hyperswitch_constraint_graph
|
trait_definition
| null | null | null | 50
| null | null |
ValueNode
| null | null | null | null |
// Function: get_expiry_date_as_yymm
// File: crates/common_types/src/payments.rs
// Module: common_types
// Documentation: Get the expiry date in YYMM format from the Apple Pay pre-decrypt data
pub fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ValidationError>
|
crates/common_types/src/payments.rs
|
common_types
|
function_signature
| null | null | null | 68
|
get_expiry_date_as_yymm
| null | null | null | null | null | null |
// Struct: AcquirerDetails
// File: crates/api_models/src/authentication.rs
// Module: api_models
// Implementations: 0
pub struct AcquirerDetails
|
crates/api_models/src/authentication.rs
|
api_models
|
struct_definition
|
AcquirerDetails
| 0
|
[] | 35
| null | null | null | null | null | null | null |
// Struct: PaymentMethodStatusTrackingData
// File: crates/router/src/types/storage/payment_method.rs
// Module: router
// Implementations: 0
pub struct PaymentMethodStatusTrackingData
|
crates/router/src/types/storage/payment_method.rs
|
router
|
struct_definition
|
PaymentMethodStatusTrackingData
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Implementation: impl api::ConnectorAccessToken for for Nomupay
// File: crates/hyperswitch_connectors/src/connectors/nomupay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::ConnectorAccessToken for for Nomupay
|
crates/hyperswitch_connectors/src/connectors/nomupay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Nomupay
|
api::ConnectorAccessToken for
| 0
| 0
| null | null |
// Function: get_payment_filters_profile
// File: crates/router/src/routes/payments.rs
// Module: router
pub fn get_payment_filters_profile(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
) -> impl Responder
|
crates/router/src/routes/payments.rs
|
router
|
function_signature
| null | null | null | 56
|
get_payment_filters_profile
| null | null | null | null | null | null |
// Function: schedule_refund_execution
// File: crates/router/src/core/refunds_v2.rs
// Module: router
pub fn schedule_refund_execution(
state: &SessionState,
refund: diesel_refund::Refund,
refund_type: api_models::refunds::RefundType,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>,
) -> errors::RouterResult<diesel_refund::Refund>
|
crates/router/src/core/refunds_v2.rs
|
router
|
function_signature
| null | null | null | 125
|
schedule_refund_execution
| null | null | null | null | null | null |
// Function: update_merchant_routing_dictionary
// File: crates/router/src/core/routing/helpers.rs
// Module: router
pub fn update_merchant_routing_dictionary(
db: &dyn StorageInterface,
merchant_id: &str,
dictionary: routing_types::RoutingDictionary,
) -> RouterResult<()>
|
crates/router/src/core/routing/helpers.rs
|
router
|
function_signature
| null | null | null | 63
|
update_merchant_routing_dictionary
| null | null | null | null | null | null |
// File: crates/router/src/core/fraud_check/operation.rs
// Module: router
pub mod fraud_check_post;
pub mod fraud_check_pre;
use async_trait::async_trait;
use common_enums::FrmSuggestion;
use error_stack::{report, ResultExt};
pub use self::{fraud_check_post::FraudCheckPost, fraud_check_pre::FraudCheckPre};
use super::{
types::{ConnectorDetailsCore, FrmConfigsObject, PaymentToFrmData},
FrmData,
};
use crate::{
core::errors::{self, RouterResult},
routes::{app::ReqState, SessionState},
types::{domain, fraud_check::FrmRouterData},
};
pub type BoxedFraudCheckOperation<F, D> = Box<dyn FraudCheckOperation<F, D> + Send + Sync>;
pub trait FraudCheckOperation<F, D>: Send + std::fmt::Debug {
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("get tracker interface not found for {self:?}"))
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("domain interface not found for {self:?}"))
}
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("get tracker interface not found for {self:?}"))
}
}
#[async_trait]
pub trait GetTracker<D>: Send {
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_data: D,
frm_connector_details: ConnectorDetailsCore,
) -> RouterResult<Option<FrmData>>;
}
#[async_trait]
#[allow(clippy::too_many_arguments)]
pub trait Domain<F, D>: Send + Sync {
async fn post_payment_frm<'a>(
&'a self,
state: &'a SessionState,
req_state: ReqState,
payment_data: &mut D,
frm_data: &mut FrmData,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
) -> RouterResult<Option<FrmRouterData>>
where
F: Send + Clone;
async fn pre_payment_frm<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut D,
frm_data: &mut FrmData,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
) -> RouterResult<FrmRouterData>
where
F: Send + Clone;
// To execute several tasks conditionally based on the result of post_flow.
// Eg: If the /sale(post flow) is returning the transaction as fraud we can execute refund in post task
#[allow(clippy::too_many_arguments)]
async fn execute_post_tasks(
&self,
_state: &SessionState,
_req_state: ReqState,
frm_data: &mut FrmData,
_merchant_context: &domain::MerchantContext,
_frm_configs: FrmConfigsObject,
_frm_suggestion: &mut Option<FrmSuggestion>,
_payment_data: &mut D,
_customer: &Option<domain::Customer>,
_should_continue_capture: &mut bool,
) -> RouterResult<Option<FrmData>>
where
F: Send + Clone,
{
return Ok(Some(frm_data.to_owned()));
}
}
#[async_trait]
pub trait UpdateTracker<Fd, F: Clone, D>: Send {
async fn update_tracker<'b>(
&'b self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
frm_data: Fd,
payment_data: &mut D,
_frm_suggestion: Option<FrmSuggestion>,
frm_router_data: FrmRouterData,
) -> RouterResult<Fd>;
}
|
crates/router/src/core/fraud_check/operation.rs
|
router
|
full_file
| null | null | null | 892
| null | null | null | null | null | null | null |
// Struct: CardPaymentInformation
// File: crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CardPaymentInformation
|
crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CardPaymentInformation
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Function: get_profile_dispute_filters
// File: crates/router/src/analytics.rs
// Module: router
pub fn get_profile_dispute_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<api_models::analytics::GetDisputeFilterRequest>,
) -> impl Responder
|
crates/router/src/analytics.rs
|
router
|
function_signature
| null | null | null | 75
|
get_profile_dispute_filters
| null | null | null | null | null | null |
// Implementation: impl api::PaymentVoid for for Billwerk
// File: crates/hyperswitch_connectors/src/connectors/billwerk.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Billwerk
|
crates/hyperswitch_connectors/src/connectors/billwerk.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Billwerk
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Function: get_tokenize_card_form_records
// File: crates/router/src/core/payment_methods/tokenize.rs
// Module: router
pub fn get_tokenize_card_form_records(
form: CardNetworkTokenizeForm,
) -> Result<
(
id_type::MerchantId,
Vec<payment_methods_api::CardNetworkTokenizeRequest>,
),
errors::ApiErrorResponse,
>
|
crates/router/src/core/payment_methods/tokenize.rs
|
router
|
function_signature
| null | null | null | 79
|
get_tokenize_card_form_records
| null | null | null | null | null | null |
// Struct: DigitalvirgoAuthType
// File: crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct DigitalvirgoAuthType
|
crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
DigitalvirgoAuthType
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// File: crates/router/src/core/chat.rs
// Module: router
// Public functions: 2
use api_models::chat as chat_api;
use common_utils::{
consts,
crypto::{DecodeMessage, GcmAes256},
errors::CustomResult,
request::{Method, RequestBuilder, RequestContent},
};
use error_stack::ResultExt;
use external_services::http_client;
use hyperswitch_domain_models::chat as chat_domain;
use masking::ExposeInterface;
use router_env::{
instrument, logger,
tracing::{self, Instrument},
};
use crate::{
db::errors::chat::ChatErrors,
routes::{app::SessionStateInfo, SessionState},
services::{authentication as auth, authorization::roles, ApplicationResponse},
utils,
};
#[instrument(skip_all, fields(?session_id))]
pub async fn get_data_from_hyperswitch_ai_workflow(
state: SessionState,
user_from_token: auth::UserFromToken,
req: chat_api::ChatRequest,
session_id: Option<&str>,
) -> CustomResult<ApplicationResponse<chat_api::ChatResponse>, ChatErrors> {
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to retrieve role information")?;
let url = format!(
"{}/webhook",
state.conf.chat.get_inner().hyperswitch_ai_host
);
let request_id = state
.get_request_id()
.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
let request_body = chat_domain::HyperswitchAiDataRequest {
query: chat_domain::GetDataMessage {
message: req.message.clone(),
},
org_id: user_from_token.org_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
profile_id: user_from_token.profile_id.clone(),
entity_type: role_info.get_entity_type(),
};
logger::info!("Request for AI service: {:?}", request_body);
let mut request_builder = RequestBuilder::new()
.method(Method::Post)
.url(&url)
.attach_default_headers()
.header(consts::X_REQUEST_ID, &request_id)
.set_body(RequestContent::Json(Box::new(request_body.clone())));
if let Some(session_id) = session_id {
request_builder = request_builder.header(consts::X_CHAT_SESSION_ID, session_id);
}
let request = request_builder.build();
let response = http_client::send_request(
&state.conf.proxy,
request,
Some(consts::REQUEST_TIME_OUT_FOR_AI_SERVICE),
)
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Error when sending request to AI service")?
.json::<chat_api::ChatResponse>()
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Error when deserializing response from AI service")?;
let response_to_return = response.clone();
tokio::spawn(
async move {
let new_hyperswitch_ai_interaction = utils::chat::construct_hyperswitch_ai_interaction(
&state,
&user_from_token,
&req,
&response,
&request_id,
)
.await;
match new_hyperswitch_ai_interaction {
Ok(interaction) => {
let db = state.store.as_ref();
if let Err(e) = db.insert_hyperswitch_ai_interaction(interaction).await {
logger::error!("Failed to insert hyperswitch_ai_interaction: {:?}", e);
}
}
Err(e) => {
logger::error!("Failed to construct hyperswitch_ai_interaction: {:?}", e);
}
}
}
.in_current_span(),
);
Ok(ApplicationResponse::Json(response_to_return))
}
#[instrument(skip_all)]
pub async fn list_chat_conversations(
state: SessionState,
user_from_token: auth::UserFromToken,
req: chat_api::ChatListRequest,
) -> CustomResult<ApplicationResponse<chat_api::ChatListResponse>, ChatErrors> {
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to retrieve role information")?;
if !role_info.is_internal() {
return Err(error_stack::Report::new(ChatErrors::UnauthorizedAccess)
.attach_printable("Only internal roles are allowed for this operation"));
}
let db = state.store.as_ref();
let hyperswitch_ai_interactions = db
.list_hyperswitch_ai_interactions(
req.merchant_id,
req.limit.unwrap_or(consts::DEFAULT_LIST_LIMIT),
req.offset.unwrap_or(consts::DEFAULT_LIST_OFFSET),
)
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Error when fetching hyperswitch_ai_interactions")?;
let encryption_key = state.conf.chat.get_inner().encryption_key.clone().expose();
let key = match hex::decode(&encryption_key) {
Ok(key) => key,
Err(e) => {
router_env::logger::error!("Failed to decode encryption key: {}", e);
encryption_key.as_bytes().to_vec()
}
};
let mut conversations = Vec::new();
for interaction in hyperswitch_ai_interactions {
let user_query_encrypted = interaction
.user_query
.ok_or(ChatErrors::InternalServerError)
.attach_printable("Missing user_query field in hyperswitch_ai_interaction")?;
let response_encrypted = interaction
.response
.ok_or(ChatErrors::InternalServerError)
.attach_printable("Missing response field in hyperswitch_ai_interaction")?;
let user_query_decrypted_bytes = GcmAes256
.decode_message(&key, user_query_encrypted.into_inner())
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to decrypt user query")?;
let response_decrypted_bytes = GcmAes256
.decode_message(&key, response_encrypted.into_inner())
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to decrypt response")?;
let user_query_decrypted = String::from_utf8(user_query_decrypted_bytes)
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to convert decrypted user query to string")?;
let response_decrypted = serde_json::from_slice(&response_decrypted_bytes)
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to deserialize decrypted response")?;
conversations.push(chat_api::ChatConversation {
id: interaction.id,
session_id: interaction.session_id,
user_id: interaction.user_id,
merchant_id: interaction.merchant_id,
profile_id: interaction.profile_id,
org_id: interaction.org_id,
role_id: interaction.role_id,
user_query: user_query_decrypted.into(),
response: response_decrypted,
database_query: interaction.database_query,
interaction_status: interaction.interaction_status,
created_at: interaction.created_at,
});
}
return Ok(ApplicationResponse::Json(chat_api::ChatListResponse {
conversations,
}));
}
|
crates/router/src/core/chat.rs
|
router
|
full_file
| null | null | null | 1,630
| null | null | null | null | null | null | null |
// Function: get_payout_variant_values
// File: crates/euclid_wasm/src/lib.rs
// Module: euclid_wasm
pub fn get_payout_variant_values(key: &str) -> Result<JsValue, JsValue>
|
crates/euclid_wasm/src/lib.rs
|
euclid_wasm
|
function_signature
| null | null | null | 51
|
get_payout_variant_values
| null | null | null | null | null | null |
)
.change_context(errors::ApiErrorResponse::MaximumRefundCount)?;
let connector = payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("No connector populated in payment attempt")?;
let (connector_transaction_id, processor_transaction_data) =
common_utils_types::ConnectorTransactionId::form_id_and_data(connector_payment_id);
let refund_create_req = diesel_refund::RefundNew {
id: global_refund_id,
merchant_reference_id: merchant_reference_id.clone(),
external_reference_id: Some(merchant_reference_id.get_string_repr().to_string()),
payment_id: req.payment_id,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
connector_transaction_id,
connector,
refund_type: enums::RefundType::foreign_from(req.refund_type.unwrap_or_default()),
total_amount: payment_attempt.get_total_amount(),
refund_amount,
currency,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
refund_status: enums::RefundStatus::Pending,
metadata: req.metadata,
description: req.reason.clone(),
attempt_id: payment_attempt.id.clone(),
refund_reason: req.reason,
profile_id: Some(payment_intent.profile_id.clone()),
connector_id: payment_attempt.merchant_connector_id.clone(),
charges: None,
split_refunds: None,
connector_refund_id: None,
sent_to_gateway: Default::default(),
refund_arn: None,
updated_by: Default::default(),
organization_id: merchant_context
.get_merchant_account()
.organization_id
.clone(),
processor_transaction_data,
processor_refund_data: None,
};
let refund = match db
.insert_refund(
refund_create_req,
merchant_context.get_merchant_account().storage_scheme,
)
.await
{
Ok(refund) => {
Box::pin(schedule_refund_execution(
state,
refund.clone(),
refund_type,
merchant_context,
payment_attempt,
payment_intent,
merchant_connector_details,
))
.await?
}
Err(err) => {
if err.current_context().is_db_unique_violation() {
Err(errors::ApiErrorResponse::DuplicateRefundRequest)?
} else {
Err(err)
.change_context(errors::ApiErrorResponse::RefundFailed { data: None })
.attach_printable("Failed to insert refund")?
}
}
};
let unified_translated_message =
match (refund.unified_code.clone(), refund.unified_message.clone()) {
(Some(unified_code), Some(unified_message)) => helpers::get_unified_translation(
state,
unified_code,
unified_message.clone(),
state.locale.to_string(),
)
.await
.or(Some(unified_message)),
_ => refund.unified_message,
};
let refund = diesel_refund::Refund {
unified_message: unified_translated_message,
..refund
};
api::RefundResponse::foreign_try_from(refund)
}
impl ForeignTryFrom<diesel_refund::Refund> for api::RefundResponse {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(refund: diesel_refund::Refund) -> Result<Self, Self::Error> {
let refund = refund;
let profile_id = refund
.profile_id
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Profile id not found")?;
let connector_name = refund.connector;
let connector = Connector::from_str(&connector_name)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| {
format!("unable to parse connector name {connector_name:?}")
})?;
Ok(Self {
payment_id: refund.payment_id,
id: refund.id.clone(),
amount: refund.refund_amount,
currency: refund.currency,
reason: refund.refund_reason,
status: refunds::RefundStatus::foreign_from(refund.refund_status),
profile_id,
metadata: refund.metadata,
created_at: refund.created_at,
updated_at: refund.modified_at,
connector,
merchant_connector_id: refund.connector_id,
merchant_reference_id: Some(refund.merchant_reference_id),
error_details: Some(RefundErrorDetails {
code: refund.refund_error_code.unwrap_or_default(),
message: refund.refund_error_message.unwrap_or_default(),
}),
connector_refund_reference_id: None,
})
}
}
// ********************************************** PROCESS TRACKER **********************************************
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn schedule_refund_execution(
state: &SessionState,
refund: diesel_refund::Refund,
refund_type: api_models::refunds::RefundType,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>,
) -> errors::RouterResult<diesel_refund::Refund> {
let db = &*state.store;
let runner = storage::ProcessTrackerRunner::RefundWorkflowRouter;
let task = "EXECUTE_REFUND";
let task_id = format!("{runner}_{task}_{}", refund.id.get_string_repr());
let refund_process = db
.find_process_by_id(&task_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to find the process id")?;
let result = match refund.refund_status {
enums::RefundStatus::Pending | enums::RefundStatus::ManualReview => {
match (refund.sent_to_gateway, refund_process) {
(false, None) => {
// Execute the refund task based on refund_type
match refund_type {
api_models::refunds::RefundType::Scheduled => {
add_refund_execute_task(db, &refund, runner)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Failed while pushing refund execute task to scheduler, refund_id: {}", refund.id.get_string_repr()))?;
Ok(refund)
}
api_models::refunds::RefundType::Instant => {
let update_refund =
if state.conf.merchant_id_auth.merchant_id_auth_enabled {
let merchant_connector_details =
match merchant_connector_details {
Some(details) => details,
None => {
return Err(report!(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "merchant_connector_details"
}
));
}
};
Box::pin(internal_trigger_refund_to_gateway(
state,
&refund,
merchant_context,
payment_attempt,
payment_intent,
merchant_connector_details,
))
.await
} else {
Box::pin(trigger_refund_to_gateway(
state,
&refund,
merchant_context,
payment_attempt,
payment_intent,
))
.await
};
match update_refund {
Ok(updated_refund_data) => {
add_refund_sync_task(db, &updated_refund_data, runner)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!(
"Failed while pushing refund sync task in scheduler: refund_id: {}",
refund.id.get_string_repr()
))?;
Ok(updated_refund_data)
}
Err(err) => Err(err),
}
}
}
}
_ => {
// Sync the refund for status check
//[#300]: return refund status response
match refund_type {
api_models::refunds::RefundType::Scheduled => {
add_refund_sync_task(db, &refund, runner)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Failed while pushing refund sync task in scheduler: refund_id: {}", refund.id.get_string_repr()))?;
Ok(refund)
}
api_models::refunds::RefundType::Instant => {
// [#255]: This is not possible in schedule_refund_execution as it will always be scheduled
// sync_refund_with_gateway(data, &refund).await
Ok(refund)
}
}
}
}
}
// [#255]: This is not allowed to be otherwise or all
_ => Ok(refund),
}?;
Ok(result)
}
#[instrument]
pub fn refund_to_refund_core_workflow_model(
refund: &diesel_refund::Refund,
) -> diesel_refund::RefundCoreWorkflow {
diesel_refund::RefundCoreWorkflow {
refund_id: refund.id.clone(),
connector_transaction_id: refund.connector_transaction_id.clone(),
merchant_id: refund.merchant_id.clone(),
payment_id: refund.payment_id.clone(),
processor_transaction_data: refund.processor_transaction_data.clone(),
}
}
#[instrument(skip_all)]
pub async fn add_refund_execute_task(
db: &dyn db::StorageInterface,
refund: &diesel_refund::Refund,
runner: storage::ProcessTrackerRunner,
) -> errors::RouterResult<storage::ProcessTracker> {
let task = "EXECUTE_REFUND";
let process_tracker_id = format!("{runner}_{task}_{}", refund.id.get_string_repr());
let tag = ["REFUND"];
let schedule_time = common_utils::date_time::now();
let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund);
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
refund_workflow_tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct refund execute process tracker task")?;
let response = db
.insert_process(process_tracker_entry)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest)
.attach_printable_lazy(|| {
format!(
"Failed while inserting task in process_tracker: refund_id: {}",
refund.id.get_string_repr()
)
})?;
Ok(response)
}
#[instrument(skip_all)]
pub async fn add_refund_sync_task(
db: &dyn db::StorageInterface,
refund: &diesel_refund::Refund,
runner: storage::ProcessTrackerRunner,
) -> errors::RouterResult<storage::ProcessTracker> {
let task = "SYNC_REFUND";
let process_tracker_id = format!("{runner}_{task}_{}", refund.id.get_string_repr());
let schedule_time = common_utils::date_time::now();
let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund);
let tag = ["REFUND"];
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
refund_workflow_tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct refund sync process tracker task")?;
let response = db
.insert_process(process_tracker_entry)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest)
.attach_printable_lazy(|| {
format!(
"Failed while inserting task in process_tracker: refund_id: {}",
refund.id.get_string_repr()
)
})?;
metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "Refund")));
Ok(response)
}
|
crates/router/src/core/refunds_v2.rs#chunk1
|
router
|
chunk
| null | null | null | 2,555
| null | null | null | null | null | null | null |
) -> Result<Self, Self::Error> {
let email = item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let payment_information = PaymentInformation::try_from(&ccard)?;
let processing_information = ProcessingInformation::try_from((item, None, None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
let pares_status = Some(BarclaycardParesStatus::AuthenticationSuccessful);
let consumer_authentication_information = item
.router_data
.request
.authentication_data
.as_ref()
.map(|authn_data| {
let (ucaf_authentication_data, cavv, ucaf_collection_indicator) =
if ccard.card_network == Some(common_enums::CardNetwork::Mastercard) {
(Some(authn_data.cavv.clone()), None, Some("2".to_string()))
} else {
(None, Some(authn_data.cavv.clone()), None)
};
let authentication_date = date_time::format_date(
authn_data.created_at,
date_time::DateFormat::YYYYMMDDHHmmss,
)
.ok();
let effective_authentication_type = authn_data.authentication_type.map(Into::into);
let network_score: Option<u32> =
if ccard.card_network == Some(common_enums::CardNetwork::CartesBancaires) {
match authn_data.message_extension.as_ref() {
Some(secret) => {
let exposed_value = secret.clone().expose();
match serde_json::from_value::<Vec<MessageExtensionAttribute>>(
exposed_value,
) {
Ok(exts) => extract_score_id(&exts),
Err(err) => {
router_env::logger::error!(
"Failed to deserialize message_extension: {:?}",
err
);
None
}
}
}
None => None,
}
} else {
None
};
BarclaycardConsumerAuthInformation {
pares_status,
ucaf_collection_indicator,
cavv,
ucaf_authentication_data,
xid: None,
directory_server_transaction_id: authn_data
.ds_trans_id
.clone()
.map(Secret::new),
specification_version: authn_data.message_version.clone(),
pa_specification_version: authn_data.message_version.clone(),
veres_enrolled: Some("Y".to_string()),
eci_raw: authn_data.eci.clone(),
authentication_date,
effective_authentication_type,
challenge_code: authn_data.challenge_code.clone(),
pares_status_reason: authn_data.challenge_code_reason.clone(),
challenge_cancel_code: authn_data.challenge_cancel.clone(),
network_score,
acs_transaction_id: authn_data.acs_trans_id.clone(),
}
});
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information,
})
}
}
impl
TryFrom<(
&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>,
hyperswitch_domain_models::payment_method_data::Card,
)> for BarclaycardPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, ccard): (
&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>,
hyperswitch_domain_models::payment_method_data::Card,
),
) -> Result<Self, Self::Error> {
let email = item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?;
let order_information = OrderInformationWithBill::from((item, bill_to));
let payment_information = PaymentInformation::try_from(&ccard)?;
let processing_information = ProcessingInformation::try_from((item, None, None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
let pares_status = Some(BarclaycardParesStatus::AuthenticationSuccessful);
let three_ds_info: BarclaycardThreeDSMetadata = item
.router_data
.request
.connector_meta
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "connector_meta",
})?
.parse_value("BarclaycardThreeDSMetadata")
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
let consumer_authentication_information = Some(BarclaycardConsumerAuthInformation {
pares_status,
ucaf_collection_indicator: three_ds_info.three_ds_data.ucaf_collection_indicator,
cavv: three_ds_info.three_ds_data.cavv,
ucaf_authentication_data: three_ds_info.three_ds_data.ucaf_authentication_data,
xid: three_ds_info.three_ds_data.xid,
directory_server_transaction_id: three_ds_info
.three_ds_data
.directory_server_transaction_id,
specification_version: three_ds_info.three_ds_data.specification_version.clone(),
pa_specification_version: three_ds_info.three_ds_data.specification_version.clone(),
veres_enrolled: None,
eci_raw: None,
authentication_date: None,
effective_authentication_type: None,
challenge_code: None,
pares_status_reason: None,
challenge_cancel_code: None,
network_score: None,
acs_transaction_id: None,
});
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information,
})
}
}
impl
TryFrom<(
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
GooglePayWalletData,
)> for BarclaycardPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, google_pay_data): (
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
GooglePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let payment_information = PaymentInformation::try_from(&google_pay_data)?;
let processing_information =
ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay), None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: None,
})
}
}
impl
TryFrom<(
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
ApplePayWalletData,
)> for BarclaycardPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, apple_pay_data, apple_pay_wallet_data): (
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
ApplePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let processing_information =
ProcessingInformation::try_from((item, Some(PaymentSolution::ApplePay), None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let expiration_month = apple_pay_data.get_expiry_month().change_context(
errors::ConnectorError::InvalidDataFormat {
field_name: "expiration_month",
},
)?;
let expiration_year = apple_pay_data.get_four_digit_expiry_year();
let payment_information =
PaymentInformation::ApplePay(Box::new(ApplePayPaymentInformation {
tokenized_card: TokenizedCard {
number: apple_pay_data.application_primary_account_number,
cryptogram: Some(apple_pay_data.payment_data.online_payment_cryptogram),
transaction_type: TransactionType::InApp,
expiration_year,
expiration_month,
},
}));
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
let ucaf_collection_indicator = match apple_pay_wallet_data
.payment_method
.network
.to_lowercase()
.as_str()
{
"mastercard" => Some("2".to_string()),
_ => None,
};
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
consumer_authentication_information: Some(BarclaycardConsumerAuthInformation {
ucaf_collection_indicator,
cavv: None,
ucaf_authentication_data: None,
xid: None,
directory_server_transaction_id: None,
specification_version: None,
pa_specification_version: None,
veres_enrolled: None,
eci_raw: None,
pares_status: None,
authentication_date: None,
effective_authentication_type: None,
challenge_code: None,
pares_status_reason: None,
challenge_cancel_code: None,
network_score: None,
acs_transaction_id: None,
}),
merchant_defined_information,
})
}
}
impl TryFrom<&BarclaycardRouterData<&PaymentsAuthorizeRouterData>> for BarclaycardPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::GooglePay(google_pay_data) => Self::try_from((item, google_pay_data)),
WalletData::ApplePay(apple_pay_data) => {
match item.router_data.payment_method_token.clone() {
Some(payment_method_token) => match payment_method_token {
PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
Self::try_from((item, decrypt_data, apple_pay_data))
}
PaymentMethodToken::Token(_) => Err(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Cybersource"
))?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Cybersource"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Cybersource"))?
}
},
None => {
let transaction_type = TransactionType::InApp;
let email = item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to =
build_bill_to(item.router_data.get_billing_address()?, email)?;
let order_information =
OrderInformationWithBill::from((item, Some(bill_to)));
let processing_information = ProcessingInformation::try_from((
item,
Some(PaymentSolution::ApplePay),
Some(apple_pay_data.payment_method.network.clone()),
))?;
let client_reference_information =
ClientReferenceInformation::from(item);
let apple_pay_encrypted_data = apple_pay_data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
let payment_information = PaymentInformation::ApplePayToken(Box::new(
ApplePayTokenPaymentInformation {
fluid_data: FluidData {
value: Secret::from(apple_pay_encrypted_data.clone()),
descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()),
},
tokenized_card: ApplePayTokenizedCard { transaction_type },
},
));
let merchant_defined_information =
item.router_data.request.metadata.clone().map(|metadata| {
convert_metadata_to_merchant_defined_info(metadata)
});
let ucaf_collection_indicator = match apple_pay_data
.payment_method
.network
.to_lowercase()
.as_str()
{
"mastercard" => Some("2".to_string()),
_ => None,
};
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: Some(
BarclaycardConsumerAuthInformation {
ucaf_collection_indicator,
cavv: None,
ucaf_authentication_data: None,
xid: None,
directory_server_transaction_id: None,
specification_version: None,
pa_specification_version: None,
veres_enrolled: None,
eci_raw: None,
pares_status: None,
authentication_date: None,
effective_authentication_type: None,
challenge_code: None,
pares_status_reason: None,
challenge_cancel_code: None,
network_score: None,
acs_transaction_id: None,
},
),
})
}
}
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::RevolutPay(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::AmazonPay(_)
| WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Barclaycard"),
)
.into()),
},
PaymentMethodData::MandatePayment
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Barclaycard"),
)
.into())
}
}
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BarclaycardAuthSetupResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BarclaycardAuthSetupResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
BarclaycardAuthSetupResponse::ClientAuthSetupInfo(info_response) => Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::BarclaycardAuthSetup {
access_token: info_response
.consumer_authentication_information
.access_token,
ddc_url: info_response
.consumer_authentication_information
.device_data_collection_url,
reference_id: info_response
.consumer_authentication_information
.reference_id,
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
info_response
.client_reference_information
.code
.unwrap_or(info_response.id.clone()),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
BarclaycardAuthSetupResponse::ErrorInformation(error_response) => {
let detailed_error_info =
error_response
.error_information
.details
.to_owned()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message,
detailed_error_info,
None,
);
let error_message = error_response.error_information.reason;
Ok(Self {
response: Err(ErrorResponse {
code: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_message.unwrap_or(
hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string(),
),
reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
status: enums::AttemptStatus::AuthenticationFailed,
..item.data
})
}
}
}
}
impl TryFrom<&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>>
for BarclaycardPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "payment_method_data",
},
)?;
match payment_method_data {
PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)),
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Barclaycard"),
)
.into())
}
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BarclaycardPaymentStatus {
Authorized,
Succeeded,
Failed,
Voided,
Reversed,
Pending,
Declined,
Rejected,
Challenge,
AuthorizedPendingReview,
AuthorizedRiskDeclined,
Transmitted,
InvalidRequest,
ServerError,
PendingAuthentication,
PendingReview,
Accepted,
Cancelled,
StatusNotReceived,
//PartialAuthorized, not being consumed yet.
}
fn map_barclaycard_attempt_status(
(status, auto_capture): (BarclaycardPaymentStatus, bool),
) -> enums::AttemptStatus {
match status {
BarclaycardPaymentStatus::Authorized
| BarclaycardPaymentStatus::AuthorizedPendingReview => {
if auto_capture {
// Because Barclaycard will return Payment Status as Authorized even in AutoCapture Payment
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
BarclaycardPaymentStatus::Pending => {
if auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Pending
}
}
BarclaycardPaymentStatus::Succeeded | BarclaycardPaymentStatus::Transmitted => {
enums::AttemptStatus::Charged
}
BarclaycardPaymentStatus::Voided
| BarclaycardPaymentStatus::Reversed
| BarclaycardPaymentStatus::Cancelled => enums::AttemptStatus::Voided,
BarclaycardPaymentStatus::Failed
| BarclaycardPaymentStatus::Declined
| BarclaycardPaymentStatus::AuthorizedRiskDeclined
| BarclaycardPaymentStatus::InvalidRequest
| BarclaycardPaymentStatus::Rejected
| BarclaycardPaymentStatus::ServerError => enums::AttemptStatus::Failure,
BarclaycardPaymentStatus::PendingAuthentication => {
enums::AttemptStatus::AuthenticationPending
}
BarclaycardPaymentStatus::PendingReview
| BarclaycardPaymentStatus::StatusNotReceived
| BarclaycardPaymentStatus::Challenge
| BarclaycardPaymentStatus::Accepted => enums::AttemptStatus::Pending,
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BarclaycardPaymentsResponse {
ClientReferenceInformation(Box<BarclaycardClientReferenceResponse>),
ErrorInformation(Box<BarclaycardErrorInformationResponse>),
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardClientReferenceResponse {
id: String,
status: Option<BarclaycardPaymentStatus>,
client_reference_information: ClientReferenceInformation,
processor_information: Option<ClientProcessorInformation>,
processing_information: Option<ProcessingInformationResponse>,
payment_information: Option<PaymentInformationResponse>,
payment_insights_information: Option<PaymentInsightsInformation>,
risk_information: Option<ClientRiskInformation>,
error_information: Option<BarclaycardErrorInformation>,
issuer_information: Option<IssuerInformation>,
sender_information: Option<SenderInformation>,
payment_account_information: Option<PaymentAccountInformation>,
reconciliation_id: Option<String>,
consumer_authentication_information: Option<ConsumerAuthenticationInformation>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConsumerAuthenticationInformation {
eci_raw: Option<String>,
eci: Option<String>,
acs_transaction_id: Option<String>,
cavv: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SenderInformation {
payment_information: Option<PaymentInformationResponse>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInsightsInformation {
response_insights: Option<ResponseInsights>,
rule_results: Option<RuleResults>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResponseInsights {
category_code: Option<String>,
category: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RuleResults {
id: Option<String>,
decision: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInformationResponse {
tokenized_card: Option<CardResponseObject>,
customer: Option<CustomerResponseObject>,
card: Option<CardResponseObject>,
scheme: Option<String>,
bin: Option<String>,
account_type: Option<String>,
issuer: Option<String>,
bin_country: Option<enums::CountryAlpha2>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomerResponseObject {
customer_id: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentAccountInformation {
card: Option<PaymentAccountCardInformation>,
features: Option<PaymentAccountFeatureInformation>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentAccountFeatureInformation {
health_card: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentAccountCardInformation {
#[serde(rename = "type")]
card_type: Option<String>,
hashed_number: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingInformationResponse {
payment_solution: Option<String>,
commerce_indicator: Option<String>,
commerce_indicator_label: Option<String>,
ecommerce_indicator: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IssuerInformation {
country: Option<enums::CountryAlpha2>,
discretionary_data: Option<String>,
country_specific_discretionary_data: Option<String>,
response_code: Option<String>,
pin_request_indicator: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardResponseObject {
suffix: Option<String>,
prefix: Option<String>,
expiration_month: Option<Secret<String>>,
expiration_year: Option<Secret<String>>,
#[serde(rename = "type")]
card_type: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardErrorInformationResponse {
id: String,
error_information: BarclaycardErrorInformation,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct BarclaycardErrorInformation {
reason: Option<String>,
message: Option<String>,
details: Option<Vec<Details>>,
}
fn map_error_response<F, T>(
error_response: &BarclaycardErrorInformationResponse,
item: ResponseRouterData<F, BarclaycardPaymentsResponse, T, PaymentsResponseData>,
transaction_status: Option<enums::AttemptStatus>,
) -> RouterData<F, T, PaymentsResponseData> {
let detailed_error_info = error_response
.error_information
.details
.as_ref()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message.clone(),
detailed_error_info,
None,
);
let response = Err(ErrorResponse {
code: error_response
.error_information
.reason
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_response
.error_information
.reason
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
match transaction_status {
Some(status) => RouterData {
response,
status,
..item.data
},
None => RouterData {
response,
..item.data
},
}
}
fn get_error_response_if_failure(
(info_response, status, http_code): (
&BarclaycardClientReferenceResponse,
enums::AttemptStatus,
u16,
),
) -> Option<ErrorResponse> {
if utils::is_payment_failure(status) {
Some(get_error_response(
&info_response.error_information,
&info_response.processor_information,
&info_response.risk_information,
Some(status),
http_code,
info_response.id.clone(),
))
} else {
None
}
}
fn get_payment_response(
(info_response, status, http_code): (
&BarclaycardClientReferenceResponse,
enums::AttemptStatus,
u16,
),
) -> Result<PaymentsResponseData, Box<ErrorResponse>> {
let error_response = get_error_response_if_failure((info_response, status, http_code));
match error_response {
Some(error) => Err(Box::new(error)),
None => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(info_response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
info_response
.client_reference_information
.code
.clone()
.unwrap_or(info_response.id.clone()),
),
incremental_authorization_allowed: None,
charges: None,
}),
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BarclaycardPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BarclaycardPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
BarclaycardPaymentsResponse::ClientReferenceInformation(info_response) => {
let status = map_barclaycard_attempt_status((
info_response
.status
.clone()
.unwrap_or(BarclaycardPaymentStatus::StatusNotReceived),
item.data.request.is_auto_capture()?,
));
let response = get_payment_response((&info_response, status, item.http_code))
.map_err(|err| *err);
let connector_response = match item.data.payment_method {
common_enums::PaymentMethod::Card => info_response
.processor_information
.as_ref()
.and_then(|processor_information| {
info_response
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
convert_to_additional_payment_method_connector_response(
processor_information,
consumer_auth_information,
)
})
})
.map(ConnectorResponseData::with_additional_payment_method_data),
common_enums::PaymentMethod::CardRedirect
| common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::Wallet
| common_enums::PaymentMethod::BankRedirect
| common_enums::PaymentMethod::BankTransfer
| common_enums::PaymentMethod::Crypto
| common_enums::PaymentMethod::BankDebit
| common_enums::PaymentMethod::Reward
| common_enums::PaymentMethod::RealTimePayment
| common_enums::PaymentMethod::MobilePayment
| common_enums::PaymentMethod::Upi
| common_enums::PaymentMethod::Voucher
| common_enums::PaymentMethod::OpenBanking
| common_enums::PaymentMethod::GiftCard => None,
};
Ok(Self {
status,
response,
connector_response,
..item.data
})
}
BarclaycardPaymentsResponse::ErrorInformation(ref error_response) => {
Ok(map_error_response(
&error_response.clone(),
item,
Some(enums::AttemptStatus::Failure),
))
}
}
}
}
fn convert_to_additional_payment_method_connector_response(
processor_information: &ClientProcessorInformation,
consumer_authentication_information: &ConsumerAuthenticationInformation,
) -> AdditionalPaymentMethodConnectorResponse {
let payment_checks = Some(serde_json::json!({
"avs_response": processor_information.avs,
"card_verification": processor_information.card_verification,
"approval_code": processor_information.approval_code,
"consumer_authentication_response": processor_information.consumer_authentication_response,
"cavv": consumer_authentication_information.cavv,
"eci": consumer_authentication_information.eci,
"eci_raw": consumer_authentication_information.eci_raw,
}));
let authentication_data = Some(serde_json::json!({
"retrieval_reference_number": processor_information.retrieval_reference_number,
"acs_transaction_id": consumer_authentication_information.acs_transaction_id,
"system_trace_audit_number": processor_information.system_trace_audit_number,
}));
AdditionalPaymentMethodConnectorResponse::Card {
authentication_data,
payment_checks,
card_network: None,
domestic_network: None,
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BarclaycardPaymentsResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BarclaycardPaymentsResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
BarclaycardPaymentsResponse::ClientReferenceInformation(info_response) => {
let status = map_barclaycard_attempt_status((
info_response
.status
.clone()
.unwrap_or(BarclaycardPaymentStatus::StatusNotReceived),
true,
));
let response = get_payment_response((&info_response, status, item.http_code))
.map_err(|err| *err);
Ok(Self {
status,
response,
..item.data
})
}
BarclaycardPaymentsResponse::ErrorInformation(ref error_response) => {
Ok(map_error_response(&error_response.clone(), item, None))
}
}
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
BarclaycardPaymentsResponse,
PaymentsCancelData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
BarclaycardPaymentsResponse,
PaymentsCancelData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
BarclaycardPaymentsResponse::ClientReferenceInformation(info_response) => {
let status = map_barclaycard_attempt_status((
info_response
.status
.clone()
.unwrap_or(BarclaycardPaymentStatus::StatusNotReceived),
false,
));
let response = get_payment_response((&info_response, status, item.http_code))
.map_err(|err| *err);
Ok(Self {
status,
response,
..item.data
})
}
BarclaycardPaymentsResponse::ErrorInformation(ref error_response) => {
Ok(map_error_response(&error_response.clone(), item, None))
}
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardTransactionResponse {
id: String,
application_information: ApplicationInformation,
client_reference_information: Option<ClientReferenceInformation>,
processor_information: Option<ClientProcessorInformation>,
processing_information: Option<ProcessingInformationResponse>,
payment_information: Option<PaymentInformationResponse>,
payment_insights_information: Option<PaymentInsightsInformation>,
error_information: Option<BarclaycardErrorInformation>,
fraud_marking_information: Option<FraudMarkingInformation>,
risk_information: Option<ClientRiskInformation>,
reconciliation_id: Option<String>,
consumer_authentication_information: Option<ConsumerAuthenticationInformation>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FraudMarkingInformation {
reason: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs#chunk1
|
hyperswitch_connectors
|
chunk
| null | null | null | 8,192
| null | null | null | null | null | null | null |
// Struct: MerchantAccountSetter
// File: crates/hyperswitch_domain_models/src/merchant_account.rs
// Module: hyperswitch_domain_models
// Implementations: 0
// Documentation: Set the private fields of merchant account
pub struct MerchantAccountSetter
|
crates/hyperswitch_domain_models/src/merchant_account.rs
|
hyperswitch_domain_models
|
struct_definition
|
MerchantAccountSetter
| 0
|
[] | 54
| null | null | null | null | null | null | null |
// File: crates/storage_impl/src/callback_mapper.rs
// Module: storage_impl
use diesel_models::callback_mapper::CallbackMapper as DieselCallbackMapper;
use hyperswitch_domain_models::callback_mapper::CallbackMapper;
use crate::DataModelExt;
impl DataModelExt for CallbackMapper {
type StorageModel = DieselCallbackMapper;
fn to_storage_model(self) -> Self::StorageModel {
DieselCallbackMapper {
id: self.id,
type_: self.callback_mapper_id_type,
data: self.data,
created_at: self.created_at,
last_modified_at: self.last_modified_at,
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
Self {
id: storage_model.id,
callback_mapper_id_type: storage_model.type_,
data: storage_model.data,
created_at: storage_model.created_at,
last_modified_at: storage_model.last_modified_at,
}
}
}
|
crates/storage_impl/src/callback_mapper.rs
|
storage_impl
|
full_file
| null | null | null | 196
| null | null | null | null | null | null | null |
// Implementation: impl RefundMetricsAccumulator
// File: crates/analytics/src/refunds/accumulator.rs
// Module: analytics
// Methods: 1 total (1 public)
impl RefundMetricsAccumulator
|
crates/analytics/src/refunds/accumulator.rs
|
analytics
|
impl_block
| null | null | null | 46
| null |
RefundMetricsAccumulator
| null | 1
| 1
| null | null |
// File: crates/diesel_models/src/mandate.rs
// Module: diesel_models
// Public functions: 5
// Public structs: 4
use common_enums::MerchantStorageScheme;
use common_utils::pii;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::Secret;
use time::PrimitiveDateTime;
use crate::{enums as storage_enums, schema::mandate};
#[derive(
Clone, Debug, Identifiable, Queryable, Selectable, serde::Serialize, serde::Deserialize,
)]
#[diesel(table_name = mandate, primary_key(mandate_id), check_for_backend(diesel::pg::Pg))]
pub struct Mandate {
pub mandate_id: String,
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
pub mandate_status: storage_enums::MandateStatus,
pub mandate_type: storage_enums::MandateType,
pub customer_accepted_at: Option<PrimitiveDateTime>,
pub customer_ip_address: Option<Secret<String, pii::IpAddress>>,
pub customer_user_agent: Option<String>,
pub network_transaction_id: Option<String>,
pub previous_attempt_id: Option<String>,
pub created_at: PrimitiveDateTime,
pub mandate_amount: Option<i64>,
pub mandate_currency: Option<storage_enums::Currency>,
pub amount_captured: Option<i64>,
pub connector: String,
pub connector_mandate_id: Option<String>,
pub start_date: Option<PrimitiveDateTime>,
pub end_date: Option<PrimitiveDateTime>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_mandate_ids: Option<pii::SecretSerdeValue>,
pub original_payment_id: Option<common_utils::id_type::PaymentId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub updated_by: Option<String>,
// This is the extended version of customer user agent that can store string upto 2048 characters unlike customer user agent that can store 255 characters at max
pub customer_user_agent_extended: Option<String>,
}
#[derive(
router_derive::Setter,
Clone,
Debug,
Default,
Insertable,
router_derive::DebugAsDisplay,
serde::Serialize,
serde::Deserialize,
)]
#[diesel(table_name = mandate)]
pub struct MandateNew {
pub mandate_id: String,
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
pub mandate_status: storage_enums::MandateStatus,
pub mandate_type: storage_enums::MandateType,
pub customer_accepted_at: Option<PrimitiveDateTime>,
pub customer_ip_address: Option<Secret<String, pii::IpAddress>>,
pub customer_user_agent: Option<String>,
pub network_transaction_id: Option<String>,
pub previous_attempt_id: Option<String>,
pub created_at: Option<PrimitiveDateTime>,
pub mandate_amount: Option<i64>,
pub mandate_currency: Option<storage_enums::Currency>,
pub amount_captured: Option<i64>,
pub connector: String,
pub connector_mandate_id: Option<String>,
pub start_date: Option<PrimitiveDateTime>,
pub end_date: Option<PrimitiveDateTime>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_mandate_ids: Option<pii::SecretSerdeValue>,
pub original_payment_id: Option<common_utils::id_type::PaymentId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub updated_by: Option<String>,
pub customer_user_agent_extended: Option<String>,
}
impl Mandate {
/// Returns customer_user_agent_extended with customer_user_agent as fallback
pub fn get_user_agent_extended(&self) -> Option<String> {
self.customer_user_agent_extended
.clone()
.or_else(|| self.customer_user_agent.clone())
}
}
impl MandateNew {
pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) {
self.updated_by = Some(storage_scheme.to_string());
}
/// Returns customer_user_agent_extended with customer_user_agent as fallback
pub fn get_customer_user_agent_extended(&self) -> Option<String> {
self.customer_user_agent_extended
.clone()
.or_else(|| self.customer_user_agent.clone())
}
}
#[derive(Debug)]
pub enum MandateUpdate {
StatusUpdate {
mandate_status: storage_enums::MandateStatus,
},
CaptureAmountUpdate {
amount_captured: Option<i64>,
},
ConnectorReferenceUpdate {
connector_mandate_ids: Option<pii::SecretSerdeValue>,
},
ConnectorMandateIdUpdate {
connector_mandate_id: Option<String>,
connector_mandate_ids: Option<pii::SecretSerdeValue>,
payment_method_id: String,
original_payment_id: Option<common_utils::id_type::PaymentId>,
},
}
impl MandateUpdate {
pub fn convert_to_mandate_update(
self,
storage_scheme: MerchantStorageScheme,
) -> MandateUpdateInternal {
let mut updated_object = MandateUpdateInternal::from(self);
updated_object.updated_by = Some(storage_scheme.to_string());
updated_object
}
}
#[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct SingleUseMandate {
pub amount: i64,
pub currency: storage_enums::Currency,
}
#[derive(
Clone,
Debug,
Default,
AsChangeset,
router_derive::DebugAsDisplay,
serde::Serialize,
serde::Deserialize,
)]
#[diesel(table_name = mandate)]
pub struct MandateUpdateInternal {
mandate_status: Option<storage_enums::MandateStatus>,
amount_captured: Option<i64>,
connector_mandate_ids: Option<pii::SecretSerdeValue>,
connector_mandate_id: Option<String>,
payment_method_id: Option<String>,
original_payment_id: Option<common_utils::id_type::PaymentId>,
updated_by: Option<String>,
}
impl From<MandateUpdate> for MandateUpdateInternal {
fn from(mandate_update: MandateUpdate) -> Self {
match mandate_update {
MandateUpdate::StatusUpdate { mandate_status } => Self {
mandate_status: Some(mandate_status),
connector_mandate_ids: None,
amount_captured: None,
connector_mandate_id: None,
payment_method_id: None,
original_payment_id: None,
updated_by: None,
},
MandateUpdate::CaptureAmountUpdate { amount_captured } => Self {
mandate_status: None,
amount_captured,
connector_mandate_ids: None,
connector_mandate_id: None,
payment_method_id: None,
original_payment_id: None,
updated_by: None,
},
MandateUpdate::ConnectorReferenceUpdate {
connector_mandate_ids,
} => Self {
connector_mandate_ids,
..Default::default()
},
MandateUpdate::ConnectorMandateIdUpdate {
connector_mandate_id,
connector_mandate_ids,
payment_method_id,
original_payment_id,
} => Self {
connector_mandate_id,
connector_mandate_ids,
payment_method_id: Some(payment_method_id),
original_payment_id,
..Default::default()
},
}
}
}
impl MandateUpdateInternal {
pub fn apply_changeset(self, source: Mandate) -> Mandate {
let Self {
mandate_status,
amount_captured,
connector_mandate_ids,
connector_mandate_id,
payment_method_id,
original_payment_id,
updated_by,
} = self;
Mandate {
mandate_status: mandate_status.unwrap_or(source.mandate_status),
amount_captured: amount_captured.map_or(source.amount_captured, Some),
connector_mandate_ids: connector_mandate_ids.map_or(source.connector_mandate_ids, Some),
connector_mandate_id: connector_mandate_id.map_or(source.connector_mandate_id, Some),
payment_method_id: payment_method_id.unwrap_or(source.payment_method_id),
original_payment_id: original_payment_id.map_or(source.original_payment_id, Some),
updated_by: updated_by.map_or(source.updated_by, Some),
..source
}
}
}
impl From<&MandateNew> for Mandate {
fn from(mandate_new: &MandateNew) -> Self {
Self {
mandate_id: mandate_new.mandate_id.clone(),
customer_id: mandate_new.customer_id.clone(),
merchant_id: mandate_new.merchant_id.clone(),
payment_method_id: mandate_new.payment_method_id.clone(),
mandate_status: mandate_new.mandate_status,
mandate_type: mandate_new.mandate_type,
customer_accepted_at: mandate_new.customer_accepted_at,
customer_ip_address: mandate_new.customer_ip_address.clone(),
customer_user_agent: None,
network_transaction_id: mandate_new.network_transaction_id.clone(),
previous_attempt_id: mandate_new.previous_attempt_id.clone(),
created_at: mandate_new
.created_at
.unwrap_or_else(common_utils::date_time::now),
mandate_amount: mandate_new.mandate_amount,
mandate_currency: mandate_new.mandate_currency,
amount_captured: mandate_new.amount_captured,
connector: mandate_new.connector.clone(),
connector_mandate_id: mandate_new.connector_mandate_id.clone(),
start_date: mandate_new.start_date,
end_date: mandate_new.end_date,
metadata: mandate_new.metadata.clone(),
connector_mandate_ids: mandate_new.connector_mandate_ids.clone(),
original_payment_id: mandate_new.original_payment_id.clone(),
merchant_connector_id: mandate_new.merchant_connector_id.clone(),
updated_by: mandate_new.updated_by.clone(),
// Using customer_user_agent as a fallback
customer_user_agent_extended: mandate_new.get_customer_user_agent_extended(),
}
}
}
|
crates/diesel_models/src/mandate.rs
|
diesel_models
|
full_file
| null | null | null | 2,181
| null | null | null | null | null | null | null |
// Struct: SuccessBasedRoutingConfig
// File: crates/api_models/src/routing.rs
// Module: api_models
// Implementations: 2
// Traits: Default
pub struct SuccessBasedRoutingConfig
|
crates/api_models/src/routing.rs
|
api_models
|
struct_definition
|
SuccessBasedRoutingConfig
| 2
|
[
"Default"
] | 43
| null | null | null | null | null | null | null |
// Function: make_all_aggregator
// File: crates/hyperswitch_constraint_graph/src/builder.rs
// Module: hyperswitch_constraint_graph
pub fn make_all_aggregator<M: Metadata>(
&mut self,
nodes: &[(NodeId, Relation, Strength)
|
crates/hyperswitch_constraint_graph/src/builder.rs
|
hyperswitch_constraint_graph
|
function_signature
| null | null | null | 57
|
make_all_aggregator
| null | null | null | null | null | null |
// Function: get_optional_connector_metadata
// File: crates/hyperswitch_domain_models/src/payments.rs
// Module: hyperswitch_domain_models
pub fn get_optional_connector_metadata(
&self,
) -> CustomResult<
Option<api_models::payments::ConnectorMetadata>,
common_utils::errors::ParsingError,
>
|
crates/hyperswitch_domain_models/src/payments.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 70
|
get_optional_connector_metadata
| 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.