id stringlengths 11 116 | type stringclasses 1 value | granularity stringclasses 4 values | content stringlengths 16 477k | metadata dict |
|---|---|---|---|---|
file_router_-2772609402682719321 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/payments/operations/payment_create.rs
// Contains: 1 structs, 0 enums
use std::marker::PhantomData;
use api_models::{
enums::FrmSuggestion, mandates::RecurringDetails, payment_methods::PaymentMethodsData,
payments::GetAddressFromPaymentMethodData,
};
use async_trait::async_trait;
use common_types::payments as common_payments_types;
use common_utils::{
ext_traits::{AsyncExt, Encode, ValueExt},
type_name,
types::{
keymanager::{Identifier, KeyManagerState, ToEncryptable},
MinorUnit,
},
};
use diesel_models::{
ephemeral_key,
payment_attempt::ConnectorMandateReferenceId as DieselConnectorMandateReferenceId,
};
use error_stack::{self, ResultExt};
use hyperswitch_domain_models::{
mandates::MandateDetails,
payments::{
payment_attempt::PaymentAttempt, payment_intent::CustomerData,
FromRequestEncryptablePaymentIntent,
},
};
use masking::{ExposeInterface, PeekInterface, Secret};
use router_derive::PaymentOperation;
use router_env::{instrument, logger, tracing};
use time::PrimitiveDateTime;
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
consts,
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payment_link,
payment_methods::cards::create_encrypted_data,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
db::StorageInterface,
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
domain,
storage::{
self,
enums::{self, IntentStatus},
},
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::{self, OptionExt},
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
#[operation(operations = "all", flow = "authorize")]
pub struct PaymentCreate;
type PaymentCreateOperation<'a, F> = BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>>;
/// The `get_trackers` function for `PaymentsCreate` is an entrypoint for new payments
/// This will create all the entities required for a new payment from the request
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentCreate {
#[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 db = &*state.store;
let key_manager_state = &state.into();
let ephemeral_key = Self::get_ephemeral_key(request, state, merchant_context).await;
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let money @ (amount, currency) = payments_create_request_validation(request)?;
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
#[cfg(feature = "v1")]
helpers::validate_business_details(
request.business_country,
request.business_label.as_ref(),
merchant_context,
)?;
// If profile id is not passed, get it from the business_country and business_label
#[cfg(feature = "v1")]
let profile_id = core_utils::get_profile_id_from_business_details(
key_manager_state,
request.business_country,
request.business_label.as_ref(),
merchant_context,
request.profile_id.as_ref(),
&*state.store,
true,
)
.await?;
// Profile id will be mandatory in v2 in the request / headers
#[cfg(feature = "v2")]
let profile_id = request
.profile_id
.clone()
.get_required_value("profile_id")
.attach_printable("Profile id is a mandatory parameter")?;
// TODO: eliminate a redundant db call to fetch the business profile
// Validate whether profile_id passed in request is valid and is linked to the merchant
let business_profile = if let Some(business_profile) =
core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_id,
)
.await?
{
business_profile
} else {
db.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?
};
let customer_acceptance = request.customer_acceptance.clone();
let recurring_details = request.recurring_details.clone();
let mandate_type = m_helpers::get_mandate_type(
request.mandate_data.clone(),
request.off_session,
request.setup_future_usage,
request.customer_acceptance.clone(),
request.payment_token.clone(),
request.payment_method,
)
.change_context(errors::ApiErrorResponse::MandateValidationFailed {
reason: "Expected one out of recurring_details and mandate_data but got both".into(),
})?;
let m_helpers::MandateGenericData {
token,
payment_method,
payment_method_type,
mandate_data,
recurring_mandate_payment_data,
mandate_connector,
payment_method_info,
} = helpers::get_token_pm_type_mandate_details(
state,
request,
mandate_type,
merchant_context,
None,
None,
)
.await?;
helpers::validate_allowed_payment_method_types_request(
state,
&profile_id,
merchant_context,
request.allowed_payment_method_types.clone(),
)
.await?;
let customer_details = helpers::get_customer_details_from_request(request);
let shipping_address = helpers::create_or_find_address_for_payment_by_request(
state,
request.shipping.as_ref(),
None,
merchant_id,
customer_details.customer_id.as_ref(),
merchant_context.get_merchant_key_store(),
&payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::create_or_find_address_for_payment_by_request(
state,
request.billing.as_ref(),
None,
merchant_id,
customer_details.customer_id.as_ref(),
merchant_context.get_merchant_key_store(),
&payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing_address =
helpers::create_or_find_address_for_payment_by_request(
state,
request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.billing.as_ref()),
None,
merchant_id,
customer_details.customer_id.as_ref(),
merchant_context.get_merchant_key_store(),
&payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let browser_info = request
.browser_info
.clone()
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let attempt_id = if core_utils::is_merchant_enabled_for_payment_id_as_connector_request_id(
&state.conf,
merchant_id,
) {
payment_id.get_string_repr().to_string()
} else {
payment_id.get_attempt_id(1)
};
let session_expiry =
common_utils::date_time::now().saturating_add(time::Duration::seconds(
request.session_expiry.map(i64::from).unwrap_or(
business_profile
.session_expiry
.unwrap_or(consts::DEFAULT_SESSION_EXPIRY),
),
));
let payment_link_data = match request.payment_link {
Some(true) => {
let merchant_name = merchant_context
.get_merchant_account()
.merchant_name
.clone()
.map(|name| name.into_inner().peek().to_owned())
.unwrap_or_default();
let default_domain_name = state.base_url.clone();
let (payment_link_config, domain_name) =
payment_link::get_payment_link_config_based_on_priority(
request.payment_link_config.clone(),
business_profile.payment_link_config.clone(),
merchant_name,
default_domain_name,
request.payment_link_config_id.clone(),
)?;
create_payment_link(
request,
payment_link_config,
merchant_id,
payment_id.clone(),
db,
amount,
request.description.clone(),
profile_id.clone(),
domain_name,
session_expiry,
header_payload.locale.clone(),
)
.await?
}
_ => None,
};
let payment_intent_new = Self::make_payment_intent(
state,
&payment_id,
merchant_context,
money,
request,
shipping_address
.as_ref()
.map(|address| address.address_id.clone()),
payment_link_data.clone(),
billing_address
.as_ref()
.map(|address| address.address_id.clone()),
attempt_id,
profile_id.clone(),
session_expiry,
&business_profile,
request.is_payment_id_from_merchant,
)
.await?;
let (payment_attempt_new, additional_payment_data) = Self::make_payment_attempt(
&payment_id,
merchant_id,
&merchant_context.get_merchant_account().organization_id,
money,
payment_method,
payment_method_type,
request,
browser_info,
state,
payment_method_billing_address
.as_ref()
.map(|address| address.address_id.clone()),
&payment_method_info,
merchant_context.get_merchant_key_store(),
profile_id,
&customer_acceptance,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_intent = db
.insert_payment_intent(
key_manager_state,
payment_intent_new,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment {
payment_id: payment_id.clone(),
})?;
if let Some(order_details) = &request.order_details {
helpers::validate_order_details_amount(
order_details.to_owned(),
payment_intent.amount,
false,
)?;
}
#[cfg(feature = "v1")]
let mut payment_attempt = db
.insert_payment_attempt(payment_attempt_new, storage_scheme)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment {
payment_id: payment_id.clone(),
})?;
#[cfg(feature = "v2")]
let payment_attempt = db
.insert_payment_attempt(
key_manager_state,
merchant_key_store,
payment_attempt_new,
storage_scheme,
)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment {
payment_id: payment_id.clone(),
})?;
let mandate_details_present = payment_attempt.mandate_details.is_some();
helpers::validate_mandate_data_and_future_usage(
request.setup_future_usage,
mandate_details_present,
)?;
// connector mandate reference update history
let mandate_id = request
.mandate_id
.as_ref()
.or_else(|| {
request.recurring_details
.as_ref()
.and_then(|recurring_details| match recurring_details {
RecurringDetails::MandateId(id) => Some(id),
_ => None,
})
})
.async_and_then(|mandate_id| async {
let mandate = db
.find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id, storage_scheme)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound);
Some(mandate.and_then(|mandate_obj| {
match (
mandate_obj.network_transaction_id,
mandate_obj.connector_mandate_ids,
) {
(_, Some(connector_mandate_id)) => connector_mandate_id
.parse_value("ConnectorMandateId")
.change_context(errors::ApiErrorResponse::MandateNotFound)
.map(|connector_id: api_models::payments::ConnectorMandateReferenceId| {
api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId::new(
connector_id.get_connector_mandate_id(),
connector_id.get_payment_method_id(),
None,
None,
connector_id.get_connector_mandate_request_reference_id(),
)
))
}
}),
(Some(network_tx_id), _) => Ok(api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::NetworkMandateId(
network_tx_id,
),
),
}),
(_, _) => Ok(api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: None,
}),
}
}))
})
.await
.transpose()?;
let mandate_id = if mandate_id.is_none() {
request
.recurring_details
.as_ref()
.and_then(|recurring_details| match recurring_details {
RecurringDetails::ProcessorPaymentToken(token) => {
Some(api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId::new(
Some(token.processor_payment_token.clone()),
None,
None,
None,
None,
),
),
),
})
}
_ => None,
})
} else {
mandate_id
};
let operation = payments::if_not_create_change_operation::<_, F>(
payment_intent.status,
request.confirm,
self,
);
let creds_identifier = request
.merchant_connector_details
.as_ref()
.map(|mcd| mcd.creds_identifier.to_owned());
request
.merchant_connector_details
.to_owned()
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(
db,
merchant_context.get_merchant_account().get_id(),
mcd,
)
.await
})
.await
.transpose()?;
// The operation merges mandate data from both request and payment_attempt
let setup_mandate = mandate_data;
let surcharge_details = request.surcharge_details.map(|request_surcharge_details| {
payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt))
});
let payment_method_data_after_card_bin_call = request
.payment_method_data
.as_ref()
.and_then(|payment_method_data_from_request| {
payment_method_data_from_request
.payment_method_data
.as_ref()
})
.zip(additional_payment_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")?;
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")?,
);
}
let amount = payment_attempt.get_total_amount().into();
payment_attempt.connector_mandate_detail =
Some(DieselConnectorMandateReferenceId::foreign_from(
api_models::payments::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 address = PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing_address.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);
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: None,
confirm: request.confirm,
payment_method_data: payment_method_data_after_card_bin_call.map(Into::into),
payment_method_token: None,
payment_method_info,
refunds: vec![],
disputes: vec![],
attempts: None,
force_sync: None,
all_keys_required: 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,
multiple_capture_data: None,
redirect_response: None,
surcharge_details,
frm_message: None,
payment_link_data,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: business_profile.is_l2_l3_enabled,
};
let get_trackers_response = operations::GetTrackerResponse {
operation,
customer_details: Some(customer_details),
payment_data,
business_profile,
mandate_type,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for PaymentCreate {
#[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: enums::MerchantStorageScheme,
) -> CustomResult<(PaymentCreateOperation<'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
}
async fn payments_dynamic_tax_calculation<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
_connector_call_type: &ConnectorCallType,
business_profile: &domain::Profile,
merchant_context: &domain::MerchantContext,
) -> CustomResult<(), errors::ApiErrorResponse> {
let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled();
let skip_external_tax_calculation = payment_data
.payment_intent
.skip_external_tax_calculation
.unwrap_or(false);
if is_tax_connector_enabled && !skip_external_tax_calculation {
let db = state.store.as_ref();
let key_manager_state: &KeyManagerState = &state.into();
let merchant_connector_id = business_profile
.tax_connector_id
.as_ref()
.get_required_value("business_profile.tax_connector_id")?;
#[cfg(feature = "v1")]
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&business_profile.merchant_id,
merchant_connector_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
#[cfg(feature = "v2")]
let mca = db
.find_merchant_connector_account_by_id(
key_manager_state,
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
let connector_data =
api::TaxCalculateConnectorData::get_connector_by_name(&mca.connector_name)?;
let router_data = core_utils::construct_payments_dynamic_tax_calculation_router_data(
state,
merchant_context,
payment_data,
&mca,
)
.await?;
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CalculateTax,
types::PaymentsTaxCalculationData,
types::TaxCalculationResponseData,
> = connector_data.connector.get_connector_integration();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Tax connector Response Failed")?;
let tax_response = response.response.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector_data.connector_name.clone().to_string(),
status_code: err.status_code,
reason: err.reason,
}
})?;
payment_data.payment_intent.tax_details = Some(diesel_models::TaxDetails {
default: Some(diesel_models::DefaultTax {
order_tax_amount: tax_response.order_tax_amount,
}),
payment_method_type: None,
});
Ok(())
} else {
Ok(())
}
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: enums::MerchantStorageScheme,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
PaymentCreateOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
merchant_key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await
}
#[instrument(skip_all)]
async fn add_task_to_process_tracker<'a>(
&'a self,
_state: &'a SessionState,
_payment_attempt: &PaymentAttempt,
_requeue: bool,
_schedule_time: Option<PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
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> {
helpers::get_connector_default(state, request.routing.clone()).await
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut PaymentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentCreate {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentCreateOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
let status = match payment_data.payment_intent.status {
IntentStatus::RequiresPaymentMethod => match payment_data.payment_method_data {
Some(_) => Some(IntentStatus::RequiresConfirmation),
_ => None,
},
IntentStatus::RequiresConfirmation => {
if let Some(true) = payment_data.confirm {
//TODO: do this later, request validation should happen before
Some(IntentStatus::Processing)
} else {
None
}
}
_ => None,
};
let payment_token = payment_data.token.clone();
let connector = payment_data.payment_attempt.connector.clone();
let straight_through_algorithm = payment_data
.payment_attempt
.straight_through_algorithm
.clone();
let authorized_amount = payment_data.payment_attempt.get_total_amount();
let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
let surcharge_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.surcharge_amount);
let tax_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.tax_on_surcharge_amount);
let routing_approach = payment_data.payment_attempt.routing_approach.clone();
let is_stored_credential = helpers::is_stored_credential(
&payment_data.recurring_details,
&payment_data.pm_token,
payment_data.mandate_id.is_some(),
payment_data.payment_attempt.is_stored_credential,
);
payment_data.payment_attempt = state
.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt,
storage::PaymentAttemptUpdate::UpdateTrackers {
payment_token,
connector,
straight_through_algorithm,
amount_capturable: match payment_data.confirm.unwrap_or(true) {
true => Some(authorized_amount),
false => None,
},
surcharge_amount,
tax_amount,
updated_by: storage_scheme.to_string(),
merchant_connector_id,
routing_approach,
is_stored_credential,
},
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let customer_id = payment_data.payment_intent.customer_id.clone();
let raw_customer_details = customer
.map(|customer| CustomerData::foreign_try_from(customer.clone()))
.transpose()?;
let key_manager_state = state.into();
// Updation of Customer Details for the cases where both customer_id and specific customer
// details are provided in Payment Create Request
let customer_details = raw_customer_details
.clone()
.async_map(|customer_details| {
create_encrypted_data(&key_manager_state, key_store, customer_details)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt customer details")?;
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent,
storage::PaymentIntentUpdate::PaymentCreateUpdate {
return_url: None,
status,
customer_id,
shipping_address_id: None,
billing_address_id: None,
customer_details,
updated_by: storage_scheme.to_string(),
},
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentCreate))
.with(payment_data.to_event())
.emit();
// payment_data.mandate_id = response.and_then(|router_data| router_data.request.mandate_id);
Ok((
payments::is_confirm(self, payment_data.confirm),
payment_data,
))
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentData<F>>
for PaymentCreate
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentCreateOperation<'b, F>, operations::ValidateResult)> {
helpers::validate_customer_information(request)?;
if let Some(amount) = request.amount {
helpers::validate_max_amount(amount)?;
}
if let Some(session_expiry) = &request.session_expiry {
helpers::validate_session_expiry(session_expiry.to_owned())?;
}
if let Some(payment_link) = &request.payment_link {
if *payment_link {
helpers::validate_payment_link_request(request)?;
}
};
let payment_id = request.payment_id.clone().ok_or(error_stack::report!(
errors::ApiErrorResponse::PaymentNotFound
))?;
let request_merchant_id = request.merchant_id.as_ref();
helpers::validate_merchant_id(
merchant_context.get_merchant_account().get_id(),
request_merchant_id,
)
.change_context(errors::ApiErrorResponse::MerchantAccountNotFound)?;
helpers::validate_request_amount_and_amount_to_capture(
request.amount,
request.amount_to_capture,
request.surcharge_details,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "amount_to_capture".to_string(),
expected_format: "amount_to_capture lesser than amount".to_string(),
})?;
helpers::validate_amount_to_capture_and_capture_method(None, request)?;
helpers::validate_card_data(
request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone()),
)?;
helpers::validate_payment_method_fields_present(request)?;
let mandate_type =
helpers::validate_mandate(request, payments::is_operation_confirm(self))?;
helpers::validate_recurring_details_and_token(
&request.recurring_details,
&request.payment_token,
&request.mandate_id,
)?;
request.validate_stored_credential().change_context(
errors::ApiErrorResponse::InvalidRequestData {
message:
"is_stored_credential should be true when reusing stored payment method data"
.to_string(),
},
)?;
helpers::validate_overcapture_request(
&request.enable_overcapture,
&request.capture_method,
)?;
request.validate_mit_request().change_context(
errors::ApiErrorResponse::InvalidRequestData {
message:
"`mit_category` requires both: (1) `off_session = true`, and (2) `recurring_details`."
.to_string(),
},
)?;
if request.confirm.unwrap_or(false) {
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,
&request.payment_token,
&request.ctp_service_details,
)?;
helpers::validate_customer_id_mandatory_cases(
request.setup_future_usage.is_some(),
request.customer_id.as_ref().or(request
.customer
.as_ref()
.map(|customer| customer.id.clone())
.as_ref()),
)?;
}
if request.split_payments.is_some() {
let amount = request.amount.get_required_value("amount")?;
helpers::validate_platform_request_for_marketplace(
amount,
request.split_payments.clone(),
)?;
};
let _request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request
.routing
.clone()
.map(|val| val.parse_value("RoutingAlgorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid straight through routing rules format".to_string(),
})
.attach_printable("Invalid straight through routing rules format")?;
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id,
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: matches!(
request.retry_action,
Some(api_models::enums::RetryAction::Requeue)
),
},
))
}
}
impl PaymentCreate {
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn make_payment_attempt(
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
organization_id: &common_utils::id_type::OrganizationId,
money: (api::Amount, enums::Currency),
payment_method: Option<enums::PaymentMethod>,
payment_method_type: Option<enums::PaymentMethodType>,
request: &api::PaymentsRequest,
browser_info: Option<serde_json::Value>,
state: &SessionState,
payment_method_billing_address_id: Option<String>,
payment_method_info: &Option<domain::PaymentMethod>,
_key_store: &domain::MerchantKeyStore,
profile_id: common_utils::id_type::ProfileId,
customer_acceptance: &Option<payments::CustomerAcceptance>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
storage::PaymentAttemptNew,
Option<api_models::payments::AdditionalPaymentData>,
)> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn make_payment_attempt(
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
organization_id: &common_utils::id_type::OrganizationId,
money: (api::Amount, enums::Currency),
payment_method: Option<enums::PaymentMethod>,
payment_method_type: Option<enums::PaymentMethodType>,
request: &api::PaymentsRequest,
browser_info: Option<serde_json::Value>,
state: &SessionState,
optional_payment_method_billing_address_id: Option<String>,
payment_method_info: &Option<domain::PaymentMethod>,
key_store: &domain::MerchantKeyStore,
profile_id: common_utils::id_type::ProfileId,
customer_acceptance: &Option<common_payments_types::CustomerAcceptance>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
storage::PaymentAttemptNew,
Option<api_models::payments::AdditionalPaymentData>,
)> {
let payment_method_data =
request
.payment_method_data
.as_ref()
.and_then(|payment_method_data_request| {
payment_method_data_request.payment_method_data.as_ref()
});
let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now());
let status = helpers::payment_attempt_status_fsm(payment_method_data, request.confirm);
let (amount, currency) = (money.0, Some(money.1));
let mut additional_pm_data = request
.payment_method_data
.as_ref()
.and_then(|payment_method_data_request| {
payment_method_data_request.payment_method_data.clone()
})
.async_map(|payment_method_data| async {
helpers::get_additional_payment_data(
&payment_method_data.into(),
&*state.store,
&profile_id,
)
.await
})
.await
.transpose()?
.flatten();
if additional_pm_data.is_none() {
// If recurring payment is made using payment_method_id, then fetch payment_method_data from retrieved payment_method object
additional_pm_data = payment_method_info.as_ref().and_then(|pm_info| {
pm_info
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|v| {
serde_json::from_value::<PaymentMethodsData>(v)
.map_err(|err| {
logger::error!(
"Unable to deserialize payment methods data: {:?}",
err
)
})
.ok()
})
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(card) => {
Some(api_models::payments::AdditionalPaymentData::Card(Box::new(
api::CardDetailFromLocker::from(card).into(),
)))
}
PaymentMethodsData::WalletDetails(wallet) => match payment_method_type {
Some(enums::PaymentMethodType::ApplePay) => {
Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: api::payments::ApplepayPaymentMethod::try_from(
wallet,
)
.inspect_err(|err| {
logger::error!(
"Unable to transform PaymentMethodDataWalletInfo to ApplepayPaymentMethod: {:?}",
err
)
})
.ok(),
google_pay: None,
samsung_pay: None,
})
}
Some(enums::PaymentMethodType::GooglePay) => {
Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: None,
google_pay: Some(wallet.into()),
samsung_pay: None,
})
}
Some(enums::PaymentMethodType::SamsungPay) => {
Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: None,
google_pay: None,
samsung_pay: Some(wallet.into()),
})
}
_ => None,
},
_ => None,
})
.or_else(|| match payment_method_type {
Some(enums::PaymentMethodType::Paypal) => {
Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: None,
google_pay: None,
samsung_pay: None,
})
}
_ => None,
})
});
};
let additional_pm_data_value = additional_pm_data
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?;
let attempt_id = if core_utils::is_merchant_enabled_for_payment_id_as_connector_request_id(
&state.conf,
merchant_id,
) {
payment_id.get_string_repr().to_owned()
} else {
payment_id.get_attempt_id(1)
};
if request.mandate_data.as_ref().is_some_and(|mandate_data| {
mandate_data.update_mandate_id.is_some() && mandate_data.mandate_type.is_some()
}) {
Err(errors::ApiErrorResponse::InvalidRequestData {message:"Only one field out of 'mandate_type' and 'update_mandate_id' was expected, found both".to_string()})?
}
let mandate_data = if let Some(update_id) = request
.mandate_data
.as_ref()
.and_then(|inner| inner.update_mandate_id.clone())
{
let mandate_details = MandateDetails {
update_mandate_id: Some(update_id),
};
Some(mandate_details)
} else {
None
};
let payment_method_type = Option::<enums::PaymentMethodType>::foreign_from((
payment_method_type,
additional_pm_data.as_ref(),
payment_method,
));
// TODO: remove once https://github.com/juspay/hyperswitch/issues/7421 is fixed
let payment_method_billing_address_id = match optional_payment_method_billing_address_id {
None => payment_method_info
.as_ref()
.and_then(|pm_info| pm_info.payment_method_billing_address.as_ref())
.map(|address| {
address.clone().deserialize_inner_value(|value| {
value.parse_value::<api_models::payments::Address>("Address")
})
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.ok()
.flatten()
.async_map(|addr| async move {
helpers::create_or_find_address_for_payment_by_request(
state,
Some(addr.get_inner()),
None,
merchant_id,
payment_method_info
.as_ref()
.map(|pmd_info| pmd_info.customer_id.clone())
.as_ref(),
key_store,
payment_id,
storage_scheme,
)
.await
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?
.flatten()
.map(|address| address.address_id),
address_id => address_id,
};
let is_stored_credential = helpers::is_stored_credential(
&request.recurring_details,
&request.payment_token,
request.mandate_id.is_some(),
request.is_stored_credential,
);
Ok((
storage::PaymentAttemptNew {
payment_id: payment_id.to_owned(),
merchant_id: merchant_id.to_owned(),
attempt_id,
status,
currency,
payment_method,
capture_method: request.capture_method,
capture_on: request.capture_on,
confirm: request.confirm.unwrap_or(false),
created_at,
modified_at,
last_synced,
authentication_type: request.authentication_type,
browser_info,
payment_experience: request.payment_experience,
payment_method_type,
payment_method_data: additional_pm_data_value,
amount_to_capture: request.amount_to_capture,
payment_token: request.payment_token.clone(),
mandate_id: request.mandate_id.clone(),
business_sub_label: request.business_sub_label.clone(),
mandate_details: request
.mandate_data
.as_ref()
.and_then(|inner| inner.mandate_type.clone().map(Into::into)),
external_three_ds_authentication_attempted: None,
mandate_data,
payment_method_billing_address_id,
net_amount: hyperswitch_domain_models::payments::payment_attempt::NetAmount::from_payments_request(
request,
MinorUnit::from(amount),
),
save_to_locker: None,
connector: None,
error_message: None,
offer_amount: None,
payment_method_id: payment_method_info
.as_ref()
.map(|pm_info| pm_info.get_id().clone()),
cancellation_reason: None,
error_code: None,
connector_metadata: None,
straight_through_algorithm: None,
preprocessing_step_id: None,
error_reason: None,
connector_response_reference_id: None,
multiple_capture_count: None,
amount_capturable: MinorUnit::new(i64::default()),
updated_by: String::default(),
authentication_data: None,
encoded_data: None,
merchant_connector_id: None,
unified_code: None,
unified_message: None,
fingerprint_id: None,
authentication_connector: None,
authentication_id: None,
client_source: None,
client_version: None,
customer_acceptance: customer_acceptance
.clone()
.map(|customer_acceptance| customer_acceptance.encode_to_value())
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize customer_acceptance")?
.map(Secret::new),
organization_id: organization_id.clone(),
profile_id,
connector_mandate_detail: None,
request_extended_authorization: None,
extended_authorization_applied: None,
capture_before: None,
card_discovery: None,
processor_merchant_id: merchant_id.to_owned(),
created_by: None,
setup_future_usage_applied: request.setup_future_usage,
routing_approach: Some(common_enums::RoutingApproach::default()),
connector_request_reference_id: None,
network_transaction_id:None,
network_details:None,
is_stored_credential,
authorized_amount: None,
},
additional_pm_data,
))
}
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
async fn make_payment_intent(
state: &SessionState,
payment_id: &common_utils::id_type::PaymentId,
merchant_context: &domain::MerchantContext,
money: (api::Amount, enums::Currency),
request: &api::PaymentsRequest,
shipping_address_id: Option<String>,
payment_link_data: Option<api_models::payments::PaymentLinkResponse>,
billing_address_id: Option<String>,
active_attempt_id: String,
profile_id: common_utils::id_type::ProfileId,
session_expiry: PrimitiveDateTime,
business_profile: &domain::Profile,
is_payment_id_from_merchant: bool,
) -> RouterResult<storage::PaymentIntent> {
let created_at @ modified_at @ last_synced = common_utils::date_time::now();
let status = helpers::payment_intent_status_fsm(
request
.payment_method_data
.as_ref()
.and_then(|request_payment_method_data| {
request_payment_method_data.payment_method_data.as_ref()
}),
request.confirm,
);
let client_secret = payment_id.generate_client_secret();
let (amount, currency) = (money.0, Some(money.1));
let order_details = request
.get_order_details_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert order details to value")?;
let 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")?;
let connector_metadata = request
.get_connector_metadata_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting connector_metadata to Value")?;
let feature_metadata = request
.get_feature_metadata_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting feature_metadata to Value")?;
let payment_link_id = payment_link_data.map(|pl_data| pl_data.payment_link_id);
let request_incremental_authorization =
core_utils::get_request_incremental_authorization_value(
request.request_incremental_authorization,
request.capture_method,
)?;
let split_payments = request.split_payments.clone();
// Derivation of directly supplied Customer data in our Payment Create Request
let raw_customer_details = if request.customer_id.is_none()
&& (request.name.is_some()
|| request.email.is_some()
|| request.phone.is_some()
|| request.phone_country_code.is_some())
{
Some(CustomerData {
name: request.name.clone(),
phone: request.phone.clone(),
email: request.email.clone(),
phone_country_code: request.phone_country_code.clone(),
tax_registration_id: None,
})
} else {
None
};
let is_payment_processor_token_flow = request.recurring_details.as_ref().and_then(
|recurring_details| match recurring_details {
RecurringDetails::ProcessorPaymentToken(_) => Some(true),
_ => None,
},
);
let key = merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek();
let identifier = Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
);
let key_manager_state: KeyManagerState = state.into();
let shipping_details_encoded = request
.shipping
.clone()
.map(|shipping| Encode::encode_to_value(&shipping).map(Secret::new))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encode billing details to serde_json::Value")?;
let billing_details_encoded = request
.billing
.clone()
.map(|billing| Encode::encode_to_value(&billing).map(Secret::new))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encode billing details to serde_json::Value")?;
let customer_details_encoded = raw_customer_details
.map(|customer| Encode::encode_to_value(&customer).map(Secret::new))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encode shipping details to serde_json::Value")?;
let encrypted_data = domain::types::crypto_operation(
&key_manager_state,
type_name!(storage::PaymentIntent),
domain::types::CryptoOperation::BatchEncrypt(
FromRequestEncryptablePaymentIntent::to_encryptable(
FromRequestEncryptablePaymentIntent {
shipping_details: shipping_details_encoded,
billing_details: billing_details_encoded,
customer_details: customer_details_encoded,
},
),
),
identifier.clone(),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt data")?;
let encrypted_data = FromRequestEncryptablePaymentIntent::from_encryptable(encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt the payment intent data")?;
let skip_external_tax_calculation = request.skip_external_tax_calculation;
let tax_details = request
.order_tax_amount
.map(|tax_amount| diesel_models::TaxDetails {
default: Some(diesel_models::DefaultTax {
order_tax_amount: tax_amount,
}),
payment_method_type: None,
});
let force_3ds_challenge_trigger = request
.force_3ds_challenge
.unwrap_or(business_profile.force_3ds_challenge);
Ok(storage::PaymentIntent {
payment_id: payment_id.to_owned(),
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
status,
amount: MinorUnit::from(amount),
currency,
description: request.description.clone(),
created_at,
modified_at,
last_synced: Some(last_synced),
client_secret: Some(client_secret),
setup_future_usage: request.setup_future_usage,
off_session: request.off_session,
return_url: request.return_url.as_ref().map(|a| a.to_string()),
shipping_address_id,
billing_address_id,
statement_descriptor_name: request.statement_descriptor_name.clone(),
statement_descriptor_suffix: request.statement_descriptor_suffix.clone(),
metadata: request.metadata.clone(),
business_country: request.business_country,
business_label: request.business_label.clone(),
active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
active_attempt_id,
),
order_details,
amount_captured: None,
customer_id: request.get_customer_id().cloned(),
connector_id: None,
allowed_payment_method_types,
connector_metadata,
feature_metadata,
attempt_count: 1,
profile_id: Some(profile_id),
merchant_decision: None,
payment_link_id,
payment_confirm_source: None,
surcharge_applicable: None,
updated_by: merchant_context
.get_merchant_account()
.storage_scheme
.to_string(),
request_incremental_authorization,
incremental_authorization_allowed: None,
authorization_count: None,
fingerprint_id: None,
session_expiry: Some(session_expiry),
request_external_three_ds_authentication: request
.request_external_three_ds_authentication,
split_payments,
frm_metadata: request.frm_metadata.clone(),
billing_details: encrypted_data.billing_details,
customer_details: encrypted_data.customer_details,
merchant_order_reference_id: request.merchant_order_reference_id.clone(),
shipping_details: encrypted_data.shipping_details,
is_payment_processor_token_flow,
organization_id: merchant_context
.get_merchant_account()
.organization_id
.clone(),
shipping_cost: request.shipping_cost,
tax_details,
skip_external_tax_calculation,
request_extended_authorization: request.request_extended_authorization,
psd2_sca_exemption_type: request.psd2_sca_exemption_type,
processor_merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
created_by: None,
force_3ds_challenge: request.force_3ds_challenge,
force_3ds_challenge_trigger: Some(force_3ds_challenge_trigger),
is_iframe_redirection_enabled: request
.is_iframe_redirection_enabled
.or(business_profile.is_iframe_redirection_enabled),
is_payment_id_from_merchant: Some(is_payment_id_from_merchant),
payment_channel: request.payment_channel.clone(),
order_date: request.order_date,
discount_amount: request.discount_amount,
duty_amount: request.duty_amount,
tax_status: request.tax_status,
shipping_amount_tax: request.shipping_amount_tax,
enable_partial_authorization: request.enable_partial_authorization,
enable_overcapture: request.enable_overcapture,
mit_category: request.mit_category,
})
}
#[instrument(skip_all)]
pub async fn get_ephemeral_key(
request: &api::PaymentsRequest,
state: &SessionState,
merchant_context: &domain::MerchantContext,
) -> Option<ephemeral_key::EphemeralKey> {
match request.get_customer_id() {
Some(customer_id) => helpers::make_ephemeral_key(
state.clone(),
customer_id.clone(),
merchant_context
.get_merchant_account()
.get_id()
.to_owned()
.clone(),
)
.await
.ok()
.and_then(|ek| {
if let services::ApplicationResponse::Json(ek) = ek {
Some(ek)
} else {
None
}
}),
None => None,
}
}
}
#[instrument(skip_all)]
pub fn payments_create_request_validation(
req: &api::PaymentsRequest,
) -> RouterResult<(api::Amount, enums::Currency)> {
let currency = req.currency.get_required_value("currency")?;
let amount = req.amount.get_required_value("amount")?;
Ok((amount, currency))
}
#[allow(clippy::too_many_arguments)]
async fn create_payment_link(
request: &api::PaymentsRequest,
payment_link_config: api_models::admin::PaymentLinkConfig,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: common_utils::id_type::PaymentId,
db: &dyn StorageInterface,
amount: api::Amount,
description: Option<String>,
profile_id: common_utils::id_type::ProfileId,
domain_name: String,
session_expiry: PrimitiveDateTime,
locale: Option<String>,
) -> RouterResult<Option<api_models::payments::PaymentLinkResponse>> {
let created_at @ last_modified_at = Some(common_utils::date_time::now());
let payment_link_id = utils::generate_id(consts::ID_LENGTH, "plink");
let locale_str = locale.unwrap_or("en".to_owned());
let open_payment_link = format!(
"{}/payment_link/{}/{}?locale={}",
domain_name,
merchant_id.get_string_repr(),
payment_id.get_string_repr(),
locale_str.clone(),
);
let secure_link = payment_link_config.allowed_domains.as_ref().map(|_| {
format!(
"{}/payment_link/s/{}/{}?locale={}",
domain_name,
merchant_id.get_string_repr(),
payment_id.get_string_repr(),
locale_str,
)
});
let payment_link_config_encoded_value = payment_link_config.encode_to_value().change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "payment_link_config",
},
)?;
let payment_link_req = storage::PaymentLinkNew {
payment_link_id: payment_link_id.clone(),
payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
link_to_pay: open_payment_link.clone(),
amount: MinorUnit::from(amount),
currency: request.currency,
created_at,
last_modified_at,
fulfilment_time: Some(session_expiry),
custom_merchant_name: Some(payment_link_config.seller_name),
description,
payment_link_config: Some(payment_link_config_encoded_value),
profile_id: Some(profile_id),
secure_link,
};
let payment_link_db = db
.insert_payment_link(payment_link_req)
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: "payment link already exists!".to_string(),
})?;
Ok(Some(api_models::payments::PaymentLinkResponse {
link: payment_link_db.link_to_pay.clone(),
secure_link: payment_link_db.secure_link,
payment_link_id: payment_link_db.payment_link_id,
}))
}
| {
"crate": "router",
"file": "crates/router/src/core/payments/operations/payment_create.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_7001153356502551287 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/payments/operations/payment_cancel.rs
// Contains: 1 structs, 0 enums
use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
use router_derive;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{helpers, operations, PaymentData},
},
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
self as core_types,
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, router_derive::PaymentOperation)]
#[operation(operations = "all", flow = "cancel")]
pub struct PaymentCancel;
type PaymentCancelOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsCancelRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
for PaymentCancel
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsCancelRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<'a, F, api::PaymentsCancelRequest, PaymentData<F>>,
> {
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
enums::IntentStatus::Failed,
enums::IntentStatus::Succeeded,
enums::IntentStatus::Cancelled,
enums::IntentStatus::Processing,
enums::IntentStatus::RequiresMerchantAction,
],
"cancel",
)?;
let mut payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
payment_attempt
.cancellation_reason
.clone_from(&request.cancellation_reason);
let creds_identifier = request
.merchant_connector_details
.as_ref()
.map(|mcd| mcd.creds_identifier.to_owned());
request
.merchant_connector_details
.to_owned()
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(
db,
merchant_context.get_merchant_account().get_id(),
mcd,
)
.await
})
.await
.transpose()?;
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
token_data: None,
address: core_types::PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
confirm: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
for PaymentCancel
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentCancelOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
let cancellation_reason = payment_data.payment_attempt.cancellation_reason.clone();
let (intent_status_update, attempt_status_update) =
if payment_data.payment_intent.status != enums::IntentStatus::RequiresCapture {
let payment_intent_update = storage::PaymentIntentUpdate::PGStatusUpdate {
status: enums::IntentStatus::Cancelled,
updated_by: storage_scheme.to_string(),
incremental_authorization_allowed: None,
feature_metadata: payment_data
.payment_intent
.feature_metadata
.clone()
.map(masking::Secret::new),
};
(Some(payment_intent_update), enums::AttemptStatus::Voided)
} else {
(None, enums::AttemptStatus::VoidInitiated)
};
if let Some(payment_intent_update) = intent_status_update {
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
state
.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt.clone(),
storage::PaymentAttemptUpdate::VoidUpdate {
status: attempt_status_update,
cancellation_reason: cancellation_reason.clone(),
updated_by: storage_scheme.to_string(),
},
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentCancelled {
cancellation_reason,
}))
.with(payment_data.to_event())
.emit();
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsCancelRequest, PaymentData<F>>
for PaymentCancel
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsCancelRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentCancelOperation<'b, F>, operations::ValidateResult)> {
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
| {
"crate": "router",
"file": "crates/router/src/core/payments/operations/payment_cancel.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_2281420594011971885 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/payments/operations/payment_confirm.rs
// Contains: 1 structs, 0 enums
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,
is_l2_l3_enabled: business_profile.is_l2_l3_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.browser_info.as_ref(),
card.card_number.clone(),
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,
payment_data: &mut PaymentData<F>,
business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse> {
// If the business profile has a three_ds_decision_rule_algorithm, we will use it to determine the 3DS strategy (authentication_type, exemption_type and force_three_ds_challenge)
if let Some(three_ds_decision_rule) =
business_profile.three_ds_decision_rule_algorithm.clone()
{
// Parse the three_ds_decision_rule to get the algorithm_id
let algorithm_id = three_ds_decision_rule
.parse_value::<api::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode profile routing algorithm ref")?
.algorithm_id
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("No algorithm_id found in three_ds_decision_rule_algorithm")?;
// get additional card info from payment data
let additional_card_info = payment_data
.payment_attempt
.payment_method_data
.as_ref()
.map(|payment_method_data| {
payment_method_data
.clone()
.parse_value::<api_models::payments::AdditionalPaymentData>(
"additional_payment_method_data",
)
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse value into additional_payment_method_data")?
.and_then(|additional_payment_method_data| {
additional_payment_method_data.get_additional_card_info()
});
// get acquirer details from business profile based on card network
let acquirer_config = additional_card_info.as_ref().and_then(|card_info| {
card_info
.card_network
.clone()
.and_then(|network| business_profile.get_acquirer_details_from_network(network))
});
let country = business_profile
.merchant_country_code
.as_ref()
.map(|country_code| {
country_code.validate_and_get_country_from_merchant_country_code()
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing country from merchant country code")?;
// get three_ds_decision_rule_output using algorithm_id and payment data
let decision = three_ds_decision_rule::get_three_ds_decision_rule_output(
state,
&business_profile.merchant_id,
api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest {
routing_id: algorithm_id,
payment: api_models::three_ds_decision_rule::PaymentData {
amount: payment_data.payment_intent.amount,
currency: payment_data
.payment_intent
.currency
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("currency is not set in payment intent")?,
},
payment_method: Some(
api_models::three_ds_decision_rule::PaymentMethodMetaData {
card_network: additional_card_info
.as_ref()
.and_then(|info| info.card_network.clone()),
},
),
issuer: Some(api_models::three_ds_decision_rule::IssuerData {
name: additional_card_info
.as_ref()
.and_then(|info| info.card_issuer.clone()),
country: additional_card_info
.as_ref()
.map(|info| info.card_issuing_country.clone().parse_enum("Country"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Error while getting country enum from issuer country",
)?,
}),
customer_device: None,
acquirer: acquirer_config.as_ref().map(|acquirer| {
api_models::three_ds_decision_rule::AcquirerData {
country,
fraud_rate: Some(acquirer.acquirer_fraud_rate),
}
}),
},
)
.await?;
logger::info!("Three DS Decision Rule Output: {:?}", decision);
// We should update authentication_type from the Three DS Decision if it is not already set
if payment_data.payment_attempt.authentication_type.is_none() {
payment_data.payment_attempt.authentication_type =
Some(common_enums::AuthenticationType::foreign_from(decision));
}
// We should update psd2_sca_exemption_type from the Three DS Decision
payment_data.payment_intent.psd2_sca_exemption_type = decision.foreign_into();
// We should update force_3ds_challenge from the Three DS Decision
payment_data.payment_intent.force_3ds_challenge =
decision.should_force_3ds_challenge().then_some(true);
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn call_unified_authentication_service_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 unified_authentication_service_flow =
helpers::decide_action_for_unified_authentication_service(
state,
key_store,
business_profile,
payment_data,
connector_call_type,
mandate_type,
)
.await?;
if let Some(unified_authentication_service_flow) = unified_authentication_service_flow {
match unified_authentication_service_flow {
helpers::UnifiedAuthenticationServiceFlow::ClickToPayInitiate => {
let authentication_product_ids = business_profile
.authentication_product_ids
.clone()
.ok_or(errors::ApiErrorResponse::PreconditionFailed {
message: "authentication_product_ids is not configured in business profile"
.to_string(),
})?;
let click_to_pay_mca_id = authentication_product_ids
.get_click_to_pay_connector_account_id()
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "authentication_product_ids",
})?;
let key_manager_state = &(state).into();
let merchant_id = &business_profile.merchant_id;
let connector_mca = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_id,
&click_to_pay_mca_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: click_to_pay_mca_id.get_string_repr().to_string(),
},
)?;
let authentication_id =
common_utils::id_type::AuthenticationId::generate_authentication_id(consts::AUTHENTICATION_ID_PREFIX);
let payment_method = payment_data.payment_attempt.payment_method.ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_method",
},
)?;
ClickToPay::pre_authentication(
state,
&payment_data.payment_attempt.merchant_id,
Some(&payment_data.payment_intent.payment_id),
payment_data.payment_method_data.as_ref(),
payment_data.payment_attempt.payment_method_type,
&helpers::MerchantConnectorAccountType::DbVal(Box::new(connector_mca.clone())),
&connector_mca.connector_name,
&authentication_id,
payment_method,
payment_data.payment_intent.amount,
payment_data.payment_intent.currency,
payment_data.service_details.clone(),
None,
None,
None,
None
)
.await?;
payment_data.payment_attempt.authentication_id = Some(authentication_id.clone());
let response = ClickToPay::post_authentication(
state,
business_profile,
Some(&payment_data.payment_intent.payment_id),
&helpers::MerchantConnectorAccountType::DbVal(Box::new(connector_mca.clone())),
&connector_mca.connector_name,
&authentication_id,
payment_method,
&payment_data.payment_intent.merchant_id,
None
)
.await?;
let (network_token, authentication_status) = match response.response.clone() {
Ok(unified_authentication_service::UasAuthenticationResponseData::PostAuthentication {
authentication_details,
}) => {
let token_details = authentication_details.token_details.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Missing authentication_details.token_details")?;
(Some(
hyperswitch_domain_models::payment_method_data::NetworkTokenData {
token_number: token_details.payment_token,
token_exp_month: token_details
.token_expiration_month,
token_exp_year: token_details
.token_expiration_year,
token_cryptogram: authentication_details
.dynamic_data_details
.and_then(|data| data.dynamic_data_value),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: None,
eci: authentication_details.eci,
}),common_enums::AuthenticationStatus::Success)
},
Ok(unified_authentication_service::UasAuthenticationResponseData::PreAuthentication { .. })
| Ok(unified_authentication_service::UasAuthenticationResponseData::Confirmation {})
| Ok(unified_authentication_service::UasAuthenticationResponseData::Authentication { .. }) => Err(errors::ApiErrorResponse::InternalServerError).attach_printable("unexpected response received from unified authentication service")?,
Err(_) => (None, common_enums::AuthenticationStatus::Failed)
};
payment_data.payment_attempt.payment_method =
Some(common_enums::PaymentMethod::Card);
payment_data.payment_method_data = network_token
.clone()
.map(domain::PaymentMethodData::NetworkToken);
let authentication = uas_utils::create_new_authentication(
state,
payment_data.payment_attempt.merchant_id.clone(),
Some(connector_mca.connector_name.to_string()),
business_profile.get_id().clone(),
Some(payment_data.payment_intent.get_id().clone()),
Some(click_to_pay_mca_id.to_owned()),
&authentication_id,
payment_data.service_details.clone(),
authentication_status,
network_token.clone(),
payment_data.payment_attempt.organization_id.clone(),
payment_data.payment_intent.force_3ds_challenge,
payment_data.payment_intent.psd2_sca_exemption_type,
None,
None,
None,
None,
None,
None,
None
)
.await?;
let authentication_store = hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {
cavv: network_token.and_then(|token| token.token_cryptogram),
authentication
};
payment_data.authentication = Some(authentication_store);
},
helpers::UnifiedAuthenticationServiceFlow::ExternalAuthenticationInitiate {
acquirer_details,
..
} => {
let (authentication_connector, three_ds_connector_account) =
authentication::utils::get_authentication_connector_data(state, key_store, business_profile, None).await?;
let authentication_connector_name = authentication_connector.to_string();
let authentication_id =
common_utils::id_type::AuthenticationId::generate_authentication_id(consts::AUTHENTICATION_ID_PREFIX);
let (acquirer_bin, acquirer_merchant_id, acquirer_country_code) = if let Some(details) = &acquirer_details {
(
Some(details.acquirer_bin.clone()),
Some(details.acquirer_merchant_id.clone()),
details.acquirer_country_code.clone(),
)
} else {
(None, None, None)
};
let authentication = uas_utils::create_new_authentication(
state,
business_profile.merchant_id.clone(),
Some(authentication_connector_name.clone()),
business_profile.get_id().to_owned(),
Some(payment_data.payment_intent.payment_id.clone()),
Some(three_ds_connector_account
.get_mca_id()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while finding mca_id from merchant_connector_account")?),
&authentication_id,
payment_data.service_details.clone(),
common_enums::AuthenticationStatus::Started,
None,
payment_data.payment_attempt.organization_id.clone(),
payment_data.payment_intent.force_3ds_challenge,
payment_data.payment_intent.psd2_sca_exemption_type,
acquirer_bin,
acquirer_merchant_id,
acquirer_country_code,
None,
None,
None,
None,
)
.await?;
let acquirer_configs = authentication
.profile_acquirer_id
.clone()
.and_then(|acquirer_id| {
business_profile
.acquirer_config_map.as_ref()
.and_then(|acquirer_config_map| acquirer_config_map.0.get(&acquirer_id).cloned())
});
let metadata: Option<ThreeDsMetaData> = three_ds_connector_account
.get_metadata()
.map(|metadata| {
metadata
.expose()
.parse_value("ThreeDsMetaData")
.attach_printable("Error while parsing ThreeDsMetaData")
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let merchant_country_code = authentication.acquirer_country_code.clone();
let return_url = helpers::create_authorize_url(
&state.base_url,
&payment_data.payment_attempt.clone(),
payment_data.payment_attempt.connector.as_ref().get_required_value("connector")?,
);
let notification_url = Some(url::Url::parse(&return_url))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse webhook url")?;
let merchant_details = Some(unified_authentication_service::MerchantDetails {
merchant_id: Some(authentication.merchant_id.get_string_repr().to_string()),
merchant_name: acquirer_configs.clone().map(|detail| detail.merchant_name.clone()).or(metadata.clone().and_then(|metadata| metadata.merchant_name)),
merchant_category_code: business_profile.merchant_category_code.or(metadata.clone().and_then(|metadata| metadata.merchant_category_code)),
endpoint_prefix: metadata.clone().and_then(|metadata| metadata.endpoint_prefix),
three_ds_requestor_url: business_profile.authentication_connector_details.clone().map(|details| details.three_ds_requestor_url),
three_ds_requestor_id: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_id),
three_ds_requestor_name: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_name),
merchant_country_code: merchant_country_code.map(common_types::payments::MerchantCountryCode::new),
notification_url,
});
let domain_address = payment_data.address.get_payment_method_billing();
let pre_auth_response = uas_utils::types::ExternalAuthentication::pre_authentication(
state,
&payment_data.payment_attempt.merchant_id,
Some(&payment_data.payment_intent.payment_id),
payment_data.payment_method_data.as_ref(),
payment_data.payment_attempt.payment_method_type,
&three_ds_connector_account,
&authentication_connector_name,
&authentication.authentication_id,
payment_data.payment_attempt.payment_method.ok_or(
errors::ApiErrorResponse::InternalServerError
).attach_printable("payment_method not found in payment_attempt")?,
payment_data.payment_intent.amount,
payment_data.payment_intent.currency,
payment_data.service_details.clone(),
merchant_details.as_ref(),
domain_address,
authentication.acquirer_bin.clone(),
authentication.acquirer_merchant_id.clone(),
)
.await?;
let updated_authentication = uas_utils::utils::external_authentication_update_trackers(
state,
pre_auth_response,
authentication.clone(),
acquirer_details,
key_store,
None,
None,
None,
None,
).await?;
let authentication_store = hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {
cavv: None, // since in case of pre_authentication cavv is not present
authentication: updated_authentication.clone(),
};
payment_data.authentication = Some(authentication_store.clone());
if updated_authentication.is_separate_authn_required()
|| updated_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 = updated_authentication.authentication_connector
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("authentication_connector not found in updated_authentication")?;
let poll_config = state
.store
.find_config_by_key_unwrap_or(
&types::PollConfig::get_poll_config_key(
authentication_connector.clone(),
),
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)
}
},
helpers::UnifiedAuthenticationServiceFlow::ExternalAuthenticationPostAuthenticate {authentication_id} => {
let (authentication_connector, three_ds_connector_account) =
authentication::utils::get_authentication_connector_data(state, key_store, business_profile, None).await?;
let is_pull_mechanism_enabled =
utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(
three_ds_connector_account
.get_metadata()
.map(|metadata| metadata.expose()),
);
let authentication = state
.store
.find_authentication_by_merchant_id_authentication_id(
&business_profile.merchant_id,
&authentication_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Error while fetching authentication record with authentication_id {}", authentication_id.get_string_repr()))?;
let updated_authentication = if !authentication.authentication_status.is_terminal_status() && is_pull_mechanism_enabled {
let post_auth_response = uas_utils::types::ExternalAuthentication::post_authentication(
state,
business_profile,
Some(&payment_data.payment_intent.payment_id),
&three_ds_connector_account,
&authentication_connector.to_string(),
&authentication.authentication_id,
payment_data.payment_attempt.payment_method.ok_or(
errors::ApiErrorResponse::InternalServerError
).attach_printable("payment_method not found in payment_attempt")?,
&payment_data.payment_intent.merchant_id,
Some(&authentication),
).await?;
uas_utils::utils::external_authentication_update_trackers(
state,
post_auth_response,
authentication,
None,
key_store,
None,
None,
None,
None,
).await?
} else {
authentication
};
let tokenized_data = if updated_authentication.authentication_status.is_success() {
Some(crate::core::payment_methods::vault::get_tokenized_data(state, authentication_id.get_string_repr(), false, key_store.key.get_inner()).await?)
} else {
None
};
let authentication_store = hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {
cavv: tokenized_data.map(|tokenized_data| masking::Secret::new(tokenized_data.value1)),
authentication: updated_authentication
};
payment_data.authentication = Some(authentication_store.clone());
//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;
}
},
}
}
Ok(())
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_data: &mut PaymentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
blocklist_utils::validate_data_for_blocklist(state, merchant_context, payment_data).await
}
#[instrument(skip_all)]
async fn store_extended_card_info_temporarily<'a>(
&'a self,
state: &SessionState,
payment_id: &common_utils::id_type::PaymentId,
business_profile: &domain::Profile,
payment_method_data: Option<&domain::PaymentMethodData>,
) -> CustomResult<(), errors::ApiErrorResponse> {
if let (Some(true), Some(domain::PaymentMethodData::Card(card)), Some(merchant_config)) = (
business_profile.is_extended_card_info_enabled,
payment_method_data,
business_profile.extended_card_info_config.clone(),
) {
let merchant_config = merchant_config
.expose()
.parse_value::<ExtendedCardInfoConfig>("ExtendedCardInfoConfig")
.map_err(|err| logger::error!(parse_err=?err,"Error while parsing ExtendedCardInfoConfig"));
let card_data = ExtendedCardInfo::from(card.clone())
.encode_to_vec()
.map_err(|err| logger::error!(encode_err=?err,"Error while encoding ExtendedCardInfo to vec"));
let (Ok(merchant_config), Ok(card_data)) = (merchant_config, card_data) else {
return Ok(());
};
let encrypted_payload =
services::encrypt_jwe(&card_data, merchant_config.public_key.peek(), services::EncryptionAlgorithm::A256GCM, None)
.await
.map_err(|err| {
logger::error!(jwe_encryption_err=?err,"Error while JWE encrypting extended card info")
});
let Ok(encrypted_payload) = encrypted_payload else {
return Ok(());
};
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let key = helpers::get_redis_key_for_extended_card_info(
&business_profile.merchant_id,
payment_id,
);
redis_conn
.set_key_with_expiry(
&key.into(),
encrypted_payload.clone(),
(*merchant_config.ttl_in_secs).into(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add extended card info in redis")?;
logger::info!("Extended card info added to redis");
}
Ok(())
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentConfirm {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
_req_state: ReqState,
mut _payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsRequest, PaymentData<F>>,
PaymentData<F>,
)>
where
F: 'b + Send,
{
todo!()
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentConfirm {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
frm_suggestion: Option<FrmSuggestion>,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsRequest, PaymentData<F>>,
PaymentData<F>,
)>
where
F: 'b + Send,
{
let payment_method = payment_data.payment_attempt.payment_method;
let browser_info = payment_data.payment_attempt.browser_info.clone();
let frm_message = payment_data.frm_message.clone();
let capture_method = payment_data.payment_attempt.capture_method;
let default_status_result = (
storage_enums::IntentStatus::Processing,
storage_enums::AttemptStatus::Pending,
(None, None),
);
let status_handler_for_frm_results = |frm_suggestion: FrmSuggestion| match frm_suggestion {
FrmSuggestion::FrmCancelTransaction => (
storage_enums::IntentStatus::Failed,
storage_enums::AttemptStatus::Failure,
frm_message.map_or((None, None), |fraud_check| {
(
Some(Some(fraud_check.frm_status.to_string())),
Some(fraud_check.frm_reason.map(|reason| reason.to_string())),
)
}),
),
FrmSuggestion::FrmManualReview => (
storage_enums::IntentStatus::RequiresMerchantAction,
storage_enums::AttemptStatus::Unresolved,
(None, None),
),
FrmSuggestion::FrmAuthorizeTransaction => (
storage_enums::IntentStatus::RequiresCapture,
storage_enums::AttemptStatus::Authorized,
(None, None),
),
};
let status_handler_for_authentication_results =
|authentication: &storage::Authentication| {
if authentication.authentication_status.is_failed() {
(
storage_enums::IntentStatus::Failed,
storage_enums::AttemptStatus::Failure,
(
Some(Some("EXTERNAL_AUTHENTICATION_FAILURE".to_string())),
Some(Some("external authentication failure".to_string())),
),
)
} else if authentication.is_separate_authn_required() {
(
storage_enums::IntentStatus::RequiresCustomerAction,
storage_enums::AttemptStatus::AuthenticationPending,
(None, None),
)
} else {
default_status_result.clone()
}
};
let (intent_status, attempt_status, (error_code, error_message)) =
match (frm_suggestion, payment_data.authentication.as_ref()) {
(Some(frm_suggestion), _) => status_handler_for_frm_results(frm_suggestion),
(_, Some(authentication_details)) => status_handler_for_authentication_results(
&authentication_details.authentication,
),
_ => default_status_result,
};
let connector = payment_data.payment_attempt.connector.clone();
let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
let connector_request_reference_id = payment_data
.payment_attempt
.connector_request_reference_id
.clone();
let straight_through_algorithm = payment_data
.payment_attempt
.straight_through_algorithm
.clone();
let payment_token = payment_data.token.clone();
let payment_method_type = payment_data.payment_attempt.payment_method_type;
let profile_id = payment_data
.payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let payment_experience = payment_data.payment_attempt.payment_experience;
let additional_pm_data = payment_data
.payment_method_data
.as_ref()
.async_map(|payment_method_data| async {
helpers::get_additional_payment_data(payment_method_data, &*state.store, profile_id)
.await
})
.await
.transpose()?
.flatten();
let encoded_additional_pm_data = additional_pm_data
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?;
let customer_details = payment_data.payment_intent.customer_details.clone();
let business_sub_label = payment_data.payment_attempt.business_sub_label.clone();
let authentication_type = payment_data.payment_attempt.authentication_type;
let (shipping_address_id, billing_address_id, payment_method_billing_address_id) = (
payment_data.payment_intent.shipping_address_id.clone(),
payment_data.payment_intent.billing_address_id.clone(),
payment_data
.payment_attempt
.payment_method_billing_address_id
.clone(),
);
let customer_id = customer.clone().map(|c| c.customer_id);
let return_url = payment_data.payment_intent.return_url.take();
let setup_future_usage = payment_data.payment_intent.setup_future_usage;
let business_label = payment_data.payment_intent.business_label.clone();
let business_country = payment_data.payment_intent.business_country;
let description = payment_data.payment_intent.description.take();
let statement_descriptor_name =
payment_data.payment_intent.statement_descriptor_name.take();
let statement_descriptor_suffix = payment_data
.payment_intent
.statement_descriptor_suffix
.take();
let order_details = payment_data.payment_intent.order_details.clone();
let metadata = payment_data.payment_intent.metadata.clone();
let frm_metadata = payment_data.payment_intent.frm_metadata.clone();
let client_source = header_payload
.client_source
.clone()
.or(payment_data.payment_attempt.client_source.clone());
let client_version = header_payload
.client_version
.clone()
.or(payment_data.payment_attempt.client_version.clone());
let m_payment_data_payment_attempt = payment_data.payment_attempt.clone();
let m_payment_method_id =
payment_data
.payment_attempt
.payment_method_id
.clone()
.or(payment_data
.payment_method_info
.as_ref()
.map(|payment_method| payment_method.payment_method_id.clone()));
let m_browser_info = browser_info.clone();
let m_connector = connector.clone();
let m_capture_method = capture_method;
let m_payment_token = payment_token.clone();
let m_additional_pm_data = encoded_additional_pm_data
.clone()
.or(payment_data.payment_attempt.payment_method_data.clone());
let m_business_sub_label = business_sub_label.clone();
let m_straight_through_algorithm = straight_through_algorithm.clone();
let m_error_code = error_code.clone();
let m_error_message = error_message.clone();
let m_fingerprint_id = payment_data.payment_attempt.fingerprint_id.clone();
let m_db = state.clone().store;
let surcharge_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.surcharge_amount);
let tax_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.tax_on_surcharge_amount);
let (
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
) = match payment_data.authentication.as_ref() {
Some(authentication_store) => (
Some(
authentication_store
.authentication
.is_separate_authn_required(),
),
authentication_store
.authentication
.authentication_connector
.clone(),
Some(
authentication_store
.authentication
.authentication_id
.clone(),
),
),
None => (None, None, None),
};
let card_discovery = payment_data.get_card_discovery_for_card_payment_method();
let is_stored_credential = helpers::is_stored_credential(
&payment_data.recurring_details,
&payment_data.pm_token,
payment_data.mandate_id.is_some(),
payment_data.payment_attempt.is_stored_credential,
);
let payment_attempt_fut = tokio::spawn(
async move {
m_db.update_payment_attempt_with_attempt_id(
m_payment_data_payment_attempt,
storage::PaymentAttemptUpdate::ConfirmUpdate {
currency: payment_data.currency,
status: attempt_status,
payment_method,
authentication_type,
capture_method: m_capture_method,
browser_info: m_browser_info,
connector: m_connector,
payment_token: m_payment_token,
payment_method_data: m_additional_pm_data,
payment_method_type,
payment_experience,
business_sub_label: m_business_sub_label,
straight_through_algorithm: m_straight_through_algorithm,
error_code: m_error_code,
error_message: m_error_message,
updated_by: storage_scheme.to_string(),
merchant_connector_id,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
payment_method_billing_address_id,
fingerprint_id: m_fingerprint_id,
payment_method_id: m_payment_method_id,
client_source,
client_version,
customer_acceptance: payment_data.payment_attempt.customer_acceptance,
net_amount:
hyperswitch_domain_models::payments::payment_attempt::NetAmount::new(
payment_data.payment_attempt.net_amount.get_order_amount(),
payment_data.payment_intent.shipping_cost,
payment_data
.payment_attempt
.net_amount
.get_order_tax_amount(),
surcharge_amount,
tax_amount,
),
connector_mandate_detail: payment_data
.payment_attempt
.connector_mandate_detail,
card_discovery,
routing_approach: payment_data.payment_attempt.routing_approach,
connector_request_reference_id,
network_transaction_id: payment_data
.payment_attempt
.network_transaction_id
.clone(),
is_stored_credential,
request_extended_authorization: payment_data
.payment_attempt
.request_extended_authorization,
},
storage_scheme,
)
.map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))
.await
}
.in_current_span(),
);
let billing_address = payment_data.address.get_payment_billing();
let key_manager_state = state.into();
let billing_details = billing_address
.async_map(|billing_details| {
create_encrypted_data(&key_manager_state, key_store, billing_details)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt billing details")?;
let shipping_address = payment_data.address.get_shipping();
let shipping_details = shipping_address
.async_map(|shipping_details| {
create_encrypted_data(&key_manager_state, key_store, shipping_details)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt shipping details")?;
let m_payment_data_payment_intent = payment_data.payment_intent.clone();
let m_customer_id = customer_id.clone();
let m_shipping_address_id = shipping_address_id.clone();
let m_billing_address_id = billing_address_id.clone();
let m_return_url = return_url.clone();
let m_business_label = business_label.clone();
let m_description = description.clone();
let m_statement_descriptor_name = statement_descriptor_name.clone();
let m_statement_descriptor_suffix = statement_descriptor_suffix.clone();
let m_order_details = order_details.clone();
let m_metadata = metadata.clone();
let m_frm_metadata = frm_metadata.clone();
let m_db = state.clone().store;
let m_storage_scheme = storage_scheme.to_string();
let session_expiry = m_payment_data_payment_intent.session_expiry;
let m_key_store = key_store.clone();
let key_manager_state = state.into();
let is_payment_processor_token_flow =
payment_data.payment_intent.is_payment_processor_token_flow;
let payment_intent_fut = tokio::spawn(
async move {
m_db.update_payment_intent(
&key_manager_state,
m_payment_data_payment_intent,
storage::PaymentIntentUpdate::Update(Box::new(PaymentIntentUpdateFields {
amount: payment_data.payment_intent.amount,
currency: payment_data.currency,
setup_future_usage,
status: intent_status,
customer_id: m_customer_id,
shipping_address_id: m_shipping_address_id,
billing_address_id: m_billing_address_id,
return_url: m_return_url,
business_country,
business_label: m_business_label,
description: m_description,
statement_descriptor_name: m_statement_descriptor_name,
statement_descriptor_suffix: m_statement_descriptor_suffix,
order_details: m_order_details,
metadata: m_metadata,
payment_confirm_source: header_payload.payment_confirm_source,
updated_by: m_storage_scheme,
fingerprint_id: None,
session_expiry,
request_external_three_ds_authentication: None,
frm_metadata: m_frm_metadata,
customer_details,
merchant_order_reference_id: None,
billing_details,
shipping_details,
is_payment_processor_token_flow,
tax_details: None,
force_3ds_challenge: payment_data.payment_intent.force_3ds_challenge,
is_iframe_redirection_enabled: payment_data
.payment_intent
.is_iframe_redirection_enabled,
is_confirm_operation: true, // Indicates that this is a confirm operation
payment_channel: payment_data.payment_intent.payment_channel,
feature_metadata: payment_data
.payment_intent
.feature_metadata
.clone()
.map(masking::Secret::new),
tax_status: payment_data.payment_intent.tax_status,
discount_amount: payment_data.payment_intent.discount_amount,
order_date: payment_data.payment_intent.order_date,
shipping_amount_tax: payment_data.payment_intent.shipping_amount_tax,
duty_amount: payment_data.payment_intent.duty_amount,
enable_partial_authorization: payment_data
.payment_intent
.enable_partial_authorization,
enable_overcapture: payment_data.payment_intent.enable_overcapture,
})),
&m_key_store,
storage_scheme,
)
.map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))
.await
}
.in_current_span(),
);
let customer_fut =
if let Some((updated_customer, customer)) = updated_customer.zip(customer) {
let m_customer_merchant_id = customer.merchant_id.to_owned();
let m_key_store = key_store.clone();
let m_updated_customer = updated_customer.clone();
let session_state = state.clone();
let m_db = session_state.store.clone();
let key_manager_state = state.into();
tokio::spawn(
async move {
let m_customer_customer_id = customer.customer_id.to_owned();
m_db.update_customer_by_customer_id_merchant_id(
&key_manager_state,
m_customer_customer_id,
m_customer_merchant_id,
customer,
m_updated_customer,
&m_key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update CustomerConnector in customer")?;
Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(())
}
.in_current_span(),
)
} else {
tokio::spawn(
async move { Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(()) }
.in_current_span(),
)
};
let (payment_intent, payment_attempt, _) = tokio::try_join!(
utils::flatten_join_error(payment_intent_fut),
utils::flatten_join_error(payment_attempt_fut),
utils::flatten_join_error(customer_fut)
)?;
payment_data.payment_intent = payment_intent;
payment_data.payment_attempt = payment_attempt;
let client_src = payment_data.payment_attempt.client_source.clone();
let client_ver = payment_data.payment_attempt.client_version.clone();
let frm_message = payment_data.frm_message.clone();
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentConfirm {
client_src,
client_ver,
frm_message: Box::new(frm_message),
}))
.with(payment_data.to_event())
.emit();
Ok((Box::new(self), payment_data))
}
}
#[async_trait]
impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentData<F>>
for PaymentConfirm
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentConfirmOperation<'b, F>, operations::ValidateResult)> {
helpers::validate_customer_information(request)?;
if let Some(amount) = request.amount {
helpers::validate_max_amount(amount)?;
}
let request_merchant_id = request.merchant_id.as_ref();
helpers::validate_merchant_id(
merchant_context.get_merchant_account().get_id(),
request_merchant_id,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
})?;
helpers::validate_payment_method_fields_present(request)?;
let _mandate_type =
helpers::validate_mandate(request, payments::is_operation_confirm(self))?;
helpers::validate_recurring_details_and_token(
&request.recurring_details,
&request.payment_token,
&request.mandate_id,
)?;
request.validate_stored_credential().change_context(
errors::ApiErrorResponse::InvalidRequestData {
message:
"is_stored_credential should be true when reusing stored payment method data"
.to_string(),
},
)?;
let payment_id = request
.payment_id
.clone()
.ok_or(report!(errors::ApiErrorResponse::PaymentNotFound))?;
let _request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request
.routing
.clone()
.map(|val| val.parse_value("RoutingAlgorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid straight through routing rules format".to_string(),
})
.attach_printable("Invalid straight through routing rules format")?;
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id,
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: matches!(
request.retry_action,
Some(api_models::enums::RetryAction::Requeue)
),
},
))
}
}
| {
"crate": "router",
"file": "crates/router/src/core/payments/operations/payment_confirm.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_8524294582769129731 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/payments/operations/proxy_payments_intent.rs
// Contains: 1 structs, 0 enums
use api_models::payments::ProxyPaymentsRequest;
use async_trait::async_trait;
use common_enums::enums;
use common_utils::types::keymanager::ToEncryptable;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData, payments::PaymentConfirmData,
};
use hyperswitch_interfaces::api::ConnectorSpecifications;
use masking::PeekInterface;
use router_env::{instrument, tracing};
use super::{Domain, GetTracker, Operation, PostUpdateTracker, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payments::{
operations::{self, ValidateStatusForOperation},
OperationSessionGetters, OperationSessionSetters,
},
},
routes::{app::ReqState, SessionState},
types::{
self,
api::{self, ConnectorCallType},
domain::{self, types as domain_types},
storage::{self, enums as storage_enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy)]
pub struct PaymentProxyIntent;
impl ValidateStatusForOperation for PaymentProxyIntent {
/// Validate if the current operation can be performed on the current status of the payment intent
fn validate_status_for_operation(
&self,
intent_status: common_enums::IntentStatus,
) -> Result<(), errors::ApiErrorResponse> {
match intent_status {
//Failed state is included here so that in PCR, retries can be done for failed payments, otherwise for a failed attempt it was asking for new payment_intent
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::Processing => Ok(()),
//Failed state is included here so that in PCR, retries can be done for failed payments, otherwise for a failed attempt it was asking for new payment_intent
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::Failed => Ok(()),
common_enums::IntentStatus::Conflicted
| common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::Cancelled
| common_enums::IntentStatus::CancelledPostCapture
| common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
| common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::PartiallyCapturedAndCapturable
| common_enums::IntentStatus::Expired => {
Err(errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow: format!("{self:?}"),
field_name: "status".to_string(),
current_value: intent_status.to_string(),
states: ["requires_payment_method".to_string()].join(", "),
})
}
}
}
}
type BoxedConfirmOperation<'b, F> =
super::BoxedOperation<'b, F, ProxyPaymentsRequest, PaymentConfirmData<F>>;
impl<F: Send + Clone + Sync> Operation<F, ProxyPaymentsRequest> for &PaymentProxyIntent {
type Data = PaymentConfirmData<F>;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, ProxyPaymentsRequest, Self::Data> + Send + Sync)>
{
Ok(*self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, ProxyPaymentsRequest> + Send + Sync)> {
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&(dyn Domain<F, ProxyPaymentsRequest, Self::Data>)> {
Ok(*self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, ProxyPaymentsRequest> + Send + Sync)> {
Ok(*self)
}
}
#[automatically_derived]
impl<F: Send + Clone + Sync> Operation<F, ProxyPaymentsRequest> for PaymentProxyIntent {
type Data = PaymentConfirmData<F>;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, ProxyPaymentsRequest, Self::Data> + Send + Sync)>
{
Ok(self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, ProxyPaymentsRequest> + Send + Sync)> {
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, ProxyPaymentsRequest, Self::Data>> {
Ok(self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, ProxyPaymentsRequest> + Send + Sync)> {
Ok(self)
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, ProxyPaymentsRequest, PaymentConfirmData<F>>
for PaymentProxyIntent
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
_request: &ProxyPaymentsRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<operations::ValidateResult> {
let validate_result = operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
};
Ok(validate_result)
}
}
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, ProxyPaymentsRequest>
for PaymentProxyIntent
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &common_utils::id_type::GlobalPaymentId,
request: &ProxyPaymentsRequest,
merchant_context: &domain::MerchantContext,
_profile: &domain::Profile,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<PaymentConfirmData<F>>> {
let db = &*state.store;
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
self.validate_status_for_operation(payment_intent.status)?;
let cell_id = state.conf.cell_information.id.clone();
let batch_encrypted_data = domain_types::crypto_operation(
key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt),
domain_types::CryptoOperation::BatchEncrypt(
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::to_encryptable(
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt {
payment_method_billing_address: None,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details".to_string())?;
let encrypted_data =
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::from_encryptable(batch_encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details")?;
let payment_attempt = match payment_intent.active_attempt_id.clone() {
Some(ref active_attempt_id) => db
.find_payment_attempt_by_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
active_attempt_id,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Could not find payment attempt")?,
None => {
let payment_attempt_domain_model: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt =
hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt::proxy_create_domain_model(
&payment_intent,
cell_id,
storage_scheme,
request,
encrypted_data
)
.await?;
db.insert_payment_attempt(
key_manager_state,
merchant_context.get_merchant_key_store(),
payment_attempt_domain_model,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not insert payment attempt")?
}
};
let processor_payment_token = request.recurring_details.processor_payment_token.clone();
let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new(
payment_intent
.shipping_address
.clone()
.map(|address| address.into_inner()),
payment_intent
.billing_address
.clone()
.map(|address| address.into_inner()),
payment_attempt
.payment_method_billing_address
.clone()
.map(|address| address.into_inner()),
Some(true),
);
let mandate_data_input = api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId::new(
Some(processor_payment_token),
None,
None,
None,
None,
),
),
),
};
let payment_data = PaymentConfirmData {
flow: std::marker::PhantomData,
payment_intent,
payment_attempt,
payment_method_data: Some(PaymentMethodData::MandatePayment),
payment_address,
mandate_data: Some(mandate_data_input),
payment_method: None,
merchant_connector_details: None,
external_vault_pmd: None,
webhook_url: None,
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, ProxyPaymentsRequest, PaymentConfirmData<F>>
for PaymentProxyIntent
{
async fn get_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut PaymentConfirmData<F>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<(BoxedConfirmOperation<'a, F>, Option<domain::Customer>), errors::StorageError>
{
Ok((Box::new(self), None))
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
_state: &'a SessionState,
_payment_data: &mut PaymentConfirmData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
BoxedConfirmOperation<'a, F>,
Option<PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
#[instrument(skip_all)]
async fn populate_payment_data<'a>(
&'a self,
_state: &SessionState,
payment_data: &mut PaymentConfirmData<F>,
_merchant_context: &domain::MerchantContext,
_business_profile: &domain::Profile,
connector_data: &api::ConnectorData,
) -> CustomResult<(), errors::ApiErrorResponse> {
let connector_request_reference_id = connector_data
.connector
.generate_connector_request_reference_id(
&payment_data.payment_intent,
&payment_data.payment_attempt,
);
payment_data.set_connector_request_reference_id(Some(connector_request_reference_id));
Ok(())
}
async fn perform_routing<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
_business_profile: &domain::Profile,
state: &SessionState,
payment_data: &mut PaymentConfirmData<F>,
) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> {
let connector_name = payment_data.get_payment_attempt_connector();
if let Some(connector_name) = connector_name {
let merchant_connector_id = payment_data.get_merchant_connector_id_in_attempt();
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
merchant_connector_id,
)?;
Ok(ConnectorCallType::PreDetermined(connector_data.into()))
} else {
Err(error_stack::Report::new(
errors::ApiErrorResponse::InternalServerError,
))
}
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentConfirmData<F>, ProxyPaymentsRequest>
for PaymentProxyIntent
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
_req_state: ReqState,
mut payment_data: PaymentConfirmData<F>,
_customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<api_models::enums::FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(BoxedConfirmOperation<'b, F>, PaymentConfirmData<F>)>
where
F: 'b + Send,
{
let db = &*state.store;
let key_manager_state = &state.into();
let intent_status = common_enums::IntentStatus::Processing;
let attempt_status = common_enums::AttemptStatus::Pending;
let connector = payment_data
.payment_attempt
.connector
.clone()
.get_required_value("connector")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Connector is none when constructing response")?;
let merchant_connector_id = Some(
payment_data
.payment_attempt
.merchant_connector_id
.clone()
.get_required_value("merchant_connector_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant connector id is none when constructing response")?,
);
let payment_intent_update =
hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::ConfirmIntent {
status: intent_status,
updated_by: storage_scheme.to_string(),
active_attempt_id: Some(payment_data.payment_attempt.id.clone()),
};
let authentication_type = payment_data
.payment_intent
.authentication_type
.unwrap_or_default();
let connector_request_reference_id = payment_data
.payment_attempt
.connector_request_reference_id
.clone();
let connector_response_reference_id = payment_data
.payment_attempt
.connector_response_reference_id
.clone();
let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ConfirmIntent {
status: attempt_status,
updated_by: storage_scheme.to_string(),
connector,
merchant_connector_id,
authentication_type,
connector_request_reference_id,
connector_response_reference_id,
};
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent.clone(),
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
payment_data.payment_intent = updated_payment_intent;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt.clone(),
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_attempt = updated_payment_attempt;
Ok((Box::new(self), payment_data))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::PaymentsAuthorizeData>
for PaymentProxyIntent
{
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: PaymentConfirmData<F>,
response: types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentConfirmData<F>>
where
F: 'b + Send + Sync,
types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
F,
types::PaymentsAuthorizeData,
PaymentConfirmData<F>,
>,
{
use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
let db = &*state.store;
let key_manager_state = &state.into();
let response_router_data = response;
let payment_intent_update =
response_router_data.get_payment_intent_update(&payment_data, storage_scheme);
let payment_attempt_update =
response_router_data.get_payment_attempt_update(&payment_data, storage_scheme);
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_intent = updated_payment_intent;
payment_data.payment_attempt = updated_payment_attempt;
Ok(payment_data)
}
}
| {
"crate": "router",
"file": "crates/router/src/core/payments/operations/proxy_payments_intent.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_7845194249217518751 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/payments/operations/payment_update_intent.rs
// Contains: 1 structs, 0 enums
use std::marker::PhantomData;
use api_models::{
enums::{FrmSuggestion, UpdateActiveAttempt},
payments::PaymentsUpdateIntentRequest,
};
use async_trait::async_trait;
use common_utils::{
errors::CustomResult,
ext_traits::{Encode, ValueExt},
types::keymanager::ToEncryptable,
};
use diesel_models::types::FeatureMetadata;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payments::payment_intent::{PaymentIntentUpdate, PaymentIntentUpdateFields},
ApiModelToDieselModelConvertor,
};
use masking::PeekInterface;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult},
payments::{
self, helpers,
operations::{self, ValidateStatusForOperation},
},
},
db::errors::StorageErrorExt,
routes::{app::ReqState, SessionState},
types::{
api,
domain::{self, types as domain_types},
storage::{self, enums},
},
};
#[derive(Debug, Clone, Copy)]
pub struct PaymentUpdateIntent;
impl ValidateStatusForOperation for PaymentUpdateIntent {
/// Validate if the current operation can be performed on the current status of the payment intent
fn validate_status_for_operation(
&self,
intent_status: common_enums::IntentStatus,
) -> Result<(), errors::ApiErrorResponse> {
match intent_status {
// if the status is `Failed`` we would want to Update few intent fields to perform a Revenue Recovery retry
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::Conflicted => Ok(()),
common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::Cancelled
| common_enums::IntentStatus::CancelledPostCapture
| common_enums::IntentStatus::Processing
| common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
| common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::PartiallyCapturedAndCapturable
| common_enums::IntentStatus::Expired => {
Err(errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow: format!("{self:?}"),
field_name: "status".to_string(),
current_value: intent_status.to_string(),
states: ["requires_payment_method".to_string()].join(", "),
})
}
}
}
}
impl<F: Send + Clone> Operation<F, PaymentsUpdateIntentRequest> for &PaymentUpdateIntent {
type Data = payments::PaymentIntentData<F>;
fn to_validate_request(
&self,
) -> RouterResult<
&(dyn ValidateRequest<F, PaymentsUpdateIntentRequest, Self::Data> + Send + Sync),
> {
Ok(*self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)>
{
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsUpdateIntentRequest, Self::Data>)> {
Ok(*self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)>
{
Ok(*self)
}
}
impl<F: Send + Clone> Operation<F, PaymentsUpdateIntentRequest> for PaymentUpdateIntent {
type Data = payments::PaymentIntentData<F>;
fn to_validate_request(
&self,
) -> RouterResult<
&(dyn ValidateRequest<F, PaymentsUpdateIntentRequest, Self::Data> + Send + Sync),
> {
Ok(self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)>
{
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsUpdateIntentRequest, Self::Data>> {
Ok(self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)>
{
Ok(self)
}
}
type PaymentsUpdateIntentOperation<'b, F> =
BoxedOperation<'b, F, PaymentsUpdateIntentRequest, payments::PaymentIntentData<F>>;
#[async_trait]
impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsUpdateIntentRequest>
for PaymentUpdateIntent
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &common_utils::id_type::GlobalPaymentId,
request: &PaymentsUpdateIntentRequest,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> {
let db = &*state.store;
if let Some(routing_algorithm_id) = request.routing_algorithm_id.as_ref() {
helpers::validate_routing_id_with_profile_id(
db,
routing_algorithm_id,
profile.get_id(),
)
.await?;
}
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
self.validate_status_for_operation(payment_intent.status)?;
let PaymentsUpdateIntentRequest {
amount_details,
routing_algorithm_id,
capture_method,
authentication_type,
billing,
shipping,
customer_present,
description,
return_url,
setup_future_usage,
apply_mit_exemption,
statement_descriptor,
order_details,
allowed_payment_method_types,
metadata,
connector_metadata,
feature_metadata,
payment_link_config,
request_incremental_authorization,
session_expiry,
frm_metadata,
request_external_three_ds_authentication,
set_active_attempt_id,
enable_partial_authorization,
} = request.clone();
let batch_encrypted_data = domain_types::crypto_operation(
key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::payments::PaymentIntent),
domain_types::CryptoOperation::BatchEncrypt(
hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent::to_encryptable(
hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent {
shipping_address: shipping.map(|address| address.encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode shipping address")?.map(masking::Secret::new),
billing_address: billing.map(|address| address.encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode billing address")?.map(masking::Secret::new),
customer_details: None,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details".to_string())?;
let decrypted_payment_intent =
hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent::from_encryptable(batch_encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details")?;
let order_details = order_details.clone().map(|order_details| {
order_details
.into_iter()
.map(|order_detail| {
masking::Secret::new(
diesel_models::types::OrderDetailsWithAmount::convert_from(order_detail),
)
})
.collect()
});
let session_expiry = session_expiry.map(|expiry| {
payment_intent
.created_at
.saturating_add(time::Duration::seconds(i64::from(expiry)))
});
let updated_amount_details = match amount_details {
Some(details) => payment_intent.amount_details.update_from_request(&details),
None => payment_intent.amount_details,
};
let active_attempt_id = set_active_attempt_id
.map(|active_attempt_req| match active_attempt_req {
UpdateActiveAttempt::Set(global_attempt_id) => Some(global_attempt_id),
UpdateActiveAttempt::Unset => None,
})
.unwrap_or(payment_intent.active_attempt_id);
let payment_intent = hyperswitch_domain_models::payments::PaymentIntent {
amount_details: updated_amount_details,
description: description.or(payment_intent.description),
return_url: return_url.or(payment_intent.return_url),
metadata: metadata.or(payment_intent.metadata),
statement_descriptor: statement_descriptor.or(payment_intent.statement_descriptor),
modified_at: common_utils::date_time::now(),
order_details,
connector_metadata: connector_metadata.or(payment_intent.connector_metadata),
feature_metadata: (feature_metadata
.map(FeatureMetadata::convert_from)
.or(payment_intent.feature_metadata)),
updated_by: storage_scheme.to_string(),
request_incremental_authorization: request_incremental_authorization
.unwrap_or(payment_intent.request_incremental_authorization),
session_expiry: session_expiry.unwrap_or(payment_intent.session_expiry),
request_external_three_ds_authentication: request_external_three_ds_authentication
.unwrap_or(payment_intent.request_external_three_ds_authentication),
frm_metadata: frm_metadata.or(payment_intent.frm_metadata),
billing_address: decrypted_payment_intent
.billing_address
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode billing address")?,
shipping_address: decrypted_payment_intent
.shipping_address
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode shipping address")?,
capture_method: capture_method.unwrap_or(payment_intent.capture_method),
authentication_type: authentication_type.or(payment_intent.authentication_type),
payment_link_config: payment_link_config
.map(ApiModelToDieselModelConvertor::convert_from)
.or(payment_intent.payment_link_config),
apply_mit_exemption: apply_mit_exemption.unwrap_or(payment_intent.apply_mit_exemption),
customer_present: customer_present.unwrap_or(payment_intent.customer_present),
routing_algorithm_id: routing_algorithm_id.or(payment_intent.routing_algorithm_id),
allowed_payment_method_types: allowed_payment_method_types
.or(payment_intent.allowed_payment_method_types),
active_attempt_id,
enable_partial_authorization: enable_partial_authorization
.or(payment_intent.enable_partial_authorization),
..payment_intent
};
let payment_data = payments::PaymentIntentData {
flow: PhantomData,
payment_intent,
client_secret: None,
sessions_token: vec![],
vault_session_details: None,
connector_customer_id: None,
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone> UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsUpdateIntentRequest>
for PaymentUpdateIntent
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
_req_state: ReqState,
mut payment_data: payments::PaymentIntentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
PaymentsUpdateIntentOperation<'b, F>,
payments::PaymentIntentData<F>,
)>
where
F: 'b + Send,
{
let db = &*state.store;
let key_manager_state = &state.into();
let intent = payment_data.payment_intent.clone();
let payment_intent_update =
PaymentIntentUpdate::UpdateIntent(Box::new(PaymentIntentUpdateFields {
amount: Some(intent.amount_details.order_amount),
currency: Some(intent.amount_details.currency),
shipping_cost: intent.amount_details.shipping_cost,
skip_external_tax_calculation: Some(
intent.amount_details.skip_external_tax_calculation,
),
skip_surcharge_calculation: Some(intent.amount_details.skip_surcharge_calculation),
surcharge_amount: intent.amount_details.surcharge_amount,
tax_on_surcharge: intent.amount_details.tax_on_surcharge,
routing_algorithm_id: intent.routing_algorithm_id,
capture_method: Some(intent.capture_method),
authentication_type: intent.authentication_type,
billing_address: intent.billing_address,
shipping_address: intent.shipping_address,
customer_present: Some(intent.customer_present),
description: intent.description,
return_url: intent.return_url,
setup_future_usage: Some(intent.setup_future_usage),
apply_mit_exemption: Some(intent.apply_mit_exemption),
statement_descriptor: intent.statement_descriptor,
order_details: intent.order_details,
allowed_payment_method_types: intent.allowed_payment_method_types,
metadata: intent.metadata,
connector_metadata: intent
.connector_metadata
.map(|cm| cm.encode_to_value())
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize connector_metadata")?
.map(masking::Secret::new),
feature_metadata: intent.feature_metadata,
payment_link_config: intent.payment_link_config,
request_incremental_authorization: Some(intent.request_incremental_authorization),
session_expiry: Some(intent.session_expiry),
frm_metadata: intent.frm_metadata,
request_external_three_ds_authentication: Some(
intent.request_external_three_ds_authentication,
),
updated_by: intent.updated_by,
tax_details: intent.amount_details.tax_details,
active_attempt_id: Some(intent.active_attempt_id),
force_3ds_challenge: intent.force_3ds_challenge,
is_iframe_redirection_enabled: intent.is_iframe_redirection_enabled,
enable_partial_authorization: intent.enable_partial_authorization,
}));
let new_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not update Intent")?;
payment_data.payment_intent = new_payment_intent;
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone>
ValidateRequest<F, PaymentsUpdateIntentRequest, payments::PaymentIntentData<F>>
for PaymentUpdateIntent
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
_request: &PaymentsUpdateIntentRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<operations::ValidateResult> {
Ok(operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
})
}
}
#[async_trait]
impl<F: Clone + Send> Domain<F, PaymentsUpdateIntentRequest, payments::PaymentIntentData<F>>
for PaymentUpdateIntent
{
#[instrument(skip_all)]
async fn get_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut payments::PaymentIntentData<F>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, PaymentsUpdateIntentRequest, payments::PaymentIntentData<F>>,
Option<domain::Customer>,
),
errors::StorageError,
> {
Ok((Box::new(self), None))
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
_state: &'a SessionState,
_payment_data: &mut payments::PaymentIntentData<F>,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
PaymentsUpdateIntentOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
#[instrument(skip_all)]
async fn perform_routing<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
_business_profile: &domain::Profile,
_state: &SessionState,
_payment_data: &mut payments::PaymentIntentData<F>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
Ok(api::ConnectorCallType::Skip)
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut payments::PaymentIntentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
| {
"crate": "router",
"file": "crates/router/src/core/payments/operations/payment_update_intent.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_9093034479378097478 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/payments/operations/payments_extend_authorization.rs
// Contains: 1 structs, 0 enums
use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use error_stack::ResultExt;
use router_derive;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{self, helpers, operations, PaymentData},
},
routes::{app::ReqState, SessionState},
services,
types::{
self as core_types,
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, router_derive::PaymentOperation)]
#[operation(operations = "all", flow = "extend_authorization")]
pub struct PaymentExtendAuthorization;
type PaymentExtendAuthorizationOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsExtendAuthorizationRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsExtendAuthorizationRequest>
for PaymentExtendAuthorization
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
_request: &api::PaymentsExtendAuthorizationRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<
'a,
F,
api::PaymentsExtendAuthorizationRequest,
PaymentData<F>,
>,
> {
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
helpers::validate_payment_status_against_allowed_statuses(
payment_intent.status,
&[
enums::IntentStatus::RequiresCapture,
enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture,
],
"extend authorization",
)?;
let payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
if !payment_attempt
.request_extended_authorization
.is_some_and(|request_extended_authorization| request_extended_authorization.is_true())
{
Err(errors::ApiErrorResponse::PreconditionFailed {
message:
"You cannot extend the authorization for this payment because authorization extension is not enabled.".to_owned(),
})?
}
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
token_data: None,
address: core_types::PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
confirm: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, api::PaymentsExtendAuthorizationRequest, PaymentData<F>>
for PaymentExtendAuthorization
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut PaymentData<F>,
_request: Option<payments::CustomerDetails>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> errors::CustomResult<
(
PaymentExtendAuthorizationOperation<'a, F>,
Option<domain::Customer>,
),
errors::StorageError,
> {
Ok((Box::new(self), None))
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
_state: &'a SessionState,
_payment_data: &mut PaymentData<F>,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
PaymentExtendAuthorizationOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
async fn get_connector<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
state: &SessionState,
_request: &api::PaymentsExtendAuthorizationRequest,
_payment_intent: &storage::PaymentIntent,
) -> errors::CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
helpers::get_connector_default(state, None).await
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut PaymentData<F>,
) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsExtendAuthorizationRequest>
for PaymentExtendAuthorization
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
_req_state: ReqState,
payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentExtendAuthorizationOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync>
ValidateRequest<F, api::PaymentsExtendAuthorizationRequest, PaymentData<F>>
for PaymentExtendAuthorization
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsExtendAuthorizationRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(
PaymentExtendAuthorizationOperation<'b, F>,
operations::ValidateResult,
)> {
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
| {
"crate": "router",
"file": "crates/router/src/core/payments/operations/payments_extend_authorization.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_7583994678333398375 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/payments/operations/payment_update.rs
// Contains: 1 structs, 0 enums
use std::marker::PhantomData;
use api_models::{
enums::FrmSuggestion, mandates::RecurringDetails, payments::RequestSurchargeDetails,
};
use async_trait::async_trait;
use common_utils::{
ext_traits::{AsyncExt, Encode, ValueExt},
pii::Email,
types::keymanager::KeyManagerState,
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::payments::payment_intent::{
CustomerData, PaymentIntentUpdateFields,
};
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payment_methods::cards::create_encrypted_data,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums, payment_attempt::PaymentAttemptExt},
transformers::ForeignTryFrom,
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
#[operation(operations = "all", flow = "authorize")]
pub struct PaymentUpdate;
type PaymentUpdateOperation<'a, F> = BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentUpdate {
#[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 (mut payment_intent, mut payment_attempt, currency): (_, _, storage_enums::Currency);
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let db = &*state.store;
let key_manager_state = &state.into();
helpers::allow_payment_update_enabled_for_client_auth(merchant_id, state, auth_flow)
.await?;
payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
// TODO (#7195): Add platform merchant account validation once publishable key auth is solved
if let Some(order_details) = &request.order_details {
helpers::validate_order_details_amount(
order_details.to_owned(),
payment_intent.amount,
false,
)?;
}
payment_intent.setup_future_usage = request
.setup_future_usage
.or(payment_intent.setup_future_usage);
helpers::validate_customer_access(&payment_intent, auth_flow, request)?;
helpers::validate_card_data(
request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone()),
)?;
helpers::validate_payment_status_against_allowed_statuses(
payment_intent.status,
&[
storage_enums::IntentStatus::RequiresPaymentMethod,
storage_enums::IntentStatus::RequiresConfirmation,
],
"update",
)?;
helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
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_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let customer_acceptance = request.customer_acceptance.clone();
let recurring_details = request.recurring_details.clone();
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_helpers::MandateGenericData {
token,
payment_method,
payment_method_type,
mandate_data,
recurring_mandate_payment_data,
mandate_connector,
payment_method_info,
} = Box::pin(helpers::get_token_pm_type_mandate_details(
state,
request,
mandate_type.to_owned(),
merchant_context,
None,
payment_intent.customer_id.as_ref(),
))
.await?;
helpers::validate_amount_to_capture_and_capture_method(Some(&payment_attempt), request)?;
helpers::validate_request_amount_and_amount_to_capture(
request.amount,
request.amount_to_capture,
request
.surcharge_details
.or(payment_attempt.get_surcharge_details()),
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "amount_to_capture".to_string(),
expected_format: "amount_to_capture lesser than or equal to amount".to_string(),
})?;
currency = request
.currency
.or(payment_attempt.currency)
.get_required_value("currency")?;
payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method);
payment_attempt.payment_method_type =
payment_method_type.or(payment_attempt.payment_method_type);
let customer_details = helpers::get_customer_details_from_request(request);
let amount = request
.amount
.unwrap_or_else(|| payment_attempt.net_amount.get_order_amount().into());
if request.confirm.unwrap_or(false) {
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 shipping_address = helpers::create_or_update_address_for_payment_by_request(
state,
request.shipping.as_ref(),
payment_intent.shipping_address_id.as_deref(),
merchant_id,
payment_intent
.customer_id
.as_ref()
.or(customer_details.customer_id.as_ref()),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::create_or_update_address_for_payment_by_request(
state,
request.billing.as_ref(),
payment_intent.billing_address_id.as_deref(),
merchant_id,
payment_intent
.customer_id
.as_ref()
.or(customer_details.customer_id.as_ref()),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::create_or_update_address_for_payment_by_request(
state,
request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.billing.as_ref()),
payment_attempt.payment_method_billing_address_id.as_deref(),
merchant_id,
payment_intent
.customer_id
.as_ref()
.or(customer_details.customer_id.as_ref()),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
payment_intent.shipping_address_id = shipping_address.clone().map(|x| x.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|x| x.address_id);
payment_attempt.payment_method_billing_address_id = payment_method_billing
.as_ref()
.map(|payment_method_billing| payment_method_billing.address_id.clone());
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.psd2_sca_exemption_type = request
.psd2_sca_exemption_type
.or(payment_intent.psd2_sca_exemption_type);
Self::populate_payment_intent_with_request(&mut payment_intent, request);
let token = token.or_else(|| payment_attempt.payment_token.clone());
if request.confirm.unwrap_or(false) {
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 = if let Some(token) = token.clone() {
Some(helpers::retrieve_payment_token_data(state, token, payment_method).await?)
} else {
None
};
let mandate_id = request
.mandate_id
.as_ref()
.or_else(|| {
request.recurring_details
.as_ref()
.and_then(|recurring_details| match recurring_details {
RecurringDetails::MandateId(id) => Some(id),
_ => None,
})
})
.async_and_then(|mandate_id| async {
let mandate = db
.find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id, merchant_context.get_merchant_account().storage_scheme)
.await
.change_context(errors::ApiErrorResponse::MandateNotFound);
Some(mandate.and_then(|mandate_obj| {
match (
mandate_obj.network_transaction_id,
mandate_obj.connector_mandate_ids,
) {
(Some(network_tx_id), _) => Ok(api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::NetworkMandateId(
network_tx_id,
),
),
}),
(_, Some(connector_mandate_id)) => connector_mandate_id
.parse_value("ConnectorMandateId")
.change_context(errors::ApiErrorResponse::MandateNotFound)
.map(|connector_id: api_models::payments::ConnectorMandateReferenceId| {
api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId::new(
connector_id.get_connector_mandate_id(), // connector_mandate_id
connector_id.get_payment_method_id(), // payment_method_id
None, // update_history
connector_id.get_mandate_metadata(), // mandate_metadata
connector_id.get_connector_mandate_request_reference_id() // connector_mandate_request_reference_id
)
))
}
}),
(_, _) => Ok(api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: None,
}),
}
}))
})
.await
.transpose()?;
let (next_operation, amount): (PaymentUpdateOperation<'a, F>, _) =
if request.confirm.unwrap_or(false) {
let amount = {
let amount = request
.amount
.map(Into::into)
.unwrap_or(payment_attempt.net_amount.get_order_amount());
payment_attempt.net_amount.set_order_amount(amount);
payment_intent.amount = amount;
let surcharge_amount = request
.surcharge_details
.as_ref()
.map(RequestSurchargeDetails::get_total_surcharge_amount)
.or(payment_attempt.get_total_surcharge_amount());
amount + surcharge_amount.unwrap_or_default()
};
(Box::new(operations::PaymentConfirm), amount.into())
} else {
(Box::new(self), amount)
};
payment_intent.status = if request
.payment_method_data
.as_ref()
.is_some_and(|payment_method_data| payment_method_data.payment_method_data.is_some())
{
if request.confirm.unwrap_or(false) {
payment_intent.status
} else {
storage_enums::IntentStatus::RequiresConfirmation
}
} else {
storage_enums::IntentStatus::RequiresPaymentMethod
};
payment_intent.request_external_three_ds_authentication = request
.request_external_three_ds_authentication
.or(payment_intent.request_external_three_ds_authentication);
payment_intent.merchant_order_reference_id = request
.merchant_order_reference_id
.clone()
.or(payment_intent.merchant_order_reference_id);
Self::populate_payment_attempt_with_request(&mut payment_attempt, request);
let creds_identifier = request
.merchant_connector_details
.as_ref()
.map(|mcd| mcd.creds_identifier.to_owned());
request
.merchant_connector_details
.to_owned()
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(
db,
merchant_context.get_merchant_account().get_id(),
mcd,
)
.await
})
.await
.transpose()?;
// The operation merges mandate data from both request and payment_attempt
let setup_mandate = mandate_data;
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 profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let surcharge_details = request.surcharge_details.map(|request_surcharge_details| {
payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt))
});
payment_intent.force_3ds_challenge = request
.force_3ds_challenge
.or(payment_intent.force_3ds_challenge);
payment_intent.payment_channel = request
.payment_channel
.clone()
.or(payment_intent.payment_channel);
payment_intent.enable_partial_authorization = request
.enable_partial_authorization
.or(payment_intent.enable_partial_authorization);
helpers::validate_overcapture_request(
&request.enable_overcapture,
&payment_attempt.capture_method,
)?;
payment_intent.enable_overcapture = request.enable_overcapture;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: request.email.clone(),
mandate_id,
mandate_connector,
token,
token_data,
setup_mandate,
customer_acceptance,
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,
),
confirm: request.confirm,
payment_method_data: request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone().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,
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: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: business_profile.is_l2_l3_enabled,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: next_operation,
customer_details: Some(customer_details),
payment_data,
business_profile,
mandate_type,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for PaymentUpdate {
#[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<(PaymentUpdateOperation<'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
}
async fn payments_dynamic_tax_calculation<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
_connector_call_type: &ConnectorCallType,
business_profile: &domain::Profile,
merchant_context: &domain::MerchantContext,
) -> CustomResult<(), errors::ApiErrorResponse> {
let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled();
let skip_external_tax_calculation = payment_data
.payment_intent
.skip_external_tax_calculation
.unwrap_or(false);
if is_tax_connector_enabled && !skip_external_tax_calculation {
let db = state.store.as_ref();
let key_manager_state: &KeyManagerState = &state.into();
let merchant_connector_id = business_profile
.tax_connector_id
.as_ref()
.get_required_value("business_profile.tax_connector_id")?;
#[cfg(feature = "v1")]
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&business_profile.merchant_id,
merchant_connector_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
#[cfg(feature = "v2")]
let mca = db
.find_merchant_connector_account_by_id(
key_manager_state,
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
let connector_data =
api::TaxCalculateConnectorData::get_connector_by_name(&mca.connector_name)?;
let router_data = core_utils::construct_payments_dynamic_tax_calculation_router_data(
state,
merchant_context,
payment_data,
&mca,
)
.await?;
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CalculateTax,
types::PaymentsTaxCalculationData,
types::TaxCalculationResponseData,
> = connector_data.connector.get_connector_integration();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Tax connector Response Failed")?;
let tax_response = response.response.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector_data.connector_name.clone().to_string(),
status_code: err.status_code,
reason: err.reason,
}
})?;
payment_data.payment_intent.tax_details = Some(diesel_models::TaxDetails {
default: Some(diesel_models::DefaultTax {
order_tax_amount: tax_response.order_tax_amount,
}),
payment_method_type: None,
});
Ok(())
} else {
Ok(())
}
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: storage_enums::MerchantStorageScheme,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
PaymentUpdateOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
merchant_key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await
}
#[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> {
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> {
helpers::get_connector_default(state, request.routing.clone()).await
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut PaymentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentUpdate {
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
req_state: ReqState,
mut _payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentUpdateOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentUpdateOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
let is_payment_method_unavailable =
payment_data.payment_attempt.payment_method_id.is_none()
&& payment_data.payment_intent.status
== storage_enums::IntentStatus::RequiresPaymentMethod;
let payment_method = payment_data.payment_attempt.payment_method;
let get_attempt_status = || {
if is_payment_method_unavailable {
storage_enums::AttemptStatus::PaymentMethodAwaited
} else {
storage_enums::AttemptStatus::ConfirmationAwaited
}
};
let profile_id = payment_data
.payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let additional_pm_data = payment_data
.payment_method_data
.as_ref()
.async_map(|payment_method_data| async {
helpers::get_additional_payment_data(payment_method_data, &*state.store, profile_id)
.await
})
.await
.transpose()?
.flatten();
let encoded_pm_data = additional_pm_data
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?;
let business_sub_label = payment_data.payment_attempt.business_sub_label.clone();
let payment_method_type = payment_data.payment_attempt.payment_method_type;
let payment_experience = payment_data.payment_attempt.payment_experience;
let amount_to_capture = payment_data.payment_attempt.amount_to_capture;
let capture_method = payment_data.payment_attempt.capture_method;
let payment_method_billing_address_id = payment_data
.payment_attempt
.payment_method_billing_address_id
.clone();
let surcharge_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.surcharge_amount);
let tax_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.tax_on_surcharge_amount);
let network_transaction_id = payment_data.payment_attempt.network_transaction_id.clone();
payment_data.payment_attempt = state
.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt,
storage::PaymentAttemptUpdate::Update {
currency: payment_data.currency,
status: get_attempt_status(),
authentication_type: None,
payment_method,
payment_token: payment_data.token.clone(),
payment_method_data: encoded_pm_data,
payment_experience,
payment_method_type,
business_sub_label,
amount_to_capture,
capture_method,
fingerprint_id: None,
payment_method_billing_address_id,
updated_by: storage_scheme.to_string(),
network_transaction_id,
net_amount:
hyperswitch_domain_models::payments::payment_attempt::NetAmount::new(
payment_data.amount.into(),
None,
None,
surcharge_amount,
tax_amount,
),
},
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let customer_id = customer.clone().map(|c| c.customer_id);
let intent_status = {
let current_intent_status = payment_data.payment_intent.status;
if is_payment_method_unavailable {
storage_enums::IntentStatus::RequiresPaymentMethod
} else if !payment_data.confirm.unwrap_or(true)
|| current_intent_status == storage_enums::IntentStatus::RequiresCustomerAction
{
storage_enums::IntentStatus::RequiresConfirmation
} else {
payment_data.payment_intent.status
}
};
let (shipping_address, billing_address) = (
payment_data.payment_intent.shipping_address_id.clone(),
payment_data.payment_intent.billing_address_id.clone(),
);
let customer_details = payment_data.payment_intent.customer_details.clone();
let return_url = payment_data.payment_intent.return_url.clone();
let setup_future_usage = payment_data.payment_intent.setup_future_usage;
let business_label = payment_data.payment_intent.business_label.clone();
let business_country = payment_data.payment_intent.business_country;
let description = payment_data.payment_intent.description.clone();
let statement_descriptor_name = payment_data
.payment_intent
.statement_descriptor_name
.clone();
let statement_descriptor_suffix = payment_data
.payment_intent
.statement_descriptor_suffix
.clone();
let key_manager_state = state.into();
let billing_details = payment_data
.address
.get_payment_billing()
.async_map(|billing_details| {
create_encrypted_data(&key_manager_state, key_store, billing_details)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt billing details")?;
let shipping_details = payment_data
.address
.get_shipping()
.async_map(|shipping_details| {
create_encrypted_data(&key_manager_state, key_store, shipping_details)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt shipping details")?;
let order_details = payment_data.payment_intent.order_details.clone();
let metadata = payment_data.payment_intent.metadata.clone();
let frm_metadata = payment_data.payment_intent.frm_metadata.clone();
let session_expiry = payment_data.payment_intent.session_expiry;
let merchant_order_reference_id = payment_data
.payment_intent
.merchant_order_reference_id
.clone();
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent.clone(),
storage::PaymentIntentUpdate::Update(Box::new(PaymentIntentUpdateFields {
amount: payment_data.amount.into(),
currency: payment_data.currency,
setup_future_usage,
status: intent_status,
customer_id: customer_id.clone(),
shipping_address_id: shipping_address,
billing_address_id: billing_address,
return_url,
business_country,
business_label,
description,
statement_descriptor_name,
statement_descriptor_suffix,
order_details,
metadata,
payment_confirm_source: None,
updated_by: storage_scheme.to_string(),
fingerprint_id: None,
session_expiry,
request_external_three_ds_authentication: payment_data
.payment_intent
.request_external_three_ds_authentication,
frm_metadata,
customer_details,
merchant_order_reference_id,
billing_details,
shipping_details,
is_payment_processor_token_flow: None,
tax_details: None,
force_3ds_challenge: payment_data.payment_intent.force_3ds_challenge,
is_iframe_redirection_enabled: payment_data
.payment_intent
.is_iframe_redirection_enabled,
is_confirm_operation: false, // this is not a confirm operation
payment_channel: payment_data.payment_intent.payment_channel,
feature_metadata: payment_data
.payment_intent
.feature_metadata
.clone()
.map(masking::Secret::new),
tax_status: payment_data.payment_intent.tax_status,
discount_amount: payment_data.payment_intent.discount_amount,
order_date: payment_data.payment_intent.order_date,
shipping_amount_tax: payment_data.payment_intent.shipping_amount_tax,
duty_amount: payment_data.payment_intent.duty_amount,
enable_partial_authorization: payment_data
.payment_intent
.enable_partial_authorization,
enable_overcapture: payment_data.payment_intent.enable_overcapture,
})),
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let amount = payment_data.amount;
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentUpdate { amount }))
.with(payment_data.to_event())
.emit();
Ok((
payments::is_confirm(self, payment_data.confirm),
payment_data,
))
}
}
impl ForeignTryFrom<domain::Customer> for CustomerData {
type Error = errors::ApiErrorResponse;
fn foreign_try_from(value: domain::Customer) -> Result<Self, Self::Error> {
Ok(Self {
name: value.name.map(|name| name.into_inner()),
email: value.email.map(Email::from),
phone: value.phone.map(|ph| ph.into_inner()),
phone_country_code: value.phone_country_code,
tax_registration_id: value
.tax_registration_id
.map(|tax_registration_id| tax_registration_id.into_inner()),
})
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentData<F>>
for PaymentUpdate
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentUpdateOperation<'b, F>, operations::ValidateResult)> {
helpers::validate_customer_information(request)?;
if let Some(amount) = request.amount {
helpers::validate_max_amount(amount)?;
}
if let Some(session_expiry) = &request.session_expiry {
helpers::validate_session_expiry(session_expiry.to_owned())?;
}
let payment_id = request
.payment_id
.clone()
.ok_or(report!(errors::ApiErrorResponse::PaymentNotFound))?;
let request_merchant_id = request.merchant_id.as_ref();
helpers::validate_merchant_id(
merchant_context.get_merchant_account().get_id(),
request_merchant_id,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
})?;
helpers::validate_request_amount_and_amount_to_capture(
request.amount,
request.amount_to_capture,
request.surcharge_details,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "amount_to_capture".to_string(),
expected_format: "amount_to_capture lesser than or equal to amount".to_string(),
})?;
helpers::validate_payment_method_fields_present(request)?;
let _mandate_type = helpers::validate_mandate(request, false)?;
helpers::validate_recurring_details_and_token(
&request.recurring_details,
&request.payment_token,
&request.mandate_id,
)?;
let _request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request
.routing
.clone()
.map(|val| val.parse_value("RoutingAlgorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid straight through routing rules format".to_string(),
})
.attach_printable("Invalid straight through routing rules format")?;
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id,
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: matches!(
request.retry_action,
Some(api_models::enums::RetryAction::Requeue)
),
},
))
}
}
impl PaymentUpdate {
fn populate_payment_attempt_with_request(
payment_attempt: &mut storage::PaymentAttempt,
request: &api::PaymentsRequest,
) {
request
.business_sub_label
.clone()
.map(|bsl| payment_attempt.business_sub_label.replace(bsl));
request
.payment_method_type
.map(|pmt| payment_attempt.payment_method_type.replace(pmt));
request
.payment_experience
.map(|experience| payment_attempt.payment_experience.replace(experience));
payment_attempt.amount_to_capture = request
.amount_to_capture
.or(payment_attempt.amount_to_capture);
request
.capture_method
.map(|i| payment_attempt.capture_method.replace(i));
}
fn populate_payment_intent_with_request(
payment_intent: &mut storage::PaymentIntent,
request: &api::PaymentsRequest,
) {
request
.return_url
.clone()
.map(|i| payment_intent.return_url.replace(i.to_string()));
payment_intent.business_country = request.business_country;
payment_intent
.business_label
.clone_from(&request.business_label);
request
.description
.clone()
.map(|i| payment_intent.description.replace(i));
request
.statement_descriptor_name
.clone()
.map(|i| payment_intent.statement_descriptor_name.replace(i));
request
.statement_descriptor_suffix
.clone()
.map(|i| payment_intent.statement_descriptor_suffix.replace(i));
request
.client_secret
.clone()
.map(|i| payment_intent.client_secret.replace(i));
}
}
| {
"crate": "router",
"file": "crates/router/src/core/payments/operations/payment_update.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-3451067206245137353 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/payments/routing/utils.rs
// Contains: 38 structs, 9 enums
use std::{
collections::{HashMap, HashSet},
str::FromStr,
};
use api_models::{
open_router as or_types,
routing::{
self as api_routing, ComparisonType, ConnectorSelection, ConnectorVolumeSplit,
DeRoutableConnectorChoice, MetadataValue, NumberComparison, RoutableConnectorChoice,
RoutingEvaluateRequest, RoutingEvaluateResponse, ValueType,
},
};
use async_trait::async_trait;
use common_enums::{RoutableConnectors, TransactionType};
use common_utils::{
ext_traits::{BytesExt, StringExt},
id_type,
};
use diesel_models::{enums, routing_algorithm};
use error_stack::ResultExt;
use euclid::{
backend::BackendInput,
frontend::{
ast::{self},
dir::{self, transformers::IntoDirValue},
},
};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use external_services::grpc_client::dynamic_routing as ir_client;
use hyperswitch_domain_models::business_profile;
use hyperswitch_interfaces::events::routing_api_logs as routing_events;
use router_env::tracing_actix_web::RequestId;
use serde::{Deserialize, Serialize};
use super::RoutingResult;
use crate::{
core::errors,
db::domain,
routes::{app::SessionStateInfo, SessionState},
services::{self, logger},
types::transformers::ForeignInto,
};
// New Trait for handling Euclid API calls
#[async_trait]
pub trait DecisionEngineApiHandler {
async fn send_decision_engine_request<Req, Res>(
state: &SessionState,
http_method: services::Method,
path: &str,
request_body: Option<Req>, // Option to handle GET/DELETE requests without body
timeout: Option<u64>,
events_wrapper: Option<RoutingEventsWrapper<Req>>,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
Req: Serialize + Send + Sync + 'static + Clone,
Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone;
}
// Struct to implement the DecisionEngineApiHandler trait
pub struct EuclidApiClient;
pub struct ConfigApiClient;
pub struct SRApiClient;
pub async fn build_and_send_decision_engine_http_request<Req, Res, ErrRes>(
state: &SessionState,
http_method: services::Method,
path: &str,
request_body: Option<Req>,
_timeout: Option<u64>,
context_message: &str,
events_wrapper: Option<RoutingEventsWrapper<Req>>,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
Req: Serialize + Send + Sync + 'static + Clone,
Res: Serialize + serde::de::DeserializeOwned + std::fmt::Debug + Clone + 'static,
ErrRes: serde::de::DeserializeOwned + std::fmt::Debug + Clone + DecisionEngineErrorsInterface,
{
let decision_engine_base_url = &state.conf.open_router.url;
let url = format!("{decision_engine_base_url}/{path}");
logger::debug!(decision_engine_api_call_url = %url, decision_engine_request_path = %path, http_method = ?http_method, "decision_engine: Initiating decision_engine API call ({})", context_message);
let mut request_builder = services::RequestBuilder::new()
.method(http_method)
.url(&url);
if let Some(body_content) = request_body {
let body = common_utils::request::RequestContent::Json(Box::new(body_content));
request_builder = request_builder.set_body(body);
}
let http_request = request_builder.build();
logger::info!(?http_request, decision_engine_request_path = %path, "decision_engine: Constructed Decision Engine API request details ({})", context_message);
let should_parse_response = events_wrapper
.as_ref()
.map(|wrapper| wrapper.parse_response)
.unwrap_or(true);
let closure = || async {
let response =
services::call_connector_api(state, http_request, "Decision Engine API call")
.await
.change_context(errors::RoutingError::OpenRouterCallFailed)?;
match response {
Ok(resp) => {
logger::debug!(
"decision_engine: Received response from Decision Engine API ({:?})",
String::from_utf8_lossy(&resp.response) // For logging
);
let resp = should_parse_response
.then(|| {
if std::any::TypeId::of::<Res>() == std::any::TypeId::of::<String>()
&& resp.response.is_empty()
{
return serde_json::from_str::<Res>("\"\"").change_context(
errors::RoutingError::OpenRouterError(
"Failed to parse empty response as String".into(),
),
);
}
let response_type: Res = resp
.response
.parse_struct(std::any::type_name::<Res>())
.change_context(errors::RoutingError::OpenRouterError(
"Failed to parse the response from open_router".into(),
))?;
Ok::<_, error_stack::Report<errors::RoutingError>>(response_type)
})
.transpose()?;
logger::debug!("decision_engine_success_response: {:?}", resp);
Ok(resp)
}
Err(err) => {
logger::debug!(
"decision_engine: Received response from Decision Engine API ({:?})",
String::from_utf8_lossy(&err.response) // For logging
);
let err_resp: ErrRes = err
.response
.parse_struct(std::any::type_name::<ErrRes>())
.change_context(errors::RoutingError::OpenRouterError(
"Failed to parse the response from open_router".into(),
))?;
logger::error!(
decision_engine_error_code = %err_resp.get_error_code(),
decision_engine_error_message = %err_resp.get_error_message(),
decision_engine_raw_response = ?err_resp.get_error_data(),
);
Err(error_stack::report!(
errors::RoutingError::RoutingEventsError {
message: err_resp.get_error_message(),
status_code: err.status_code,
}
))
}
}
};
let events_response = if let Some(wrapper) = events_wrapper {
wrapper
.construct_event_builder(
url,
routing_events::RoutingEngine::DecisionEngine,
routing_events::ApiMethod::Rest(http_method),
)?
.trigger_event(state, closure)
.await?
} else {
let resp = closure()
.await
.change_context(errors::RoutingError::OpenRouterCallFailed)?;
RoutingEventsResponse::new(None, resp)
};
Ok(events_response)
}
#[async_trait]
impl DecisionEngineApiHandler for EuclidApiClient {
async fn send_decision_engine_request<Req, Res>(
state: &SessionState,
http_method: services::Method,
path: &str,
request_body: Option<Req>, // Option to handle GET/DELETE requests without body
timeout: Option<u64>,
events_wrapper: Option<RoutingEventsWrapper<Req>>,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
Req: Serialize + Send + Sync + 'static + Clone,
Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone,
{
let event_response = build_and_send_decision_engine_http_request::<_, _, DeErrorResponse>(
state,
http_method,
path,
request_body,
timeout,
"parsing response",
events_wrapper,
)
.await?;
let parsed_response =
event_response
.response
.as_ref()
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), euclid_request_path = %path, "decision_engine_euclid: Successfully parsed response from Euclid API");
Ok(event_response)
}
}
#[async_trait]
impl DecisionEngineApiHandler for ConfigApiClient {
async fn send_decision_engine_request<Req, Res>(
state: &SessionState,
http_method: services::Method,
path: &str,
request_body: Option<Req>,
timeout: Option<u64>,
events_wrapper: Option<RoutingEventsWrapper<Req>>,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
Req: Serialize + Send + Sync + 'static + Clone,
Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone,
{
let events_response = build_and_send_decision_engine_http_request::<_, _, DeErrorResponse>(
state,
http_method,
path,
request_body,
timeout,
"parsing response",
events_wrapper,
)
.await?;
let parsed_response =
events_response
.response
.as_ref()
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), decision_engine_request_path = %path, "decision_engine_config: Successfully parsed response from Decision Engine config API");
Ok(events_response)
}
}
#[async_trait]
impl DecisionEngineApiHandler for SRApiClient {
async fn send_decision_engine_request<Req, Res>(
state: &SessionState,
http_method: services::Method,
path: &str,
request_body: Option<Req>,
timeout: Option<u64>,
events_wrapper: Option<RoutingEventsWrapper<Req>>,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
Req: Serialize + Send + Sync + 'static + Clone,
Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone,
{
let events_response =
build_and_send_decision_engine_http_request::<_, _, or_types::ErrorResponse>(
state,
http_method,
path,
request_body,
timeout,
"parsing response",
events_wrapper,
)
.await?;
let parsed_response =
events_response
.response
.as_ref()
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), decision_engine_request_path = %path, "decision_engine_config: Successfully parsed response from Decision Engine config API");
Ok(events_response)
}
}
const EUCLID_API_TIMEOUT: u64 = 5;
pub async fn perform_decision_euclid_routing(
state: &SessionState,
input: BackendInput,
created_by: String,
events_wrapper: RoutingEventsWrapper<RoutingEvaluateRequest>,
fallback_output: Vec<RoutableConnectorChoice>,
) -> RoutingResult<RoutingEvaluateResponse> {
logger::debug!("decision_engine_euclid: evaluate api call for euclid routing evaluation");
let mut events_wrapper = events_wrapper;
let fallback_output = fallback_output
.into_iter()
.map(|c| DeRoutableConnectorChoice {
gateway_name: c.connector,
gateway_id: c.merchant_connector_id,
})
.collect::<Vec<_>>();
let routing_request =
convert_backend_input_to_routing_eval(created_by, input, fallback_output)?;
events_wrapper.set_request_body(routing_request.clone());
let event_response = EuclidApiClient::send_decision_engine_request(
state,
services::Method::Post,
"routing/evaluate",
Some(routing_request),
Some(EUCLID_API_TIMEOUT),
Some(events_wrapper),
)
.await?;
let euclid_response: RoutingEvaluateResponse =
event_response
.response
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
let mut routing_event =
event_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message: "Routing event not found in EventsResponse".to_string(),
status_code: 500,
})?;
routing_event.set_routing_approach(RoutingApproach::StaticRouting.to_string());
routing_event.set_routable_connectors(euclid_response.evaluated_output.clone());
state.event_handler.log_event(&routing_event);
logger::debug!(decision_engine_euclid_response=?euclid_response,"decision_engine_euclid");
logger::debug!(decision_engine_euclid_selected_connector=?euclid_response.evaluated_output,"decision_engine_euclid");
Ok(euclid_response)
}
/// This function transforms the decision_engine response in a way that's usable for further flows:
/// It places evaluated_output connectors first, followed by remaining output connectors (no duplicates).
pub fn transform_de_output_for_router(
de_output: Vec<ConnectorInfo>,
de_evaluated_output: Vec<RoutableConnectorChoice>,
) -> RoutingResult<Vec<RoutableConnectorChoice>> {
let mut seen = HashSet::new();
// evaluated connectors on top, to ensure the fallback is based on other connectors.
let mut ordered = Vec::with_capacity(de_output.len() + de_evaluated_output.len());
for eval_conn in de_evaluated_output {
if seen.insert(eval_conn.connector) {
ordered.push(eval_conn);
}
}
// Add remaining connectors from de_output (only if not already seen), for fallback
for conn in de_output {
let key = RoutableConnectors::from_str(&conn.gateway_name).map_err(|_| {
errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
}
})?;
if seen.insert(key) {
let de_choice = DeRoutableConnectorChoice::try_from(conn)?;
ordered.push(RoutableConnectorChoice::from(de_choice));
}
}
Ok(ordered)
}
pub async fn decision_engine_routing(
state: &SessionState,
backend_input: BackendInput,
business_profile: &domain::Profile,
payment_id: String,
merchant_fallback_config: Vec<RoutableConnectorChoice>,
) -> RoutingResult<Vec<RoutableConnectorChoice>> {
let routing_events_wrapper = RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_id,
business_profile.get_id().to_owned(),
business_profile.merchant_id.to_owned(),
"DecisionEngine: Euclid Static Routing".to_string(),
None,
true,
false,
);
let de_euclid_evaluate_response = perform_decision_euclid_routing(
state,
backend_input.clone(),
business_profile.get_id().get_string_repr().to_string(),
routing_events_wrapper,
merchant_fallback_config,
)
.await;
let Ok(de_euclid_response) = de_euclid_evaluate_response else {
logger::error!("decision_engine_euclid_evaluation_error: error in evaluation of rule");
return Ok(Vec::default());
};
let de_output_connector = extract_de_output_connectors(de_euclid_response.output)
.map_err(|e| {
logger::error!(error=?e, "decision_engine_euclid_evaluation_error: Failed to extract connector from Output");
e
})?;
transform_de_output_for_router(
de_output_connector.clone(),
de_euclid_response.evaluated_output.clone(),
)
.map_err(|e| {
logger::error!(error=?e, "decision_engine_euclid_evaluation_error: failed to transform connector from de-output");
e
})
}
/// Custom deserializer for output from decision_engine, this is required as untagged enum is
/// stored but the enum requires tagged deserialization, hence deserializing it into specific
/// variants
pub fn extract_de_output_connectors(
output_value: serde_json::Value,
) -> RoutingResult<Vec<ConnectorInfo>> {
const SINGLE: &str = "straight_through";
const PRIORITY: &str = "priority";
const VOLUME_SPLIT: &str = "volume_split";
const VOLUME_SPLIT_PRIORITY: &str = "volume_split_priority";
let obj = output_value.as_object().ok_or_else(|| {
logger::error!("decision_engine_euclid_error: output is not a JSON object");
errors::RoutingError::OpenRouterError("Expected output to be a JSON object".into())
})?;
let type_str = obj.get("type").and_then(|v| v.as_str()).ok_or_else(|| {
logger::error!("decision_engine_euclid_error: missing or invalid 'type' in output");
errors::RoutingError::OpenRouterError("Missing or invalid 'type' field in output".into())
})?;
match type_str {
SINGLE => {
let connector_value = obj.get("connector").ok_or_else(|| {
logger::error!(
"decision_engine_euclid_error: missing 'connector' field for type=single"
);
errors::RoutingError::OpenRouterError(
"Missing 'connector' field for single output".into(),
)
})?;
let connector: ConnectorInfo = serde_json::from_value(connector_value.clone())
.map_err(|e| {
logger::error!(
?e,
"decision_engine_euclid_error: Failed to parse single connector"
);
errors::RoutingError::OpenRouterError(
"Failed to deserialize single connector".into(),
)
})?;
Ok(vec![connector])
}
PRIORITY => {
let connectors_value = obj.get("connectors").ok_or_else(|| {
logger::error!(
"decision_engine_euclid_error: missing 'connectors' field for type=priority"
);
errors::RoutingError::OpenRouterError(
"Missing 'connectors' field for priority output".into(),
)
})?;
let connectors: Vec<ConnectorInfo> = serde_json::from_value(connectors_value.clone())
.map_err(|e| {
logger::error!(
?e,
"decision_engine_euclid_error: Failed to parse connectors for priority"
);
errors::RoutingError::OpenRouterError(
"Failed to deserialize priority connectors".into(),
)
})?;
Ok(connectors)
}
VOLUME_SPLIT => {
let splits_value = obj.get("splits").ok_or_else(|| {
logger::error!(
"decision_engine_euclid_error: missing 'splits' field for type=volume_split"
);
errors::RoutingError::OpenRouterError(
"Missing 'splits' field for volume_split output".into(),
)
})?;
// Transform each {connector, split} into {output, split}
let fixed_splits: Vec<_> = splits_value
.as_array()
.ok_or_else(|| {
logger::error!("decision_engine_euclid_error: 'splits' is not an array");
errors::RoutingError::OpenRouterError("'splits' field must be an array".into())
})?
.iter()
.map(|entry| {
let mut entry_map = entry.as_object().cloned().ok_or_else(|| {
logger::error!(
"decision_engine_euclid_error: invalid split entry in volume_split"
);
errors::RoutingError::OpenRouterError(
"Invalid entry in splits array".into(),
)
})?;
if let Some(connector) = entry_map.remove("connector") {
entry_map.insert("output".to_string(), connector);
}
Ok::<_, error_stack::Report<errors::RoutingError>>(serde_json::Value::Object(
entry_map,
))
})
.collect::<Result<Vec<_>, _>>()?;
let splits: Vec<VolumeSplit<ConnectorInfo>> =
serde_json::from_value(serde_json::Value::Array(fixed_splits)).map_err(|e| {
logger::error!(
?e,
"decision_engine_euclid_error: Failed to parse volume_split"
);
errors::RoutingError::OpenRouterError(
"Failed to deserialize volume_split connectors".into(),
)
})?;
Ok(splits.into_iter().map(|s| s.output).collect())
}
VOLUME_SPLIT_PRIORITY => {
let splits_value = obj.get("splits").ok_or_else(|| {
logger::error!("decision_engine_euclid_error: missing 'splits' field for type=volume_split_priority");
errors::RoutingError::OpenRouterError("Missing 'splits' field for volume_split_priority output".into())
})?;
// Transform each {connector: [...], split} into {output: [...], split}
let fixed_splits: Vec<_> = splits_value
.as_array()
.ok_or_else(|| {
logger::error!("decision_engine_euclid_error: 'splits' is not an array");
errors::RoutingError::OpenRouterError("'splits' field must be an array".into())
})?
.iter()
.map(|entry| {
let mut entry_map = entry.as_object().cloned().ok_or_else(|| {
logger::error!("decision_engine_euclid_error: invalid split entry in volume_split_priority");
errors::RoutingError::OpenRouterError("Invalid entry in splits array".into())
})?;
if let Some(connector) = entry_map.remove("connector") {
entry_map.insert("output".to_string(), connector);
}
Ok::<_, error_stack::Report<errors::RoutingError>>(serde_json::Value::Object(entry_map))
})
.collect::<Result<Vec<_>, _>>()?;
let splits: Vec<VolumeSplit<Vec<ConnectorInfo>>> =
serde_json::from_value(serde_json::Value::Array(fixed_splits)).map_err(|e| {
logger::error!(
?e,
"decision_engine_euclid_error: Failed to parse volume_split_priority"
);
errors::RoutingError::OpenRouterError(
"Failed to deserialize volume_split_priority connectors".into(),
)
})?;
Ok(splits.into_iter().flat_map(|s| s.output).collect())
}
other => {
logger::error!(type_str=%other, "decision_engine_euclid_error: unknown output type");
Err(
errors::RoutingError::OpenRouterError(format!("Unknown output type: {other}"))
.into(),
)
}
}
}
pub async fn create_de_euclid_routing_algo(
state: &SessionState,
routing_request: &RoutingRule,
) -> RoutingResult<String> {
logger::debug!("decision_engine_euclid: create api call for euclid routing rule creation");
logger::debug!(decision_engine_euclid_request=?routing_request,"decision_engine_euclid");
let events_response = EuclidApiClient::send_decision_engine_request(
state,
services::Method::Post,
"routing/create",
Some(routing_request.clone()),
Some(EUCLID_API_TIMEOUT),
None,
)
.await?;
let euclid_response: RoutingDictionaryRecord =
events_response
.response
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
logger::debug!(decision_engine_euclid_parsed_response=?euclid_response,"decision_engine_euclid");
Ok(euclid_response.rule_id)
}
pub async fn link_de_euclid_routing_algorithm(
state: &SessionState,
routing_request: ActivateRoutingConfigRequest,
) -> RoutingResult<()> {
logger::debug!("decision_engine_euclid: link api call for euclid routing algorithm");
EuclidApiClient::send_decision_engine_request::<_, String>(
state,
services::Method::Post,
"routing/activate",
Some(routing_request.clone()),
Some(EUCLID_API_TIMEOUT),
None,
)
.await?;
logger::debug!(decision_engine_euclid_activated=?routing_request, "decision_engine_euclid: link_de_euclid_routing_algorithm completed");
Ok(())
}
pub async fn list_de_euclid_routing_algorithms(
state: &SessionState,
routing_list_request: ListRountingAlgorithmsRequest,
) -> RoutingResult<Vec<api_routing::RoutingDictionaryRecord>> {
logger::debug!("decision_engine_euclid: list api call for euclid routing algorithms");
let created_by = routing_list_request.created_by;
let events_response = EuclidApiClient::send_decision_engine_request(
state,
services::Method::Post,
format!("routing/list/{created_by}").as_str(),
None::<()>,
Some(EUCLID_API_TIMEOUT),
None,
)
.await?;
let euclid_response: Vec<RoutingAlgorithmRecord> =
events_response
.response
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
Ok(euclid_response
.into_iter()
.map(routing_algorithm::RoutingProfileMetadata::from)
.map(ForeignInto::foreign_into)
.collect::<Vec<_>>())
}
pub async fn list_de_euclid_active_routing_algorithm(
state: &SessionState,
created_by: String,
) -> RoutingResult<Vec<api_routing::RoutingDictionaryRecord>> {
logger::debug!("decision_engine_euclid: list api call for euclid active routing algorithm");
let response: Vec<RoutingAlgorithmRecord> = EuclidApiClient::send_decision_engine_request(
state,
services::Method::Post,
format!("routing/list/active/{created_by}").as_str(),
None::<()>,
Some(EUCLID_API_TIMEOUT),
None,
)
.await?
.response
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
Ok(response
.into_iter()
.map(|record| routing_algorithm::RoutingProfileMetadata::from(record).foreign_into())
.collect())
}
pub fn compare_and_log_result<T: RoutingEq<T> + Serialize>(
de_result: Vec<T>,
result: Vec<T>,
flow: String,
) {
let is_equal = de_result
.iter()
.zip(result.iter())
.all(|(a, b)| T::is_equal(a, b));
let is_equal_in_length = de_result.len() == result.len();
router_env::logger::debug!(routing_flow=?flow, is_equal=?is_equal, is_equal_length=?is_equal_in_length, de_response=?to_json_string(&de_result), hs_response=?to_json_string(&result), "decision_engine_euclid");
}
pub trait RoutingEq<T> {
fn is_equal(a: &T, b: &T) -> bool;
}
impl RoutingEq<Self> for api_routing::RoutingDictionaryRecord {
fn is_equal(a: &Self, b: &Self) -> bool {
a.id == b.id
&& a.name == b.name
&& a.profile_id == b.profile_id
&& a.description == b.description
&& a.kind == b.kind
&& a.algorithm_for == b.algorithm_for
}
}
impl RoutingEq<Self> for String {
fn is_equal(a: &Self, b: &Self) -> bool {
a.to_lowercase() == b.to_lowercase()
}
}
impl RoutingEq<Self> for RoutableConnectorChoice {
fn is_equal(a: &Self, b: &Self) -> bool {
a.connector.eq(&b.connector)
&& a.choice_kind.eq(&b.choice_kind)
&& a.merchant_connector_id.eq(&b.merchant_connector_id)
}
}
pub fn to_json_string<T: Serialize>(value: &T) -> String {
serde_json::to_string(value)
.map_err(|_| errors::RoutingError::GenericConversionError {
from: "T".to_string(),
to: "JsonValue".to_string(),
})
.unwrap_or_default()
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ActivateRoutingConfigRequest {
pub created_by: String,
pub routing_algorithm_id: String,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ListRountingAlgorithmsRequest {
pub created_by: String,
}
// Maps Hyperswitch `BackendInput` to a `RoutingEvaluateRequest` compatible with Decision Engine
pub fn convert_backend_input_to_routing_eval(
created_by: String,
input: BackendInput,
fallback_output: Vec<DeRoutableConnectorChoice>,
) -> RoutingResult<RoutingEvaluateRequest> {
let mut params: HashMap<String, Option<ValueType>> = HashMap::new();
// Payment
params.insert(
"amount".to_string(),
Some(ValueType::Number(
input
.payment
.amount
.get_amount_as_i64()
.try_into()
.unwrap_or_default(),
)),
);
params.insert(
"currency".to_string(),
Some(ValueType::EnumVariant(input.payment.currency.to_string())),
);
if let Some(auth_type) = input.payment.authentication_type {
params.insert(
"authentication_type".to_string(),
Some(ValueType::EnumVariant(auth_type.to_string())),
);
}
if let Some(bin) = input.payment.card_bin {
params.insert("card_bin".to_string(), Some(ValueType::StrValue(bin)));
}
if let Some(capture_method) = input.payment.capture_method {
params.insert(
"capture_method".to_string(),
Some(ValueType::EnumVariant(capture_method.to_string())),
);
}
if let Some(country) = input.payment.business_country {
params.insert(
"business_country".to_string(),
Some(ValueType::EnumVariant(country.to_string())),
);
}
if let Some(country) = input.payment.billing_country {
params.insert(
"billing_country".to_string(),
Some(ValueType::EnumVariant(country.to_string())),
);
}
if let Some(label) = input.payment.business_label {
params.insert(
"business_label".to_string(),
Some(ValueType::StrValue(label)),
);
}
if let Some(sfu) = input.payment.setup_future_usage {
params.insert(
"setup_future_usage".to_string(),
Some(ValueType::EnumVariant(sfu.to_string())),
);
}
// PaymentMethod
if let Some(pm) = input.payment_method.payment_method {
params.insert(
"payment_method".to_string(),
Some(ValueType::EnumVariant(pm.to_string())),
);
if let Some(pmt) = input.payment_method.payment_method_type {
match (pmt, pm).into_dir_value() {
Ok(dv) => insert_dirvalue_param(&mut params, dv),
Err(e) => logger::debug!(
?e,
?pmt,
?pm,
"decision_engine_euclid: into_dir_value failed; skipping subset param"
),
}
}
}
if let Some(pmt) = input.payment_method.payment_method_type {
params.insert(
"payment_method_type".to_string(),
Some(ValueType::EnumVariant(pmt.to_string())),
);
}
if let Some(network) = input.payment_method.card_network {
params.insert(
"card_network".to_string(),
Some(ValueType::EnumVariant(network.to_string())),
);
}
// Mandate
if let Some(pt) = input.mandate.payment_type {
params.insert(
"payment_type".to_string(),
Some(ValueType::EnumVariant(pt.to_string())),
);
}
if let Some(mt) = input.mandate.mandate_type {
params.insert(
"mandate_type".to_string(),
Some(ValueType::EnumVariant(mt.to_string())),
);
}
if let Some(mat) = input.mandate.mandate_acceptance_type {
params.insert(
"mandate_acceptance_type".to_string(),
Some(ValueType::EnumVariant(mat.to_string())),
);
}
// Metadata
if let Some(meta) = input.metadata {
for (k, v) in meta.into_iter() {
params.insert(
k.clone(),
Some(ValueType::MetadataVariant(MetadataValue {
key: k,
value: v,
})),
);
}
}
Ok(RoutingEvaluateRequest {
created_by,
parameters: params,
fallback_output,
})
}
// All the independent variants of payment method types, configured via dashboard
fn insert_dirvalue_param(params: &mut HashMap<String, Option<ValueType>>, dv: dir::DirValue) {
match dv {
dir::DirValue::RewardType(v) => {
params.insert(
"reward".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::CardType(v) => {
params.insert(
"card".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::PayLaterType(v) => {
params.insert(
"pay_later".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::WalletType(v) => {
params.insert(
"wallet".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::VoucherType(v) => {
params.insert(
"voucher".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::BankRedirectType(v) => {
params.insert(
"bank_redirect".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::BankDebitType(v) => {
params.insert(
"bank_debit".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::BankTransferType(v) => {
params.insert(
"bank_transfer".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::RealTimePaymentType(v) => {
params.insert(
"real_time_payment".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::UpiType(v) => {
params.insert(
"upi".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::GiftCardType(v) => {
params.insert(
"gift_card".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::CardRedirectType(v) => {
params.insert(
"card_redirect".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::OpenBankingType(v) => {
params.insert(
"open_banking".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::MobilePaymentType(v) => {
params.insert(
"mobile_payment".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::CryptoType(v) => {
params.insert(
"crypto".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
other => {
// all other values can be ignored for now as they don't converge with
// payment method type
logger::warn!(
?other,
"decision_engine_euclid: unmapped dir::DirValue; add a mapping here"
);
}
}
}
#[derive(Debug, Clone, serde::Deserialize)]
struct DeErrorResponse {
code: String,
message: String,
data: Option<serde_json::Value>,
}
impl DecisionEngineErrorsInterface for DeErrorResponse {
fn get_error_message(&self) -> String {
self.message.clone()
}
fn get_error_code(&self) -> String {
self.code.clone()
}
fn get_error_data(&self) -> Option<String> {
self.data.as_ref().map(|data| data.to_string())
}
}
impl DecisionEngineErrorsInterface for or_types::ErrorResponse {
fn get_error_message(&self) -> String {
self.error_message.clone()
}
fn get_error_code(&self) -> String {
self.error_code.clone()
}
fn get_error_data(&self) -> Option<String> {
Some(format!(
"decision_engine Error: {}",
self.error_message.clone()
))
}
}
pub type Metadata = HashMap<String, serde_json::Value>;
/// Represents a single comparison condition.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Comparison {
/// The left hand side which will always be a domain input identifier like "payment.method.cardtype"
pub lhs: String,
/// The comparison operator
pub comparison: ComparisonType,
/// The value to compare against
pub value: ValueType,
/// Additional metadata that the Static Analyzer and Backend does not touch.
/// This can be used to store useful information for the frontend and is required for communication
/// between the static analyzer and the frontend.
// #[schema(value_type=HashMap<String, serde_json::Value>)]
pub metadata: Metadata,
}
/// Represents all the conditions of an IF statement
/// eg:
///
/// ```text
/// payment.method = card & payment.method.cardtype = debit & payment.method.network = diners
/// ```
pub type IfCondition = Vec<Comparison>;
/// Represents an IF statement with conditions and optional nested IF statements
///
/// ```text
/// payment.method = card {
/// payment.method.cardtype = (credit, debit) {
/// payment.method.network = (amex, rupay, diners)
/// }
/// }
/// ```
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct IfStatement {
// #[schema(value_type=Vec<Comparison>)]
pub condition: IfCondition,
pub nested: Option<Vec<IfStatement>>,
}
/// Represents a rule
///
/// ```text
/// rule_name: [stripe, adyen, checkout]
/// {
/// payment.method = card {
/// payment.method.cardtype = (credit, debit) {
/// payment.method.network = (amex, rupay, diners)
/// }
///
/// payment.method.cardtype = credit
/// }
/// }
/// ```
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
// #[aliases(RuleConnectorSelection = Rule<ConnectorSelection>)]
pub struct Rule {
pub name: String,
#[serde(alias = "routingType")]
pub routing_type: RoutingType,
#[serde(alias = "routingOutput")]
pub output: Output,
pub statements: Vec<IfStatement>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RoutingType {
Priority,
VolumeSplit,
VolumeSplitPriority,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct VolumeSplit<T> {
pub split: u8,
pub output: T,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct ConnectorInfo {
pub gateway_name: String,
pub gateway_id: Option<String>,
}
impl TryFrom<ConnectorInfo> for DeRoutableConnectorChoice {
type Error = error_stack::Report<errors::RoutingError>;
fn try_from(c: ConnectorInfo) -> Result<Self, Self::Error> {
let gateway_id = c
.gateway_id
.map(|mca| {
id_type::MerchantConnectorAccountId::wrap(mca)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "MerchantConnectorAccountId".to_string(),
})
.attach_printable("unable to convert MerchantConnectorAccountId from string")
})
.transpose()?;
let gateway_name = RoutableConnectors::from_str(&c.gateway_name)
.map_err(|_| errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
})
.attach_printable("unable to convert connector name to RoutableConnectors")?;
Ok(Self {
gateway_name,
gateway_id,
})
}
}
impl ConnectorInfo {
pub fn new(gateway_name: String, gateway_id: Option<String>) -> Self {
Self {
gateway_name,
gateway_id,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Output {
Single(ConnectorInfo),
Priority(Vec<ConnectorInfo>),
VolumeSplit(Vec<VolumeSplit<ConnectorInfo>>),
VolumeSplitPriority(Vec<VolumeSplit<Vec<ConnectorInfo>>>),
}
pub type Globals = HashMap<String, HashSet<ValueType>>;
/// The program, having a default connector selection and
/// a bunch of rules. Also can hold arbitrary metadata.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
// #[aliases(ProgramConnectorSelection = Program<ConnectorSelection>)]
pub struct Program {
pub globals: Globals,
pub default_selection: Output,
// #[schema(value_type=RuleConnectorSelection)]
pub rules: Vec<Rule>,
// #[schema(value_type=HashMap<String, serde_json::Value>)]
pub metadata: Option<Metadata>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RoutingRule {
pub rule_id: Option<String>,
pub name: String,
pub description: Option<String>,
pub metadata: Option<RoutingMetadata>,
pub created_by: String,
#[serde(default)]
pub algorithm_for: AlgorithmType,
pub algorithm: StaticRoutingAlgorithm,
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, strum::Display)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum AlgorithmType {
#[default]
Payment,
Payout,
ThreeDsAuthentication,
}
impl From<TransactionType> for AlgorithmType {
fn from(transaction_type: TransactionType) -> Self {
match transaction_type {
TransactionType::Payment => Self::Payment,
TransactionType::Payout => Self::Payout,
TransactionType::ThreeDsAuthentication => Self::ThreeDsAuthentication,
}
}
}
impl From<RoutableConnectorChoice> for ConnectorInfo {
fn from(c: RoutableConnectorChoice) -> Self {
Self {
gateway_name: c.connector.to_string(),
gateway_id: c
.merchant_connector_id
.map(|mca_id| mca_id.get_string_repr().to_string()),
}
}
}
impl From<Box<RoutableConnectorChoice>> for ConnectorInfo {
fn from(c: Box<RoutableConnectorChoice>) -> Self {
Self {
gateway_name: c.connector.to_string(),
gateway_id: c
.merchant_connector_id
.map(|mca_id| mca_id.get_string_repr().to_string()),
}
}
}
impl From<ConnectorVolumeSplit> for VolumeSplit<ConnectorInfo> {
fn from(v: ConnectorVolumeSplit) -> Self {
Self {
split: v.split,
output: ConnectorInfo {
gateway_name: v.connector.connector.to_string(),
gateway_id: v
.connector
.merchant_connector_id
.map(|mca_id| mca_id.get_string_repr().to_string()),
},
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum StaticRoutingAlgorithm {
Single(Box<ConnectorInfo>),
Priority(Vec<ConnectorInfo>),
VolumeSplit(Vec<VolumeSplit<ConnectorInfo>>),
Advanced(Program),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RoutingMetadata {
pub kind: enums::RoutingAlgorithmKind,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RoutingDictionaryRecord {
pub rule_id: String,
pub name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RoutingAlgorithmRecord {
pub id: id_type::RoutingId,
pub name: String,
pub description: Option<String>,
pub created_by: id_type::ProfileId,
pub algorithm_data: StaticRoutingAlgorithm,
pub algorithm_for: TransactionType,
pub metadata: Option<RoutingMetadata>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
}
impl From<RoutingAlgorithmRecord> for routing_algorithm::RoutingProfileMetadata {
fn from(record: RoutingAlgorithmRecord) -> Self {
let kind = match record.algorithm_data {
StaticRoutingAlgorithm::Single(_) => enums::RoutingAlgorithmKind::Single,
StaticRoutingAlgorithm::Priority(_) => enums::RoutingAlgorithmKind::Priority,
StaticRoutingAlgorithm::VolumeSplit(_) => enums::RoutingAlgorithmKind::VolumeSplit,
StaticRoutingAlgorithm::Advanced(_) => enums::RoutingAlgorithmKind::Advanced,
};
Self {
profile_id: record.created_by,
algorithm_id: record.id,
name: record.name,
description: record.description,
kind,
created_at: record.created_at,
modified_at: record.modified_at,
algorithm_for: record.algorithm_for,
}
}
}
impl TryFrom<ast::Program<ConnectorSelection>> for Program {
type Error = error_stack::Report<errors::RoutingError>;
fn try_from(p: ast::Program<ConnectorSelection>) -> Result<Self, Self::Error> {
let rules = p
.rules
.into_iter()
.map(convert_rule)
.collect::<Result<Vec<_>, _>>()?;
Ok(Self {
globals: HashMap::new(),
default_selection: convert_output(p.default_selection),
rules,
metadata: Some(p.metadata),
})
}
}
impl TryFrom<ast::Program<ConnectorSelection>> for StaticRoutingAlgorithm {
type Error = error_stack::Report<errors::RoutingError>;
fn try_from(p: ast::Program<ConnectorSelection>) -> Result<Self, Self::Error> {
let internal_program: Program = p.try_into()?;
Ok(Self::Advanced(internal_program))
}
}
fn convert_rule(rule: ast::Rule<ConnectorSelection>) -> RoutingResult<Rule> {
let routing_type = match &rule.connector_selection {
ConnectorSelection::Priority(_) => RoutingType::Priority,
ConnectorSelection::VolumeSplit(_) => RoutingType::VolumeSplit,
};
Ok(Rule {
name: rule.name,
routing_type,
output: convert_output(rule.connector_selection),
statements: rule
.statements
.into_iter()
.map(convert_if_stmt)
.collect::<RoutingResult<Vec<IfStatement>>>()?,
})
}
fn convert_if_stmt(stmt: ast::IfStatement) -> RoutingResult<IfStatement> {
Ok(IfStatement {
condition: stmt
.condition
.into_iter()
.map(convert_comparison)
.collect::<RoutingResult<Vec<Comparison>>>()?,
nested: stmt
.nested
.map(|v| {
v.into_iter()
.map(convert_if_stmt)
.collect::<RoutingResult<Vec<IfStatement>>>()
})
.transpose()?,
})
}
fn convert_comparison(c: ast::Comparison) -> RoutingResult<Comparison> {
Ok(Comparison {
lhs: c.lhs,
comparison: convert_comparison_type(c.comparison),
value: convert_value(c.value)?,
metadata: c.metadata,
})
}
fn convert_comparison_type(ct: ast::ComparisonType) -> ComparisonType {
match ct {
ast::ComparisonType::Equal => ComparisonType::Equal,
ast::ComparisonType::NotEqual => ComparisonType::NotEqual,
ast::ComparisonType::LessThan => ComparisonType::LessThan,
ast::ComparisonType::LessThanEqual => ComparisonType::LessThanEqual,
ast::ComparisonType::GreaterThan => ComparisonType::GreaterThan,
ast::ComparisonType::GreaterThanEqual => ComparisonType::GreaterThanEqual,
}
}
fn convert_value(v: ast::ValueType) -> RoutingResult<ValueType> {
use ast::ValueType::*;
match v {
Number(n) => Ok(ValueType::Number(
n.get_amount_as_i64().try_into().unwrap_or_default(),
)),
EnumVariant(e) => Ok(ValueType::EnumVariant(e)),
MetadataVariant(m) => Ok(ValueType::MetadataVariant(MetadataValue {
key: m.key,
value: m.value,
})),
StrValue(s) => Ok(ValueType::StrValue(s)),
NumberArray(arr) => Ok(ValueType::NumberArray(
arr.into_iter()
.map(|n| n.get_amount_as_i64().try_into().unwrap_or_default())
.collect(),
)),
EnumVariantArray(arr) => Ok(ValueType::EnumVariantArray(arr)),
NumberComparisonArray(arr) => Ok(ValueType::NumberComparisonArray(
arr.into_iter()
.map(|nc| NumberComparison {
comparison_type: convert_comparison_type(nc.comparison_type),
number: nc.number.get_amount_as_i64().try_into().unwrap_or_default(),
})
.collect(),
)),
}
}
fn convert_output(sel: ConnectorSelection) -> Output {
match sel {
ConnectorSelection::Priority(choices) => {
Output::Priority(choices.into_iter().map(stringify_choice).collect())
}
ConnectorSelection::VolumeSplit(vs) => Output::VolumeSplit(
vs.into_iter()
.map(|v| VolumeSplit {
split: v.split,
output: stringify_choice(v.connector),
})
.collect(),
),
}
}
fn stringify_choice(c: RoutableConnectorChoice) -> ConnectorInfo {
ConnectorInfo::new(
c.connector.to_string(),
c.merchant_connector_id
.map(|mca_id| mca_id.get_string_repr().to_string()),
)
}
pub async fn select_routing_result<T>(
state: &SessionState,
business_profile: &business_profile::Profile,
hyperswitch_result: T,
de_result: T,
) -> T {
let routing_result_source: Option<api_routing::RoutingResultSource> = state
.store
.find_config_by_key(&format!(
"routing_result_source_{0}",
business_profile.get_id().get_string_repr()
))
.await
.map(|c| c.config.parse_enum("RoutingResultSource").ok())
.unwrap_or(None); //Ignore errors so that we can use the hyperswitch result as a fallback
if let Some(api_routing::RoutingResultSource::DecisionEngine) = routing_result_source {
logger::debug!(business_profile_id=?business_profile.get_id(), "Using Decision Engine routing result");
de_result
} else {
logger::debug!(business_profile_id=?business_profile.get_id(), "Using Hyperswitch routing result");
hyperswitch_result
}
}
pub trait DecisionEngineErrorsInterface {
fn get_error_message(&self) -> String;
fn get_error_code(&self) -> String;
fn get_error_data(&self) -> Option<String>;
}
#[derive(Debug)]
pub struct RoutingEventsWrapper<Req>
where
Req: Serialize + Clone,
{
pub tenant_id: id_type::TenantId,
pub request_id: Option<RequestId>,
pub payment_id: String,
pub profile_id: id_type::ProfileId,
pub merchant_id: id_type::MerchantId,
pub flow: String,
pub request: Option<Req>,
pub parse_response: bool,
pub log_event: bool,
pub routing_event: Option<routing_events::RoutingEvent>,
}
#[derive(Debug)]
pub enum EventResponseType<Res>
where
Res: Serialize + serde::de::DeserializeOwned + Clone,
{
Structured(Res),
String(String),
}
#[derive(Debug, Serialize)]
pub struct RoutingEventsResponse<Res>
where
Res: Serialize + serde::de::DeserializeOwned + Clone,
{
pub event: Option<routing_events::RoutingEvent>,
pub response: Option<Res>,
}
impl<Res> RoutingEventsResponse<Res>
where
Res: Serialize + serde::de::DeserializeOwned + Clone,
{
pub fn new(event: Option<routing_events::RoutingEvent>, response: Option<Res>) -> Self {
Self { event, response }
}
pub fn set_response(&mut self, response: Res) {
self.response = Some(response);
}
pub fn set_event(&mut self, event: routing_events::RoutingEvent) {
self.event = Some(event);
}
}
impl<Req> RoutingEventsWrapper<Req>
where
Req: Serialize + Clone,
{
#[allow(clippy::too_many_arguments)]
pub fn new(
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
payment_id: String,
profile_id: id_type::ProfileId,
merchant_id: id_type::MerchantId,
flow: String,
request: Option<Req>,
parse_response: bool,
log_event: bool,
) -> Self {
Self {
tenant_id,
request_id,
payment_id,
profile_id,
merchant_id,
flow,
request,
parse_response,
log_event,
routing_event: None,
}
}
pub fn construct_event_builder(
self,
url: String,
routing_engine: routing_events::RoutingEngine,
method: routing_events::ApiMethod,
) -> RoutingResult<Self> {
let mut wrapper = self;
let request = wrapper
.request
.clone()
.ok_or(errors::RoutingError::RoutingEventsError {
message: "Request body is missing".to_string(),
status_code: 400,
})?;
let serialized_request = serde_json::to_value(&request)
.change_context(errors::RoutingError::RoutingEventsError {
message: "Failed to serialize RoutingRequest".to_string(),
status_code: 500,
})
.attach_printable("Failed to serialize request body")?;
let routing_event = routing_events::RoutingEvent::new(
wrapper.tenant_id.clone(),
"".to_string(),
&wrapper.flow,
serialized_request,
url,
method,
wrapper.payment_id.clone(),
wrapper.profile_id.clone(),
wrapper.merchant_id.clone(),
wrapper.request_id,
routing_engine,
);
wrapper.set_routing_event(routing_event);
Ok(wrapper)
}
pub async fn trigger_event<Res, F, Fut>(
self,
state: &SessionState,
func: F,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
F: FnOnce() -> Fut + Send,
Res: Serialize + serde::de::DeserializeOwned + Clone,
Fut: futures::Future<Output = RoutingResult<Option<Res>>> + Send,
{
let mut routing_event =
self.routing_event
.ok_or(errors::RoutingError::RoutingEventsError {
message: "Routing event is missing".to_string(),
status_code: 500,
})?;
let mut response = RoutingEventsResponse::new(None, None);
let resp = func().await;
match resp {
Ok(ok_resp) => {
if let Some(resp) = ok_resp {
routing_event.set_response_body(&resp);
// routing_event
// .set_routable_connectors(ok_resp.get_routable_connectors().unwrap_or_default());
// routing_event.set_payment_connector(ok_resp.get_payment_connector());
routing_event.set_status_code(200);
response.set_response(resp.clone());
self.log_event
.then(|| state.event_handler().log_event(&routing_event));
}
}
Err(err) => {
// Need to figure out a generic way to log errors
routing_event
.set_error(serde_json::json!({"error": err.current_context().to_string()}));
match err.current_context() {
errors::RoutingError::RoutingEventsError { status_code, .. } => {
routing_event.set_status_code(*status_code);
}
_ => {
routing_event.set_status_code(500);
}
}
state.event_handler().log_event(&routing_event)
}
}
response.set_event(routing_event);
Ok(response)
}
pub fn set_log_event(&mut self, log_event: bool) {
self.log_event = log_event;
}
pub fn set_request_body(&mut self, request: Req) {
self.request = Some(request);
}
pub fn set_routing_event(&mut self, routing_event: routing_events::RoutingEvent) {
self.routing_event = Some(routing_event);
}
}
pub trait RoutingEventsInterface {
fn get_routable_connectors(&self) -> Option<Vec<RoutableConnectorChoice>>;
fn get_payment_connector(&self) -> Option<RoutableConnectorChoice>;
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalSuccessRateConfigEventRequest {
pub min_aggregates_size: Option<u32>,
pub default_success_rate: Option<f64>,
pub specificity_level: api_routing::SuccessRateSpecificityLevel,
pub exploration_percent: Option<f64>,
}
impl From<&api_routing::SuccessBasedRoutingConfigBody> for CalSuccessRateConfigEventRequest {
fn from(value: &api_routing::SuccessBasedRoutingConfigBody) -> Self {
Self {
min_aggregates_size: value.min_aggregates_size,
default_success_rate: value.default_success_rate,
specificity_level: value.specificity_level,
exploration_percent: value.exploration_percent,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalSuccessRateEventRequest {
pub id: String,
pub params: String,
pub labels: Vec<String>,
pub config: Option<CalSuccessRateConfigEventRequest>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct EliminationRoutingEventBucketConfig {
pub bucket_size: Option<u64>,
pub bucket_leak_interval_in_secs: Option<u64>,
}
impl From<&api_routing::EliminationAnalyserConfig> for EliminationRoutingEventBucketConfig {
fn from(value: &api_routing::EliminationAnalyserConfig) -> Self {
Self {
bucket_size: value.bucket_size,
bucket_leak_interval_in_secs: value.bucket_leak_interval_in_secs,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct EliminationRoutingEventRequest {
pub id: String,
pub params: String,
pub labels: Vec<String>,
pub config: Option<EliminationRoutingEventBucketConfig>,
}
/// API-1 types
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalContractScoreEventRequest {
pub id: String,
pub params: String,
pub labels: Vec<String>,
pub config: Option<api_routing::ContractBasedRoutingConfig>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct LabelWithScoreEventResponse {
pub score: f64,
pub label: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalSuccessRateEventResponse {
pub labels_with_score: Vec<LabelWithScoreEventResponse>,
pub routing_approach: RoutingApproach,
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
impl TryFrom<&ir_client::success_rate_client::CalSuccessRateResponse>
for CalSuccessRateEventResponse
{
type Error = errors::RoutingError;
fn try_from(
value: &ir_client::success_rate_client::CalSuccessRateResponse,
) -> Result<Self, Self::Error> {
Ok(Self {
labels_with_score: value
.labels_with_score
.iter()
.map(|l| LabelWithScoreEventResponse {
score: l.score,
label: l.label.clone(),
})
.collect(),
routing_approach: match value.routing_approach {
0 => RoutingApproach::Exploration,
1 => RoutingApproach::Exploitation,
_ => {
return Err(errors::RoutingError::GenericNotFoundError {
field: "unknown routing approach from dynamic routing service".to_string(),
})
}
},
})
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RoutingApproach {
Exploitation,
Exploration,
Elimination,
ContractBased,
StaticRouting,
Default,
}
impl RoutingApproach {
pub fn from_decision_engine_approach(approach: &str) -> Self {
match approach {
"SR_SELECTION_V3_ROUTING" => Self::Exploitation,
"SR_V3_HEDGING" => Self::Exploration,
_ => Self::Default,
}
}
}
impl From<RoutingApproach> for common_enums::RoutingApproach {
fn from(approach: RoutingApproach) -> Self {
match approach {
RoutingApproach::Exploitation => Self::SuccessRateExploitation,
RoutingApproach::Exploration => Self::SuccessRateExploration,
RoutingApproach::ContractBased => Self::ContractBasedRouting,
RoutingApproach::StaticRouting => Self::RuleBasedRouting,
_ => Self::DefaultFallback,
}
}
}
impl std::fmt::Display for RoutingApproach {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Exploitation => write!(f, "Exploitation"),
Self::Exploration => write!(f, "Exploration"),
Self::Elimination => write!(f, "Elimination"),
Self::ContractBased => write!(f, "ContractBased"),
Self::StaticRouting => write!(f, "StaticRouting"),
Self::Default => write!(f, "Default"),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct BucketInformationEventResponse {
pub is_eliminated: bool,
pub bucket_name: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct EliminationInformationEventResponse {
pub entity: Option<BucketInformationEventResponse>,
pub global: Option<BucketInformationEventResponse>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct LabelWithStatusEliminationEventResponse {
pub label: String,
pub elimination_information: Option<EliminationInformationEventResponse>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct EliminationEventResponse {
pub labels_with_status: Vec<LabelWithStatusEliminationEventResponse>,
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
impl From<&ir_client::elimination_based_client::EliminationResponse> for EliminationEventResponse {
fn from(value: &ir_client::elimination_based_client::EliminationResponse) -> Self {
Self {
labels_with_status: value
.labels_with_status
.iter()
.map(
|label_with_status| LabelWithStatusEliminationEventResponse {
label: label_with_status.label.clone(),
elimination_information: label_with_status
.elimination_information
.as_ref()
.map(|info| EliminationInformationEventResponse {
entity: info.entity.as_ref().map(|entity_info| {
BucketInformationEventResponse {
is_eliminated: entity_info.is_eliminated,
bucket_name: entity_info.bucket_name.clone(),
}
}),
global: info.global.as_ref().map(|global_info| {
BucketInformationEventResponse {
is_eliminated: global_info.is_eliminated,
bucket_name: global_info.bucket_name.clone(),
}
}),
}),
},
)
.collect(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct ScoreDataEventResponse {
pub score: f64,
pub label: String,
pub current_count: u64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalContractScoreEventResponse {
pub labels_with_score: Vec<ScoreDataEventResponse>,
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
impl From<&ir_client::contract_routing_client::CalContractScoreResponse>
for CalContractScoreEventResponse
{
fn from(value: &ir_client::contract_routing_client::CalContractScoreResponse) -> Self {
Self {
labels_with_score: value
.labels_with_score
.iter()
.map(|label_with_score| ScoreDataEventResponse {
score: label_with_score.score,
label: label_with_score.label.clone(),
current_count: label_with_score.current_count,
})
.collect(),
}
}
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalGlobalSuccessRateConfigEventRequest {
pub entity_min_aggregates_size: u32,
pub entity_default_success_rate: f64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalGlobalSuccessRateEventRequest {
pub entity_id: String,
pub entity_params: String,
pub entity_labels: Vec<String>,
pub global_labels: Vec<String>,
pub config: Option<CalGlobalSuccessRateConfigEventRequest>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct UpdateSuccessRateWindowConfig {
pub max_aggregates_size: Option<u32>,
pub current_block_threshold: Option<api_routing::CurrentBlockThreshold>,
}
impl From<&api_routing::SuccessBasedRoutingConfigBody> for UpdateSuccessRateWindowConfig {
fn from(value: &api_routing::SuccessBasedRoutingConfigBody) -> Self {
Self {
max_aggregates_size: value.max_aggregates_size,
current_block_threshold: value.current_block_threshold.clone(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct UpdateLabelWithStatusEventRequest {
pub label: String,
pub status: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct UpdateSuccessRateWindowEventRequest {
pub id: String,
pub params: String,
pub labels_with_status: Vec<UpdateLabelWithStatusEventRequest>,
pub config: Option<UpdateSuccessRateWindowConfig>,
pub global_labels_with_status: Vec<UpdateLabelWithStatusEventRequest>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct UpdateSuccessRateWindowEventResponse {
pub status: UpdationStatusEventResponse,
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
impl TryFrom<&ir_client::success_rate_client::UpdateSuccessRateWindowResponse>
for UpdateSuccessRateWindowEventResponse
{
type Error = errors::RoutingError;
fn try_from(
value: &ir_client::success_rate_client::UpdateSuccessRateWindowResponse,
) -> Result<Self, Self::Error> {
Ok(Self {
status: match value.status {
0 => UpdationStatusEventResponse::WindowUpdationSucceeded,
1 => UpdationStatusEventResponse::WindowUpdationFailed,
_ => {
return Err(errors::RoutingError::GenericNotFoundError {
field: "unknown updation status from dynamic routing service".to_string(),
})
}
},
})
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UpdationStatusEventResponse {
WindowUpdationSucceeded,
WindowUpdationFailed,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct LabelWithBucketNameEventRequest {
pub label: String,
pub bucket_name: String,
}
impl From<&api_routing::RoutableConnectorChoiceWithBucketName> for LabelWithBucketNameEventRequest {
fn from(value: &api_routing::RoutableConnectorChoiceWithBucketName) -> Self {
Self {
label: value.routable_connector_choice.to_string(),
bucket_name: value.bucket_name.clone(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct UpdateEliminationBucketEventRequest {
pub id: String,
pub params: String,
pub labels_with_bucket_name: Vec<LabelWithBucketNameEventRequest>,
pub config: Option<EliminationRoutingEventBucketConfig>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct UpdateEliminationBucketEventResponse {
pub status: EliminationUpdationStatusEventResponse,
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
impl TryFrom<&ir_client::elimination_based_client::UpdateEliminationBucketResponse>
for UpdateEliminationBucketEventResponse
{
type Error = errors::RoutingError;
fn try_from(
value: &ir_client::elimination_based_client::UpdateEliminationBucketResponse,
) -> Result<Self, Self::Error> {
Ok(Self {
status: match value.status {
0 => EliminationUpdationStatusEventResponse::BucketUpdationSucceeded,
1 => EliminationUpdationStatusEventResponse::BucketUpdationFailed,
_ => {
return Err(errors::RoutingError::GenericNotFoundError {
field: "unknown updation status from dynamic routing service".to_string(),
})
}
},
})
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EliminationUpdationStatusEventResponse {
BucketUpdationSucceeded,
BucketUpdationFailed,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct ContractLabelInformationEventRequest {
pub label: String,
pub target_count: u64,
pub target_time: u64,
pub current_count: u64,
}
impl From<&api_routing::LabelInformation> for ContractLabelInformationEventRequest {
fn from(value: &api_routing::LabelInformation) -> Self {
Self {
label: value.label.clone(),
target_count: value.target_count,
target_time: value.target_time,
current_count: 1,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct UpdateContractRequestEventRequest {
pub id: String,
pub params: String,
pub labels_information: Vec<ContractLabelInformationEventRequest>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct UpdateContractEventResponse {
pub status: ContractUpdationStatusEventResponse,
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
impl TryFrom<&ir_client::contract_routing_client::UpdateContractResponse>
for UpdateContractEventResponse
{
type Error = errors::RoutingError;
fn try_from(
value: &ir_client::contract_routing_client::UpdateContractResponse,
) -> Result<Self, Self::Error> {
Ok(Self {
status: match value.status {
0 => ContractUpdationStatusEventResponse::ContractUpdationSucceeded,
1 => ContractUpdationStatusEventResponse::ContractUpdationFailed,
_ => {
return Err(errors::RoutingError::GenericNotFoundError {
field: "unknown updation status from dynamic routing service".to_string(),
})
}
},
})
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContractUpdationStatusEventResponse {
ContractUpdationSucceeded,
ContractUpdationFailed,
}
| {
"crate": "router",
"file": "crates/router/src/core/payments/routing/utils.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 9,
"num_structs": 38,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-4864131862672667992 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/fraud_check/types.rs
// Contains: 12 structs, 0 enums
use api_models::{
enums as api_enums,
enums::{PaymentMethod, PaymentMethodType},
payments::Amount,
refunds::RefundResponse,
};
use common_enums::FrmSuggestion;
use common_utils::pii::SecretSerdeValue;
use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
pub use hyperswitch_domain_models::{
router_request_types::fraud_check::{
Address, Destination, FrmFulfillmentRequest, FulfillmentStatus, Fulfillments, Product,
},
types::OrderDetailsWithAmount,
};
use masking::Serialize;
use serde::Deserialize;
use utoipa::ToSchema;
use super::operation::BoxedFraudCheckOperation;
use crate::types::{
domain::MerchantAccount,
storage::{enums as storage_enums, fraud_check::FraudCheck},
PaymentAddress,
};
#[derive(Clone, Default, Debug)]
pub struct PaymentIntentCore {
pub payment_id: common_utils::id_type::PaymentId,
}
#[derive(Clone, Debug)]
pub struct PaymentAttemptCore {
pub attempt_id: String,
pub payment_details: Option<PaymentDetails>,
pub amount: Amount,
}
#[derive(Clone, Debug, Serialize)]
pub struct PaymentDetails {
pub amount: i64,
pub currency: Option<storage_enums::Currency>,
pub payment_method: Option<PaymentMethod>,
pub payment_method_type: Option<PaymentMethodType>,
pub refund_transaction_id: Option<String>,
}
#[derive(Clone, Default, Debug)]
pub struct FrmMerchantAccount {
pub merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Clone, Debug)]
pub struct FrmData {
pub payment_intent: PaymentIntent,
pub payment_attempt: PaymentAttempt,
pub merchant_account: MerchantAccount,
pub fraud_check: FraudCheck,
pub address: PaymentAddress,
pub connector_details: ConnectorDetailsCore,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub refund: Option<RefundResponse>,
pub frm_metadata: Option<SecretSerdeValue>,
}
#[derive(Debug)]
pub struct FrmInfo<F, D> {
pub fraud_check_operation: BoxedFraudCheckOperation<F, D>,
pub frm_data: Option<FrmData>,
pub suggested_action: Option<FrmSuggestion>,
}
#[derive(Clone, Debug)]
pub struct ConnectorDetailsCore {
pub connector_name: String,
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Clone)]
pub struct PaymentToFrmData {
pub amount: Amount,
pub payment_intent: PaymentIntent,
pub payment_attempt: PaymentAttempt,
pub merchant_account: MerchantAccount,
pub address: PaymentAddress,
pub connector_details: ConnectorDetailsCore,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub frm_metadata: Option<SecretSerdeValue>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrmConfigsObject {
pub frm_enabled_pm: Option<PaymentMethod>,
pub frm_enabled_gateway: Option<api_models::enums::Connector>,
pub frm_preferred_flow_type: api_enums::FrmPreferredFlowTypes,
}
#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct FrmFulfillmentSignifydApiRequest {
///unique order_id for the order_details in the transaction
#[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
pub order_id: String,
///denotes the status of the fulfillment... can be one of PARTIAL, COMPLETE, REPLACEMENT, CANCELED
#[schema(value_type = Option<FulfillmentStatus>, example = "COMPLETE")]
pub fulfillment_status: Option<FulfillmentStatus>,
///contains details of the fulfillment
#[schema(value_type = Vec<Fulfillments>)]
pub fulfillments: Vec<Fulfillments>,
}
#[derive(Debug, ToSchema, Clone, Serialize)]
pub struct FrmFulfillmentResponse {
///unique order_id for the transaction
#[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
pub order_id: String,
///shipment_ids used in the fulfillment overall...also data from previous fulfillments for the same transactions/order is sent
#[schema(example = r#"["ship_101", "ship_102"]"#)]
pub shipment_ids: Vec<String>,
}
#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct FrmFulfillmentSignifydApiResponse {
///unique order_id for the transaction
#[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
pub order_id: String,
///shipment_ids used in the fulfillment overall...also data from previous fulfillments for the same transactions/order is sent
#[schema(example = r#"["ship_101","ship_102"]"#)]
pub shipment_ids: Vec<String>,
}
pub const CANCEL_INITIATED: &str = "Cancel Initiated with the processor";
| {
"crate": "router",
"file": "crates/router/src/core/fraud_check/types.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 12,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_3679705506937897890 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/fraud_check/operation/fraud_check_pre.rs
// Contains: 1 structs, 0 enums
use async_trait::async_trait;
use common_enums::FrmSuggestion;
use common_utils::ext_traits::Encode;
use diesel_models::enums::FraudCheckLastStep;
use router_env::{instrument, tracing};
use uuid::Uuid;
use super::{Domain, FraudCheckOperation, GetTracker, UpdateTracker};
use crate::{
core::{
errors::RouterResult,
fraud_check::{
self as frm_core,
types::{FrmData, PaymentDetails, PaymentToFrmData},
ConnectorDetailsCore,
},
payments,
},
errors,
routes::app::ReqState,
types::{
api::fraud_check as frm_api,
domain,
fraud_check::{
FraudCheckCheckoutData, FraudCheckResponseData, FraudCheckTransactionData, FrmRequest,
FrmResponse, FrmRouterData,
},
storage::{
enums::{FraudCheckStatus, FraudCheckType},
fraud_check::{FraudCheckNew, FraudCheckUpdate},
},
ResponseId,
},
SessionState,
};
#[derive(Debug, Clone, Copy)]
pub struct FraudCheckPre;
impl<F, D> FraudCheckOperation<F, D> for &FraudCheckPre
where
F: Clone + Send,
D: payments::OperationSessionGetters<F> + Send + Sync + Clone,
{
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> {
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> {
Ok(*self)
}
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> {
Ok(*self)
}
}
impl<F, D> FraudCheckOperation<F, D> for FraudCheckPre
where
F: Clone + Send,
D: payments::OperationSessionGetters<F> + Send + Sync + Clone,
{
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> {
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> {
Ok(self)
}
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> {
Ok(self)
}
}
#[async_trait]
impl GetTracker<PaymentToFrmData> for FraudCheckPre {
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_data: PaymentToFrmData,
frm_connector_details: ConnectorDetailsCore,
) -> RouterResult<Option<FrmData>> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_data: PaymentToFrmData,
frm_connector_details: ConnectorDetailsCore,
) -> RouterResult<Option<FrmData>> {
let db = &*state.store;
let payment_details: Option<serde_json::Value> = PaymentDetails::from(payment_data.clone())
.encode_to_value()
.ok();
let existing_fraud_check = db
.find_fraud_check_by_payment_id_if_present(
payment_data.payment_intent.get_id().to_owned(),
payment_data.merchant_account.get_id().clone(),
)
.await
.ok();
let fraud_check = match existing_fraud_check {
Some(Some(fraud_check)) => Ok(fraud_check),
_ => {
db.insert_fraud_check_response(FraudCheckNew {
frm_id: Uuid::new_v4().simple().to_string(),
payment_id: payment_data.payment_intent.get_id().to_owned(),
merchant_id: payment_data.merchant_account.get_id().clone(),
attempt_id: payment_data.payment_attempt.attempt_id.clone(),
created_at: common_utils::date_time::now(),
frm_name: frm_connector_details.connector_name,
frm_transaction_id: None,
frm_transaction_type: FraudCheckType::PreFrm,
frm_status: FraudCheckStatus::Pending,
frm_score: None,
frm_reason: None,
frm_error: None,
payment_details,
metadata: None,
modified_at: common_utils::date_time::now(),
last_step: FraudCheckLastStep::Processing,
payment_capture_method: payment_data.payment_attempt.capture_method,
})
.await
}
};
match fraud_check {
Ok(fraud_check_value) => {
let frm_data = FrmData {
payment_intent: payment_data.payment_intent,
payment_attempt: payment_data.payment_attempt,
merchant_account: payment_data.merchant_account,
address: payment_data.address,
fraud_check: fraud_check_value,
connector_details: payment_data.connector_details,
order_details: payment_data.order_details,
refund: None,
frm_metadata: payment_data.frm_metadata,
};
Ok(Some(frm_data))
}
Err(error) => {
router_env::logger::error!("inserting into fraud_check table failed {error:?}");
Ok(None)
}
}
}
}
#[async_trait]
impl<F, D> Domain<F, D> for FraudCheckPre
where
F: Clone + Send,
D: payments::OperationSessionGetters<F> + Send + Sync + Clone,
{
#[cfg(feature = "v2")]
#[instrument(skip_all)]
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>> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
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>> {
let router_data = frm_core::call_frm_service::<F, frm_api::Transaction, _, D>(
state,
payment_data,
&mut frm_data.to_owned(),
merchant_context,
customer,
)
.await?;
frm_data.fraud_check.last_step = FraudCheckLastStep::TransactionOrRecordRefund;
Ok(Some(FrmRouterData {
merchant_id: router_data.merchant_id,
connector: router_data.connector,
payment_id: router_data.payment_id.clone(),
attempt_id: router_data.attempt_id,
request: FrmRequest::Transaction(FraudCheckTransactionData {
amount: router_data.request.amount,
order_details: router_data.request.order_details,
currency: router_data.request.currency,
payment_method: Some(router_data.payment_method),
error_code: router_data.request.error_code,
error_message: router_data.request.error_message,
connector_transaction_id: router_data.request.connector_transaction_id,
connector: router_data.request.connector,
}),
response: FrmResponse::Transaction(router_data.response),
}))
}
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> {
let router_data = frm_core::call_frm_service::<F, frm_api::Checkout, _, D>(
state,
payment_data,
&mut frm_data.to_owned(),
merchant_context,
customer,
)
.await?;
frm_data.fraud_check.last_step = FraudCheckLastStep::CheckoutOrSale;
Ok(FrmRouterData {
merchant_id: router_data.merchant_id,
connector: router_data.connector,
payment_id: router_data.payment_id.clone(),
attempt_id: router_data.attempt_id,
request: FrmRequest::Checkout(Box::new(FraudCheckCheckoutData {
amount: router_data.request.amount,
order_details: router_data.request.order_details,
currency: router_data.request.currency,
browser_info: router_data.request.browser_info,
payment_method_data: router_data.request.payment_method_data,
email: router_data.request.email,
gateway: router_data.request.gateway,
})),
response: FrmResponse::Checkout(router_data.response),
})
}
}
#[async_trait]
impl<F, D> UpdateTracker<FrmData, F, D> for FraudCheckPre
where
F: Clone + Send,
D: payments::OperationSessionGetters<F> + Send + Sync + Clone,
{
async fn update_tracker<'b>(
&'b self,
state: &SessionState,
_key_store: &domain::MerchantKeyStore,
mut frm_data: FrmData,
payment_data: &mut D,
_frm_suggestion: Option<FrmSuggestion>,
frm_router_data: FrmRouterData,
) -> RouterResult<FrmData> {
let frm_check_update = match frm_router_data.response {
FrmResponse::Checkout(response) => match response {
Err(err) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(err.message)),
}),
Ok(payments_response) => match payments_response {
FraudCheckResponseData::TransactionResponse {
resource_id,
connector_metadata,
status,
reason,
score,
} => {
let connector_transaction_id = match resource_id {
ResponseId::NoResponseId => None,
ResponseId::ConnectorTransactionId(id) => Some(id),
ResponseId::EncodedData(id) => Some(id),
};
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status: status,
frm_transaction_id: connector_transaction_id,
frm_reason: reason,
frm_score: score,
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
payment_capture_method: frm_data.fraud_check.payment_capture_method,
};
Some(fraud_check_update)
}
FraudCheckResponseData::FulfillmentResponse {
order_id: _,
shipment_ids: _,
} => None,
FraudCheckResponseData::RecordReturnResponse {
resource_id: _,
connector_metadata: _,
return_id: _,
} => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Record Return Response response in current Checkout flow"
.to_string(),
)),
}),
},
},
FrmResponse::Transaction(response) => match response {
Err(err) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(err.message)),
}),
Ok(payments_response) => match payments_response {
FraudCheckResponseData::TransactionResponse {
resource_id,
connector_metadata,
status,
reason,
score,
} => {
let connector_transaction_id = match resource_id {
ResponseId::NoResponseId => None,
ResponseId::ConnectorTransactionId(id) => Some(id),
ResponseId::EncodedData(id) => Some(id),
};
let frm_status = payment_data
.get_frm_message()
.as_ref()
.map_or(status, |frm_data| frm_data.frm_status);
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status,
frm_transaction_id: connector_transaction_id,
frm_reason: reason,
frm_score: score,
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
payment_capture_method: None,
};
Some(fraud_check_update)
}
FraudCheckResponseData::FulfillmentResponse {
order_id: _,
shipment_ids: _,
} => None,
FraudCheckResponseData::RecordReturnResponse {
resource_id: _,
connector_metadata: _,
return_id: _,
} => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Record Return Response response in current Checkout flow"
.to_string(),
)),
}),
},
},
FrmResponse::Sale(_response)
| FrmResponse::Fulfillment(_response)
| FrmResponse::RecordReturn(_response) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Pre(Sale) flow response in current post flow".to_string(),
)),
}),
};
let db = &*state.store;
frm_data.fraud_check = match frm_check_update {
Some(fraud_check_update) => db
.update_fraud_check_response_with_attempt_id(
frm_data.clone().fraud_check,
fraud_check_update,
)
.await
.map_err(|error| error.change_context(errors::ApiErrorResponse::PaymentNotFound))?,
None => frm_data.clone().fraud_check,
};
Ok(frm_data)
}
}
| {
"crate": "router",
"file": "crates/router/src/core/fraud_check/operation/fraud_check_pre.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-8355942472241767850 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/fraud_check/operation/fraud_check_post.rs
// Contains: 1 structs, 0 enums
use async_trait::async_trait;
use common_enums::{CaptureMethod, FrmSuggestion};
use common_utils::ext_traits::Encode;
use hyperswitch_domain_models::payments::{
payment_attempt::PaymentAttemptUpdate, payment_intent::PaymentIntentUpdate, HeaderPayload,
};
use router_env::{instrument, logger, tracing};
use super::{Domain, FraudCheckOperation, GetTracker, UpdateTracker};
use crate::{
consts,
core::{
errors::{RouterResult, StorageErrorExt},
fraud_check::{
self as frm_core,
types::{FrmData, PaymentDetails, PaymentToFrmData, CANCEL_INITIATED},
ConnectorDetailsCore, FrmConfigsObject,
},
payments,
},
errors,
routes::app::ReqState,
services::{self, api},
types::{
api::{
enums::{AttemptStatus, IntentStatus},
fraud_check as frm_api, payments as payment_types, Capture, Void,
},
domain,
fraud_check::{
FraudCheckResponseData, FraudCheckSaleData, FrmRequest, FrmResponse, FrmRouterData,
},
storage::{
enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType, MerchantDecision},
fraud_check::{FraudCheckNew, FraudCheckUpdate},
},
ResponseId,
},
utils, SessionState,
};
#[derive(Debug, Clone, Copy)]
pub struct FraudCheckPost;
impl<F, D> FraudCheckOperation<F, D> for &FraudCheckPost
where
F: Clone + Send,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> {
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> {
Ok(*self)
}
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> {
Ok(*self)
}
}
impl<F, D> FraudCheckOperation<F, D> for FraudCheckPost
where
F: Clone + Send,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> {
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> {
Ok(self)
}
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> {
Ok(self)
}
}
#[async_trait]
impl GetTracker<PaymentToFrmData> for FraudCheckPost {
#[cfg(feature = "v2")]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_data: PaymentToFrmData,
frm_connector_details: ConnectorDetailsCore,
) -> RouterResult<Option<FrmData>> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_data: PaymentToFrmData,
frm_connector_details: ConnectorDetailsCore,
) -> RouterResult<Option<FrmData>> {
let db = &*state.store;
let payment_details: Option<serde_json::Value> = PaymentDetails::from(payment_data.clone())
.encode_to_value()
.ok();
let existing_fraud_check = db
.find_fraud_check_by_payment_id_if_present(
payment_data.payment_intent.get_id().to_owned(),
payment_data.merchant_account.get_id().clone(),
)
.await
.ok();
let fraud_check = match existing_fraud_check {
Some(Some(fraud_check)) => Ok(fraud_check),
_ => {
db.insert_fraud_check_response(FraudCheckNew {
frm_id: utils::generate_id(consts::ID_LENGTH, "frm"),
payment_id: payment_data.payment_intent.get_id().to_owned(),
merchant_id: payment_data.merchant_account.get_id().clone(),
attempt_id: payment_data.payment_attempt.attempt_id.clone(),
created_at: common_utils::date_time::now(),
frm_name: frm_connector_details.connector_name,
frm_transaction_id: None,
frm_transaction_type: FraudCheckType::PostFrm,
frm_status: FraudCheckStatus::Pending,
frm_score: None,
frm_reason: None,
frm_error: None,
payment_details,
metadata: None,
modified_at: common_utils::date_time::now(),
last_step: FraudCheckLastStep::Processing,
payment_capture_method: payment_data.payment_attempt.capture_method,
})
.await
}
};
match fraud_check {
Ok(fraud_check_value) => {
let frm_data = FrmData {
payment_intent: payment_data.payment_intent,
payment_attempt: payment_data.payment_attempt,
merchant_account: payment_data.merchant_account,
address: payment_data.address,
fraud_check: fraud_check_value,
connector_details: payment_data.connector_details,
order_details: payment_data.order_details,
refund: None,
frm_metadata: payment_data.frm_metadata,
};
Ok(Some(frm_data))
}
Err(error) => {
router_env::logger::error!("inserting into fraud_check table failed {error:?}");
Ok(None)
}
}
}
}
#[async_trait]
impl<F, D> Domain<F, D> for FraudCheckPost
where
F: Clone + Send,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
#[instrument(skip_all)]
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>> {
if frm_data.fraud_check.last_step != FraudCheckLastStep::Processing {
logger::debug!("post_flow::Sale Skipped");
return Ok(None);
}
let router_data = frm_core::call_frm_service::<F, frm_api::Sale, _, D>(
state,
payment_data,
&mut frm_data.to_owned(),
merchant_context,
customer,
)
.await?;
frm_data.fraud_check.last_step = FraudCheckLastStep::CheckoutOrSale;
Ok(Some(FrmRouterData {
merchant_id: router_data.merchant_id,
connector: router_data.connector,
payment_id: router_data.payment_id.clone(),
attempt_id: router_data.attempt_id,
request: FrmRequest::Sale(FraudCheckSaleData {
amount: router_data.request.amount,
order_details: router_data.request.order_details,
currency: router_data.request.currency,
email: router_data.request.email,
}),
response: FrmResponse::Sale(router_data.response),
}))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
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>> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
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>> {
if matches!(frm_data.fraud_check.frm_status, FraudCheckStatus::Fraud)
&& matches!(
frm_data.fraud_check.last_step,
FraudCheckLastStep::CheckoutOrSale
)
{
*frm_suggestion = Some(FrmSuggestion::FrmCancelTransaction);
let cancel_req = api_models::payments::PaymentsCancelRequest {
payment_id: frm_data.payment_intent.get_id().to_owned(),
cancellation_reason: frm_data.fraud_check.frm_error.clone(),
merchant_connector_details: None,
};
let cancel_res = Box::pin(payments::payments_core::<
Void,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<Void>,
>(
state.clone(),
req_state.clone(),
merchant_context.clone(),
None,
payments::PaymentCancel,
cancel_req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
))
.await?;
logger::debug!("payment_id : {:?} has been cancelled since it has been found fraudulent by configured frm connector",payment_data.get_payment_attempt().payment_id);
if let services::ApplicationResponse::JsonWithHeaders((payments_response, _)) =
cancel_res
{
payment_data.set_payment_intent_status(payments_response.status);
}
let _router_data = frm_core::call_frm_service::<F, frm_api::RecordReturn, _, D>(
state,
payment_data,
&mut frm_data.to_owned(),
merchant_context,
customer,
)
.await?;
frm_data.fraud_check.last_step = FraudCheckLastStep::TransactionOrRecordRefund;
} else if matches!(
frm_data.fraud_check.frm_status,
FraudCheckStatus::ManualReview
) {
*frm_suggestion = Some(FrmSuggestion::FrmManualReview);
} else if matches!(frm_data.fraud_check.frm_status, FraudCheckStatus::Legit)
&& matches!(
frm_data.fraud_check.payment_capture_method,
Some(CaptureMethod::Automatic) | Some(CaptureMethod::SequentialAutomatic)
)
{
let capture_request = api_models::payments::PaymentsCaptureRequest {
payment_id: frm_data.payment_intent.get_id().to_owned(),
merchant_id: None,
amount_to_capture: None,
refund_uncaptured_amount: None,
statement_descriptor_suffix: None,
statement_descriptor_prefix: None,
merchant_connector_details: None,
};
let capture_response = Box::pin(payments::payments_core::<
Capture,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<Capture>,
>(
state.clone(),
req_state.clone(),
merchant_context.clone(),
None,
payments::PaymentCapture,
capture_request,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
))
.await?;
logger::debug!("payment_id : {:?} has been captured since it has been found legit by configured frm connector",payment_data.get_payment_attempt().payment_id);
if let services::ApplicationResponse::JsonWithHeaders((payments_response, _)) =
capture_response
{
payment_data.set_payment_intent_status(payments_response.status);
}
};
return Ok(Some(frm_data.to_owned()));
}
#[instrument(skip_all)]
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> {
let router_data = frm_core::call_frm_service::<F, frm_api::Sale, _, D>(
state,
payment_data,
&mut frm_data.to_owned(),
merchant_context,
customer,
)
.await?;
Ok(FrmRouterData {
merchant_id: router_data.merchant_id,
connector: router_data.connector,
payment_id: router_data.payment_id,
attempt_id: router_data.attempt_id,
request: FrmRequest::Sale(FraudCheckSaleData {
amount: router_data.request.amount,
order_details: router_data.request.order_details,
currency: router_data.request.currency,
email: router_data.request.email,
}),
response: FrmResponse::Sale(router_data.response),
})
}
}
#[async_trait]
impl<F, D> UpdateTracker<FrmData, F, D> for FraudCheckPost
where
F: Clone + Send,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
#[cfg(feature = "v2")]
async fn update_tracker<'b>(
&'b self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
mut frm_data: FrmData,
payment_data: &mut D,
frm_suggestion: Option<FrmSuggestion>,
frm_router_data: FrmRouterData,
) -> RouterResult<FrmData> {
todo!()
}
#[cfg(feature = "v1")]
async fn update_tracker<'b>(
&'b self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
mut frm_data: FrmData,
payment_data: &mut D,
frm_suggestion: Option<FrmSuggestion>,
frm_router_data: FrmRouterData,
) -> RouterResult<FrmData> {
let db = &*state.store;
let key_manager_state = &state.into();
let frm_check_update = match frm_router_data.response {
FrmResponse::Sale(response) => match response {
Err(err) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(err.message)),
}),
Ok(payments_response) => match payments_response {
FraudCheckResponseData::TransactionResponse {
resource_id,
connector_metadata,
status,
reason,
score,
} => {
let connector_transaction_id = match resource_id {
ResponseId::NoResponseId => None,
ResponseId::ConnectorTransactionId(id) => Some(id),
ResponseId::EncodedData(id) => Some(id),
};
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status: status,
frm_transaction_id: connector_transaction_id,
frm_reason: reason,
frm_score: score,
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
payment_capture_method: frm_data.fraud_check.payment_capture_method,
};
Some(fraud_check_update)
},
FraudCheckResponseData::RecordReturnResponse { resource_id: _, connector_metadata: _, return_id: _ } => {
Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Record Return Response response in current Sale flow".to_string(),
)),
})
}
FraudCheckResponseData::FulfillmentResponse {
order_id: _,
shipment_ids: _,
} => None,
},
},
FrmResponse::Fulfillment(response) => match response {
Err(err) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(err.message)),
}),
Ok(payments_response) => match payments_response {
FraudCheckResponseData::TransactionResponse {
resource_id,
connector_metadata,
status,
reason,
score,
} => {
let connector_transaction_id = match resource_id {
ResponseId::NoResponseId => None,
ResponseId::ConnectorTransactionId(id) => Some(id),
ResponseId::EncodedData(id) => Some(id),
};
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status: status,
frm_transaction_id: connector_transaction_id,
frm_reason: reason,
frm_score: score,
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
payment_capture_method: frm_data.fraud_check.payment_capture_method,
};
Some(fraud_check_update)
}
FraudCheckResponseData::FulfillmentResponse {
order_id: _,
shipment_ids: _,
} => None,
FraudCheckResponseData::RecordReturnResponse { resource_id: _, connector_metadata: _, return_id: _ } => None,
},
},
FrmResponse::RecordReturn(response) => match response {
Err(err) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(err.message)),
}),
Ok(payments_response) => match payments_response {
FraudCheckResponseData::TransactionResponse {
resource_id: _,
connector_metadata: _,
status: _,
reason: _,
score: _,
} => {
Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Transaction Response response in current Record Return flow".to_string(),
)),
})
},
FraudCheckResponseData::FulfillmentResponse {order_id: _, shipment_ids: _ } => {
None
},
FraudCheckResponseData::RecordReturnResponse { resource_id, connector_metadata, return_id: _ } => {
let connector_transaction_id = match resource_id {
ResponseId::NoResponseId => None,
ResponseId::ConnectorTransactionId(id) => Some(id),
ResponseId::EncodedData(id) => Some(id),
};
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status: frm_data.fraud_check.frm_status,
frm_transaction_id: connector_transaction_id,
frm_reason: frm_data.fraud_check.frm_reason.clone(),
frm_score: frm_data.fraud_check.frm_score,
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
payment_capture_method: frm_data.fraud_check.payment_capture_method,
};
Some(fraud_check_update)
}
},
},
FrmResponse::Checkout(_) | FrmResponse::Transaction(_) => {
Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Pre(Sale) flow response in current post flow".to_string(),
)),
})
}
};
if let Some(frm_suggestion) = frm_suggestion {
let (payment_attempt_status, payment_intent_status, merchant_decision, error_message) =
match frm_suggestion {
FrmSuggestion::FrmCancelTransaction => (
AttemptStatus::Failure,
IntentStatus::Failed,
Some(MerchantDecision::Rejected.to_string()),
Some(Some(CANCEL_INITIATED.to_string())),
),
FrmSuggestion::FrmManualReview => (
AttemptStatus::Unresolved,
IntentStatus::RequiresMerchantAction,
None,
None,
),
FrmSuggestion::FrmAuthorizeTransaction => (
AttemptStatus::Authorized,
IntentStatus::RequiresCapture,
None,
None,
),
};
let payment_attempt_update = PaymentAttemptUpdate::RejectUpdate {
status: payment_attempt_status,
error_code: Some(Some(frm_data.fraud_check.frm_status.to_string())),
error_message,
updated_by: frm_data.merchant_account.storage_scheme.to_string(),
};
#[cfg(feature = "v1")]
let payment_attempt = db
.update_payment_attempt_with_attempt_id(
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
frm_data.merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
#[cfg(feature = "v2")]
let payment_attempt = db
.update_payment_attempt_with_attempt_id(
key_manager_state,
key_store,
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
frm_data.merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.set_payment_attempt(payment_attempt);
let payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.get_payment_intent().clone(),
PaymentIntentUpdate::RejectUpdate {
status: payment_intent_status,
merchant_decision,
updated_by: frm_data.merchant_account.storage_scheme.to_string(),
},
key_store,
frm_data.merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.set_payment_intent(payment_intent);
}
frm_data.fraud_check = match frm_check_update {
Some(fraud_check_update) => db
.update_fraud_check_response_with_attempt_id(
frm_data.fraud_check.clone(),
fraud_check_update,
)
.await
.map_err(|error| error.change_context(errors::ApiErrorResponse::PaymentNotFound))?,
None => frm_data.fraud_check.clone(),
};
Ok(frm_data)
}
}
| {
"crate": "router",
"file": "crates/router/src/core/fraud_check/operation/fraud_check_post.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-4485638564191628157 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/proxy/utils.rs
// Contains: 1 structs, 0 enums
use api_models::{payment_methods::PaymentMethodId, proxy as proxy_api_models};
use common_utils::{
ext_traits::{Encode, OptionExt},
id_type,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::payment_methods;
use masking::Mask;
use serde_json::Value;
use x509_parser::nom::{
bytes::complete::{tag, take_while1},
character::complete::{char, multispace0},
sequence::{delimited, preceded, terminated},
IResult,
};
use crate::{
core::{
errors::{self, RouterResult},
payment_methods::vault,
},
routes::SessionState,
types::{domain, payment_methods as pm_types},
};
pub struct ProxyRequestWrapper(pub proxy_api_models::ProxyRequest);
pub enum ProxyRecord {
PaymentMethodRecord(Box<domain::PaymentMethod>),
TokenizationRecord(Box<domain::Tokenization>),
}
impl ProxyRequestWrapper {
pub async fn get_proxy_record(
&self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> RouterResult<ProxyRecord> {
let token = &self.0.token;
match self.0.token_type {
proxy_api_models::TokenType::PaymentMethodId => {
let pm_id = PaymentMethodId {
payment_method_id: token.clone(),
};
let pm_id =
id_type::GlobalPaymentMethodId::generate_from_string(pm_id.payment_method_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodId")?;
let payment_method_record = state
.store
.find_payment_method(&((state).into()), key_store, &pm_id, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)?;
Ok(ProxyRecord::PaymentMethodRecord(Box::new(
payment_method_record,
)))
}
proxy_api_models::TokenType::TokenizationId => {
let token_id = id_type::GlobalTokenId::from_string(token.clone().as_str())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Error while coneverting from string to GlobalTokenId type",
)?;
let db = state.store.as_ref();
let key_manager_state = &(state).into();
let tokenization_record = db
.get_entity_id_vault_id_by_token_id(&token_id, key_store, key_manager_state)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while fetching tokenization record from vault")?;
Ok(ProxyRecord::TokenizationRecord(Box::new(
tokenization_record,
)))
}
}
}
pub fn get_headers(&self) -> Vec<(String, masking::Maskable<String>)> {
self.0
.headers
.as_map()
.iter()
.map(|(key, value)| (key.clone(), value.clone().into_masked()))
.collect()
}
pub fn get_destination_url(&self) -> &str {
self.0.destination_url.as_str()
}
pub fn get_method(&self) -> common_utils::request::Method {
self.0.method
}
}
impl ProxyRecord {
fn get_vault_id(&self) -> RouterResult<payment_methods::VaultId> {
match self {
Self::PaymentMethodRecord(payment_method) => payment_method
.locker_id
.clone()
.get_required_value("vault_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Locker id not present in Payment Method Entry"),
Self::TokenizationRecord(tokenization_record) => Ok(
payment_methods::VaultId::generate(tokenization_record.locker_id.clone()),
),
}
}
fn get_customer_id(&self) -> id_type::GlobalCustomerId {
match self {
Self::PaymentMethodRecord(payment_method) => payment_method.customer_id.clone(),
Self::TokenizationRecord(tokenization_record) => {
tokenization_record.customer_id.clone()
}
}
}
pub async fn get_vault_data(
&self,
state: &SessionState,
merchant_context: domain::MerchantContext,
) -> RouterResult<Value> {
match self {
Self::PaymentMethodRecord(_) => {
let vault_resp = vault::retrieve_payment_method_from_vault_internal(
state,
&merchant_context,
&self.get_vault_id()?,
&self.get_customer_id(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while fetching data from vault")?;
Ok(vault_resp
.data
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize vault data")?)
}
Self::TokenizationRecord(_) => {
let vault_request = pm_types::VaultRetrieveRequest {
entity_id: self.get_customer_id(),
vault_id: self.get_vault_id()?,
};
let vault_data = vault::retrieve_value_from_vault(state, vault_request)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve vault data")?;
Ok(vault_data.get("data").cloned().unwrap_or(Value::Null))
}
}
}
}
#[derive(Debug)]
pub struct TokenReference {
pub field: String,
}
pub fn parse_token(input: &str) -> IResult<&str, TokenReference> {
let (input, field) = delimited(
tag("{{"),
preceded(
multispace0,
preceded(
char('$'),
terminated(
take_while1(|c: char| c.is_alphanumeric() || c == '_'),
multispace0,
),
),
),
tag("}}"),
)(input)?;
Ok((
input,
TokenReference {
field: field.to_string(),
},
))
}
pub fn contains_token(s: &str) -> bool {
s.contains("{{") && s.contains("$") && s.contains("}}")
}
| {
"crate": "router",
"file": "crates/router/src/core/proxy/utils.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-8450355510689428781 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/mandate/helpers.rs
// Contains: 1 structs, 0 enums
use api_models::payments as api_payments;
use common_enums::enums;
use common_types::payments as common_payments_types;
use common_utils::errors::CustomResult;
use diesel_models::Mandate;
use error_stack::ResultExt;
use hyperswitch_domain_models::mandates::MandateData;
use crate::{
core::{errors, payments},
routes::SessionState,
types::{api, domain},
};
#[cfg(feature = "v1")]
pub async fn get_profile_id_for_mandate(
state: &SessionState,
merchant_context: &domain::MerchantContext,
mandate: Mandate,
) -> CustomResult<common_utils::id_type::ProfileId, errors::ApiErrorResponse> {
let profile_id = if let Some(ref payment_id) = mandate.original_payment_id {
let pi = state
.store
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let profile_id =
pi.profile_id
.clone()
.ok_or(errors::ApiErrorResponse::ProfileNotFound {
id: pi
.profile_id
.map(|profile_id| profile_id.get_string_repr().to_owned())
.unwrap_or_else(|| "Profile id is Null".to_string()),
})?;
Ok(profile_id)
} else {
Err(errors::ApiErrorResponse::PaymentNotFound)
}?;
Ok(profile_id)
}
pub fn get_mandate_type(
mandate_data: Option<api_payments::MandateData>,
off_session: Option<bool>,
setup_future_usage: Option<enums::FutureUsage>,
customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
token: Option<String>,
payment_method: Option<enums::PaymentMethod>,
) -> CustomResult<Option<api::MandateTransactionType>, errors::ValidationError> {
match (
mandate_data.clone(),
off_session,
setup_future_usage,
customer_acceptance.or(mandate_data.and_then(|m_data| m_data.customer_acceptance)),
token,
payment_method,
) {
(Some(_), Some(_), Some(enums::FutureUsage::OffSession), Some(_), Some(_), _) => {
Err(errors::ValidationError::InvalidValue {
message: "Expected one out of recurring_details and mandate_data but got both"
.to_string(),
}
.into())
}
(_, _, Some(enums::FutureUsage::OffSession), Some(_), Some(_), _)
| (_, _, Some(enums::FutureUsage::OffSession), Some(_), _, _)
| (Some(_), _, Some(enums::FutureUsage::OffSession), _, _, _) => {
Ok(Some(api::MandateTransactionType::NewMandateTransaction))
}
(_, _, Some(enums::FutureUsage::OffSession), _, Some(_), _)
| (_, Some(_), _, _, _, _)
| (_, _, Some(enums::FutureUsage::OffSession), _, _, Some(enums::PaymentMethod::Wallet)) => {
Ok(Some(
api::MandateTransactionType::RecurringMandateTransaction,
))
}
_ => Ok(None),
}
}
#[derive(Clone)]
pub struct MandateGenericData {
pub token: Option<String>,
pub payment_method: Option<enums::PaymentMethod>,
pub payment_method_type: Option<enums::PaymentMethodType>,
pub mandate_data: Option<MandateData>,
pub recurring_mandate_payment_data:
Option<hyperswitch_domain_models::router_data::RecurringMandatePaymentData>,
pub mandate_connector: Option<payments::MandateConnectorDetails>,
pub payment_method_info: Option<domain::PaymentMethod>,
}
| {
"crate": "router",
"file": "crates/router/src/core/mandate/helpers.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_4746908228904298479 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/routing/helpers.rs
// Contains: 4 structs, 0 enums
//! Analysis for usage of all helper functions for use case of routing
//!
//! Functions that are used to perform the retrieval of merchant's
//! routing dict, configs, defaults
use std::fmt::Debug;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use std::str::FromStr;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use std::sync::Arc;
#[cfg(feature = "v1")]
use api_models::open_router;
use api_models::routing as routing_types;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use common_utils::ext_traits::ValueExt;
use common_utils::{ext_traits::Encode, id_type, types::keymanager::KeyManagerState};
use diesel_models::configs;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use diesel_models::dynamic_routing_stats::{DynamicRoutingStatsNew, DynamicRoutingStatsUpdate};
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use diesel_models::routing_algorithm;
use error_stack::ResultExt;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use external_services::grpc_client::dynamic_routing::{
contract_routing_client::ContractBasedDynamicRouting,
elimination_based_client::EliminationBasedRouting,
success_rate_client::SuccessBasedDynamicRouting,
};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use hyperswitch_domain_models::api::ApplicationResponse;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use hyperswitch_interfaces::events::routing_api_logs as routing_events;
#[cfg(feature = "v1")]
use router_env::logger;
#[cfg(feature = "v1")]
use router_env::{instrument, tracing};
use rustc_hash::FxHashSet;
use storage_impl::redis::cache;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use storage_impl::redis::cache::Cacheable;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use crate::db::errors::StorageErrorExt;
#[cfg(feature = "v2")]
use crate::types::domain::MerchantConnectorAccount;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use crate::types::transformers::ForeignFrom;
use crate::{
core::errors::{self, RouterResult},
db::StorageInterface,
routes::SessionState,
types::{domain, storage},
utils::StringExt,
};
#[cfg(feature = "v1")]
use crate::{
core::payments::{
routing::utils::{self as routing_utils, DecisionEngineApiHandler},
OperationSessionGetters, OperationSessionSetters,
},
services,
};
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use crate::{
core::{metrics as core_metrics, routing},
routes::app::SessionStateInfo,
types::transformers::ForeignInto,
};
pub const SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM: &str =
"Success rate based dynamic routing algorithm";
pub const ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM: &str =
"Elimination based dynamic routing algorithm";
pub const CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM: &str =
"Contract based dynamic routing algorithm";
pub const DECISION_ENGINE_RULE_CREATE_ENDPOINT: &str = "rule/create";
pub const DECISION_ENGINE_RULE_UPDATE_ENDPOINT: &str = "rule/update";
pub const DECISION_ENGINE_RULE_GET_ENDPOINT: &str = "rule/get";
pub const DECISION_ENGINE_RULE_DELETE_ENDPOINT: &str = "rule/delete";
pub const DECISION_ENGINE_MERCHANT_BASE_ENDPOINT: &str = "merchant-account";
pub const DECISION_ENGINE_MERCHANT_CREATE_ENDPOINT: &str = "merchant-account/create";
/// Provides us with all the configured configs of the Merchant in the ascending time configured
/// manner and chooses the first of them
pub async fn get_merchant_default_config(
db: &dyn StorageInterface,
// Cannot make this as merchant id domain type because, we are passing profile id also here
merchant_id: &str,
transaction_type: &storage::enums::TransactionType,
) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> {
let key = get_default_config_key(merchant_id, transaction_type);
let maybe_config = db.find_config_by_key(&key).await;
match maybe_config {
Ok(config) => config
.config
.parse_struct("Vec<RoutableConnectors>")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant default config has invalid structure"),
Err(e) if e.current_context().is_db_not_found() => {
let new_config_conns = Vec::<routing_types::RoutableConnectorChoice>::new();
let serialized = new_config_conns
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Error while creating and serializing new merchant default config",
)?;
let new_config = configs::ConfigNew {
key,
config: serialized,
};
db.insert_config(new_config)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error inserting new default routing config into DB")?;
Ok(new_config_conns)
}
Err(e) => Err(e)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error fetching default config for merchant"),
}
}
/// Merchant's already created config can be updated and this change will be reflected
/// in DB as well for the particular updated config
pub async fn update_merchant_default_config(
db: &dyn StorageInterface,
merchant_id: &str,
connectors: Vec<routing_types::RoutableConnectorChoice>,
transaction_type: &storage::enums::TransactionType,
) -> RouterResult<()> {
let key = get_default_config_key(merchant_id, transaction_type);
let config_str = connectors
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize merchant default routing config during update")?;
let config_update = configs::ConfigUpdate::Update {
config: Some(config_str),
};
db.update_config_by_key(&key, config_update)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating the default routing config in DB")?;
Ok(())
}
pub async fn update_merchant_routing_dictionary(
db: &dyn StorageInterface,
merchant_id: &str,
dictionary: routing_types::RoutingDictionary,
) -> RouterResult<()> {
let key = get_routing_dictionary_key(merchant_id);
let dictionary_str = dictionary
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize routing dictionary during update")?;
let config_update = configs::ConfigUpdate::Update {
config: Some(dictionary_str),
};
db.update_config_by_key(&key, config_update)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error saving routing dictionary to DB")?;
Ok(())
}
/// This will help make one of all configured algorithms to be in active state for a particular
/// merchant
#[cfg(feature = "v1")]
pub async fn update_merchant_active_algorithm_ref(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
config_key: cache::CacheKind<'_>,
algorithm_id: routing_types::RoutingAlgorithmRef,
) -> RouterResult<()> {
let ref_value = algorithm_id
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed converting routing algorithm ref to json value")?;
let merchant_account_update = storage::MerchantAccountUpdate::Update {
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
locker_id: None,
metadata: None,
routing_algorithm: Some(ref_value),
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
default_profile: None,
payment_link_config: None,
pm_collect_link_config: None,
};
let db = &*state.store;
db.update_specific_fields_in_merchant(
&state.into(),
&key_store.merchant_id,
merchant_account_update,
key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref in merchant account")?;
cache::redact_from_redis_and_publish(db.get_cache_store().as_ref(), [config_key])
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate the config cache")?;
Ok(())
}
#[cfg(feature = "v1")]
pub async fn update_profile_active_algorithm_ref(
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
current_business_profile: domain::Profile,
algorithm_id: routing_types::RoutingAlgorithmRef,
transaction_type: &storage::enums::TransactionType,
) -> RouterResult<()> {
let ref_val = algorithm_id
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert routing ref to value")?;
let merchant_id = current_business_profile.merchant_id.clone();
let profile_id = current_business_profile.get_id().to_owned();
let (routing_algorithm, payout_routing_algorithm, three_ds_decision_rule_algorithm) =
match transaction_type {
storage::enums::TransactionType::Payment => (Some(ref_val), None, None),
#[cfg(feature = "payouts")]
storage::enums::TransactionType::Payout => (None, Some(ref_val), None),
storage::enums::TransactionType::ThreeDsAuthentication => (None, None, Some(ref_val)),
};
let business_profile_update = domain::ProfileUpdate::RoutingAlgorithmUpdate {
routing_algorithm,
payout_routing_algorithm,
three_ds_decision_rule_algorithm,
};
db.update_profile_by_profile_id(
key_manager_state,
merchant_key_store,
current_business_profile,
business_profile_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref in business profile")?;
// Invalidate the routing cache for Payments and Payouts transaction types
if !transaction_type.is_three_ds_authentication() {
let routing_cache_key = cache::CacheKind::Routing(
format!(
"routing_config_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
)
.into(),
);
cache::redact_from_redis_and_publish(db.get_cache_store().as_ref(), [routing_cache_key])
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate routing cache")?;
}
Ok(())
}
#[cfg(feature = "v1")]
pub async fn update_business_profile_active_dynamic_algorithm_ref(
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
current_business_profile: domain::Profile,
dynamic_routing_algorithm_ref: routing_types::DynamicRoutingAlgorithmRef,
) -> RouterResult<()> {
let ref_val = dynamic_routing_algorithm_ref
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert dynamic routing ref to value")?;
let business_profile_update = domain::ProfileUpdate::DynamicRoutingAlgorithmUpdate {
dynamic_routing_algorithm: Some(ref_val),
};
db.update_profile_by_profile_id(
key_manager_state,
merchant_key_store,
current_business_profile,
business_profile_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update dynamic routing algorithm ref in business profile")?;
Ok(())
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct RoutingAlgorithmHelpers<'h> {
pub name_mca_id_set: ConnectNameAndMCAIdForProfile<'h>,
pub name_set: ConnectNameForProfile<'h>,
pub routing_algorithm: &'h routing_types::StaticRoutingAlgorithm,
}
#[cfg(feature = "v1")]
pub enum RoutingDecisionData {
DebitRouting(DebitRoutingDecisionData),
}
#[cfg(feature = "v1")]
pub struct DebitRoutingDecisionData {
pub card_network: common_enums::enums::CardNetwork,
pub debit_routing_result: Option<open_router::DebitRoutingOutput>,
}
#[cfg(feature = "v1")]
impl RoutingDecisionData {
pub fn apply_routing_decision<F, D>(&self, payment_data: &mut D)
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
match self {
Self::DebitRouting(data) => data.apply_debit_routing_decision(payment_data),
}
}
pub fn get_debit_routing_decision_data(
network: common_enums::enums::CardNetwork,
debit_routing_result: Option<open_router::DebitRoutingOutput>,
) -> Self {
Self::DebitRouting(DebitRoutingDecisionData {
card_network: network,
debit_routing_result,
})
}
}
#[cfg(feature = "v1")]
impl DebitRoutingDecisionData {
pub fn apply_debit_routing_decision<F, D>(&self, payment_data: &mut D)
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
payment_data.set_card_network(self.card_network.clone());
self.debit_routing_result
.as_ref()
.map(|data| payment_data.set_co_badged_card_data(data));
}
}
#[derive(Clone, Debug)]
pub struct ConnectNameAndMCAIdForProfile<'a>(
pub FxHashSet<(
&'a common_enums::connector_enums::Connector,
id_type::MerchantConnectorAccountId,
)>,
);
#[derive(Clone, Debug)]
pub struct ConnectNameForProfile<'a>(pub FxHashSet<&'a common_enums::connector_enums::Connector>);
#[cfg(feature = "v2")]
impl RoutingAlgorithmHelpers<'_> {
fn connector_choice(
&self,
choice: &routing_types::RoutableConnectorChoice,
) -> RouterResult<()> {
if let Some(ref mca_id) = choice.merchant_connector_id {
let connector_choice = common_enums::connector_enums::Connector::from(choice.connector);
error_stack::ensure!(
self.name_mca_id_set.0.contains(&(&connector_choice, mca_id.clone())),
errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector with name '{connector_choice}' and merchant connector account id '{mca_id:?}' not found for the given profile",
)
}
);
} else {
let connector_choice = common_enums::connector_enums::Connector::from(choice.connector);
error_stack::ensure!(
self.name_set.0.contains(&connector_choice),
errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector with name '{connector_choice}' not found for the given profile",
)
}
);
};
Ok(())
}
pub fn validate_connectors_in_routing_config(&self) -> RouterResult<()> {
match self.routing_algorithm {
routing_types::StaticRoutingAlgorithm::Single(choice) => {
self.connector_choice(choice)?;
}
routing_types::StaticRoutingAlgorithm::Priority(list) => {
for choice in list {
self.connector_choice(choice)?;
}
}
routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => {
for split in splits {
self.connector_choice(&split.connector)?;
}
}
routing_types::StaticRoutingAlgorithm::Advanced(program) => {
let check_connector_selection =
|selection: &routing_types::ConnectorSelection| -> RouterResult<()> {
match selection {
routing_types::ConnectorSelection::VolumeSplit(splits) => {
for split in splits {
self.connector_choice(&split.connector)?;
}
}
routing_types::ConnectorSelection::Priority(list) => {
for choice in list {
self.connector_choice(choice)?;
}
}
}
Ok(())
};
check_connector_selection(&program.default_selection)?;
for rule in &program.rules {
check_connector_selection(&rule.connector_selection)?;
}
}
routing_types::StaticRoutingAlgorithm::ThreeDsDecisionRule(_) => {
return Err(errors::ApiErrorResponse::InternalServerError).attach_printable(
"Invalid routing algorithm three_ds decision rule received",
)?;
}
}
Ok(())
}
}
#[cfg(feature = "v1")]
pub async fn validate_connectors_in_routing_config(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
routing_algorithm: &routing_types::StaticRoutingAlgorithm,
) -> RouterResult<()> {
let all_mcas = state
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
merchant_id,
true,
key_store,
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_id.get_string_repr().to_owned(),
})?;
let name_mca_id_set = all_mcas
.iter()
.filter(|mca| mca.profile_id == *profile_id)
.map(|mca| (&mca.connector_name, mca.get_id()))
.collect::<FxHashSet<_>>();
let name_set = all_mcas
.iter()
.filter(|mca| mca.profile_id == *profile_id)
.map(|mca| &mca.connector_name)
.collect::<FxHashSet<_>>();
let connector_choice = |choice: &routing_types::RoutableConnectorChoice| {
if let Some(ref mca_id) = choice.merchant_connector_id {
error_stack::ensure!(
name_mca_id_set.contains(&(&choice.connector.to_string(), mca_id.clone())),
errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector with name '{}' and merchant connector account id '{:?}' not found for the given profile",
choice.connector,
mca_id,
)
}
);
} else {
error_stack::ensure!(
name_set.contains(&choice.connector.to_string()),
errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector with name '{}' not found for the given profile",
choice.connector,
)
}
);
}
Ok(())
};
match routing_algorithm {
routing_types::StaticRoutingAlgorithm::Single(choice) => {
connector_choice(choice)?;
}
routing_types::StaticRoutingAlgorithm::Priority(list) => {
for choice in list {
connector_choice(choice)?;
}
}
routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => {
for split in splits {
connector_choice(&split.connector)?;
}
}
routing_types::StaticRoutingAlgorithm::Advanced(program) => {
let check_connector_selection =
|selection: &routing_types::ConnectorSelection| -> RouterResult<()> {
match selection {
routing_types::ConnectorSelection::VolumeSplit(splits) => {
for split in splits {
connector_choice(&split.connector)?;
}
}
routing_types::ConnectorSelection::Priority(list) => {
for choice in list {
connector_choice(choice)?;
}
}
}
Ok(())
};
check_connector_selection(&program.default_selection)?;
for rule in &program.rules {
check_connector_selection(&rule.connector_selection)?;
}
}
routing_types::StaticRoutingAlgorithm::ThreeDsDecisionRule(_) => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid routing algorithm three_ds decision rule received")?
}
}
Ok(())
}
/// Provides the identifier for the specific merchant's routing_dictionary_key
#[inline(always)]
pub fn get_routing_dictionary_key(merchant_id: &str) -> String {
format!("routing_dict_{merchant_id}")
}
/// Provides the identifier for the specific merchant's default_config
#[inline(always)]
pub fn get_default_config_key(
merchant_id: &str,
transaction_type: &storage::enums::TransactionType,
) -> String {
match transaction_type {
storage::enums::TransactionType::Payment => format!("routing_default_{merchant_id}"),
#[cfg(feature = "payouts")]
storage::enums::TransactionType::Payout => format!("routing_default_po_{merchant_id}"),
storage::enums::TransactionType::ThreeDsAuthentication => {
format!("three_ds_authentication_{merchant_id}")
}
}
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[async_trait::async_trait]
pub trait DynamicRoutingCache {
async fn get_cached_dynamic_routing_config_for_profile(
state: &SessionState,
key: &str,
) -> Option<Arc<Self>>;
async fn refresh_dynamic_routing_cache<T, F, Fut>(
state: &SessionState,
key: &str,
func: F,
) -> RouterResult<T>
where
F: FnOnce() -> Fut + Send,
T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send;
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[async_trait::async_trait]
impl DynamicRoutingCache for routing_types::SuccessBasedRoutingConfig {
async fn get_cached_dynamic_routing_config_for_profile(
state: &SessionState,
key: &str,
) -> Option<Arc<Self>> {
cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
.get_val::<Arc<Self>>(cache::CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
})
.await
}
async fn refresh_dynamic_routing_cache<T, F, Fut>(
state: &SessionState,
key: &str,
func: F,
) -> RouterResult<T>
where
F: FnOnce() -> Fut + Send,
T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send,
{
cache::get_or_populate_in_memory(
state.store.get_cache_store().as_ref(),
key,
func,
&cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to populate SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE")
}
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[async_trait::async_trait]
impl DynamicRoutingCache for routing_types::ContractBasedRoutingConfig {
async fn get_cached_dynamic_routing_config_for_profile(
state: &SessionState,
key: &str,
) -> Option<Arc<Self>> {
cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE
.get_val::<Arc<Self>>(cache::CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
})
.await
}
async fn refresh_dynamic_routing_cache<T, F, Fut>(
state: &SessionState,
key: &str,
func: F,
) -> RouterResult<T>
where
F: FnOnce() -> Fut + Send,
T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send,
{
cache::get_or_populate_in_memory(
state.store.get_cache_store().as_ref(),
key,
func,
&cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to populate CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE")
}
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[async_trait::async_trait]
impl DynamicRoutingCache for routing_types::EliminationRoutingConfig {
async fn get_cached_dynamic_routing_config_for_profile(
state: &SessionState,
key: &str,
) -> Option<Arc<Self>> {
cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE
.get_val::<Arc<Self>>(cache::CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
})
.await
}
async fn refresh_dynamic_routing_cache<T, F, Fut>(
state: &SessionState,
key: &str,
func: F,
) -> RouterResult<T>
where
F: FnOnce() -> Fut + Send,
T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send,
{
cache::get_or_populate_in_memory(
state.store.get_cache_store().as_ref(),
key,
func,
&cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to populate ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE")
}
}
/// Cfetch dynamic routing configs
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn fetch_dynamic_routing_configs<T>(
state: &SessionState,
profile_id: &id_type::ProfileId,
routing_id: id_type::RoutingId,
) -> RouterResult<T>
where
T: serde::de::DeserializeOwned
+ Clone
+ DynamicRoutingCache
+ Cacheable
+ serde::Serialize
+ Debug,
{
let key = format!(
"{}_{}",
profile_id.get_string_repr(),
routing_id.get_string_repr()
);
if let Some(config) =
T::get_cached_dynamic_routing_config_for_profile(state, key.as_str()).await
{
Ok(config.as_ref().clone())
} else {
let func = || async {
let routing_algorithm = state
.store
.find_routing_algorithm_by_profile_id_algorithm_id(profile_id, &routing_id)
.await
.change_context(errors::StorageError::ValueNotFound(
"RoutingAlgorithm".to_string(),
))
.attach_printable("unable to retrieve routing_algorithm for profile from db")?;
let dynamic_routing_config = routing_algorithm
.algorithm_data
.parse_value::<T>("dynamic_routing_config")
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("unable to parse dynamic_routing_config")?;
Ok(dynamic_routing_config)
};
let dynamic_routing_config =
T::refresh_dynamic_routing_cache(state, key.as_str(), func).await?;
Ok(dynamic_routing_config)
}
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn update_gateway_score_helper_with_open_router(
state: &SessionState,
payment_attempt: &storage::PaymentAttempt,
profile_id: &id_type::ProfileId,
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
) -> RouterResult<()> {
let is_success_rate_routing_enabled =
dynamic_routing_algo_ref.is_success_rate_routing_enabled();
let is_elimination_enabled = dynamic_routing_algo_ref.is_elimination_enabled();
if is_success_rate_routing_enabled || is_elimination_enabled {
let payment_connector = &payment_attempt.connector.clone().ok_or(
errors::ApiErrorResponse::GenericNotFoundError {
message: "unable to derive payment connector from payment attempt".to_string(),
},
)?;
let routable_connector = routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(payment_connector.as_str())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to infer routable_connector from connector")?,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
};
logger::debug!(
"performing update-gateway-score for gateway with id {} in open_router for profile: {}",
routable_connector,
profile_id.get_string_repr()
);
routing::payments_routing::update_gateway_score_with_open_router(
state,
routable_connector.clone(),
profile_id,
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
payment_attempt.status,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to update gateway score in open_router service")?;
}
Ok(())
}
/// metrics for success based dynamic routing
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn push_metrics_with_update_window_for_success_based_routing(
state: &SessionState,
payment_attempt: &storage::PaymentAttempt,
routable_connectors: Vec<routing_types::RoutableConnectorChoice>,
profile_id: &id_type::ProfileId,
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,
) -> RouterResult<()> {
if let Some(success_based_algo_ref) = dynamic_routing_algo_ref.success_based_algorithm {
if success_based_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "dynamic routing gRPC client not found".to_string(),
})?
.success_rate_client;
let payment_connector = &payment_attempt.connector.clone().ok_or(
errors::ApiErrorResponse::GenericNotFoundError {
message: "unable to derive payment connector from payment attempt".to_string(),
},
)?;
let routable_connector = routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(payment_connector.as_str())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to infer routable_connector from connector")?,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
};
let payment_status_attribute =
get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status);
let success_based_routing_configs = fetch_dynamic_routing_configs::<
routing_types::SuccessBasedRoutingConfig,
>(
state,
profile_id,
success_based_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "success_rate algorithm_id not found".to_string(),
})
.attach_printable(
"success_based_routing_algorithm_id not found in business_profile",
)?,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "success_rate based dynamic routing configs not found".to_string(),
})
.attach_printable("unable to retrieve success_rate based dynamic routing configs")?;
let success_based_routing_config_params = dynamic_routing_config_params_interpolator
.get_string_val(
success_based_routing_configs
.params
.as_ref()
.ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)
.change_context(errors::ApiErrorResponse::InternalServerError)?,
);
let success_based_connectors = client
.calculate_entity_and_global_success_rate(
profile_id.get_string_repr().into(),
success_based_routing_configs.clone(),
success_based_routing_config_params.clone(),
routable_connectors.clone(),
state.get_grpc_headers(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to calculate/fetch success rate from dynamic routing service",
)?;
let first_merchant_success_based_connector = &success_based_connectors
.entity_scores_with_labels
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to fetch the first connector from list of connectors obtained from dynamic routing service",
)?;
let (first_merchant_success_based_connector_label, _) = first_merchant_success_based_connector.label
.split_once(':')
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service",
first_merchant_success_based_connector.label
))?;
let first_global_success_based_connector = &success_based_connectors
.global_scores_with_labels
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to fetch the first global connector from list of connectors obtained from dynamic routing service",
)?;
let outcome = get_dynamic_routing_based_metrics_outcome_for_payment(
payment_status_attribute,
payment_connector.to_string(),
first_merchant_success_based_connector_label.to_string(),
);
core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add(
1,
router_env::metric_attributes!(
(
"tenant",
state.tenant.tenant_id.get_string_repr().to_owned(),
),
(
"merchant_profile_id",
format!(
"{}:{}",
payment_attempt.merchant_id.get_string_repr(),
payment_attempt.profile_id.get_string_repr()
),
),
(
"merchant_specific_success_based_routing_connector",
first_merchant_success_based_connector_label.to_string(),
),
(
"merchant_specific_success_based_routing_connector_score",
first_merchant_success_based_connector.score.to_string(),
),
(
"global_success_based_routing_connector",
first_global_success_based_connector.label.to_string(),
),
(
"global_success_based_routing_connector_score",
first_global_success_based_connector.score.to_string(),
),
("payment_connector", payment_connector.to_string()),
(
"currency",
payment_attempt
.currency
.map_or_else(|| "None".to_string(), |currency| currency.to_string()),
),
(
"payment_method",
payment_attempt.payment_method.map_or_else(
|| "None".to_string(),
|payment_method| payment_method.to_string(),
),
),
(
"payment_method_type",
payment_attempt.payment_method_type.map_or_else(
|| "None".to_string(),
|payment_method_type| payment_method_type.to_string(),
),
),
(
"capture_method",
payment_attempt.capture_method.map_or_else(
|| "None".to_string(),
|capture_method| capture_method.to_string(),
),
),
(
"authentication_type",
payment_attempt.authentication_type.map_or_else(
|| "None".to_string(),
|authentication_type| authentication_type.to_string(),
),
),
("payment_status", payment_attempt.status.to_string()),
("conclusive_classification", outcome.to_string()),
),
);
logger::debug!("successfully pushed success_based_routing metrics");
let duplicate_stats = state
.store
.find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
payment_attempt.attempt_id.clone(),
&payment_attempt.merchant_id.to_owned(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch dynamic_routing_stats entry")?;
if duplicate_stats.is_some() {
let dynamic_routing_update = DynamicRoutingStatsUpdate {
amount: payment_attempt.get_total_amount(),
success_based_routing_connector: first_merchant_success_based_connector_label
.to_string(),
payment_connector: payment_connector.to_string(),
payment_method_type: payment_attempt.payment_method_type,
currency: payment_attempt.currency,
payment_method: payment_attempt.payment_method,
capture_method: payment_attempt.capture_method,
authentication_type: payment_attempt.authentication_type,
payment_status: payment_attempt.status,
conclusive_classification: outcome,
global_success_based_connector: Some(
first_global_success_based_connector.label.to_string(),
),
};
state
.store
.update_dynamic_routing_stats(
payment_attempt.attempt_id.clone(),
&payment_attempt.merchant_id.to_owned(),
dynamic_routing_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update dynamic routing stats to db")?;
} else {
let dynamic_routing_stats = DynamicRoutingStatsNew {
payment_id: payment_attempt.payment_id.to_owned(),
attempt_id: payment_attempt.attempt_id.clone(),
merchant_id: payment_attempt.merchant_id.to_owned(),
profile_id: payment_attempt.profile_id.to_owned(),
amount: payment_attempt.get_total_amount(),
success_based_routing_connector: first_merchant_success_based_connector_label
.to_string(),
payment_connector: payment_connector.to_string(),
payment_method_type: payment_attempt.payment_method_type,
currency: payment_attempt.currency,
payment_method: payment_attempt.payment_method,
capture_method: payment_attempt.capture_method,
authentication_type: payment_attempt.authentication_type,
payment_status: payment_attempt.status,
conclusive_classification: outcome,
created_at: common_utils::date_time::now(),
global_success_based_connector: Some(
first_global_success_based_connector.label.to_string(),
),
};
state
.store
.insert_dynamic_routing_stat_entry(dynamic_routing_stats)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to push dynamic routing stats to db")?;
};
let label_with_status = routing_utils::UpdateLabelWithStatusEventRequest {
label: routable_connector.clone().to_string(),
status: payment_status_attribute == common_enums::AttemptStatus::Charged,
};
let event_request = routing_utils::UpdateSuccessRateWindowEventRequest {
id: payment_attempt.profile_id.get_string_repr().to_string(),
params: success_based_routing_config_params.clone(),
labels_with_status: vec![label_with_status.clone()],
global_labels_with_status: vec![label_with_status],
config: success_based_routing_configs
.config
.as_ref()
.map(routing_utils::UpdateSuccessRateWindowConfig::from),
};
let routing_events_wrapper = routing_utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_attempt.payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
"IntelligentRouter: UpdateSuccessRateWindow".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let update_response_result = client
.update_success_rate(
profile_id.get_string_repr().into(),
success_based_routing_configs,
success_based_routing_config_params,
vec![routing_types::RoutableConnectorChoiceWithStatus::new(
routable_connector.clone(),
payment_status_attribute == common_enums::AttemptStatus::Charged,
)],
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::SuccessRateCalculationError)
.attach_printable(
"unable to update success based routing window in dynamic routing service",
);
match update_response_result {
Ok(update_response) => {
let updated_resp =
routing_utils::UpdateSuccessRateWindowEventResponse::try_from(
&update_response,
)
.change_context(errors::RoutingError::RoutingEventsError { message: "Unable to convert to UpdateSuccessRateWindowEventResponse from UpdateSuccessRateWindowResponse".to_string(), status_code: 500 })?;
Ok(Some(updated_resp))
}
Err(err) => {
logger::error!(
"unable to update connector score in dynamic routing service: {:?}",
err.current_context()
);
Err(err)
}
}
};
let events_response = routing_events_wrapper
.construct_event_builder(
"SuccessRateCalculator.UpdateSuccessRateWindow".to_string(),
routing_events::RoutingEngine::IntelligentRouter,
routing_events::ApiMethod::Grpc,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"SR-Intelligent-Router: Failed to update success rate in Intelligent-Router",
)?
.trigger_event(state, closure)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"SR-Intelligent-Router: Failed to update success rate in Intelligent-Router",
)?;
let _response: routing_utils::UpdateSuccessRateWindowEventResponse = events_response
.response
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"UpdateSuccessRateWindowEventResponse not found in RoutingEventResponse",
)?;
let mut routing_event = events_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message:
"SR-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"SR-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse",
)?;
routing_event.set_status_code(200);
routing_event.set_payment_connector(routable_connector); // we can do this inside the event wrap by implementing an interface on the req type
state.event_handler().log_event(&routing_event);
Ok(())
} else {
Ok(())
}
} else {
Ok(())
}
}
/// update window for elimination based dynamic routing
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn update_window_for_elimination_routing(
state: &SessionState,
payment_attempt: &storage::PaymentAttempt,
profile_id: &id_type::ProfileId,
dynamic_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
elimination_routing_configs_params_interpolator: DynamicRoutingConfigParamsInterpolator,
gsm_error_category: common_enums::ErrorCategory,
) -> RouterResult<()> {
if let Some(elimination_algo_ref) = dynamic_algo_ref.elimination_routing_algorithm {
if elimination_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "dynamic routing gRPC client not found".to_string(),
})?
.elimination_based_client;
let elimination_routing_config = fetch_dynamic_routing_configs::<
routing_types::EliminationRoutingConfig,
>(
state,
profile_id,
elimination_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "elimination routing algorithm_id not found".to_string(),
})
.attach_printable(
"elimination_routing_algorithm_id not found in business_profile",
)?,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "elimination based dynamic routing configs not found".to_string(),
})
.attach_printable("unable to retrieve success_rate based dynamic routing configs")?;
let payment_connector = &payment_attempt.connector.clone().ok_or(
errors::ApiErrorResponse::GenericNotFoundError {
message: "unable to derive payment connector from payment attempt".to_string(),
},
)?;
let elimination_routing_config_params = elimination_routing_configs_params_interpolator
.get_string_val(
elimination_routing_config
.params
.as_ref()
.ok_or(errors::RoutingError::EliminationBasedRoutingParamsNotFoundError)
.change_context(errors::ApiErrorResponse::InternalServerError)?,
);
let labels_with_bucket_name =
vec![routing_types::RoutableConnectorChoiceWithBucketName::new(
routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(
payment_connector.as_str(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to infer routable_connector from connector")?,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
},
gsm_error_category.to_string(),
)];
let event_request = routing_utils::UpdateEliminationBucketEventRequest {
id: profile_id.get_string_repr().to_string(),
params: elimination_routing_config_params.clone(),
labels_with_bucket_name: labels_with_bucket_name
.iter()
.map(|conn_choice| {
routing_utils::LabelWithBucketNameEventRequest::from(conn_choice)
})
.collect(),
config: elimination_routing_config
.elimination_analyser_config
.as_ref()
.map(routing_utils::EliminationRoutingEventBucketConfig::from),
};
let routing_events_wrapper = routing_utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_attempt.payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
"IntelligentRouter: UpdateEliminationBucket".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let update_response_result = client
.update_elimination_bucket_config(
profile_id.get_string_repr().to_string(),
elimination_routing_config_params,
labels_with_bucket_name,
elimination_routing_config.elimination_analyser_config,
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::EliminationRoutingCalculationError)
.attach_printable(
"unable to update elimination based routing buckets in dynamic routing service",
);
match update_response_result {
Ok(resp) => {
let updated_resp =
routing_utils::UpdateEliminationBucketEventResponse::try_from(&resp)
.change_context(errors::RoutingError::RoutingEventsError { message: "Unable to convert to UpdateEliminationBucketEventResponse from UpdateEliminationBucketResponse".to_string(), status_code: 500 })?;
Ok(Some(updated_resp))
}
Err(err) => {
logger::error!(
"unable to update elimination score in dynamic routing service: {:?}",
err.current_context()
);
Err(err)
}
}
};
let events_response = routing_events_wrapper.construct_event_builder( "EliminationAnalyser.UpdateEliminationBucket".to_string(),
routing_events::RoutingEngine::IntelligentRouter,
routing_events::ApiMethod::Grpc)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Elimination-Intelligent-Router: Failed to update elimination bucket in Intelligent-Router")?
.trigger_event(state, closure)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Elimination-Intelligent-Router: Failed to update elimination bucket in Intelligent-Router")?;
let _response: routing_utils::UpdateEliminationBucketEventResponse = events_response
.response
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"UpdateEliminationBucketEventResponse not found in RoutingEventResponse",
)?;
let mut routing_event = events_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message:
"Elimination-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Elimination-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse")?;
routing_event.set_status_code(200);
routing_event.set_payment_connector(routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(payment_connector.as_str())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to infer routable_connector from connector")?,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
});
state.event_handler().log_event(&routing_event);
Ok(())
} else {
Ok(())
}
} else {
Ok(())
}
}
/// metrics for contract based dynamic routing
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn push_metrics_with_update_window_for_contract_based_routing(
state: &SessionState,
payment_attempt: &storage::PaymentAttempt,
routable_connectors: Vec<routing_types::RoutableConnectorChoice>,
profile_id: &id_type::ProfileId,
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
_dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,
) -> RouterResult<()> {
if let Some(contract_routing_algo_ref) = dynamic_routing_algo_ref.contract_based_routing {
if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None
{
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "dynamic routing gRPC client not found".to_string(),
})?
.contract_based_client;
let payment_connector = &payment_attempt.connector.clone().ok_or(
errors::ApiErrorResponse::GenericNotFoundError {
message: "unable to derive payment connector from payment attempt".to_string(),
},
)?;
let contract_based_routing_config =
fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(
state,
profile_id,
contract_routing_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "contract_routing algorithm_id not found".to_string(),
})
.attach_printable(
"contract_based_routing_algorithm_id not found in business_profile",
)?,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "contract based dynamic routing configs not found".to_string(),
})
.attach_printable("unable to retrieve contract based dynamic routing configs")?;
let mut existing_label_info = None;
contract_based_routing_config
.label_info
.as_ref()
.map(|label_info_vec| {
for label_info in label_info_vec {
if Some(&label_info.mca_id)
== payment_attempt.merchant_connector_id.as_ref()
{
existing_label_info = Some(label_info.clone());
}
}
});
let final_label_info = existing_label_info
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "LabelInformation from ContractBasedRoutingConfig not found"
.to_string(),
})
.attach_printable(
"unable to get LabelInformation from ContractBasedRoutingConfig",
)?;
logger::debug!(
"contract based routing: matched LabelInformation - {:?}",
final_label_info
);
let request_label_info = routing_types::LabelInformation {
label: final_label_info.label.clone(),
target_count: final_label_info.target_count,
target_time: final_label_info.target_time,
mca_id: final_label_info.mca_id.to_owned(),
};
let payment_status_attribute =
get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status);
if payment_status_attribute == common_enums::AttemptStatus::Charged {
let event_request = routing_utils::UpdateContractRequestEventRequest {
id: profile_id.get_string_repr().to_string(),
params: "".to_string(),
labels_information: vec![
routing_utils::ContractLabelInformationEventRequest::from(
&request_label_info,
),
],
};
let routing_events_wrapper = routing_utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_attempt.payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
"IntelligentRouter: UpdateContractScore".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let update_response_result = client
.update_contracts(
profile_id.get_string_repr().into(),
vec![request_label_info],
"".to_string(),
vec![],
1,
state.get_grpc_headers(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to update contract based routing window in dynamic routing service",
);
match update_response_result {
Ok(resp) => {
let updated_resp =
routing_utils::UpdateContractEventResponse::try_from(&resp)
.change_context(errors::RoutingError::RoutingEventsError { message: "Unable to convert to UpdateContractEventResponse from UpdateContractResponse".to_string(), status_code: 500 })?;
Ok(Some(updated_resp))
}
Err(err) => {
logger::error!(
"unable to update elimination score in dynamic routing service: {:?}",
err.current_context()
);
// have to refactor errors
Err(error_stack::report!(
errors::RoutingError::ContractScoreUpdationError
))
}
}
};
let events_response = routing_events_wrapper.construct_event_builder( "ContractScoreCalculator.UpdateContract".to_string(),
routing_events::RoutingEngine::IntelligentRouter,
routing_events::ApiMethod::Grpc)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("ContractRouting-Intelligent-Router: Failed to construct RoutingEventsBuilder")?
.trigger_event(state, closure)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("ContractRouting-Intelligent-Router: Failed to update contract scores in Intelligent-Router")?;
let _response: routing_utils::UpdateContractEventResponse = events_response
.response
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"UpdateContractEventResponse not found in RoutingEventResponse",
)?;
let mut routing_event = events_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message:
"ContractRouting-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("ContractRouting-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse")?;
routing_event.set_payment_connector(routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(
final_label_info.label.as_str(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to infer routable_connector from connector")?,
merchant_connector_id: Some(final_label_info.mca_id.clone()),
});
routing_event.set_status_code(200);
state.event_handler().log_event(&routing_event);
}
let contract_based_connectors = routable_connectors
.into_iter()
.filter(|conn| {
conn.merchant_connector_id.clone() == Some(final_label_info.mca_id.clone())
})
.collect::<Vec<_>>();
let contract_scores = client
.calculate_contract_score(
profile_id.get_string_repr().into(),
contract_based_routing_config.clone(),
"".to_string(),
contract_based_connectors,
state.get_grpc_headers(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to calculate/fetch contract scores from dynamic routing service",
)?;
let first_contract_based_connector = &contract_scores
.labels_with_score
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to fetch the first connector from list of connectors obtained from dynamic routing service",
)?;
let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label
.split_once(':')
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"unable to split connector_name and mca_id from the first connector {first_contract_based_connector:?} obtained from dynamic routing service",
))?
.0, first_contract_based_connector.score, first_contract_based_connector.current_count );
core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(
1,
router_env::metric_attributes!(
(
"tenant",
state.tenant.tenant_id.get_string_repr().to_owned(),
),
(
"merchant_profile_id",
format!(
"{}:{}",
payment_attempt.merchant_id.get_string_repr(),
payment_attempt.profile_id.get_string_repr()
),
),
(
"contract_based_routing_connector",
first_contract_based_connector.to_string(),
),
(
"contract_based_routing_connector_score",
connector_score.to_string(),
),
(
"current_payment_count_contract_based_routing_connector",
current_payment_cnt.to_string(),
),
("payment_connector", payment_connector.to_string()),
(
"currency",
payment_attempt
.currency
.map_or_else(|| "None".to_string(), |currency| currency.to_string()),
),
(
"payment_method",
payment_attempt.payment_method.map_or_else(
|| "None".to_string(),
|payment_method| payment_method.to_string(),
),
),
(
"payment_method_type",
payment_attempt.payment_method_type.map_or_else(
|| "None".to_string(),
|payment_method_type| payment_method_type.to_string(),
),
),
(
"capture_method",
payment_attempt.capture_method.map_or_else(
|| "None".to_string(),
|capture_method| capture_method.to_string(),
),
),
(
"authentication_type",
payment_attempt.authentication_type.map_or_else(
|| "None".to_string(),
|authentication_type| authentication_type.to_string(),
),
),
("payment_status", payment_attempt.status.to_string()),
),
);
logger::debug!("successfully pushed contract_based_routing metrics");
Ok(())
} else {
Ok(())
}
} else {
Ok(())
}
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
fn get_desired_payment_status_for_dynamic_routing_metrics(
attempt_status: common_enums::AttemptStatus,
) -> common_enums::AttemptStatus {
match attempt_status {
common_enums::AttemptStatus::Charged
| common_enums::AttemptStatus::Authorized
| common_enums::AttemptStatus::PartialCharged
| common_enums::AttemptStatus::PartialChargedAndChargeable
| common_enums::AttemptStatus::PartiallyAuthorized => common_enums::AttemptStatus::Charged,
common_enums::AttemptStatus::Failure
| common_enums::AttemptStatus::AuthorizationFailed
| common_enums::AttemptStatus::AuthenticationFailed
| common_enums::AttemptStatus::CaptureFailed
| common_enums::AttemptStatus::RouterDeclined => common_enums::AttemptStatus::Failure,
common_enums::AttemptStatus::Started
| common_enums::AttemptStatus::AuthenticationPending
| common_enums::AttemptStatus::AuthenticationSuccessful
| common_enums::AttemptStatus::Authorizing
| common_enums::AttemptStatus::CodInitiated
| common_enums::AttemptStatus::Voided
| common_enums::AttemptStatus::VoidedPostCharge
| common_enums::AttemptStatus::VoidInitiated
| common_enums::AttemptStatus::CaptureInitiated
| common_enums::AttemptStatus::VoidFailed
| common_enums::AttemptStatus::AutoRefunded
| common_enums::AttemptStatus::Unresolved
| common_enums::AttemptStatus::Pending
| common_enums::AttemptStatus::IntegrityFailure
| common_enums::AttemptStatus::PaymentMethodAwaited
| common_enums::AttemptStatus::ConfirmationAwaited
| common_enums::AttemptStatus::DeviceDataCollectionPending
| common_enums::AttemptStatus::Expired => common_enums::AttemptStatus::Pending,
}
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
impl ForeignFrom<common_enums::AttemptStatus> for open_router::TxnStatus {
fn foreign_from(attempt_status: common_enums::AttemptStatus) -> Self {
match attempt_status {
common_enums::AttemptStatus::Started => Self::Started,
common_enums::AttemptStatus::AuthenticationFailed => Self::AuthenticationFailed,
common_enums::AttemptStatus::RouterDeclined => Self::JuspayDeclined,
common_enums::AttemptStatus::AuthenticationPending => Self::PendingVbv,
common_enums::AttemptStatus::AuthenticationSuccessful => Self::VBVSuccessful,
common_enums::AttemptStatus::Authorized
| common_enums::AttemptStatus::PartiallyAuthorized => Self::Authorized,
common_enums::AttemptStatus::AuthorizationFailed => Self::AuthorizationFailed,
common_enums::AttemptStatus::Charged => Self::Charged,
common_enums::AttemptStatus::Authorizing => Self::Authorizing,
common_enums::AttemptStatus::CodInitiated => Self::CODInitiated,
common_enums::AttemptStatus::Voided | common_enums::AttemptStatus::Expired => {
Self::Voided
}
common_enums::AttemptStatus::VoidedPostCharge => Self::VoidedPostCharge,
common_enums::AttemptStatus::VoidInitiated => Self::VoidInitiated,
common_enums::AttemptStatus::CaptureInitiated => Self::CaptureInitiated,
common_enums::AttemptStatus::CaptureFailed => Self::CaptureFailed,
common_enums::AttemptStatus::VoidFailed => Self::VoidFailed,
common_enums::AttemptStatus::AutoRefunded => Self::AutoRefunded,
common_enums::AttemptStatus::PartialCharged => Self::PartialCharged,
common_enums::AttemptStatus::PartialChargedAndChargeable => Self::ToBeCharged,
common_enums::AttemptStatus::Unresolved => Self::Pending,
common_enums::AttemptStatus::Pending
| common_enums::AttemptStatus::IntegrityFailure => Self::Pending,
common_enums::AttemptStatus::Failure => Self::Failure,
common_enums::AttemptStatus::PaymentMethodAwaited => Self::Pending,
common_enums::AttemptStatus::ConfirmationAwaited => Self::Pending,
common_enums::AttemptStatus::DeviceDataCollectionPending => Self::Pending,
}
}
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
fn get_dynamic_routing_based_metrics_outcome_for_payment(
payment_status_attribute: common_enums::AttemptStatus,
payment_connector: String,
first_success_based_connector: String,
) -> common_enums::SuccessBasedRoutingConclusiveState {
match payment_status_attribute {
common_enums::AttemptStatus::Charged
if *first_success_based_connector == *payment_connector =>
{
common_enums::SuccessBasedRoutingConclusiveState::TruePositive
}
common_enums::AttemptStatus::Failure
if *first_success_based_connector == *payment_connector =>
{
common_enums::SuccessBasedRoutingConclusiveState::FalsePositive
}
common_enums::AttemptStatus::Failure
if *first_success_based_connector != *payment_connector =>
{
common_enums::SuccessBasedRoutingConclusiveState::TrueNegative
}
common_enums::AttemptStatus::Charged
if *first_success_based_connector != *payment_connector =>
{
common_enums::SuccessBasedRoutingConclusiveState::FalseNegative
}
_ => common_enums::SuccessBasedRoutingConclusiveState::NonDeterministic,
}
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn disable_dynamic_routing_algorithm(
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: domain::Profile,
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_type: routing_types::DynamicRoutingType,
) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
let db = state.store.as_ref();
let key_manager_state = &state.into();
let profile_id = business_profile.get_id().clone();
let (algorithm_id, mut dynamic_routing_algorithm, cache_entries_to_redact) =
match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
let Some(algorithm_ref) = dynamic_routing_algo_ref.success_based_algorithm else {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Success rate based routing is already disabled".to_string(),
})?
};
let Some(algorithm_id) = algorithm_ref.algorithm_id_with_timestamp.algorithm_id
else {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already inactive".to_string(),
})?
};
let cache_key = format!(
"{}_{}",
business_profile.get_id().get_string_repr(),
algorithm_id.get_string_repr()
);
let cache_entries_to_redact =
vec![cache::CacheKind::SuccessBasedDynamicRoutingCache(
cache_key.into(),
)];
(
algorithm_id,
routing_types::DynamicRoutingAlgorithmRef {
success_based_algorithm: Some(routing_types::SuccessBasedAlgorithm {
algorithm_id_with_timestamp:
routing_types::DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: routing_types::DynamicRoutingFeatures::None,
}),
elimination_routing_algorithm: dynamic_routing_algo_ref
.elimination_routing_algorithm,
contract_based_routing: dynamic_routing_algo_ref.contract_based_routing,
dynamic_routing_volume_split: dynamic_routing_algo_ref
.dynamic_routing_volume_split,
is_merchant_created_in_decision_engine: dynamic_routing_algo_ref
.is_merchant_created_in_decision_engine,
},
cache_entries_to_redact,
)
}
routing_types::DynamicRoutingType::EliminationRouting => {
let Some(algorithm_ref) = dynamic_routing_algo_ref.elimination_routing_algorithm
else {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Elimination routing is already disabled".to_string(),
})?
};
let Some(algorithm_id) = algorithm_ref.algorithm_id_with_timestamp.algorithm_id
else {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already inactive".to_string(),
})?
};
let cache_key = format!(
"{}_{}",
business_profile.get_id().get_string_repr(),
algorithm_id.get_string_repr()
);
let cache_entries_to_redact =
vec![cache::CacheKind::EliminationBasedDynamicRoutingCache(
cache_key.into(),
)];
(
algorithm_id,
routing_types::DynamicRoutingAlgorithmRef {
success_based_algorithm: dynamic_routing_algo_ref.success_based_algorithm,
dynamic_routing_volume_split: dynamic_routing_algo_ref
.dynamic_routing_volume_split,
elimination_routing_algorithm: Some(
routing_types::EliminationRoutingAlgorithm {
algorithm_id_with_timestamp:
routing_types::DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: routing_types::DynamicRoutingFeatures::None,
},
),
contract_based_routing: dynamic_routing_algo_ref.contract_based_routing,
is_merchant_created_in_decision_engine: dynamic_routing_algo_ref
.is_merchant_created_in_decision_engine,
},
cache_entries_to_redact,
)
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
let Some(algorithm_ref) = dynamic_routing_algo_ref.contract_based_routing else {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Contract routing is already disabled".to_string(),
})?
};
let Some(algorithm_id) = algorithm_ref.algorithm_id_with_timestamp.algorithm_id
else {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already inactive".to_string(),
})?
};
let cache_key = format!(
"{}_{}",
business_profile.get_id().get_string_repr(),
algorithm_id.get_string_repr()
);
let cache_entries_to_redact =
vec![cache::CacheKind::ContractBasedDynamicRoutingCache(
cache_key.into(),
)];
(
algorithm_id,
routing_types::DynamicRoutingAlgorithmRef {
success_based_algorithm: dynamic_routing_algo_ref.success_based_algorithm,
elimination_routing_algorithm: dynamic_routing_algo_ref
.elimination_routing_algorithm,
dynamic_routing_volume_split: dynamic_routing_algo_ref
.dynamic_routing_volume_split,
contract_based_routing: Some(routing_types::ContractRoutingAlgorithm {
algorithm_id_with_timestamp:
routing_types::DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: routing_types::DynamicRoutingFeatures::None,
}),
is_merchant_created_in_decision_engine: dynamic_routing_algo_ref
.is_merchant_created_in_decision_engine,
},
cache_entries_to_redact,
)
}
};
// Call to DE here
if state.conf.open_router.dynamic_routing_enabled {
disable_decision_engine_dynamic_routing_setup(
state,
business_profile.get_id(),
dynamic_routing_type,
&mut dynamic_routing_algorithm,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to disable dynamic routing setup in decision engine")?;
}
// redact cache for dynamic routing config
let _ = cache::redact_from_redis_and_publish(
state.store.get_cache_store().as_ref(),
cache_entries_to_redact,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to publish into the redact channel for evicting the dynamic routing config cache",
)?;
let record = db
.find_routing_algorithm_by_profile_id_algorithm_id(business_profile.get_id(), &algorithm_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let response = record.foreign_into();
update_business_profile_active_dynamic_algorithm_ref(
db,
key_manager_state,
&key_store,
business_profile,
dynamic_routing_algorithm,
)
.await?;
core_metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id)),
);
Ok(ApplicationResponse::Json(response))
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn enable_dynamic_routing_algorithm(
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: domain::Profile,
feature_to_enable: routing_types::DynamicRoutingFeatures,
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_type: routing_types::DynamicRoutingType,
payload: Option<routing_types::DynamicRoutingPayload>,
) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
let mut dynamic_routing = dynamic_routing_algo_ref.clone();
match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
dynamic_routing
.disable_algorithm_id(routing_types::DynamicRoutingType::ContractBasedRouting);
enable_specific_routing_algorithm(
state,
key_store,
business_profile,
feature_to_enable,
dynamic_routing.clone(),
dynamic_routing_type,
dynamic_routing.success_based_algorithm,
payload,
)
.await
}
routing_types::DynamicRoutingType::EliminationRouting => {
enable_specific_routing_algorithm(
state,
key_store,
business_profile,
feature_to_enable,
dynamic_routing.clone(),
dynamic_routing_type,
dynamic_routing.elimination_routing_algorithm,
payload,
)
.await
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing cannot be set as default".to_string(),
})
.into())
}
}
}
#[allow(clippy::too_many_arguments)]
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn enable_specific_routing_algorithm<A>(
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: domain::Profile,
feature_to_enable: routing_types::DynamicRoutingFeatures,
mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_type: routing_types::DynamicRoutingType,
algo_type: Option<A>,
payload: Option<routing_types::DynamicRoutingPayload>,
) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>>
where
A: routing_types::DynamicRoutingAlgoAccessor + Clone + Debug,
{
//Check for payload
if let Some(payload) = payload {
return create_specific_dynamic_routing_setup(
state,
key_store,
business_profile,
feature_to_enable,
dynamic_routing_algo_ref,
dynamic_routing_type,
payload,
)
.await;
}
// Algorithm wasn't created yet
let Some(mut algo_type) = algo_type else {
return default_specific_dynamic_routing_setup(
state,
key_store,
business_profile,
feature_to_enable,
dynamic_routing_algo_ref,
dynamic_routing_type,
)
.await;
};
// Algorithm was in disabled state
let Some(algo_type_algorithm_id) = algo_type
.clone()
.get_algorithm_id_with_timestamp()
.algorithm_id
else {
return default_specific_dynamic_routing_setup(
state,
key_store,
business_profile,
feature_to_enable,
dynamic_routing_algo_ref,
dynamic_routing_type,
)
.await;
};
let db = state.store.as_ref();
let profile_id = business_profile.get_id().clone();
let algo_type_enabled_features = algo_type.get_enabled_features();
if *algo_type_enabled_features == feature_to_enable {
// algorithm already has the required feature
let routing_algorithm = db
.find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algo_type_algorithm_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let updated_routing_record = routing_algorithm.foreign_into();
return Ok(ApplicationResponse::Json(updated_routing_record));
};
*algo_type_enabled_features = feature_to_enable;
dynamic_routing_algo_ref.update_enabled_features(dynamic_routing_type, feature_to_enable);
update_business_profile_active_dynamic_algorithm_ref(
db,
&state.into(),
&key_store,
business_profile,
dynamic_routing_algo_ref.clone(),
)
.await?;
let routing_algorithm = db
.find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algo_type_algorithm_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let updated_routing_record = routing_algorithm.foreign_into();
core_metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.clone())),
);
Ok(ApplicationResponse::Json(updated_routing_record))
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn default_specific_dynamic_routing_setup(
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: domain::Profile,
feature_to_enable: routing_types::DynamicRoutingFeatures,
mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_type: routing_types::DynamicRoutingType,
) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
let db = state.store.as_ref();
let key_manager_state = &state.into();
let profile_id = business_profile.get_id().clone();
let merchant_id = business_profile.merchant_id.clone();
let algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
let default_success_based_routing_config =
if state.conf.open_router.dynamic_routing_enabled {
routing_types::SuccessBasedRoutingConfig::open_router_config_default()
} else {
routing_types::SuccessBasedRoutingConfig::default()
};
routing_algorithm::RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id: profile_id.clone(),
merchant_id,
name: SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),
description: None,
kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
algorithm_data: serde_json::json!(default_success_based_routing_config),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: common_enums::TransactionType::Payment,
decision_engine_routing_id: None,
}
}
routing_types::DynamicRoutingType::EliminationRouting => {
let default_elimination_routing_config =
if state.conf.open_router.dynamic_routing_enabled {
routing_types::EliminationRoutingConfig::open_router_config_default()
} else {
routing_types::EliminationRoutingConfig::default()
};
routing_algorithm::RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id: profile_id.clone(),
merchant_id,
name: ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),
description: None,
kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
algorithm_data: serde_json::json!(default_elimination_routing_config),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: common_enums::TransactionType::Payment,
decision_engine_routing_id: None,
}
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing cannot be set as default".to_string(),
})
.into())
}
};
// Call to DE here
// Need to map out the cases if this call should always be made or not
if state.conf.open_router.dynamic_routing_enabled {
enable_decision_engine_dynamic_routing_setup(
state,
business_profile.get_id(),
dynamic_routing_type,
&mut dynamic_routing_algo_ref,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to setup decision engine dynamic routing")?;
}
let record = db
.insert_routing_algorithm(algo)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to insert record in routing algorithm table")?;
dynamic_routing_algo_ref.update_algorithm_id(
algorithm_id,
feature_to_enable,
dynamic_routing_type,
);
update_business_profile_active_dynamic_algorithm_ref(
db,
key_manager_state,
&key_store,
business_profile,
dynamic_routing_algo_ref,
)
.await?;
let new_record = record.foreign_into();
core_metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.clone())),
);
Ok(ApplicationResponse::Json(new_record))
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn create_specific_dynamic_routing_setup(
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: domain::Profile,
feature_to_enable: routing_types::DynamicRoutingFeatures,
mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_type: routing_types::DynamicRoutingType,
payload: routing_types::DynamicRoutingPayload,
) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
let db = state.store.as_ref();
let key_manager_state = &state.into();
let profile_id = business_profile.get_id().clone();
let merchant_id = business_profile.merchant_id.clone();
let algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
let success_config = match &payload {
routing_types::DynamicRoutingPayload::SuccessBasedRoutingPayload(config) => config,
_ => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid payload type for Success Rate Based Routing".to_string(),
})
.into())
}
};
routing_algorithm::RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id: profile_id.clone(),
merchant_id,
name: SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),
description: None,
kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
algorithm_data: serde_json::json!(success_config),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: common_enums::TransactionType::Payment,
decision_engine_routing_id: None,
}
}
routing_types::DynamicRoutingType::EliminationRouting => {
let elimination_config = match &payload {
routing_types::DynamicRoutingPayload::EliminationRoutingPayload(config) => config,
_ => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid payload type for Elimination Routing".to_string(),
})
.into())
}
};
routing_algorithm::RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id: profile_id.clone(),
merchant_id,
name: ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),
description: None,
kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
algorithm_data: serde_json::json!(elimination_config),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: common_enums::TransactionType::Payment,
decision_engine_routing_id: None,
}
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing cannot be set as default".to_string(),
})
.into())
}
};
let record = db
.insert_routing_algorithm(algo)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to insert record in routing algorithm table")?;
dynamic_routing_algo_ref.update_feature(feature_to_enable, dynamic_routing_type);
update_business_profile_active_dynamic_algorithm_ref(
db,
key_manager_state,
&key_store,
business_profile,
dynamic_routing_algo_ref,
)
.await?;
let new_record = record.foreign_into();
core_metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.clone())),
);
Ok(ApplicationResponse::Json(new_record))
}
#[derive(Debug, Clone)]
pub struct DynamicRoutingConfigParamsInterpolator {
pub payment_method: Option<common_enums::PaymentMethod>,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub currency: Option<common_enums::Currency>,
pub country: Option<common_enums::CountryAlpha2>,
pub card_network: Option<String>,
pub card_bin: Option<String>,
}
impl DynamicRoutingConfigParamsInterpolator {
pub fn new(
payment_method: Option<common_enums::PaymentMethod>,
payment_method_type: Option<common_enums::PaymentMethodType>,
authentication_type: Option<common_enums::AuthenticationType>,
currency: Option<common_enums::Currency>,
country: Option<common_enums::CountryAlpha2>,
card_network: Option<String>,
card_bin: Option<String>,
) -> Self {
Self {
payment_method,
payment_method_type,
authentication_type,
currency,
country,
card_network,
card_bin,
}
}
pub fn get_string_val(
&self,
params: &Vec<routing_types::DynamicRoutingConfigParams>,
) -> String {
let mut parts: Vec<String> = Vec::new();
for param in params {
let val = match param {
routing_types::DynamicRoutingConfigParams::PaymentMethod => self
.payment_method
.as_ref()
.map_or(String::new(), |pm| pm.to_string()),
routing_types::DynamicRoutingConfigParams::PaymentMethodType => self
.payment_method_type
.as_ref()
.map_or(String::new(), |pmt| pmt.to_string()),
routing_types::DynamicRoutingConfigParams::AuthenticationType => self
.authentication_type
.as_ref()
.map_or(String::new(), |at| at.to_string()),
routing_types::DynamicRoutingConfigParams::Currency => self
.currency
.as_ref()
.map_or(String::new(), |cur| cur.to_string()),
routing_types::DynamicRoutingConfigParams::Country => self
.country
.as_ref()
.map_or(String::new(), |cn| cn.to_string()),
routing_types::DynamicRoutingConfigParams::CardNetwork => {
self.card_network.clone().unwrap_or_default()
}
routing_types::DynamicRoutingConfigParams::CardBin => {
self.card_bin.clone().unwrap_or_default()
}
};
if !val.is_empty() {
parts.push(val);
}
}
parts.join(":")
}
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn enable_decision_engine_dynamic_routing_setup(
state: &SessionState,
profile_id: &id_type::ProfileId,
dynamic_routing_type: routing_types::DynamicRoutingType,
dynamic_routing_algo_ref: &mut routing_types::DynamicRoutingAlgorithmRef,
payload: Option<routing_types::DynamicRoutingPayload>,
) -> RouterResult<()> {
logger::debug!(
"performing call with open_router for profile {}",
profile_id.get_string_repr()
);
let decision_engine_config_request = match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
let success_based_routing_config = payload
.and_then(|p| match p {
routing_types::DynamicRoutingPayload::SuccessBasedRoutingPayload(config) => {
Some(config)
}
_ => None,
})
.unwrap_or_else(
routing_types::SuccessBasedRoutingConfig::open_router_config_default,
);
open_router::DecisionEngineConfigSetupRequest {
merchant_id: profile_id.get_string_repr().to_string(),
config: open_router::DecisionEngineConfigVariant::SuccessRate(
success_based_routing_config
.get_decision_engine_configs()
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Decision engine config not found".to_string(),
})
.attach_printable("Decision engine config not found")?,
),
}
}
routing_types::DynamicRoutingType::EliminationRouting => {
let elimination_based_routing_config = payload
.and_then(|p| match p {
routing_types::DynamicRoutingPayload::EliminationRoutingPayload(config) => {
Some(config)
}
_ => None,
})
.unwrap_or_else(
routing_types::EliminationRoutingConfig::open_router_config_default,
);
open_router::DecisionEngineConfigSetupRequest {
merchant_id: profile_id.get_string_repr().to_string(),
config: open_router::DecisionEngineConfigVariant::Elimination(
elimination_based_routing_config
.get_decision_engine_configs()
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Decision engine config not found".to_string(),
})
.attach_printable("Decision engine config not found")?,
),
}
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing cannot be set as default".to_string(),
})
.into())
}
};
// Create merchant in Decision Engine if it is not already created
create_merchant_in_decision_engine_if_not_exists(state, profile_id, dynamic_routing_algo_ref)
.await;
routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
state,
services::Method::Post,
DECISION_ENGINE_RULE_CREATE_ENDPOINT,
Some(decision_engine_config_request),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to setup decision engine dynamic routing")?;
Ok(())
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn update_decision_engine_dynamic_routing_setup(
state: &SessionState,
profile_id: &id_type::ProfileId,
request: serde_json::Value,
dynamic_routing_type: routing_types::DynamicRoutingType,
dynamic_routing_algo_ref: &mut routing_types::DynamicRoutingAlgorithmRef,
) -> RouterResult<()> {
logger::debug!(
"performing call with open_router for profile {}",
profile_id.get_string_repr()
);
let decision_engine_request = match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
let success_rate_config: routing_types::SuccessBasedRoutingConfig = request
.parse_value("SuccessBasedRoutingConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize SuccessBasedRoutingConfig")?;
open_router::DecisionEngineConfigSetupRequest {
merchant_id: profile_id.get_string_repr().to_string(),
config: open_router::DecisionEngineConfigVariant::SuccessRate(
success_rate_config
.get_decision_engine_configs()
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Decision engine config not found".to_string(),
})
.attach_printable("Decision engine config not found")?,
),
}
}
routing_types::DynamicRoutingType::EliminationRouting => {
let elimination_config: routing_types::EliminationRoutingConfig = request
.parse_value("EliminationRoutingConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize EliminationRoutingConfig")?;
open_router::DecisionEngineConfigSetupRequest {
merchant_id: profile_id.get_string_repr().to_string(),
config: open_router::DecisionEngineConfigVariant::Elimination(
elimination_config
.get_decision_engine_configs()
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Decision engine config not found".to_string(),
})
.attach_printable("Decision engine config not found")?,
),
}
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing cannot be set as default".to_string(),
})
.into())
}
};
// Create merchant in Decision Engine if it is not already created
create_merchant_in_decision_engine_if_not_exists(state, profile_id, dynamic_routing_algo_ref)
.await;
routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
state,
services::Method::Post,
DECISION_ENGINE_RULE_UPDATE_ENDPOINT,
Some(decision_engine_request),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update decision engine dynamic routing")?;
Ok(())
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn get_decision_engine_active_dynamic_routing_algorithm(
state: &SessionState,
profile_id: &id_type::ProfileId,
dynamic_routing_type: open_router::DecisionEngineDynamicAlgorithmType,
) -> RouterResult<Option<open_router::DecisionEngineConfigSetupRequest>> {
logger::debug!(
"decision_engine_euclid: GET api call for decision active {:?} routing algorithm",
dynamic_routing_type
);
let request = open_router::GetDecisionEngineConfigRequest {
merchant_id: profile_id.get_string_repr().to_owned(),
algorithm: dynamic_routing_type,
};
let response: Option<open_router::DecisionEngineConfigSetupRequest> =
routing_utils::ConfigApiClient::send_decision_engine_request(
state,
services::Method::Post,
DECISION_ENGINE_RULE_GET_ENDPOINT,
Some(request),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get active dynamic algorithm from decision engine")?
.response;
Ok(response)
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn disable_decision_engine_dynamic_routing_setup(
state: &SessionState,
profile_id: &id_type::ProfileId,
dynamic_routing_type: routing_types::DynamicRoutingType,
dynamic_routing_algo_ref: &mut routing_types::DynamicRoutingAlgorithmRef,
) -> RouterResult<()> {
logger::debug!(
"performing call with open_router for profile {}",
profile_id.get_string_repr()
);
let decision_engine_request = open_router::FetchRoutingConfig {
merchant_id: profile_id.get_string_repr().to_string(),
algorithm: match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
open_router::AlgorithmType::SuccessRate
}
routing_types::DynamicRoutingType::EliminationRouting => {
open_router::AlgorithmType::Elimination
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing is not enabled for decision engine".to_string(),
})
.into())
}
},
};
// Create merchant in Decision Engine if it is not already created
create_merchant_in_decision_engine_if_not_exists(state, profile_id, dynamic_routing_algo_ref)
.await;
routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
state,
services::Method::Post,
DECISION_ENGINE_RULE_DELETE_ENDPOINT,
Some(decision_engine_request),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to disable decision engine dynamic routing")?;
Ok(())
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn create_merchant_in_decision_engine_if_not_exists(
state: &SessionState,
profile_id: &id_type::ProfileId,
dynamic_routing_algo_ref: &mut routing_types::DynamicRoutingAlgorithmRef,
) {
if !dynamic_routing_algo_ref.is_merchant_created_in_decision_engine {
logger::debug!(
"Creating merchant_account in decision engine for profile {}",
profile_id.get_string_repr()
);
create_decision_engine_merchant(state, profile_id)
.await
.map_err(|err| {
logger::warn!("Merchant creation error in decision_engine: {err:?}");
})
.ok();
// TODO: Update the status based on the status code or error message from the API call
dynamic_routing_algo_ref.update_merchant_creation_status_in_decision_engine(true);
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn create_decision_engine_merchant(
state: &SessionState,
profile_id: &id_type::ProfileId,
) -> RouterResult<()> {
let merchant_account_req = open_router::MerchantAccount {
merchant_id: profile_id.get_string_repr().to_string(),
gateway_success_rate_based_decider_input: None,
};
routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
state,
services::Method::Post,
DECISION_ENGINE_MERCHANT_CREATE_ENDPOINT,
Some(merchant_account_req),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to create merchant account on decision engine")?;
Ok(())
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn delete_decision_engine_merchant(
state: &SessionState,
profile_id: &id_type::ProfileId,
) -> RouterResult<()> {
let path = format!(
"{}/{}",
DECISION_ENGINE_MERCHANT_BASE_ENDPOINT,
profile_id.get_string_repr()
);
routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
state,
services::Method::Delete,
&path,
None::<id_type::ProfileId>,
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to delete merchant account on decision engine")?;
Ok(())
}
pub async fn redact_cgraph_cache(
state: &SessionState,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
) -> RouterResult<()> {
let cgraph_payouts_key = format!(
"cgraph_po_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
);
let cgraph_payments_key = format!(
"cgraph_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
);
let config_payouts_key = cache::CacheKind::CGraph(cgraph_payouts_key.clone().into());
let config_payments_key = cache::CacheKind::CGraph(cgraph_payments_key.clone().into());
cache::redact_from_redis_and_publish(
state.store.get_cache_store().as_ref(),
[config_payouts_key, config_payments_key],
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate the cgraph cache")?;
Ok(())
}
pub async fn redact_routing_cache(
state: &SessionState,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
) -> RouterResult<()> {
let routing_payments_key = format!(
"routing_config_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
);
let routing_payouts_key = format!(
"routing_config_po_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
);
let routing_payouts_cache_key = cache::CacheKind::Routing(routing_payouts_key.clone().into());
let routing_payments_cache_key = cache::CacheKind::CGraph(routing_payments_key.clone().into());
cache::redact_from_redis_and_publish(
state.store.get_cache_store().as_ref(),
[routing_payouts_cache_key, routing_payments_cache_key],
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate the routing cache")?;
Ok(())
}
| {
"crate": "router",
"file": "crates/router/src/core/routing/helpers.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 4,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_4631926721750420617 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/webhooks/types.rs
// Contains: 1 structs, 1 enums
use api_models::{webhook_events, webhooks};
use common_utils::{crypto::SignMessage, ext_traits::Encode};
use error_stack::ResultExt;
use masking::Secret;
use serde::Serialize;
use crate::{
core::errors,
headers, logger,
services::request::Maskable,
types::storage::{self, enums},
};
#[derive(Debug)]
pub enum ScheduleWebhookRetry {
WithProcessTracker(Box<storage::ProcessTracker>),
NoSchedule,
}
pub struct OutgoingWebhookPayloadWithSignature {
pub payload: Secret<String>,
pub signature: Option<String>,
}
pub trait OutgoingWebhookType:
Serialize + From<webhooks::OutgoingWebhook> + Sync + Send + std::fmt::Debug + 'static
{
fn get_outgoing_webhooks_signature(
&self,
payment_response_hash_key: Option<impl AsRef<[u8]>>,
) -> errors::CustomResult<OutgoingWebhookPayloadWithSignature, errors::WebhooksFlowError>;
fn add_webhook_header(header: &mut Vec<(String, Maskable<String>)>, signature: String);
}
impl OutgoingWebhookType for webhooks::OutgoingWebhook {
fn get_outgoing_webhooks_signature(
&self,
payment_response_hash_key: Option<impl AsRef<[u8]>>,
) -> errors::CustomResult<OutgoingWebhookPayloadWithSignature, errors::WebhooksFlowError> {
let webhook_signature_payload = self
.encode_to_string_of_json()
.change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
.attach_printable("failed encoding outgoing webhook payload")?;
let signature = payment_response_hash_key
.map(|key| {
common_utils::crypto::HmacSha512::sign_message(
&common_utils::crypto::HmacSha512,
key.as_ref(),
webhook_signature_payload.as_bytes(),
)
})
.transpose()
.change_context(errors::WebhooksFlowError::OutgoingWebhookSigningFailed)
.attach_printable("Failed to sign the message")?
.map(hex::encode);
Ok(OutgoingWebhookPayloadWithSignature {
payload: webhook_signature_payload.into(),
signature,
})
}
fn add_webhook_header(header: &mut Vec<(String, Maskable<String>)>, signature: String) {
header.push((headers::X_WEBHOOK_SIGNATURE.to_string(), signature.into()))
}
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct OutgoingWebhookTrackingData {
pub(crate) merchant_id: common_utils::id_type::MerchantId,
pub(crate) business_profile_id: common_utils::id_type::ProfileId,
pub(crate) event_type: enums::EventType,
pub(crate) event_class: enums::EventClass,
pub(crate) primary_object_id: String,
pub(crate) primary_object_type: enums::EventObjectType,
pub(crate) initial_attempt_id: Option<String>,
}
pub struct WebhookResponse {
pub response: reqwest::Response,
}
impl WebhookResponse {
pub async fn get_outgoing_webhook_response_content(
self,
) -> webhook_events::OutgoingWebhookResponseContent {
let status_code = self.response.status();
let response_headers = self
.response
.headers()
.iter()
.map(|(name, value)| {
(
name.as_str().to_owned(),
value
.to_str()
.map(|s| Secret::from(String::from(s)))
.unwrap_or_else(|error| {
logger::warn!(
"Response header {} contains non-UTF-8 characters: {error:?}",
name.as_str()
);
Secret::from(String::from("Non-UTF-8 header value"))
}),
)
})
.collect::<Vec<_>>();
let response_body = self
.response
.text()
.await
.map(Secret::from)
.unwrap_or_else(|error| {
logger::warn!("Response contains non-UTF-8 characters: {error:?}");
Secret::from(String::from("Non-UTF-8 response body"))
});
webhook_events::OutgoingWebhookResponseContent {
body: Some(response_body),
headers: Some(response_headers),
status_code: Some(status_code.as_u16()),
error_message: None,
}
}
}
| {
"crate": "router",
"file": "crates/router/src/core/webhooks/types.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-8913315627087513085 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/webhooks/recovery_incoming.rs
// Contains: 4 structs, 0 enums
use std::{collections::HashMap, marker::PhantomData, str::FromStr};
use api_models::{enums as api_enums, payments as api_payments, webhooks};
use common_utils::{
ext_traits::{AsyncExt, ValueExt},
id_type,
};
use diesel_models::process_tracker as storage;
use error_stack::{report, ResultExt};
use futures::stream::SelectNextSome;
use hyperswitch_domain_models::{
payments as domain_payments,
revenue_recovery::{self, RecoveryPaymentIntent},
router_data_v2::flow_common_types,
router_flow_types,
router_request_types::revenue_recovery as revenue_recovery_request,
router_response_types::revenue_recovery as revenue_recovery_response,
types as router_types,
};
use hyperswitch_interfaces::webhooks as interface_webhooks;
use masking::{PeekInterface, Secret};
use router_env::{instrument, logger, tracing};
use services::kafka;
use storage::business_status;
use crate::{
core::{
self, admin,
errors::{self, CustomResult},
payments::{self, helpers},
},
db::{errors::RevenueRecoveryError, StorageInterface},
routes::{app::ReqState, metrics, SessionState},
services::{
self,
connector_integration_interface::{self, RouterDataConversion},
},
types::{
self, api, domain,
storage::{
revenue_recovery as storage_revenue_recovery,
revenue_recovery_redis_operation::{
PaymentProcessorTokenDetails, PaymentProcessorTokenStatus, RedisTokenManager,
},
},
transformers::ForeignFrom,
},
workflows::revenue_recovery as revenue_recovery_flow,
};
#[cfg(feature = "v2")]
pub const REVENUE_RECOVERY: &str = "revenue_recovery";
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
#[cfg(feature = "revenue_recovery")]
pub async fn recovery_incoming_webhook_flow(
state: SessionState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
source_verified: bool,
connector_enum: &connector_integration_interface::ConnectorEnum,
billing_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
event_type: webhooks::IncomingWebhookEvent,
req_state: ReqState,
object_ref_id: &webhooks::ObjectReferenceId,
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
// Source verification is necessary for revenue recovery webhooks flow since We don't have payment intent/attempt object created before in our system.
common_utils::fp_utils::when(!source_verified, || {
Err(report!(
errors::RevenueRecoveryError::WebhookAuthenticationFailed
))
})?;
let connector = api_enums::Connector::from_str(connector_name)
.change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed)
.attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?;
let billing_connectors_with_invoice_sync_call = &state.conf.billing_connectors_invoice_sync;
let should_billing_connector_invoice_api_called = billing_connectors_with_invoice_sync_call
.billing_connectors_which_requires_invoice_sync_call
.contains(&connector);
let billing_connectors_with_payment_sync_call = &state.conf.billing_connectors_payment_sync;
let should_billing_connector_payment_api_called = billing_connectors_with_payment_sync_call
.billing_connectors_which_require_payment_sync
.contains(&connector);
let billing_connector_payment_details =
BillingConnectorPaymentsSyncResponseData::get_billing_connector_payment_details(
should_billing_connector_payment_api_called,
&state,
&merchant_context,
&billing_connector_account,
connector_name,
object_ref_id,
)
.await?;
let invoice_id = billing_connector_payment_details
.clone()
.map(|data| data.merchant_reference_id);
let billing_connector_invoice_details =
BillingConnectorInvoiceSyncResponseData::get_billing_connector_invoice_details(
should_billing_connector_invoice_api_called,
&state,
&merchant_context,
&billing_connector_account,
connector_name,
invoice_id,
)
.await?;
// Checks whether we have data in billing_connector_invoice_details , if it is there then we construct revenue recovery invoice from it else it takes from webhook
let invoice_details = RevenueRecoveryInvoice::get_recovery_invoice_details(
connector_enum,
request_details,
billing_connector_invoice_details.as_ref(),
)?;
// Fetch the intent using merchant reference id, if not found create new intent.
let payment_intent = invoice_details
.get_payment_intent(&state, &req_state, &merchant_context, &business_profile)
.await
.transpose()
.async_unwrap_or_else(|| async {
invoice_details
.create_payment_intent(&state, &req_state, &merchant_context, &business_profile)
.await
})
.await?;
let is_event_recovery_transaction_event = event_type.is_recovery_transaction_event();
let (recovery_attempt_from_payment_attempt, recovery_intent_from_payment_attempt) =
RevenueRecoveryAttempt::get_recovery_payment_attempt(
is_event_recovery_transaction_event,
&billing_connector_account,
&state,
connector_enum,
&req_state,
billing_connector_payment_details.as_ref(),
request_details,
&merchant_context,
&business_profile,
&payment_intent,
&invoice_details.0,
)
.await?;
// Publish event to Kafka
if let Some(ref attempt) = recovery_attempt_from_payment_attempt {
// Passing `merchant_context` here
let recovery_payment_tuple =
&RecoveryPaymentTuple::new(&recovery_intent_from_payment_attempt, attempt);
if let Err(e) = RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
&state,
recovery_payment_tuple,
None,
)
.await
{
logger::error!(
"Failed to publish revenue recovery event to kafka : {:?}",
e
);
};
}
let attempt_triggered_by = recovery_attempt_from_payment_attempt
.as_ref()
.and_then(|attempt| attempt.get_attempt_triggered_by());
let recovery_action = RecoveryAction {
action: RecoveryAction::get_action(event_type, attempt_triggered_by),
};
let mca_retry_threshold = billing_connector_account
.get_retry_threshold()
.ok_or(report!(
errors::RevenueRecoveryError::BillingThresholdRetryCountFetchFailed
))?;
let intent_retry_count = recovery_intent_from_payment_attempt
.feature_metadata
.as_ref()
.and_then(|metadata| metadata.get_retry_count())
.ok_or(report!(errors::RevenueRecoveryError::RetryCountFetchFailed))?;
logger::info!("Intent retry count: {:?}", intent_retry_count);
recovery_action
.handle_action(
&state,
&business_profile,
&merchant_context,
&billing_connector_account,
mca_retry_threshold,
intent_retry_count,
&(
recovery_attempt_from_payment_attempt,
recovery_intent_from_payment_attempt,
),
)
.await
}
async fn handle_monitoring_threshold(
state: &SessionState,
business_profile: &domain::Profile,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
let db = &*state.store;
let key_manager_state = &(state).into();
let monitoring_threshold_config = state.conf.revenue_recovery.monitoring_threshold_in_seconds;
let retry_algorithm_type = state.conf.revenue_recovery.retry_algorithm_type;
let revenue_recovery_retry_algorithm = business_profile
.revenue_recovery_retry_algorithm_data
.clone()
.ok_or(report!(
errors::RevenueRecoveryError::RetryAlgorithmTypeNotFound
))?;
if revenue_recovery_retry_algorithm
.has_exceeded_monitoring_threshold(monitoring_threshold_config)
{
let profile_wrapper = admin::ProfileWrapper::new(business_profile.clone());
profile_wrapper
.update_revenue_recovery_algorithm_under_profile(
db,
key_manager_state,
key_store,
retry_algorithm_type,
)
.await
.change_context(errors::RevenueRecoveryError::RetryAlgorithmUpdationFailed)?;
}
Ok(webhooks::WebhookResponseTracker::NoEffect)
}
#[allow(clippy::too_many_arguments)]
async fn handle_schedule_failed_payment(
billing_connector_account: &domain::MerchantConnectorAccount,
intent_retry_count: u16,
mca_retry_threshold: u16,
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_attempt_with_recovery_intent: &(
Option<revenue_recovery::RecoveryPaymentAttempt>,
revenue_recovery::RecoveryPaymentIntent,
),
business_profile: &domain::Profile,
revenue_recovery_retry: api_enums::RevenueRecoveryAlgorithmType,
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
let (recovery_attempt_from_payment_attempt, recovery_intent_from_payment_attempt) =
payment_attempt_with_recovery_intent;
// When intent_retry_count is less than or equal to threshold
(intent_retry_count <= mca_retry_threshold)
.then(|| {
logger::error!(
"Payment retry count {} is less than threshold {}",
intent_retry_count,
mca_retry_threshold
);
Ok(webhooks::WebhookResponseTracker::NoEffect)
})
.async_unwrap_or_else(|| async {
// Call calculate_job
core::revenue_recovery::upsert_calculate_pcr_task(
billing_connector_account,
state,
merchant_context,
recovery_intent_from_payment_attempt,
business_profile,
intent_retry_count,
recovery_attempt_from_payment_attempt
.as_ref()
.map(|attempt| attempt.attempt_id.clone()),
storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,
revenue_recovery_retry,
)
.await
})
.await
}
#[derive(Debug)]
pub struct RevenueRecoveryInvoice(revenue_recovery::RevenueRecoveryInvoiceData);
#[derive(Debug)]
pub struct RevenueRecoveryAttempt(revenue_recovery::RevenueRecoveryAttemptData);
impl RevenueRecoveryInvoice {
pub async fn get_or_create_custom_recovery_intent(
data: api_models::payments::RecoveryPaymentsCreate,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
) -> CustomResult<revenue_recovery::RecoveryPaymentIntent, errors::RevenueRecoveryError> {
let recovery_intent = Self(revenue_recovery::RevenueRecoveryInvoiceData::foreign_from(
data,
));
recovery_intent
.get_payment_intent(state, req_state, merchant_context, profile)
.await
.transpose()
.async_unwrap_or_else(|| async {
recovery_intent
.create_payment_intent(state, req_state, merchant_context, profile)
.await
})
.await
}
fn get_recovery_invoice_details(
connector_enum: &connector_integration_interface::ConnectorEnum,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
billing_connector_invoice_details: Option<
&revenue_recovery_response::BillingConnectorInvoiceSyncResponse,
>,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
billing_connector_invoice_details.map_or_else(
|| {
interface_webhooks::IncomingWebhook::get_revenue_recovery_invoice_details(
connector_enum,
request_details,
)
.change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed)
.attach_printable("Failed while getting revenue recovery invoice details")
.map(RevenueRecoveryInvoice)
},
|data| {
Ok(Self(revenue_recovery::RevenueRecoveryInvoiceData::from(
data,
)))
},
)
}
async fn get_payment_intent(
&self,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
) -> CustomResult<Option<revenue_recovery::RecoveryPaymentIntent>, errors::RevenueRecoveryError>
{
let payment_response = Box::pin(payments::payments_get_intent_using_merchant_reference(
state.clone(),
merchant_context.clone(),
profile.clone(),
req_state.clone(),
&self.0.merchant_reference_id,
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await;
let response = match payment_response {
Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => {
let payment_id = payments_response.id.clone();
let status = payments_response.status;
let feature_metadata = payments_response.feature_metadata;
let merchant_id = merchant_context.get_merchant_account().get_id().clone();
let revenue_recovery_invoice_data = &self.0;
Ok(Some(revenue_recovery::RecoveryPaymentIntent {
payment_id,
status,
feature_metadata,
merchant_id,
merchant_reference_id: Some(
revenue_recovery_invoice_data.merchant_reference_id.clone(),
),
invoice_amount: revenue_recovery_invoice_data.amount,
invoice_currency: revenue_recovery_invoice_data.currency,
created_at: revenue_recovery_invoice_data.billing_started_at,
billing_address: revenue_recovery_invoice_data.billing_address.clone(),
}))
}
Err(err)
if matches!(
err.current_context(),
&errors::ApiErrorResponse::PaymentNotFound
) =>
{
Ok(None)
}
Ok(_) => Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed)
.attach_printable("Unexpected response from payment intent core"),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed)
.attach_printable("failed to fetch payment intent recovery webhook flow")
}
}?;
Ok(response)
}
async fn create_payment_intent(
&self,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
) -> CustomResult<revenue_recovery::RecoveryPaymentIntent, errors::RevenueRecoveryError> {
let payload = api_payments::PaymentsCreateIntentRequest::from(&self.0);
let global_payment_id = id_type::GlobalPaymentId::generate(&state.conf.cell_information.id);
let create_intent_response = Box::pin(payments::payments_intent_core::<
router_flow_types::payments::PaymentCreateIntent,
api_payments::PaymentsIntentResponse,
_,
_,
hyperswitch_domain_models::payments::PaymentIntentData<
router_flow_types::payments::PaymentCreateIntent,
>,
>(
state.clone(),
req_state.clone(),
merchant_context.clone(),
profile.clone(),
payments::operations::PaymentIntentCreate,
payload,
global_payment_id,
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await
.change_context(errors::RevenueRecoveryError::PaymentIntentCreateFailed)?;
let response = create_intent_response
.get_json_body()
.change_context(errors::RevenueRecoveryError::PaymentIntentCreateFailed)
.attach_printable("expected json response")?;
let merchant_id = merchant_context.get_merchant_account().get_id().clone();
let revenue_recovery_invoice_data = &self.0;
Ok(revenue_recovery::RecoveryPaymentIntent {
payment_id: response.id,
status: response.status,
feature_metadata: response.feature_metadata,
merchant_id,
merchant_reference_id: Some(
revenue_recovery_invoice_data.merchant_reference_id.clone(),
),
invoice_amount: revenue_recovery_invoice_data.amount,
invoice_currency: revenue_recovery_invoice_data.currency,
created_at: revenue_recovery_invoice_data.billing_started_at,
billing_address: revenue_recovery_invoice_data.billing_address.clone(),
})
}
}
impl RevenueRecoveryAttempt {
pub async fn load_recovery_attempt_from_api(
data: api_models::payments::RecoveryPaymentsCreate,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
payment_intent: revenue_recovery::RecoveryPaymentIntent,
payment_merchant_connector_account: domain::MerchantConnectorAccount,
) -> CustomResult<
(
revenue_recovery::RecoveryPaymentAttempt,
revenue_recovery::RecoveryPaymentIntent,
),
errors::RevenueRecoveryError,
> {
let recovery_attempt = Self(revenue_recovery::RevenueRecoveryAttemptData::foreign_from(
&data,
));
recovery_attempt
.get_payment_attempt(state, req_state, merchant_context, profile, &payment_intent)
.await
.transpose()
.async_unwrap_or_else(|| async {
recovery_attempt
.record_payment_attempt(
state,
req_state,
merchant_context,
profile,
&payment_intent,
&data.billing_merchant_connector_id,
Some(payment_merchant_connector_account),
)
.await
})
.await
}
fn get_recovery_invoice_transaction_details(
connector_enum: &connector_integration_interface::ConnectorEnum,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
billing_connector_payment_details: Option<
&revenue_recovery_response::BillingConnectorPaymentsSyncResponse,
>,
billing_connector_invoice_details: &revenue_recovery::RevenueRecoveryInvoiceData,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
billing_connector_payment_details.map_or_else(
|| {
interface_webhooks::IncomingWebhook::get_revenue_recovery_attempt_details(
connector_enum,
request_details,
)
.change_context(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed)
.attach_printable(
"Failed to get recovery attempt details from the billing connector",
)
.map(RevenueRecoveryAttempt)
},
|data| {
Ok(Self(revenue_recovery::RevenueRecoveryAttemptData::from((
data,
billing_connector_invoice_details,
))))
},
)
}
pub fn get_revenue_recovery_attempt(
payment_intent: &domain_payments::PaymentIntent,
revenue_recovery_metadata: &api_payments::PaymentRevenueRecoveryMetadata,
billing_connector_account: &domain::MerchantConnectorAccount,
card_info: api_payments::AdditionalCardInfo,
payment_processor_token: &str,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
let revenue_recovery_data = payment_intent
.create_revenue_recovery_attempt_data(
revenue_recovery_metadata.clone(),
billing_connector_account,
card_info,
payment_processor_token,
)
.change_context(errors::RevenueRecoveryError::RevenueRecoveryAttemptDataCreateFailed)
.attach_printable("Failed to build recovery attempt data")?;
Ok(Self(revenue_recovery_data))
}
async fn get_payment_attempt(
&self,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
payment_intent: &revenue_recovery::RecoveryPaymentIntent,
) -> CustomResult<
Option<(
revenue_recovery::RecoveryPaymentAttempt,
revenue_recovery::RecoveryPaymentIntent,
)>,
errors::RevenueRecoveryError,
> {
let attempt_response =
Box::pin(payments::payments_list_attempts_using_payment_intent_id::<
payments::operations::PaymentGetListAttempts,
api_payments::PaymentAttemptListResponse,
_,
payments::operations::payment_attempt_list::PaymentGetListAttempts,
hyperswitch_domain_models::payments::PaymentAttemptListData<
payments::operations::PaymentGetListAttempts,
>,
>(
state.clone(),
req_state.clone(),
merchant_context.clone(),
profile.clone(),
payments::operations::PaymentGetListAttempts,
api_payments::PaymentAttemptListRequest {
payment_intent_id: payment_intent.payment_id.clone(),
},
payment_intent.payment_id.clone(),
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await;
let response = match attempt_response {
Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => {
let final_attempt = self
.0
.charge_id
.as_ref()
.map(|charge_id| {
payments_response
.find_attempt_in_attempts_list_using_charge_id(charge_id.clone())
})
.unwrap_or_else(|| {
self.0
.connector_transaction_id
.as_ref()
.and_then(|transaction_id| {
payments_response
.find_attempt_in_attempts_list_using_connector_transaction_id(
transaction_id,
)
})
});
let payment_attempt =
final_attempt.map(|res| revenue_recovery::RecoveryPaymentAttempt {
attempt_id: res.id.to_owned(),
attempt_status: res.status.to_owned(),
feature_metadata: res.feature_metadata.to_owned(),
amount: res.amount.net_amount,
network_advice_code: res.error.clone().and_then(|e| e.network_advice_code), // Placeholder, to be populated if available
network_decline_code: res
.error
.clone()
.and_then(|e| e.network_decline_code), // Placeholder, to be populated if available
error_code: res.error.clone().map(|error| error.code),
created_at: res.created_at,
});
// If we have an attempt, combine it with payment_intent in a tuple.
let res_with_payment_intent_and_attempt =
payment_attempt.map(|attempt| (attempt, (*payment_intent).clone()));
Ok(res_with_payment_intent_and_attempt)
}
Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("Unexpected response from payment intent core"),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("failed to fetch payment attempt in recovery webhook flow")
}
}?;
Ok(response)
}
#[allow(clippy::too_many_arguments)]
async fn record_payment_attempt(
&self,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
payment_intent: &revenue_recovery::RecoveryPaymentIntent,
billing_connector_account_id: &id_type::MerchantConnectorAccountId,
payment_connector_account: Option<domain::MerchantConnectorAccount>,
) -> CustomResult<
(
revenue_recovery::RecoveryPaymentAttempt,
revenue_recovery::RecoveryPaymentIntent,
),
errors::RevenueRecoveryError,
> {
let payment_connector_id = payment_connector_account.as_ref().map(|account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount| account.id.clone());
let payment_connector_name = payment_connector_account
.as_ref()
.map(|account| account.connector_name);
let request_payload: api_payments::PaymentsAttemptRecordRequest = self
.create_payment_record_request(
state,
billing_connector_account_id,
payment_connector_id,
payment_connector_name,
common_enums::TriggeredBy::External,
)
.await?;
let attempt_response = Box::pin(payments::record_attempt_core(
state.clone(),
req_state.clone(),
merchant_context.clone(),
profile.clone(),
request_payload,
payment_intent.payment_id.clone(),
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await;
let (recovery_attempt, updated_recovery_intent) = match attempt_response {
Ok(services::ApplicationResponse::JsonWithHeaders((attempt_response, _))) => {
Ok((
revenue_recovery::RecoveryPaymentAttempt {
attempt_id: attempt_response.id.clone(),
attempt_status: attempt_response.status,
feature_metadata: attempt_response.payment_attempt_feature_metadata,
amount: attempt_response.amount,
network_advice_code: attempt_response
.error_details
.clone()
.and_then(|error| error.network_decline_code), // Placeholder, to be populated if available
network_decline_code: attempt_response
.error_details
.clone()
.and_then(|error| error.network_decline_code), // Placeholder, to be populated if available
error_code: attempt_response
.error_details
.clone()
.map(|error| error.code),
created_at: attempt_response.created_at,
},
revenue_recovery::RecoveryPaymentIntent {
payment_id: payment_intent.payment_id.clone(),
status: attempt_response.status.into(), // Using status from attempt_response
feature_metadata: attempt_response.payment_intent_feature_metadata, // Using feature_metadata from attempt_response
merchant_id: payment_intent.merchant_id.clone(),
merchant_reference_id: payment_intent.merchant_reference_id.clone(),
invoice_amount: payment_intent.invoice_amount,
invoice_currency: payment_intent.invoice_currency,
created_at: payment_intent.created_at,
billing_address: payment_intent.billing_address.clone(),
},
))
}
Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("Unexpected response from record attempt core"),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("failed to record attempt in recovery webhook flow")
}
}?;
let response = (recovery_attempt, updated_recovery_intent);
self.store_payment_processor_tokens_in_redis(state, &response.0, payment_connector_name)
.await
.map_err(|e| {
router_env::logger::error!(
"Failed to store payment processor tokens in Redis: {:?}",
e
);
errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed
})?;
Ok(response)
}
pub async fn create_payment_record_request(
&self,
state: &SessionState,
billing_merchant_connector_account_id: &id_type::MerchantConnectorAccountId,
payment_merchant_connector_account_id: Option<id_type::MerchantConnectorAccountId>,
payment_connector: Option<common_enums::connector_enums::Connector>,
triggered_by: common_enums::TriggeredBy,
) -> CustomResult<api_payments::PaymentsAttemptRecordRequest, errors::RevenueRecoveryError>
{
let revenue_recovery_attempt_data = &self.0;
let amount_details =
api_payments::PaymentAttemptAmountDetails::from(revenue_recovery_attempt_data);
let feature_metadata = api_payments::PaymentAttemptFeatureMetadata {
revenue_recovery: Some(api_payments::PaymentAttemptRevenueRecoveryData {
// Since we are recording the external paymenmt attempt, this is hardcoded to External
attempt_triggered_by: triggered_by,
charge_id: self.0.charge_id.clone(),
}),
};
let card_info = revenue_recovery_attempt_data
.card_info
.card_isin
.clone()
.async_and_then(|isin| async move {
let issuer_identifier_number = isin.clone();
state
.store
.get_card_info(issuer_identifier_number.as_str())
.await
.map_err(|error| services::logger::warn!(card_info_error=?error))
.ok()
})
.await
.flatten();
let payment_method_data = api_models::payments::RecordAttemptPaymentMethodDataRequest {
payment_method_data: api_models::payments::AdditionalPaymentData::Card(Box::new(
revenue_recovery_attempt_data.card_info.clone(),
)),
billing: None,
};
let card_issuer = revenue_recovery_attempt_data.card_info.card_issuer.clone();
let error =
Option::<api_payments::RecordAttemptErrorDetails>::from(revenue_recovery_attempt_data);
Ok(api_payments::PaymentsAttemptRecordRequest {
amount_details,
status: revenue_recovery_attempt_data.status,
billing: None,
shipping: None,
connector: payment_connector,
payment_merchant_connector_id: payment_merchant_connector_account_id,
error,
description: None,
connector_transaction_id: revenue_recovery_attempt_data
.connector_transaction_id
.clone(),
payment_method_type: revenue_recovery_attempt_data.payment_method_type,
billing_connector_id: billing_merchant_connector_account_id.clone(),
payment_method_subtype: revenue_recovery_attempt_data.payment_method_sub_type,
payment_method_data: Some(payment_method_data),
metadata: None,
feature_metadata: Some(feature_metadata),
transaction_created_at: revenue_recovery_attempt_data.transaction_created_at,
processor_payment_method_token: revenue_recovery_attempt_data
.processor_payment_method_token
.clone(),
connector_customer_id: revenue_recovery_attempt_data.connector_customer_id.clone(),
retry_count: revenue_recovery_attempt_data.retry_count,
invoice_next_billing_time: revenue_recovery_attempt_data.invoice_next_billing_time,
invoice_billing_started_at_time: revenue_recovery_attempt_data
.invoice_billing_started_at_time,
triggered_by,
card_network: revenue_recovery_attempt_data.card_info.card_network.clone(),
card_issuer,
})
}
pub async fn find_payment_merchant_connector_account(
&self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
billing_connector_account: &domain::MerchantConnectorAccount,
) -> CustomResult<Option<domain::MerchantConnectorAccount>, errors::RevenueRecoveryError> {
let payment_merchant_connector_account_id = billing_connector_account
.get_payment_merchant_connector_account_id_using_account_reference_id(
self.0.connector_account_reference_id.clone(),
);
let db = &*state.store;
let key_manager_state = &(state).into();
let payment_merchant_connector_account = payment_merchant_connector_account_id
.as_ref()
.async_map(|mca_id| async move {
db.find_merchant_connector_account_by_id(key_manager_state, mca_id, key_store)
.await
})
.await
.transpose()
.change_context(errors::RevenueRecoveryError::PaymentMerchantConnectorAccountNotFound)
.attach_printable(
"failed to fetch payment merchant connector id using account reference id",
)?;
Ok(payment_merchant_connector_account)
}
#[allow(clippy::too_many_arguments)]
async fn get_recovery_payment_attempt(
is_recovery_transaction_event: bool,
billing_connector_account: &domain::MerchantConnectorAccount,
state: &SessionState,
connector_enum: &connector_integration_interface::ConnectorEnum,
req_state: &ReqState,
billing_connector_payment_details: Option<
&revenue_recovery_response::BillingConnectorPaymentsSyncResponse,
>,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
payment_intent: &revenue_recovery::RecoveryPaymentIntent,
invoice_details: &revenue_recovery::RevenueRecoveryInvoiceData,
) -> CustomResult<
(
Option<revenue_recovery::RecoveryPaymentAttempt>,
revenue_recovery::RecoveryPaymentIntent,
),
errors::RevenueRecoveryError,
> {
let payment_attempt_with_recovery_intent = match is_recovery_transaction_event {
true => {
let invoice_transaction_details = Self::get_recovery_invoice_transaction_details(
connector_enum,
request_details,
billing_connector_payment_details,
invoice_details,
)?;
// Find the payment merchant connector ID at the top level to avoid multiple DB calls.
let payment_merchant_connector_account = invoice_transaction_details
.find_payment_merchant_connector_account(
state,
merchant_context.get_merchant_key_store(),
billing_connector_account,
)
.await?;
let (payment_attempt, updated_payment_intent) = invoice_transaction_details
.get_payment_attempt(
state,
req_state,
merchant_context,
business_profile,
payment_intent,
)
.await
.transpose()
.async_unwrap_or_else(|| async {
invoice_transaction_details
.record_payment_attempt(
state,
req_state,
merchant_context,
business_profile,
payment_intent,
&billing_connector_account.get_id(),
payment_merchant_connector_account,
)
.await
})
.await?;
(Some(payment_attempt), updated_payment_intent)
}
false => (None, payment_intent.clone()),
};
Ok(payment_attempt_with_recovery_intent)
}
/// Store payment processor tokens in Redis for retry management
async fn store_payment_processor_tokens_in_redis(
&self,
state: &SessionState,
recovery_attempt: &revenue_recovery::RecoveryPaymentAttempt,
payment_connector_name: Option<common_enums::connector_enums::Connector>,
) -> CustomResult<(), errors::RevenueRecoveryError> {
let revenue_recovery_attempt_data = &self.0;
let error_code = revenue_recovery_attempt_data.error_code.clone();
let error_message = revenue_recovery_attempt_data.error_message.clone();
let connector_name = payment_connector_name
.ok_or(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed)
.attach_printable("unable to derive payment connector")?
.to_string();
let gsm_record = helpers::get_gsm_record(
state,
error_code.clone(),
error_message,
connector_name,
REVENUE_RECOVERY.to_string(),
)
.await;
let is_hard_decline = gsm_record
.and_then(|record| record.error_category)
.map(|category| category == common_enums::ErrorCategory::HardDecline)
.unwrap_or(false);
// Extract required fields from the revenue recovery attempt data
let connector_customer_id = revenue_recovery_attempt_data.connector_customer_id.clone();
let attempt_id = recovery_attempt.attempt_id.clone();
let token_unit = PaymentProcessorTokenStatus {
error_code,
inserted_by_attempt_id: attempt_id.clone(),
daily_retry_history: HashMap::from([(recovery_attempt.created_at.date(), 1)]),
scheduled_at: None,
is_hard_decline: Some(is_hard_decline),
payment_processor_token_details: PaymentProcessorTokenDetails {
payment_processor_token: revenue_recovery_attempt_data
.processor_payment_method_token
.clone(),
expiry_month: revenue_recovery_attempt_data
.card_info
.card_exp_month
.clone(),
expiry_year: revenue_recovery_attempt_data
.card_info
.card_exp_year
.clone(),
card_issuer: revenue_recovery_attempt_data.card_info.card_issuer.clone(),
last_four_digits: revenue_recovery_attempt_data.card_info.last4.clone(),
card_network: revenue_recovery_attempt_data.card_info.card_network.clone(),
card_type: revenue_recovery_attempt_data.card_info.card_type.clone(),
},
};
// Make the Redis call to store tokens
RedisTokenManager::upsert_payment_processor_token(
state,
&connector_customer_id,
token_unit,
)
.await
.change_context(errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed)
.attach_printable("Failed to store payment processor tokens in Redis")?;
Ok(())
}
}
pub struct BillingConnectorPaymentsSyncResponseData(
revenue_recovery_response::BillingConnectorPaymentsSyncResponse,
);
pub struct BillingConnectorPaymentsSyncFlowRouterData(
router_types::BillingConnectorPaymentsSyncRouterData,
);
impl BillingConnectorPaymentsSyncResponseData {
async fn handle_billing_connector_payment_sync_call(
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
id: &str,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
None,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("invalid connector name received in payment attempt")?;
let connector_integration: services::BoxedBillingConnectorPaymentsSyncIntegrationInterface<
router_flow_types::BillingConnectorPaymentsSync,
revenue_recovery_request::BillingConnectorPaymentsSyncRequest,
revenue_recovery_response::BillingConnectorPaymentsSyncResponse,
> = connector_data.connector.get_connector_integration();
let router_data =
BillingConnectorPaymentsSyncFlowRouterData::construct_router_data_for_billing_connector_payment_sync_call(
state,
connector_name,
merchant_connector_account,
merchant_context,
id,
)
.await
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable(
"Failed while constructing router data for billing connector psync call",
)?
.inner();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("Failed while fetching billing connector payment details")?;
let additional_recovery_details = match response.response {
Ok(response) => Ok(response),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("Failed while fetching billing connector payment details")
}
}?;
Ok(Self(additional_recovery_details))
}
async fn get_billing_connector_payment_details(
should_billing_connector_payment_api_called: bool,
state: &SessionState,
merchant_context: &domain::MerchantContext,
billing_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
object_ref_id: &webhooks::ObjectReferenceId,
) -> CustomResult<
Option<revenue_recovery_response::BillingConnectorPaymentsSyncResponse>,
errors::RevenueRecoveryError,
> {
let response_data = match should_billing_connector_payment_api_called {
true => {
let billing_connector_transaction_id = object_ref_id
.clone()
.get_connector_transaction_id_as_string()
.change_context(
errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed,
)
.attach_printable("Billing connector Payments api call failed")?;
let billing_connector_payment_details =
Self::handle_billing_connector_payment_sync_call(
state,
merchant_context,
billing_connector_account,
connector_name,
&billing_connector_transaction_id,
)
.await?;
Some(billing_connector_payment_details.inner())
}
false => None,
};
Ok(response_data)
}
fn inner(self) -> revenue_recovery_response::BillingConnectorPaymentsSyncResponse {
self.0
}
}
impl BillingConnectorPaymentsSyncFlowRouterData {
async fn construct_router_data_for_billing_connector_payment_sync_call(
state: &SessionState,
connector_name: &str,
merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
merchant_context: &domain::MerchantContext,
billing_connector_psync_id: &str,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
let auth_type: types::ConnectorAuthType = helpers::MerchantConnectorAccountType::DbVal(
Box::new(merchant_connector_account.clone()),
)
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)?;
let connector = common_enums::connector_enums::Connector::from_str(connector_name)
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)
.attach_printable("Cannot find connector from the connector_name")?;
let connector_params =
hyperswitch_domain_models::connector_endpoints::Connectors::get_connector_params(
&state.conf.connectors,
connector,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable(format!(
"cannot find connector params for this connector {connector} in this flow",
))?;
let router_data = types::RouterDataV2 {
flow: PhantomData::<router_flow_types::BillingConnectorPaymentsSync>,
tenant_id: state.tenant.tenant_id.clone(),
resource_common_data: flow_common_types::BillingConnectorPaymentsSyncFlowData,
connector_auth_type: auth_type,
request: revenue_recovery_request::BillingConnectorPaymentsSyncRequest {
connector_params,
billing_connector_psync_id: billing_connector_psync_id.to_string(),
},
response: Err(types::ErrorResponse::default()),
};
let old_router_data =
flow_common_types::BillingConnectorPaymentsSyncFlowData::to_old_router_data(
router_data,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable(
"Cannot construct router data for making the billing connector payments api call",
)?;
Ok(Self(old_router_data))
}
fn inner(self) -> router_types::BillingConnectorPaymentsSyncRouterData {
self.0
}
}
pub struct BillingConnectorInvoiceSyncResponseData(
revenue_recovery_response::BillingConnectorInvoiceSyncResponse,
);
pub struct BillingConnectorInvoiceSyncFlowRouterData(
router_types::BillingConnectorInvoiceSyncRouterData,
);
impl BillingConnectorInvoiceSyncResponseData {
async fn handle_billing_connector_invoice_sync_call(
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
id: &str,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
None,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)
.attach_printable("invalid connector name received in payment attempt")?;
let connector_integration: services::BoxedBillingConnectorInvoiceSyncIntegrationInterface<
router_flow_types::BillingConnectorInvoiceSync,
revenue_recovery_request::BillingConnectorInvoiceSyncRequest,
revenue_recovery_response::BillingConnectorInvoiceSyncResponse,
> = connector_data.connector.get_connector_integration();
let router_data =
BillingConnectorInvoiceSyncFlowRouterData::construct_router_data_for_billing_connector_invoice_sync_call(
state,
connector_name,
merchant_connector_account,
merchant_context,
id,
)
.await
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)
.attach_printable(
"Failed while constructing router data for billing connector psync call",
)?
.inner();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)
.attach_printable("Failed while fetching billing connector Invoice details")?;
let additional_recovery_details = match response.response {
Ok(response) => Ok(response),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("Failed while fetching billing connector Invoice details")
}
}?;
Ok(Self(additional_recovery_details))
}
async fn get_billing_connector_invoice_details(
should_billing_connector_invoice_api_called: bool,
state: &SessionState,
merchant_context: &domain::MerchantContext,
billing_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
merchant_reference_id: Option<id_type::PaymentReferenceId>,
) -> CustomResult<
Option<revenue_recovery_response::BillingConnectorInvoiceSyncResponse>,
errors::RevenueRecoveryError,
> {
let response_data = match should_billing_connector_invoice_api_called {
true => {
let billing_connector_invoice_id = merchant_reference_id
.as_ref()
.map(|id| id.get_string_repr())
.ok_or(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)?;
let billing_connector_invoice_details =
Self::handle_billing_connector_invoice_sync_call(
state,
merchant_context,
billing_connector_account,
connector_name,
billing_connector_invoice_id,
)
.await?;
Some(billing_connector_invoice_details.inner())
}
false => None,
};
Ok(response_data)
}
fn inner(self) -> revenue_recovery_response::BillingConnectorInvoiceSyncResponse {
self.0
}
}
impl BillingConnectorInvoiceSyncFlowRouterData {
async fn construct_router_data_for_billing_connector_invoice_sync_call(
state: &SessionState,
connector_name: &str,
merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
merchant_context: &domain::MerchantContext,
billing_connector_invoice_id: &str,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
let auth_type: types::ConnectorAuthType = helpers::MerchantConnectorAccountType::DbVal(
Box::new(merchant_connector_account.clone()),
)
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)?;
let connector = common_enums::connector_enums::Connector::from_str(connector_name)
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)
.attach_printable("Cannot find connector from the connector_name")?;
let connector_params =
hyperswitch_domain_models::connector_endpoints::Connectors::get_connector_params(
&state.conf.connectors,
connector,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable(format!(
"cannot find connector params for this connector {connector} in this flow",
))?;
let router_data = types::RouterDataV2 {
flow: PhantomData::<router_flow_types::BillingConnectorInvoiceSync>,
tenant_id: state.tenant.tenant_id.clone(),
resource_common_data: flow_common_types::BillingConnectorInvoiceSyncFlowData,
connector_auth_type: auth_type,
request: revenue_recovery_request::BillingConnectorInvoiceSyncRequest {
billing_connector_invoice_id: billing_connector_invoice_id.to_string(),
connector_params,
},
response: Err(types::ErrorResponse::default()),
};
let old_router_data =
flow_common_types::BillingConnectorInvoiceSyncFlowData::to_old_router_data(
router_data,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)
.attach_printable(
"Cannot construct router data for making the billing connector invoice api call",
)?;
Ok(Self(old_router_data))
}
fn inner(self) -> router_types::BillingConnectorInvoiceSyncRouterData {
self.0
}
}
#[derive(Clone, Debug)]
pub struct RecoveryPaymentTuple(
revenue_recovery::RecoveryPaymentIntent,
revenue_recovery::RecoveryPaymentAttempt,
);
impl RecoveryPaymentTuple {
pub fn new(
payment_intent: &revenue_recovery::RecoveryPaymentIntent,
payment_attempt: &revenue_recovery::RecoveryPaymentAttempt,
) -> Self {
Self(payment_intent.clone(), payment_attempt.clone())
}
pub async fn publish_revenue_recovery_event_to_kafka(
state: &SessionState,
recovery_payment_tuple: &Self,
retry_count: Option<i32>,
) -> CustomResult<(), errors::RevenueRecoveryError> {
let recovery_payment_intent = &recovery_payment_tuple.0;
let recovery_payment_attempt = &recovery_payment_tuple.1;
let revenue_recovery_feature_metadata = recovery_payment_intent
.feature_metadata
.as_ref()
.and_then(|metadata| metadata.revenue_recovery.as_ref());
let billing_city = recovery_payment_intent
.billing_address
.as_ref()
.and_then(|billing_address| billing_address.address.as_ref())
.and_then(|address| address.city.clone())
.map(Secret::new);
let billing_state = recovery_payment_intent
.billing_address
.as_ref()
.and_then(|billing_address| billing_address.address.as_ref())
.and_then(|address| address.state.clone());
let billing_country = recovery_payment_intent
.billing_address
.as_ref()
.and_then(|billing_address| billing_address.address.as_ref())
.and_then(|address| address.country);
let card_info = revenue_recovery_feature_metadata.and_then(|metadata| {
metadata
.billing_connector_payment_method_details
.as_ref()
.and_then(|details| details.get_billing_connector_card_info())
});
#[allow(clippy::as_conversions)]
let retry_count = Some(retry_count.unwrap_or_else(|| {
revenue_recovery_feature_metadata
.map(|data| data.total_retry_count as i32)
.unwrap_or(0)
}));
let event = kafka::revenue_recovery::RevenueRecovery {
merchant_id: &recovery_payment_intent.merchant_id,
invoice_amount: recovery_payment_intent.invoice_amount,
invoice_currency: &recovery_payment_intent.invoice_currency,
invoice_date: revenue_recovery_feature_metadata.and_then(|data| {
data.invoice_billing_started_at_time
.map(|time| time.assume_utc())
}),
invoice_due_date: revenue_recovery_feature_metadata
.and_then(|data| data.invoice_next_billing_time.map(|time| time.assume_utc())),
billing_city,
billing_country: billing_country.as_ref(),
billing_state,
attempt_amount: recovery_payment_attempt.amount,
attempt_currency: &recovery_payment_intent.invoice_currency.clone(),
attempt_status: &recovery_payment_attempt.attempt_status.clone(),
pg_error_code: recovery_payment_attempt.error_code.clone(),
network_advice_code: recovery_payment_attempt.network_advice_code.clone(),
network_error_code: recovery_payment_attempt.network_decline_code.clone(),
first_pg_error_code: revenue_recovery_feature_metadata
.and_then(|data| data.first_payment_attempt_pg_error_code.clone()),
first_network_advice_code: revenue_recovery_feature_metadata
.and_then(|data| data.first_payment_attempt_network_advice_code.clone()),
first_network_error_code: revenue_recovery_feature_metadata
.and_then(|data| data.first_payment_attempt_network_decline_code.clone()),
attempt_created_at: recovery_payment_attempt.created_at.assume_utc(),
payment_method_type: revenue_recovery_feature_metadata
.map(|data| &data.payment_method_type),
payment_method_subtype: revenue_recovery_feature_metadata
.map(|data| &data.payment_method_subtype),
card_network: card_info
.as_ref()
.and_then(|info| info.card_network.as_ref()),
card_issuer: card_info.and_then(|data| data.card_issuer.clone()),
retry_count,
payment_gateway: revenue_recovery_feature_metadata.map(|data| data.connector),
};
state.event_handler.log_event(&event);
Ok(())
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct RecoveryAction {
pub action: common_types::payments::RecoveryAction,
}
impl RecoveryAction {
pub fn get_action(
event_type: webhooks::IncomingWebhookEvent,
attempt_triggered_by: Option<common_enums::TriggeredBy>,
) -> common_types::payments::RecoveryAction {
match event_type {
webhooks::IncomingWebhookEvent::PaymentIntentFailure
| webhooks::IncomingWebhookEvent::PaymentIntentSuccess
| webhooks::IncomingWebhookEvent::PaymentIntentProcessing
| webhooks::IncomingWebhookEvent::PaymentIntentPartiallyFunded
| webhooks::IncomingWebhookEvent::PaymentIntentCancelled
| webhooks::IncomingWebhookEvent::PaymentIntentCancelFailure
| webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationSuccess
| webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationFailure
| webhooks::IncomingWebhookEvent::PaymentIntentCaptureSuccess
| webhooks::IncomingWebhookEvent::PaymentIntentCaptureFailure
| webhooks::IncomingWebhookEvent::PaymentIntentExpired
| webhooks::IncomingWebhookEvent::PaymentActionRequired
| webhooks::IncomingWebhookEvent::EventNotSupported
| webhooks::IncomingWebhookEvent::SourceChargeable
| webhooks::IncomingWebhookEvent::SourceTransactionCreated
| webhooks::IncomingWebhookEvent::RefundFailure
| webhooks::IncomingWebhookEvent::RefundSuccess
| webhooks::IncomingWebhookEvent::DisputeOpened
| webhooks::IncomingWebhookEvent::DisputeExpired
| webhooks::IncomingWebhookEvent::DisputeAccepted
| webhooks::IncomingWebhookEvent::DisputeCancelled
| webhooks::IncomingWebhookEvent::DisputeChallenged
| webhooks::IncomingWebhookEvent::DisputeWon
| webhooks::IncomingWebhookEvent::DisputeLost
| webhooks::IncomingWebhookEvent::MandateActive
| webhooks::IncomingWebhookEvent::MandateRevoked
| webhooks::IncomingWebhookEvent::EndpointVerification
| webhooks::IncomingWebhookEvent::PaymentIntentExtendAuthorizationSuccess
| webhooks::IncomingWebhookEvent::PaymentIntentExtendAuthorizationFailure
| webhooks::IncomingWebhookEvent::ExternalAuthenticationARes
| webhooks::IncomingWebhookEvent::FrmApproved
| webhooks::IncomingWebhookEvent::FrmRejected
| webhooks::IncomingWebhookEvent::PayoutSuccess
| webhooks::IncomingWebhookEvent::PayoutFailure
| webhooks::IncomingWebhookEvent::PayoutProcessing
| webhooks::IncomingWebhookEvent::PayoutCancelled
| webhooks::IncomingWebhookEvent::PayoutCreated
| webhooks::IncomingWebhookEvent::PayoutExpired
| webhooks::IncomingWebhookEvent::PayoutReversed
| webhooks::IncomingWebhookEvent::InvoiceGenerated
| webhooks::IncomingWebhookEvent::SetupWebhook => {
common_types::payments::RecoveryAction::InvalidAction
}
webhooks::IncomingWebhookEvent::RecoveryPaymentFailure => match attempt_triggered_by {
Some(common_enums::TriggeredBy::Internal) => {
common_types::payments::RecoveryAction::NoAction
}
Some(common_enums::TriggeredBy::External) | None => {
common_types::payments::RecoveryAction::ScheduleFailedPayment
}
},
webhooks::IncomingWebhookEvent::RecoveryPaymentSuccess => match attempt_triggered_by {
Some(common_enums::TriggeredBy::Internal) => {
common_types::payments::RecoveryAction::NoAction
}
Some(common_enums::TriggeredBy::External) | None => {
common_types::payments::RecoveryAction::SuccessPaymentExternal
}
},
webhooks::IncomingWebhookEvent::RecoveryPaymentPending => {
common_types::payments::RecoveryAction::PendingPayment
}
webhooks::IncomingWebhookEvent::RecoveryInvoiceCancel => {
common_types::payments::RecoveryAction::CancelInvoice
}
}
}
#[allow(clippy::too_many_arguments)]
pub async fn handle_action(
&self,
state: &SessionState,
business_profile: &domain::Profile,
merchant_context: &domain::MerchantContext,
billing_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
mca_retry_threshold: u16,
intent_retry_count: u16,
recovery_tuple: &(
Option<revenue_recovery::RecoveryPaymentAttempt>,
revenue_recovery::RecoveryPaymentIntent,
),
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
match self.action {
common_types::payments::RecoveryAction::CancelInvoice => todo!(),
common_types::payments::RecoveryAction::ScheduleFailedPayment => {
let recovery_algorithm_type = business_profile
.revenue_recovery_retry_algorithm_type
.ok_or(report!(
errors::RevenueRecoveryError::RetryAlgorithmTypeNotFound
))?;
match recovery_algorithm_type {
api_enums::RevenueRecoveryAlgorithmType::Monitoring => {
handle_monitoring_threshold(
state,
business_profile,
merchant_context.get_merchant_key_store(),
)
.await
}
revenue_recovery_retry_type => {
handle_schedule_failed_payment(
billing_connector_account,
intent_retry_count,
mca_retry_threshold,
state,
merchant_context,
recovery_tuple,
business_profile,
revenue_recovery_retry_type,
)
.await
}
}
}
common_types::payments::RecoveryAction::SuccessPaymentExternal => {
logger::info!("Payment has been succeeded via external system");
Ok(webhooks::WebhookResponseTracker::NoEffect)
}
common_types::payments::RecoveryAction::PendingPayment => {
logger::info!(
"Pending transactions are not consumed by the revenue recovery webhooks"
);
Ok(webhooks::WebhookResponseTracker::NoEffect)
}
common_types::payments::RecoveryAction::NoAction => {
logger::info!(
"No Recovery action is taken place for recovery event and attempt triggered_by"
);
Ok(webhooks::WebhookResponseTracker::NoEffect)
}
common_types::payments::RecoveryAction::InvalidAction => {
logger::error!("Invalid Revenue recovery action state has been received");
Ok(webhooks::WebhookResponseTracker::NoEffect)
}
}
}
}
| {
"crate": "router",
"file": "crates/router/src/core/webhooks/recovery_incoming.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 4,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_5254052251124823032 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/payment_methods/surcharge_decision_configs.rs
// Contains: 1 structs, 0 enums
use api_models::{
payment_methods::SurchargeDetailsResponse,
payments, routing,
surcharge_decision_configs::{self, SurchargeDecisionConfigs, SurchargeDecisionManagerRecord},
};
#[cfg(feature = "v1")]
use common_utils::{ext_traits::StringExt, types as common_utils_types};
#[cfg(feature = "v2")]
use common_utils::{
ext_traits::{OptionExt, StringExt},
types as common_utils_types,
};
use error_stack::{self, ResultExt};
use euclid::{
backend,
backend::{inputs as dsl_inputs, EuclidBackend},
};
use router_env::{instrument, logger, tracing};
use serde::{Deserialize, Serialize};
use storage_impl::redis::cache::{self, SURCHARGE_CACHE};
use crate::{
core::{
errors::{self, ConditionalConfigError as ConfigError},
payments::{
conditional_configs::ConditionalConfigResult, routing::make_dsl_input_for_surcharge,
types,
},
},
db::StorageInterface,
types::{
storage::{self, payment_attempt::PaymentAttemptExt},
transformers::ForeignTryFrom,
},
SessionState,
};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct VirInterpreterBackendCacheWrapper {
cached_algorithm: backend::VirInterpreterBackend<SurchargeDecisionConfigs>,
merchant_surcharge_configs: surcharge_decision_configs::MerchantSurchargeConfigs,
}
impl TryFrom<SurchargeDecisionManagerRecord> for VirInterpreterBackendCacheWrapper {
type Error = error_stack::Report<ConfigError>;
fn try_from(value: SurchargeDecisionManagerRecord) -> Result<Self, Self::Error> {
let cached_algorithm = backend::VirInterpreterBackend::with_program(value.algorithm)
.change_context(ConfigError::DslBackendInitError)
.attach_printable("Error initializing DSL interpreter backend")?;
let merchant_surcharge_configs = value.merchant_surcharge_configs;
Ok(Self {
cached_algorithm,
merchant_surcharge_configs,
})
}
}
enum SurchargeSource {
/// Surcharge will be generated through the surcharge rules
Generate(VirInterpreterBackendCacheWrapper),
/// Surcharge is predefined by the merchant through payment create request
Predetermined(payments::RequestSurchargeDetails),
}
impl SurchargeSource {
pub fn generate_surcharge_details_and_populate_surcharge_metadata(
&self,
backend_input: &backend::BackendInput,
payment_attempt: &storage::PaymentAttempt,
surcharge_metadata_and_key: (&mut types::SurchargeMetadata, types::SurchargeKey),
) -> ConditionalConfigResult<Option<types::SurchargeDetails>> {
match self {
Self::Generate(interpreter) => {
let surcharge_output = execute_dsl_and_get_conditional_config(
backend_input.clone(),
&interpreter.cached_algorithm,
)?;
Ok(surcharge_output
.surcharge_details
.map(|surcharge_details| {
get_surcharge_details_from_surcharge_output(
surcharge_details,
payment_attempt,
)
})
.transpose()?
.inspect(|surcharge_details| {
let (surcharge_metadata, surcharge_key) = surcharge_metadata_and_key;
surcharge_metadata
.insert_surcharge_details(surcharge_key, surcharge_details.clone());
}))
}
Self::Predetermined(request_surcharge_details) => Ok(Some(
types::SurchargeDetails::from((request_surcharge_details, payment_attempt)),
)),
}
}
}
#[cfg(feature = "v2")]
pub async fn perform_surcharge_decision_management_for_payment_method_list(
_state: &SessionState,
_algorithm_ref: routing::RoutingAlgorithmRef,
_payment_attempt: &storage::PaymentAttempt,
_payment_intent: &storage::PaymentIntent,
_billing_address: Option<payments::Address>,
_response_payment_method_types: &mut [api_models::payment_methods::ResponsePaymentMethodsEnabled],
) -> ConditionalConfigResult<(
types::SurchargeMetadata,
surcharge_decision_configs::MerchantSurchargeConfigs,
)> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn perform_surcharge_decision_management_for_payment_method_list(
state: &SessionState,
algorithm_ref: routing::RoutingAlgorithmRef,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
billing_address: Option<hyperswitch_domain_models::address::Address>,
response_payment_method_types: &mut [api_models::payment_methods::ResponsePaymentMethodsEnabled],
) -> ConditionalConfigResult<(
types::SurchargeMetadata,
surcharge_decision_configs::MerchantSurchargeConfigs,
)> {
let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.attempt_id.clone());
let (surcharge_source, merchant_surcharge_configs) = match (
payment_attempt.get_surcharge_details(),
algorithm_ref.surcharge_config_algo_id,
) {
(Some(request_surcharge_details), _) => (
SurchargeSource::Predetermined(request_surcharge_details),
surcharge_decision_configs::MerchantSurchargeConfigs::default(),
),
(None, Some(algorithm_id)) => {
let cached_algo = ensure_algorithm_cached(
&*state.store,
&payment_attempt.merchant_id,
algorithm_id.as_str(),
)
.await?;
let merchant_surcharge_config = cached_algo.merchant_surcharge_configs.clone();
(
SurchargeSource::Generate(cached_algo),
merchant_surcharge_config,
)
}
(None, None) => {
return Ok((
surcharge_metadata,
surcharge_decision_configs::MerchantSurchargeConfigs::default(),
))
}
};
let surcharge_source_log_message = match &surcharge_source {
SurchargeSource::Generate(_) => "Surcharge was calculated through surcharge rules",
SurchargeSource::Predetermined(_) => "Surcharge was sent in payment create request",
};
logger::debug!(payment_method_list_surcharge_source = surcharge_source_log_message);
let mut backend_input =
make_dsl_input_for_surcharge(payment_attempt, payment_intent, billing_address)
.change_context(ConfigError::InputConstructionError)?;
for payment_methods_enabled in response_payment_method_types.iter_mut() {
for payment_method_type_response in
&mut payment_methods_enabled.payment_method_types.iter_mut()
{
let payment_method_type = payment_method_type_response.payment_method_type;
backend_input.payment_method.payment_method_type = Some(payment_method_type);
backend_input.payment_method.payment_method =
Some(payment_methods_enabled.payment_method);
if let Some(card_network_list) = &mut payment_method_type_response.card_networks {
for card_network_type in card_network_list.iter_mut() {
backend_input.payment_method.card_network =
Some(card_network_type.card_network.clone());
let surcharge_details = surcharge_source
.generate_surcharge_details_and_populate_surcharge_metadata(
&backend_input,
payment_attempt,
(
&mut surcharge_metadata,
types::SurchargeKey::PaymentMethodData(
payment_methods_enabled.payment_method,
payment_method_type_response.payment_method_type,
Some(card_network_type.card_network.clone()),
),
),
)?;
card_network_type.surcharge_details = surcharge_details
.map(|surcharge_details| {
SurchargeDetailsResponse::foreign_try_from((
&surcharge_details,
payment_attempt,
))
.change_context(ConfigError::DslExecutionError)
.attach_printable("Error while constructing Surcharge response type")
})
.transpose()?;
}
} else {
let surcharge_details = surcharge_source
.generate_surcharge_details_and_populate_surcharge_metadata(
&backend_input,
payment_attempt,
(
&mut surcharge_metadata,
types::SurchargeKey::PaymentMethodData(
payment_methods_enabled.payment_method,
payment_method_type_response.payment_method_type,
None,
),
),
)?;
payment_method_type_response.surcharge_details = surcharge_details
.map(|surcharge_details| {
SurchargeDetailsResponse::foreign_try_from((
&surcharge_details,
payment_attempt,
))
.change_context(ConfigError::DslExecutionError)
.attach_printable("Error while constructing Surcharge response type")
})
.transpose()?;
}
}
}
Ok((surcharge_metadata, merchant_surcharge_configs))
}
#[cfg(feature = "v1")]
pub async fn perform_surcharge_decision_management_for_session_flow(
state: &SessionState,
algorithm_ref: routing::RoutingAlgorithmRef,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
billing_address: Option<hyperswitch_domain_models::address::Address>,
payment_method_type_list: &Vec<common_enums::PaymentMethodType>,
) -> ConditionalConfigResult<types::SurchargeMetadata> {
let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.attempt_id.clone());
let surcharge_source = match (
payment_attempt.get_surcharge_details(),
algorithm_ref.surcharge_config_algo_id,
) {
(Some(request_surcharge_details), _) => {
SurchargeSource::Predetermined(request_surcharge_details)
}
(None, Some(algorithm_id)) => {
let cached_algo = ensure_algorithm_cached(
&*state.store,
&payment_attempt.merchant_id,
algorithm_id.as_str(),
)
.await?;
SurchargeSource::Generate(cached_algo)
}
(None, None) => return Ok(surcharge_metadata),
};
let mut backend_input =
make_dsl_input_for_surcharge(payment_attempt, payment_intent, billing_address)
.change_context(ConfigError::InputConstructionError)?;
for payment_method_type in payment_method_type_list {
backend_input.payment_method.payment_method_type = Some(*payment_method_type);
// in case of session flow, payment_method will always be wallet
backend_input.payment_method.payment_method = Some(payment_method_type.to_owned().into());
surcharge_source.generate_surcharge_details_and_populate_surcharge_metadata(
&backend_input,
payment_attempt,
(
&mut surcharge_metadata,
types::SurchargeKey::PaymentMethodData(
payment_method_type.to_owned().into(),
*payment_method_type,
None,
),
),
)?;
}
Ok(surcharge_metadata)
}
#[cfg(feature = "v1")]
pub async fn perform_surcharge_decision_management_for_saved_cards(
state: &SessionState,
algorithm_ref: routing::RoutingAlgorithmRef,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
customer_payment_method_list: &mut [api_models::payment_methods::CustomerPaymentMethod],
) -> ConditionalConfigResult<types::SurchargeMetadata> {
let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.attempt_id.clone());
let surcharge_source = match (
payment_attempt.get_surcharge_details(),
algorithm_ref.surcharge_config_algo_id,
) {
(Some(request_surcharge_details), _) => {
SurchargeSource::Predetermined(request_surcharge_details)
}
(None, Some(algorithm_id)) => {
let cached_algo = ensure_algorithm_cached(
&*state.store,
&payment_attempt.merchant_id,
algorithm_id.as_str(),
)
.await?;
SurchargeSource::Generate(cached_algo)
}
(None, None) => return Ok(surcharge_metadata),
};
let surcharge_source_log_message = match &surcharge_source {
SurchargeSource::Generate(_) => "Surcharge was calculated through surcharge rules",
SurchargeSource::Predetermined(_) => "Surcharge was sent in payment create request",
};
logger::debug!(customer_saved_card_list_surcharge_source = surcharge_source_log_message);
let mut backend_input = make_dsl_input_for_surcharge(payment_attempt, payment_intent, None)
.change_context(ConfigError::InputConstructionError)?;
for customer_payment_method in customer_payment_method_list.iter_mut() {
let payment_token = customer_payment_method.payment_token.clone();
backend_input.payment_method.payment_method = Some(customer_payment_method.payment_method);
backend_input.payment_method.payment_method_type =
customer_payment_method.payment_method_type;
let card_network = customer_payment_method
.card
.as_ref()
.and_then(|card| card.scheme.as_ref())
.map(|scheme| {
scheme
.clone()
.parse_enum("CardNetwork")
.change_context(ConfigError::DslExecutionError)
})
.transpose()?;
backend_input.payment_method.card_network = card_network;
let surcharge_details = surcharge_source
.generate_surcharge_details_and_populate_surcharge_metadata(
&backend_input,
payment_attempt,
(
&mut surcharge_metadata,
types::SurchargeKey::Token(payment_token),
),
)?;
customer_payment_method.surcharge_details = surcharge_details
.map(|surcharge_details| {
SurchargeDetailsResponse::foreign_try_from((&surcharge_details, payment_attempt))
.change_context(ConfigError::DslParsingError)
})
.transpose()?;
}
Ok(surcharge_metadata)
}
// TODO: uncomment and resolve compiler error when required
// #[cfg(feature = "v2")]
// pub async fn perform_surcharge_decision_management_for_saved_cards(
// state: &SessionState,
// algorithm_ref: routing::RoutingAlgorithmRef,
// payment_attempt: &storage::PaymentAttempt,
// payment_intent: &storage::PaymentIntent,
// customer_payment_method_list: &mut [api_models::payment_methods::CustomerPaymentMethod],
// ) -> ConditionalConfigResult<types::SurchargeMetadata> {
// // let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.id.clone());
// let mut surcharge_metadata = todo!();
// let surcharge_source = match (
// payment_attempt.get_surcharge_details(),
// algorithm_ref.surcharge_config_algo_id,
// ) {
// (Some(request_surcharge_details), _) => {
// SurchargeSource::Predetermined(request_surcharge_details)
// }
// (None, Some(algorithm_id)) => {
// let cached_algo = ensure_algorithm_cached(
// &*state.store,
// &payment_attempt.merchant_id,
// algorithm_id.as_str(),
// )
// .await?;
// SurchargeSource::Generate(cached_algo)
// }
// (None, None) => return Ok(surcharge_metadata),
// };
// let surcharge_source_log_message = match &surcharge_source {
// SurchargeSource::Generate(_) => "Surcharge was calculated through surcharge rules",
// SurchargeSource::Predetermined(_) => "Surcharge was sent in payment create request",
// };
// logger::debug!(customer_saved_card_list_surcharge_source = surcharge_source_log_message);
// let mut backend_input = make_dsl_input_for_surcharge(payment_attempt, payment_intent, None)
// .change_context(ConfigError::InputConstructionError)?;
// for customer_payment_method in customer_payment_method_list.iter_mut() {
// let payment_token = customer_payment_method
// .payment_token
// .clone()
// .get_required_value("payment_token")
// .change_context(ConfigError::InputConstructionError)?;
// backend_input.payment_method.payment_method =
// Some(customer_payment_method.payment_method_type);
// backend_input.payment_method.payment_method_type =
// customer_payment_method.payment_method_subtype;
// let card_network = match customer_payment_method.payment_method_data.as_ref() {
// Some(api_models::payment_methods::PaymentMethodListData::Card(card)) => {
// card.card_network.clone()
// }
// _ => None,
// };
// backend_input.payment_method.card_network = card_network;
// let surcharge_details = surcharge_source
// .generate_surcharge_details_and_populate_surcharge_metadata(
// &backend_input,
// payment_attempt,
// (
// &mut surcharge_metadata,
// types::SurchargeKey::Token(payment_token),
// ),
// )?;
// customer_payment_method.surcharge_details = surcharge_details
// .map(|surcharge_details| {
// SurchargeDetailsResponse::foreign_try_from((&surcharge_details, payment_attempt))
// .change_context(ConfigError::DslParsingError)
// })
// .transpose()?;
// }
// Ok(surcharge_metadata)
// }
#[cfg(feature = "v2")]
fn get_surcharge_details_from_surcharge_output(
_surcharge_details: surcharge_decision_configs::SurchargeDetailsOutput,
_payment_attempt: &storage::PaymentAttempt,
) -> ConditionalConfigResult<types::SurchargeDetails> {
todo!()
}
#[cfg(feature = "v1")]
fn get_surcharge_details_from_surcharge_output(
surcharge_details: surcharge_decision_configs::SurchargeDetailsOutput,
payment_attempt: &storage::PaymentAttempt,
) -> ConditionalConfigResult<types::SurchargeDetails> {
let surcharge_amount = match surcharge_details.surcharge.clone() {
surcharge_decision_configs::SurchargeOutput::Fixed { amount } => amount,
surcharge_decision_configs::SurchargeOutput::Rate(percentage) => percentage
.apply_and_ceil_result(payment_attempt.net_amount.get_total_amount())
.change_context(ConfigError::DslExecutionError)
.attach_printable("Failed to Calculate surcharge amount by applying percentage")?,
};
let tax_on_surcharge_amount = surcharge_details
.tax_on_surcharge
.clone()
.map(|tax_on_surcharge| {
tax_on_surcharge
.apply_and_ceil_result(surcharge_amount)
.change_context(ConfigError::DslExecutionError)
.attach_printable("Failed to Calculate tax amount")
})
.transpose()?
.unwrap_or_default();
Ok(types::SurchargeDetails {
original_amount: payment_attempt.net_amount.get_order_amount(),
surcharge: match surcharge_details.surcharge {
surcharge_decision_configs::SurchargeOutput::Fixed { amount } => {
common_utils_types::Surcharge::Fixed(amount)
}
surcharge_decision_configs::SurchargeOutput::Rate(percentage) => {
common_utils_types::Surcharge::Rate(percentage)
}
},
tax_on_surcharge: surcharge_details.tax_on_surcharge,
surcharge_amount,
tax_on_surcharge_amount,
})
}
#[instrument(skip_all)]
pub async fn ensure_algorithm_cached(
store: &dyn StorageInterface,
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: &str,
) -> ConditionalConfigResult<VirInterpreterBackendCacheWrapper> {
let key = merchant_id.get_surcharge_dsk_key();
let value_to_cache = || async {
let config: diesel_models::Config = store.find_config_by_key(algorithm_id).await?;
let record: SurchargeDecisionManagerRecord = config
.config
.parse_struct("Program")
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("Error parsing routing algorithm from configs")?;
VirInterpreterBackendCacheWrapper::try_from(record)
.change_context(errors::StorageError::ValueNotFound("Program".to_string()))
.attach_printable("Error initializing DSL interpreter backend")
};
let interpreter = cache::get_or_populate_in_memory(
store.get_cache_store().as_ref(),
&key,
value_to_cache,
&SURCHARGE_CACHE,
)
.await
.change_context(ConfigError::CacheMiss)
.attach_printable("Unable to retrieve cached routing algorithm even after refresh")?;
Ok(interpreter)
}
pub fn execute_dsl_and_get_conditional_config(
backend_input: dsl_inputs::BackendInput,
interpreter: &backend::VirInterpreterBackend<SurchargeDecisionConfigs>,
) -> ConditionalConfigResult<SurchargeDecisionConfigs> {
let routing_output = interpreter
.execute(backend_input)
.map(|out| out.connector_selection)
.change_context(ConfigError::DslExecutionError)?;
Ok(routing_output)
}
| {
"crate": "router",
"file": "crates/router/src/core/payment_methods/surcharge_decision_configs.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_5167482213383783337 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/payment_methods/transformers.rs
// Contains: 16 structs, 1 enums
pub use ::payment_methods::controller::{DataDuplicationCheck, DeleteCardResp};
#[cfg(feature = "v2")]
use api_models::payment_methods::PaymentMethodResponseItem;
use api_models::{enums as api_enums, payment_methods::Card};
use common_utils::{
ext_traits::{Encode, StringExt},
id_type,
pii::Email,
request::RequestContent,
};
use error_stack::ResultExt;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payment_method_data;
use josekit::jwe;
use router_env::tracing_actix_web::RequestId;
use serde::{Deserialize, Serialize};
#[cfg(feature = "v2")]
use crate::types::{payment_methods as pm_types, transformers};
use crate::{
configs::settings,
core::errors::{self, CustomResult},
headers,
pii::{prelude::*, Secret},
services::{api as services, encryption, EncryptionAlgorithm},
types::{api, domain},
utils::OptionExt,
};
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum StoreLockerReq {
LockerCard(StoreCardReq),
LockerGeneric(StoreGenericReq),
}
impl StoreLockerReq {
pub fn update_requestor_card_reference(&mut self, card_reference: Option<String>) {
match self {
Self::LockerCard(c) => c.requestor_card_reference = card_reference,
Self::LockerGeneric(_) => (),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StoreCardReq {
pub merchant_id: id_type::MerchantId,
pub merchant_customer_id: id_type::CustomerId,
#[serde(skip_serializing_if = "Option::is_none")]
pub requestor_card_reference: Option<String>,
pub card: Card,
pub ttl: i64,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StoreGenericReq {
pub merchant_id: id_type::MerchantId,
pub merchant_customer_id: id_type::CustomerId,
#[serde(rename = "enc_card_data")]
pub enc_data: String,
pub ttl: i64,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StoreCardResp {
pub status: String,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub payload: Option<StoreCardRespPayload>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StoreCardRespPayload {
pub card_reference: String,
pub duplication_check: Option<DataDuplicationCheck>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CardReqBody {
pub merchant_id: id_type::MerchantId,
pub merchant_customer_id: id_type::CustomerId,
pub card_reference: String,
}
#[cfg(feature = "v2")]
#[derive(Debug, Deserialize, Serialize)]
pub struct CardReqBodyV2 {
pub merchant_id: id_type::MerchantId,
pub merchant_customer_id: String, // Not changing this as it might lead to api contract failure
pub card_reference: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RetrieveCardResp {
pub status: String,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub payload: Option<RetrieveCardRespPayload>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RetrieveCardRespPayload {
pub card: Option<Card>,
pub enc_card_data: Option<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddCardRequest {
pub card_number: cards::CardNumber,
pub customer_id: id_type::CustomerId,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub merchant_id: id_type::MerchantId,
pub email_address: Option<Email>,
pub name_on_card: Option<Secret<String>>,
pub nickname: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddCardResponse {
pub card_id: String,
pub external_id: String,
pub card_fingerprint: Secret<String>,
pub card_global_fingerprint: Secret<String>,
#[serde(rename = "merchant_id")]
pub merchant_id: Option<id_type::MerchantId>,
pub card_number: Option<cards::CardNumber>,
pub card_exp_year: Option<Secret<String>>,
pub card_exp_month: Option<Secret<String>>,
pub name_on_card: Option<Secret<String>>,
pub nickname: Option<String>,
pub customer_id: Option<id_type::CustomerId>,
pub duplicate: Option<bool>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddPaymentMethodResponse {
pub payment_method_id: String,
pub external_id: String,
#[serde(rename = "merchant_id")]
pub merchant_id: Option<id_type::MerchantId>,
pub nickname: Option<String>,
pub customer_id: Option<id_type::CustomerId>,
pub duplicate: Option<bool>,
pub payment_method_data: Secret<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GetPaymentMethodResponse {
pub payment_method: AddPaymentMethodResponse,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GetCardResponse {
pub card: AddCardResponse,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetCard<'a> {
merchant_id: &'a str,
card_id: &'a str,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteCardResponse {
pub card_id: Option<String>,
pub external_id: Option<String>,
pub card_isin: Option<Secret<String>>,
pub status: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(transparent)]
pub struct PaymentMethodMetadata {
pub payment_method_tokenization: std::collections::HashMap<String, String>,
}
pub fn get_dotted_jwe(jwe: encryption::JweBody) -> String {
let header = jwe.header;
let encryption_key = jwe.encrypted_key;
let iv = jwe.iv;
let encryption_payload = jwe.encrypted_payload;
let tag = jwe.tag;
format!("{header}.{encryption_key}.{iv}.{encryption_payload}.{tag}")
}
pub fn get_dotted_jws(jws: encryption::JwsBody) -> String {
let header = jws.header;
let payload = jws.payload;
let signature = jws.signature;
format!("{header}.{payload}.{signature}")
}
pub async fn get_decrypted_response_payload(
jwekey: &settings::Jwekey,
jwe_body: encryption::JweBody,
locker_choice: Option<api_enums::LockerChoice>,
decryption_scheme: settings::DecryptionScheme,
) -> CustomResult<String, errors::VaultError> {
let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault);
let public_key = match target_locker {
api_enums::LockerChoice::HyperswitchCardVault => {
jwekey.vault_encryption_key.peek().as_bytes()
}
};
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jwt = get_dotted_jwe(jwe_body);
let alg = match decryption_scheme {
settings::DecryptionScheme::RsaOaep => jwe::RSA_OAEP,
settings::DecryptionScheme::RsaOaep256 => jwe::RSA_OAEP_256,
};
let jwe_decrypted = encryption::decrypt_jwe(
&jwt,
encryption::KeyIdCheck::SkipKeyIdCheck,
private_key,
alg,
)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Jwe Decryption failed for JweBody for vault")?;
let jws = jwe_decrypted
.parse_struct("JwsBody")
.change_context(errors::VaultError::ResponseDeserializationFailed)?;
let jws_body = get_dotted_jws(jws);
encryption::verify_sign(jws_body, public_key)
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Jws Decryption failed for JwsBody for vault")
}
pub async fn get_decrypted_vault_response_payload(
jwekey: &settings::Jwekey,
jwe_body: encryption::JweBody,
decryption_scheme: settings::DecryptionScheme,
) -> CustomResult<String, errors::VaultError> {
let public_key = jwekey.vault_encryption_key.peek().as_bytes();
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jwt = get_dotted_jwe(jwe_body);
let alg = match decryption_scheme {
settings::DecryptionScheme::RsaOaep => jwe::RSA_OAEP,
settings::DecryptionScheme::RsaOaep256 => jwe::RSA_OAEP_256,
};
let jwe_decrypted = encryption::decrypt_jwe(
&jwt,
encryption::KeyIdCheck::SkipKeyIdCheck,
private_key,
alg,
)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Jwe Decryption failed for JweBody for vault")?;
let jws = jwe_decrypted
.parse_struct("JwsBody")
.change_context(errors::VaultError::ResponseDeserializationFailed)?;
let jws_body = get_dotted_jws(jws);
encryption::verify_sign(jws_body, public_key)
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Jws Decryption failed for JwsBody for vault")
}
#[cfg(feature = "v2")]
pub async fn create_jwe_body_for_vault(
jwekey: &settings::Jwekey,
jws: &str,
) -> CustomResult<encryption::JweBody, errors::VaultError> {
let jws_payload: Vec<&str> = jws.split('.').collect();
let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> {
Some(encryption::JwsBody {
header: payload.first()?.to_string(),
payload: payload.get(1)?.to_string(),
signature: payload.get(2)?.to_string(),
})
};
let jws_body =
generate_jws_body(jws_payload).ok_or(errors::VaultError::RequestEncryptionFailed)?;
let payload = jws_body
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let public_key = jwekey.vault_encryption_key.peek().as_bytes();
let jwe_encrypted =
encryption::encrypt_jwe(&payload, public_key, EncryptionAlgorithm::A256GCM, None)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Error on jwe encrypt")?;
let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect();
let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> {
Some(encryption::JweBody {
header: payload.first()?.to_string(),
iv: payload.get(2)?.to_string(),
encrypted_payload: payload.get(3)?.to_string(),
tag: payload.get(4)?.to_string(),
encrypted_key: payload.get(1)?.to_string(),
})
};
let jwe_body =
generate_jwe_body(jwe_payload).ok_or(errors::VaultError::RequestEncodingFailed)?;
Ok(jwe_body)
}
pub async fn mk_basilisk_req(
jwekey: &settings::Jwekey,
jws: &str,
locker_choice: api_enums::LockerChoice,
) -> CustomResult<encryption::JweBody, errors::VaultError> {
let jws_payload: Vec<&str> = jws.split('.').collect();
let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> {
Some(encryption::JwsBody {
header: payload.first()?.to_string(),
payload: payload.get(1)?.to_string(),
signature: payload.get(2)?.to_string(),
})
};
let jws_body = generate_jws_body(jws_payload).ok_or(errors::VaultError::SaveCardFailed)?;
let payload = jws_body
.encode_to_vec()
.change_context(errors::VaultError::SaveCardFailed)?;
let public_key = match locker_choice {
api_enums::LockerChoice::HyperswitchCardVault => {
jwekey.vault_encryption_key.peek().as_bytes()
}
};
let jwe_encrypted =
encryption::encrypt_jwe(&payload, public_key, EncryptionAlgorithm::A256GCM, None)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Error on jwe encrypt")?;
let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect();
let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> {
Some(encryption::JweBody {
header: payload.first()?.to_string(),
iv: payload.get(2)?.to_string(),
encrypted_payload: payload.get(3)?.to_string(),
tag: payload.get(4)?.to_string(),
encrypted_key: payload.get(1)?.to_string(),
})
};
let jwe_body = generate_jwe_body(jwe_payload).ok_or(errors::VaultError::SaveCardFailed)?;
Ok(jwe_body)
}
pub async fn mk_add_locker_request_hs(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
payload: &StoreLockerReq,
locker_choice: api_enums::LockerChoice,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let payload = payload
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
.change_context(errors::VaultError::RequestEncodingFailed)?;
let jwe_payload = mk_basilisk_req(jwekey, &jws, locker_choice).await?;
let mut url = match locker_choice {
api_enums::LockerChoice::HyperswitchCardVault => locker.host.to_owned(),
};
url.push_str("/cards/add");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
#[cfg(all(feature = "v1", feature = "payouts"))]
pub fn mk_add_bank_response_hs(
bank: api::BankPayout,
bank_reference: String,
req: api::PaymentMethodCreate,
merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
api::PaymentMethodResponse {
merchant_id: merchant_id.to_owned(),
customer_id: req.customer_id,
payment_method_id: bank_reference,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
bank_transfer: Some(bank),
card: None,
metadata: req.metadata,
created: Some(common_utils::date_time::now()),
recurring_enabled: Some(false), // [#256]
installment_payment_enabled: Some(false), // #[#256]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
}
}
#[cfg(all(feature = "v2", feature = "payouts"))]
pub fn mk_add_bank_response_hs(
_bank: api::BankPayout,
_bank_reference: String,
_req: api::PaymentMethodCreate,
_merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
todo!()
}
#[cfg(feature = "v1")]
pub fn mk_add_card_response_hs(
card: api::CardDetail,
card_reference: String,
req: api::PaymentMethodCreate,
merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
let card_number = card.card_number.clone();
let last4_digits = card_number.get_last4();
let card_isin = card_number.get_card_isin();
let card = api::CardDetailFromLocker {
scheme: card
.card_network
.clone()
.map(|card_network| card_network.to_string()),
last4_digits: Some(last4_digits),
issuer_country: card.card_issuing_country,
card_number: Some(card.card_number.clone()),
expiry_month: Some(card.card_exp_month.clone()),
expiry_year: Some(card.card_exp_year.clone()),
card_token: None,
card_fingerprint: None,
card_holder_name: card.card_holder_name.clone(),
nick_name: card.nick_name.clone(),
card_isin: Some(card_isin),
card_issuer: card.card_issuer,
card_network: card.card_network,
card_type: card.card_type,
saved_to_locker: true,
};
api::PaymentMethodResponse {
merchant_id: merchant_id.to_owned(),
customer_id: req.customer_id,
payment_method_id: card_reference,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
#[cfg(feature = "payouts")]
bank_transfer: None,
card: Some(card),
metadata: req.metadata,
created: Some(common_utils::date_time::now()),
recurring_enabled: Some(false), // [#256]
installment_payment_enabled: Some(false), // #[#256]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()), // [#256]
client_secret: req.client_secret,
}
}
#[cfg(feature = "v2")]
pub fn mk_add_card_response_hs(
card: api::CardDetail,
card_reference: String,
req: api::PaymentMethodCreate,
merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
todo!()
}
#[cfg(feature = "v2")]
pub fn generate_pm_vaulting_req_from_update_request(
pm_create: domain::PaymentMethodVaultingData,
pm_update: api::PaymentMethodUpdateData,
) -> domain::PaymentMethodVaultingData {
match (pm_create, pm_update) {
(
domain::PaymentMethodVaultingData::Card(card_create),
api::PaymentMethodUpdateData::Card(update_card),
) => domain::PaymentMethodVaultingData::Card(api::CardDetail {
card_number: card_create.card_number,
card_exp_month: card_create.card_exp_month,
card_exp_year: card_create.card_exp_year,
card_issuing_country: card_create.card_issuing_country,
card_network: card_create.card_network,
card_issuer: card_create.card_issuer,
card_type: card_create.card_type,
card_holder_name: update_card
.card_holder_name
.or(card_create.card_holder_name),
nick_name: update_card.nick_name.or(card_create.nick_name),
card_cvc: None,
}),
_ => todo!(), //todo! - since support for network tokenization is not added PaymentMethodUpdateData. should be handled later.
}
}
#[cfg(feature = "v2")]
pub fn generate_payment_method_response(
payment_method: &domain::PaymentMethod,
single_use_token: &Option<payment_method_data::SingleUsePaymentMethodToken>,
) -> errors::RouterResult<api::PaymentMethodResponse> {
let pmd = payment_method
.payment_method_data
.clone()
.map(|data| data.into_inner())
.and_then(|data| match data {
api::PaymentMethodsData::Card(card) => {
Some(api::PaymentMethodResponseData::Card(card.into()))
}
_ => None,
});
let mut connector_tokens = payment_method
.connector_mandate_details
.as_ref()
.and_then(|connector_token_details| connector_token_details.payments.clone())
.map(|payment_token_details| payment_token_details.0)
.map(|payment_token_details| {
payment_token_details
.into_iter()
.map(transformers::ForeignFrom::foreign_from)
.collect::<Vec<_>>()
})
.unwrap_or_default();
if let Some(token) = single_use_token {
let connector_token_single_use = transformers::ForeignFrom::foreign_from(token);
connector_tokens.push(connector_token_single_use);
}
let connector_tokens = if connector_tokens.is_empty() {
None
} else {
Some(connector_tokens)
};
let network_token_pmd = payment_method
.network_token_payment_method_data
.clone()
.map(|data| data.into_inner())
.and_then(|data| match data {
domain::PaymentMethodsData::NetworkToken(token) => {
Some(api::NetworkTokenDetailsPaymentMethod::from(token))
}
_ => None,
});
let network_token = network_token_pmd.map(|pmd| api::NetworkTokenResponse {
payment_method_data: pmd,
});
let resp = api::PaymentMethodResponse {
merchant_id: payment_method.merchant_id.to_owned(),
customer_id: payment_method.customer_id.to_owned(),
id: payment_method.id.to_owned(),
payment_method_type: payment_method.get_payment_method_type(),
payment_method_subtype: payment_method.get_payment_method_subtype(),
created: Some(payment_method.created_at),
recurring_enabled: Some(false),
last_used_at: Some(payment_method.last_used_at),
payment_method_data: pmd,
connector_tokens,
network_token,
};
Ok(resp)
}
#[allow(clippy::too_many_arguments)]
pub async fn mk_get_card_request_hs(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
locker_choice: Option<api_enums::LockerChoice>,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let merchant_customer_id = customer_id.to_owned();
let card_req_body = CardReqBody {
merchant_id: merchant_id.to_owned(),
merchant_customer_id,
card_reference: card_reference.to_owned(),
};
let payload = card_req_body
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
.change_context(errors::VaultError::RequestEncodingFailed)?;
let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault);
let jwe_payload = mk_basilisk_req(jwekey, &jws, target_locker).await?;
let mut url = match target_locker {
api_enums::LockerChoice::HyperswitchCardVault => locker.host.to_owned(),
};
url.push_str("/cards/retrieve");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
pub fn mk_get_card_request(
locker: &settings::Locker,
locker_id: &'static str,
card_id: &'static str,
) -> CustomResult<services::Request, errors::VaultError> {
let get_card_req = GetCard {
merchant_id: locker_id,
card_id,
};
let mut url = locker.host.to_owned();
url.push_str("/card/getCard");
let mut request = services::Request::new(services::Method::Post, &url);
request.set_body(RequestContent::FormUrlEncoded(Box::new(get_card_req)));
Ok(request)
}
pub fn mk_get_card_response(card: GetCardResponse) -> errors::RouterResult<Card> {
Ok(Card {
card_number: card.card.card_number.get_required_value("card_number")?,
name_on_card: card.card.name_on_card,
card_exp_month: card
.card
.card_exp_month
.get_required_value("card_exp_month")?,
card_exp_year: card
.card
.card_exp_year
.get_required_value("card_exp_year")?,
card_brand: None,
card_isin: None,
nick_name: card.card.nickname,
})
}
pub async fn mk_delete_card_request_hs(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let merchant_customer_id = customer_id.to_owned();
let card_req_body = CardReqBody {
merchant_id: merchant_id.to_owned(),
merchant_customer_id,
card_reference: card_reference.to_owned(),
};
let payload = card_req_body
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
.change_context(errors::VaultError::RequestEncodingFailed)?;
let jwe_payload =
mk_basilisk_req(jwekey, &jws, api_enums::LockerChoice::HyperswitchCardVault).await?;
let mut url = locker.host.to_owned();
url.push_str("/cards/delete");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
// Need to fix this once we start moving to v2 completion
#[cfg(feature = "v2")]
pub async fn mk_delete_card_request_hs_by_id(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
id: &String,
merchant_id: &id_type::MerchantId,
card_reference: &str,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let merchant_customer_id = id.to_owned();
let card_req_body = CardReqBodyV2 {
merchant_id: merchant_id.to_owned(),
merchant_customer_id,
card_reference: card_reference.to_owned(),
};
let payload = card_req_body
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
.change_context(errors::VaultError::RequestEncodingFailed)?;
let jwe_payload =
mk_basilisk_req(jwekey, &jws, api_enums::LockerChoice::HyperswitchCardVault).await?;
let mut url = locker.host.to_owned();
url.push_str("/cards/delete");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
pub fn mk_delete_card_response(
response: DeleteCardResponse,
) -> errors::RouterResult<DeleteCardResp> {
Ok(DeleteCardResp {
status: response.status,
error_message: None,
error_code: None,
})
}
#[cfg(feature = "v1")]
pub fn get_card_detail(
pm: &domain::PaymentMethod,
response: Card,
) -> CustomResult<api::CardDetailFromLocker, errors::VaultError> {
let card_number = response.card_number;
let last4_digits = card_number.clone().get_last4();
//fetch form card bin
let card_detail = api::CardDetailFromLocker {
scheme: pm.scheme.to_owned(),
issuer_country: pm.issuer_country.clone(),
last4_digits: Some(last4_digits),
card_number: Some(card_number),
expiry_month: Some(response.card_exp_month),
expiry_year: Some(response.card_exp_year),
card_token: None,
card_fingerprint: None,
card_holder_name: response.name_on_card,
nick_name: response.nick_name.map(Secret::new),
card_isin: None,
card_issuer: None,
card_network: None,
card_type: None,
saved_to_locker: true,
};
Ok(card_detail)
}
#[cfg(feature = "v2")]
pub fn get_card_detail(
_pm: &domain::PaymentMethod,
response: Card,
) -> CustomResult<api::CardDetailFromLocker, errors::VaultError> {
let card_number = response.card_number;
let last4_digits = card_number.clone().get_last4();
//fetch form card bin
let card_detail = api::CardDetailFromLocker {
issuer_country: None,
last4_digits: Some(last4_digits),
card_number: Some(card_number),
expiry_month: Some(response.card_exp_month),
expiry_year: Some(response.card_exp_year),
card_fingerprint: None,
card_holder_name: response.name_on_card,
nick_name: response.nick_name.map(Secret::new),
card_isin: None,
card_issuer: None,
card_network: None,
card_type: None,
saved_to_locker: true,
};
Ok(card_detail)
}
//------------------------------------------------TokenizeService------------------------------------------------
pub fn mk_crud_locker_request(
locker: &settings::Locker,
path: &str,
req: api::TokenizePayloadEncrypted,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let mut url = locker.basilisk_host.to_owned();
url.push_str(path);
let mut request = services::Request::new(services::Method::Post, &url);
request.add_default_headers();
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(req)));
Ok(request)
}
pub fn mk_card_value1(
card_number: cards::CardNumber,
exp_year: String,
exp_month: String,
name_on_card: Option<String>,
nickname: Option<String>,
card_last_four: Option<String>,
card_token: Option<String>,
) -> CustomResult<String, errors::VaultError> {
let value1 = api::TokenizedCardValue1 {
card_number: card_number.peek().clone(),
exp_year,
exp_month,
name_on_card,
nickname,
card_last_four,
card_token,
};
let value1_req = value1
.encode_to_string_of_json()
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(value1_req)
}
pub fn mk_card_value2(
card_security_code: Option<String>,
card_fingerprint: Option<String>,
external_id: Option<String>,
customer_id: Option<id_type::CustomerId>,
payment_method_id: Option<String>,
) -> CustomResult<String, errors::VaultError> {
let value2 = api::TokenizedCardValue2 {
card_security_code,
card_fingerprint,
external_id,
customer_id,
payment_method_id,
};
let value2_req = value2
.encode_to_string_of_json()
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(value2_req)
}
#[cfg(feature = "v2")]
impl transformers::ForeignTryFrom<(domain::PaymentMethod, String)>
for api::CustomerPaymentMethodResponseItem
{
type Error = error_stack::Report<errors::ValidationError>;
fn foreign_try_from(
(item, payment_token): (domain::PaymentMethod, String),
) -> Result<Self, Self::Error> {
// For payment methods that are active we should always have the payment method subtype
let payment_method_subtype =
item.payment_method_subtype
.ok_or(errors::ValidationError::MissingRequiredField {
field_name: "payment_method_subtype".to_string(),
})?;
// For payment methods that are active we should always have the payment method type
let payment_method_type =
item.payment_method_type
.ok_or(errors::ValidationError::MissingRequiredField {
field_name: "payment_method_type".to_string(),
})?;
let payment_method_data = item
.payment_method_data
.map(|payment_method_data| payment_method_data.into_inner())
.map(|payment_method_data| match payment_method_data {
api_models::payment_methods::PaymentMethodsData::Card(
card_details_payment_method,
) => {
let card_details = api::CardDetailFromLocker::from(card_details_payment_method);
api_models::payment_methods::PaymentMethodListData::Card(card_details)
}
api_models::payment_methods::PaymentMethodsData::BankDetails(..) => todo!(),
api_models::payment_methods::PaymentMethodsData::WalletDetails(..) => {
todo!()
}
});
let payment_method_billing = item
.payment_method_billing_address
.clone()
.map(|billing| billing.into_inner())
.map(From::from);
// TODO: check how we can get this field
let recurring_enabled = true;
Ok(Self {
id: item.id,
customer_id: item.customer_id,
payment_method_type,
payment_method_subtype,
created: item.created_at,
last_used_at: item.last_used_at,
recurring_enabled,
payment_method_data,
bank: None,
requires_cvv: true,
is_default: false,
billing: payment_method_billing,
payment_token,
})
}
}
#[cfg(feature = "v2")]
impl transformers::ForeignTryFrom<domain::PaymentMethod> for PaymentMethodResponseItem {
type Error = error_stack::Report<errors::ValidationError>;
fn foreign_try_from(item: domain::PaymentMethod) -> Result<Self, Self::Error> {
// For payment methods that are active we should always have the payment method subtype
let payment_method_subtype =
item.payment_method_subtype
.ok_or(errors::ValidationError::MissingRequiredField {
field_name: "payment_method_subtype".to_string(),
})?;
// For payment methods that are active we should always have the payment method type
let payment_method_type =
item.payment_method_type
.ok_or(errors::ValidationError::MissingRequiredField {
field_name: "payment_method_type".to_string(),
})?;
let payment_method_data = item
.payment_method_data
.map(|payment_method_data| payment_method_data.into_inner())
.map(|payment_method_data| match payment_method_data {
api_models::payment_methods::PaymentMethodsData::Card(
card_details_payment_method,
) => {
let card_details = api::CardDetailFromLocker::from(card_details_payment_method);
api_models::payment_methods::PaymentMethodListData::Card(card_details)
}
api_models::payment_methods::PaymentMethodsData::BankDetails(..) => todo!(),
api_models::payment_methods::PaymentMethodsData::WalletDetails(..) => {
todo!()
}
});
let payment_method_billing = item
.payment_method_billing_address
.clone()
.map(|billing| billing.into_inner())
.map(From::from);
let network_token_pmd = item
.network_token_payment_method_data
.clone()
.map(|data| data.into_inner())
.and_then(|data| match data {
domain::PaymentMethodsData::NetworkToken(token) => {
Some(api::NetworkTokenDetailsPaymentMethod::from(token))
}
_ => None,
});
let network_token_resp = network_token_pmd.map(|pmd| api::NetworkTokenResponse {
payment_method_data: pmd,
});
// TODO: check how we can get this field
let recurring_enabled = Some(true);
let psp_tokenization_enabled = item.connector_mandate_details.and_then(|details| {
details.payments.map(|payments| {
payments.values().any(|connector_token_reference| {
connector_token_reference.connector_token_status
== api_enums::ConnectorTokenStatus::Active
})
})
});
Ok(Self {
id: item.id,
customer_id: item.customer_id,
payment_method_type,
payment_method_subtype,
created: item.created_at,
last_used_at: item.last_used_at,
recurring_enabled,
payment_method_data,
bank: None,
requires_cvv: true,
is_default: false,
billing: payment_method_billing,
network_tokenization: network_token_resp,
psp_tokenization_enabled: psp_tokenization_enabled.unwrap_or(false),
})
}
}
#[cfg(feature = "v2")]
pub fn generate_payment_method_session_response(
payment_method_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession,
client_secret: Secret<String>,
associated_payment: Option<api_models::payments::PaymentsResponse>,
tokenization_service_response: Option<api_models::tokenization::GenericTokenizationResponse>,
) -> api_models::payment_methods::PaymentMethodSessionResponse {
let next_action = associated_payment
.as_ref()
.and_then(|payment| payment.next_action.clone());
let authentication_details =
associated_payment.map(
|payment| api_models::payment_methods::AuthenticationDetails {
status: payment.status,
error: payment.error,
},
);
let token_id = tokenization_service_response
.as_ref()
.map(|tokenization_service_response| tokenization_service_response.id.clone());
api_models::payment_methods::PaymentMethodSessionResponse {
id: payment_method_session.id,
customer_id: payment_method_session.customer_id,
billing: payment_method_session
.billing
.map(|address| address.into_inner())
.map(From::from),
psp_tokenization: payment_method_session.psp_tokenization,
network_tokenization: payment_method_session.network_tokenization,
tokenization_data: payment_method_session.tokenization_data,
expires_at: payment_method_session.expires_at,
client_secret,
next_action,
return_url: payment_method_session.return_url,
associated_payment_methods: payment_method_session.associated_payment_methods,
authentication_details,
associated_token_id: token_id,
}
}
#[cfg(feature = "v2")]
impl transformers::ForeignFrom<api_models::payment_methods::ConnectorTokenDetails>
for hyperswitch_domain_models::mandates::ConnectorTokenReferenceRecord
{
fn foreign_from(item: api_models::payment_methods::ConnectorTokenDetails) -> Self {
let api_models::payment_methods::ConnectorTokenDetails {
status,
connector_token_request_reference_id,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
token,
..
} = item;
Self {
connector_token: token.expose().clone(),
// TODO: check why do we need this field
payment_method_subtype: None,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
connector_token_status: status,
connector_token_request_reference_id,
}
}
}
#[cfg(feature = "v2")]
impl
transformers::ForeignFrom<(
id_type::MerchantConnectorAccountId,
hyperswitch_domain_models::mandates::ConnectorTokenReferenceRecord,
)> for api_models::payment_methods::ConnectorTokenDetails
{
fn foreign_from(
(connector_id, mandate_reference_record): (
id_type::MerchantConnectorAccountId,
hyperswitch_domain_models::mandates::ConnectorTokenReferenceRecord,
),
) -> Self {
let hyperswitch_domain_models::mandates::ConnectorTokenReferenceRecord {
connector_token_request_reference_id,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
connector_token,
connector_token_status,
..
} = mandate_reference_record;
Self {
connector_id,
status: connector_token_status,
connector_token_request_reference_id,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
token: Secret::new(connector_token),
// Token that is derived from payments mandate reference will always be multi use token
token_type: common_enums::TokenizationType::MultiUse,
}
}
}
#[cfg(feature = "v2")]
impl transformers::ForeignFrom<&payment_method_data::SingleUsePaymentMethodToken>
for api_models::payment_methods::ConnectorTokenDetails
{
fn foreign_from(token: &payment_method_data::SingleUsePaymentMethodToken) -> Self {
Self {
connector_id: token.clone().merchant_connector_id,
token_type: common_enums::TokenizationType::SingleUse,
status: api_enums::ConnectorTokenStatus::Active,
connector_token_request_reference_id: None,
original_payment_authorized_amount: None,
original_payment_authorized_currency: None,
metadata: None,
token: token.clone().token,
}
}
}
| {
"crate": "router",
"file": "crates/router/src/core/payment_methods/transformers.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 16,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-7732684490042801629 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/payment_methods/tokenize.rs
// Contains: 1 structs, 0 enums
use actix_multipart::form::{bytes::Bytes, text::Text, MultipartForm};
use api_models::{enums as api_enums, payment_methods as payment_methods_api};
use cards::CardNumber;
use common_utils::{
crypto::Encryptable,
id_type,
transformers::{ForeignFrom, ForeignTryFrom},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::router_request_types as domain_request_types;
use masking::{ExposeInterface, Secret};
use router_env::logger;
use crate::{
core::payment_methods::{
cards::{add_card_to_hs_locker, create_encrypted_data, tokenize_card_flow},
network_tokenization, transformers as pm_transformers,
},
errors::{self, RouterResult},
services,
types::{api, domain, payment_methods as pm_types},
SessionState,
};
pub mod card_executor;
pub mod payment_method_executor;
pub use card_executor::*;
pub use payment_method_executor::*;
use rdkafka::message::ToBytes;
#[derive(Debug, MultipartForm)]
pub struct CardNetworkTokenizeForm {
#[multipart(limit = "1MB")]
pub file: Bytes,
pub merchant_id: Text<id_type::MerchantId>,
}
pub fn parse_csv(
merchant_id: &id_type::MerchantId,
data: &[u8],
) -> csv::Result<Vec<payment_methods_api::CardNetworkTokenizeRequest>> {
let mut csv_reader = csv::ReaderBuilder::new()
.has_headers(true)
.from_reader(data);
let mut records = Vec::new();
let mut id_counter = 0;
for (i, result) in csv_reader
.deserialize::<domain::CardNetworkTokenizeRecord>()
.enumerate()
{
match result {
Ok(mut record) => {
logger::info!("Parsed Record (line {}): {:?}", i + 1, record);
id_counter += 1;
record.line_number = Some(id_counter);
record.merchant_id = Some(merchant_id.clone());
match payment_methods_api::CardNetworkTokenizeRequest::foreign_try_from(record) {
Ok(record) => {
records.push(record);
}
Err(err) => {
logger::error!("Error parsing line {}: {}", i + 1, err.to_string());
}
}
}
Err(e) => logger::error!("Error parsing line {}: {}", i + 1, e),
}
}
Ok(records)
}
pub fn get_tokenize_card_form_records(
form: CardNetworkTokenizeForm,
) -> Result<
(
id_type::MerchantId,
Vec<payment_methods_api::CardNetworkTokenizeRequest>,
),
errors::ApiErrorResponse,
> {
match parse_csv(&form.merchant_id, form.file.data.to_bytes()) {
Ok(records) => {
logger::info!("Parsed a total of {} records", records.len());
Ok((form.merchant_id.0, records))
}
Err(e) => {
logger::error!("Failed to parse CSV: {:?}", e);
Err(errors::ApiErrorResponse::PreconditionFailed {
message: e.to_string(),
})
}
}
}
pub async fn tokenize_cards(
state: &SessionState,
records: Vec<payment_methods_api::CardNetworkTokenizeRequest>,
merchant_context: &domain::MerchantContext,
) -> errors::RouterResponse<Vec<payment_methods_api::CardNetworkTokenizeResponse>> {
use futures::stream::StreamExt;
// Process all records in parallel
let responses = futures::stream::iter(records.into_iter())
.map(|record| async move {
let tokenize_request = record.data.clone();
let customer = record.customer.clone();
Box::pin(tokenize_card_flow(
state,
domain::CardNetworkTokenizeRequest::foreign_from(record),
merchant_context,
))
.await
.unwrap_or_else(|e| {
let err = e.current_context();
payment_methods_api::CardNetworkTokenizeResponse {
tokenization_data: Some(tokenize_request),
error_code: Some(err.error_code()),
error_message: Some(err.error_message()),
card_tokenized: false,
payment_method_response: None,
customer: Some(customer),
}
})
})
.buffer_unordered(10)
.collect()
.await;
// Return the final response
Ok(services::ApplicationResponse::Json(responses))
}
// Data types
type NetworkTokenizationResponse = (pm_types::CardNetworkTokenResponsePayload, Option<String>);
pub struct StoreLockerResponse {
pub store_card_resp: pm_transformers::StoreCardRespPayload,
pub store_token_resp: pm_transformers::StoreCardRespPayload,
}
// Builder
pub struct NetworkTokenizationBuilder<'a, S: State> {
/// Current state
state: std::marker::PhantomData<S>,
/// Customer details
pub customer: Option<&'a api::CustomerDetails>,
/// Card details
pub card: Option<domain::CardDetail>,
/// CVC
pub card_cvc: Option<Secret<String>>,
/// Network token details
pub network_token: Option<&'a pm_types::CardNetworkTokenResponsePayload>,
/// Stored card details
pub stored_card: Option<&'a pm_transformers::StoreCardRespPayload>,
/// Stored token details
pub stored_token: Option<&'a pm_transformers::StoreCardRespPayload>,
/// Payment method response
pub payment_method_response: Option<api::PaymentMethodResponse>,
/// Card network tokenization status
pub card_tokenized: bool,
/// Error code
pub error_code: Option<&'a String>,
/// Error message
pub error_message: Option<&'a String>,
}
// Async executor
pub struct CardNetworkTokenizeExecutor<'a, D> {
pub state: &'a SessionState,
pub merchant_account: &'a domain::MerchantAccount,
key_store: &'a domain::MerchantKeyStore,
data: &'a D,
customer: &'a domain_request_types::CustomerDetails,
}
// State machine
pub trait State {}
pub trait TransitionTo<S: State> {}
// Trait for network tokenization
#[async_trait::async_trait]
pub trait NetworkTokenizationProcess<'a, D> {
fn new(
state: &'a SessionState,
merchant_context: &'a domain::MerchantContext,
data: &'a D,
customer: &'a domain_request_types::CustomerDetails,
) -> Self;
async fn encrypt_card(
&self,
card_details: &domain::CardDetail,
saved_to_locker: bool,
) -> RouterResult<Encryptable<Secret<serde_json::Value>>>;
async fn encrypt_network_token(
&self,
network_token_details: &NetworkTokenizationResponse,
card_details: &domain::CardDetail,
saved_to_locker: bool,
) -> RouterResult<Encryptable<Secret<serde_json::Value>>>;
async fn fetch_bin_details_and_validate_card_network(
&self,
card_number: CardNumber,
card_issuer: Option<&String>,
card_network: Option<&api_enums::CardNetwork>,
card_type: Option<&api_models::payment_methods::CardType>,
card_issuing_country: Option<&String>,
) -> RouterResult<Option<diesel_models::CardInfo>>;
fn validate_card_network(
&self,
optional_card_network: Option<&api_enums::CardNetwork>,
) -> RouterResult<()>;
async fn tokenize_card(
&self,
customer_id: &id_type::CustomerId,
card: &domain::CardDetail,
optional_cvc: Option<Secret<String>>,
) -> RouterResult<NetworkTokenizationResponse>;
async fn store_network_token_in_locker(
&self,
network_token: &NetworkTokenizationResponse,
customer_id: &id_type::CustomerId,
card_holder_name: Option<Secret<String>>,
nick_name: Option<Secret<String>>,
) -> RouterResult<pm_transformers::StoreCardRespPayload>;
}
// Generic implementation
#[async_trait::async_trait]
impl<'a, D> NetworkTokenizationProcess<'a, D> for CardNetworkTokenizeExecutor<'a, D>
where
D: Send + Sync + 'static,
{
fn new(
state: &'a SessionState,
merchant_context: &'a domain::MerchantContext,
data: &'a D,
customer: &'a domain_request_types::CustomerDetails,
) -> Self {
Self {
data,
customer,
state,
merchant_account: merchant_context.get_merchant_account(),
key_store: merchant_context.get_merchant_key_store(),
}
}
async fn encrypt_card(
&self,
card_details: &domain::CardDetail,
saved_to_locker: bool,
) -> RouterResult<Encryptable<Secret<serde_json::Value>>> {
let pm_data = api::PaymentMethodsData::Card(api::CardDetailsPaymentMethod {
last4_digits: Some(card_details.card_number.get_last4()),
expiry_month: Some(card_details.card_exp_month.clone()),
expiry_year: Some(card_details.card_exp_year.clone()),
card_isin: Some(card_details.card_number.get_card_isin()),
nick_name: card_details.nick_name.clone(),
card_holder_name: card_details.card_holder_name.clone(),
issuer_country: card_details.card_issuing_country.clone(),
card_issuer: card_details.card_issuer.clone(),
card_network: card_details.card_network.clone(),
card_type: card_details.card_type.clone(),
saved_to_locker,
co_badged_card_data: card_details
.co_badged_card_data
.as_ref()
.map(|data| data.into()),
});
create_encrypted_data(&self.state.into(), self.key_store, pm_data)
.await
.inspect_err(|err| logger::info!("Error encrypting payment method data: {:?}", err))
.change_context(errors::ApiErrorResponse::InternalServerError)
}
async fn encrypt_network_token(
&self,
network_token_details: &NetworkTokenizationResponse,
card_details: &domain::CardDetail,
saved_to_locker: bool,
) -> RouterResult<Encryptable<Secret<serde_json::Value>>> {
let network_token = &network_token_details.0;
let token_data = api::PaymentMethodsData::Card(api::CardDetailsPaymentMethod {
last4_digits: Some(network_token.token_last_four.clone()),
expiry_month: Some(network_token.token_expiry_month.clone()),
expiry_year: Some(network_token.token_expiry_year.clone()),
card_isin: Some(network_token.token_isin.clone()),
nick_name: card_details.nick_name.clone(),
card_holder_name: card_details.card_holder_name.clone(),
issuer_country: card_details.card_issuing_country.clone(),
card_issuer: card_details.card_issuer.clone(),
card_network: card_details.card_network.clone(),
card_type: card_details.card_type.clone(),
saved_to_locker,
co_badged_card_data: None,
});
create_encrypted_data(&self.state.into(), self.key_store, token_data)
.await
.inspect_err(|err| logger::info!("Error encrypting network token data: {:?}", err))
.change_context(errors::ApiErrorResponse::InternalServerError)
}
async fn fetch_bin_details_and_validate_card_network(
&self,
card_number: CardNumber,
card_issuer: Option<&String>,
card_network: Option<&api_enums::CardNetwork>,
card_type: Option<&api_models::payment_methods::CardType>,
card_issuing_country: Option<&String>,
) -> RouterResult<Option<diesel_models::CardInfo>> {
let db = &*self.state.store;
if card_issuer.is_some()
&& card_network.is_some()
&& card_type.is_some()
&& card_issuing_country.is_some()
{
self.validate_card_network(card_network)?;
return Ok(None);
}
db.get_card_info(&card_number.get_card_isin())
.await
.attach_printable("Failed to perform BIN lookup")
.change_context(errors::ApiErrorResponse::InternalServerError)?
.map(|card_info| {
self.validate_card_network(card_info.card_network.as_ref())?;
Ok(card_info)
})
.transpose()
}
async fn tokenize_card(
&self,
customer_id: &id_type::CustomerId,
card: &domain::CardDetail,
optional_cvc: Option<Secret<String>>,
) -> RouterResult<NetworkTokenizationResponse> {
network_tokenization::make_card_network_tokenization_request(
self.state,
card,
optional_cvc,
customer_id,
)
.await
.map_err(|err| {
logger::error!("Failed to tokenize card with the network: {:?}", err);
report!(errors::ApiErrorResponse::InternalServerError)
})
}
fn validate_card_network(
&self,
optional_card_network: Option<&api_enums::CardNetwork>,
) -> RouterResult<()> {
optional_card_network.map_or(
Err(report!(errors::ApiErrorResponse::NotSupported {
message: "Unknown card network".to_string()
})),
|card_network| {
if self
.state
.conf
.network_tokenization_supported_card_networks
.card_networks
.contains(card_network)
{
Ok(())
} else {
Err(report!(errors::ApiErrorResponse::NotSupported {
message: format!(
"Network tokenization for {card_network} is not supported",
)
}))
}
},
)
}
async fn store_network_token_in_locker(
&self,
network_token: &NetworkTokenizationResponse,
customer_id: &id_type::CustomerId,
card_holder_name: Option<Secret<String>>,
nick_name: Option<Secret<String>>,
) -> RouterResult<pm_transformers::StoreCardRespPayload> {
let network_token = &network_token.0;
let merchant_id = self.merchant_account.get_id();
let locker_req =
pm_transformers::StoreLockerReq::LockerCard(pm_transformers::StoreCardReq {
merchant_id: merchant_id.clone(),
merchant_customer_id: customer_id.clone(),
card: payment_methods_api::Card {
card_number: network_token.token.clone(),
card_exp_month: network_token.token_expiry_month.clone(),
card_exp_year: network_token.token_expiry_year.clone(),
card_brand: Some(network_token.card_brand.to_string()),
card_isin: Some(network_token.token_isin.clone()),
name_on_card: card_holder_name,
nick_name: nick_name.map(|nick_name| nick_name.expose()),
},
requestor_card_reference: None,
ttl: self.state.conf.locker.ttl_for_storage_in_secs,
});
let stored_resp = add_card_to_hs_locker(
self.state,
&locker_req,
customer_id,
api_enums::LockerChoice::HyperswitchCardVault,
)
.await
.inspect_err(|err| logger::info!("Error adding card in locker: {:?}", err))
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(stored_resp)
}
}
| {
"crate": "router",
"file": "crates/router/src/core/payment_methods/tokenize.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-7389205850812460215 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/payment_methods/migration.rs
// Contains: 1 structs, 0 enums
use actix_multipart::form::{self, bytes, text};
use api_models::payment_methods as pm_api;
use common_utils::{errors::CustomResult, id_type};
use csv::Reader;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
api::ApplicationResponse, errors::api_error_response as errors, merchant_context,
payment_methods::PaymentMethodUpdate,
};
use masking::{ExposeInterface, PeekInterface};
use payment_methods::core::migration::MerchantConnectorValidator;
use rdkafka::message::ToBytes;
use router_env::logger;
use crate::{
core::{errors::StorageErrorExt, payment_methods::cards::create_encrypted_data},
routes::SessionState,
};
type PmMigrationResult<T> = CustomResult<ApplicationResponse<T>, errors::ApiErrorResponse>;
#[cfg(feature = "v1")]
pub async fn update_payment_methods(
state: &SessionState,
payment_methods: Vec<pm_api::UpdatePaymentMethodRecord>,
merchant_id: &id_type::MerchantId,
merchant_context: &merchant_context::MerchantContext,
) -> PmMigrationResult<Vec<pm_api::PaymentMethodUpdateResponse>> {
let mut result = Vec::with_capacity(payment_methods.len());
for record in payment_methods {
let update_res =
update_payment_method_record(state, record.clone(), merchant_id, merchant_context)
.await;
let res = match update_res {
Ok(ApplicationResponse::Json(response)) => Ok(response),
Err(e) => Err(e.to_string()),
_ => Err("Failed to update payment method".to_string()),
};
result.push(pm_api::PaymentMethodUpdateResponse::from((res, record)));
}
Ok(ApplicationResponse::Json(result))
}
#[cfg(feature = "v1")]
pub async fn update_payment_method_record(
state: &SessionState,
req: pm_api::UpdatePaymentMethodRecord,
merchant_id: &id_type::MerchantId,
merchant_context: &merchant_context::MerchantContext,
) -> CustomResult<
ApplicationResponse<pm_api::PaymentMethodRecordUpdateResponse>,
errors::ApiErrorResponse,
> {
use std::collections::HashMap;
use common_enums::enums;
use common_utils::pii;
use hyperswitch_domain_models::mandates::{
CommonMandateReference, PaymentsMandateReference, PaymentsMandateReferenceRecord,
PayoutsMandateReference, PayoutsMandateReferenceRecord,
};
let db = &*state.store;
let payment_method_id = req.payment_method_id.clone();
let network_transaction_id = req.network_transaction_id.clone();
let status = req.status;
let key_manager_state = state.into();
let mut updated_card_expiry = false;
let payment_method = db
.find_payment_method(
&state.into(),
merchant_context.get_merchant_key_store(),
&payment_method_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
if payment_method.merchant_id != *merchant_id {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Merchant ID in the request does not match the Merchant ID in the payment method record.".to_string(),
}.into());
}
let updated_payment_method_data = match payment_method.payment_method_data.as_ref() {
Some(data) => {
match serde_json::from_value::<pm_api::PaymentMethodsData>(
data.clone().into_inner().expose(),
) {
Ok(pm_api::PaymentMethodsData::Card(mut card_data)) => {
if let Some(new_month) = &req.card_expiry_month {
card_data.expiry_month = Some(new_month.clone());
updated_card_expiry = true;
}
if let Some(new_year) = &req.card_expiry_year {
card_data.expiry_year = Some(new_year.clone());
updated_card_expiry = true;
}
if updated_card_expiry {
Some(
create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
pm_api::PaymentMethodsData::Card(card_data),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")
.map(Into::into),
)
} else {
None
}
}
_ => None,
}
}
None => None,
}
.transpose()?;
let mca_data_cache = if let Some(merchant_connector_ids) = &req.merchant_connector_ids {
let parsed_mca_ids =
MerchantConnectorValidator::parse_comma_separated_ids(merchant_connector_ids)?;
let mut cache = HashMap::new();
for merchant_connector_id in parsed_mca_ids {
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&state.into(),
merchant_context.get_merchant_account().get_id(),
&merchant_connector_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
cache.insert(merchant_connector_id, mca);
}
Some(cache)
} else {
None
};
let (customer, updated_customer) = match (&req.connector_customer_id, &mca_data_cache) {
(Some(connector_customer_id), Some(cache)) => {
let customer = db
.find_customer_by_customer_id_merchant_id(
&state.into(),
&payment_method.customer_id,
merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let customer_update =
build_connector_customer_update(&customer, connector_customer_id, cache)?;
(Some(customer), Some(customer_update))
}
_ => (None, None),
};
let pm_update = match (&req.payment_instrument_id, &mca_data_cache) {
(Some(payment_instrument_id), Some(cache)) => {
let mandate_details = payment_method
.get_common_mandate_reference()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize to Payment Mandate Reference ")?;
let mut existing_payments_mandate = mandate_details
.payments
.clone()
.unwrap_or(PaymentsMandateReference(HashMap::new()));
let mut existing_payouts_mandate = mandate_details
.payouts
.clone()
.unwrap_or(PayoutsMandateReference(HashMap::new()));
for (merchant_connector_id, mca) in cache.iter() {
match mca.connector_type {
enums::ConnectorType::PayoutProcessor => {
let new_payout_record = PayoutsMandateReferenceRecord {
transfer_method_id: Some(payment_instrument_id.peek().to_string()),
};
if let Some(existing_record) =
existing_payouts_mandate.0.get_mut(merchant_connector_id)
{
if let Some(transfer_method_id) = &new_payout_record.transfer_method_id
{
existing_record.transfer_method_id =
Some(transfer_method_id.clone());
}
} else {
existing_payouts_mandate
.0
.insert(merchant_connector_id.clone(), new_payout_record);
}
}
_ => {
if let Some(existing_record) =
existing_payments_mandate.0.get_mut(merchant_connector_id)
{
existing_record.connector_mandate_id =
payment_instrument_id.peek().to_string();
} else {
existing_payments_mandate.0.insert(
merchant_connector_id.clone(),
PaymentsMandateReferenceRecord {
connector_mandate_id: payment_instrument_id.peek().to_string(),
payment_method_type: None,
original_payment_authorized_amount: None,
original_payment_authorized_currency: None,
mandate_metadata: None,
connector_mandate_status: None,
connector_mandate_request_reference_id: None,
},
);
}
}
}
}
let updated_connector_mandate_details = CommonMandateReference {
payments: if !existing_payments_mandate.0.is_empty() {
Some(existing_payments_mandate)
} else {
mandate_details.payments
},
payouts: if !existing_payouts_mandate.0.is_empty() {
Some(existing_payouts_mandate)
} else {
mandate_details.payouts
},
};
let connector_mandate_details_value = updated_connector_mandate_details
.get_mandate_details_value()
.map_err(|err| {
logger::error!("Failed to get get_mandate_details_value : {:?}", err);
errors::ApiErrorResponse::MandateUpdateFailed
})?;
PaymentMethodUpdate::PaymentMethodBatchUpdate {
connector_mandate_details: Some(pii::SecretSerdeValue::new(
connector_mandate_details_value,
)),
network_transaction_id,
status,
payment_method_data: updated_payment_method_data.clone(),
}
}
_ => {
if updated_payment_method_data.is_some() {
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data: updated_payment_method_data,
}
} else {
PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
status,
}
}
}
};
let response = db
.update_payment_method(
&state.into(),
merchant_context.get_merchant_key_store(),
payment_method,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Failed to update payment method for existing pm_id: {payment_method_id:?} in db",
))?;
let connector_customer_response =
if let (Some(customer_data), Some(customer_update)) = (customer, updated_customer) {
let updated_customer = db
.update_customer_by_customer_id_merchant_id(
&state.into(),
response.customer_id.clone(),
merchant_id.clone(),
customer_data,
customer_update,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update customer connector data")?;
updated_customer.connector_customer
} else {
None
};
Ok(ApplicationResponse::Json(
pm_api::PaymentMethodRecordUpdateResponse {
payment_method_id: response.payment_method_id,
status: response.status,
network_transaction_id: response.network_transaction_id,
connector_mandate_details: response
.connector_mandate_details
.map(pii::SecretSerdeValue::new),
updated_payment_method_data: Some(updated_card_expiry),
connector_customer: connector_customer_response,
},
))
}
#[derive(Debug, form::MultipartForm)]
pub struct PaymentMethodsUpdateForm {
#[multipart(limit = "1MB")]
pub file: bytes::Bytes,
pub merchant_id: text::Text<id_type::MerchantId>,
}
fn parse_update_csv(data: &[u8]) -> csv::Result<Vec<pm_api::UpdatePaymentMethodRecord>> {
let mut csv_reader = Reader::from_reader(data);
let mut records = Vec::new();
let mut id_counter = 0;
for result in csv_reader.deserialize() {
let mut record: pm_api::UpdatePaymentMethodRecord = result?;
id_counter += 1;
record.line_number = Some(id_counter);
records.push(record);
}
Ok(records)
}
type UpdateValidationResult =
Result<(id_type::MerchantId, Vec<pm_api::UpdatePaymentMethodRecord>), errors::ApiErrorResponse>;
impl PaymentMethodsUpdateForm {
pub fn validate_and_get_payment_method_records(self) -> UpdateValidationResult {
let records = parse_update_csv(self.file.data.to_bytes()).map_err(|e| {
errors::ApiErrorResponse::PreconditionFailed {
message: e.to_string(),
}
})?;
Ok((self.merchant_id.clone(), records))
}
}
#[cfg(feature = "v1")]
fn build_connector_customer_update(
customer: &hyperswitch_domain_models::customer::Customer,
connector_customer_id: &str,
mca_cache: &std::collections::HashMap<
id_type::MerchantConnectorAccountId,
hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
>,
) -> CustomResult<hyperswitch_domain_models::customer::CustomerUpdate, errors::ApiErrorResponse> {
use common_enums::enums;
use common_utils::pii;
let mut updated_connector_customer_data: std::collections::HashMap<String, serde_json::Value> =
customer
.connector_customer
.as_ref()
.and_then(|cc| serde_json::from_value(cc.peek().clone()).ok())
.unwrap_or_default();
for (_, mca) in mca_cache.iter() {
let key = match mca.connector_type {
enums::ConnectorType::PayoutProcessor => {
format!(
"{}_{}",
mca.profile_id.get_string_repr(),
mca.connector_name
)
}
_ => mca.merchant_connector_id.get_string_repr().to_string(),
};
updated_connector_customer_data.insert(
key,
serde_json::Value::String(connector_customer_id.to_string()),
);
}
Ok(
hyperswitch_domain_models::customer::CustomerUpdate::ConnectorCustomer {
connector_customer: Some(pii::SecretSerdeValue::new(
serde_json::to_value(updated_connector_customer_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize connector customer data")?,
)),
},
)
}
| {
"crate": "router",
"file": "crates/router/src/core/payment_methods/migration.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-7829879502373524080 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/core/payment_methods/vault.rs
// Contains: 8 structs, 2 enums
use common_enums::PaymentMethodType;
#[cfg(feature = "v2")]
use common_utils::request;
use common_utils::{
crypto::{DecodeMessage, EncodeMessage, GcmAes256},
ext_traits::{BytesExt, Encode},
generate_id_with_default_len, id_type,
pii::Email,
};
use error_stack::{report, ResultExt};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::router_flow_types::{
ExternalVaultDeleteFlow, ExternalVaultRetrieveFlow,
};
use hyperswitch_domain_models::{
router_data_v2::flow_common_types::VaultConnectorFlowData, types::VaultRouterData,
};
use masking::PeekInterface;
use router_env::{instrument, tracing};
use scheduler::{types::process_data, utils as process_tracker_utils};
#[cfg(feature = "payouts")]
use crate::types::api::payouts;
use crate::{
consts,
core::{
errors::{self, ConnectorErrorExt, CustomResult, RouterResult},
payments, utils as core_utils,
},
db, logger,
routes::{self, metrics},
services::{self, connector_integration_interface::RouterDataConversion},
types::{
self, api, domain,
storage::{self, enums},
},
utils::StringExt,
};
#[cfg(feature = "v2")]
use crate::{
core::{
errors::StorageErrorExt,
payment_methods::{transformers as pm_transforms, utils},
payments::{self as payments_core, helpers as payment_helpers},
},
headers, settings,
types::payment_methods as pm_types,
utils::{ext_traits::OptionExt, ConnectorResponseExt},
};
const VAULT_SERVICE_NAME: &str = "CARD";
pub struct SupplementaryVaultData {
pub customer_id: Option<id_type::CustomerId>,
pub payment_method_id: Option<String>,
}
pub trait Vaultable: Sized {
fn get_value1(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError>;
fn get_value2(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
Ok(String::new())
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError>;
}
impl Vaultable for domain::Card {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = domain::TokenizedCardValue1 {
card_number: self.card_number.peek().clone(),
exp_year: self.card_exp_year.peek().clone(),
exp_month: self.card_exp_month.peek().clone(),
nickname: self.nick_name.as_ref().map(|name| name.peek().clone()),
card_last_four: None,
card_token: None,
card_holder_name: self.card_holder_name.clone(),
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode card value1")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = domain::TokenizedCardValue2 {
card_security_code: Some(self.card_cvc.peek().clone()),
card_fingerprint: None,
external_id: None,
customer_id,
payment_method_id: None,
};
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode card value2")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: domain::TokenizedCardValue1 = value1
.parse_struct("TokenizedCardValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into card value1")?;
let value2: domain::TokenizedCardValue2 = value2
.parse_struct("TokenizedCardValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into card value2")?;
let card = Self {
card_number: cards::CardNumber::try_from(value1.card_number)
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Invalid card number format from the mock locker")?,
card_exp_month: value1.exp_month.into(),
card_exp_year: value1.exp_year.into(),
card_cvc: value2.card_security_code.unwrap_or_default().into(),
card_issuer: None,
card_network: None,
bank_code: None,
card_issuing_country: None,
card_type: None,
nick_name: value1.nickname.map(masking::Secret::new),
card_holder_name: value1.card_holder_name,
co_badged_card_data: None,
};
let supp_data = SupplementaryVaultData {
customer_id: value2.customer_id,
payment_method_id: value2.payment_method_id,
};
Ok((card, supp_data))
}
}
impl Vaultable for domain::BankTransferData {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = domain::TokenizedBankTransferValue1 {
data: self.to_owned(),
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode bank transfer data")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = domain::TokenizedBankTransferValue2 { customer_id };
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode bank transfer supplementary data")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: domain::TokenizedBankTransferValue1 = value1
.parse_struct("TokenizedBankTransferValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into bank transfer data")?;
let value2: domain::TokenizedBankTransferValue2 = value2
.parse_struct("TokenizedBankTransferValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into supplementary bank transfer data")?;
let bank_transfer_data = value1.data;
let supp_data = SupplementaryVaultData {
customer_id: value2.customer_id,
payment_method_id: None,
};
Ok((bank_transfer_data, supp_data))
}
}
impl Vaultable for domain::WalletData {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = domain::TokenizedWalletValue1 {
data: self.to_owned(),
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode wallet data value1")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = domain::TokenizedWalletValue2 { customer_id };
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode wallet data value2")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: domain::TokenizedWalletValue1 = value1
.parse_struct("TokenizedWalletValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into wallet data value1")?;
let value2: domain::TokenizedWalletValue2 = value2
.parse_struct("TokenizedWalletValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into wallet data value2")?;
let wallet = value1.data;
let supp_data = SupplementaryVaultData {
customer_id: value2.customer_id,
payment_method_id: None,
};
Ok((wallet, supp_data))
}
}
impl Vaultable for domain::BankRedirectData {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = domain::TokenizedBankRedirectValue1 {
data: self.to_owned(),
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode bank redirect data")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = domain::TokenizedBankRedirectValue2 { customer_id };
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode bank redirect supplementary data")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: domain::TokenizedBankRedirectValue1 = value1
.parse_struct("TokenizedBankRedirectValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into bank redirect data")?;
let value2: domain::TokenizedBankRedirectValue2 = value2
.parse_struct("TokenizedBankRedirectValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into supplementary bank redirect data")?;
let bank_transfer_data = value1.data;
let supp_data = SupplementaryVaultData {
customer_id: value2.customer_id,
payment_method_id: None,
};
Ok((bank_transfer_data, supp_data))
}
}
impl Vaultable for domain::BankDebitData {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = domain::TokenizedBankDebitValue1 {
data: self.to_owned(),
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode bank debit data")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = domain::TokenizedBankDebitValue2 { customer_id };
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode bank debit supplementary data")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: domain::TokenizedBankDebitValue1 = value1
.parse_struct("TokenizedBankDebitValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into bank debit data")?;
let value2: domain::TokenizedBankDebitValue2 = value2
.parse_struct("TokenizedBankDebitValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into supplementary bank debit data")?;
let bank_transfer_data = value1.data;
let supp_data = SupplementaryVaultData {
customer_id: value2.customer_id,
payment_method_id: None,
};
Ok((bank_transfer_data, supp_data))
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum VaultPaymentMethod {
Card(String),
Wallet(String),
BankTransfer(String),
BankRedirect(String),
BankDebit(String),
}
impl Vaultable for domain::PaymentMethodData {
fn get_value1(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = match self {
Self::Card(card) => VaultPaymentMethod::Card(card.get_value1(customer_id)?),
Self::Wallet(wallet) => VaultPaymentMethod::Wallet(wallet.get_value1(customer_id)?),
Self::BankTransfer(bank_transfer) => {
VaultPaymentMethod::BankTransfer(bank_transfer.get_value1(customer_id)?)
}
Self::BankRedirect(bank_redirect) => {
VaultPaymentMethod::BankRedirect(bank_redirect.get_value1(customer_id)?)
}
Self::BankDebit(bank_debit) => {
VaultPaymentMethod::BankDebit(bank_debit.get_value1(customer_id)?)
}
_ => Err(errors::VaultError::PaymentMethodNotSupported)
.attach_printable("Payment method not supported")?,
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode payment method value1")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = match self {
Self::Card(card) => VaultPaymentMethod::Card(card.get_value2(customer_id)?),
Self::Wallet(wallet) => VaultPaymentMethod::Wallet(wallet.get_value2(customer_id)?),
Self::BankTransfer(bank_transfer) => {
VaultPaymentMethod::BankTransfer(bank_transfer.get_value2(customer_id)?)
}
Self::BankRedirect(bank_redirect) => {
VaultPaymentMethod::BankRedirect(bank_redirect.get_value2(customer_id)?)
}
Self::BankDebit(bank_debit) => {
VaultPaymentMethod::BankDebit(bank_debit.get_value2(customer_id)?)
}
_ => Err(errors::VaultError::PaymentMethodNotSupported)
.attach_printable("Payment method not supported")?,
};
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode payment method value2")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: VaultPaymentMethod = value1
.parse_struct("PaymentMethodValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into payment method value 1")?;
let value2: VaultPaymentMethod = value2
.parse_struct("PaymentMethodValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into payment method value 2")?;
match (value1, value2) {
(VaultPaymentMethod::Card(mvalue1), VaultPaymentMethod::Card(mvalue2)) => {
let (card, supp_data) = domain::Card::from_values(mvalue1, mvalue2)?;
Ok((Self::Card(card), supp_data))
}
(VaultPaymentMethod::Wallet(mvalue1), VaultPaymentMethod::Wallet(mvalue2)) => {
let (wallet, supp_data) = domain::WalletData::from_values(mvalue1, mvalue2)?;
Ok((Self::Wallet(wallet), supp_data))
}
(
VaultPaymentMethod::BankTransfer(mvalue1),
VaultPaymentMethod::BankTransfer(mvalue2),
) => {
let (bank_transfer, supp_data) =
domain::BankTransferData::from_values(mvalue1, mvalue2)?;
Ok((Self::BankTransfer(Box::new(bank_transfer)), supp_data))
}
(
VaultPaymentMethod::BankRedirect(mvalue1),
VaultPaymentMethod::BankRedirect(mvalue2),
) => {
let (bank_redirect, supp_data) =
domain::BankRedirectData::from_values(mvalue1, mvalue2)?;
Ok((Self::BankRedirect(bank_redirect), supp_data))
}
(VaultPaymentMethod::BankDebit(mvalue1), VaultPaymentMethod::BankDebit(mvalue2)) => {
let (bank_debit, supp_data) = domain::BankDebitData::from_values(mvalue1, mvalue2)?;
Ok((Self::BankDebit(bank_debit), supp_data))
}
_ => Err(errors::VaultError::PaymentMethodNotSupported)
.attach_printable("Payment method not supported"),
}
}
}
#[cfg(feature = "payouts")]
impl Vaultable for api::CardPayout {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = api::TokenizedCardValue1 {
card_number: self.card_number.peek().clone(),
exp_year: self.expiry_year.peek().clone(),
exp_month: self.expiry_month.peek().clone(),
name_on_card: self.card_holder_name.clone().map(|n| n.peek().to_string()),
nickname: None,
card_last_four: None,
card_token: None,
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode card value1")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = api::TokenizedCardValue2 {
card_security_code: None,
card_fingerprint: None,
external_id: None,
customer_id,
payment_method_id: None,
};
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode card value2")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: api::TokenizedCardValue1 = value1
.parse_struct("TokenizedCardValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into card value1")?;
let value2: api::TokenizedCardValue2 = value2
.parse_struct("TokenizedCardValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into card value2")?;
let card = Self {
card_number: value1
.card_number
.parse()
.map_err(|_| errors::VaultError::FetchCardFailed)?,
expiry_month: value1.exp_month.into(),
expiry_year: value1.exp_year.into(),
card_holder_name: value1.name_on_card.map(masking::Secret::new),
};
let supp_data = SupplementaryVaultData {
customer_id: value2.customer_id,
payment_method_id: value2.payment_method_id,
};
Ok((card, supp_data))
}
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedWalletSensitiveValues {
pub email: Option<Email>,
pub telephone_number: Option<masking::Secret<String>>,
pub wallet_id: Option<masking::Secret<String>>,
pub wallet_type: PaymentMethodType,
pub dpan: Option<cards::CardNumber>,
pub expiry_month: Option<masking::Secret<String>>,
pub expiry_year: Option<masking::Secret<String>>,
pub card_holder_name: Option<masking::Secret<String>>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedWalletInsensitiveValues {
pub customer_id: Option<id_type::CustomerId>,
}
#[cfg(feature = "payouts")]
impl Vaultable for api::WalletPayout {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = match self {
Self::Paypal(paypal_data) => TokenizedWalletSensitiveValues {
email: paypal_data.email.clone(),
telephone_number: paypal_data.telephone_number.clone(),
wallet_id: paypal_data.paypal_id.clone(),
wallet_type: PaymentMethodType::Paypal,
dpan: None,
expiry_month: None,
expiry_year: None,
card_holder_name: None,
},
Self::Venmo(venmo_data) => TokenizedWalletSensitiveValues {
email: None,
telephone_number: venmo_data.telephone_number.clone(),
wallet_id: None,
wallet_type: PaymentMethodType::Venmo,
dpan: None,
expiry_month: None,
expiry_year: None,
card_holder_name: None,
},
Self::ApplePayDecrypt(apple_pay_decrypt_data) => TokenizedWalletSensitiveValues {
email: None,
telephone_number: None,
wallet_id: None,
wallet_type: PaymentMethodType::ApplePay,
dpan: Some(apple_pay_decrypt_data.dpan.clone()),
expiry_month: Some(apple_pay_decrypt_data.expiry_month.clone()),
expiry_year: Some(apple_pay_decrypt_data.expiry_year.clone()),
card_holder_name: apple_pay_decrypt_data.card_holder_name.clone(),
},
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode wallet data - TokenizedWalletSensitiveValues")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = TokenizedWalletInsensitiveValues { customer_id };
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode data - TokenizedWalletInsensitiveValues")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: TokenizedWalletSensitiveValues = value1
.parse_struct("TokenizedWalletSensitiveValues")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into wallet data wallet_sensitive_data")?;
let value2: TokenizedWalletInsensitiveValues = value2
.parse_struct("TokenizedWalletInsensitiveValues")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into wallet data wallet_insensitive_data")?;
let wallet = match value1.wallet_type {
PaymentMethodType::Paypal => Self::Paypal(api_models::payouts::Paypal {
email: value1.email,
telephone_number: value1.telephone_number,
paypal_id: value1.wallet_id,
}),
PaymentMethodType::Venmo => Self::Venmo(api_models::payouts::Venmo {
telephone_number: value1.telephone_number,
}),
PaymentMethodType::ApplePay => {
match (value1.dpan, value1.expiry_month, value1.expiry_year) {
(Some(dpan), Some(expiry_month), Some(expiry_year)) => {
Self::ApplePayDecrypt(api_models::payouts::ApplePayDecrypt {
dpan,
expiry_month,
expiry_year,
card_holder_name: value1.card_holder_name,
})
}
_ => Err(errors::VaultError::ResponseDeserializationFailed)?,
}
}
_ => Err(errors::VaultError::PayoutMethodNotSupported)?,
};
let supp_data = SupplementaryVaultData {
customer_id: value2.customer_id,
payment_method_id: None,
};
Ok((wallet, supp_data))
}
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankSensitiveValues {
pub bank_account_number: Option<masking::Secret<String>>,
pub bank_routing_number: Option<masking::Secret<String>>,
pub bic: Option<masking::Secret<String>>,
pub bank_sort_code: Option<masking::Secret<String>>,
pub iban: Option<masking::Secret<String>>,
pub pix_key: Option<masking::Secret<String>>,
pub tax_id: Option<masking::Secret<String>>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankInsensitiveValues {
pub customer_id: Option<id_type::CustomerId>,
pub bank_name: Option<String>,
pub bank_country_code: Option<api::enums::CountryAlpha2>,
pub bank_city: Option<String>,
pub bank_branch: Option<String>,
}
#[cfg(feature = "payouts")]
impl Vaultable for api::BankPayout {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let bank_sensitive_data = match self {
Self::Ach(b) => TokenizedBankSensitiveValues {
bank_account_number: Some(b.bank_account_number.clone()),
bank_routing_number: Some(b.bank_routing_number.to_owned()),
bic: None,
bank_sort_code: None,
iban: None,
pix_key: None,
tax_id: None,
},
Self::Bacs(b) => TokenizedBankSensitiveValues {
bank_account_number: Some(b.bank_account_number.to_owned()),
bank_routing_number: None,
bic: None,
bank_sort_code: Some(b.bank_sort_code.to_owned()),
iban: None,
pix_key: None,
tax_id: None,
},
Self::Sepa(b) => TokenizedBankSensitiveValues {
bank_account_number: None,
bank_routing_number: None,
bic: b.bic.to_owned(),
bank_sort_code: None,
iban: Some(b.iban.to_owned()),
pix_key: None,
tax_id: None,
},
Self::Pix(bank_details) => TokenizedBankSensitiveValues {
bank_account_number: Some(bank_details.bank_account_number.to_owned()),
bank_routing_number: None,
bic: None,
bank_sort_code: None,
iban: None,
pix_key: Some(bank_details.pix_key.to_owned()),
tax_id: bank_details.tax_id.to_owned(),
},
};
bank_sensitive_data
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode data - bank_sensitive_data")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let bank_insensitive_data = match self {
Self::Ach(b) => TokenizedBankInsensitiveValues {
customer_id,
bank_name: b.bank_name.to_owned(),
bank_country_code: b.bank_country_code.to_owned(),
bank_city: b.bank_city.to_owned(),
bank_branch: None,
},
Self::Bacs(b) => TokenizedBankInsensitiveValues {
customer_id,
bank_name: b.bank_name.to_owned(),
bank_country_code: b.bank_country_code.to_owned(),
bank_city: b.bank_city.to_owned(),
bank_branch: None,
},
Self::Sepa(bank_details) => TokenizedBankInsensitiveValues {
customer_id,
bank_name: bank_details.bank_name.to_owned(),
bank_country_code: bank_details.bank_country_code.to_owned(),
bank_city: bank_details.bank_city.to_owned(),
bank_branch: None,
},
Self::Pix(bank_details) => TokenizedBankInsensitiveValues {
customer_id,
bank_name: bank_details.bank_name.to_owned(),
bank_country_code: None,
bank_city: None,
bank_branch: bank_details.bank_branch.to_owned(),
},
};
bank_insensitive_data
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode wallet data bank_insensitive_data")
}
fn from_values(
bank_sensitive_data: String,
bank_insensitive_data: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let bank_sensitive_data: TokenizedBankSensitiveValues = bank_sensitive_data
.parse_struct("TokenizedBankValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into bank data bank_sensitive_data")?;
let bank_insensitive_data: TokenizedBankInsensitiveValues = bank_insensitive_data
.parse_struct("TokenizedBankValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into wallet data bank_insensitive_data")?;
let bank = match (
// ACH + BACS + PIX
bank_sensitive_data.bank_account_number.to_owned(),
bank_sensitive_data.bank_routing_number.to_owned(), // ACH
bank_sensitive_data.bank_sort_code.to_owned(), // BACS
// SEPA
bank_sensitive_data.iban.to_owned(),
bank_sensitive_data.bic,
// PIX
bank_sensitive_data.pix_key,
bank_sensitive_data.tax_id,
) {
(Some(ban), Some(brn), None, None, None, None, None) => {
Self::Ach(payouts::AchBankTransfer {
bank_account_number: ban,
bank_routing_number: brn,
bank_name: bank_insensitive_data.bank_name,
bank_country_code: bank_insensitive_data.bank_country_code,
bank_city: bank_insensitive_data.bank_city,
})
}
(Some(ban), None, Some(bsc), None, None, None, None) => {
Self::Bacs(payouts::BacsBankTransfer {
bank_account_number: ban,
bank_sort_code: bsc,
bank_name: bank_insensitive_data.bank_name,
bank_country_code: bank_insensitive_data.bank_country_code,
bank_city: bank_insensitive_data.bank_city,
})
}
(None, None, None, Some(iban), bic, None, None) => {
Self::Sepa(payouts::SepaBankTransfer {
iban,
bic,
bank_name: bank_insensitive_data.bank_name,
bank_country_code: bank_insensitive_data.bank_country_code,
bank_city: bank_insensitive_data.bank_city,
})
}
(Some(ban), None, None, None, None, Some(pix_key), tax_id) => {
Self::Pix(payouts::PixBankTransfer {
bank_account_number: ban,
bank_branch: bank_insensitive_data.bank_branch,
bank_name: bank_insensitive_data.bank_name,
pix_key,
tax_id,
})
}
_ => Err(errors::VaultError::ResponseDeserializationFailed)?,
};
let supp_data = SupplementaryVaultData {
customer_id: bank_insensitive_data.customer_id,
payment_method_id: None,
};
Ok((bank, supp_data))
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum VaultPayoutMethod {
Card(String),
Bank(String),
Wallet(String),
BankRedirect(String),
}
#[cfg(feature = "payouts")]
impl Vaultable for api::PayoutMethodData {
fn get_value1(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = match self {
Self::Card(card) => VaultPayoutMethod::Card(card.get_value1(customer_id)?),
Self::Bank(bank) => VaultPayoutMethod::Bank(bank.get_value1(customer_id)?),
Self::Wallet(wallet) => VaultPayoutMethod::Wallet(wallet.get_value1(customer_id)?),
Self::BankRedirect(bank_redirect) => {
VaultPayoutMethod::BankRedirect(bank_redirect.get_value1(customer_id)?)
}
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode payout method value1")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = match self {
Self::Card(card) => VaultPayoutMethod::Card(card.get_value2(customer_id)?),
Self::Bank(bank) => VaultPayoutMethod::Bank(bank.get_value2(customer_id)?),
Self::Wallet(wallet) => VaultPayoutMethod::Wallet(wallet.get_value2(customer_id)?),
Self::BankRedirect(bank_redirect) => {
VaultPayoutMethod::BankRedirect(bank_redirect.get_value2(customer_id)?)
}
};
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode payout method value2")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: VaultPayoutMethod = value1
.parse_struct("VaultMethodValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into vault method value 1")?;
let value2: VaultPayoutMethod = value2
.parse_struct("VaultMethodValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into vault method value 2")?;
match (value1, value2) {
(VaultPayoutMethod::Card(mvalue1), VaultPayoutMethod::Card(mvalue2)) => {
let (card, supp_data) = api::CardPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Card(card), supp_data))
}
(VaultPayoutMethod::Bank(mvalue1), VaultPayoutMethod::Bank(mvalue2)) => {
let (bank, supp_data) = api::BankPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Bank(bank), supp_data))
}
(VaultPayoutMethod::Wallet(mvalue1), VaultPayoutMethod::Wallet(mvalue2)) => {
let (wallet, supp_data) = api::WalletPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Wallet(wallet), supp_data))
}
(
VaultPayoutMethod::BankRedirect(mvalue1),
VaultPayoutMethod::BankRedirect(mvalue2),
) => {
let (bank_redirect, supp_data) =
api::BankRedirectPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::BankRedirect(bank_redirect), supp_data))
}
_ => Err(errors::VaultError::PayoutMethodNotSupported)
.attach_printable("Payout method not supported"),
}
}
}
#[cfg(feature = "payouts")]
impl Vaultable for api::BankRedirectPayout {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = match self {
Self::Interac(interac_data) => TokenizedBankRedirectSensitiveValues {
email: interac_data.email.clone(),
bank_redirect_type: PaymentMethodType::Interac,
},
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable(
"Failed to encode bank redirect data - TokenizedBankRedirectSensitiveValues",
)
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = TokenizedBankRedirectInsensitiveValues { customer_id };
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode wallet data value2")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: TokenizedBankRedirectSensitiveValues = value1
.parse_struct("TokenizedBankRedirectSensitiveValues")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into wallet data value1")?;
let value2: TokenizedBankRedirectInsensitiveValues = value2
.parse_struct("TokenizedBankRedirectInsensitiveValues")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into wallet data value2")?;
let bank_redirect = match value1.bank_redirect_type {
PaymentMethodType::Interac => Self::Interac(api_models::payouts::Interac {
email: value1.email,
}),
_ => Err(errors::VaultError::PayoutMethodNotSupported)
.attach_printable("Payout method not supported")?,
};
let supp_data = SupplementaryVaultData {
customer_id: value2.customer_id,
payment_method_id: None,
};
Ok((bank_redirect, supp_data))
}
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankRedirectSensitiveValues {
pub email: Email,
pub bank_redirect_type: PaymentMethodType,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankRedirectInsensitiveValues {
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MockTokenizeDBValue {
pub value1: String,
pub value2: String,
}
pub struct Vault;
impl Vault {
#[instrument(skip_all)]
pub async fn get_payment_method_data_from_locker(
state: &routes::SessionState,
lookup_key: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<(Option<domain::PaymentMethodData>, SupplementaryVaultData)> {
let de_tokenize =
get_tokenized_data(state, lookup_key, true, merchant_key_store.key.get_inner()).await?;
let (payment_method, customer_id) =
domain::PaymentMethodData::from_values(de_tokenize.value1, de_tokenize.value2)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing Payment Method from Values")?;
Ok((Some(payment_method), customer_id))
}
#[instrument(skip_all)]
pub async fn store_payment_method_data_in_locker(
state: &routes::SessionState,
token_id: Option<String>,
payment_method: &domain::PaymentMethodData,
customer_id: Option<id_type::CustomerId>,
pm: enums::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<String> {
let value1 = payment_method
.get_value1(customer_id.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value1 for locker")?;
let value2 = payment_method
.get_value2(customer_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value12 for locker")?;
let lookup_key = token_id.unwrap_or_else(|| generate_id_with_default_len("token"));
let lookup_key = create_tokenize(
state,
value1,
Some(value2),
lookup_key,
merchant_key_store.key.get_inner(),
)
.await?;
add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?;
metrics::TOKENIZED_DATA_COUNT.add(1, &[]);
Ok(lookup_key)
}
#[cfg(feature = "payouts")]
#[instrument(skip_all)]
pub async fn get_payout_method_data_from_temporary_locker(
state: &routes::SessionState,
lookup_key: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<(Option<api::PayoutMethodData>, SupplementaryVaultData)> {
let de_tokenize =
get_tokenized_data(state, lookup_key, true, merchant_key_store.key.get_inner()).await?;
let (payout_method, supp_data) =
api::PayoutMethodData::from_values(de_tokenize.value1, de_tokenize.value2)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing Payout Method from Values")?;
Ok((Some(payout_method), supp_data))
}
#[cfg(feature = "payouts")]
#[instrument(skip_all)]
pub async fn store_payout_method_data_in_locker(
state: &routes::SessionState,
token_id: Option<String>,
payout_method: &api::PayoutMethodData,
customer_id: Option<id_type::CustomerId>,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<String> {
let value1 = payout_method
.get_value1(customer_id.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value1 for locker")?;
let value2 = payout_method
.get_value2(customer_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value2 for locker")?;
let lookup_key =
token_id.unwrap_or_else(|| generate_id_with_default_len("temporary_token"));
let lookup_key = create_tokenize(
state,
value1,
Some(value2),
lookup_key,
merchant_key_store.key.get_inner(),
)
.await?;
// add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?;
// scheduler_metrics::TOKENIZED_DATA_COUNT.add(1, &[]);
Ok(lookup_key)
}
#[instrument(skip_all)]
pub async fn delete_locker_payment_method_by_lookup_key(
state: &routes::SessionState,
lookup_key: &Option<String>,
) {
if let Some(lookup_key) = lookup_key {
delete_tokenized_data(state, lookup_key)
.await
.map(|_| logger::info!("Card From locker deleted Successfully"))
.map_err(|err| logger::error!("Error: Deleting Card From Redis Locker : {:?}", err))
.ok();
}
}
}
//------------------------------------------------TokenizeService------------------------------------------------
#[inline(always)]
fn get_redis_locker_key(lookup_key: &str) -> String {
format!("{}_{}", consts::LOCKER_REDIS_PREFIX, lookup_key)
}
#[instrument(skip(state, value1, value2))]
pub async fn create_tokenize(
state: &routes::SessionState,
value1: String,
value2: Option<String>,
lookup_key: String,
encryption_key: &masking::Secret<Vec<u8>>,
) -> RouterResult<String> {
let redis_key = get_redis_locker_key(lookup_key.as_str());
let func = || async {
metrics::CREATED_TOKENIZED_CARD.add(1, &[]);
let payload_to_be_encrypted = api::TokenizePayloadRequest {
value1: value1.clone(),
value2: value2.clone().unwrap_or_default(),
lookup_key: lookup_key.clone(),
service_name: VAULT_SERVICE_NAME.to_string(),
};
let payload = payload_to_be_encrypted
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let encrypted_payload = GcmAes256
.encode_message(encryption_key.peek().as_ref(), payload.as_bytes())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode redis temp locker data")?;
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
redis_conn
.set_key_if_not_exists_with_expiry(
&redis_key.as_str().into(),
bytes::Bytes::from(encrypted_payload),
Some(i64::from(consts::LOCKER_REDIS_EXPIRY_SECONDS)),
)
.await
.map(|_| lookup_key.clone())
.inspect_err(|error| {
metrics::TEMP_LOCKER_FAILURES.add(1, &[]);
logger::error!(?error, "Failed to store tokenized data in Redis");
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error from redis locker")
};
match func().await {
Ok(s) => {
logger::info!(
"Insert payload in redis locker successful with lookup key: {:?}",
redis_key
);
Ok(s)
}
Err(err) => {
logger::error!("Redis Temp locker Failed: {:?}", err);
Err(err)
}
}
}
#[instrument(skip(state))]
pub async fn get_tokenized_data(
state: &routes::SessionState,
lookup_key: &str,
_should_get_value2: bool,
encryption_key: &masking::Secret<Vec<u8>>,
) -> RouterResult<api::TokenizePayloadRequest> {
let redis_key = get_redis_locker_key(lookup_key);
let func = || async {
metrics::GET_TOKENIZED_CARD.add(1, &[]);
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let response = redis_conn
.get_key::<bytes::Bytes>(&redis_key.as_str().into())
.await;
match response {
Ok(resp) => {
let decrypted_payload = GcmAes256
.decode_message(
encryption_key.peek().as_ref(),
masking::Secret::new(resp.into()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to decode redis temp locker data")?;
let get_response: api::TokenizePayloadRequest =
bytes::Bytes::from(decrypted_payload)
.parse_struct("TokenizePayloadRequest")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Error getting TokenizePayloadRequest from tokenize response",
)?;
Ok(get_response)
}
Err(err) => {
metrics::TEMP_LOCKER_FAILURES.add(1, &[]);
Err(err).change_context(errors::ApiErrorResponse::UnprocessableEntity {
message: "Token is invalid or expired".into(),
})
}
}
};
match func().await {
Ok(s) => {
logger::info!(
"Fetch payload in redis locker successful with lookup key: {:?}",
redis_key
);
Ok(s)
}
Err(err) => {
logger::error!("Redis Temp locker Failed: {:?}", err);
Err(err)
}
}
}
#[instrument(skip(state))]
pub async fn delete_tokenized_data(
state: &routes::SessionState,
lookup_key: &str,
) -> RouterResult<()> {
let redis_key = get_redis_locker_key(lookup_key);
let func = || async {
metrics::DELETED_TOKENIZED_CARD.add(1, &[]);
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let response = redis_conn.delete_key(&redis_key.as_str().into()).await;
match response {
Ok(redis_interface::DelReply::KeyDeleted) => Ok(()),
Ok(redis_interface::DelReply::KeyNotDeleted) => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Token invalid or expired")
}
Err(err) => {
metrics::TEMP_LOCKER_FAILURES.add(1, &[]);
Err(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| {
format!("Failed to delete from redis locker: {err:?}")
})
}
}
};
match func().await {
Ok(s) => {
logger::info!(
"Delete payload in redis locker successful with lookup key: {:?}",
redis_key
);
Ok(s)
}
Err(err) => {
logger::error!("Redis Temp locker Failed: {:?}", err);
Err(err)
}
}
}
#[cfg(feature = "v2")]
async fn create_vault_request<R: pm_types::VaultingInterface>(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
payload: Vec<u8>,
tenant_id: id_type::TenantId,
) -> CustomResult<request::Request, errors::VaultError> {
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = services::encryption::jws_sign_payload(
&payload,
&locker.locker_signing_key_id,
private_key,
)
.await
.change_context(errors::VaultError::RequestEncryptionFailed)?;
let jwe_payload = pm_transforms::create_jwe_body_for_vault(jwekey, &jws).await?;
let mut url = locker.host.to_owned();
url.push_str(R::get_vaulting_request_url());
let mut request = request::Request::new(services::Method::Post, &url);
request.add_header(
headers::CONTENT_TYPE,
consts::VAULT_HEADER_CONTENT_TYPE.into(),
);
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
request.set_body(request::RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn call_to_vault<V: pm_types::VaultingInterface>(
state: &routes::SessionState,
payload: Vec<u8>,
) -> CustomResult<String, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = state.conf.jwekey.get_inner();
let request =
create_vault_request::<V>(jwekey, locker, payload, state.tenant.tenant_id.to_owned())
.await?;
let response = services::call_connector_api(state, request, V::get_vaulting_flow_name())
.await
.change_context(errors::VaultError::VaultAPIError);
let jwe_body: services::JweBody = response
.get_response_inner("JweBody")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to get JweBody from vault response")?;
let decrypted_payload = pm_transforms::get_decrypted_vault_response_payload(
jwekey,
jwe_body,
locker.decryption_scheme.clone(),
)
.await
.change_context(errors::VaultError::ResponseDecryptionFailed)
.attach_printable("Error getting decrypted vault response payload")?;
Ok(decrypted_payload)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn get_fingerprint_id_from_vault<D: domain::VaultingDataInterface + serde::Serialize>(
state: &routes::SessionState,
data: &D,
key: String,
) -> CustomResult<String, errors::VaultError> {
let data = serde_json::to_string(data)
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode Vaulting data to string")?;
let payload = pm_types::VaultFingerprintRequest { key, data }
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode VaultFingerprintRequest")?;
let resp = call_to_vault::<pm_types::GetVaultFingerprint>(state, payload)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
let fingerprint_resp: pm_types::VaultFingerprintResponse = resp
.parse_struct("VaultFingerprintResponse")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to parse data into VaultFingerprintResponse")?;
Ok(fingerprint_resp.fingerprint_id)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn add_payment_method_to_vault(
state: &routes::SessionState,
merchant_context: &domain::MerchantContext,
pmd: &domain::PaymentMethodVaultingData,
existing_vault_id: Option<domain::VaultId>,
customer_id: &id_type::GlobalCustomerId,
) -> CustomResult<pm_types::AddVaultResponse, errors::VaultError> {
let payload = pm_types::AddVaultRequest {
entity_id: customer_id.to_owned(),
vault_id: existing_vault_id
.unwrap_or(domain::VaultId::generate(uuid::Uuid::now_v7().to_string())),
data: pmd,
ttl: state.conf.locker.ttl_for_storage_in_secs,
}
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode AddVaultRequest")?;
let resp = call_to_vault::<pm_types::AddVault>(state, payload)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
let stored_pm_resp: pm_types::AddVaultResponse = resp
.parse_struct("AddVaultResponse")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to parse data into AddVaultResponse")?;
Ok(stored_pm_resp)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn retrieve_payment_method_from_vault_internal(
state: &routes::SessionState,
merchant_context: &domain::MerchantContext,
vault_id: &domain::VaultId,
customer_id: &id_type::GlobalCustomerId,
) -> CustomResult<pm_types::VaultRetrieveResponse, errors::VaultError> {
let payload = pm_types::VaultRetrieveRequest {
entity_id: customer_id.to_owned(),
vault_id: vault_id.to_owned(),
}
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode VaultRetrieveRequest")?;
let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
let stored_pm_resp: pm_types::VaultRetrieveResponse = resp
.parse_struct("VaultRetrieveResponse")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to parse data into VaultRetrieveResponse")?;
Ok(stored_pm_resp)
}
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[instrument(skip_all)]
pub async fn retrieve_value_from_vault(
state: &routes::SessionState,
request: pm_types::VaultRetrieveRequest,
) -> CustomResult<serde_json::value::Value, errors::VaultError> {
let payload = request
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode VaultRetrieveRequest")?;
let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
let stored_resp: serde_json::Value = resp
.parse_struct("VaultRetrieveResponse")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to parse data into VaultRetrieveResponse")?;
Ok(stored_resp)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn retrieve_payment_method_from_vault_external(
state: &routes::SessionState,
merchant_account: &domain::MerchantAccount,
pm: &domain::PaymentMethod,
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
) -> RouterResult<pm_types::VaultRetrieveResponse> {
let connector_vault_id = pm
.locker_id
.clone()
.map(|id| id.get_string_repr().to_owned());
let merchant_connector_account = match &merchant_connector_account {
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => {
Ok(mca.as_ref())
}
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => {
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("MerchantConnectorDetails not supported for vault operations"))
}
}?;
let router_data = core_utils::construct_vault_router_data(
state,
merchant_account.get_id(),
merchant_connector_account,
None,
connector_vault_id,
None,
)
.await?;
let mut old_router_data = VaultConnectorFlowData::to_old_router_data(router_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Cannot construct router data for making the external vault retrieve api call",
)?;
let connector_name = merchant_connector_account.get_connector_name_as_string(); // always get the connector name from this call
let connector_data = api::ConnectorData::get_external_vault_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
Some(merchant_connector_account.get_id()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector data")?;
let connector_integration: services::BoxedVaultConnectorIntegrationInterface<
ExternalVaultRetrieveFlow,
types::VaultRequestData,
types::VaultResponseData,
> = connector_data.connector.get_connector_integration();
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&old_router_data,
payments_core::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_vault_failed_response()?;
get_vault_response_for_retrieve_payment_method_data::<ExternalVaultRetrieveFlow>(
router_data_resp,
)
}
#[cfg(feature = "v2")]
pub fn get_vault_response_for_retrieve_payment_method_data<F>(
router_data: VaultRouterData<F>,
) -> RouterResult<pm_types::VaultRetrieveResponse> {
match router_data.response {
Ok(response) => match response {
types::VaultResponseData::ExternalVaultRetrieveResponse { vault_data } => {
Ok(pm_types::VaultRetrieveResponse { data: vault_data })
}
types::VaultResponseData::ExternalVaultInsertResponse { .. }
| types::VaultResponseData::ExternalVaultDeleteResponse { .. }
| types::VaultResponseData::ExternalVaultCreateResponse { .. } => {
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid Vault Response"))
}
},
Err(err) => Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve payment method")),
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn retrieve_payment_method_from_vault_using_payment_token(
state: &routes::SessionState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
payment_token: &String,
payment_method_type: &common_enums::PaymentMethod,
) -> RouterResult<(domain::PaymentMethod, domain::PaymentMethodVaultingData)> {
let pm_token_data = utils::retrieve_payment_token_data(
state,
payment_token.to_string(),
Some(payment_method_type),
)
.await?;
let payment_method_id = match pm_token_data {
storage::PaymentTokenData::PermanentCard(card_token_data) => {
card_token_data.payment_method_id
}
storage::PaymentTokenData::TemporaryGeneric(_) => {
Err(errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(
"TemporaryGeneric Token not implemented".to_string(),
),
})?
}
storage::PaymentTokenData::AuthBankDebit(_) => {
Err(errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(
"AuthBankDebit Token not implemented".to_string(),
),
})?
}
};
let db = &*state.store;
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_method = db
.find_payment_method(
key_manager_state,
merchant_context.get_merchant_key_store(),
&payment_method_id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let vault_data =
retrieve_payment_method_from_vault(state, merchant_context, profile, &payment_method)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve payment method from vault")?
.data;
Ok((payment_method, vault_data))
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TemporaryVaultCvc {
card_cvc: masking::Secret<String>,
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn insert_cvc_using_payment_token(
state: &routes::SessionState,
payment_token: &String,
payment_method_data: api_models::payment_methods::PaymentMethodCreateData,
payment_method: common_enums::PaymentMethod,
fulfillment_time: i64,
encryption_key: &masking::Secret<Vec<u8>>,
) -> RouterResult<()> {
let card_cvc = domain::PaymentMethodVaultingData::try_from(payment_method_data)?
.get_card()
.and_then(|card| card.card_cvc.clone());
if let Some(card_cvc) = card_cvc {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let key = format!("pm_token_{payment_token}_{payment_method}_hyperswitch_cvc");
let payload_to_be_encrypted = TemporaryVaultCvc { card_cvc };
let payload = payload_to_be_encrypted
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
// Encrypt the CVC and store it in Redis
let encrypted_payload = GcmAes256
.encode_message(encryption_key.peek().as_ref(), payload.as_bytes())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode TemporaryVaultCvc for vault")?;
redis_conn
.set_key_if_not_exists_with_expiry(
&key.as_str().into(),
bytes::Bytes::from(encrypted_payload),
Some(fulfillment_time),
)
.await
.change_context(errors::StorageError::KVError)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add token in redis")?;
};
Ok(())
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn retrieve_and_delete_cvc_from_payment_token(
state: &routes::SessionState,
payment_token: &String,
payment_method: common_enums::PaymentMethod,
encryption_key: &masking::Secret<Vec<u8>>,
) -> RouterResult<masking::Secret<String>> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let key = format!("pm_token_{payment_token}_{payment_method}_hyperswitch_cvc",);
let data = redis_conn
.get_key::<bytes::Bytes>(&key.clone().into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch the token from redis")?;
// decrypt the cvc data
let decrypted_payload = GcmAes256
.decode_message(
encryption_key.peek().as_ref(),
masking::Secret::new(data.into()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to decode TemporaryVaultCvc from vault")?;
let cvc_data: TemporaryVaultCvc = bytes::Bytes::from(decrypted_payload)
.parse_struct("TemporaryVaultCvc")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize TemporaryVaultCvc")?;
// delete key after retrieving the cvc
redis_conn.delete_key(&key.into()).await.map_err(|err| {
logger::error!("Failed to delete token from redis: {:?}", err);
});
Ok(cvc_data.card_cvc)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn delete_payment_token(
state: &routes::SessionState,
key_for_token: &str,
intent_status: enums::IntentStatus,
) -> RouterResult<()> {
if ![
enums::IntentStatus::RequiresCustomerAction,
enums::IntentStatus::RequiresMerchantAction,
]
.contains(&intent_status)
{
utils::delete_payment_token_data(state, key_for_token)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to delete payment_token")?;
}
Ok(())
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn retrieve_payment_method_from_vault(
state: &routes::SessionState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
pm: &domain::PaymentMethod,
) -> RouterResult<pm_types::VaultRetrieveResponse> {
let is_external_vault_enabled = profile.is_external_vault_enabled();
match is_external_vault_enabled {
true => {
let external_vault_source = pm.external_vault_source.as_ref();
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
payments_core::helpers::get_merchant_connector_account_v2(
state,
merchant_context.get_merchant_key_store(),
external_vault_source,
)
.await
.attach_printable(
"failed to fetch merchant connector account for external vault retrieve",
)?,
));
retrieve_payment_method_from_vault_external(
state,
merchant_context.get_merchant_account(),
pm,
merchant_connector_account,
)
.await
}
false => {
let vault_id = pm
.locker_id
.clone()
.ok_or(errors::VaultError::MissingRequiredField {
field_name: "locker_id",
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Missing locker_id for VaultRetrieveRequest")?;
retrieve_payment_method_from_vault_internal(
state,
merchant_context,
&vault_id,
&pm.customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve payment method from vault")
}
}
}
#[cfg(feature = "v2")]
pub async fn delete_payment_method_data_from_vault_internal(
state: &routes::SessionState,
merchant_context: &domain::MerchantContext,
vault_id: domain::VaultId,
customer_id: &id_type::GlobalCustomerId,
) -> CustomResult<pm_types::VaultDeleteResponse, errors::VaultError> {
let payload = pm_types::VaultDeleteRequest {
entity_id: customer_id.to_owned(),
vault_id,
}
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode VaultDeleteRequest")?;
let resp = call_to_vault::<pm_types::VaultDelete>(state, payload)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
let stored_pm_resp: pm_types::VaultDeleteResponse = resp
.parse_struct("VaultDeleteResponse")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to parse data into VaultDeleteResponse")?;
Ok(stored_pm_resp)
}
#[cfg(feature = "v2")]
pub async fn delete_payment_method_data_from_vault_external(
state: &routes::SessionState,
merchant_account: &domain::MerchantAccount,
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
vault_id: domain::VaultId,
customer_id: &id_type::GlobalCustomerId,
) -> RouterResult<pm_types::VaultDeleteResponse> {
let connector_vault_id = vault_id.get_string_repr().to_owned();
// Extract MerchantConnectorAccount from the enum
let merchant_connector_account = match &merchant_connector_account {
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => {
Ok(mca.as_ref())
}
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => {
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("MerchantConnectorDetails not supported for vault operations"))
}
}?;
let router_data = core_utils::construct_vault_router_data(
state,
merchant_account.get_id(),
merchant_connector_account,
None,
Some(connector_vault_id),
None,
)
.await?;
let mut old_router_data = VaultConnectorFlowData::to_old_router_data(router_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Cannot construct router data for making the external vault delete api call",
)?;
let connector_name = merchant_connector_account.get_connector_name_as_string(); // always get the connector name from this call
let connector_data = api::ConnectorData::get_external_vault_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
Some(merchant_connector_account.get_id()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector data")?;
let connector_integration: services::BoxedVaultConnectorIntegrationInterface<
ExternalVaultDeleteFlow,
types::VaultRequestData,
types::VaultResponseData,
> = connector_data.connector.get_connector_integration();
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&old_router_data,
payments_core::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_vault_failed_response()?;
get_vault_response_for_delete_payment_method_data::<ExternalVaultDeleteFlow>(
router_data_resp,
customer_id.to_owned(),
)
}
#[cfg(feature = "v2")]
pub fn get_vault_response_for_delete_payment_method_data<F>(
router_data: VaultRouterData<F>,
customer_id: id_type::GlobalCustomerId,
) -> RouterResult<pm_types::VaultDeleteResponse> {
match router_data.response {
Ok(response) => match response {
types::VaultResponseData::ExternalVaultDeleteResponse { connector_vault_id } => {
Ok(pm_types::VaultDeleteResponse {
vault_id: domain::VaultId::generate(connector_vault_id), // converted to VaultId type
entity_id: customer_id,
})
}
types::VaultResponseData::ExternalVaultInsertResponse { .. }
| types::VaultResponseData::ExternalVaultRetrieveResponse { .. }
| types::VaultResponseData::ExternalVaultCreateResponse { .. } => {
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid Vault Response"))
}
},
Err(err) => Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve payment method")),
}
}
#[cfg(feature = "v2")]
pub async fn delete_payment_method_data_from_vault(
state: &routes::SessionState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
pm: &domain::PaymentMethod,
) -> RouterResult<pm_types::VaultDeleteResponse> {
let is_external_vault_enabled = profile.is_external_vault_enabled();
let vault_id = pm
.locker_id
.clone()
.get_required_value("locker_id")
.attach_printable("Missing locker_id in PaymentMethod")?;
match is_external_vault_enabled {
true => {
let external_vault_source = pm.external_vault_source.as_ref();
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
payments_core::helpers::get_merchant_connector_account_v2(
state,
merchant_context.get_merchant_key_store(),
external_vault_source,
)
.await
.attach_printable(
"failed to fetch merchant connector account for external vault delete",
)?,
));
delete_payment_method_data_from_vault_external(
state,
merchant_context.get_merchant_account(),
merchant_connector_account,
vault_id.clone(),
&pm.customer_id,
)
.await
}
false => delete_payment_method_data_from_vault_internal(
state,
merchant_context,
vault_id,
&pm.customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to delete payment method from vault"),
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn retrieve_payment_method_from_vault_external_v1(
state: &routes::SessionState,
merchant_id: &id_type::MerchantId,
pm: &domain::PaymentMethod,
merchant_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
) -> RouterResult<hyperswitch_domain_models::vault::PaymentMethodVaultingData> {
let connector_vault_id = pm.locker_id.clone().map(|id| id.to_string());
let router_data = core_utils::construct_vault_router_data(
state,
merchant_id,
&merchant_connector_account,
None,
connector_vault_id,
None,
)
.await?;
let old_router_data = VaultConnectorFlowData::to_old_router_data(router_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Cannot construct router data for making the external vault retrieve api call",
)?;
let connector_name = merchant_connector_account.get_connector_name_as_string();
let connector_data = api::ConnectorData::get_external_vault_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
Some(merchant_connector_account.get_id()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector data")?;
let connector_integration: services::BoxedVaultConnectorIntegrationInterface<
hyperswitch_domain_models::router_flow_types::ExternalVaultRetrieveFlow,
types::VaultRequestData,
types::VaultResponseData,
> = connector_data.connector.get_connector_integration();
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&old_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_vault_failed_response()?;
get_vault_response_for_retrieve_payment_method_data_v1(router_data_resp)
}
pub fn get_vault_response_for_retrieve_payment_method_data_v1<F>(
router_data: VaultRouterData<F>,
) -> RouterResult<hyperswitch_domain_models::vault::PaymentMethodVaultingData> {
match router_data.response {
Ok(response) => match response {
types::VaultResponseData::ExternalVaultRetrieveResponse { vault_data } => {
Ok(vault_data)
}
types::VaultResponseData::ExternalVaultInsertResponse { .. }
| types::VaultResponseData::ExternalVaultDeleteResponse { .. }
| types::VaultResponseData::ExternalVaultCreateResponse { .. } => {
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid Vault Response"))
}
},
Err(err) => {
logger::error!(
"Failed to retrieve payment method from external vault: {:?}",
err
);
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve payment method from external vault"))
}
}
}
// ********************************************** PROCESS TRACKER **********************************************
pub async fn add_delete_tokenized_data_task(
db: &dyn db::StorageInterface,
lookup_key: &str,
pm: enums::PaymentMethod,
) -> RouterResult<()> {
let runner = storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow;
let process_tracker_id = format!("{runner}_{lookup_key}");
let task = runner.to_string();
let tag = ["BASILISK-V3"];
let tracking_data = storage::TokenizeCoreWorkflow {
lookup_key: lookup_key.to_owned(),
pm,
};
let schedule_time = get_delete_tokenize_schedule_time(db, pm, 0)
.await
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain initial process tracker schedule time")?;
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
&task,
runner,
tag,
tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct delete tokenized data process tracker task")?;
let response = db.insert_process(process_tracker_entry).await;
response.map(|_| ()).or_else(|err| {
if err.current_context().is_db_unique_violation() {
Ok(())
} else {
Err(report!(errors::ApiErrorResponse::InternalServerError))
}
})
}
pub async fn start_tokenize_data_workflow(
state: &routes::SessionState,
tokenize_tracker: &storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let db = &*state.store;
let delete_tokenize_data = serde_json::from_value::<storage::TokenizeCoreWorkflow>(
tokenize_tracker.tracking_data.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"unable to convert into DeleteTokenizeByTokenRequest {:?}",
tokenize_tracker.tracking_data
)
})?;
match delete_tokenized_data(state, &delete_tokenize_data.lookup_key).await {
Ok(()) => {
logger::info!("Card From locker deleted Successfully");
//mark task as finished
db.as_scheduler()
.finish_process_with_business_status(
tokenize_tracker.clone(),
diesel_models::process_tracker::business_status::COMPLETED_BY_PT,
)
.await?;
}
Err(err) => {
logger::error!("Err: Deleting Card From Locker : {:?}", err);
retry_delete_tokenize(db, delete_tokenize_data.pm, tokenize_tracker.to_owned()).await?;
metrics::RETRIED_DELETE_DATA_COUNT.add(1, &[]);
}
}
Ok(())
}
pub async fn get_delete_tokenize_schedule_time(
db: &dyn db::StorageInterface,
pm: enums::PaymentMethod,
retry_count: i32,
) -> Option<time::PrimitiveDateTime> {
let redis_mapping = db::get_and_deserialize_key(
db,
&format!("pt_mapping_delete_{pm}_tokenize_data"),
"PaymentMethodsPTMapping",
)
.await;
let mapping = match redis_mapping {
Ok(x) => x,
Err(error) => {
logger::info!(?error, "Redis Mapping Error");
process_data::PaymentMethodsPTMapping::default()
}
};
let time_delta = process_tracker_utils::get_pm_schedule_time(mapping, pm, retry_count + 1);
process_tracker_utils::get_time_from_delta(time_delta)
}
pub async fn retry_delete_tokenize(
db: &dyn db::StorageInterface,
pm: enums::PaymentMethod,
pt: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let schedule_time = get_delete_tokenize_schedule_time(db, pm, pt.retry_count).await;
match schedule_time {
Some(s_time) => {
let retry_schedule = db
.as_scheduler()
.retry_process(pt, s_time)
.await
.map_err(Into::into);
metrics::TASKS_RESET_COUNT.add(
1,
router_env::metric_attributes!(("flow", "DeleteTokenizeData")),
);
retry_schedule
}
None => db
.as_scheduler()
.finish_process_with_business_status(
pt,
diesel_models::process_tracker::business_status::RETRIES_EXCEEDED,
)
.await
.map_err(Into::into),
}
}
// Fallback logic of old temp locker needs to be removed later
| {
"crate": "router",
"file": "crates/router/src/core/payment_methods/vault.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 8,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-4930095866742917626 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/bin/scheduler.rs
// Contains: 1 structs, 0 enums
use std::{collections::HashMap, str::FromStr, sync::Arc};
use actix_web::{dev::Server, web, Scope};
use api_models::health_check::SchedulerHealthCheckResponse;
use common_utils::ext_traits::{OptionExt, StringExt};
use diesel_models::process_tracker::{self as storage, business_status};
use error_stack::ResultExt;
use router::{
configs::settings::{CmdLineConf, Settings},
core::{
errors::{self, CustomResult},
health_check::HealthCheckInterface,
},
logger, routes,
services::{self, api},
workflows,
};
use router_env::{
instrument,
tracing::{self, Instrument},
};
use scheduler::{
consumer::workflows::ProcessTrackerWorkflow, errors::ProcessTrackerError,
workflows::ProcessTrackerWorkflows, SchedulerSessionState,
};
use storage_impl::errors::ApplicationError;
use tokio::sync::{mpsc, oneshot};
const SCHEDULER_FLOW: &str = "SCHEDULER_FLOW";
#[tokio::main]
async fn main() -> CustomResult<(), ProcessTrackerError> {
let cmd_line = <CmdLineConf as clap::Parser>::parse();
#[allow(clippy::expect_used)]
let conf = Settings::with_config_path(cmd_line.config_path)
.expect("Unable to construct application configuration");
let api_client = Box::new(
services::ProxyClient::new(&conf.proxy)
.change_context(ProcessTrackerError::ConfigurationError)?,
);
// channel for listening to redis disconnect events
let (redis_shutdown_signal_tx, redis_shutdown_signal_rx) = oneshot::channel();
let state = Box::pin(routes::AppState::new(
conf,
redis_shutdown_signal_tx,
api_client,
))
.await;
// channel to shutdown scheduler gracefully
let (tx, rx) = mpsc::channel(1);
let _task_handle = tokio::spawn(
router::receiver_for_error(redis_shutdown_signal_rx, tx.clone()).in_current_span(),
);
#[allow(clippy::expect_used)]
let scheduler_flow_str =
std::env::var(SCHEDULER_FLOW).expect("SCHEDULER_FLOW environment variable not set");
#[allow(clippy::expect_used)]
let scheduler_flow = scheduler::SchedulerFlow::from_str(&scheduler_flow_str)
.expect("Unable to parse SchedulerFlow from environment variable");
#[allow(clippy::print_stdout)] // The logger has not yet been initialized
#[cfg(feature = "vergen")]
{
println!(
"Starting {scheduler_flow} (Version: {})",
router_env::git_tag!()
);
}
let _guard = router_env::setup(
&state.conf.log,
&scheduler_flow_str,
[router_env::service_name!()],
);
#[allow(clippy::expect_used)]
let web_server = Box::pin(start_web_server(
state.clone(),
scheduler_flow_str.to_string(),
))
.await
.expect("Failed to create the server");
let _task_handle = tokio::spawn(
async move {
let _ = web_server.await;
logger::error!("The health check probe stopped working!");
}
.in_current_span(),
);
logger::debug!(startup_config=?state.conf);
start_scheduler(&state, scheduler_flow, (tx, rx)).await?;
logger::error!("Scheduler shut down");
Ok(())
}
pub async fn start_web_server(
state: routes::AppState,
service: String,
) -> errors::ApplicationResult<Server> {
let server = state
.conf
.scheduler
.as_ref()
.ok_or(ApplicationError::InvalidConfigurationValueError(
"Scheduler server is invalidly configured".into(),
))?
.server
.clone();
let web_server = actix_web::HttpServer::new(move || {
actix_web::App::new().service(Health::server(state.clone(), service.clone()))
})
.bind((server.host.as_str(), server.port))
.change_context(ApplicationError::ConfigurationError)?
.workers(server.workers)
.run();
let _ = web_server.handle();
Ok(web_server)
}
pub struct Health;
impl Health {
pub fn server(state: routes::AppState, service: String) -> Scope {
web::scope("health")
.app_data(web::Data::new(state))
.app_data(web::Data::new(service))
.service(web::resource("").route(web::get().to(health)))
.service(web::resource("/ready").route(web::get().to(deep_health_check)))
}
}
#[instrument(skip_all)]
pub async fn health() -> impl actix_web::Responder {
logger::info!("Scheduler health was called");
actix_web::HttpResponse::Ok().body("Scheduler health is good")
}
#[instrument(skip_all)]
pub async fn deep_health_check(
state: web::Data<routes::AppState>,
service: web::Data<String>,
) -> impl actix_web::Responder {
let mut checks = HashMap::new();
let stores = state.stores.clone();
let app_state = Arc::clone(&state.into_inner());
let service_name = service.into_inner();
for (tenant, _) in stores {
let session_state_res = app_state.clone().get_session_state(&tenant, None, || {
errors::ApiErrorResponse::MissingRequiredField {
field_name: "tenant_id",
}
.into()
});
let session_state = match session_state_res {
Ok(state) => state,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let report = deep_health_check_func(session_state, &service_name).await;
match report {
Ok(response) => {
checks.insert(
tenant,
serde_json::to_string(&response)
.map_err(|err| {
logger::error!(serialization_error=?err);
})
.unwrap_or_default(),
);
}
Err(err) => {
return api::log_and_return_error_response(err);
}
}
}
services::http_response_json(
serde_json::to_string(&checks)
.map_err(|err| {
logger::error!(serialization_error=?err);
})
.unwrap_or_default(),
)
}
#[instrument(skip_all)]
pub async fn deep_health_check_func(
state: routes::SessionState,
service: &str,
) -> errors::RouterResult<SchedulerHealthCheckResponse> {
logger::info!("{} deep health check was called", service);
logger::debug!("Database health check begin");
let db_status = state
.health_check_db()
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Database",
message,
})
})?;
logger::debug!("Database health check end");
logger::debug!("Redis health check begin");
let redis_status = state
.health_check_redis()
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Redis",
message,
})
})?;
let outgoing_req_check =
state
.health_check_outgoing()
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Outgoing Request",
message,
})
})?;
logger::debug!("Redis health check end");
let response = SchedulerHealthCheckResponse {
database: db_status,
redis: redis_status,
outgoing_request: outgoing_req_check,
};
Ok(response)
}
#[derive(Debug, Copy, Clone)]
pub struct WorkflowRunner;
#[async_trait::async_trait]
impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {
async fn trigger_workflow<'a>(
&'a self,
state: &'a routes::SessionState,
process: storage::ProcessTracker,
) -> CustomResult<(), ProcessTrackerError> {
let runner = process
.runner
.clone()
.get_required_value("runner")
.change_context(ProcessTrackerError::MissingRequiredField)
.attach_printable("Missing runner field in process information")?;
let runner: storage::ProcessTrackerRunner = runner
.parse_enum("ProcessTrackerRunner")
.change_context(ProcessTrackerError::UnexpectedFlow)
.attach_printable("Failed to parse workflow runner name")?;
let get_operation = |runner: storage::ProcessTrackerRunner| -> CustomResult<
Box<dyn ProcessTrackerWorkflow<routes::SessionState>>,
ProcessTrackerError,
> {
match runner {
storage::ProcessTrackerRunner::PaymentsSyncWorkflow => {
Ok(Box::new(workflows::payment_sync::PaymentsSyncWorkflow))
}
storage::ProcessTrackerRunner::RefundWorkflowRouter => {
Ok(Box::new(workflows::refund_router::RefundWorkflowRouter))
}
storage::ProcessTrackerRunner::ProcessDisputeWorkflow => {
Ok(Box::new(workflows::process_dispute::ProcessDisputeWorkflow))
}
storage::ProcessTrackerRunner::DisputeListWorkflow => {
Ok(Box::new(workflows::dispute_list::DisputeListWorkflow))
}
storage::ProcessTrackerRunner::InvoiceSyncflow => {
Ok(Box::new(workflows::invoice_sync::InvoiceSyncWorkflow))
}
storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow => Ok(Box::new(
workflows::tokenized_data::DeleteTokenizeDataWorkflow,
)),
storage::ProcessTrackerRunner::ApiKeyExpiryWorkflow => {
#[cfg(feature = "email")]
{
Ok(Box::new(workflows::api_key_expiry::ApiKeyExpiryWorkflow))
}
#[cfg(not(feature = "email"))]
{
Err(error_stack::report!(ProcessTrackerError::UnexpectedFlow))
.attach_printable(
"Cannot run API key expiry workflow when email feature is disabled",
)
}
}
storage::ProcessTrackerRunner::OutgoingWebhookRetryWorkflow => Ok(Box::new(
workflows::outgoing_webhook_retry::OutgoingWebhookRetryWorkflow,
)),
storage::ProcessTrackerRunner::AttachPayoutAccountWorkflow => {
#[cfg(feature = "payouts")]
{
Ok(Box::new(
workflows::attach_payout_account_workflow::AttachPayoutAccountWorkflow,
))
}
#[cfg(not(feature = "payouts"))]
{
Err(
error_stack::report!(ProcessTrackerError::UnexpectedFlow),
)
.attach_printable(
"Cannot run Stripe external account workflow when payouts feature is disabled",
)
}
}
storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow => Ok(Box::new(
workflows::payment_method_status_update::PaymentMethodStatusUpdateWorkflow,
)),
storage::ProcessTrackerRunner::PassiveRecoveryWorkflow => {
Ok(Box::new(workflows::revenue_recovery::ExecutePcrWorkflow))
}
}
};
let operation = get_operation(runner)?;
let app_state = &state.clone();
let output = operation.execute_workflow(state, process.clone()).await;
match output {
Ok(_) => operation.success_handler(app_state, process).await,
Err(error) => match operation
.error_handler(app_state, process.clone(), error)
.await
{
Ok(_) => (),
Err(error) => {
logger::error!(?error, "Failed while handling error");
let status = state
.get_db()
.as_scheduler()
.finish_process_with_business_status(
process,
business_status::GLOBAL_FAILURE,
)
.await;
if let Err(error) = status {
logger::error!(
?error,
"Failed while performing database operation: {}",
business_status::GLOBAL_FAILURE
);
}
}
},
};
Ok(())
}
}
async fn start_scheduler(
state: &routes::AppState,
scheduler_flow: scheduler::SchedulerFlow,
channel: (mpsc::Sender<()>, mpsc::Receiver<()>),
) -> CustomResult<(), ProcessTrackerError> {
let scheduler_settings = state
.conf
.scheduler
.clone()
.ok_or(ProcessTrackerError::ConfigurationError)?;
scheduler::start_process_tracker(
state,
scheduler_flow,
Arc::new(scheduler_settings),
channel,
WorkflowRunner {},
|state, tenant| {
Arc::new(state.clone())
.get_session_state(tenant, None, || ProcessTrackerError::TenantNotFound.into())
},
)
.await
}
| {
"crate": "router",
"file": "crates/router/src/bin/scheduler.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_8310263323250853712 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/workflows/revenue_recovery.rs
// Contains: 2 structs, 0 enums
#[cfg(feature = "v2")]
use std::collections::HashMap;
#[cfg(feature = "v2")]
use api_models::{enums::RevenueRecoveryAlgorithmType, payments::PaymentsGetIntentRequest};
use common_utils::errors::CustomResult;
#[cfg(feature = "v2")]
use common_utils::{
ext_traits::AsyncExt,
ext_traits::{StringExt, ValueExt},
id_type,
};
#[cfg(feature = "v2")]
use diesel_models::types::BillingConnectorPaymentMethodDetails;
#[cfg(feature = "v2")]
use error_stack::{Report, ResultExt};
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
use external_services::{
date_time, grpc_client::revenue_recovery::recovery_decider_client as external_grpc_client,
};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
payments::{payment_attempt, PaymentConfirmData, PaymentIntent, PaymentIntentData},
router_flow_types,
router_flow_types::Authorize,
};
#[cfg(feature = "v2")]
use masking::{ExposeInterface, PeekInterface, Secret};
#[cfg(feature = "v2")]
use rand::Rng;
use router_env::{
logger,
tracing::{self, instrument},
};
use scheduler::{
consumer::{self, workflows::ProcessTrackerWorkflow},
errors,
};
#[cfg(feature = "v2")]
use scheduler::{types::process_data, utils as scheduler_utils};
#[cfg(feature = "v2")]
use storage_impl::errors as storage_errors;
#[cfg(feature = "v2")]
use time::Date;
#[cfg(feature = "v2")]
use crate::core::payments::operations;
#[cfg(feature = "v2")]
use crate::routes::app::ReqState;
#[cfg(feature = "v2")]
use crate::services;
#[cfg(feature = "v2")]
use crate::types::storage::{
revenue_recovery::RetryLimitsConfig,
revenue_recovery_redis_operation::{
PaymentProcessorTokenStatus, PaymentProcessorTokenWithRetryInfo, RedisTokenManager,
},
};
#[cfg(feature = "v2")]
use crate::workflows::revenue_recovery::pcr::api;
#[cfg(feature = "v2")]
use crate::{
core::{
payments,
revenue_recovery::{self as pcr},
},
db::StorageInterface,
errors::StorageError,
types::{
api::{self as api_types},
domain,
storage::{
revenue_recovery as pcr_storage_types,
revenue_recovery_redis_operation::PaymentProcessorTokenDetails,
},
},
};
use crate::{routes::SessionState, types::storage};
pub struct ExecutePcrWorkflow;
#[cfg(feature = "v2")]
pub const REVENUE_RECOVERY: &str = "revenue_recovery";
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for ExecutePcrWorkflow {
#[cfg(feature = "v1")]
async fn execute_workflow<'a>(
&'a self,
_state: &'a SessionState,
_process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
Ok(())
}
#[cfg(feature = "v2")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let tracking_data = process
.tracking_data
.clone()
.parse_value::<pcr_storage_types::RevenueRecoveryWorkflowTrackingData>(
"PCRWorkflowTrackingData",
)?;
let request = PaymentsGetIntentRequest {
id: tracking_data.global_payment_id.clone(),
};
let revenue_recovery_payment_data =
extract_data_and_perform_action(state, &tracking_data).await?;
let merchant_context_from_revenue_recovery_payment_data =
domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
revenue_recovery_payment_data.merchant_account.clone(),
revenue_recovery_payment_data.key_store.clone(),
)));
let (payment_data, _, _) = payments::payments_intent_operation_core::<
api_types::PaymentGetIntent,
_,
_,
PaymentIntentData<api_types::PaymentGetIntent>,
>(
state,
state.get_req_state(),
merchant_context_from_revenue_recovery_payment_data.clone(),
revenue_recovery_payment_data.profile.clone(),
payments::operations::PaymentGetIntent,
request,
tracking_data.global_payment_id.clone(),
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
.await?;
match process.name.as_deref() {
Some("EXECUTE_WORKFLOW") => {
Box::pin(pcr::perform_execute_payment(
state,
&process,
&revenue_recovery_payment_data.profile.clone(),
merchant_context_from_revenue_recovery_payment_data.clone(),
&tracking_data,
&revenue_recovery_payment_data,
&payment_data.payment_intent,
))
.await
}
Some("PSYNC_WORKFLOW") => {
Box::pin(pcr::perform_payments_sync(
state,
&process,
&revenue_recovery_payment_data.profile.clone(),
merchant_context_from_revenue_recovery_payment_data.clone(),
&tracking_data,
&revenue_recovery_payment_data,
&payment_data.payment_intent,
))
.await?;
Ok(())
}
Some("CALCULATE_WORKFLOW") => {
Box::pin(pcr::perform_calculate_workflow(
state,
&process,
&revenue_recovery_payment_data.profile.clone(),
merchant_context_from_revenue_recovery_payment_data,
&tracking_data,
&revenue_recovery_payment_data,
&payment_data.payment_intent,
))
.await
}
_ => Err(errors::ProcessTrackerError::JobNotFound),
}
}
#[instrument(skip_all)]
async fn error_handler<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
error: errors::ProcessTrackerError,
) -> CustomResult<(), errors::ProcessTrackerError> {
logger::error!("Encountered error");
consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await
}
}
#[cfg(feature = "v2")]
pub(crate) async fn extract_data_and_perform_action(
state: &SessionState,
tracking_data: &pcr_storage_types::RevenueRecoveryWorkflowTrackingData,
) -> Result<pcr_storage_types::RevenueRecoveryPaymentData, errors::ProcessTrackerError> {
let db = &state.store;
let key_manager_state = &state.into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&tracking_data.merchant_id,
&db.get_master_key().to_vec().into(),
)
.await?;
let merchant_account = db
.find_merchant_account_by_merchant_id(
key_manager_state,
&tracking_data.merchant_id,
&key_store,
)
.await?;
let profile = db
.find_business_profile_by_profile_id(
key_manager_state,
&key_store,
&tracking_data.profile_id,
)
.await?;
let billing_mca = db
.find_merchant_connector_account_by_id(
key_manager_state,
&tracking_data.billing_mca_id,
&key_store,
)
.await?;
let pcr_payment_data = pcr_storage_types::RevenueRecoveryPaymentData {
merchant_account,
profile: profile.clone(),
key_store,
billing_mca,
retry_algorithm: profile
.revenue_recovery_retry_algorithm_type
.unwrap_or(tracking_data.revenue_recovery_retry),
psync_data: None,
};
Ok(pcr_payment_data)
}
#[cfg(feature = "v2")]
pub(crate) async fn get_schedule_time_to_retry_mit_payments(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
retry_count: i32,
) -> Option<time::PrimitiveDateTime> {
let key = "pt_mapping_pcr_retries";
let result = db
.find_config_by_key(key)
.await
.map(|value| value.config)
.and_then(|config| {
config
.parse_struct("RevenueRecoveryPaymentProcessTrackerMapping")
.change_context(StorageError::DeserializationFailed)
});
let mapping = result.map_or_else(
|error| {
if error.current_context().is_db_not_found() {
logger::debug!("Revenue Recovery retry config `{key}` not found, ignoring");
} else {
logger::error!(
?error,
"Failed to read Revenue Recovery retry config `{key}`"
);
}
process_data::RevenueRecoveryPaymentProcessTrackerMapping::default()
},
|mapping| {
logger::debug!(?mapping, "Using custom pcr payments retry config");
mapping
},
);
let time_delta =
scheduler_utils::get_pcr_payments_retry_schedule_time(mapping, merchant_id, retry_count);
scheduler_utils::get_time_from_delta(time_delta)
}
#[cfg(feature = "v2")]
pub(crate) async fn get_schedule_time_for_smart_retry(
state: &SessionState,
payment_intent: &PaymentIntent,
retry_after_time: Option<prost_types::Timestamp>,
token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,
) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
let card_config = &state.conf.revenue_recovery.card_config;
// Not populating it right now
let first_error_message = "None".to_string();
let retry_count_left = token_with_retry_info.monthly_retry_remaining;
let pg_error_code = token_with_retry_info.token_status.error_code.clone();
let card_info = token_with_retry_info
.token_status
.payment_processor_token_details
.clone();
let billing_state = payment_intent
.billing_address
.as_ref()
.and_then(|addr_enc| addr_enc.get_inner().address.as_ref())
.and_then(|details| details.state.as_ref())
.cloned();
let revenue_recovery_metadata = payment_intent
.feature_metadata
.as_ref()
.and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref());
let card_network = card_info.card_network.clone();
let total_retry_count_within_network = card_config.get_network_config(card_network.clone());
let card_network_str = card_network.map(|network| network.to_string());
let card_issuer_str = card_info.card_issuer.clone();
let card_funding_str = match card_info.card_type.as_deref() {
Some("card") => None,
Some(s) => Some(s.to_string()),
None => None,
};
let start_time_primitive = payment_intent.created_at;
let recovery_timestamp_config = &state.conf.revenue_recovery.recovery_timestamp;
let modified_start_time_primitive = start_time_primitive.saturating_add(
time::Duration::seconds(recovery_timestamp_config.initial_timestamp_in_seconds),
);
let start_time_proto = date_time::convert_to_prost_timestamp(modified_start_time_primitive);
let merchant_id = Some(payment_intent.merchant_id.get_string_repr().to_string());
let invoice_amount = Some(
payment_intent
.amount_details
.order_amount
.get_amount_as_i64(),
);
let invoice_currency = Some(payment_intent.amount_details.currency.to_string());
let billing_country = payment_intent
.billing_address
.as_ref()
.and_then(|addr_enc| addr_enc.get_inner().address.as_ref())
.and_then(|details| details.country.as_ref())
.map(|country| country.to_string());
let billing_city = payment_intent
.billing_address
.as_ref()
.and_then(|addr_enc| addr_enc.get_inner().address.as_ref())
.and_then(|details| details.city.as_ref())
.cloned();
let first_pg_error_code = revenue_recovery_metadata
.and_then(|metadata| metadata.first_payment_attempt_pg_error_code.clone());
let first_network_advice_code = revenue_recovery_metadata
.and_then(|metadata| metadata.first_payment_attempt_network_advice_code.clone());
let first_network_error_code = revenue_recovery_metadata
.and_then(|metadata| metadata.first_payment_attempt_network_decline_code.clone());
let invoice_due_date = revenue_recovery_metadata
.and_then(|metadata| metadata.invoice_next_billing_time)
.map(date_time::convert_to_prost_timestamp);
let decider_request = InternalDeciderRequest {
first_error_message,
billing_state,
card_funding: card_funding_str,
card_network: card_network_str,
card_issuer: card_issuer_str,
invoice_start_time: Some(start_time_proto),
retry_count: Some(token_with_retry_info.total_30_day_retries.into()),
merchant_id,
invoice_amount,
invoice_currency,
invoice_due_date,
billing_country,
billing_city,
attempt_currency: None,
attempt_status: None,
attempt_amount: None,
pg_error_code,
network_advice_code: None,
network_error_code: None,
first_pg_error_code,
first_network_advice_code,
first_network_error_code,
attempt_response_time: None,
payment_method_type: None,
payment_gateway: None,
retry_count_left: Some(retry_count_left.into()),
total_retry_count_within_network: Some(
total_retry_count_within_network
.max_retry_count_for_thirty_day
.into(),
),
first_error_msg_time: None,
wait_time: retry_after_time,
};
if let Some(mut client) = state.grpc_client.recovery_decider_client.clone() {
match client
.decide_on_retry(decider_request.into(), state.get_recovery_grpc_headers())
.await
{
Ok(grpc_response) => Ok(grpc_response
.retry_flag
.then_some(())
.and(grpc_response.retry_time)
.and_then(|prost_ts| {
match date_time::convert_from_prost_timestamp(&prost_ts) {
Ok(pdt) => Some(pdt),
Err(e) => {
logger::error!(
"Failed to convert retry_time from prost::Timestamp: {e:?}"
);
None // If conversion fails, treat as no valid retry time
}
}
})),
Err(e) => {
logger::error!("Recovery decider gRPC call failed: {e:?}");
Ok(None)
}
}
} else {
logger::debug!("Recovery decider client is not configured");
Ok(None)
}
}
#[cfg(feature = "v2")]
#[derive(Debug)]
struct InternalDeciderRequest {
first_error_message: String,
billing_state: Option<Secret<String>>,
card_funding: Option<String>,
card_network: Option<String>,
card_issuer: Option<String>,
invoice_start_time: Option<prost_types::Timestamp>,
retry_count: Option<i64>,
merchant_id: Option<String>,
invoice_amount: Option<i64>,
invoice_currency: Option<String>,
invoice_due_date: Option<prost_types::Timestamp>,
billing_country: Option<String>,
billing_city: Option<String>,
attempt_currency: Option<String>,
attempt_status: Option<String>,
attempt_amount: Option<i64>,
pg_error_code: Option<String>,
network_advice_code: Option<String>,
network_error_code: Option<String>,
first_pg_error_code: Option<String>,
first_network_advice_code: Option<String>,
first_network_error_code: Option<String>,
attempt_response_time: Option<prost_types::Timestamp>,
payment_method_type: Option<String>,
payment_gateway: Option<String>,
retry_count_left: Option<i64>,
total_retry_count_within_network: Option<i64>,
first_error_msg_time: Option<prost_types::Timestamp>,
wait_time: Option<prost_types::Timestamp>,
}
#[cfg(feature = "v2")]
impl From<InternalDeciderRequest> for external_grpc_client::DeciderRequest {
fn from(internal_request: InternalDeciderRequest) -> Self {
Self {
first_error_message: internal_request.first_error_message,
billing_state: internal_request.billing_state.map(|s| s.peek().to_string()),
card_funding: internal_request.card_funding,
card_network: internal_request.card_network,
card_issuer: internal_request.card_issuer,
invoice_start_time: internal_request.invoice_start_time,
retry_count: internal_request.retry_count,
merchant_id: internal_request.merchant_id,
invoice_amount: internal_request.invoice_amount,
invoice_currency: internal_request.invoice_currency,
invoice_due_date: internal_request.invoice_due_date,
billing_country: internal_request.billing_country,
billing_city: internal_request.billing_city,
attempt_currency: internal_request.attempt_currency,
attempt_status: internal_request.attempt_status,
attempt_amount: internal_request.attempt_amount,
pg_error_code: internal_request.pg_error_code,
network_advice_code: internal_request.network_advice_code,
network_error_code: internal_request.network_error_code,
first_pg_error_code: internal_request.first_pg_error_code,
first_network_advice_code: internal_request.first_network_advice_code,
first_network_error_code: internal_request.first_network_error_code,
attempt_response_time: internal_request.attempt_response_time,
payment_method_type: internal_request.payment_method_type,
payment_gateway: internal_request.payment_gateway,
retry_count_left: internal_request.retry_count_left,
total_retry_count_within_network: internal_request.total_retry_count_within_network,
first_error_msg_time: internal_request.first_error_msg_time,
wait_time: internal_request.wait_time,
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone)]
pub struct ScheduledToken {
pub token_details: PaymentProcessorTokenDetails,
pub schedule_time: time::PrimitiveDateTime,
}
#[cfg(feature = "v2")]
pub fn calculate_difference_in_seconds(scheduled_time: time::PrimitiveDateTime) -> i64 {
let now_utc = time::OffsetDateTime::now_utc();
let scheduled_offset_dt = scheduled_time.assume_utc();
let difference = scheduled_offset_dt - now_utc;
difference.whole_seconds()
}
#[cfg(feature = "v2")]
pub async fn update_token_expiry_based_on_schedule_time(
state: &SessionState,
connector_customer_id: &str,
delayed_schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ProcessTrackerError> {
let expiry_buffer = state
.conf
.revenue_recovery
.recovery_timestamp
.redis_ttl_buffer_in_seconds;
delayed_schedule_time
.async_map(|t| async move {
let expiry_time = calculate_difference_in_seconds(t) + expiry_buffer;
RedisTokenManager::update_connector_customer_lock_ttl(
state,
connector_customer_id,
expiry_time,
)
.await
.change_context(errors::ProcessTrackerError::ERedisError(
errors::RedisError::RedisConnectionError.into(),
))
})
.await
.transpose()?;
Ok(())
}
#[cfg(feature = "v2")]
pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
state: &SessionState,
connector_customer_id: &str,
payment_intent: &PaymentIntent,
retry_algorithm_type: RevenueRecoveryAlgorithmType,
retry_count: i32,
) -> CustomResult<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
let mut scheduled_time = None;
match retry_algorithm_type {
RevenueRecoveryAlgorithmType::Monitoring => {
logger::error!("Monitoring type found for Revenue Recovery retry payment");
}
RevenueRecoveryAlgorithmType::Cascading => {
let time = get_schedule_time_to_retry_mit_payments(
state.store.as_ref(),
&payment_intent.merchant_id,
retry_count,
)
.await
.ok_or(errors::ProcessTrackerError::EApiErrorResponse)?;
scheduled_time = Some(time);
}
RevenueRecoveryAlgorithmType::Smart => {
scheduled_time = get_best_psp_token_available_for_smart_retry(
state,
connector_customer_id,
payment_intent,
)
.await
.change_context(errors::ProcessTrackerError::EApiErrorResponse)?;
}
}
let delayed_schedule_time =
scheduled_time.map(|time| add_random_delay_to_schedule_time(state, time));
let _ = update_token_expiry_based_on_schedule_time(
state,
connector_customer_id,
delayed_schedule_time,
)
.await;
Ok(delayed_schedule_time)
}
#[cfg(feature = "v2")]
pub async fn get_best_psp_token_available_for_smart_retry(
state: &SessionState,
connector_customer_id: &str,
payment_intent: &PaymentIntent,
) -> CustomResult<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
// Lock using payment_id
let locked = RedisTokenManager::lock_connector_customer_status(
state,
connector_customer_id,
&payment_intent.id,
)
.await
.change_context(errors::ProcessTrackerError::ERedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
match !locked {
true => Ok(None),
false => {
// Get existing tokens from Redis
let existing_tokens =
RedisTokenManager::get_connector_customer_payment_processor_tokens(
state,
connector_customer_id,
)
.await
.change_context(errors::ProcessTrackerError::ERedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
// TODO: Insert into payment_intent_feature_metadata (DB operation)
let result = RedisTokenManager::get_tokens_with_retry_metadata(state, &existing_tokens);
let best_token_time = call_decider_for_payment_processor_tokens_select_closet_time(
state,
&result,
payment_intent,
connector_customer_id,
)
.await
.change_context(errors::ProcessTrackerError::EApiErrorResponse)?;
Ok(best_token_time)
}
}
}
#[cfg(feature = "v2")]
pub async fn calculate_smart_retry_time(
state: &SessionState,
payment_intent: &PaymentIntent,
token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,
) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
let wait_hours = token_with_retry_info.retry_wait_time_hours;
let current_time = time::OffsetDateTime::now_utc();
let future_time = current_time + time::Duration::hours(wait_hours);
// Timestamp after which retry can be done without penalty
let future_timestamp = Some(prost_types::Timestamp {
seconds: future_time.unix_timestamp(),
nanos: 0,
});
get_schedule_time_for_smart_retry(
state,
payment_intent,
future_timestamp,
token_with_retry_info,
)
.await
}
#[cfg(feature = "v2")]
async fn process_token_for_retry(
state: &SessionState,
token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,
payment_intent: &PaymentIntent,
) -> Result<Option<ScheduledToken>, errors::ProcessTrackerError> {
let token_status: &PaymentProcessorTokenStatus = &token_with_retry_info.token_status;
let inserted_by_attempt_id = &token_status.inserted_by_attempt_id;
let skip = token_status.is_hard_decline.unwrap_or(false);
match skip {
true => {
logger::info!(
"Skipping decider call due to hard decline token inserted by attempt_id: {}",
inserted_by_attempt_id.get_string_repr()
);
Ok(None)
}
false => {
let schedule_time =
calculate_smart_retry_time(state, payment_intent, token_with_retry_info).await?;
Ok(schedule_time.map(|schedule_time| ScheduledToken {
token_details: token_status.payment_processor_token_details.clone(),
schedule_time,
}))
}
}
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn call_decider_for_payment_processor_tokens_select_closet_time(
state: &SessionState,
processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>,
payment_intent: &PaymentIntent,
connector_customer_id: &str,
) -> CustomResult<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
tracing::debug!("Filtered payment attempts based on payment tokens",);
let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new();
for token_with_retry_info in processor_tokens.values() {
let token_details = &token_with_retry_info
.token_status
.payment_processor_token_details;
let error_code = token_with_retry_info.token_status.error_code.clone();
match error_code {
None => {
let utc_schedule_time =
time::OffsetDateTime::now_utc() + time::Duration::minutes(1);
let schedule_time = time::PrimitiveDateTime::new(
utc_schedule_time.date(),
utc_schedule_time.time(),
);
tokens_with_schedule_time = vec![ScheduledToken {
token_details: token_details.clone(),
schedule_time,
}];
tracing::debug!(
"Found payment processor token with no error code scheduling it for {schedule_time}",
);
break;
}
Some(_) => {
process_token_for_retry(state, token_with_retry_info, payment_intent)
.await?
.map(|token_with_schedule_time| {
tokens_with_schedule_time.push(token_with_schedule_time)
});
}
}
}
let best_token = tokens_with_schedule_time
.iter()
.min_by_key(|token| token.schedule_time)
.cloned();
match best_token {
None => {
RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)
.await
.change_context(errors::ProcessTrackerError::EApiErrorResponse)?;
tracing::debug!("No payment processor tokens available for scheduling");
Ok(None)
}
Some(token) => {
tracing::debug!("Found payment processor token with least schedule time");
RedisTokenManager::update_payment_processor_token_schedule_time(
state,
connector_customer_id,
&token.token_details.payment_processor_token,
Some(token.schedule_time),
)
.await
.change_context(errors::ProcessTrackerError::EApiErrorResponse)?;
Ok(Some(token.schedule_time))
}
}
}
#[cfg(feature = "v2")]
pub async fn check_hard_decline(
state: &SessionState,
payment_attempt: &payment_attempt::PaymentAttempt,
) -> Result<bool, error_stack::Report<storage_impl::errors::RecoveryError>> {
let error_message = payment_attempt
.error
.as_ref()
.map(|details| details.message.clone());
let error_code = payment_attempt
.error
.as_ref()
.map(|details| details.code.clone());
let connector_name = payment_attempt
.connector
.clone()
.ok_or(storage_impl::errors::RecoveryError::ValueNotFound)
.attach_printable("unable to derive payment connector from payment attempt")?;
let gsm_record = payments::helpers::get_gsm_record(
state,
error_code,
error_message,
connector_name,
REVENUE_RECOVERY.to_string(),
)
.await;
let is_hard_decline = gsm_record
.and_then(|record| record.error_category)
.map(|category| category == common_enums::ErrorCategory::HardDecline)
.unwrap_or(false);
Ok(is_hard_decline)
}
#[cfg(feature = "v2")]
pub fn add_random_delay_to_schedule_time(
state: &SessionState,
schedule_time: time::PrimitiveDateTime,
) -> time::PrimitiveDateTime {
let mut rng = rand::thread_rng();
let delay_limit = state
.conf
.revenue_recovery
.recovery_timestamp
.max_random_schedule_delay_in_seconds;
let random_secs = rng.gen_range(1..=delay_limit);
logger::info!("Adding random delay of {random_secs} seconds to schedule time");
schedule_time + time::Duration::seconds(random_secs)
}
| {
"crate": "router",
"file": "crates/router/src/workflows/revenue_recovery.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-5299396500633497412 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/utils/currency.rs
// Contains: 4 structs, 1 enums
use std::{
collections::HashMap,
ops::Deref,
str::FromStr,
sync::{Arc, LazyLock},
};
use api_models::enums;
use common_utils::{date_time, errors::CustomResult, events::ApiEventMetric, ext_traits::AsyncExt};
use currency_conversion::types::{CurrencyFactors, ExchangeRates};
use error_stack::ResultExt;
use masking::PeekInterface;
use redis_interface::DelReply;
use router_env::{instrument, tracing};
use rust_decimal::Decimal;
use strum::IntoEnumIterator;
use tokio::sync::RwLock;
use tracing_futures::Instrument;
use crate::{
logger,
routes::app::settings::{Conversion, DefaultExchangeRates},
services, SessionState,
};
const REDIX_FOREX_CACHE_KEY: &str = "{forex_cache}_lock";
const REDIX_FOREX_CACHE_DATA: &str = "{forex_cache}_data";
const FOREX_API_TIMEOUT: u64 = 5;
const FOREX_BASE_URL: &str = "https://openexchangerates.org/api/latest.json?app_id=";
const FOREX_BASE_CURRENCY: &str = "&base=USD";
const FALLBACK_FOREX_BASE_URL: &str = "http://apilayer.net/api/live?access_key=";
const FALLBACK_FOREX_API_CURRENCY_PREFIX: &str = "USD";
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct FxExchangeRatesCacheEntry {
pub data: Arc<ExchangeRates>,
timestamp: i64,
}
static FX_EXCHANGE_RATES_CACHE: LazyLock<RwLock<Option<FxExchangeRatesCacheEntry>>> =
LazyLock::new(|| RwLock::new(None));
impl ApiEventMetric for FxExchangeRatesCacheEntry {}
#[derive(Debug, Clone, thiserror::Error)]
pub enum ForexError {
#[error("API error")]
ApiError,
#[error("API timeout")]
ApiTimeout,
#[error("API unresponsive")]
ApiUnresponsive,
#[error("Conversion error")]
ConversionError,
#[error("Could not acquire the lock for cache entry")]
CouldNotAcquireLock,
#[error("Provided currency not acceptable")]
CurrencyNotAcceptable,
#[error("Forex configuration error: {0}")]
ConfigurationError(String),
#[error("Incorrect entries in default Currency response")]
DefaultCurrencyParsingError,
#[error("Entry not found in cache")]
EntryNotFound,
#[error("Forex data unavailable")]
ForexDataUnavailable,
#[error("Expiration time invalid")]
InvalidLogExpiry,
#[error("Error reading local")]
LocalReadError,
#[error("Error writing to local cache")]
LocalWriteError,
#[error("Json Parsing error")]
ParsingError,
#[error("Aws Kms decryption error")]
AwsKmsDecryptionFailed,
#[error("Error connecting to redis")]
RedisConnectionError,
#[error("Not able to release write lock")]
RedisLockReleaseFailed,
#[error("Error writing to redis")]
RedisWriteError,
#[error("Not able to acquire write lock")]
WriteLockNotAcquired,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct ForexResponse {
pub rates: HashMap<String, FloatDecimal>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct FallbackForexResponse {
pub quotes: HashMap<String, FloatDecimal>,
}
#[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
struct FloatDecimal(#[serde(with = "rust_decimal::serde::float")] Decimal);
impl Deref for FloatDecimal {
type Target = Decimal;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl FxExchangeRatesCacheEntry {
fn new(exchange_rate: ExchangeRates) -> Self {
Self {
data: Arc::new(exchange_rate),
timestamp: date_time::now_unix_timestamp(),
}
}
fn is_expired(&self, data_expiration_delay: u32) -> bool {
self.timestamp + i64::from(data_expiration_delay) < date_time::now_unix_timestamp()
}
}
async fn retrieve_forex_from_local_cache() -> Option<FxExchangeRatesCacheEntry> {
FX_EXCHANGE_RATES_CACHE.read().await.clone()
}
async fn save_forex_data_to_local_cache(
exchange_rates_cache_entry: FxExchangeRatesCacheEntry,
) -> CustomResult<(), ForexError> {
let mut local = FX_EXCHANGE_RATES_CACHE.write().await;
*local = Some(exchange_rates_cache_entry);
logger::debug!("forex_log: forex saved in cache");
Ok(())
}
impl TryFrom<DefaultExchangeRates> for ExchangeRates {
type Error = error_stack::Report<ForexError>;
fn try_from(value: DefaultExchangeRates) -> Result<Self, Self::Error> {
let mut conversion_usable: HashMap<enums::Currency, CurrencyFactors> = HashMap::new();
for (curr, conversion) in value.conversion {
let enum_curr = enums::Currency::from_str(curr.as_str())
.change_context(ForexError::ConversionError)
.attach_printable("Unable to Convert currency received")?;
conversion_usable.insert(enum_curr, CurrencyFactors::from(conversion));
}
let base_curr = enums::Currency::from_str(value.base_currency.as_str())
.change_context(ForexError::ConversionError)
.attach_printable("Unable to convert base currency")?;
Ok(Self {
base_currency: base_curr,
conversion: conversion_usable,
})
}
}
impl From<Conversion> for CurrencyFactors {
fn from(value: Conversion) -> Self {
Self {
to_factor: value.to_factor,
from_factor: value.from_factor,
}
}
}
#[instrument(skip_all)]
pub async fn get_forex_rates(
state: &SessionState,
data_expiration_delay: u32,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
if let Some(local_rates) = retrieve_forex_from_local_cache().await {
if local_rates.is_expired(data_expiration_delay) {
// expired local data
logger::debug!("forex_log: Forex stored in cache is expired");
call_forex_api_and_save_data_to_cache_and_redis(state, Some(local_rates)).await
} else {
// Valid data present in local
logger::debug!("forex_log: forex found in cache");
Ok(local_rates)
}
} else {
// No data in local
call_api_if_redis_forex_data_expired(state, data_expiration_delay).await
}
}
async fn call_api_if_redis_forex_data_expired(
state: &SessionState,
data_expiration_delay: u32,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
match retrieve_forex_data_from_redis(state).await {
Ok(Some(data)) => {
call_forex_api_if_redis_data_expired(state, data, data_expiration_delay).await
}
Ok(None) => {
// No data in local as well as redis
call_forex_api_and_save_data_to_cache_and_redis(state, None).await?;
Err(ForexError::ForexDataUnavailable.into())
}
Err(error) => {
// Error in deriving forex rates from redis
logger::error!("forex_error: {:?}", error);
call_forex_api_and_save_data_to_cache_and_redis(state, None).await?;
Err(ForexError::ForexDataUnavailable.into())
}
}
}
async fn call_forex_api_and_save_data_to_cache_and_redis(
state: &SessionState,
stale_redis_data: Option<FxExchangeRatesCacheEntry>,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
// spawn a new thread and do the api fetch and write operations on redis.
let forex_api_key = state.conf.forex_api.get_inner().api_key.peek();
if forex_api_key.is_empty() {
Err(ForexError::ConfigurationError("api_keys not provided".into()).into())
} else {
let state = state.clone();
tokio::spawn(
async move {
acquire_redis_lock_and_call_forex_api(&state)
.await
.map_err(|err| {
logger::error!(forex_error=?err);
})
.ok();
}
.in_current_span(),
);
stale_redis_data.ok_or(ForexError::EntryNotFound.into())
}
}
async fn acquire_redis_lock_and_call_forex_api(
state: &SessionState,
) -> CustomResult<(), ForexError> {
let lock_acquired = acquire_redis_lock(state).await?;
if !lock_acquired {
Err(ForexError::CouldNotAcquireLock.into())
} else {
logger::debug!("forex_log: redis lock acquired");
let api_rates = fetch_forex_rates_from_primary_api(state).await;
match api_rates {
Ok(rates) => save_forex_data_to_cache_and_redis(state, rates).await,
Err(error) => {
logger::error!(forex_error=?error,"primary_forex_error");
// API not able to fetch data call secondary service
let secondary_api_rates = fetch_forex_rates_from_fallback_api(state).await;
match secondary_api_rates {
Ok(rates) => save_forex_data_to_cache_and_redis(state, rates).await,
Err(error) => {
release_redis_lock(state).await?;
Err(error)
}
}
}
}
}
}
async fn save_forex_data_to_cache_and_redis(
state: &SessionState,
forex: FxExchangeRatesCacheEntry,
) -> CustomResult<(), ForexError> {
save_forex_data_to_redis(state, &forex)
.await
.async_and_then(|_rates| release_redis_lock(state))
.await
.async_and_then(|_val| save_forex_data_to_local_cache(forex.clone()))
.await
}
async fn call_forex_api_if_redis_data_expired(
state: &SessionState,
redis_data: FxExchangeRatesCacheEntry,
data_expiration_delay: u32,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
match is_redis_expired(Some(redis_data.clone()).as_ref(), data_expiration_delay).await {
Some(redis_forex) => {
// Valid data present in redis
let exchange_rates = FxExchangeRatesCacheEntry::new(redis_forex.as_ref().clone());
logger::debug!("forex_log: forex response found in redis");
save_forex_data_to_local_cache(exchange_rates.clone()).await?;
Ok(exchange_rates)
}
None => {
// redis expired
call_forex_api_and_save_data_to_cache_and_redis(state, Some(redis_data)).await
}
}
}
async fn fetch_forex_rates_from_primary_api(
state: &SessionState,
) -> Result<FxExchangeRatesCacheEntry, error_stack::Report<ForexError>> {
let forex_api_key = state.conf.forex_api.get_inner().api_key.peek();
logger::debug!("forex_log: Primary api call for forex fetch");
let forex_url: String = format!("{FOREX_BASE_URL}{forex_api_key}{FOREX_BASE_CURRENCY}");
let forex_request = services::RequestBuilder::new()
.method(services::Method::Get)
.url(&forex_url)
.build();
logger::info!(primary_forex_request=?forex_request,"forex_log: Primary api call for forex fetch");
let response = state
.api_client
.send_request(
&state.clone(),
forex_request,
Some(FOREX_API_TIMEOUT),
false,
)
.await
.change_context(ForexError::ApiUnresponsive)
.attach_printable("Primary forex fetch api unresponsive")?;
let forex_response = response
.json::<ForexResponse>()
.await
.change_context(ForexError::ParsingError)
.attach_printable(
"Unable to parse response received from primary api into ForexResponse",
)?;
logger::info!(primary_forex_response=?forex_response,"forex_log");
let mut conversions: HashMap<enums::Currency, CurrencyFactors> = HashMap::new();
for enum_curr in enums::Currency::iter() {
match forex_response.rates.get(&enum_curr.to_string()) {
Some(rate) => {
let from_factor = match Decimal::new(1, 0).checked_div(**rate) {
Some(rate) => rate,
None => {
logger::error!(
"forex_error: Rates for {} not received from API",
&enum_curr
);
continue;
}
};
let currency_factors = CurrencyFactors::new(**rate, from_factor);
conversions.insert(enum_curr, currency_factors);
}
None => {
logger::error!(
"forex_error: Rates for {} not received from API",
&enum_curr
);
}
};
}
Ok(FxExchangeRatesCacheEntry::new(ExchangeRates::new(
enums::Currency::USD,
conversions,
)))
}
pub async fn fetch_forex_rates_from_fallback_api(
state: &SessionState,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
let fallback_forex_api_key = state.conf.forex_api.get_inner().fallback_api_key.peek();
let fallback_forex_url: String = format!("{FALLBACK_FOREX_BASE_URL}{fallback_forex_api_key}");
let fallback_forex_request = services::RequestBuilder::new()
.method(services::Method::Get)
.url(&fallback_forex_url)
.build();
logger::info!(fallback_forex_request=?fallback_forex_request,"forex_log: Fallback api call for forex fetch");
let response = state
.api_client
.send_request(
&state.clone(),
fallback_forex_request,
Some(FOREX_API_TIMEOUT),
false,
)
.await
.change_context(ForexError::ApiUnresponsive)
.attach_printable("Fallback forex fetch api unresponsive")?;
let fallback_forex_response = response
.json::<FallbackForexResponse>()
.await
.change_context(ForexError::ParsingError)
.attach_printable(
"Unable to parse response received from fallback api into ForexResponse",
)?;
logger::info!(fallback_forex_response=?fallback_forex_response,"forex_log");
let mut conversions: HashMap<enums::Currency, CurrencyFactors> = HashMap::new();
for enum_curr in enums::Currency::iter() {
match fallback_forex_response.quotes.get(
format!(
"{}{}",
FALLBACK_FOREX_API_CURRENCY_PREFIX,
&enum_curr.to_string()
)
.as_str(),
) {
Some(rate) => {
let from_factor = match Decimal::new(1, 0).checked_div(**rate) {
Some(rate) => rate,
None => {
logger::error!(
"forex_error: Rates for {} not received from API",
&enum_curr
);
continue;
}
};
let currency_factors = CurrencyFactors::new(**rate, from_factor);
conversions.insert(enum_curr, currency_factors);
}
None => {
if enum_curr == enums::Currency::USD {
let currency_factors =
CurrencyFactors::new(Decimal::new(1, 0), Decimal::new(1, 0));
conversions.insert(enum_curr, currency_factors);
} else {
logger::error!(
"forex_error: Rates for {} not received from API",
&enum_curr
);
}
}
};
}
let rates =
FxExchangeRatesCacheEntry::new(ExchangeRates::new(enums::Currency::USD, conversions));
match acquire_redis_lock(state).await {
Ok(_) => {
save_forex_data_to_cache_and_redis(state, rates.clone()).await?;
Ok(rates)
}
Err(e) => Err(e),
}
}
async fn release_redis_lock(
state: &SessionState,
) -> Result<DelReply, error_stack::Report<ForexError>> {
logger::debug!("forex_log: Releasing redis lock");
state
.store
.get_redis_conn()
.change_context(ForexError::RedisConnectionError)?
.delete_key(&REDIX_FOREX_CACHE_KEY.into())
.await
.change_context(ForexError::RedisLockReleaseFailed)
.attach_printable("Unable to release redis lock")
}
async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexError> {
let forex_api = state.conf.forex_api.get_inner();
logger::debug!("forex_log: Acquiring redis lock");
state
.store
.get_redis_conn()
.change_context(ForexError::RedisConnectionError)?
.set_key_if_not_exists_with_expiry(
&REDIX_FOREX_CACHE_KEY.into(),
"",
Some(i64::from(forex_api.redis_lock_timeout_in_seconds)),
)
.await
.map(|val| matches!(val, redis_interface::SetnxReply::KeySet))
.change_context(ForexError::CouldNotAcquireLock)
.attach_printable("Unable to acquire redis lock")
}
async fn save_forex_data_to_redis(
app_state: &SessionState,
forex_exchange_cache_entry: &FxExchangeRatesCacheEntry,
) -> CustomResult<(), ForexError> {
let forex_api = app_state.conf.forex_api.get_inner();
logger::debug!("forex_log: Saving forex to redis");
app_state
.store
.get_redis_conn()
.change_context(ForexError::RedisConnectionError)?
.serialize_and_set_key_with_expiry(
&REDIX_FOREX_CACHE_DATA.into(),
forex_exchange_cache_entry,
i64::from(forex_api.redis_ttl_in_seconds),
)
.await
.change_context(ForexError::RedisWriteError)
.attach_printable("Unable to save forex data to redis")
}
async fn retrieve_forex_data_from_redis(
app_state: &SessionState,
) -> CustomResult<Option<FxExchangeRatesCacheEntry>, ForexError> {
logger::debug!("forex_log: Retrieving forex from redis");
app_state
.store
.get_redis_conn()
.change_context(ForexError::RedisConnectionError)?
.get_and_deserialize_key(&REDIX_FOREX_CACHE_DATA.into(), "FxExchangeRatesCache")
.await
.change_context(ForexError::EntryNotFound)
.attach_printable("Forex entry not found in redis")
}
async fn is_redis_expired(
redis_cache: Option<&FxExchangeRatesCacheEntry>,
data_expiration_delay: u32,
) -> Option<Arc<ExchangeRates>> {
redis_cache.and_then(|cache| {
if cache.timestamp + i64::from(data_expiration_delay) > date_time::now_unix_timestamp() {
Some(cache.data.clone())
} else {
logger::debug!("forex_log: Forex stored in redis is expired");
None
}
})
}
#[instrument(skip_all)]
pub async fn convert_currency(
state: SessionState,
amount: i64,
to_currency: String,
from_currency: String,
) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexError> {
let forex_api = state.conf.forex_api.get_inner();
let rates = get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds)
.await
.change_context(ForexError::ApiError)?;
let to_currency = enums::Currency::from_str(to_currency.as_str())
.change_context(ForexError::CurrencyNotAcceptable)
.attach_printable("The provided currency is not acceptable")?;
let from_currency = enums::Currency::from_str(from_currency.as_str())
.change_context(ForexError::CurrencyNotAcceptable)
.attach_printable("The provided currency is not acceptable")?;
let converted_amount =
currency_conversion::conversion::convert(&rates.data, from_currency, to_currency, amount)
.change_context(ForexError::ConversionError)
.attach_printable("Unable to perform currency conversion")?;
Ok(api_models::currency::CurrencyConversionResponse {
converted_amount: converted_amount.to_string(),
currency: to_currency.to_string(),
})
}
| {
"crate": "router",
"file": "crates/router/src/utils/currency.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 4,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_4902444177950513220 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/configs/settings.rs
// Contains: 78 structs, 6 enums
use std::{
collections::{HashMap, HashSet},
path::PathBuf,
sync::Arc,
};
#[cfg(feature = "olap")]
use analytics::{opensearch::OpenSearchConfig, ReportConfig};
use api_models::enums;
use common_utils::{
ext_traits::ConfigExt,
id_type,
types::{user::EmailThemeConfig, Url},
};
use config::{Environment, File};
use error_stack::ResultExt;
#[cfg(feature = "email")]
use external_services::email::EmailSettings;
use external_services::{
crm::CrmManagerConfig,
file_storage::FileStorageConfig,
grpc_client::GrpcClientSettings,
managers::{
encryption_management::EncryptionManagementConfig,
secrets_management::SecretsManagementConfig,
},
superposition::SuperpositionClientConfig,
};
pub use hyperswitch_interfaces::{
configs::{
Connectors, GlobalTenant, InternalMerchantIdProfileIdAuthSettings, InternalServicesConfig,
Tenant, TenantUserConfig,
},
secrets_interface::secret_state::{
RawSecret, SecretState, SecretStateContainer, SecuredSecret,
},
types::Proxy,
};
use masking::Secret;
pub use payment_methods::configs::settings::{
BankRedirectConfig, BanksVector, ConnectorBankNames, ConnectorFields, EligiblePaymentMethods,
Mandates, PaymentMethodAuth, PaymentMethodType, RequiredFieldFinal, RequiredFields,
SupportedConnectorsForMandate, SupportedPaymentMethodTypesForMandate,
SupportedPaymentMethodsForMandate, ZeroMandates,
};
use redis_interface::RedisSettings;
pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry};
use rust_decimal::Decimal;
use scheduler::SchedulerSettings;
use serde::Deserialize;
use storage_impl::config::QueueStrategy;
#[cfg(feature = "olap")]
use crate::analytics::{AnalyticsConfig, AnalyticsProvider};
#[cfg(feature = "v2")]
use crate::types::storage::revenue_recovery;
use crate::{
configs,
core::errors::{ApplicationError, ApplicationResult},
env::{self, Env},
events::EventsConfig,
routes::app,
AppState,
};
pub const REQUIRED_FIELDS_CONFIG_FILE: &str = "payment_required_fields_v2.toml";
#[derive(clap::Parser, Default)]
#[cfg_attr(feature = "vergen", command(version = router_env::version!()))]
pub struct CmdLineConf {
/// Config file.
/// Application will look for "config/config.toml" if this option isn't specified.
#[arg(short = 'f', long, value_name = "FILE")]
pub config_path: Option<PathBuf>,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct Settings<S: SecretState> {
pub server: Server,
pub proxy: Proxy,
pub env: Env,
pub chat: SecretStateContainer<ChatSettings, S>,
pub master_database: SecretStateContainer<Database, S>,
#[cfg(feature = "olap")]
pub replica_database: SecretStateContainer<Database, S>,
pub redis: RedisSettings,
pub log: Log,
pub secrets: SecretStateContainer<Secrets, S>,
pub fallback_merchant_ids_api_key_auth: Option<FallbackMerchantIds>,
pub locker: Locker,
pub key_manager: SecretStateContainer<KeyManagerConfig, S>,
pub connectors: Connectors,
pub forex_api: SecretStateContainer<ForexApi, S>,
pub refund: Refund,
pub eph_key: EphemeralConfig,
pub scheduler: Option<SchedulerSettings>,
#[cfg(feature = "kv_store")]
pub drainer: DrainerSettings,
pub jwekey: SecretStateContainer<Jwekey, S>,
pub webhooks: WebhooksSettings,
pub pm_filters: ConnectorFilters,
pub bank_config: BankRedirectConfig,
pub api_keys: SecretStateContainer<ApiKeys, S>,
pub file_storage: FileStorageConfig,
pub encryption_management: EncryptionManagementConfig,
pub secrets_management: SecretsManagementConfig,
pub tokenization: TokenizationConfig,
pub connector_customer: ConnectorCustomer,
#[cfg(feature = "dummy_connector")]
pub dummy_connector: DummyConnector,
#[cfg(feature = "email")]
pub email: EmailSettings,
pub user: UserSettings,
pub crm: CrmManagerConfig,
pub cors: CorsSettings,
pub mandates: Mandates,
pub zero_mandates: ZeroMandates,
pub network_transaction_id_supported_connectors: NetworkTransactionIdSupportedConnectors,
pub list_dispute_supported_connectors: ListDiputeSupportedConnectors,
pub required_fields: RequiredFields,
pub delayed_session_response: DelayedSessionConfig,
pub webhook_source_verification_call: WebhookSourceVerificationCall,
pub billing_connectors_payment_sync: BillingConnectorPaymentsSyncCall,
pub billing_connectors_invoice_sync: BillingConnectorInvoiceSyncCall,
pub payment_method_auth: SecretStateContainer<PaymentMethodAuth, S>,
pub connector_request_reference_id_config: ConnectorRequestReferenceIdConfig,
#[cfg(feature = "payouts")]
pub payouts: Payouts,
pub payout_method_filters: ConnectorFilters,
pub l2_l3_data_config: L2L3DataConfig,
pub debit_routing_config: DebitRoutingConfig,
pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConfig, S>,
pub paze_decrypt_keys: Option<SecretStateContainer<PazeDecryptConfig, S>>,
pub google_pay_decrypt_keys: Option<GooglePayDecryptConfig>,
pub multiple_api_version_supported_connectors: MultipleApiVersionSupportedConnectors,
pub applepay_merchant_configs: SecretStateContainer<ApplepayMerchantConfigs, S>,
pub lock_settings: LockSettings,
pub temp_locker_enable_config: TempLockerEnableConfig,
pub generic_link: GenericLink,
pub payment_link: PaymentLink,
#[cfg(feature = "olap")]
pub analytics: SecretStateContainer<AnalyticsConfig, S>,
#[cfg(feature = "kv_store")]
pub kv_config: KvConfig,
#[cfg(feature = "frm")]
pub frm: Frm,
#[cfg(feature = "olap")]
pub report_download_config: ReportConfig,
#[cfg(feature = "olap")]
pub opensearch: OpenSearchConfig,
pub events: EventsConfig,
#[cfg(feature = "olap")]
pub connector_onboarding: SecretStateContainer<ConnectorOnboarding, S>,
pub unmasked_headers: UnmaskedHeaders,
pub multitenancy: Multitenancy,
pub saved_payment_methods: EligiblePaymentMethods,
pub user_auth_methods: SecretStateContainer<UserAuthMethodSettings, S>,
pub decision: Option<DecisionConfig>,
pub locker_based_open_banking_connectors: LockerBasedRecipientConnectorList,
pub grpc_client: GrpcClientSettings,
#[cfg(feature = "v2")]
pub cell_information: CellInformation,
pub network_tokenization_supported_card_networks: NetworkTokenizationSupportedCardNetworks,
pub network_tokenization_service: Option<SecretStateContainer<NetworkTokenizationService, S>>,
pub network_tokenization_supported_connectors: NetworkTokenizationSupportedConnectors,
pub theme: ThemeSettings,
pub platform: Platform,
pub authentication_providers: AuthenticationProviders,
pub open_router: OpenRouter,
#[cfg(feature = "v2")]
pub revenue_recovery: revenue_recovery::RevenueRecoverySettings,
pub clone_connector_allowlist: Option<CloneConnectorAllowlistConfig>,
pub merchant_id_auth: MerchantIdAuthSettings,
pub internal_merchant_id_profile_id_auth: InternalMerchantIdProfileIdAuthSettings,
#[serde(default)]
pub infra_values: Option<HashMap<String, String>>,
#[serde(default)]
pub enhancement: Option<HashMap<String, String>>,
pub superposition: SecretStateContainer<SuperpositionClientConfig, S>,
pub proxy_status_mapping: ProxyStatusMapping,
pub internal_services: InternalServicesConfig,
pub comparison_service: Option<ComparisonServiceConfig>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct DebitRoutingConfig {
#[serde(deserialize_with = "deserialize_hashmap")]
pub connector_supported_debit_networks: HashMap<enums::Connector, HashSet<enums::CardNetwork>>,
#[serde(deserialize_with = "deserialize_hashset")]
pub supported_currencies: HashSet<enums::Currency>,
#[serde(deserialize_with = "deserialize_hashset")]
pub supported_connectors: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct OpenRouter {
pub dynamic_routing_enabled: bool,
pub static_routing_enabled: bool,
pub url: String,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct CloneConnectorAllowlistConfig {
#[serde(deserialize_with = "deserialize_merchant_ids")]
pub merchant_ids: HashSet<id_type::MerchantId>,
#[serde(deserialize_with = "deserialize_hashset")]
pub connector_names: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone)]
pub struct ComparisonServiceConfig {
pub url: Url,
pub enabled: bool,
pub timeout_secs: Option<u64>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct Platform {
pub enabled: bool,
pub allow_connected_merchants: bool,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct ChatSettings {
pub enabled: bool,
pub hyperswitch_ai_host: String,
pub encryption_key: Secret<String>,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Multitenancy {
pub tenants: TenantConfig,
pub enabled: bool,
pub global_tenant: GlobalTenant,
}
impl Multitenancy {
pub fn get_tenants(&self) -> &HashMap<id_type::TenantId, Tenant> {
&self.tenants.0
}
pub fn get_tenant_ids(&self) -> Vec<id_type::TenantId> {
self.tenants
.0
.values()
.map(|tenant| tenant.tenant_id.clone())
.collect()
}
pub fn get_tenant(&self, tenant_id: &id_type::TenantId) -> Option<&Tenant> {
self.tenants.0.get(tenant_id)
}
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct DecisionConfig {
pub base_url: String,
}
#[derive(Debug, Clone, Default)]
pub struct TenantConfig(pub HashMap<id_type::TenantId, Tenant>);
impl TenantConfig {
/// # Panics
///
/// Panics if Failed to create event handler
pub async fn get_store_interface_map(
&self,
storage_impl: &app::StorageImpl,
conf: &configs::Settings,
cache_store: Arc<storage_impl::redis::RedisStore>,
testable: bool,
) -> HashMap<id_type::TenantId, Box<dyn app::StorageInterface>> {
#[allow(clippy::expect_used)]
let event_handler = conf
.events
.get_event_handler()
.await
.expect("Failed to create event handler");
futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async {
let store = AppState::get_store_interface(
storage_impl,
&event_handler,
conf,
tenant,
cache_store.clone(),
testable,
)
.await
.get_storage_interface();
(tenant_name.clone(), store)
}))
.await
.into_iter()
.collect()
}
/// # Panics
///
/// Panics if Failed to create event handler
pub async fn get_accounts_store_interface_map(
&self,
storage_impl: &app::StorageImpl,
conf: &configs::Settings,
cache_store: Arc<storage_impl::redis::RedisStore>,
testable: bool,
) -> HashMap<id_type::TenantId, Box<dyn app::AccountsStorageInterface>> {
#[allow(clippy::expect_used)]
let event_handler = conf
.events
.get_event_handler()
.await
.expect("Failed to create event handler");
futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async {
let store = AppState::get_store_interface(
storage_impl,
&event_handler,
conf,
tenant,
cache_store.clone(),
testable,
)
.await
.get_accounts_storage_interface();
(tenant_name.clone(), store)
}))
.await
.into_iter()
.collect()
}
#[cfg(feature = "olap")]
pub async fn get_pools_map(
&self,
analytics_config: &AnalyticsConfig,
) -> HashMap<id_type::TenantId, AnalyticsProvider> {
futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async {
(
tenant_name.clone(),
AnalyticsProvider::from_conf(analytics_config, tenant).await,
)
}))
.await
.into_iter()
.collect()
}
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct L2L3DataConfig {
pub enabled: bool,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct UnmaskedHeaders {
#[serde(deserialize_with = "deserialize_hashset")]
pub keys: HashSet<String>,
}
#[cfg(feature = "frm")]
#[derive(Debug, Deserialize, Clone, Default)]
pub struct Frm {
pub enabled: bool,
}
#[derive(Debug, Deserialize, Clone)]
pub struct KvConfig {
pub ttl: u32,
pub soft_kill: Option<bool>,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct KeyManagerConfig {
pub enabled: bool,
pub url: String,
#[cfg(feature = "keymanager_mtls")]
pub cert: Secret<String>,
#[cfg(feature = "keymanager_mtls")]
pub ca: Secret<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct GenericLink {
pub payment_method_collect: GenericLinkEnvConfig,
pub payout_link: GenericLinkEnvConfig,
}
#[derive(Debug, Deserialize, Clone)]
pub struct GenericLinkEnvConfig {
pub sdk_url: url::Url,
pub expiry: u32,
pub ui_config: GenericLinkEnvUiConfig,
#[serde(deserialize_with = "deserialize_hashmap")]
pub enabled_payment_methods: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>,
}
impl Default for GenericLinkEnvConfig {
fn default() -> Self {
Self {
#[allow(clippy::expect_used)]
sdk_url: url::Url::parse("http://localhost:9050/HyperLoader.js")
.expect("Failed to parse default SDK URL"),
expiry: 900,
ui_config: GenericLinkEnvUiConfig::default(),
enabled_payment_methods: HashMap::default(),
}
}
}
#[derive(Debug, Deserialize, Clone)]
pub struct GenericLinkEnvUiConfig {
pub logo: url::Url,
pub merchant_name: Secret<String>,
pub theme: String,
}
#[allow(clippy::panic)]
impl Default for GenericLinkEnvUiConfig {
fn default() -> Self {
Self {
#[allow(clippy::expect_used)]
logo: url::Url::parse("https://hyperswitch.io/favicon.ico")
.expect("Failed to parse default logo URL"),
merchant_name: Secret::new("HyperSwitch".to_string()),
theme: "#4285F4".to_string(),
}
}
}
#[derive(Debug, Deserialize, Clone)]
pub struct PaymentLink {
pub sdk_url: url::Url,
}
impl Default for PaymentLink {
fn default() -> Self {
Self {
#[allow(clippy::expect_used)]
sdk_url: url::Url::parse("https://beta.hyperswitch.io/v0/HyperLoader.js")
.expect("Failed to parse default SDK URL"),
}
}
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct ForexApi {
pub api_key: Secret<String>,
pub fallback_api_key: Secret<String>,
pub data_expiration_delay_in_seconds: u32,
pub redis_lock_timeout_in_seconds: u32,
pub redis_ttl_in_seconds: u32,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct DefaultExchangeRates {
pub base_currency: String,
pub conversion: HashMap<String, Conversion>,
pub timestamp: i64,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct Conversion {
#[serde(with = "rust_decimal::serde::str")]
pub to_factor: Decimal,
#[serde(with = "rust_decimal::serde::str")]
pub from_factor: Decimal,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct ApplepayMerchantConfigs {
pub merchant_cert: Secret<String>,
pub merchant_cert_key: Secret<String>,
pub common_merchant_identifier: Secret<String>,
pub applepay_endpoint: String,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct MultipleApiVersionSupportedConnectors {
#[serde(deserialize_with = "deserialize_hashset")]
pub supported_connectors: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(transparent)]
pub struct TokenizationConfig(pub HashMap<String, PaymentMethodTokenFilter>);
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(transparent)]
pub struct TempLockerEnableConfig(pub HashMap<String, TempLockerEnablePaymentMethodFilter>);
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ConnectorCustomer {
#[cfg(feature = "payouts")]
#[serde(deserialize_with = "deserialize_hashset")]
pub payout_connector_list: HashSet<enums::PayoutConnectors>,
}
#[cfg(feature = "dummy_connector")]
#[derive(Debug, Deserialize, Clone, Default)]
pub struct DummyConnector {
pub enabled: bool,
pub payment_ttl: i64,
pub payment_duration: u64,
pub payment_tolerance: u64,
pub payment_retrieve_duration: u64,
pub payment_retrieve_tolerance: u64,
pub payment_complete_duration: i64,
pub payment_complete_tolerance: i64,
pub refund_ttl: i64,
pub refund_duration: u64,
pub refund_tolerance: u64,
pub refund_retrieve_duration: u64,
pub refund_retrieve_tolerance: u64,
pub authorize_ttl: i64,
pub assets_base_url: String,
pub default_return_url: String,
pub slack_invite_url: String,
pub discord_invite_url: String,
}
#[derive(Debug, Deserialize, Clone)]
pub struct CorsSettings {
#[serde(default, deserialize_with = "deserialize_hashset")]
pub origins: HashSet<String>,
#[serde(default)]
pub wildcard_origin: bool,
pub max_age: usize,
#[serde(deserialize_with = "deserialize_hashset")]
pub allowed_methods: HashSet<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct AuthenticationProviders {
#[serde(deserialize_with = "deserialize_connector_list")]
pub click_to_pay: HashSet<enums::Connector>,
}
fn deserialize_connector_list<'a, D>(deserializer: D) -> Result<HashSet<enums::Connector>, D::Error>
where
D: serde::Deserializer<'a>,
{
use serde::de::Error;
#[derive(Deserialize)]
struct Wrapper {
connector_list: String,
}
let wrapper = Wrapper::deserialize(deserializer)?;
wrapper
.connector_list
.split(',')
.map(|s| s.trim().parse().map_err(D::Error::custom))
.collect()
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct NetworkTransactionIdSupportedConnectors {
#[serde(deserialize_with = "deserialize_hashset")]
pub connector_list: HashSet<enums::Connector>,
}
/// Connectors that support only dispute list API for syncing disputes with Hyperswitch
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ListDiputeSupportedConnectors {
#[serde(deserialize_with = "deserialize_hashset")]
pub connector_list: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct NetworkTokenizationSupportedCardNetworks {
#[serde(deserialize_with = "deserialize_hashset")]
pub card_networks: HashSet<enums::CardNetwork>,
}
#[derive(Debug, Deserialize, Clone)]
pub struct NetworkTokenizationService {
pub generate_token_url: url::Url,
pub fetch_token_url: url::Url,
pub token_service_api_key: Secret<String>,
pub public_key: Secret<String>,
pub private_key: Secret<String>,
pub key_id: String,
pub delete_token_url: url::Url,
pub check_token_status_url: url::Url,
pub webhook_source_verification_key: Secret<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct PaymentMethodTokenFilter {
#[serde(deserialize_with = "deserialize_hashset")]
pub payment_method: HashSet<diesel_models::enums::PaymentMethod>,
pub payment_method_type: Option<PaymentMethodTypeTokenFilter>,
pub long_lived_token: bool,
pub apple_pay_pre_decrypt_flow: Option<ApplePayPreDecryptFlow>,
pub google_pay_pre_decrypt_flow: Option<GooglePayPreDecryptFlow>,
pub flow: Option<PaymentFlow>,
}
#[derive(Debug, Deserialize, Clone, PartialEq)]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub enum PaymentFlow {
Mandates,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub enum ApplePayPreDecryptFlow {
#[default]
ConnectorTokenization,
NetworkTokenization,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub enum GooglePayPreDecryptFlow {
#[default]
ConnectorTokenization,
NetworkTokenization,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct TempLockerEnablePaymentMethodFilter {
#[serde(deserialize_with = "deserialize_hashset")]
pub payment_method: HashSet<diesel_models::enums::PaymentMethod>,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(
deny_unknown_fields,
tag = "type",
content = "list",
rename_all = "snake_case"
)]
pub enum PaymentMethodTypeTokenFilter {
#[serde(deserialize_with = "deserialize_hashset")]
EnableOnly(HashSet<diesel_models::enums::PaymentMethodType>),
#[serde(deserialize_with = "deserialize_hashset")]
DisableOnly(HashSet<diesel_models::enums::PaymentMethodType>),
#[default]
AllAccepted,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(transparent)]
pub struct ConnectorFilters(pub HashMap<String, PaymentMethodFilters>);
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(transparent)]
pub struct PaymentMethodFilters(pub HashMap<PaymentMethodFilterKey, CurrencyCountryFlowFilter>);
#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash)]
#[serde(untagged)]
pub enum PaymentMethodFilterKey {
PaymentMethodType(enums::PaymentMethodType),
CardNetwork(enums::CardNetwork),
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct CurrencyCountryFlowFilter {
#[serde(deserialize_with = "deserialize_optional_hashset")]
pub currency: Option<HashSet<enums::Currency>>,
#[serde(deserialize_with = "deserialize_optional_hashset")]
pub country: Option<HashSet<enums::CountryAlpha2>>,
pub not_available_flows: Option<NotAvailableFlows>,
}
#[derive(Debug, Deserialize, Copy, Clone, Default)]
#[serde(default)]
pub struct NotAvailableFlows {
pub capture_method: Option<enums::CaptureMethod>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "v2", derive(Default))] // Configs are read from the config file in config/payout_required_fields.toml
pub struct PayoutRequiredFields(pub HashMap<enums::PaymentMethod, PaymentMethodType>);
#[derive(Debug, Default, Deserialize, Clone)]
#[serde(default)]
pub struct Secrets {
pub jwt_secret: Secret<String>,
pub admin_api_key: Secret<String>,
pub master_enc_key: Secret<String>,
}
#[derive(Debug, Default, Deserialize, Clone)]
#[serde(default)]
pub struct FallbackMerchantIds {
#[serde(deserialize_with = "deserialize_merchant_ids")]
pub merchant_ids: HashSet<id_type::MerchantId>,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct UserSettings {
pub password_validity_in_days: u16,
pub two_factor_auth_expiry_in_secs: i64,
pub totp_issuer_name: String,
pub base_url: String,
pub force_two_factor_auth: bool,
pub force_cookies: bool,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct Locker {
pub host: String,
pub host_rs: String,
pub mock_locker: bool,
pub basilisk_host: String,
pub locker_signing_key_id: String,
pub locker_enabled: bool,
pub ttl_for_storage_in_secs: i64,
pub decryption_scheme: DecryptionScheme,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub enum DecryptionScheme {
#[default]
#[serde(rename = "RSA-OAEP")]
RsaOaep,
#[serde(rename = "RSA-OAEP-256")]
RsaOaep256,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct Refund {
pub max_attempts: usize,
pub max_age: i64,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct EphemeralConfig {
pub validity: i64,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct Jwekey {
pub vault_encryption_key: Secret<String>,
pub rust_locker_encryption_key: Secret<String>,
pub vault_private_key: Secret<String>,
pub tunnel_private_key: Secret<String>,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct Server {
pub port: u16,
pub workers: usize,
pub host: String,
pub request_body_limit: usize,
pub shutdown_timeout: u64,
#[cfg(feature = "tls")]
pub tls: Option<ServerTls>,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct Database {
pub username: String,
pub password: Secret<String>,
pub host: String,
pub port: u16,
pub dbname: String,
pub pool_size: u32,
pub connection_timeout: u64,
pub queue_strategy: QueueStrategy,
pub min_idle: Option<u32>,
pub max_lifetime: Option<u64>,
}
impl From<Database> for storage_impl::config::Database {
fn from(val: Database) -> Self {
Self {
username: val.username,
password: val.password,
host: val.host,
port: val.port,
dbname: val.dbname,
pool_size: val.pool_size,
connection_timeout: val.connection_timeout,
queue_strategy: val.queue_strategy,
min_idle: val.min_idle,
max_lifetime: val.max_lifetime,
}
}
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct SupportedConnectors {
pub wallets: Vec<String>,
}
#[cfg(feature = "kv_store")]
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct DrainerSettings {
pub stream_name: String,
pub num_partitions: u8,
pub max_read_count: u64,
pub shutdown_interval: u32, // in milliseconds
pub loop_interval: u32, // in milliseconds
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct MerchantIdAuthSettings {
pub merchant_id_auth_enabled: bool,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct ProxyStatusMapping {
pub proxy_connector_http_status_code: bool,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct WebhooksSettings {
pub outgoing_enabled: bool,
pub ignore_error: WebhookIgnoreErrorSettings,
pub redis_lock_expiry_seconds: u32,
}
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(default)]
pub struct WebhookIgnoreErrorSettings {
pub event_type: Option<bool>,
pub payment_not_found: Option<bool>,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct ApiKeys {
/// Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating
/// hashes of API keys
pub hash_key: Secret<String>,
// Specifies the number of days before API key expiry when email reminders should be sent
#[cfg(feature = "email")]
pub expiry_reminder_days: Vec<u8>,
#[cfg(feature = "partial-auth")]
pub checksum_auth_context: Secret<String>,
#[cfg(feature = "partial-auth")]
pub checksum_auth_key: Secret<String>,
#[cfg(feature = "partial-auth")]
pub enable_partial_auth: bool,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct DelayedSessionConfig {
#[serde(deserialize_with = "deserialize_hashset")]
pub connectors_with_delayed_session_response: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct WebhookSourceVerificationCall {
#[serde(deserialize_with = "deserialize_hashset")]
pub connectors_with_webhook_source_verification_call: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct BillingConnectorPaymentsSyncCall {
#[serde(deserialize_with = "deserialize_hashset")]
pub billing_connectors_which_require_payment_sync: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct BillingConnectorInvoiceSyncCall {
#[serde(deserialize_with = "deserialize_hashset")]
pub billing_connectors_which_requires_invoice_sync_call: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ApplePayDecryptConfig {
pub apple_pay_ppc: Secret<String>,
pub apple_pay_ppc_key: Secret<String>,
pub apple_pay_merchant_cert: Secret<String>,
pub apple_pay_merchant_cert_key: Secret<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct PazeDecryptConfig {
pub paze_private_key: Secret<String>,
pub paze_private_key_passphrase: Secret<String>,
}
#[derive(Debug, Deserialize, Clone)]
pub struct GooglePayDecryptConfig {
pub google_pay_root_signing_keys: Secret<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct LockerBasedRecipientConnectorList {
#[serde(deserialize_with = "deserialize_hashset")]
pub connector_list: HashSet<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ConnectorRequestReferenceIdConfig {
pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<id_type::MerchantId>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct UserAuthMethodSettings {
pub encryption_key: Secret<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct NetworkTokenizationSupportedConnectors {
#[serde(deserialize_with = "deserialize_hashset")]
pub connector_list: HashSet<enums::Connector>,
}
impl Settings<SecuredSecret> {
pub fn new() -> ApplicationResult<Self> {
Self::with_config_path(None)
}
pub fn with_config_path(config_path: Option<PathBuf>) -> ApplicationResult<Self> {
// Configuration values are picked up in the following priority order (1 being least
// priority):
// 1. Defaults from the implementation of the `Default` trait.
// 2. Values from config file. The config file accessed depends on the environment
// specified by the `RUN_ENV` environment variable. `RUN_ENV` can be one of
// `development`, `sandbox` or `production`. If nothing is specified for `RUN_ENV`,
// `/config/development.toml` file is read.
// 3. Environment variables prefixed with `ROUTER` and each level separated by double
// underscores.
//
// Values in config file override the defaults in `Default` trait, and the values set using
// environment variables override both the defaults and the config file values.
let environment = env::which();
let config_path = router_env::Config::config_path(&environment.to_string(), config_path);
let config = router_env::Config::builder(&environment.to_string())
.change_context(ApplicationError::ConfigurationError)?
.add_source(File::from(config_path).required(false));
#[cfg(feature = "v2")]
let config = {
let required_fields_config_file =
router_env::Config::get_config_directory().join(REQUIRED_FIELDS_CONFIG_FILE);
config.add_source(File::from(required_fields_config_file).required(false))
};
let config = config
.add_source(
Environment::with_prefix("ROUTER")
.try_parsing(true)
.separator("__")
.list_separator(",")
.with_list_parse_key("log.telemetry.route_to_trace")
.with_list_parse_key("redis.cluster_urls")
.with_list_parse_key("events.kafka.brokers")
.with_list_parse_key("connectors.supported.wallets")
.with_list_parse_key("connector_request_reference_id_config.merchant_ids_send_payment_id_as_connector_request_id"),
)
.build()
.change_context(ApplicationError::ConfigurationError)?;
let mut settings: Self = serde_path_to_error::deserialize(config)
.attach_printable("Unable to deserialize application configuration")
.change_context(ApplicationError::ConfigurationError)?;
#[cfg(feature = "v1")]
{
settings.required_fields = RequiredFields::new(&settings.bank_config);
}
Ok(settings)
}
pub fn validate(&self) -> ApplicationResult<()> {
self.server.validate()?;
self.master_database.get_inner().validate()?;
#[cfg(feature = "olap")]
self.replica_database.get_inner().validate()?;
// The logger may not yet be initialized when validating the application configuration
#[allow(clippy::print_stderr)]
self.redis.validate().map_err(|error| {
eprintln!("{error}");
ApplicationError::InvalidConfigurationValueError("Redis configuration".into())
})?;
if self.log.file.enabled {
if self.log.file.file_name.is_default_or_empty() {
return Err(error_stack::Report::from(
ApplicationError::InvalidConfigurationValueError(
"log file name must not be empty".into(),
),
));
}
if self.log.file.path.is_default_or_empty() {
return Err(error_stack::Report::from(
ApplicationError::InvalidConfigurationValueError(
"log directory path must not be empty".into(),
),
));
}
}
self.secrets.get_inner().validate()?;
self.locker.validate()?;
self.connectors.validate("connectors")?;
self.chat.get_inner().validate()?;
self.cors.validate()?;
self.scheduler
.as_ref()
.map(|scheduler_settings| scheduler_settings.validate())
.transpose()?;
#[cfg(feature = "kv_store")]
self.drainer.validate()?;
self.api_keys.get_inner().validate()?;
self.file_storage
.validate()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?;
self.crm
.validate()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?;
self.lock_settings.validate()?;
self.events.validate()?;
#[cfg(feature = "olap")]
self.opensearch.validate()?;
self.encryption_management
.validate()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?;
self.secrets_management
.validate()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?;
self.generic_link.payment_method_collect.validate()?;
self.generic_link.payout_link.validate()?;
#[cfg(feature = "v2")]
self.cell_information.validate()?;
self.network_tokenization_service
.as_ref()
.map(|x| x.get_inner().validate())
.transpose()?;
self.paze_decrypt_keys
.as_ref()
.map(|x| x.get_inner().validate())
.transpose()?;
self.google_pay_decrypt_keys
.as_ref()
.map(|x| x.validate())
.transpose()?;
self.key_manager.get_inner().validate()?;
#[cfg(feature = "email")]
self.email
.validate()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?;
self.theme
.storage
.validate()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?;
self.platform.validate()?;
self.open_router.validate()?;
// Validate gRPC client settings
#[cfg(feature = "revenue_recovery")]
self.grpc_client
.recovery_decider_client
.as_ref()
.map(|config| config.validate())
.transpose()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?;
self.superposition
.get_inner()
.validate()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?;
Ok(())
}
}
impl Settings<RawSecret> {
#[cfg(feature = "kv_store")]
pub fn is_kv_soft_kill_mode(&self) -> bool {
self.kv_config.soft_kill.unwrap_or(false)
}
#[cfg(not(feature = "kv_store"))]
pub fn is_kv_soft_kill_mode(&self) -> bool {
false
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Clone, Default)]
pub struct Payouts {
pub payout_eligibility: bool,
#[serde(default)]
pub required_fields: PayoutRequiredFields,
}
#[derive(Debug, Clone, Default)]
pub struct LockSettings {
pub redis_lock_expiry_seconds: u32,
pub delay_between_retries_in_milliseconds: u32,
pub lock_retries: u32,
}
impl<'de> Deserialize<'de> for LockSettings {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Inner {
redis_lock_expiry_seconds: u32,
delay_between_retries_in_milliseconds: u32,
}
let Inner {
redis_lock_expiry_seconds,
delay_between_retries_in_milliseconds,
} = Inner::deserialize(deserializer)?;
let redis_lock_expiry_milliseconds = redis_lock_expiry_seconds * 1000;
Ok(Self {
redis_lock_expiry_seconds,
delay_between_retries_in_milliseconds,
lock_retries: redis_lock_expiry_milliseconds / delay_between_retries_in_milliseconds,
})
}
}
#[cfg(feature = "olap")]
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ConnectorOnboarding {
pub paypal: PayPalOnboarding,
}
#[cfg(feature = "olap")]
#[derive(Debug, Deserialize, Clone, Default)]
pub struct PayPalOnboarding {
pub client_id: Secret<String>,
pub client_secret: Secret<String>,
pub partner_id: Secret<String>,
pub enabled: bool,
}
#[cfg(feature = "tls")]
#[derive(Debug, Deserialize, Clone)]
pub struct ServerTls {
/// Port to host the TLS secure server on
pub port: u16,
/// Use a different host (optional) (defaults to the host provided in [`Server`] config)
pub host: Option<String>,
/// private key file path associated with TLS (path to the private key file (`pem` format))
pub private_key: PathBuf,
/// certificate file associated with TLS (path to the certificate file (`pem` format))
pub certificate: PathBuf,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct CellInformation {
pub id: id_type::CellId,
}
#[cfg(feature = "v2")]
impl Default for CellInformation {
fn default() -> Self {
// We provide a static default cell id for constructing application settings.
// This will only panic at application startup if we're unable to construct the default,
// around the time of deserializing application settings.
// And a panic at application startup is considered acceptable.
#[allow(clippy::expect_used)]
let cell_id =
id_type::CellId::from_string("defid").expect("Failed to create a default for Cell Id");
Self { id: cell_id }
}
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ThemeSettings {
pub storage: FileStorageConfig,
pub email_config: EmailThemeConfig,
}
fn deserialize_hashmap_inner<K, V>(
value: HashMap<String, String>,
) -> Result<HashMap<K, HashSet<V>>, String>
where
K: Eq + std::str::FromStr + std::hash::Hash,
V: Eq + std::str::FromStr + std::hash::Hash,
<K as std::str::FromStr>::Err: std::fmt::Display,
<V as std::str::FromStr>::Err: std::fmt::Display,
{
let (values, errors) = value
.into_iter()
.map(
|(k, v)| match (K::from_str(k.trim()), deserialize_hashset_inner(v)) {
(Err(error), _) => Err(format!(
"Unable to deserialize `{}` as `{}`: {error}",
k,
std::any::type_name::<K>()
)),
(_, Err(error)) => Err(error),
(Ok(key), Ok(value)) => Ok((key, value)),
},
)
.fold(
(HashMap::new(), Vec::new()),
|(mut values, mut errors), result| match result {
Ok((key, value)) => {
values.insert(key, value);
(values, errors)
}
Err(error) => {
errors.push(error);
(values, errors)
}
},
);
if !errors.is_empty() {
Err(format!("Some errors occurred:\n{}", errors.join("\n")))
} else {
Ok(values)
}
}
fn deserialize_hashmap<'a, D, K, V>(deserializer: D) -> Result<HashMap<K, HashSet<V>>, D::Error>
where
D: serde::Deserializer<'a>,
K: Eq + std::str::FromStr + std::hash::Hash,
V: Eq + std::str::FromStr + std::hash::Hash,
<K as std::str::FromStr>::Err: std::fmt::Display,
<V as std::str::FromStr>::Err: std::fmt::Display,
{
use serde::de::Error;
deserialize_hashmap_inner(<HashMap<String, String>>::deserialize(deserializer)?)
.map_err(D::Error::custom)
}
fn deserialize_hashset_inner<T>(value: impl AsRef<str>) -> Result<HashSet<T>, String>
where
T: Eq + std::str::FromStr + std::hash::Hash,
<T as std::str::FromStr>::Err: std::fmt::Display,
{
let (values, errors) = value
.as_ref()
.trim()
.split(',')
.map(|s| {
T::from_str(s.trim()).map_err(|error| {
format!(
"Unable to deserialize `{}` as `{}`: {error}",
s.trim(),
std::any::type_name::<T>()
)
})
})
.fold(
(HashSet::new(), Vec::new()),
|(mut values, mut errors), result| match result {
Ok(t) => {
values.insert(t);
(values, errors)
}
Err(error) => {
errors.push(error);
(values, errors)
}
},
);
if !errors.is_empty() {
Err(format!("Some errors occurred:\n{}", errors.join("\n")))
} else {
Ok(values)
}
}
fn deserialize_hashset<'a, D, T>(deserializer: D) -> Result<HashSet<T>, D::Error>
where
D: serde::Deserializer<'a>,
T: Eq + std::str::FromStr + std::hash::Hash,
<T as std::str::FromStr>::Err: std::fmt::Display,
{
use serde::de::Error;
deserialize_hashset_inner(<String>::deserialize(deserializer)?).map_err(D::Error::custom)
}
fn deserialize_optional_hashset<'a, D, T>(deserializer: D) -> Result<Option<HashSet<T>>, D::Error>
where
D: serde::Deserializer<'a>,
T: Eq + std::str::FromStr + std::hash::Hash,
<T as std::str::FromStr>::Err: std::fmt::Display,
{
use serde::de::Error;
<Option<String>>::deserialize(deserializer).map(|value| {
value.map_or(Ok(None), |inner: String| {
let list = deserialize_hashset_inner(inner).map_err(D::Error::custom)?;
match list.len() {
0 => Ok(None),
_ => Ok(Some(list)),
}
})
})?
}
fn deserialize_merchant_ids_inner(
value: impl AsRef<str>,
) -> Result<HashSet<id_type::MerchantId>, String> {
let (values, errors) = value
.as_ref()
.trim()
.split(',')
.map(|s| {
let trimmed = s.trim();
id_type::MerchantId::wrap(trimmed.to_owned()).map_err(|error| {
format!("Unable to deserialize `{trimmed}` as `MerchantId`: {error}")
})
})
.fold(
(HashSet::new(), Vec::new()),
|(mut values, mut errors), result| match result {
Ok(t) => {
values.insert(t);
(values, errors)
}
Err(error) => {
errors.push(error);
(values, errors)
}
},
);
if !errors.is_empty() {
Err(format!("Some errors occurred:\n{}", errors.join("\n")))
} else {
Ok(values)
}
}
fn deserialize_merchant_ids<'de, D>(
deserializer: D,
) -> Result<HashSet<id_type::MerchantId>, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
deserialize_merchant_ids_inner(s).map_err(serde::de::Error::custom)
}
impl<'de> Deserialize<'de> for TenantConfig {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
struct Inner {
base_url: String,
schema: String,
accounts_schema: String,
redis_key_prefix: String,
clickhouse_database: String,
user: TenantUserConfig,
}
let hashmap = <HashMap<id_type::TenantId, Inner>>::deserialize(deserializer)?;
Ok(Self(
hashmap
.into_iter()
.map(|(key, value)| {
(
key.clone(),
Tenant {
tenant_id: key,
base_url: value.base_url,
schema: value.schema,
accounts_schema: value.accounts_schema,
redis_key_prefix: value.redis_key_prefix,
clickhouse_database: value.clickhouse_database,
user: value.user,
},
)
})
.collect(),
))
}
}
#[cfg(test)]
mod hashmap_deserialization_test {
#![allow(clippy::unwrap_used)]
use std::collections::{HashMap, HashSet};
use serde::de::{
value::{Error as ValueError, MapDeserializer},
IntoDeserializer,
};
use super::deserialize_hashmap;
#[test]
fn test_payment_method_and_payment_method_types() {
use diesel_models::enums::{PaymentMethod, PaymentMethodType};
let input_map: HashMap<String, String> = HashMap::from([
("bank_transfer".to_string(), "ach,bacs".to_string()),
("wallet".to_string(), "paypal,venmo".to_string()),
]);
let deserializer: MapDeserializer<
'_,
std::collections::hash_map::IntoIter<String, String>,
ValueError,
> = input_map.into_deserializer();
let result = deserialize_hashmap::<'_, _, PaymentMethod, PaymentMethodType>(deserializer);
let expected_result = HashMap::from([
(
PaymentMethod::BankTransfer,
HashSet::from([PaymentMethodType::Ach, PaymentMethodType::Bacs]),
),
(
PaymentMethod::Wallet,
HashSet::from([PaymentMethodType::Paypal, PaymentMethodType::Venmo]),
),
]);
assert!(result.is_ok());
assert_eq!(result.unwrap(), expected_result);
}
#[test]
fn test_payment_method_and_payment_method_types_with_spaces() {
use diesel_models::enums::{PaymentMethod, PaymentMethodType};
let input_map: HashMap<String, String> = HashMap::from([
(" bank_transfer ".to_string(), " ach , bacs ".to_string()),
("wallet ".to_string(), " paypal , pix , venmo ".to_string()),
]);
let deserializer: MapDeserializer<
'_,
std::collections::hash_map::IntoIter<String, String>,
ValueError,
> = input_map.into_deserializer();
let result = deserialize_hashmap::<'_, _, PaymentMethod, PaymentMethodType>(deserializer);
let expected_result = HashMap::from([
(
PaymentMethod::BankTransfer,
HashSet::from([PaymentMethodType::Ach, PaymentMethodType::Bacs]),
),
(
PaymentMethod::Wallet,
HashSet::from([
PaymentMethodType::Paypal,
PaymentMethodType::Pix,
PaymentMethodType::Venmo,
]),
),
]);
assert!(result.is_ok());
assert_eq!(result.unwrap(), expected_result);
}
#[test]
fn test_payment_method_deserializer_error() {
use diesel_models::enums::{PaymentMethod, PaymentMethodType};
let input_map: HashMap<String, String> = HashMap::from([
("unknown".to_string(), "ach,bacs".to_string()),
("wallet".to_string(), "paypal,unknown".to_string()),
]);
let deserializer: MapDeserializer<
'_,
std::collections::hash_map::IntoIter<String, String>,
ValueError,
> = input_map.into_deserializer();
let result = deserialize_hashmap::<'_, _, PaymentMethod, PaymentMethodType>(deserializer);
assert!(result.is_err());
}
}
#[cfg(test)]
mod hashset_deserialization_test {
#![allow(clippy::unwrap_used)]
use std::collections::HashSet;
use serde::de::{
value::{Error as ValueError, StrDeserializer},
IntoDeserializer,
};
use super::deserialize_hashset;
#[test]
fn test_payment_method_hashset_deserializer() {
use diesel_models::enums::PaymentMethod;
let deserializer: StrDeserializer<'_, ValueError> = "wallet,card".into_deserializer();
let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer);
let expected_payment_methods = HashSet::from([PaymentMethod::Wallet, PaymentMethod::Card]);
assert!(payment_methods.is_ok());
assert_eq!(payment_methods.unwrap(), expected_payment_methods);
}
#[test]
fn test_payment_method_hashset_deserializer_with_spaces() {
use diesel_models::enums::PaymentMethod;
let deserializer: StrDeserializer<'_, ValueError> =
"wallet, card, bank_debit".into_deserializer();
let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer);
let expected_payment_methods = HashSet::from([
PaymentMethod::Wallet,
PaymentMethod::Card,
PaymentMethod::BankDebit,
]);
assert!(payment_methods.is_ok());
assert_eq!(payment_methods.unwrap(), expected_payment_methods);
}
#[test]
fn test_payment_method_hashset_deserializer_error() {
use diesel_models::enums::PaymentMethod;
let deserializer: StrDeserializer<'_, ValueError> =
"wallet, card, unknown".into_deserializer();
let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer);
assert!(payment_methods.is_err());
}
}
| {
"crate": "router",
"file": "crates/router/src/configs/settings.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 6,
"num_structs": 78,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_7762238761105495979 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/connector/utils.rs
// Contains: 1 structs, 2 enums
use std::{
collections::{HashMap, HashSet},
ops::Deref,
str::FromStr,
sync::LazyLock,
};
#[cfg(feature = "payouts")]
use api_models::payouts::{self, PayoutVendorAccountDetails};
use api_models::{
enums::{CanadaStatesAbbreviation, UsStatesAbbreviation},
payments,
};
use base64::Engine;
use common_utils::{
date_time,
errors::{ParsingError, ReportSwitchExt},
ext_traits::StringExt,
id_type,
pii::{self, Email, IpAddress},
types::{AmountConvertor, MinorUnit},
};
use diesel_models::{enums, types::OrderDetailsWithAmount};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
network_tokenization::NetworkTokenNumber, payments::payment_attempt::PaymentAttempt,
};
use masking::{Deserialize, ExposeInterface, Secret};
use regex::Regex;
#[cfg(feature = "frm")]
use crate::types::fraud_check;
use crate::{
consts,
core::{
errors::{self, ApiErrorResponse, CustomResult},
payments::{types::AuthenticationData, PaymentData},
},
pii::PeekInterface,
types::{
self, api, domain,
storage::enums as storage_enums,
transformers::{ForeignFrom, ForeignTryFrom},
BrowserInformation, PaymentsCancelData, ResponseId,
},
utils::{OptionExt, ValueExt},
};
pub 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()
})
}
type Error = error_stack::Report<errors::ConnectorError>;
pub trait AccessTokenRequestInfo {
fn get_request_id(&self) -> Result<Secret<String>, Error>;
}
impl AccessTokenRequestInfo for types::RefreshTokenRouterData {
fn get_request_id(&self) -> Result<Secret<String>, Error> {
self.request
.id
.clone()
.ok_or_else(missing_field_err("request.id"))
}
}
pub trait RouterData {
fn get_billing(&self) -> Result<&hyperswitch_domain_models::address::Address, Error>;
fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error>;
fn get_billing_phone(&self)
-> Result<&hyperswitch_domain_models::address::PhoneDetails, Error>;
fn get_description(&self) -> Result<String, Error>;
fn get_billing_address(
&self,
) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error>;
fn get_shipping_address(
&self,
) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error>;
fn get_shipping_address_with_phone_number(
&self,
) -> Result<&hyperswitch_domain_models::address::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_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<types::PaymentMethodToken, Error>;
fn get_customer_id(&self) -> Result<id_type::CustomerId, Error>;
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<types::RecurringMandatePaymentData, Error>;
#[cfg(feature = "payouts")]
fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error>;
#[cfg(feature = "payouts")]
fn get_quote_id(&self) -> Result<String, Error>;
fn get_optional_billing(&self) -> Option<&hyperswitch_domain_models::address::Address>;
fn get_optional_shipping(&self) -> Option<&hyperswitch_domain_models::address::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_phone_number(&self) -> Option<Secret<String>>;
fn get_optional_shipping_email(&self) -> Option<Email>;
fn get_optional_billing_full_name(&self) -> Option<Secret<String>>;
fn get_optional_billing_line1(&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_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>;
}
pub trait PaymentResponseRouterData {
fn get_attempt_status_for_db_update<F>(
&self,
payment_data: &PaymentData<F>,
amount_captured: Option<i64>,
amount_capturable: Option<i64>,
) -> CustomResult<enums::AttemptStatus, ApiErrorResponse>
where
F: Clone;
}
#[cfg(feature = "v1")]
impl<Flow, Request, Response> PaymentResponseRouterData
for types::RouterData<Flow, Request, Response>
where
Request: types::Capturable,
{
fn get_attempt_status_for_db_update<F>(
&self,
payment_data: &PaymentData<F>,
amount_captured: Option<i64>,
amount_capturable: Option<i64>,
) -> CustomResult<enums::AttemptStatus, ApiErrorResponse>
where
F: Clone,
{
match self.status {
enums::AttemptStatus::Voided => {
if payment_data.payment_intent.amount_captured > Some(MinorUnit::new(0)) {
Ok(enums::AttemptStatus::PartialCharged)
} else {
Ok(self.status)
}
}
enums::AttemptStatus::Charged => {
let captured_amount = types::Capturable::get_captured_amount(
&self.request,
amount_captured,
payment_data,
);
let total_capturable_amount = payment_data.payment_attempt.get_total_amount();
if Some(total_capturable_amount) == captured_amount.map(MinorUnit::new)
|| (captured_amount.is_some_and(|captured_amount| {
MinorUnit::new(captured_amount) > total_capturable_amount
}))
{
Ok(enums::AttemptStatus::Charged)
} else if captured_amount.is_some_and(|captured_amount| {
MinorUnit::new(captured_amount) < total_capturable_amount
}) {
Ok(enums::AttemptStatus::PartialCharged)
} else {
Ok(self.status)
}
}
enums::AttemptStatus::Authorized => {
let capturable_amount = types::Capturable::get_amount_capturable(
&self.request,
payment_data,
amount_capturable,
payment_data.payment_attempt.status,
);
let total_capturable_amount = payment_data.payment_attempt.get_total_amount();
let is_overcapture_enabled = *payment_data
.payment_attempt
.is_overcapture_enabled
.unwrap_or_default()
.deref();
if Some(total_capturable_amount) == capturable_amount.map(MinorUnit::new)
|| (capturable_amount.is_some_and(|capturable_amount| {
MinorUnit::new(capturable_amount) > total_capturable_amount
}) && is_overcapture_enabled)
{
Ok(enums::AttemptStatus::Authorized)
} else if capturable_amount.is_some_and(|capturable_amount| {
MinorUnit::new(capturable_amount) < total_capturable_amount
}) && payment_data
.payment_intent
.enable_partial_authorization
.is_some_and(|val| val.is_true())
{
Ok(enums::AttemptStatus::PartiallyAuthorized)
} else if capturable_amount.is_some_and(|capturable_amount| {
MinorUnit::new(capturable_amount) < total_capturable_amount
}) && !payment_data
.payment_intent
.enable_partial_authorization
.is_some_and(|val| val.is_true())
{
Err(ApiErrorResponse::IntegrityCheckFailed {
reason: "capturable_amount is less than the total attempt amount"
.to_string(),
field_names: "amount_capturable".to_string(),
connector_transaction_id: payment_data
.payment_attempt
.connector_transaction_id
.clone(),
})?
} else if capturable_amount.is_some_and(|capturable_amount| {
MinorUnit::new(capturable_amount) > total_capturable_amount
}) && !is_overcapture_enabled
{
Err(ApiErrorResponse::IntegrityCheckFailed {
reason: "capturable_amount is greater than the total attempt amount"
.to_string(),
field_names: "amount_capturable".to_string(),
connector_transaction_id: payment_data
.payment_attempt
.connector_transaction_id
.clone(),
})?
} else {
Ok(self.status)
}
}
_ => Ok(self.status),
}
}
}
#[cfg(feature = "v2")]
impl<Flow, Request, Response> PaymentResponseRouterData
for types::RouterData<Flow, Request, Response>
where
Request: types::Capturable,
{
fn get_attempt_status_for_db_update<F>(
&self,
payment_data: &PaymentData<F>,
amount_captured: Option<i64>,
amount_capturable: Option<i64>,
) -> CustomResult<enums::AttemptStatus, ApiErrorResponse>
where
F: Clone,
{
match self.status {
enums::AttemptStatus::Voided => {
if payment_data.payment_intent.amount_captured > Some(MinorUnit::new(0)) {
Ok(enums::AttemptStatus::PartialCharged)
} else {
Ok(self.status)
}
}
enums::AttemptStatus::Charged => {
let captured_amount = types::Capturable::get_captured_amount(
&self.request,
amount_captured,
payment_data,
);
let total_capturable_amount = payment_data.payment_attempt.get_total_amount();
if Some(total_capturable_amount) == captured_amount.map(MinorUnit::new) {
Ok(enums::AttemptStatus::Charged)
} else if captured_amount.is_some() {
Ok(enums::AttemptStatus::PartialCharged)
} else {
Ok(self.status)
}
}
enums::AttemptStatus::Authorized => {
let capturable_amount = types::Capturable::get_amount_capturable(
&self.request,
payment_data,
amount_capturable,
payment_data.payment_attempt.status,
);
if Some(payment_data.payment_attempt.get_total_amount())
== capturable_amount.map(MinorUnit::new)
{
Ok(enums::AttemptStatus::Authorized)
} else if capturable_amount.is_some() {
Ok(enums::AttemptStatus::PartiallyAuthorized)
} else {
Ok(self.status)
}
}
_ => Ok(self.status),
}
}
}
pub const SELECTED_PAYMENT_METHOD: &str = "Selected payment method";
pub fn get_unimplemented_payment_method_error_message(connector: &str) -> String {
format!("{SELECTED_PAYMENT_METHOD} through {connector}")
}
impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Response> {
fn get_billing(&self) -> Result<&hyperswitch_domain_models::address::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<&hyperswitch_domain_models::address::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<&hyperswitch_domain_models::address::Address> {
self.address.get_payment_method_billing()
}
fn get_optional_shipping(&self) -> Option<&hyperswitch_domain_models::address::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_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_description(&self) -> Result<String, Error> {
self.description
.clone()
.ok_or_else(missing_field_err("description"))
}
fn get_billing_address(
&self,
) -> Result<&hyperswitch_domain_models::address::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_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_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_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<&hyperswitch_domain_models::address::AddressDetails, Error> {
self.address
.get_shipping()
.and_then(|a| a.address.as_ref())
.ok_or_else(missing_field_err("shipping.address"))
}
fn get_shipping_address_with_phone_number(
&self,
) -> Result<&hyperswitch_domain_models::address::Address, Error> {
self.address
.get_shipping()
.ok_or_else(missing_field_err("shipping"))
}
fn get_payment_method_token(&self) -> Result<types::PaymentMethodToken, Error> {
self.payment_method_token
.clone()
.ok_or_else(missing_field_err("payment_method_token"))
}
fn get_customer_id(&self) -> Result<id_type::CustomerId, Error> {
self.customer_id
.to_owned()
.ok_or_else(missing_field_err("customer_id"))
}
fn get_connector_customer_id(&self) -> Result<String, Error> {
self.connector_customer
.to_owned()
.ok_or_else(missing_field_err("connector_customer_id"))
}
fn get_preprocessing_id(&self) -> Result<String, Error> {
self.preprocessing_id
.to_owned()
.ok_or_else(missing_field_err("preprocessing_id"))
}
fn get_recurring_mandate_payment_data(
&self,
) -> Result<types::RecurringMandatePaymentData, Error> {
self.recurring_mandate_payment_data
.to_owned()
.ok_or_else(missing_field_err("recurring_mandate_payment_data"))
}
fn get_optional_billing_full_name(&self) -> Option<Secret<String>> {
self.get_optional_billing()
.and_then(|billing_details| billing_details.address.as_ref())
.and_then(|billing_address| billing_address.get_optional_full_name())
}
#[cfg(feature = "payouts")]
fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error> {
self.payout_method_data
.to_owned()
.ok_or_else(missing_field_err("payout_method_data"))
}
#[cfg(feature = "payouts")]
fn get_quote_id(&self) -> Result<String, Error> {
self.quote_id
.to_owned()
.ok_or_else(missing_field_err("quote_id"))
}
}
pub trait AddressData {
fn get_email(&self) -> Result<Email, Error>;
fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error>;
fn get_optional_country(&self) -> Option<enums::CountryAlpha2>;
fn get_optional_full_name(&self) -> Option<Secret<String>>;
}
impl AddressData for hyperswitch_domain_models::address::Address {
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error> {
self.phone
.clone()
.map(|phone_details| phone_details.get_number_with_country_code())
.transpose()?
.ok_or_else(missing_field_err("phone"))
}
fn get_optional_country(&self) -> Option<enums::CountryAlpha2> {
self.address
.as_ref()
.and_then(|billing_details| billing_details.country)
}
fn get_optional_full_name(&self) -> Option<Secret<String>> {
self.address
.as_ref()
.and_then(|billing_address| billing_address.get_optional_full_name())
}
}
pub trait PaymentsPreProcessingData {
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>;
fn get_email(&self) -> Result<Email, Error>;
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>;
fn get_currency(&self) -> Result<enums::Currency, Error>;
fn get_amount(&self) -> Result<i64, Error>;
fn get_minor_amount(&self) -> Result<MinorUnit, Error>;
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_router_return_url(&self) -> Result<String, Error>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_complete_authorize_url(&self) -> Result<String, Error>;
fn connector_mandate_id(&self) -> Option<String>;
}
impl PaymentsPreProcessingData for types::PaymentsPreProcessingData {
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> {
self.payment_method_type
.to_owned()
.ok_or_else(missing_field_err("payment_method_type"))
}
fn get_currency(&self) -> Result<enums::Currency, Error> {
self.currency.ok_or_else(missing_field_err("currency"))
}
fn get_amount(&self) -> Result<i64, Error> {
self.amount.ok_or_else(missing_field_err("amount"))
}
// New minor amount function for amount framework
fn get_minor_amount(&self) -> Result<MinorUnit, Error> {
self.minor_amount.ok_or_else(missing_field_err("amount"))
}
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| None
| Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> {
self.order_details
.clone()
.ok_or_else(missing_field_err("order_details"))
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
fn get_router_return_url(&self) -> Result<String, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("return_url"))
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_complete_authorize_url(&self) -> Result<String, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
}
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error> {
self.redirect_response
.as_ref()
.and_then(|res| res.payload.to_owned())
.ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
}
.into(),
)
}
fn connector_mandate_id(&self) -> Option<String> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
connector_mandate_ids.get_connector_mandate_id()
}
Some(payments::MandateReferenceId::NetworkMandateId(_))
| None
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None,
})
}
}
pub trait PaymentsCaptureRequestData {
fn is_multiple_capture(&self) -> bool;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_capture_method(&self) -> Option<enums::CaptureMethod>;
}
impl PaymentsCaptureRequestData for types::PaymentsCaptureData {
fn is_multiple_capture(&self) -> bool {
self.multiple_capture_data.is_some()
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
self.capture_method.to_owned()
}
}
pub trait SplitPaymentData {
fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest>;
}
impl SplitPaymentData for types::PaymentsCaptureData {
fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> {
None
}
}
impl SplitPaymentData for types::PaymentsAuthorizeData {
fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> {
self.split_payments.clone()
}
}
impl SplitPaymentData for types::PaymentsSyncData {
fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> {
self.split_payments.clone()
}
}
impl SplitPaymentData for PaymentsCancelData {
fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> {
None
}
}
impl SplitPaymentData for types::SetupMandateRequestData {
fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> {
None
}
}
pub trait RevokeMandateRequestData {
fn get_connector_mandate_id(&self) -> Result<String, Error>;
}
impl RevokeMandateRequestData for types::MandateRevokeRequestData {
fn get_connector_mandate_id(&self) -> Result<String, Error> {
self.connector_mandate_id
.clone()
.ok_or_else(missing_field_err("connector_mandate_id"))
}
}
pub trait PaymentsSetupMandateRequestData {
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_email(&self) -> Result<Email, Error>;
fn is_card(&self) -> bool;
}
impl PaymentsSetupMandateRequestData for types::SetupMandateRequestData {
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn is_card(&self) -> bool {
matches!(self.payment_method_data, domain::PaymentMethodData::Card(_))
}
}
pub trait PaymentsAuthorizeRequestData {
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_email(&self) -> Result<Email, Error>;
fn get_optional_email(&self) -> Option<Email>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>;
fn get_card(&self) -> Result<domain::Card, Error>;
fn connector_mandate_id(&self) -> Option<String>;
fn get_optional_network_transaction_id(&self) -> Option<String>;
fn is_mandate_payment(&self) -> bool;
fn is_cit_mandate_payment(&self) -> bool;
fn is_customer_initiated_mandate_payment(&self) -> bool;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_router_return_url(&self) -> Result<String, Error>;
fn is_wallet(&self) -> bool;
fn is_card(&self) -> bool;
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>;
fn get_connector_mandate_id(&self) -> Result<String, Error>;
fn get_complete_authorize_url(&self) -> Result<String, Error>;
fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>>;
fn get_original_amount(&self) -> i64;
fn get_surcharge_amount(&self) -> Option<i64>;
fn get_tax_on_surcharge_amount(&self) -> Option<i64>;
fn get_total_surcharge_amount(&self) -> Option<i64>;
fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue>;
fn get_authentication_data(&self) -> Result<AuthenticationData, Error>;
fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error>;
}
pub trait PaymentMethodTokenizationRequestData {
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
}
impl PaymentMethodTokenizationRequestData for types::PaymentMethodTokenizationData {
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
}
impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData {
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| None
| Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_optional_email(&self) -> Option<Email> {
self.email.clone()
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> {
self.order_details
.clone()
.ok_or_else(missing_field_err("order_details"))
}
fn get_card(&self) -> Result<domain::Card, Error> {
match self.payment_method_data.clone() {
domain::PaymentMethodData::Card(card) => Ok(card),
_ => Err(missing_field_err("card")()),
}
}
fn get_complete_authorize_url(&self) -> Result<String, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
}
fn connector_mandate_id(&self) -> Option<String> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
connector_mandate_ids.get_connector_mandate_id()
}
Some(payments::MandateReferenceId::NetworkMandateId(_))
| None
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None,
})
}
fn get_optional_network_transaction_id(&self) -> Option<String> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => {
Some(network_transaction_id.clone())
}
Some(payments::MandateReferenceId::ConnectorMandateId(_))
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_))
| None => None,
})
}
fn is_mandate_payment(&self) -> bool {
((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession))
|| self
.mandate_id
.as_ref()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref())
.is_some()
}
fn is_cit_mandate_payment(&self) -> bool {
(self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession)
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
fn get_router_return_url(&self) -> Result<String, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("return_url"))
}
fn is_wallet(&self) -> bool {
matches!(
self.payment_method_data,
domain::PaymentMethodData::Wallet(_)
)
}
fn is_card(&self) -> bool {
matches!(self.payment_method_data, domain::PaymentMethodData::Card(_))
}
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> {
self.payment_method_type
.to_owned()
.ok_or_else(missing_field_err("payment_method_type"))
}
fn get_connector_mandate_id(&self) -> Result<String, Error> {
self.connector_mandate_id()
.ok_or_else(missing_field_err("connector_mandate_id"))
}
fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>> {
self.browser_info.clone().and_then(|browser_info| {
browser_info
.ip_address
.map(|ip| Secret::new(ip.to_string()))
})
}
fn get_original_amount(&self) -> i64 {
self.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.original_amount.get_amount_as_i64())
.unwrap_or(self.amount)
}
fn get_surcharge_amount(&self) -> Option<i64> {
self.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.surcharge_amount.get_amount_as_i64())
}
fn get_tax_on_surcharge_amount(&self) -> Option<i64> {
self.surcharge_details.as_ref().map(|surcharge_details| {
surcharge_details
.tax_on_surcharge_amount
.get_amount_as_i64()
})
}
fn get_total_surcharge_amount(&self) -> Option<i64> {
self.surcharge_details.as_ref().map(|surcharge_details| {
surcharge_details
.get_total_surcharge_amount()
.get_amount_as_i64()
})
}
fn is_customer_initiated_mandate_payment(&self) -> bool {
(self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession)
}
fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue> {
self.metadata.clone().and_then(|meta_data| match meta_data {
serde_json::Value::Null
| serde_json::Value::Bool(_)
| serde_json::Value::Number(_)
| serde_json::Value::String(_)
| serde_json::Value::Array(_) => None,
serde_json::Value::Object(_) => Some(meta_data.into()),
})
}
fn get_authentication_data(&self) -> Result<AuthenticationData, Error> {
self.authentication_data
.clone()
.ok_or_else(missing_field_err("authentication_data"))
}
/// Attempts to retrieve the connector mandate reference ID as a `Result<String, Error>`.
fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
connector_mandate_ids.get_connector_mandate_request_reference_id()
}
Some(payments::MandateReferenceId::NetworkMandateId(_))
| None
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None,
})
.ok_or_else(missing_field_err("connector_mandate_request_reference_id"))
}
}
pub trait ConnectorCustomerData {
fn get_email(&self) -> Result<Email, Error>;
}
impl ConnectorCustomerData for types::ConnectorCustomerData {
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
}
pub trait BrowserInformationData {
fn get_accept_header(&self) -> Result<String, Error>;
fn get_language(&self) -> Result<String, Error>;
fn get_screen_height(&self) -> Result<u32, Error>;
fn get_screen_width(&self) -> Result<u32, Error>;
fn get_color_depth(&self) -> Result<u8, Error>;
fn get_user_agent(&self) -> Result<String, Error>;
fn get_time_zone(&self) -> Result<i32, Error>;
fn get_java_enabled(&self) -> Result<bool, Error>;
fn get_java_script_enabled(&self) -> Result<bool, Error>;
fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error>;
}
impl BrowserInformationData for BrowserInformation {
fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error> {
let ip_address = self
.ip_address
.ok_or_else(missing_field_err("browser_info.ip_address"))?;
Ok(Secret::new(ip_address.to_string()))
}
fn get_accept_header(&self) -> Result<String, Error> {
self.accept_header
.clone()
.ok_or_else(missing_field_err("browser_info.accept_header"))
}
fn get_language(&self) -> Result<String, Error> {
self.language
.clone()
.ok_or_else(missing_field_err("browser_info.language"))
}
fn get_screen_height(&self) -> Result<u32, Error> {
self.screen_height
.ok_or_else(missing_field_err("browser_info.screen_height"))
}
fn get_screen_width(&self) -> Result<u32, Error> {
self.screen_width
.ok_or_else(missing_field_err("browser_info.screen_width"))
}
fn get_color_depth(&self) -> Result<u8, Error> {
self.color_depth
.ok_or_else(missing_field_err("browser_info.color_depth"))
}
fn get_user_agent(&self) -> Result<String, Error> {
self.user_agent
.clone()
.ok_or_else(missing_field_err("browser_info.user_agent"))
}
fn get_time_zone(&self) -> Result<i32, Error> {
self.time_zone
.ok_or_else(missing_field_err("browser_info.time_zone"))
}
fn get_java_enabled(&self) -> Result<bool, Error> {
self.java_enabled
.ok_or_else(missing_field_err("browser_info.java_enabled"))
}
fn get_java_script_enabled(&self) -> Result<bool, Error> {
self.java_script_enabled
.ok_or_else(missing_field_err("browser_info.java_script_enabled"))
}
}
pub trait PaymentsCompleteAuthorizeRequestData {
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_email(&self) -> Result<Email, Error>;
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>;
fn get_complete_authorize_url(&self) -> Result<String, Error>;
fn is_mandate_payment(&self) -> bool;
fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error>;
fn is_cit_mandate_payment(&self) -> bool;
}
impl PaymentsCompleteAuthorizeRequestData for types::CompleteAuthorizeData {
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| None
| Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error> {
self.redirect_response
.as_ref()
.and_then(|res| res.payload.to_owned())
.ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
}
.into(),
)
}
fn get_complete_authorize_url(&self) -> Result<String, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
}
fn is_mandate_payment(&self) -> bool {
((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession))
|| self
.mandate_id
.as_ref()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref())
.is_some()
}
fn is_cit_mandate_payment(&self) -> bool {
(self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession)
}
/// Attempts to retrieve the connector mandate reference ID as a `Result<String, Error>`.
fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
connector_mandate_ids.get_connector_mandate_request_reference_id()
}
Some(payments::MandateReferenceId::NetworkMandateId(_))
| None
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None,
})
.ok_or_else(missing_field_err("connector_mandate_request_reference_id"))
}
}
pub trait PaymentsSyncRequestData {
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError>;
}
impl PaymentsSyncRequestData for types::PaymentsSyncData {
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| None
| Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError> {
match self.connector_transaction_id.clone() {
ResponseId::ConnectorTransactionId(txn_id) => Ok(txn_id),
_ => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "connector_transaction_id",
})
.attach_printable("Expected connector transaction ID not found")
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
}
}
}
pub trait PaymentsPostSessionTokensRequestData {
fn is_auto_capture(&self) -> Result<bool, Error>;
}
impl PaymentsPostSessionTokensRequestData for types::PaymentsPostSessionTokensData {
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| None
| Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
}
pub trait PaymentsCancelRequestData {
fn get_amount(&self) -> Result<i64, Error>;
fn get_currency(&self) -> Result<enums::Currency, Error>;
fn get_cancellation_reason(&self) -> Result<String, Error>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
}
impl PaymentsCancelRequestData for PaymentsCancelData {
fn get_amount(&self) -> Result<i64, Error> {
self.amount.ok_or_else(missing_field_err("amount"))
}
fn get_currency(&self) -> Result<enums::Currency, Error> {
self.currency.ok_or_else(missing_field_err("currency"))
}
fn get_cancellation_reason(&self) -> Result<String, Error> {
self.cancellation_reason
.clone()
.ok_or_else(missing_field_err("cancellation_reason"))
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
}
pub trait RefundsRequestData {
fn get_connector_refund_id(&self) -> Result<String, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_connector_metadata(&self) -> Result<serde_json::Value, Error>;
}
impl RefundsRequestData for types::RefundsData {
#[track_caller]
fn get_connector_refund_id(&self) -> Result<String, Error> {
self.connector_refund_id
.clone()
.get_required_value("connector_refund_id")
.change_context(errors::ConnectorError::MissingConnectorTransactionID)
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_connector_metadata(&self) -> Result<serde_json::Value, Error> {
self.connector_metadata
.clone()
.ok_or_else(missing_field_err("connector_metadata"))
}
}
#[cfg(feature = "payouts")]
pub trait PayoutsData {
fn get_transfer_id(&self) -> Result<String, Error>;
fn get_customer_details(&self) -> Result<types::CustomerDetails, Error>;
fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error>;
#[cfg(feature = "payouts")]
fn get_payout_type(&self) -> Result<storage_enums::PayoutType, Error>;
}
#[cfg(feature = "payouts")]
impl PayoutsData for types::PayoutsData {
fn get_transfer_id(&self) -> Result<String, Error> {
self.connector_payout_id
.clone()
.ok_or_else(missing_field_err("transfer_id"))
}
fn get_customer_details(&self) -> Result<types::CustomerDetails, Error> {
self.customer_details
.clone()
.ok_or_else(missing_field_err("customer_details"))
}
fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error> {
self.vendor_details
.clone()
.ok_or_else(missing_field_err("vendor_details"))
}
#[cfg(feature = "payouts")]
fn get_payout_type(&self) -> Result<storage_enums::PayoutType, Error> {
self.payout_type
.to_owned()
.ok_or_else(missing_field_err("payout_type"))
}
}
static CARD_REGEX: LazyLock<HashMap<CardIssuer, Result<Regex, regex::Error>>> = LazyLock::new(
|| {
let mut map = HashMap::new();
// Reference: https://gist.github.com/michaelkeevildown/9096cd3aac9029c4e6e05588448a8841
// [#379]: Determine card issuer from card BIN number
map.insert(CardIssuer::Master, Regex::new(r"^5[1-5][0-9]{14}$"));
map.insert(CardIssuer::AmericanExpress, Regex::new(r"^3[47][0-9]{13}$"));
map.insert(CardIssuer::Visa, Regex::new(r"^4[0-9]{12}(?:[0-9]{3})?$"));
map.insert(CardIssuer::Discover, Regex::new(r"^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$"));
map.insert(
CardIssuer::Maestro,
Regex::new(r"^(5018|5020|5038|5893|6304|6759|6761|6762|6763)[0-9]{8,15}$"),
);
map.insert(
CardIssuer::DinersClub,
Regex::new(r"^3(?:0[0-5]|[68][0-9])[0-9]{11}$"),
);
map.insert(
CardIssuer::JCB,
Regex::new(r"^(3(?:088|096|112|158|337|5(?:2[89]|[3-8][0-9]))\d{12})$"),
);
map.insert(CardIssuer::CarteBlanche, Regex::new(r"^389[0-9]{11}$"));
map
},
);
#[derive(Debug, Copy, Clone, strum::Display, Eq, Hash, PartialEq)]
pub enum CardIssuer {
AmericanExpress,
Master,
Maestro,
Visa,
Discover,
DinersClub,
JCB,
CarteBlanche,
}
pub trait CardData {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>;
fn get_card_issuer(&self) -> Result<CardIssuer, Error>;
fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError>;
fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String>;
fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String>;
fn get_expiry_year_4_digit(&self) -> Secret<String>;
fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError>;
fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error>;
fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error>;
}
#[cfg(feature = "payouts")]
impl CardData for payouts::CardPayout {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.expiry_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.card_number.peek())
}
fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.expiry_month.peek(),
delimiter,
year.peek()
)))
}
fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
year.peek(),
delimiter,
self.expiry_month.peek()
))
}
fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
self.expiry_month.peek(),
delimiter,
year.peek()
))
}
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.expiry_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.expiry_month.clone().expose();
Ok(Secret::new(format!("{year}{month}")))
}
fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
self.expiry_month
.peek()
.clone()
.parse::<i8>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> {
self.expiry_year
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
}
impl CardData
for hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId
{
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.card_exp_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.card_number.peek())
}
fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.card_exp_month.peek(),
delimiter,
year.peek()
)))
}
fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
year.peek(),
delimiter,
self.card_exp_month.peek()
))
}
fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
self.card_exp_month.peek(),
delimiter,
year.peek()
))
}
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.card_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.card_exp_month.clone().expose();
Ok(Secret::new(format!("{year}{month}")))
}
fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
self.card_exp_month
.peek()
.clone()
.parse::<i8>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> {
self.card_exp_year
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
}
impl CardData for domain::Card {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.card_exp_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.card_number.peek())
}
fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.card_exp_month.peek(),
delimiter,
year.peek()
)))
}
fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
year.peek(),
delimiter,
self.card_exp_month.peek()
))
}
fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
self.card_exp_month.peek(),
delimiter,
year.peek()
))
}
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.card_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.card_exp_month.clone().expose();
Ok(Secret::new(format!("{year}{month}")))
}
fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
self.card_exp_month
.peek()
.clone()
.parse::<i8>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> {
self.card_exp_year
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
}
#[track_caller]
fn get_card_issuer(card_number: &str) -> Result<CardIssuer, Error> {
for (k, v) in CARD_REGEX.iter() {
let regex: Regex = v
.clone()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
if regex.is_match(card_number) {
return Ok(*k);
}
}
Err(error_stack::Report::new(
errors::ConnectorError::NotImplemented("Card Type".into()),
))
}
pub trait WalletData {
fn get_wallet_token(&self) -> Result<Secret<String>, Error>;
fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error>
where
T: serde::de::DeserializeOwned;
fn get_encoded_wallet_token(&self) -> Result<String, Error>;
}
impl WalletData for domain::WalletData {
fn get_wallet_token(&self) -> Result<Secret<String>, Error> {
match self {
Self::GooglePay(data) => Ok(data.get_googlepay_encrypted_payment_data()?),
Self::ApplePay(data) => Ok(data.get_applepay_decoded_payment_data()?),
Self::PaypalSdk(data) => Ok(Secret::new(data.token.clone())),
_ => Err(errors::ConnectorError::InvalidWallet.into()),
}
}
fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
serde_json::from_str::<T>(self.get_wallet_token()?.peek())
.change_context(errors::ConnectorError::InvalidWalletToken { wallet_name })
}
fn get_encoded_wallet_token(&self) -> Result<String, Error> {
match self {
Self::GooglePay(_) => {
let json_token: serde_json::Value =
self.get_wallet_token_as_json("Google Pay".to_owned())?;
let token_as_vec = serde_json::to_vec(&json_token).change_context(
errors::ConnectorError::InvalidWalletToken {
wallet_name: "Google Pay".to_string(),
},
)?;
let encoded_token = consts::BASE64_ENGINE.encode(token_as_vec);
Ok(encoded_token)
}
_ => Err(
errors::ConnectorError::NotImplemented("SELECTED PAYMENT METHOD".to_owned()).into(),
),
}
}
}
pub trait ApplePay {
fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error>;
}
impl ApplePay for domain::ApplePayWalletData {
fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error> {
let apple_pay_encrypted_data = self
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
let token = Secret::new(
String::from_utf8(
consts::BASE64_ENGINE
.decode(apple_pay_encrypted_data)
.change_context(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?,
)
.change_context(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?,
);
Ok(token)
}
}
pub trait GooglePay {
fn get_googlepay_encrypted_payment_data(&self) -> Result<Secret<String>, Error>;
}
impl GooglePay for domain::GooglePayWalletData {
fn get_googlepay_encrypted_payment_data(&self) -> Result<Secret<String>, Error> {
let encrypted_data = self
.tokenization_data
.get_encrypted_google_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Google Pay".to_string(),
})?;
Ok(Secret::new(encrypted_data.token.clone()))
}
}
pub trait CryptoData {
fn get_pay_currency(&self) -> Result<String, Error>;
}
impl CryptoData for domain::CryptoData {
fn get_pay_currency(&self) -> Result<String, Error> {
self.pay_currency
.clone()
.ok_or_else(missing_field_err("crypto_data.pay_currency"))
}
}
pub trait PhoneDetailsData {
fn get_number(&self) -> Result<Secret<String>, Error>;
fn get_country_code(&self) -> Result<String, Error>;
fn get_number_with_country_code(&self) -> Result<Secret<String>, Error>;
fn get_number_with_hash_country_code(&self) -> Result<Secret<String>, Error>;
fn extract_country_code(&self) -> Result<String, Error>;
}
impl PhoneDetailsData for hyperswitch_domain_models::address::PhoneDetails {
fn get_country_code(&self) -> Result<String, Error> {
self.country_code
.clone()
.ok_or_else(missing_field_err("billing.phone.country_code"))
}
fn extract_country_code(&self) -> Result<String, Error> {
self.get_country_code()
.map(|cc| cc.trim_start_matches('+').to_string())
}
fn get_number(&self) -> Result<Secret<String>, Error> {
self.number
.clone()
.ok_or_else(missing_field_err("billing.phone.number"))
}
fn get_number_with_country_code(&self) -> Result<Secret<String>, Error> {
let number = self.get_number()?;
let country_code = self.get_country_code()?;
Ok(Secret::new(format!("{}{}", country_code, number.peek())))
}
fn get_number_with_hash_country_code(&self) -> Result<Secret<String>, Error> {
let number = self.get_number()?;
let country_code = self.get_country_code()?;
let number_without_plus = country_code.trim_start_matches('+');
Ok(Secret::new(format!(
"{}#{}",
number_without_plus,
number.peek()
)))
}
}
pub trait AddressDetailsData {
fn get_first_name(&self) -> Result<&Secret<String>, Error>;
fn get_last_name(&self) -> Result<&Secret<String>, Error>;
fn get_full_name(&self) -> Result<Secret<String>, Error>;
fn get_line1(&self) -> Result<&Secret<String>, Error>;
fn get_city(&self) -> Result<&String, Error>;
fn get_line2(&self) -> Result<&Secret<String>, Error>;
fn get_state(&self) -> Result<&Secret<String>, Error>;
fn get_zip(&self) -> Result<&Secret<String>, Error>;
fn get_country(&self) -> Result<&api_models::enums::CountryAlpha2, Error>;
fn get_combined_address_line(&self) -> Result<Secret<String>, Error>;
fn get_optional_line2(&self) -> Option<Secret<String>>;
fn get_optional_country(&self) -> Option<api_models::enums::CountryAlpha2>;
}
impl AddressDetailsData for hyperswitch_domain_models::address::AddressDetails {
fn get_first_name(&self) -> Result<&Secret<String>, Error> {
self.first_name
.as_ref()
.ok_or_else(missing_field_err("address.first_name"))
}
fn get_last_name(&self) -> Result<&Secret<String>, Error> {
self.last_name
.as_ref()
.ok_or_else(missing_field_err("address.last_name"))
}
fn get_full_name(&self) -> Result<Secret<String>, Error> {
let first_name = self.get_first_name()?.peek().to_owned();
let last_name = self
.get_last_name()
.ok()
.cloned()
.unwrap_or(Secret::new("".to_string()));
let last_name = last_name.peek();
let full_name = format!("{first_name} {last_name}").trim().to_string();
Ok(Secret::new(full_name))
}
fn get_line1(&self) -> Result<&Secret<String>, Error> {
self.line1
.as_ref()
.ok_or_else(missing_field_err("address.line1"))
}
fn get_city(&self) -> Result<&String, Error> {
self.city
.as_ref()
.ok_or_else(missing_field_err("address.city"))
}
fn get_state(&self) -> Result<&Secret<String>, Error> {
self.state
.as_ref()
.ok_or_else(missing_field_err("address.state"))
}
fn get_line2(&self) -> Result<&Secret<String>, Error> {
self.line2
.as_ref()
.ok_or_else(missing_field_err("address.line2"))
}
fn get_zip(&self) -> Result<&Secret<String>, Error> {
self.zip
.as_ref()
.ok_or_else(missing_field_err("address.zip"))
}
fn get_country(&self) -> Result<&api_models::enums::CountryAlpha2, Error> {
self.country
.as_ref()
.ok_or_else(missing_field_err("address.country"))
}
fn get_combined_address_line(&self) -> Result<Secret<String>, Error> {
Ok(Secret::new(format!(
"{},{}",
self.get_line1()?.peek(),
self.get_line2()?.peek()
)))
}
fn get_optional_line2(&self) -> Option<Secret<String>> {
self.line2.clone()
}
fn get_optional_country(&self) -> Option<api_models::enums::CountryAlpha2> {
self.country
}
}
pub trait MandateData {
fn get_end_date(&self, format: date_time::DateFormat) -> Result<String, Error>;
fn get_metadata(&self) -> Result<pii::SecretSerdeValue, Error>;
}
impl MandateData for payments::MandateAmountData {
fn get_end_date(&self, format: date_time::DateFormat) -> Result<String, Error> {
let date = self.end_date.ok_or_else(missing_field_err(
"mandate_data.mandate_type.{multi_use|single_use}.end_date",
))?;
date_time::format_date(date, format)
.change_context(errors::ConnectorError::DateFormattingFailed)
}
fn get_metadata(&self) -> Result<pii::SecretSerdeValue, Error> {
self.metadata.clone().ok_or_else(missing_field_err(
"mandate_data.mandate_type.{multi_use|single_use}.metadata",
))
}
}
pub trait RecurringMandateData {
fn get_original_payment_amount(&self) -> Result<i64, Error>;
fn get_original_payment_currency(&self) -> Result<enums::Currency, Error>;
}
impl RecurringMandateData for types::RecurringMandatePaymentData {
fn get_original_payment_amount(&self) -> Result<i64, Error> {
self.original_payment_authorized_amount
.ok_or_else(missing_field_err("original_payment_authorized_amount"))
}
fn get_original_payment_currency(&self) -> Result<enums::Currency, Error> {
self.original_payment_authorized_currency
.ok_or_else(missing_field_err("original_payment_authorized_currency"))
}
}
pub trait MandateReferenceData {
fn get_connector_mandate_id(&self) -> Result<String, Error>;
}
impl MandateReferenceData for payments::ConnectorMandateReferenceId {
fn get_connector_mandate_id(&self) -> Result<String, Error> {
self.get_connector_mandate_id()
.ok_or_else(missing_field_err("mandate_id"))
}
}
pub fn get_header_key_value<'a>(
key: &str,
headers: &'a actix_web::http::header::HeaderMap,
) -> CustomResult<&'a str, errors::ConnectorError> {
get_header_field(headers.get(key))
}
fn get_header_field(
field: Option<&http::HeaderValue>,
) -> CustomResult<&str, errors::ConnectorError> {
field
.map(|header_value| {
header_value
.to_str()
.change_context(errors::ConnectorError::WebhookSignatureNotFound)
})
.ok_or(report!(
errors::ConnectorError::WebhookSourceVerificationFailed
))?
}
pub fn to_connector_meta<T>(connector_meta: Option<serde_json::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 fn to_connector_meta_from_secret<T>(
connector_meta: Option<Secret<serde_json::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()
}
impl ForeignTryFrom<String> for UsStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "UsStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => {
let binding = value.as_str().to_lowercase();
let state = binding.as_str();
match state {
"alabama" => Ok(Self::AL),
"alaska" => Ok(Self::AK),
"american samoa" => Ok(Self::AS),
"arizona" => Ok(Self::AZ),
"arkansas" => Ok(Self::AR),
"california" => Ok(Self::CA),
"colorado" => Ok(Self::CO),
"connecticut" => Ok(Self::CT),
"delaware" => Ok(Self::DE),
"district of columbia" | "columbia" => Ok(Self::DC),
"federated states of micronesia" | "micronesia" => Ok(Self::FM),
"florida" => Ok(Self::FL),
"georgia" => Ok(Self::GA),
"guam" => Ok(Self::GU),
"hawaii" => Ok(Self::HI),
"idaho" => Ok(Self::ID),
"illinois" => Ok(Self::IL),
"indiana" => Ok(Self::IN),
"iowa" => Ok(Self::IA),
"kansas" => Ok(Self::KS),
"kentucky" => Ok(Self::KY),
"louisiana" => Ok(Self::LA),
"maine" => Ok(Self::ME),
"marshall islands" => Ok(Self::MH),
"maryland" => Ok(Self::MD),
"massachusetts" => Ok(Self::MA),
"michigan" => Ok(Self::MI),
"minnesota" => Ok(Self::MN),
"mississippi" => Ok(Self::MS),
"missouri" => Ok(Self::MO),
"montana" => Ok(Self::MT),
"nebraska" => Ok(Self::NE),
"nevada" => Ok(Self::NV),
"new hampshire" => Ok(Self::NH),
"new jersey" => Ok(Self::NJ),
"new mexico" => Ok(Self::NM),
"new york" => Ok(Self::NY),
"north carolina" => Ok(Self::NC),
"north dakota" => Ok(Self::ND),
"northern mariana islands" => Ok(Self::MP),
"ohio" => Ok(Self::OH),
"oklahoma" => Ok(Self::OK),
"oregon" => Ok(Self::OR),
"palau" => Ok(Self::PW),
"pennsylvania" => Ok(Self::PA),
"puerto rico" => Ok(Self::PR),
"rhode island" => Ok(Self::RI),
"south carolina" => Ok(Self::SC),
"south dakota" => Ok(Self::SD),
"tennessee" => Ok(Self::TN),
"texas" => Ok(Self::TX),
"utah" => Ok(Self::UT),
"vermont" => Ok(Self::VT),
"virgin islands" => Ok(Self::VI),
"virginia" => Ok(Self::VA),
"washington" => Ok(Self::WA),
"west virginia" => Ok(Self::WV),
"wisconsin" => Ok(Self::WI),
"wyoming" => Ok(Self::WY),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
}
}
}
}
}
impl ForeignTryFrom<String> for CanadaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "CanadaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => {
let binding = value.as_str().to_lowercase();
let state = binding.as_str();
match state {
"alberta" => Ok(Self::AB),
"british columbia" => Ok(Self::BC),
"manitoba" => Ok(Self::MB),
"new brunswick" => Ok(Self::NB),
"newfoundland and labrador" | "newfoundland & labrador" => Ok(Self::NL),
"northwest territories" => Ok(Self::NT),
"nova scotia" => Ok(Self::NS),
"nunavut" => Ok(Self::NU),
"ontario" => Ok(Self::ON),
"prince edward island" => Ok(Self::PE),
"quebec" => Ok(Self::QC),
"saskatchewan" => Ok(Self::SK),
"yukon" => Ok(Self::YT),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
}
}
}
}
}
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,
}
//Gets the list of error_code_and_message, sorts based on the priority of error_type and gives most prior error
// This could be used in connectors where we get list of error_messages and have to choose one error_message
pub 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) -> enums::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>>;
}
#[cfg(feature = "frm")]
pub trait FraudCheckSaleRequest {
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>;
}
#[cfg(feature = "frm")]
impl FraudCheckSaleRequest for fraud_check::FraudCheckSaleData {
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> {
self.order_details
.clone()
.ok_or_else(missing_field_err("order_details"))
}
}
#[cfg(feature = "frm")]
pub trait FraudCheckRecordReturnRequest {
fn get_currency(&self) -> Result<storage_enums::Currency, Error>;
}
#[cfg(feature = "frm")]
impl FraudCheckRecordReturnRequest for fraud_check::FraudCheckRecordReturnData {
fn get_currency(&self) -> Result<storage_enums::Currency, Error> {
self.currency.ok_or_else(missing_field_err("currency"))
}
}
#[cfg(feature = "v1")]
pub trait PaymentsAttemptData {
fn get_browser_info(&self)
-> Result<BrowserInformation, error_stack::Report<ApiErrorResponse>>;
}
#[cfg(feature = "v1")]
impl PaymentsAttemptData for PaymentAttempt {
fn get_browser_info(
&self,
) -> Result<BrowserInformation, error_stack::Report<ApiErrorResponse>> {
self.browser_info
.clone()
.ok_or(ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?
.parse_value::<BrowserInformation>("BrowserInformation")
.change_context(ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})
}
}
#[cfg(feature = "frm")]
pub trait FrmTransactionRouterDataRequest {
fn is_payment_successful(&self) -> Option<bool>;
}
#[cfg(feature = "frm")]
impl FrmTransactionRouterDataRequest for fraud_check::FrmTransactionRouterData {
fn is_payment_successful(&self) -> Option<bool> {
match self.status {
storage_enums::AttemptStatus::AuthenticationFailed
| storage_enums::AttemptStatus::RouterDeclined
| storage_enums::AttemptStatus::AuthorizationFailed
| storage_enums::AttemptStatus::Voided
| storage_enums::AttemptStatus::VoidedPostCharge
| storage_enums::AttemptStatus::CaptureFailed
| storage_enums::AttemptStatus::Failure
| storage_enums::AttemptStatus::AutoRefunded
| storage_enums::AttemptStatus::Expired => Some(false),
storage_enums::AttemptStatus::AuthenticationSuccessful
| storage_enums::AttemptStatus::PartialChargedAndChargeable
| storage_enums::AttemptStatus::Authorized
| storage_enums::AttemptStatus::Charged
| storage_enums::AttemptStatus::PartiallyAuthorized => Some(true),
storage_enums::AttemptStatus::Started
| storage_enums::AttemptStatus::AuthenticationPending
| storage_enums::AttemptStatus::Authorizing
| storage_enums::AttemptStatus::CodInitiated
| storage_enums::AttemptStatus::VoidInitiated
| storage_enums::AttemptStatus::CaptureInitiated
| storage_enums::AttemptStatus::VoidFailed
| storage_enums::AttemptStatus::PartialCharged
| storage_enums::AttemptStatus::Unresolved
| storage_enums::AttemptStatus::Pending
| storage_enums::AttemptStatus::PaymentMethodAwaited
| storage_enums::AttemptStatus::ConfirmationAwaited
| storage_enums::AttemptStatus::DeviceDataCollectionPending
| storage_enums::AttemptStatus::IntegrityFailure => None,
}
}
}
pub fn is_payment_failure(status: enums::AttemptStatus) -> bool {
match status {
common_enums::AttemptStatus::AuthenticationFailed
| common_enums::AttemptStatus::AuthorizationFailed
| common_enums::AttemptStatus::CaptureFailed
| common_enums::AttemptStatus::VoidFailed
| common_enums::AttemptStatus::Failure
| common_enums::AttemptStatus::Expired => true,
common_enums::AttemptStatus::Started
| common_enums::AttemptStatus::RouterDeclined
| common_enums::AttemptStatus::AuthenticationPending
| common_enums::AttemptStatus::AuthenticationSuccessful
| common_enums::AttemptStatus::Authorized
| common_enums::AttemptStatus::Charged
| common_enums::AttemptStatus::Authorizing
| common_enums::AttemptStatus::CodInitiated
| common_enums::AttemptStatus::Voided
| common_enums::AttemptStatus::VoidedPostCharge
| common_enums::AttemptStatus::VoidInitiated
| common_enums::AttemptStatus::CaptureInitiated
| common_enums::AttemptStatus::AutoRefunded
| common_enums::AttemptStatus::PartialCharged
| common_enums::AttemptStatus::PartialChargedAndChargeable
| common_enums::AttemptStatus::Unresolved
| common_enums::AttemptStatus::Pending
| common_enums::AttemptStatus::PaymentMethodAwaited
| common_enums::AttemptStatus::ConfirmationAwaited
| common_enums::AttemptStatus::DeviceDataCollectionPending
| common_enums::AttemptStatus::IntegrityFailure
| common_enums::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,
}
}
impl
ForeignFrom<(
Option<String>,
Option<String>,
Option<String>,
u16,
Option<enums::AttemptStatus>,
Option<String>,
)> for types::ErrorResponse
{
fn foreign_from(
(code, message, reason, http_code, attempt_status, connector_transaction_id): (
Option<String>,
Option<String>,
Option<String>,
u16,
Option<enums::AttemptStatus>,
Option<String>,
),
) -> Self {
Self {
code: code.unwrap_or(consts::NO_ERROR_CODE.to_string()),
message: message
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code: http_code,
attempt_status,
connector_transaction_id,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
}
pub fn get_card_details(
payment_method_data: domain::PaymentMethodData,
connector_name: &'static str,
) -> Result<domain::payments::Card, errors::ConnectorError> {
match payment_method_data {
domain::PaymentMethodData::Card(details) => Ok(details),
_ => Err(errors::ConnectorError::NotSupported {
message: SELECTED_PAYMENT_METHOD.to_string(),
connector: connector_name,
})?,
}
}
#[cfg(test)]
mod error_code_error_message_tests {
#![allow(clippy::unwrap_used)]
use super::*;
struct TestConnector;
impl ConnectorErrorTypeMapping for TestConnector {
fn get_connector_error_type(
&self,
error_code: String,
error_message: String,
) -> ConnectorErrorType {
match (error_code.as_str(), error_message.as_str()) {
("01", "INVALID_MERCHANT") => ConnectorErrorType::BusinessError,
("03", "INVALID_CVV") => ConnectorErrorType::UserError,
("04", "04") => ConnectorErrorType::TechnicalError,
_ => ConnectorErrorType::UnknownError,
}
}
}
#[test]
fn test_get_error_code_error_message_based_on_priority() {
let error_code_message_list_unknown = vec![
ErrorCodeAndMessage {
error_code: "01".to_string(),
error_message: "INVALID_MERCHANT".to_string(),
},
ErrorCodeAndMessage {
error_code: "05".to_string(),
error_message: "05".to_string(),
},
ErrorCodeAndMessage {
error_code: "03".to_string(),
error_message: "INVALID_CVV".to_string(),
},
ErrorCodeAndMessage {
error_code: "04".to_string(),
error_message: "04".to_string(),
},
];
let error_code_message_list_user = vec![
ErrorCodeAndMessage {
error_code: "01".to_string(),
error_message: "INVALID_MERCHANT".to_string(),
},
ErrorCodeAndMessage {
error_code: "03".to_string(),
error_message: "INVALID_CVV".to_string(),
},
];
let error_code_error_message_unknown = get_error_code_error_message_based_on_priority(
TestConnector,
error_code_message_list_unknown,
);
let error_code_error_message_user = get_error_code_error_message_based_on_priority(
TestConnector,
error_code_message_list_user,
);
let error_code_error_message_none =
get_error_code_error_message_based_on_priority(TestConnector, vec![]);
assert_eq!(
error_code_error_message_unknown,
Some(ErrorCodeAndMessage {
error_code: "05".to_string(),
error_message: "05".to_string(),
})
);
assert_eq!(
error_code_error_message_user,
Some(ErrorCodeAndMessage {
error_code: "03".to_string(),
error_message: "INVALID_CVV".to_string(),
})
);
assert_eq!(error_code_error_message_none, None);
}
}
pub fn is_mandate_supported(
selected_pmd: domain::payments::PaymentMethodData,
payment_method_type: Option<types::storage::enums::PaymentMethodType>,
mandate_implemented_pmds: HashSet<PaymentMethodDataType>,
connector: &'static str,
) -> Result<(), Error> {
if mandate_implemented_pmds.contains(&PaymentMethodDataType::from(selected_pmd.clone())) {
Ok(())
} else {
match payment_method_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()),
}
}
}
#[derive(Debug, strum::Display, Eq, PartialEq, Hash)]
pub enum PaymentMethodDataType {
Card,
Knet,
Benefit,
MomoAtm,
CardRedirect,
AliPayQr,
AliPayRedirect,
AliPayHkRedirect,
AmazonPay,
AmazonPayRedirect,
Paysera,
Skrill,
MomoRedirect,
KakaoPayRedirect,
GoPayRedirect,
GcashRedirect,
ApplePay,
ApplePayRedirect,
ApplePayThirdPartySdk,
DanaRedirect,
DuitNow,
GooglePay,
Bluecode,
GooglePayRedirect,
GooglePayThirdPartySdk,
MbWayRedirect,
MobilePayRedirect,
PaypalRedirect,
PaypalSdk,
Paze,
SamsungPay,
TwintRedirect,
VippsRedirect,
TouchNGoRedirect,
WeChatPayRedirect,
WeChatPayQr,
CashappQr,
SwishQr,
KlarnaRedirect,
KlarnaSdk,
AffirmRedirect,
AfterpayClearpayRedirect,
PayBrightRedirect,
WalleyRedirect,
AlmaRedirect,
AtomeRedirect,
BreadpayRedirect,
FlexitiRedirect,
BancontactCard,
Bizum,
Blik,
Eft,
Eps,
Giropay,
Ideal,
Interac,
LocalBankRedirect,
OnlineBankingCzechRepublic,
OnlineBankingFinland,
OnlineBankingPoland,
OnlineBankingSlovakia,
OpenBankingUk,
Przelewy24,
Sofort,
Trustly,
OnlineBankingFpx,
OnlineBankingThailand,
AchBankDebit,
SepaBankDebit,
SepaGuarenteedDebit,
BecsBankDebit,
BacsBankDebit,
AchBankTransfer,
SepaBankTransfer,
BacsBankTransfer,
MultibancoBankTransfer,
PermataBankTransfer,
BcaBankTransfer,
BniVaBankTransfer,
BriVaBankTransfer,
CimbVaBankTransfer,
DanamonVaBankTransfer,
MandiriVaBankTransfer,
Pix,
Pse,
Crypto,
MandatePayment,
Reward,
Upi,
Boleto,
Efecty,
PagoEfectivo,
RedCompra,
RedPagos,
Alfamart,
Indomaret,
Oxxo,
SevenEleven,
Lawson,
MiniStop,
FamilyMart,
Seicomart,
PayEasy,
Givex,
BhnCardNetwork,
PaySafeCar,
CardToken,
LocalBankTransfer,
Mifinity,
Fps,
PromptPay,
VietQr,
OpenBanking,
NetworkToken,
DirectCarrierBilling,
InstantBankTransfer,
InstantBankTransferFinland,
InstantBankTransferPoland,
RevolutPay,
IndonesianBankTransfer,
}
impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType {
fn from(pm_data: domain::payments::PaymentMethodData) -> Self {
match pm_data {
domain::payments::PaymentMethodData::Card(_) => Self::Card,
domain::payments::PaymentMethodData::NetworkToken(_) => Self::NetworkToken,
domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Self::Card,
domain::payments::PaymentMethodData::CardRedirect(card_redirect_data) => {
match card_redirect_data {
domain::CardRedirectData::Knet {} => Self::Knet,
domain::payments::CardRedirectData::Benefit {} => Self::Benefit,
domain::payments::CardRedirectData::MomoAtm {} => Self::MomoAtm,
domain::payments::CardRedirectData::CardRedirect {} => Self::CardRedirect,
}
}
domain::payments::PaymentMethodData::Wallet(wallet_data) => match wallet_data {
domain::payments::WalletData::AliPayQr(_) => Self::AliPayQr,
domain::payments::WalletData::AliPayRedirect(_) => Self::AliPayRedirect,
domain::payments::WalletData::AliPayHkRedirect(_) => Self::AliPayHkRedirect,
domain::payments::WalletData::AmazonPay(_) => Self::AmazonPay,
domain::payments::WalletData::AmazonPayRedirect(_) => Self::AmazonPayRedirect,
domain::payments::WalletData::Paysera(_) => Self::Paysera,
domain::payments::WalletData::Skrill(_) => Self::Skrill,
domain::payments::WalletData::MomoRedirect(_) => Self::MomoRedirect,
domain::payments::WalletData::KakaoPayRedirect(_) => Self::KakaoPayRedirect,
domain::payments::WalletData::GoPayRedirect(_) => Self::GoPayRedirect,
domain::payments::WalletData::GcashRedirect(_) => Self::GcashRedirect,
domain::payments::WalletData::ApplePay(_) => Self::ApplePay,
domain::payments::WalletData::ApplePayRedirect(_) => Self::ApplePayRedirect,
domain::payments::WalletData::ApplePayThirdPartySdk(_) => {
Self::ApplePayThirdPartySdk
}
domain::payments::WalletData::DanaRedirect {} => Self::DanaRedirect,
domain::payments::WalletData::GooglePay(_) => Self::GooglePay,
domain::payments::WalletData::BluecodeRedirect {} => Self::Bluecode,
domain::payments::WalletData::GooglePayRedirect(_) => Self::GooglePayRedirect,
domain::payments::WalletData::GooglePayThirdPartySdk(_) => {
Self::GooglePayThirdPartySdk
}
domain::payments::WalletData::MbWayRedirect(_) => Self::MbWayRedirect,
domain::payments::WalletData::MobilePayRedirect(_) => Self::MobilePayRedirect,
domain::payments::WalletData::PaypalRedirect(_) => Self::PaypalRedirect,
domain::payments::WalletData::PaypalSdk(_) => Self::PaypalSdk,
domain::payments::WalletData::Paze(_) => Self::Paze,
domain::payments::WalletData::SamsungPay(_) => Self::SamsungPay,
domain::payments::WalletData::TwintRedirect {} => Self::TwintRedirect,
domain::payments::WalletData::VippsRedirect {} => Self::VippsRedirect,
domain::payments::WalletData::TouchNGoRedirect(_) => Self::TouchNGoRedirect,
domain::payments::WalletData::WeChatPayRedirect(_) => Self::WeChatPayRedirect,
domain::payments::WalletData::WeChatPayQr(_) => Self::WeChatPayQr,
domain::payments::WalletData::CashappQr(_) => Self::CashappQr,
domain::payments::WalletData::SwishQr(_) => Self::SwishQr,
domain::payments::WalletData::Mifinity(_) => Self::Mifinity,
domain::payments::WalletData::RevolutPay(_) => Self::RevolutPay,
},
domain::payments::PaymentMethodData::PayLater(pay_later_data) => match pay_later_data {
domain::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect,
domain::payments::PayLaterData::KlarnaSdk { .. } => Self::KlarnaSdk,
domain::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect,
domain::payments::PayLaterData::AfterpayClearpayRedirect { .. } => {
Self::AfterpayClearpayRedirect
}
domain::payments::PayLaterData::PayBrightRedirect {} => Self::PayBrightRedirect,
domain::payments::PayLaterData::WalleyRedirect {} => Self::WalleyRedirect,
domain::payments::PayLaterData::AlmaRedirect {} => Self::AlmaRedirect,
domain::payments::PayLaterData::FlexitiRedirect {} => Self::FlexitiRedirect,
domain::payments::PayLaterData::AtomeRedirect {} => Self::AtomeRedirect,
domain::payments::PayLaterData::BreadpayRedirect {} => Self::BreadpayRedirect,
},
domain::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => {
match bank_redirect_data {
domain::payments::BankRedirectData::BancontactCard { .. } => {
Self::BancontactCard
}
domain::payments::BankRedirectData::Bizum {} => Self::Bizum,
domain::payments::BankRedirectData::Blik { .. } => Self::Blik,
domain::payments::BankRedirectData::Eft { .. } => Self::Eft,
domain::payments::BankRedirectData::Eps { .. } => Self::Eps,
domain::payments::BankRedirectData::Giropay { .. } => Self::Giropay,
domain::payments::BankRedirectData::Ideal { .. } => Self::Ideal,
domain::payments::BankRedirectData::Interac { .. } => Self::Interac,
domain::payments::BankRedirectData::OnlineBankingCzechRepublic { .. } => {
Self::OnlineBankingCzechRepublic
}
domain::payments::BankRedirectData::OnlineBankingFinland { .. } => {
Self::OnlineBankingFinland
}
domain::payments::BankRedirectData::OnlineBankingPoland { .. } => {
Self::OnlineBankingPoland
}
domain::payments::BankRedirectData::OnlineBankingSlovakia { .. } => {
Self::OnlineBankingSlovakia
}
domain::payments::BankRedirectData::OpenBankingUk { .. } => Self::OpenBankingUk,
domain::payments::BankRedirectData::Przelewy24 { .. } => Self::Przelewy24,
domain::payments::BankRedirectData::Sofort { .. } => Self::Sofort,
domain::payments::BankRedirectData::Trustly { .. } => Self::Trustly,
domain::payments::BankRedirectData::OnlineBankingFpx { .. } => {
Self::OnlineBankingFpx
}
domain::payments::BankRedirectData::OnlineBankingThailand { .. } => {
Self::OnlineBankingThailand
}
domain::payments::BankRedirectData::LocalBankRedirect { } => {
Self::LocalBankRedirect
}
}
}
domain::payments::PaymentMethodData::BankDebit(bank_debit_data) => {
match bank_debit_data {
domain::payments::BankDebitData::AchBankDebit { .. } => Self::AchBankDebit,
domain::payments::BankDebitData::SepaBankDebit { .. } => Self::SepaBankDebit,
domain::payments::BankDebitData::SepaGuarenteedBankDebit { .. } => Self::SepaGuarenteedDebit,
domain::payments::BankDebitData::BecsBankDebit { .. } => Self::BecsBankDebit,
domain::payments::BankDebitData::BacsBankDebit { .. } => Self::BacsBankDebit,
}
}
domain::payments::PaymentMethodData::BankTransfer(bank_transfer_data) => {
match *bank_transfer_data {
domain::payments::BankTransferData::AchBankTransfer { .. } => {
Self::AchBankTransfer
}
domain::payments::BankTransferData::SepaBankTransfer { .. } => {
Self::SepaBankTransfer
}
domain::payments::BankTransferData::BacsBankTransfer { .. } => {
Self::BacsBankTransfer
}
domain::payments::BankTransferData::MultibancoBankTransfer { .. } => {
Self::MultibancoBankTransfer
}
domain::payments::BankTransferData::PermataBankTransfer { .. } => {
Self::PermataBankTransfer
}
domain::payments::BankTransferData::BcaBankTransfer { .. } => {
Self::BcaBankTransfer
}
domain::payments::BankTransferData::BniVaBankTransfer { .. } => {
Self::BniVaBankTransfer
}
domain::payments::BankTransferData::BriVaBankTransfer { .. } => {
Self::BriVaBankTransfer
}
domain::payments::BankTransferData::CimbVaBankTransfer { .. } => {
Self::CimbVaBankTransfer
}
domain::payments::BankTransferData::DanamonVaBankTransfer { .. } => {
Self::DanamonVaBankTransfer
}
domain::payments::BankTransferData::MandiriVaBankTransfer { .. } => {
Self::MandiriVaBankTransfer
}
domain::payments::BankTransferData::Pix { .. } => Self::Pix,
domain::payments::BankTransferData::Pse {} => Self::Pse,
domain::payments::BankTransferData::LocalBankTransfer { .. } => {
Self::LocalBankTransfer
}
domain::payments::BankTransferData::InstantBankTransfer {} => {
Self::InstantBankTransfer
}
domain::payments::BankTransferData::InstantBankTransferFinland {} => {
Self::InstantBankTransferFinland
}
domain::payments::BankTransferData::InstantBankTransferPoland {} => {
Self::InstantBankTransferPoland
}
domain::payments::BankTransferData::IndonesianBankTransfer { .. } => {
Self::IndonesianBankTransfer
}
}
}
domain::payments::PaymentMethodData::Crypto(_) => Self::Crypto,
domain::payments::PaymentMethodData::MandatePayment => Self::MandatePayment,
domain::payments::PaymentMethodData::Reward => Self::Reward,
domain::payments::PaymentMethodData::Upi(_) => Self::Upi,
domain::payments::PaymentMethodData::Voucher(voucher_data) => match voucher_data {
domain::payments::VoucherData::Boleto(_) => Self::Boleto,
domain::payments::VoucherData::Efecty => Self::Efecty,
domain::payments::VoucherData::PagoEfectivo => Self::PagoEfectivo,
domain::payments::VoucherData::RedCompra => Self::RedCompra,
domain::payments::VoucherData::RedPagos => Self::RedPagos,
domain::payments::VoucherData::Alfamart(_) => Self::Alfamart,
domain::payments::VoucherData::Indomaret(_) => Self::Indomaret,
domain::payments::VoucherData::Oxxo => Self::Oxxo,
domain::payments::VoucherData::SevenEleven(_) => Self::SevenEleven,
domain::payments::VoucherData::Lawson(_) => Self::Lawson,
domain::payments::VoucherData::MiniStop(_) => Self::MiniStop,
domain::payments::VoucherData::FamilyMart(_) => Self::FamilyMart,
domain::payments::VoucherData::Seicomart(_) => Self::Seicomart,
domain::payments::VoucherData::PayEasy(_) => Self::PayEasy,
},
domain::PaymentMethodData::RealTimePayment(real_time_payment_data) => match *real_time_payment_data{
hyperswitch_domain_models::payment_method_data::RealTimePaymentData::DuitNow { } => Self::DuitNow,
hyperswitch_domain_models::payment_method_data::RealTimePaymentData::Fps { } => Self::Fps,
hyperswitch_domain_models::payment_method_data::RealTimePaymentData::PromptPay { } => Self::PromptPay,
hyperswitch_domain_models::payment_method_data::RealTimePaymentData::VietQr { } => Self::VietQr,
},
domain::payments::PaymentMethodData::GiftCard(gift_card_data) => {
match *gift_card_data {
domain::payments::GiftCardData::Givex(_) => Self::Givex,
domain::payments::GiftCardData::BhnCardNetwork(_)=>Self::BhnCardNetwork,
domain::payments::GiftCardData::PaySafeCard {} => Self::PaySafeCar,
}
}
domain::payments::PaymentMethodData::CardToken(_) => Self::CardToken,
domain::payments::PaymentMethodData::OpenBanking(data) => match data {
hyperswitch_domain_models::payment_method_data::OpenBankingData::OpenBankingPIS { } => Self::OpenBanking
},
domain::payments::PaymentMethodData::MobilePayment(mobile_payment_data) => match mobile_payment_data {
hyperswitch_domain_models::payment_method_data::MobilePaymentData::DirectCarrierBilling { .. } => Self::DirectCarrierBilling,
},
}
}
}
pub 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 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 trait NetworkTokenData {
fn get_card_issuer(&self) -> Result<CardIssuer, Error>;
fn get_expiry_year_4_digit(&self) -> Secret<String>;
fn get_network_token(&self) -> NetworkTokenNumber;
fn get_network_token_expiry_month(&self) -> Secret<String>;
fn get_network_token_expiry_year(&self) -> Secret<String>;
fn get_cryptogram(&self) -> Option<Secret<String>>;
}
impl NetworkTokenData for domain::NetworkTokenData {
#[cfg(feature = "v1")]
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.token_number.peek())
}
#[cfg(feature = "v2")]
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.network_token.peek())
}
#[cfg(feature = "v1")]
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.token_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
#[cfg(feature = "v2")]
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.network_token_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
#[cfg(feature = "v1")]
fn get_network_token(&self) -> NetworkTokenNumber {
self.token_number.clone()
}
#[cfg(feature = "v2")]
fn get_network_token(&self) -> NetworkTokenNumber {
self.network_token.clone()
}
#[cfg(feature = "v1")]
fn get_network_token_expiry_month(&self) -> Secret<String> {
self.token_exp_month.clone()
}
#[cfg(feature = "v2")]
fn get_network_token_expiry_month(&self) -> Secret<String> {
self.network_token_exp_month.clone()
}
#[cfg(feature = "v1")]
fn get_network_token_expiry_year(&self) -> Secret<String> {
self.token_exp_year.clone()
}
#[cfg(feature = "v2")]
fn get_network_token_expiry_year(&self) -> Secret<String> {
self.network_token_exp_year.clone()
}
#[cfg(feature = "v1")]
fn get_cryptogram(&self) -> Option<Secret<String>> {
self.token_cryptogram.clone()
}
#[cfg(feature = "v2")]
fn get_cryptogram(&self) -> Option<Secret<String>> {
self.cryptogram.clone()
}
}
pub fn convert_uppercase<'de, D, T>(v: D) -> Result<T, D::Error>
where
D: serde::Deserializer<'de>,
T: FromStr,
<T as FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error,
{
use serde::de::Error;
let output = <&str>::deserialize(v)?;
output.to_uppercase().parse::<T>().map_err(D::Error::custom)
}
| {
"crate": "router",
"file": "crates/router/src/connector/utils.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_4254108066814551955 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/db/kafka_store.rs
// Contains: 2 structs, 0 enums
use std::{collections::HashSet, sync::Arc};
use ::payment_methods::state::PaymentMethodsStorageInterface;
use common_enums::enums::MerchantStorageScheme;
use common_utils::{
errors::CustomResult,
id_type,
types::{keymanager::KeyManagerState, user::ThemeLineage, TenantConfig},
};
#[cfg(feature = "v2")]
use diesel_models::ephemeral_key::{ClientSecretType, ClientSecretTypeNew};
use diesel_models::{
enums::{self, ProcessTrackerStatus},
ephemeral_key::{EphemeralKey, EphemeralKeyNew},
refund as diesel_refund,
reverse_lookup::{ReverseLookup, ReverseLookupNew},
user_role as user_storage,
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::payouts::{
payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface,
};
use hyperswitch_domain_models::{
cards_info::CardsInfoInterface,
disputes,
invoice::{Invoice as DomainInvoice, InvoiceInterface, InvoiceUpdate as DomainInvoiceUpdate},
payment_methods::PaymentMethodInterface,
payments::{payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface},
refunds,
subscription::{
Subscription as DomainSubscription, SubscriptionInterface,
SubscriptionUpdate as DomainSubscriptionUpdate,
},
};
#[cfg(not(feature = "payouts"))]
use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
use masking::Secret;
use redis_interface::{errors::RedisError, RedisConnectionPool, RedisEntryId};
use router_env::{instrument, logger, tracing};
use scheduler::{
db::{process_tracker::ProcessTrackerInterface, queue::QueueInterface},
SchedulerInterface,
};
use serde::Serialize;
use storage_impl::redis::kv_store::RedisConnInterface;
use time::PrimitiveDateTime;
use super::{
dashboard_metadata::DashboardMetadataInterface,
ephemeral_key::ClientSecretInterface,
hyperswitch_ai_interaction::HyperswitchAiInteractionInterface,
role::RoleInterface,
user::{sample_data::BatchSampleDataInterface, theme::ThemeInterface, UserInterface},
user_authentication_method::UserAuthenticationMethodInterface,
user_key_store::UserKeyStoreInterface,
user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload, UserRoleInterface},
};
#[cfg(feature = "payouts")]
use crate::services::kafka::payout::KafkaPayout;
use crate::{
core::errors::{self, ProcessTrackerError},
db::{
self,
address::AddressInterface,
api_keys::ApiKeyInterface,
authentication::AuthenticationInterface,
authorization::AuthorizationInterface,
business_profile::ProfileInterface,
callback_mapper::CallbackMapperInterface,
capture::CaptureInterface,
configs::ConfigInterface,
customers::CustomerInterface,
dispute::DisputeInterface,
ephemeral_key::EphemeralKeyInterface,
events::EventInterface,
file::FileMetadataInterface,
generic_link::GenericLinkInterface,
gsm::GsmInterface,
health_check::HealthCheckDbInterface,
locker_mock_up::LockerMockUpInterface,
mandate::MandateInterface,
merchant_account::MerchantAccountInterface,
merchant_connector_account::{ConnectorAccessToken, MerchantConnectorAccountInterface},
merchant_key_store::MerchantKeyStoreInterface,
payment_link::PaymentLinkInterface,
refund::RefundInterface,
reverse_lookup::ReverseLookupInterface,
routing_algorithm::RoutingAlgorithmInterface,
tokenization::TokenizationInterface,
unified_translations::UnifiedTranslationsInterface,
AccountsStorageInterface, CommonStorageInterface, GlobalStorageInterface,
MasterKeyInterface, StorageInterface,
},
services::{kafka::KafkaProducer, Store},
types::{domain, storage, AccessToken},
};
#[derive(Debug, Clone, Serialize)]
pub struct TenantID(pub String);
#[derive(Clone)]
pub struct KafkaStore {
pub kafka_producer: KafkaProducer,
pub diesel_store: Store,
pub tenant_id: TenantID,
}
impl KafkaStore {
pub async fn new(
store: Store,
mut kafka_producer: KafkaProducer,
tenant_id: TenantID,
tenant_config: &dyn TenantConfig,
) -> Self {
kafka_producer.set_tenancy(tenant_config);
Self {
kafka_producer,
diesel_store: store,
tenant_id,
}
}
}
#[async_trait::async_trait]
impl AddressInterface for KafkaStore {
async fn find_address_by_address_id(
&self,
state: &KeyManagerState,
address_id: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError> {
self.diesel_store
.find_address_by_address_id(state, address_id, key_store)
.await
}
async fn update_address(
&self,
state: &KeyManagerState,
address_id: String,
address: storage::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError> {
self.diesel_store
.update_address(state, address_id, address, key_store)
.await
}
async fn update_address_for_payments(
&self,
state: &KeyManagerState,
this: domain::PaymentAddress,
address: domain::AddressUpdate,
payment_id: id_type::PaymentId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentAddress, errors::StorageError> {
self.diesel_store
.update_address_for_payments(
state,
this,
address,
payment_id,
key_store,
storage_scheme,
)
.await
}
async fn insert_address_for_payments(
&self,
state: &KeyManagerState,
payment_id: &id_type::PaymentId,
address: domain::PaymentAddress,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentAddress, errors::StorageError> {
self.diesel_store
.insert_address_for_payments(state, payment_id, address, key_store, storage_scheme)
.await
}
async fn find_address_by_merchant_id_payment_id_address_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
address_id: &str,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentAddress, errors::StorageError> {
self.diesel_store
.find_address_by_merchant_id_payment_id_address_id(
state,
merchant_id,
payment_id,
address_id,
key_store,
storage_scheme,
)
.await
}
async fn insert_address_for_customers(
&self,
state: &KeyManagerState,
address: domain::CustomerAddress,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError> {
self.diesel_store
.insert_address_for_customers(state, address, key_store)
.await
}
async fn update_address_by_merchant_id_customer_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
address: storage::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Address>, errors::StorageError> {
self.diesel_store
.update_address_by_merchant_id_customer_id(
state,
customer_id,
merchant_id,
address,
key_store,
)
.await
}
}
#[async_trait::async_trait]
impl ApiKeyInterface for KafkaStore {
async fn insert_api_key(
&self,
api_key: storage::ApiKeyNew,
) -> CustomResult<storage::ApiKey, errors::StorageError> {
self.diesel_store.insert_api_key(api_key).await
}
async fn update_api_key(
&self,
merchant_id: id_type::MerchantId,
key_id: id_type::ApiKeyId,
api_key: storage::ApiKeyUpdate,
) -> CustomResult<storage::ApiKey, errors::StorageError> {
self.diesel_store
.update_api_key(merchant_id, key_id, api_key)
.await
}
async fn revoke_api_key(
&self,
merchant_id: &id_type::MerchantId,
key_id: &id_type::ApiKeyId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store.revoke_api_key(merchant_id, key_id).await
}
async fn find_api_key_by_merchant_id_key_id_optional(
&self,
merchant_id: &id_type::MerchantId,
key_id: &id_type::ApiKeyId,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
self.diesel_store
.find_api_key_by_merchant_id_key_id_optional(merchant_id, key_id)
.await
}
async fn find_api_key_by_hash_optional(
&self,
hashed_api_key: storage::HashedApiKey,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
self.diesel_store
.find_api_key_by_hash_optional(hashed_api_key)
.await
}
async fn list_api_keys_by_merchant_id(
&self,
merchant_id: &id_type::MerchantId,
limit: Option<i64>,
offset: Option<i64>,
) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> {
self.diesel_store
.list_api_keys_by_merchant_id(merchant_id, limit, offset)
.await
}
}
#[async_trait::async_trait]
impl CardsInfoInterface for KafkaStore {
type Error = errors::StorageError;
async fn get_card_info(
&self,
card_iin: &str,
) -> CustomResult<Option<storage::CardInfo>, errors::StorageError> {
self.diesel_store.get_card_info(card_iin).await
}
async fn add_card_info(
&self,
data: storage::CardInfo,
) -> CustomResult<storage::CardInfo, errors::StorageError> {
self.diesel_store.add_card_info(data).await
}
async fn update_card_info(
&self,
card_iin: String,
data: storage::UpdateCardInfo,
) -> CustomResult<storage::CardInfo, errors::StorageError> {
self.diesel_store.update_card_info(card_iin, data).await
}
}
#[async_trait::async_trait]
impl ConfigInterface for KafkaStore {
type Error = errors::StorageError;
async fn insert_config(
&self,
config: storage::ConfigNew,
) -> CustomResult<storage::Config, errors::StorageError> {
self.diesel_store.insert_config(config).await
}
async fn find_config_by_key(
&self,
key: &str,
) -> CustomResult<storage::Config, errors::StorageError> {
self.diesel_store.find_config_by_key(key).await
}
async fn find_config_by_key_from_db(
&self,
key: &str,
) -> CustomResult<storage::Config, errors::StorageError> {
self.diesel_store.find_config_by_key_from_db(key).await
}
async fn update_config_in_database(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, errors::StorageError> {
self.diesel_store
.update_config_in_database(key, config_update)
.await
}
async fn update_config_by_key(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, errors::StorageError> {
self.diesel_store
.update_config_by_key(key, config_update)
.await
}
async fn delete_config_by_key(
&self,
key: &str,
) -> CustomResult<storage::Config, errors::StorageError> {
self.diesel_store.delete_config_by_key(key).await
}
async fn find_config_by_key_unwrap_or(
&self,
key: &str,
default_config: Option<String>,
) -> CustomResult<storage::Config, errors::StorageError> {
self.diesel_store
.find_config_by_key_unwrap_or(key, default_config)
.await
}
}
#[async_trait::async_trait]
impl CustomerInterface for KafkaStore {
type Error = errors::StorageError;
#[cfg(feature = "v1")]
async fn delete_customer_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_customer_by_customer_id_merchant_id(customer_id, merchant_id)
.await
}
#[cfg(feature = "v1")]
async fn find_customer_optional_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
self.diesel_store
.find_customer_optional_by_customer_id_merchant_id(
state,
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
self.diesel_store
.find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
state,
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_optional_by_merchant_id_merchant_reference_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
self.diesel_store
.find_optional_by_merchant_id_merchant_reference_id(
state,
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn update_customer_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: id_type::CustomerId,
merchant_id: id_type::MerchantId,
customer: domain::Customer,
customer_update: storage::CustomerUpdate,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.update_customer_by_customer_id_merchant_id(
state,
customer_id,
merchant_id,
customer,
customer_update,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn update_customer_by_global_id(
&self,
state: &KeyManagerState,
id: &id_type::GlobalCustomerId,
customer: domain::Customer,
customer_update: storage::CustomerUpdate,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.update_customer_by_global_id(
state,
id,
customer,
customer_update,
key_store,
storage_scheme,
)
.await
}
async fn list_customers_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
constraints: super::customers::CustomerListConstraints,
) -> CustomResult<Vec<domain::Customer>, errors::StorageError> {
self.diesel_store
.list_customers_by_merchant_id(state, merchant_id, key_store, constraints)
.await
}
async fn list_customers_by_merchant_id_with_count(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
constraints: super::customers::CustomerListConstraints,
) -> CustomResult<(Vec<domain::Customer>, usize), errors::StorageError> {
self.diesel_store
.list_customers_by_merchant_id_with_count(state, merchant_id, key_store, constraints)
.await
}
#[cfg(feature = "v1")]
async fn find_customer_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.find_customer_by_customer_id_merchant_id(
state,
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_customer_by_merchant_reference_id_merchant_id(
&self,
state: &KeyManagerState,
merchant_reference_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.find_customer_by_merchant_reference_id_merchant_id(
state,
merchant_reference_id,
merchant_id,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_customer_by_global_id(
&self,
state: &KeyManagerState,
id: &id_type::GlobalCustomerId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.find_customer_by_global_id(state, id, key_store, storage_scheme)
.await
}
async fn insert_customer(
&self,
customer_data: domain::Customer,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.insert_customer(customer_data, state, key_store, storage_scheme)
.await
}
}
#[async_trait::async_trait]
impl DisputeInterface for KafkaStore {
async fn insert_dispute(
&self,
dispute_new: storage::DisputeNew,
) -> CustomResult<storage::Dispute, errors::StorageError> {
let dispute = self.diesel_store.insert_dispute(dispute_new).await?;
if let Err(er) = self
.kafka_producer
.log_dispute(&dispute, None, self.tenant_id.clone())
.await
{
logger::error!(message="Failed to add analytics entry for Dispute {dispute:?}", error_message=?er);
};
Ok(dispute)
}
async fn find_by_merchant_id_payment_id_connector_dispute_id(
&self,
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
connector_dispute_id: &str,
) -> CustomResult<Option<storage::Dispute>, errors::StorageError> {
self.diesel_store
.find_by_merchant_id_payment_id_connector_dispute_id(
merchant_id,
payment_id,
connector_dispute_id,
)
.await
}
async fn find_dispute_by_merchant_id_dispute_id(
&self,
merchant_id: &id_type::MerchantId,
dispute_id: &str,
) -> CustomResult<storage::Dispute, errors::StorageError> {
self.diesel_store
.find_dispute_by_merchant_id_dispute_id(merchant_id, dispute_id)
.await
}
async fn find_disputes_by_constraints(
&self,
merchant_id: &id_type::MerchantId,
dispute_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
self.diesel_store
.find_disputes_by_constraints(merchant_id, dispute_constraints)
.await
}
async fn update_dispute(
&self,
this: storage::Dispute,
dispute: storage::DisputeUpdate,
) -> CustomResult<storage::Dispute, errors::StorageError> {
let dispute_new = self
.diesel_store
.update_dispute(this.clone(), dispute)
.await?;
if let Err(er) = self
.kafka_producer
.log_dispute(&dispute_new, Some(this), self.tenant_id.clone())
.await
{
logger::error!(message="Failed to add analytics entry for Dispute {dispute_new:?}", error_message=?er);
};
Ok(dispute_new)
}
async fn find_disputes_by_merchant_id_payment_id(
&self,
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
self.diesel_store
.find_disputes_by_merchant_id_payment_id(merchant_id, payment_id)
.await
}
async fn get_dispute_status_with_count(
&self,
merchant_id: &id_type::MerchantId,
profile_id_list: Option<Vec<id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> {
self.diesel_store
.get_dispute_status_with_count(merchant_id, profile_id_list, time_range)
.await
}
}
#[async_trait::async_trait]
impl EphemeralKeyInterface for KafkaStore {
#[cfg(feature = "v1")]
async fn create_ephemeral_key(
&self,
ek: EphemeralKeyNew,
validity: i64,
) -> CustomResult<EphemeralKey, errors::StorageError> {
self.diesel_store.create_ephemeral_key(ek, validity).await
}
#[cfg(feature = "v1")]
async fn get_ephemeral_key(
&self,
key: &str,
) -> CustomResult<EphemeralKey, errors::StorageError> {
self.diesel_store.get_ephemeral_key(key).await
}
#[cfg(feature = "v1")]
async fn delete_ephemeral_key(
&self,
id: &str,
) -> CustomResult<EphemeralKey, errors::StorageError> {
self.diesel_store.delete_ephemeral_key(id).await
}
}
#[async_trait::async_trait]
impl ClientSecretInterface for KafkaStore {
#[cfg(feature = "v2")]
async fn create_client_secret(
&self,
ek: ClientSecretTypeNew,
validity: i64,
) -> CustomResult<ClientSecretType, errors::StorageError> {
self.diesel_store.create_client_secret(ek, validity).await
}
#[cfg(feature = "v2")]
async fn get_client_secret(
&self,
key: &str,
) -> CustomResult<ClientSecretType, errors::StorageError> {
self.diesel_store.get_client_secret(key).await
}
#[cfg(feature = "v2")]
async fn delete_client_secret(
&self,
id: &str,
) -> CustomResult<ClientSecretType, errors::StorageError> {
self.diesel_store.delete_client_secret(id).await
}
}
#[async_trait::async_trait]
impl EventInterface for KafkaStore {
async fn insert_event(
&self,
state: &KeyManagerState,
event: domain::Event,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
self.diesel_store
.insert_event(state, event, merchant_key_store)
.await
}
async fn find_event_by_merchant_id_event_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
self.diesel_store
.find_event_by_merchant_id_event_id(state, merchant_id, event_id, merchant_key_store)
.await
}
async fn find_event_by_merchant_id_idempotent_event_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
idempotent_event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
self.diesel_store
.find_event_by_merchant_id_idempotent_event_id(
state,
merchant_id,
idempotent_event_id,
merchant_key_store,
)
.await
}
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
self.diesel_store
.list_initial_events_by_merchant_id_primary_object_id(
state,
merchant_id,
primary_object_id,
merchant_key_store,
)
.await
}
async fn list_initial_events_by_merchant_id_constraints(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
created_after: PrimitiveDateTime,
created_before: PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
self.diesel_store
.list_initial_events_by_merchant_id_constraints(
state,
merchant_id,
created_after,
created_before,
limit,
offset,
event_types,
is_delivered,
merchant_key_store,
)
.await
}
async fn list_events_by_merchant_id_initial_attempt_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
self.diesel_store
.list_events_by_merchant_id_initial_attempt_id(
state,
merchant_id,
initial_attempt_id,
merchant_key_store,
)
.await
}
async fn list_initial_events_by_profile_id_primary_object_id(
&self,
state: &KeyManagerState,
profile_id: &id_type::ProfileId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
self.diesel_store
.list_initial_events_by_profile_id_primary_object_id(
state,
profile_id,
primary_object_id,
merchant_key_store,
)
.await
}
async fn list_initial_events_by_profile_id_constraints(
&self,
state: &KeyManagerState,
profile_id: &id_type::ProfileId,
created_after: PrimitiveDateTime,
created_before: PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
self.diesel_store
.list_initial_events_by_profile_id_constraints(
state,
profile_id,
created_after,
created_before,
limit,
offset,
event_types,
is_delivered,
merchant_key_store,
)
.await
}
async fn update_event_by_merchant_id_event_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
event_id: &str,
event: domain::EventUpdate,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
self.diesel_store
.update_event_by_merchant_id_event_id(
state,
merchant_id,
event_id,
event,
merchant_key_store,
)
.await
}
async fn count_initial_events_by_constraints(
&self,
merchant_id: &id_type::MerchantId,
profile_id: Option<id_type::ProfileId>,
created_after: PrimitiveDateTime,
created_before: PrimitiveDateTime,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> CustomResult<i64, errors::StorageError> {
self.diesel_store
.count_initial_events_by_constraints(
merchant_id,
profile_id,
created_after,
created_before,
event_types,
is_delivered,
)
.await
}
}
#[async_trait::async_trait]
impl LockerMockUpInterface for KafkaStore {
async fn find_locker_by_card_id(
&self,
card_id: &str,
) -> CustomResult<storage::LockerMockUp, errors::StorageError> {
self.diesel_store.find_locker_by_card_id(card_id).await
}
async fn insert_locker_mock_up(
&self,
new: storage::LockerMockUpNew,
) -> CustomResult<storage::LockerMockUp, errors::StorageError> {
self.diesel_store.insert_locker_mock_up(new).await
}
async fn delete_locker_mock_up(
&self,
card_id: &str,
) -> CustomResult<storage::LockerMockUp, errors::StorageError> {
self.diesel_store.delete_locker_mock_up(card_id).await
}
}
#[async_trait::async_trait]
impl MandateInterface for KafkaStore {
async fn find_mandate_by_merchant_id_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Mandate, errors::StorageError> {
self.diesel_store
.find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id, storage_scheme)
.await
}
async fn find_mandate_by_merchant_id_connector_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
connector_mandate_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Mandate, errors::StorageError> {
self.diesel_store
.find_mandate_by_merchant_id_connector_mandate_id(
merchant_id,
connector_mandate_id,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_mandate_by_global_customer_id(
&self,
id: &id_type::GlobalCustomerId,
) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> {
self.diesel_store
.find_mandate_by_global_customer_id(id)
.await
}
async fn find_mandate_by_merchant_id_customer_id(
&self,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> {
self.diesel_store
.find_mandate_by_merchant_id_customer_id(merchant_id, customer_id)
.await
}
async fn update_mandate_by_merchant_id_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_id: &str,
mandate_update: storage::MandateUpdate,
mandate: storage::Mandate,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Mandate, errors::StorageError> {
self.diesel_store
.update_mandate_by_merchant_id_mandate_id(
merchant_id,
mandate_id,
mandate_update,
mandate,
storage_scheme,
)
.await
}
async fn find_mandates_by_merchant_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> {
self.diesel_store
.find_mandates_by_merchant_id(merchant_id, mandate_constraints)
.await
}
async fn insert_mandate(
&self,
mandate: storage::MandateNew,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Mandate, errors::StorageError> {
self.diesel_store
.insert_mandate(mandate, storage_scheme)
.await
}
}
#[async_trait::async_trait]
impl PaymentLinkInterface for KafkaStore {
async fn find_payment_link_by_payment_link_id(
&self,
payment_link_id: &str,
) -> CustomResult<storage::PaymentLink, errors::StorageError> {
self.diesel_store
.find_payment_link_by_payment_link_id(payment_link_id)
.await
}
async fn insert_payment_link(
&self,
payment_link_object: storage::PaymentLinkNew,
) -> CustomResult<storage::PaymentLink, errors::StorageError> {
self.diesel_store
.insert_payment_link(payment_link_object)
.await
}
async fn list_payment_link_by_merchant_id(
&self,
merchant_id: &id_type::MerchantId,
payment_link_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> {
self.diesel_store
.list_payment_link_by_merchant_id(merchant_id, payment_link_constraints)
.await
}
}
#[async_trait::async_trait]
impl MerchantAccountInterface for KafkaStore {
type Error = errors::StorageError;
async fn insert_merchant(
&self,
state: &KeyManagerState,
merchant_account: domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
self.diesel_store
.insert_merchant(state, merchant_account, key_store)
.await
}
async fn find_merchant_account_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
self.diesel_store
.find_merchant_account_by_merchant_id(state, merchant_id, key_store)
.await
}
async fn update_merchant(
&self,
state: &KeyManagerState,
this: domain::MerchantAccount,
merchant_account: storage::MerchantAccountUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
self.diesel_store
.update_merchant(state, this, merchant_account, key_store)
.await
}
async fn update_specific_fields_in_merchant(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
merchant_account: storage::MerchantAccountUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
self.diesel_store
.update_specific_fields_in_merchant(state, merchant_id, merchant_account, key_store)
.await
}
async fn update_all_merchant_account(
&self,
merchant_account: storage::MerchantAccountUpdate,
) -> CustomResult<usize, errors::StorageError> {
self.diesel_store
.update_all_merchant_account(merchant_account)
.await
}
async fn find_merchant_account_by_publishable_key(
&self,
state: &KeyManagerState,
publishable_key: &str,
) -> CustomResult<(domain::MerchantAccount, domain::MerchantKeyStore), errors::StorageError>
{
self.diesel_store
.find_merchant_account_by_publishable_key(state, publishable_key)
.await
}
#[cfg(feature = "olap")]
async fn list_merchant_accounts_by_organization_id(
&self,
state: &KeyManagerState,
organization_id: &id_type::OrganizationId,
) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> {
self.diesel_store
.list_merchant_accounts_by_organization_id(state, organization_id)
.await
}
async fn delete_merchant_account_by_merchant_id(
&self,
merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_merchant_account_by_merchant_id(merchant_id)
.await
}
#[cfg(feature = "olap")]
async fn list_multiple_merchant_accounts(
&self,
state: &KeyManagerState,
merchant_ids: Vec<id_type::MerchantId>,
) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> {
self.diesel_store
.list_multiple_merchant_accounts(state, merchant_ids)
.await
}
#[cfg(feature = "olap")]
async fn list_merchant_and_org_ids(
&self,
state: &KeyManagerState,
limit: u32,
offset: Option<u32>,
) -> CustomResult<Vec<(id_type::MerchantId, id_type::OrganizationId)>, errors::StorageError>
{
self.diesel_store
.list_merchant_and_org_ids(state, limit, offset)
.await
}
}
#[async_trait::async_trait]
impl ConnectorAccessToken for KafkaStore {
async fn get_access_token(
&self,
merchant_id: &id_type::MerchantId,
merchant_connector_id: &str,
) -> CustomResult<Option<AccessToken>, errors::StorageError> {
self.diesel_store
.get_access_token(merchant_id, merchant_connector_id)
.await
}
async fn set_access_token(
&self,
merchant_id: &id_type::MerchantId,
merchant_connector_id: &str,
access_token: AccessToken,
) -> CustomResult<(), errors::StorageError> {
self.diesel_store
.set_access_token(merchant_id, merchant_connector_id, access_token)
.await
}
}
#[async_trait::async_trait]
impl FileMetadataInterface for KafkaStore {
async fn insert_file_metadata(
&self,
file: storage::FileMetadataNew,
) -> CustomResult<storage::FileMetadata, errors::StorageError> {
self.diesel_store.insert_file_metadata(file).await
}
async fn find_file_metadata_by_merchant_id_file_id(
&self,
merchant_id: &id_type::MerchantId,
file_id: &str,
) -> CustomResult<storage::FileMetadata, errors::StorageError> {
self.diesel_store
.find_file_metadata_by_merchant_id_file_id(merchant_id, file_id)
.await
}
async fn delete_file_metadata_by_merchant_id_file_id(
&self,
merchant_id: &id_type::MerchantId,
file_id: &str,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_file_metadata_by_merchant_id_file_id(merchant_id, file_id)
.await
}
async fn update_file_metadata(
&self,
this: storage::FileMetadata,
file_metadata: storage::FileMetadataUpdate,
) -> CustomResult<storage::FileMetadata, errors::StorageError> {
self.diesel_store
.update_file_metadata(this, file_metadata)
.await
}
}
#[async_trait::async_trait]
impl MerchantConnectorAccountInterface for KafkaStore {
type Error = errors::StorageError;
async fn update_multiple_merchant_connector_accounts(
&self,
merchant_connector_accounts: Vec<(
domain::MerchantConnectorAccount,
storage::MerchantConnectorAccountUpdateInternal,
)>,
) -> CustomResult<(), errors::StorageError> {
self.diesel_store
.update_multiple_merchant_connector_accounts(merchant_connector_accounts)
.await
}
#[cfg(feature = "v1")]
async fn find_merchant_connector_account_by_merchant_id_connector_label(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
connector: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
self.diesel_store
.find_merchant_connector_account_by_merchant_id_connector_label(
state,
merchant_id,
connector,
key_store,
)
.await
}
#[cfg(feature = "v1")]
async fn find_merchant_connector_account_by_merchant_id_connector_name(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
connector_name: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> {
self.diesel_store
.find_merchant_connector_account_by_merchant_id_connector_name(
state,
merchant_id,
connector_name,
key_store,
)
.await
}
#[cfg(feature = "v1")]
async fn find_merchant_connector_account_by_profile_id_connector_name(
&self,
state: &KeyManagerState,
profile_id: &id_type::ProfileId,
connector_name: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
self.diesel_store
.find_merchant_connector_account_by_profile_id_connector_name(
state,
profile_id,
connector_name,
key_store,
)
.await
}
async fn list_enabled_connector_accounts_by_profile_id(
&self,
state: &KeyManagerState,
profile_id: &id_type::ProfileId,
key_store: &domain::MerchantKeyStore,
connector_type: common_enums::ConnectorType,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> {
self.diesel_store
.list_enabled_connector_accounts_by_profile_id(
state,
profile_id,
key_store,
connector_type,
)
.await
}
async fn insert_merchant_connector_account(
&self,
state: &KeyManagerState,
t: domain::MerchantConnectorAccount,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
self.diesel_store
.insert_merchant_connector_account(state, t, key_store)
.await
}
#[cfg(feature = "v1")]
async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
merchant_connector_id: &id_type::MerchantConnectorAccountId,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
self.diesel_store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
state,
merchant_id,
merchant_connector_id,
key_store,
)
.await
}
#[cfg(feature = "v2")]
async fn find_merchant_connector_account_by_id(
&self,
state: &KeyManagerState,
id: &id_type::MerchantConnectorAccountId,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
self.diesel_store
.find_merchant_connector_account_by_id(state, id, key_store)
.await
}
async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
get_disabled: bool,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccounts, errors::StorageError> {
self.diesel_store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
state,
merchant_id,
get_disabled,
key_store,
)
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
async fn list_connector_account_by_profile_id(
&self,
state: &KeyManagerState,
profile_id: &id_type::ProfileId,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> {
self.diesel_store
.list_connector_account_by_profile_id(state, profile_id, key_store)
.await
}
async fn update_merchant_connector_account(
&self,
state: &KeyManagerState,
this: domain::MerchantConnectorAccount,
merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
self.diesel_store
.update_merchant_connector_account(state, this, merchant_connector_account, key_store)
.await
}
#[cfg(feature = "v1")]
async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
&self,
merchant_id: &id_type::MerchantId,
merchant_connector_id: &id_type::MerchantConnectorAccountId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
merchant_id,
merchant_connector_id,
)
.await
}
#[cfg(feature = "v2")]
async fn delete_merchant_connector_account_by_id(
&self,
id: &id_type::MerchantConnectorAccountId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_merchant_connector_account_by_id(id)
.await
}
}
#[async_trait::async_trait]
impl QueueInterface for KafkaStore {
async fn fetch_consumer_tasks(
&self,
stream_name: &str,
group_name: &str,
consumer_name: &str,
) -> CustomResult<Vec<storage::ProcessTracker>, ProcessTrackerError> {
self.diesel_store
.fetch_consumer_tasks(stream_name, group_name, consumer_name)
.await
}
async fn consumer_group_create(
&self,
stream: &str,
group: &str,
id: &RedisEntryId,
) -> CustomResult<(), RedisError> {
self.diesel_store
.consumer_group_create(stream, group, id)
.await
}
async fn acquire_pt_lock(
&self,
tag: &str,
lock_key: &str,
lock_val: &str,
ttl: i64,
) -> CustomResult<bool, RedisError> {
self.diesel_store
.acquire_pt_lock(tag, lock_key, lock_val, ttl)
.await
}
async fn release_pt_lock(&self, tag: &str, lock_key: &str) -> CustomResult<bool, RedisError> {
self.diesel_store.release_pt_lock(tag, lock_key).await
}
async fn stream_append_entry(
&self,
stream: &str,
entry_id: &RedisEntryId,
fields: Vec<(&str, String)>,
) -> CustomResult<(), RedisError> {
self.diesel_store
.stream_append_entry(stream, entry_id, fields)
.await
}
async fn get_key(&self, key: &str) -> CustomResult<Vec<u8>, RedisError> {
self.diesel_store.get_key(key).await
}
}
#[async_trait::async_trait]
impl PaymentAttemptInterface for KafkaStore {
type Error = errors::StorageError;
#[cfg(feature = "v1")]
async fn insert_payment_attempt(
&self,
payment_attempt: storage::PaymentAttemptNew,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
let attempt = self
.diesel_store
.insert_payment_attempt(payment_attempt, storage_scheme)
.await?;
if let Err(er) = self
.kafka_producer
.log_payment_attempt(&attempt, None, self.tenant_id.clone())
.await
{
logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er)
}
Ok(attempt)
}
#[cfg(feature = "v2")]
async fn insert_payment_attempt(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
payment_attempt: storage::PaymentAttempt,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
let attempt = self
.diesel_store
.insert_payment_attempt(
key_manager_state,
merchant_key_store,
payment_attempt,
storage_scheme,
)
.await?;
if let Err(er) = self
.kafka_producer
.log_payment_attempt(&attempt, None, self.tenant_id.clone())
.await
{
logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er)
}
Ok(attempt)
}
#[cfg(feature = "v1")]
async fn update_payment_attempt_with_attempt_id(
&self,
this: storage::PaymentAttempt,
payment_attempt: storage::PaymentAttemptUpdate,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
let mut attempt = self
.diesel_store
.update_payment_attempt_with_attempt_id(
this.clone(),
payment_attempt.clone(),
storage_scheme,
)
.await?;
let debit_routing_savings = payment_attempt.get_debit_routing_savings();
attempt.set_debit_routing_savings(debit_routing_savings);
if let Err(er) = self
.kafka_producer
.log_payment_attempt(&attempt, Some(this), self.tenant_id.clone())
.await
{
logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er)
}
Ok(attempt)
}
#[cfg(feature = "v2")]
async fn update_payment_attempt(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
this: storage::PaymentAttempt,
payment_attempt: storage::PaymentAttemptUpdate,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
let attempt = self
.diesel_store
.update_payment_attempt(
key_manager_state,
merchant_key_store,
this.clone(),
payment_attempt,
storage_scheme,
)
.await?;
if let Err(er) = self
.kafka_producer
.log_payment_attempt(&attempt, Some(this), self.tenant_id.clone())
.await
{
logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er)
}
Ok(attempt)
}
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
&self,
connector_transaction_id: &common_utils::types::ConnectorTransactionId,
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
connector_transaction_id,
payment_id,
merchant_id,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_merchant_id_connector_txn_id(
&self,
merchant_id: &id_type::MerchantId,
connector_txn_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
.find_payment_attempt_by_merchant_id_connector_txn_id(
merchant_id,
connector_txn_id,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_attempt_by_profile_id_connector_transaction_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
profile_id: &id_type::ProfileId,
connector_transaction_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
.find_payment_attempt_by_profile_id_connector_transaction_id(
key_manager_state,
merchant_key_store,
profile_id,
connector_transaction_id,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&self,
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
attempt_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
payment_id,
merchant_id,
attempt_id,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_attempt_id_merchant_id(
&self,
attempt_id: &str,
merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
.find_payment_attempt_by_attempt_id_merchant_id(attempt_id, merchant_id, storage_scheme)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_attempt_by_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
attempt_id: &id_type::GlobalAttemptId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
.find_payment_attempt_by_id(
key_manager_state,
merchant_key_store,
attempt_id,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_attempts_by_payment_intent_id(
&self,
key_manager_state: &KeyManagerState,
payment_id: &id_type::GlobalPaymentId,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<storage::PaymentAttempt>, errors::StorageError> {
self.diesel_store
.find_payment_attempts_by_payment_intent_id(
key_manager_state,
payment_id,
merchant_key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
&self,
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
.find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
payment_id,
merchant_id,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
&self,
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
.find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
payment_id,
merchant_id,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
payment_id: &id_type::GlobalPaymentId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
.find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id(
key_manager_state,
merchant_key_store,
payment_id,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_preprocessing_id_merchant_id(
&self,
preprocessing_id: &str,
merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::StorageError> {
self.diesel_store
.find_payment_attempt_by_preprocessing_id_merchant_id(
preprocessing_id,
merchant_id,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn get_filters_for_payments(
&self,
pi: &[hyperswitch_domain_models::payments::PaymentIntent],
merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<
hyperswitch_domain_models::payments::payment_attempt::PaymentListFilters,
errors::StorageError,
> {
self.diesel_store
.get_filters_for_payments(pi, merchant_id, storage_scheme)
.await
}
#[cfg(feature = "v1")]
async fn get_total_count_of_filtered_payment_attempts(
&self,
merchant_id: &id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<Vec<api_models::enums::Connector>>,
payment_method: Option<Vec<common_enums::PaymentMethod>>,
payment_method_type: Option<Vec<common_enums::PaymentMethodType>>,
authentication_type: Option<Vec<common_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
card_network: Option<Vec<common_enums::CardNetwork>>,
card_discovery: Option<Vec<common_enums::CardDiscovery>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
self.diesel_store
.get_total_count_of_filtered_payment_attempts(
merchant_id,
active_attempt_ids,
connector,
payment_method,
payment_method_type,
authentication_type,
merchant_connector_id,
card_network,
card_discovery,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn get_total_count_of_filtered_payment_attempts(
&self,
merchant_id: &id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<Vec<api_models::enums::Connector>>,
payment_method_type: Option<Vec<common_enums::PaymentMethod>>,
payment_method_subtype: Option<Vec<common_enums::PaymentMethodType>>,
authentication_type: Option<Vec<common_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
card_network: Option<Vec<common_enums::CardNetwork>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
self.diesel_store
.get_total_count_of_filtered_payment_attempts(
merchant_id,
active_attempt_ids,
connector,
payment_method_type,
payment_method_subtype,
authentication_type,
merchant_connector_id,
card_network,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn find_attempts_by_merchant_id_payment_id(
&self,
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::PaymentAttempt>, errors::StorageError> {
self.diesel_store
.find_attempts_by_merchant_id_payment_id(merchant_id, payment_id, storage_scheme)
.await
}
}
#[async_trait::async_trait]
impl PaymentIntentInterface for KafkaStore {
type Error = errors::StorageError;
async fn update_payment_intent(
&self,
state: &KeyManagerState,
this: storage::PaymentIntent,
payment_intent: storage::PaymentIntentUpdate,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentIntent, errors::StorageError> {
let intent = self
.diesel_store
.update_payment_intent(
state,
this.clone(),
payment_intent.clone(),
key_store,
storage_scheme,
)
.await?;
if let Err(er) = self
.kafka_producer
.log_payment_intent(
&intent,
Some(this),
self.tenant_id.clone(),
state.add_confirm_value_in_infra_values(payment_intent.is_confirm_operation()),
)
.await
{
logger::error!(message="Failed to add analytics entry for Payment Intent {intent:?}", error_message=?er);
};
Ok(intent)
}
async fn insert_payment_intent(
&self,
state: &KeyManagerState,
new: storage::PaymentIntent,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentIntent, errors::StorageError> {
logger::debug!("Inserting PaymentIntent Via KafkaStore");
let intent = self
.diesel_store
.insert_payment_intent(state, new, key_store, storage_scheme)
.await?;
if let Err(er) = self
.kafka_producer
.log_payment_intent(
&intent,
None,
self.tenant_id.clone(),
state.infra_values.clone(),
)
.await
{
logger::error!(message="Failed to add analytics entry for Payment Intent {intent:?}", error_message=?er);
};
Ok(intent)
}
#[cfg(feature = "v1")]
async fn find_payment_intent_by_payment_id_merchant_id(
&self,
state: &KeyManagerState,
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentIntent, errors::StorageError> {
self.diesel_store
.find_payment_intent_by_payment_id_merchant_id(
state,
payment_id,
merchant_id,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_intent_by_id(
&self,
state: &KeyManagerState,
payment_id: &id_type::GlobalPaymentId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentIntent, errors::StorageError> {
self.diesel_store
.find_payment_intent_by_id(state, payment_id, key_store, storage_scheme)
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
async fn filter_payment_intent_by_constraints(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::PaymentIntent>, errors::StorageError> {
self.diesel_store
.filter_payment_intent_by_constraints(
state,
merchant_id,
filters,
key_store,
storage_scheme,
)
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
async fn filter_payment_intents_by_time_range_constraints(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
time_range: &common_utils::types::TimeRange,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::PaymentIntent>, errors::StorageError> {
self.diesel_store
.filter_payment_intents_by_time_range_constraints(
state,
merchant_id,
time_range,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "olap")]
async fn get_intent_status_with_count(
&self,
merchant_id: &id_type::MerchantId,
profile_id_list: Option<Vec<id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::StorageError> {
self.diesel_store
.get_intent_status_with_count(merchant_id, profile_id_list, time_range)
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<
Vec<(
hyperswitch_domain_models::payments::PaymentIntent,
hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
)>,
errors::StorageError,
> {
self.diesel_store
.get_filtered_payment_intents_attempt(
state,
merchant_id,
constraints,
key_store,
storage_scheme,
)
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<
Vec<(
hyperswitch_domain_models::payments::PaymentIntent,
Option<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>,
)>,
errors::StorageError,
> {
self.diesel_store
.get_filtered_payment_intents_attempt(
state,
merchant_id,
constraints,
key_store,
storage_scheme,
)
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
merchant_id: &id_type::MerchantId,
constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<String>, errors::StorageError> {
self.diesel_store
.get_filtered_active_attempt_ids_for_total_count(
merchant_id,
constraints,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_intent_by_merchant_reference_id_profile_id(
&self,
state: &KeyManagerState,
merchant_reference_id: &id_type::PaymentReferenceId,
profile_id: &id_type::ProfileId,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: &MerchantStorageScheme,
) -> error_stack::Result<hyperswitch_domain_models::payments::PaymentIntent, errors::StorageError>
{
self.diesel_store
.find_payment_intent_by_merchant_reference_id_profile_id(
state,
merchant_reference_id,
profile_id,
merchant_key_store,
storage_scheme,
)
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
merchant_id: &id_type::MerchantId,
constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<Option<String>>, errors::StorageError> {
self.diesel_store
.get_filtered_active_attempt_ids_for_total_count(
merchant_id,
constraints,
storage_scheme,
)
.await
}
}
#[async_trait::async_trait]
impl PaymentMethodInterface for KafkaStore {
type Error = errors::StorageError;
#[cfg(feature = "v1")]
async fn find_payment_method(
&self,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
payment_method_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
self.diesel_store
.find_payment_method(state, key_store, payment_method_id, storage_scheme)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_method(
&self,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
payment_method_id: &id_type::GlobalPaymentMethodId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
self.diesel_store
.find_payment_method(state, key_store, payment_method_id, storage_scheme)
.await
}
#[cfg(feature = "v1")]
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
limit: Option<i64>,
) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> {
self.diesel_store
.find_payment_method_by_customer_id_merchant_id_list(
state,
key_store,
customer_id,
merchant_id,
limit,
)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_method_list_by_global_customer_id(
&self,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
id: &id_type::GlobalCustomerId,
limit: Option<i64>,
) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> {
self.diesel_store
.find_payment_method_list_by_global_customer_id(state, key_store, id, limit)
.await
}
#[cfg(feature = "v1")]
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> {
self.diesel_store
.find_payment_method_by_customer_id_merchant_id_status(
state,
key_store,
customer_id,
merchant_id,
status,
limit,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_method_by_global_customer_id_merchant_id_status(
&self,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
customer_id: &id_type::GlobalCustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> {
self.diesel_store
.find_payment_method_by_global_customer_id_merchant_id_status(
state,
key_store,
customer_id,
merchant_id,
status,
limit,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, errors::StorageError> {
self.diesel_store
.get_payment_method_count_by_customer_id_merchant_id_status(
customer_id,
merchant_id,
status,
)
.await
}
async fn get_payment_method_count_by_merchant_id_status(
&self,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, errors::StorageError> {
self.diesel_store
.get_payment_method_count_by_merchant_id_status(merchant_id, status)
.await
}
#[cfg(feature = "v1")]
async fn find_payment_method_by_locker_id(
&self,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
locker_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
self.diesel_store
.find_payment_method_by_locker_id(state, key_store, locker_id, storage_scheme)
.await
}
async fn insert_payment_method(
&self,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
m: domain::PaymentMethod,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
self.diesel_store
.insert_payment_method(state, key_store, m, storage_scheme)
.await
}
async fn update_payment_method(
&self,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
payment_method: domain::PaymentMethod,
payment_method_update: storage::PaymentMethodUpdate,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
self.diesel_store
.update_payment_method(
state,
key_store,
payment_method,
payment_method_update,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
payment_method_id: &str,
) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
self.diesel_store
.delete_payment_method_by_merchant_id_payment_method_id(
state,
key_store,
merchant_id,
payment_method_id,
)
.await
}
#[cfg(feature = "v2")]
async fn delete_payment_method(
&self,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
payment_method: domain::PaymentMethod,
) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
self.diesel_store
.delete_payment_method(state, key_store, payment_method)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_method_by_fingerprint_id(
&self,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
fingerprint_id: &str,
) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
self.diesel_store
.find_payment_method_by_fingerprint_id(state, key_store, fingerprint_id)
.await
}
}
#[cfg(not(feature = "payouts"))]
impl PayoutAttemptInterface for KafkaStore {}
#[cfg(feature = "payouts")]
#[async_trait::async_trait]
impl PayoutAttemptInterface for KafkaStore {
type Error = errors::StorageError;
async fn find_payout_attempt_by_merchant_id_merchant_order_reference_id(
&self,
merchant_id: &id_type::MerchantId,
merchant_order_reference_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PayoutAttempt, errors::StorageError> {
self.diesel_store
.find_payout_attempt_by_merchant_id_merchant_order_reference_id(
merchant_id,
merchant_order_reference_id,
storage_scheme,
)
.await
}
async fn find_payout_attempt_by_merchant_id_payout_attempt_id(
&self,
merchant_id: &id_type::MerchantId,
payout_attempt_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PayoutAttempt, errors::StorageError> {
self.diesel_store
.find_payout_attempt_by_merchant_id_payout_attempt_id(
merchant_id,
payout_attempt_id,
storage_scheme,
)
.await
}
async fn find_payout_attempt_by_merchant_id_connector_payout_id(
&self,
merchant_id: &id_type::MerchantId,
connector_payout_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PayoutAttempt, errors::StorageError> {
self.diesel_store
.find_payout_attempt_by_merchant_id_connector_payout_id(
merchant_id,
connector_payout_id,
storage_scheme,
)
.await
}
async fn update_payout_attempt(
&self,
this: &storage::PayoutAttempt,
payout_attempt_update: storage::PayoutAttemptUpdate,
payouts: &storage::Payouts,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PayoutAttempt, errors::StorageError> {
let updated_payout_attempt = self
.diesel_store
.update_payout_attempt(this, payout_attempt_update, payouts, storage_scheme)
.await?;
if let Err(err) = self
.kafka_producer
.log_payout(
&KafkaPayout::from_storage(payouts, &updated_payout_attempt),
Some(KafkaPayout::from_storage(payouts, this)),
self.tenant_id.clone(),
)
.await
{
logger::error!(message="Failed to update analytics entry for Payouts {payouts:?}\n{updated_payout_attempt:?}", error_message=?err);
};
Ok(updated_payout_attempt)
}
async fn insert_payout_attempt(
&self,
payout_attempt: storage::PayoutAttemptNew,
payouts: &storage::Payouts,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PayoutAttempt, errors::StorageError> {
let payout_attempt_new = self
.diesel_store
.insert_payout_attempt(payout_attempt, payouts, storage_scheme)
.await?;
if let Err(err) = self
.kafka_producer
.log_payout(
&KafkaPayout::from_storage(payouts, &payout_attempt_new),
None,
self.tenant_id.clone(),
)
.await
{
logger::error!(message="Failed to add analytics entry for Payouts {payouts:?}\n{payout_attempt_new:?}", error_message=?err);
};
Ok(payout_attempt_new)
}
async fn get_filters_for_payouts(
&self,
payouts: &[hyperswitch_domain_models::payouts::payouts::Payouts],
merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<
hyperswitch_domain_models::payouts::payout_attempt::PayoutListFilters,
errors::StorageError,
> {
self.diesel_store
.get_filters_for_payouts(payouts, merchant_id, storage_scheme)
.await
}
}
#[cfg(not(feature = "payouts"))]
impl PayoutsInterface for KafkaStore {}
#[cfg(feature = "payouts")]
#[async_trait::async_trait]
impl PayoutsInterface for KafkaStore {
type Error = errors::StorageError;
async fn find_payout_by_merchant_id_payout_id(
&self,
merchant_id: &id_type::MerchantId,
payout_id: &id_type::PayoutId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Payouts, errors::StorageError> {
self.diesel_store
.find_payout_by_merchant_id_payout_id(merchant_id, payout_id, storage_scheme)
.await
}
async fn update_payout(
&self,
this: &storage::Payouts,
payout_update: storage::PayoutsUpdate,
payout_attempt: &storage::PayoutAttempt,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Payouts, errors::StorageError> {
let payout = self
.diesel_store
.update_payout(this, payout_update, payout_attempt, storage_scheme)
.await?;
if let Err(err) = self
.kafka_producer
.log_payout(
&KafkaPayout::from_storage(&payout, payout_attempt),
Some(KafkaPayout::from_storage(this, payout_attempt)),
self.tenant_id.clone(),
)
.await
{
logger::error!(message="Failed to update analytics entry for Payouts {payout:?}\n{payout_attempt:?}", error_message=?err);
};
Ok(payout)
}
async fn insert_payout(
&self,
payout: storage::PayoutsNew,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Payouts, errors::StorageError> {
self.diesel_store
.insert_payout(payout, storage_scheme)
.await
}
async fn find_optional_payout_by_merchant_id_payout_id(
&self,
merchant_id: &id_type::MerchantId,
payout_id: &id_type::PayoutId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<storage::Payouts>, errors::StorageError> {
self.diesel_store
.find_optional_payout_by_merchant_id_payout_id(merchant_id, payout_id, storage_scheme)
.await
}
#[cfg(feature = "olap")]
async fn filter_payouts_by_constraints(
&self,
merchant_id: &id_type::MerchantId,
filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::Payouts>, errors::StorageError> {
self.diesel_store
.filter_payouts_by_constraints(merchant_id, filters, storage_scheme)
.await
}
#[cfg(feature = "olap")]
async fn filter_payouts_and_attempts(
&self,
merchant_id: &id_type::MerchantId,
filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<
Vec<(
storage::Payouts,
storage::PayoutAttempt,
Option<diesel_models::Customer>,
Option<diesel_models::Address>,
)>,
errors::StorageError,
> {
self.diesel_store
.filter_payouts_and_attempts(merchant_id, filters, storage_scheme)
.await
}
#[cfg(feature = "olap")]
async fn filter_payouts_by_time_range_constraints(
&self,
merchant_id: &id_type::MerchantId,
time_range: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::Payouts>, errors::StorageError> {
self.diesel_store
.filter_payouts_by_time_range_constraints(merchant_id, time_range, storage_scheme)
.await
}
#[cfg(feature = "olap")]
async fn get_total_count_of_filtered_payouts(
&self,
merchant_id: &id_type::MerchantId,
active_payout_ids: &[id_type::PayoutId],
connector: Option<Vec<api_models::enums::PayoutConnectors>>,
currency: Option<Vec<enums::Currency>>,
status: Option<Vec<enums::PayoutStatus>>,
payout_method: Option<Vec<enums::PayoutType>>,
) -> CustomResult<i64, errors::StorageError> {
self.diesel_store
.get_total_count_of_filtered_payouts(
merchant_id,
active_payout_ids,
connector,
currency,
status,
payout_method,
)
.await
}
#[cfg(feature = "olap")]
async fn filter_active_payout_ids_by_constraints(
&self,
merchant_id: &id_type::MerchantId,
constraints: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
) -> CustomResult<Vec<id_type::PayoutId>, errors::StorageError> {
self.diesel_store
.filter_active_payout_ids_by_constraints(merchant_id, constraints)
.await
}
}
#[async_trait::async_trait]
impl ProcessTrackerInterface for KafkaStore {
async fn reinitialize_limbo_processes(
&self,
ids: Vec<String>,
schedule_time: PrimitiveDateTime,
) -> CustomResult<usize, errors::StorageError> {
self.diesel_store
.reinitialize_limbo_processes(ids, schedule_time)
.await
}
async fn find_process_by_id(
&self,
id: &str,
) -> CustomResult<Option<storage::ProcessTracker>, errors::StorageError> {
self.diesel_store.find_process_by_id(id).await
}
async fn update_process(
&self,
this: storage::ProcessTracker,
process: storage::ProcessTrackerUpdate,
) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
self.diesel_store.update_process(this, process).await
}
async fn process_tracker_update_process_status_by_ids(
&self,
task_ids: Vec<String>,
task_update: storage::ProcessTrackerUpdate,
) -> CustomResult<usize, errors::StorageError> {
self.diesel_store
.process_tracker_update_process_status_by_ids(task_ids, task_update)
.await
}
async fn insert_process(
&self,
new: storage::ProcessTrackerNew,
) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
self.diesel_store.insert_process(new).await
}
async fn reset_process(
&self,
this: storage::ProcessTracker,
schedule_time: PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError> {
self.diesel_store.reset_process(this, schedule_time).await
}
async fn retry_process(
&self,
this: storage::ProcessTracker,
schedule_time: PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError> {
self.diesel_store.retry_process(this, schedule_time).await
}
async fn finish_process_with_business_status(
&self,
this: storage::ProcessTracker,
business_status: &'static str,
) -> CustomResult<(), errors::StorageError> {
self.diesel_store
.finish_process_with_business_status(this, business_status)
.await
}
async fn find_processes_by_time_status(
&self,
time_lower_limit: PrimitiveDateTime,
time_upper_limit: PrimitiveDateTime,
status: ProcessTrackerStatus,
limit: Option<i64>,
) -> CustomResult<Vec<storage::ProcessTracker>, errors::StorageError> {
self.diesel_store
.find_processes_by_time_status(time_lower_limit, time_upper_limit, status, limit)
.await
}
}
#[async_trait::async_trait]
impl CaptureInterface for KafkaStore {
async fn insert_capture(
&self,
capture: storage::CaptureNew,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Capture, errors::StorageError> {
self.diesel_store
.insert_capture(capture, storage_scheme)
.await
}
async fn update_capture_with_capture_id(
&self,
this: storage::Capture,
capture: storage::CaptureUpdate,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Capture, errors::StorageError> {
self.diesel_store
.update_capture_with_capture_id(this, capture, storage_scheme)
.await
}
async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
&self,
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
authorized_attempt_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::Capture>, errors::StorageError> {
self.diesel_store
.find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
merchant_id,
payment_id,
authorized_attempt_id,
storage_scheme,
)
.await
}
}
#[async_trait::async_trait]
impl RefundInterface for KafkaStore {
#[cfg(feature = "v1")]
async fn find_refund_by_internal_reference_id_merchant_id(
&self,
internal_reference_id: &str,
merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
self.diesel_store
.find_refund_by_internal_reference_id_merchant_id(
internal_reference_id,
merchant_id,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn find_refund_by_payment_id_merchant_id(
&self,
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> {
self.diesel_store
.find_refund_by_payment_id_merchant_id(payment_id, merchant_id, storage_scheme)
.await
}
#[cfg(feature = "v1")]
async fn find_refund_by_merchant_id_refund_id(
&self,
merchant_id: &id_type::MerchantId,
refund_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
self.diesel_store
.find_refund_by_merchant_id_refund_id(merchant_id, refund_id, storage_scheme)
.await
}
#[cfg(feature = "v1")]
async fn find_refund_by_merchant_id_connector_refund_id_connector(
&self,
merchant_id: &id_type::MerchantId,
connector_refund_id: &str,
connector: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
self.diesel_store
.find_refund_by_merchant_id_connector_refund_id_connector(
merchant_id,
connector_refund_id,
connector,
storage_scheme,
)
.await
}
async fn update_refund(
&self,
this: diesel_refund::Refund,
refund: diesel_refund::RefundUpdate,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
let refund = self
.diesel_store
.update_refund(this.clone(), refund, storage_scheme)
.await?;
if let Err(er) = self
.kafka_producer
.log_refund(&refund, Some(this), self.tenant_id.clone())
.await
{
logger::error!(message="Failed to insert analytics event for Refund Update {refund?}", error_message=?er);
}
Ok(refund)
}
async fn find_refund_by_merchant_id_connector_transaction_id(
&self,
merchant_id: &id_type::MerchantId,
connector_transaction_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> {
self.diesel_store
.find_refund_by_merchant_id_connector_transaction_id(
merchant_id,
connector_transaction_id,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_refund_by_id(
&self,
id: &id_type::GlobalRefundId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
self.diesel_store
.find_refund_by_id(id, storage_scheme)
.await
}
async fn insert_refund(
&self,
new: diesel_refund::RefundNew,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
let refund = self.diesel_store.insert_refund(new, storage_scheme).await?;
if let Err(er) = self
.kafka_producer
.log_refund(&refund, None, self.tenant_id.clone())
.await
{
logger::error!(message="Failed to insert analytics event for Refund Create {refund?}", error_message=?er);
}
Ok(refund)
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_refund_by_constraints(
&self,
merchant_id: &id_type::MerchantId,
refund_details: &refunds::RefundListConstraints,
storage_scheme: MerchantStorageScheme,
limit: i64,
offset: i64,
) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> {
self.diesel_store
.filter_refund_by_constraints(
merchant_id,
refund_details,
storage_scheme,
limit,
offset,
)
.await
}
#[cfg(feature = "v2")]
async fn filter_refund_by_constraints(
&self,
merchant_id: &id_type::MerchantId,
refund_details: refunds::RefundListConstraints,
storage_scheme: MerchantStorageScheme,
limit: i64,
offset: i64,
) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> {
self.diesel_store
.filter_refund_by_constraints(
merchant_id,
refund_details,
storage_scheme,
limit,
offset,
)
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_refund_by_meta_constraints(
&self,
merchant_id: &id_type::MerchantId,
refund_details: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> {
self.diesel_store
.filter_refund_by_meta_constraints(merchant_id, refund_details, storage_scheme)
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_refund_status_with_count(
&self,
merchant_id: &id_type::MerchantId,
profile_id_list: Option<Vec<id_type::ProfileId>>,
constraints: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> {
self.diesel_store
.get_refund_status_with_count(merchant_id, profile_id_list, constraints, storage_scheme)
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_total_count_of_refunds(
&self,
merchant_id: &id_type::MerchantId,
refund_details: &refunds::RefundListConstraints,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
self.diesel_store
.get_total_count_of_refunds(merchant_id, refund_details, storage_scheme)
.await
}
#[cfg(feature = "v2")]
async fn get_total_count_of_refunds(
&self,
merchant_id: &id_type::MerchantId,
refund_details: refunds::RefundListConstraints,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
self.diesel_store
.get_total_count_of_refunds(merchant_id, refund_details, storage_scheme)
.await
}
}
#[async_trait::async_trait]
impl MerchantKeyStoreInterface for KafkaStore {
type Error = errors::StorageError;
async fn insert_merchant_key_store(
&self,
state: &KeyManagerState,
merchant_key_store: domain::MerchantKeyStore,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> {
self.diesel_store
.insert_merchant_key_store(state, merchant_key_store, key)
.await
}
async fn get_merchant_key_store_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> {
self.diesel_store
.get_merchant_key_store_by_merchant_id(state, merchant_id, key)
.await
}
async fn delete_merchant_key_store_by_merchant_id(
&self,
merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_merchant_key_store_by_merchant_id(merchant_id)
.await
}
#[cfg(feature = "olap")]
async fn list_multiple_key_stores(
&self,
state: &KeyManagerState,
merchant_ids: Vec<id_type::MerchantId>,
key: &Secret<Vec<u8>>,
) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> {
self.diesel_store
.list_multiple_key_stores(state, merchant_ids, key)
.await
}
async fn get_all_key_stores(
&self,
state: &KeyManagerState,
key: &Secret<Vec<u8>>,
from: u32,
to: u32,
) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> {
self.diesel_store
.get_all_key_stores(state, key, from, to)
.await
}
}
#[async_trait::async_trait]
impl ProfileInterface for KafkaStore {
type Error = errors::StorageError;
async fn insert_business_profile(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: domain::Profile,
) -> CustomResult<domain::Profile, errors::StorageError> {
self.diesel_store
.insert_business_profile(key_manager_state, merchant_key_store, business_profile)
.await
}
async fn find_business_profile_by_profile_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
profile_id: &id_type::ProfileId,
) -> CustomResult<domain::Profile, errors::StorageError> {
self.diesel_store
.find_business_profile_by_profile_id(key_manager_state, merchant_key_store, profile_id)
.await
}
async fn find_business_profile_by_merchant_id_profile_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
) -> CustomResult<domain::Profile, errors::StorageError> {
self.diesel_store
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
merchant_key_store,
merchant_id,
profile_id,
)
.await
}
async fn update_profile_by_profile_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
current_state: domain::Profile,
business_profile_update: domain::ProfileUpdate,
) -> CustomResult<domain::Profile, errors::StorageError> {
self.diesel_store
.update_profile_by_profile_id(
key_manager_state,
merchant_key_store,
current_state,
business_profile_update,
)
.await
}
async fn delete_profile_by_profile_id_merchant_id(
&self,
profile_id: &id_type::ProfileId,
merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_profile_by_profile_id_merchant_id(profile_id, merchant_id)
.await
}
async fn list_profile_by_merchant_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
) -> CustomResult<Vec<domain::Profile>, errors::StorageError> {
self.diesel_store
.list_profile_by_merchant_id(key_manager_state, merchant_key_store, merchant_id)
.await
}
async fn find_business_profile_by_profile_name_merchant_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
profile_name: &str,
merchant_id: &id_type::MerchantId,
) -> CustomResult<domain::Profile, errors::StorageError> {
self.diesel_store
.find_business_profile_by_profile_name_merchant_id(
key_manager_state,
merchant_key_store,
profile_name,
merchant_id,
)
.await
}
}
#[async_trait::async_trait]
impl ReverseLookupInterface for KafkaStore {
async fn insert_reverse_lookup(
&self,
new: ReverseLookupNew,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
self.diesel_store
.insert_reverse_lookup(new, storage_scheme)
.await
}
async fn get_lookup_by_lookup_id(
&self,
id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
self.diesel_store
.get_lookup_by_lookup_id(id, storage_scheme)
.await
}
}
#[async_trait::async_trait]
impl RoutingAlgorithmInterface for KafkaStore {
async fn insert_routing_algorithm(
&self,
routing_algorithm: storage::RoutingAlgorithm,
) -> CustomResult<storage::RoutingAlgorithm, errors::StorageError> {
self.diesel_store
.insert_routing_algorithm(routing_algorithm)
.await
}
async fn find_routing_algorithm_by_profile_id_algorithm_id(
&self,
profile_id: &id_type::ProfileId,
algorithm_id: &id_type::RoutingId,
) -> CustomResult<storage::RoutingAlgorithm, errors::StorageError> {
self.diesel_store
.find_routing_algorithm_by_profile_id_algorithm_id(profile_id, algorithm_id)
.await
}
async fn find_routing_algorithm_by_algorithm_id_merchant_id(
&self,
algorithm_id: &id_type::RoutingId,
merchant_id: &id_type::MerchantId,
) -> CustomResult<storage::RoutingAlgorithm, errors::StorageError> {
self.diesel_store
.find_routing_algorithm_by_algorithm_id_merchant_id(algorithm_id, merchant_id)
.await
}
async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id(
&self,
algorithm_id: &id_type::RoutingId,
profile_id: &id_type::ProfileId,
) -> CustomResult<storage::RoutingProfileMetadata, errors::StorageError> {
self.diesel_store
.find_routing_algorithm_metadata_by_algorithm_id_profile_id(algorithm_id, profile_id)
.await
}
async fn list_routing_algorithm_metadata_by_profile_id(
&self,
profile_id: &id_type::ProfileId,
limit: i64,
offset: i64,
) -> CustomResult<Vec<storage::RoutingProfileMetadata>, errors::StorageError> {
self.diesel_store
.list_routing_algorithm_metadata_by_profile_id(profile_id, limit, offset)
.await
}
async fn list_routing_algorithm_metadata_by_merchant_id(
&self,
merchant_id: &id_type::MerchantId,
limit: i64,
offset: i64,
) -> CustomResult<Vec<storage::RoutingProfileMetadata>, errors::StorageError> {
self.diesel_store
.list_routing_algorithm_metadata_by_merchant_id(merchant_id, limit, offset)
.await
}
async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type(
&self,
merchant_id: &id_type::MerchantId,
transaction_type: &enums::TransactionType,
limit: i64,
offset: i64,
) -> CustomResult<Vec<storage::RoutingProfileMetadata>, errors::StorageError> {
self.diesel_store
.list_routing_algorithm_metadata_by_merchant_id_transaction_type(
merchant_id,
transaction_type,
limit,
offset,
)
.await
}
}
#[async_trait::async_trait]
impl GsmInterface for KafkaStore {
async fn add_gsm_rule(
&self,
rule: hyperswitch_domain_models::gsm::GatewayStatusMap,
) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> {
self.diesel_store.add_gsm_rule(rule).await
}
async fn find_gsm_decision(
&self,
connector: String,
flow: String,
sub_flow: String,
code: String,
message: String,
) -> CustomResult<String, errors::StorageError> {
self.diesel_store
.find_gsm_decision(connector, flow, sub_flow, code, message)
.await
}
async fn find_gsm_rule(
&self,
connector: String,
flow: String,
sub_flow: String,
code: String,
message: String,
) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> {
self.diesel_store
.find_gsm_rule(connector, flow, sub_flow, code, message)
.await
}
async fn update_gsm_rule(
&self,
connector: String,
flow: String,
sub_flow: String,
code: String,
message: String,
data: hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate,
) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> {
self.diesel_store
.update_gsm_rule(connector, flow, sub_flow, code, message, data)
.await
}
async fn delete_gsm_rule(
&self,
connector: String,
flow: String,
sub_flow: String,
code: String,
message: String,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_gsm_rule(connector, flow, sub_flow, code, message)
.await
}
}
#[async_trait::async_trait]
impl UnifiedTranslationsInterface for KafkaStore {
async fn add_unfied_translation(
&self,
translation: storage::UnifiedTranslationsNew,
) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> {
self.diesel_store.add_unfied_translation(translation).await
}
async fn find_translation(
&self,
unified_code: String,
unified_message: String,
locale: String,
) -> CustomResult<String, errors::StorageError> {
self.diesel_store
.find_translation(unified_code, unified_message, locale)
.await
}
async fn update_translation(
&self,
unified_code: String,
unified_message: String,
locale: String,
data: storage::UnifiedTranslationsUpdate,
) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> {
self.diesel_store
.update_translation(unified_code, unified_message, locale, data)
.await
}
async fn delete_translation(
&self,
unified_code: String,
unified_message: String,
locale: String,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_translation(unified_code, unified_message, locale)
.await
}
}
#[async_trait::async_trait]
impl StorageInterface for KafkaStore {
fn get_scheduler_db(&self) -> Box<dyn SchedulerInterface> {
Box::new(self.clone())
}
fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface> {
Box::new(self.clone())
}
fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> {
Box::new(self.clone())
}
fn get_subscription_store(
&self,
) -> Box<dyn subscriptions::state::SubscriptionStorageInterface> {
Box::new(self.clone())
}
}
impl GlobalStorageInterface for KafkaStore {
fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> {
Box::new(self.clone())
}
}
impl AccountsStorageInterface for KafkaStore {}
impl PaymentMethodsStorageInterface for KafkaStore {}
impl subscriptions::state::SubscriptionStorageInterface for KafkaStore {}
impl CommonStorageInterface for KafkaStore {
fn get_storage_interface(&self) -> Box<dyn StorageInterface> {
Box::new(self.clone())
}
fn get_global_storage_interface(&self) -> Box<dyn GlobalStorageInterface> {
Box::new(self.clone())
}
fn get_accounts_storage_interface(&self) -> Box<dyn AccountsStorageInterface> {
Box::new(self.clone())
}
}
#[async_trait::async_trait]
impl SchedulerInterface for KafkaStore {}
impl MasterKeyInterface for KafkaStore {
fn get_master_key(&self) -> &[u8] {
self.diesel_store.get_master_key()
}
}
#[async_trait::async_trait]
impl UserInterface for KafkaStore {
async fn insert_user(
&self,
user_data: storage::UserNew,
) -> CustomResult<storage::User, errors::StorageError> {
self.diesel_store.insert_user(user_data).await
}
async fn find_user_by_email(
&self,
user_email: &domain::UserEmail,
) -> CustomResult<storage::User, errors::StorageError> {
self.diesel_store.find_user_by_email(user_email).await
}
async fn find_user_by_id(
&self,
user_id: &str,
) -> CustomResult<storage::User, errors::StorageError> {
self.diesel_store.find_user_by_id(user_id).await
}
async fn update_user_by_user_id(
&self,
user_id: &str,
user: storage::UserUpdate,
) -> CustomResult<storage::User, errors::StorageError> {
self.diesel_store
.update_user_by_user_id(user_id, user)
.await
}
async fn update_user_by_email(
&self,
user_email: &domain::UserEmail,
user: storage::UserUpdate,
) -> CustomResult<storage::User, errors::StorageError> {
self.diesel_store
.update_user_by_email(user_email, user)
.await
}
async fn delete_user_by_user_id(
&self,
user_id: &str,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store.delete_user_by_user_id(user_id).await
}
async fn find_users_by_user_ids(
&self,
user_ids: Vec<String>,
) -> CustomResult<Vec<storage::User>, errors::StorageError> {
self.diesel_store.find_users_by_user_ids(user_ids).await
}
}
impl RedisConnInterface for KafkaStore {
fn get_redis_conn(&self) -> CustomResult<Arc<RedisConnectionPool>, RedisError> {
self.diesel_store.get_redis_conn()
}
}
#[async_trait::async_trait]
impl UserRoleInterface for KafkaStore {
async fn insert_user_role(
&self,
user_role: storage::UserRoleNew,
) -> CustomResult<user_storage::UserRole, errors::StorageError> {
self.diesel_store.insert_user_role(user_role).await
}
async fn find_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
self.diesel_store
.find_user_role_by_user_id_and_lineage(
user_id,
tenant_id,
org_id,
merchant_id,
profile_id,
version,
)
.await
}
async fn update_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: Option<&id_type::MerchantId>,
profile_id: Option<&id_type::ProfileId>,
update: user_storage::UserRoleUpdate,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
self.diesel_store
.update_user_role_by_user_id_and_lineage(
user_id,
tenant_id,
org_id,
merchant_id,
profile_id,
update,
version,
)
.await
}
async fn delete_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
self.diesel_store
.delete_user_role_by_user_id_and_lineage(
user_id,
tenant_id,
org_id,
merchant_id,
profile_id,
version,
)
.await
}
async fn list_user_roles_by_user_id<'a>(
&self,
payload: ListUserRolesByUserIdPayload<'a>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
self.diesel_store.list_user_roles_by_user_id(payload).await
}
async fn list_user_roles_by_user_id_across_tenants(
&self,
user_id: &str,
limit: Option<u32>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
self.diesel_store
.list_user_roles_by_user_id_across_tenants(user_id, limit)
.await
}
async fn list_user_roles_by_org_id<'a>(
&self,
payload: ListUserRolesByOrgIdPayload<'a>,
) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> {
self.diesel_store.list_user_roles_by_org_id(payload).await
}
}
#[async_trait::async_trait]
impl DashboardMetadataInterface for KafkaStore {
async fn insert_metadata(
&self,
metadata: storage::DashboardMetadataNew,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {
self.diesel_store.insert_metadata(metadata).await
}
async fn update_metadata(
&self,
user_id: Option<String>,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
data_key: enums::DashboardMetadata,
dashboard_metadata_update: storage::DashboardMetadataUpdate,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {
self.diesel_store
.update_metadata(
user_id,
merchant_id,
org_id,
data_key,
dashboard_metadata_update,
)
.await
}
async fn find_user_scoped_dashboard_metadata(
&self,
user_id: &str,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> {
self.diesel_store
.find_user_scoped_dashboard_metadata(user_id, merchant_id, org_id, data_keys)
.await
}
async fn find_merchant_scoped_dashboard_metadata(
&self,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> {
self.diesel_store
.find_merchant_scoped_dashboard_metadata(merchant_id, org_id, data_keys)
.await
}
async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(
&self,
user_id: &str,
merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_all_user_scoped_dashboard_metadata_by_merchant_id(user_id, merchant_id)
.await
}
async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
&self,
user_id: &str,
merchant_id: &id_type::MerchantId,
data_key: enums::DashboardMetadata,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {
self.diesel_store
.delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
user_id,
merchant_id,
data_key,
)
.await
}
}
#[async_trait::async_trait]
impl BatchSampleDataInterface for KafkaStore {
#[cfg(feature = "v1")]
async fn insert_payment_intents_batch_for_sample_data(
&self,
state: &KeyManagerState,
batch: Vec<hyperswitch_domain_models::payments::PaymentIntent>,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
) -> CustomResult<
Vec<hyperswitch_domain_models::payments::PaymentIntent>,
storage_impl::errors::StorageError,
> {
let payment_intents_list = self
.diesel_store
.insert_payment_intents_batch_for_sample_data(state, batch, key_store)
.await?;
for payment_intent in payment_intents_list.iter() {
let _ = self
.kafka_producer
.log_payment_intent(
payment_intent,
None,
self.tenant_id.clone(),
state.infra_values.clone(),
)
.await;
}
Ok(payment_intents_list)
}
#[cfg(feature = "v1")]
async fn insert_payment_attempts_batch_for_sample_data(
&self,
batch: Vec<diesel_models::user::sample_data::PaymentAttemptBatchNew>,
) -> CustomResult<
Vec<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>,
storage_impl::errors::StorageError,
> {
let payment_attempts_list = self
.diesel_store
.insert_payment_attempts_batch_for_sample_data(batch)
.await?;
for payment_attempt in payment_attempts_list.iter() {
let _ = self
.kafka_producer
.log_payment_attempt(payment_attempt, None, self.tenant_id.clone())
.await;
}
Ok(payment_attempts_list)
}
#[cfg(feature = "v1")]
async fn insert_refunds_batch_for_sample_data(
&self,
batch: Vec<diesel_models::RefundNew>,
) -> CustomResult<Vec<diesel_models::Refund>, storage_impl::errors::StorageError> {
let refunds_list = self
.diesel_store
.insert_refunds_batch_for_sample_data(batch)
.await?;
for refund in refunds_list.iter() {
let _ = self
.kafka_producer
.log_refund(refund, None, self.tenant_id.clone())
.await;
}
Ok(refunds_list)
}
#[cfg(feature = "v1")]
async fn insert_disputes_batch_for_sample_data(
&self,
batch: Vec<diesel_models::DisputeNew>,
) -> CustomResult<Vec<diesel_models::Dispute>, storage_impl::errors::StorageError> {
let disputes_list = self
.diesel_store
.insert_disputes_batch_for_sample_data(batch)
.await?;
for dispute in disputes_list.iter() {
let _ = self
.kafka_producer
.log_dispute(dispute, None, self.tenant_id.clone())
.await;
}
Ok(disputes_list)
}
#[cfg(feature = "v1")]
async fn delete_payment_intents_for_sample_data(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
) -> CustomResult<
Vec<hyperswitch_domain_models::payments::PaymentIntent>,
storage_impl::errors::StorageError,
> {
let payment_intents_list = self
.diesel_store
.delete_payment_intents_for_sample_data(state, merchant_id, key_store)
.await?;
for payment_intent in payment_intents_list.iter() {
let _ = self
.kafka_producer
.log_payment_intent_delete(
payment_intent,
self.tenant_id.clone(),
state.infra_values.clone(),
)
.await;
}
Ok(payment_intents_list)
}
#[cfg(feature = "v1")]
async fn delete_payment_attempts_for_sample_data(
&self,
merchant_id: &id_type::MerchantId,
) -> CustomResult<
Vec<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>,
storage_impl::errors::StorageError,
> {
let payment_attempts_list = self
.diesel_store
.delete_payment_attempts_for_sample_data(merchant_id)
.await?;
for payment_attempt in payment_attempts_list.iter() {
let _ = self
.kafka_producer
.log_payment_attempt_delete(payment_attempt, self.tenant_id.clone())
.await;
}
Ok(payment_attempts_list)
}
#[cfg(feature = "v1")]
async fn delete_refunds_for_sample_data(
&self,
merchant_id: &id_type::MerchantId,
) -> CustomResult<Vec<diesel_models::Refund>, storage_impl::errors::StorageError> {
let refunds_list = self
.diesel_store
.delete_refunds_for_sample_data(merchant_id)
.await?;
for refund in refunds_list.iter() {
let _ = self
.kafka_producer
.log_refund_delete(refund, self.tenant_id.clone())
.await;
}
Ok(refunds_list)
}
#[cfg(feature = "v1")]
async fn delete_disputes_for_sample_data(
&self,
merchant_id: &id_type::MerchantId,
) -> CustomResult<Vec<diesel_models::Dispute>, storage_impl::errors::StorageError> {
let disputes_list = self
.diesel_store
.delete_disputes_for_sample_data(merchant_id)
.await?;
for dispute in disputes_list.iter() {
let _ = self
.kafka_producer
.log_dispute_delete(dispute, self.tenant_id.clone())
.await;
}
Ok(disputes_list)
}
}
#[async_trait::async_trait]
impl AuthorizationInterface for KafkaStore {
async fn insert_authorization(
&self,
authorization: storage::AuthorizationNew,
) -> CustomResult<storage::Authorization, errors::StorageError> {
self.diesel_store.insert_authorization(authorization).await
}
async fn find_all_authorizations_by_merchant_id_payment_id(
&self,
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> {
self.diesel_store
.find_all_authorizations_by_merchant_id_payment_id(merchant_id, payment_id)
.await
}
async fn update_authorization_by_merchant_id_authorization_id(
&self,
merchant_id: id_type::MerchantId,
authorization_id: String,
authorization: storage::AuthorizationUpdate,
) -> CustomResult<storage::Authorization, errors::StorageError> {
self.diesel_store
.update_authorization_by_merchant_id_authorization_id(
merchant_id,
authorization_id,
authorization,
)
.await
}
}
#[async_trait::async_trait]
impl AuthenticationInterface for KafkaStore {
async fn insert_authentication(
&self,
authentication: storage::AuthenticationNew,
) -> CustomResult<storage::Authentication, errors::StorageError> {
let auth = self
.diesel_store
.insert_authentication(authentication)
.await?;
if let Err(er) = self
.kafka_producer
.log_authentication(&auth, None, self.tenant_id.clone())
.await
{
logger::error!(message="Failed to log analytics event for authentication {auth:?}", error_message=?er)
}
Ok(auth)
}
async fn find_authentication_by_merchant_id_authentication_id(
&self,
merchant_id: &id_type::MerchantId,
authentication_id: &id_type::AuthenticationId,
) -> CustomResult<storage::Authentication, errors::StorageError> {
self.diesel_store
.find_authentication_by_merchant_id_authentication_id(merchant_id, authentication_id)
.await
}
async fn find_authentication_by_merchant_id_connector_authentication_id(
&self,
merchant_id: id_type::MerchantId,
connector_authentication_id: String,
) -> CustomResult<storage::Authentication, errors::StorageError> {
self.diesel_store
.find_authentication_by_merchant_id_connector_authentication_id(
merchant_id,
connector_authentication_id,
)
.await
}
async fn update_authentication_by_merchant_id_authentication_id(
&self,
previous_state: storage::Authentication,
authentication_update: storage::AuthenticationUpdate,
) -> CustomResult<storage::Authentication, errors::StorageError> {
let auth = self
.diesel_store
.update_authentication_by_merchant_id_authentication_id(
previous_state.clone(),
authentication_update,
)
.await?;
if let Err(er) = self
.kafka_producer
.log_authentication(&auth, Some(previous_state.clone()), self.tenant_id.clone())
.await
{
logger::error!(message="Failed to log analytics event for authentication {auth:?}", error_message=?er)
}
Ok(auth)
}
}
#[async_trait::async_trait]
impl HealthCheckDbInterface for KafkaStore {
async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> {
self.diesel_store.health_check_db().await
}
}
#[async_trait::async_trait]
impl RoleInterface for KafkaStore {
async fn insert_role(
&self,
role: storage::RoleNew,
) -> CustomResult<storage::Role, errors::StorageError> {
self.diesel_store.insert_role(role).await
}
async fn find_role_by_role_id(
&self,
role_id: &str,
) -> CustomResult<storage::Role, errors::StorageError> {
self.diesel_store.find_role_by_role_id(role_id).await
}
async fn find_role_by_role_id_in_lineage(
&self,
role_id: &str,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
profile_id: &id_type::ProfileId,
tenant_id: &id_type::TenantId,
) -> CustomResult<storage::Role, errors::StorageError> {
self.diesel_store
.find_role_by_role_id_in_lineage(role_id, merchant_id, org_id, profile_id, tenant_id)
.await
}
async fn find_by_role_id_org_id_tenant_id(
&self,
role_id: &str,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
) -> CustomResult<storage::Role, errors::StorageError> {
self.diesel_store
.find_by_role_id_org_id_tenant_id(role_id, org_id, tenant_id)
.await
}
async fn update_role_by_role_id(
&self,
role_id: &str,
role_update: storage::RoleUpdate,
) -> CustomResult<storage::Role, errors::StorageError> {
self.diesel_store
.update_role_by_role_id(role_id, role_update)
.await
}
async fn delete_role_by_role_id(
&self,
role_id: &str,
) -> CustomResult<storage::Role, errors::StorageError> {
self.diesel_store.delete_role_by_role_id(role_id).await
}
//TODO: Remove once generic_list_roles_by_entity_type is stable
async fn list_roles_for_org_by_parameters(
&self,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: Option<&id_type::MerchantId>,
entity_type: Option<enums::EntityType>,
limit: Option<u32>,
) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
self.diesel_store
.list_roles_for_org_by_parameters(tenant_id, org_id, merchant_id, entity_type, limit)
.await
}
async fn generic_list_roles_by_entity_type(
&self,
payload: diesel_models::role::ListRolesByEntityPayload,
is_lineage_data_required: bool,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
self.diesel_store
.generic_list_roles_by_entity_type(payload, is_lineage_data_required, tenant_id, org_id)
.await
}
}
#[async_trait::async_trait]
impl GenericLinkInterface for KafkaStore {
async fn find_generic_link_by_link_id(
&self,
link_id: &str,
) -> CustomResult<storage::GenericLinkState, errors::StorageError> {
self.diesel_store
.find_generic_link_by_link_id(link_id)
.await
}
async fn find_pm_collect_link_by_link_id(
&self,
link_id: &str,
) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> {
self.diesel_store
.find_pm_collect_link_by_link_id(link_id)
.await
}
async fn find_payout_link_by_link_id(
&self,
link_id: &str,
) -> CustomResult<storage::PayoutLink, errors::StorageError> {
self.diesel_store.find_payout_link_by_link_id(link_id).await
}
async fn insert_generic_link(
&self,
generic_link: storage::GenericLinkNew,
) -> CustomResult<storage::GenericLinkState, errors::StorageError> {
self.diesel_store.insert_generic_link(generic_link).await
}
async fn insert_pm_collect_link(
&self,
pm_collect_link: storage::GenericLinkNew,
) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> {
self.diesel_store
.insert_pm_collect_link(pm_collect_link)
.await
}
async fn insert_payout_link(
&self,
pm_collect_link: storage::GenericLinkNew,
) -> CustomResult<storage::PayoutLink, errors::StorageError> {
self.diesel_store.insert_payout_link(pm_collect_link).await
}
async fn update_payout_link(
&self,
payout_link: storage::PayoutLink,
payout_link_update: storage::PayoutLinkUpdate,
) -> CustomResult<storage::PayoutLink, errors::StorageError> {
self.diesel_store
.update_payout_link(payout_link, payout_link_update)
.await
}
}
#[async_trait::async_trait]
impl UserKeyStoreInterface for KafkaStore {
async fn insert_user_key_store(
&self,
state: &KeyManagerState,
user_key_store: domain::UserKeyStore,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
self.diesel_store
.insert_user_key_store(state, user_key_store, key)
.await
}
async fn get_user_key_store_by_user_id(
&self,
state: &KeyManagerState,
user_id: &str,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
self.diesel_store
.get_user_key_store_by_user_id(state, user_id, key)
.await
}
async fn get_all_user_key_store(
&self,
state: &KeyManagerState,
key: &Secret<Vec<u8>>,
from: u32,
limit: u32,
) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> {
self.diesel_store
.get_all_user_key_store(state, key, from, limit)
.await
}
}
#[async_trait::async_trait]
impl UserAuthenticationMethodInterface for KafkaStore {
async fn insert_user_authentication_method(
&self,
user_authentication_method: storage::UserAuthenticationMethodNew,
) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> {
self.diesel_store
.insert_user_authentication_method(user_authentication_method)
.await
}
async fn get_user_authentication_method_by_id(
&self,
id: &str,
) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> {
self.diesel_store
.get_user_authentication_method_by_id(id)
.await
}
async fn list_user_authentication_methods_for_auth_id(
&self,
auth_id: &str,
) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> {
self.diesel_store
.list_user_authentication_methods_for_auth_id(auth_id)
.await
}
async fn list_user_authentication_methods_for_owner_id(
&self,
owner_id: &str,
) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> {
self.diesel_store
.list_user_authentication_methods_for_owner_id(owner_id)
.await
}
async fn update_user_authentication_method(
&self,
id: &str,
user_authentication_method_update: storage::UserAuthenticationMethodUpdate,
) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> {
self.diesel_store
.update_user_authentication_method(id, user_authentication_method_update)
.await
}
async fn list_user_authentication_methods_for_email_domain(
&self,
email_domain: &str,
) -> CustomResult<
Vec<diesel_models::user_authentication_method::UserAuthenticationMethod>,
errors::StorageError,
> {
self.diesel_store
.list_user_authentication_methods_for_email_domain(email_domain)
.await
}
}
#[async_trait::async_trait]
impl HyperswitchAiInteractionInterface for KafkaStore {
async fn insert_hyperswitch_ai_interaction(
&self,
hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew,
) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError> {
self.diesel_store
.insert_hyperswitch_ai_interaction(hyperswitch_ai_interaction)
.await
}
async fn list_hyperswitch_ai_interactions(
&self,
merchant_id: Option<id_type::MerchantId>,
limit: i64,
offset: i64,
) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError> {
self.diesel_store
.list_hyperswitch_ai_interactions(merchant_id, limit, offset)
.await
}
}
#[async_trait::async_trait]
impl ThemeInterface for KafkaStore {
async fn insert_theme(
&self,
theme: storage::theme::ThemeNew,
) -> CustomResult<storage::theme::Theme, errors::StorageError> {
self.diesel_store.insert_theme(theme).await
}
async fn find_theme_by_theme_id(
&self,
theme_id: String,
) -> CustomResult<storage::theme::Theme, errors::StorageError> {
self.diesel_store.find_theme_by_theme_id(theme_id).await
}
async fn find_most_specific_theme_in_lineage(
&self,
lineage: ThemeLineage,
) -> CustomResult<diesel_models::user::theme::Theme, errors::StorageError> {
self.diesel_store
.find_most_specific_theme_in_lineage(lineage)
.await
}
async fn find_theme_by_lineage(
&self,
lineage: ThemeLineage,
) -> CustomResult<storage::theme::Theme, errors::StorageError> {
self.diesel_store.find_theme_by_lineage(lineage).await
}
async fn update_theme_by_theme_id(
&self,
theme_id: String,
theme_update: diesel_models::user::theme::ThemeUpdate,
) -> CustomResult<diesel_models::user::theme::Theme, errors::StorageError> {
self.diesel_store
.update_theme_by_theme_id(theme_id, theme_update)
.await
}
async fn delete_theme_by_theme_id(
&self,
theme_id: String,
) -> CustomResult<storage::theme::Theme, errors::StorageError> {
self.diesel_store.delete_theme_by_theme_id(theme_id).await
}
async fn list_themes_at_and_under_lineage(
&self,
lineage: ThemeLineage,
) -> CustomResult<Vec<storage::theme::Theme>, errors::StorageError> {
self.diesel_store
.list_themes_at_and_under_lineage(lineage)
.await
}
}
#[async_trait::async_trait]
#[cfg(feature = "v2")]
impl db::payment_method_session::PaymentMethodsSessionInterface for KafkaStore {
async fn insert_payment_methods_session(
&self,
state: &KeyManagerState,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession,
validity: i64,
) -> CustomResult<(), errors::StorageError> {
self.diesel_store
.insert_payment_methods_session(state, key_store, payment_methods_session, validity)
.await
}
async fn get_payment_methods_session(
&self,
state: &KeyManagerState,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
id: &id_type::GlobalPaymentMethodSessionId,
) -> CustomResult<
hyperswitch_domain_models::payment_methods::PaymentMethodSession,
errors::StorageError,
> {
self.diesel_store
.get_payment_methods_session(state, key_store, id)
.await
}
async fn update_payment_method_session(
&self,
state: &KeyManagerState,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
id: &id_type::GlobalPaymentMethodSessionId,
payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum,
current_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession,
) -> CustomResult<
hyperswitch_domain_models::payment_methods::PaymentMethodSession,
errors::StorageError,
> {
self.diesel_store
.update_payment_method_session(
state,
key_store,
id,
payment_methods_session,
current_session,
)
.await
}
}
#[async_trait::async_trait]
#[cfg(feature = "v1")]
impl db::payment_method_session::PaymentMethodsSessionInterface for KafkaStore {}
#[async_trait::async_trait]
impl CallbackMapperInterface for KafkaStore {
#[instrument(skip_all)]
async fn insert_call_back_mapper(
&self,
call_back_mapper: domain::CallbackMapper,
) -> CustomResult<domain::CallbackMapper, errors::StorageError> {
self.diesel_store
.insert_call_back_mapper(call_back_mapper)
.await
}
#[instrument(skip_all)]
async fn find_call_back_mapper_by_id(
&self,
id: &str,
) -> CustomResult<domain::CallbackMapper, errors::StorageError> {
self.diesel_store.find_call_back_mapper_by_id(id).await
}
}
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[async_trait::async_trait]
impl TokenizationInterface for KafkaStore {
async fn insert_tokenization(
&self,
tokenization: hyperswitch_domain_models::tokenization::Tokenization,
merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
key_manager_state: &KeyManagerState,
) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>
{
self.diesel_store
.insert_tokenization(tokenization, merchant_key_store, key_manager_state)
.await
}
async fn get_entity_id_vault_id_by_token_id(
&self,
token: &id_type::GlobalTokenId,
merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
key_manager_state: &KeyManagerState,
) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>
{
self.diesel_store
.get_entity_id_vault_id_by_token_id(token, merchant_key_store, key_manager_state)
.await
}
async fn update_tokenization_record(
&self,
tokenization: hyperswitch_domain_models::tokenization::Tokenization,
tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate,
merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
key_manager_state: &KeyManagerState,
) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>
{
self.diesel_store
.update_tokenization_record(
tokenization,
tokenization_update,
merchant_key_store,
key_manager_state,
)
.await
}
}
#[cfg(not(all(feature = "v2", feature = "tokenization_v2")))]
impl TokenizationInterface for KafkaStore {}
#[async_trait::async_trait]
impl InvoiceInterface for KafkaStore {
type Error = errors::StorageError;
#[instrument(skip_all)]
async fn insert_invoice_entry(
&self,
state: &KeyManagerState,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
invoice_new: DomainInvoice,
) -> CustomResult<DomainInvoice, errors::StorageError> {
self.diesel_store
.insert_invoice_entry(state, key_store, invoice_new)
.await
}
#[instrument(skip_all)]
async fn find_invoice_by_invoice_id(
&self,
state: &KeyManagerState,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
invoice_id: String,
) -> CustomResult<DomainInvoice, errors::StorageError> {
self.diesel_store
.find_invoice_by_invoice_id(state, key_store, invoice_id)
.await
}
#[instrument(skip_all)]
async fn update_invoice_entry(
&self,
state: &KeyManagerState,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
invoice_id: String,
data: DomainInvoiceUpdate,
) -> CustomResult<DomainInvoice, errors::StorageError> {
self.diesel_store
.update_invoice_entry(state, key_store, invoice_id, data)
.await
}
#[instrument(skip_all)]
async fn get_latest_invoice_for_subscription(
&self,
state: &KeyManagerState,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
subscription_id: String,
) -> CustomResult<DomainInvoice, errors::StorageError> {
self.diesel_store
.get_latest_invoice_for_subscription(state, key_store, subscription_id)
.await
}
#[instrument(skip_all)]
async fn find_invoice_by_subscription_id_connector_invoice_id(
&self,
state: &KeyManagerState,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
subscription_id: String,
connector_invoice_id: id_type::InvoiceId,
) -> CustomResult<Option<DomainInvoice>, errors::StorageError> {
self.diesel_store
.find_invoice_by_subscription_id_connector_invoice_id(
state,
key_store,
subscription_id,
connector_invoice_id,
)
.await
}
}
#[async_trait::async_trait]
impl SubscriptionInterface for KafkaStore {
type Error = errors::StorageError;
#[instrument(skip_all)]
async fn insert_subscription_entry(
&self,
state: &KeyManagerState,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
subscription_new: DomainSubscription,
) -> CustomResult<DomainSubscription, errors::StorageError> {
self.diesel_store
.insert_subscription_entry(state, key_store, subscription_new)
.await
}
#[instrument(skip_all)]
async fn find_by_merchant_id_subscription_id(
&self,
state: &KeyManagerState,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
subscription_id: String,
) -> CustomResult<DomainSubscription, errors::StorageError> {
self.diesel_store
.find_by_merchant_id_subscription_id(state, key_store, merchant_id, subscription_id)
.await
}
#[instrument(skip_all)]
async fn update_subscription_entry(
&self,
state: &KeyManagerState,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
subscription_id: String,
data: DomainSubscriptionUpdate,
) -> CustomResult<DomainSubscription, errors::StorageError> {
self.diesel_store
.update_subscription_entry(state, key_store, merchant_id, subscription_id, data)
.await
}
}
| {
"crate": "router",
"file": "crates/router/src/db/kafka_store.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-1672325090655338995 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/events/outgoing_webhook_logs.rs
// Contains: 1 structs, 1 enums
use api_models::{enums::EventType as OutgoingWebhookEventType, webhooks::OutgoingWebhookContent};
use common_enums::WebhookDeliveryAttempt;
use serde::Serialize;
use serde_json::Value;
use time::OffsetDateTime;
use super::EventType;
use crate::services::kafka::KafkaMessage;
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct OutgoingWebhookEvent {
tenant_id: common_utils::id_type::TenantId,
merchant_id: common_utils::id_type::MerchantId,
event_id: String,
event_type: OutgoingWebhookEventType,
#[serde(flatten)]
content: Option<OutgoingWebhookEventContent>,
is_error: bool,
error: Option<Value>,
created_at_timestamp: i128,
initial_attempt_id: Option<String>,
status_code: Option<u16>,
delivery_attempt: Option<WebhookDeliveryAttempt>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "outgoing_webhook_event_type", rename_all = "snake_case")]
pub enum OutgoingWebhookEventContent {
#[cfg(feature = "v1")]
Payment {
payment_id: common_utils::id_type::PaymentId,
content: Value,
},
#[cfg(feature = "v2")]
Payment {
payment_id: common_utils::id_type::GlobalPaymentId,
content: Value,
},
Payout {
payout_id: common_utils::id_type::PayoutId,
content: Value,
},
#[cfg(feature = "v1")]
Refund {
payment_id: common_utils::id_type::PaymentId,
refund_id: String,
content: Value,
},
#[cfg(feature = "v2")]
Refund {
payment_id: common_utils::id_type::GlobalPaymentId,
refund_id: common_utils::id_type::GlobalRefundId,
content: Value,
},
#[cfg(feature = "v1")]
Dispute {
payment_id: common_utils::id_type::PaymentId,
attempt_id: String,
dispute_id: String,
content: Value,
},
#[cfg(feature = "v2")]
Dispute {
payment_id: common_utils::id_type::GlobalPaymentId,
attempt_id: String,
dispute_id: String,
content: Value,
},
Mandate {
payment_method_id: String,
mandate_id: String,
content: Value,
},
}
pub trait OutgoingWebhookEventMetric {
fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent>;
}
#[cfg(feature = "v1")]
impl OutgoingWebhookEventMetric for OutgoingWebhookContent {
fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent> {
match self {
Self::PaymentDetails(payment_payload) => Some(OutgoingWebhookEventContent::Payment {
payment_id: payment_payload.payment_id.clone(),
content: masking::masked_serialize(&payment_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::RefundDetails(refund_payload) => Some(OutgoingWebhookEventContent::Refund {
payment_id: refund_payload.payment_id.clone(),
refund_id: refund_payload.get_refund_id_as_string(),
content: masking::masked_serialize(&refund_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::DisputeDetails(dispute_payload) => Some(OutgoingWebhookEventContent::Dispute {
payment_id: dispute_payload.payment_id.clone(),
attempt_id: dispute_payload.attempt_id.clone(),
dispute_id: dispute_payload.dispute_id.clone(),
content: masking::masked_serialize(&dispute_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::MandateDetails(mandate_payload) => Some(OutgoingWebhookEventContent::Mandate {
payment_method_id: mandate_payload.payment_method_id.clone(),
mandate_id: mandate_payload.mandate_id.clone(),
content: masking::masked_serialize(&mandate_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
#[cfg(feature = "payouts")]
Self::PayoutDetails(payout_payload) => Some(OutgoingWebhookEventContent::Payout {
payout_id: payout_payload.payout_id.clone(),
content: masking::masked_serialize(&payout_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
}
}
}
#[cfg(feature = "v2")]
impl OutgoingWebhookEventMetric for OutgoingWebhookContent {
fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent> {
match self {
Self::PaymentDetails(payment_payload) => Some(OutgoingWebhookEventContent::Payment {
payment_id: payment_payload.id.clone(),
content: masking::masked_serialize(&payment_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::RefundDetails(refund_payload) => Some(OutgoingWebhookEventContent::Refund {
payment_id: refund_payload.payment_id.clone(),
refund_id: refund_payload.id.clone(),
content: masking::masked_serialize(&refund_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::DisputeDetails(dispute_payload) => {
//TODO: add support for dispute outgoing webhook
todo!()
}
Self::MandateDetails(mandate_payload) => Some(OutgoingWebhookEventContent::Mandate {
payment_method_id: mandate_payload.payment_method_id.clone(),
mandate_id: mandate_payload.mandate_id.clone(),
content: masking::masked_serialize(&mandate_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
#[cfg(feature = "payouts")]
Self::PayoutDetails(payout_payload) => Some(OutgoingWebhookEventContent::Payout {
payout_id: payout_payload.payout_id.clone(),
content: masking::masked_serialize(&payout_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
}
}
}
impl OutgoingWebhookEvent {
#[allow(clippy::too_many_arguments)]
pub fn new(
tenant_id: common_utils::id_type::TenantId,
merchant_id: common_utils::id_type::MerchantId,
event_id: String,
event_type: OutgoingWebhookEventType,
content: Option<OutgoingWebhookEventContent>,
error: Option<Value>,
initial_attempt_id: Option<String>,
status_code: Option<u16>,
delivery_attempt: Option<WebhookDeliveryAttempt>,
) -> Self {
Self {
tenant_id,
merchant_id,
event_id,
event_type,
content,
is_error: error.is_some(),
error,
created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,
initial_attempt_id,
status_code,
delivery_attempt,
}
}
}
impl KafkaMessage for OutgoingWebhookEvent {
fn event_type(&self) -> EventType {
EventType::OutgoingWebhookLogs
}
fn key(&self) -> String {
self.event_id.clone()
}
}
| {
"crate": "router",
"file": "crates/router/src/events/outgoing_webhook_logs.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_2338477899707745687 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/events/api_logs.rs
// Contains: 1 structs, 0 enums
use actix_web::HttpRequest;
pub use common_utils::events::{ApiEventMetric, ApiEventsType};
use common_utils::impl_api_event_type;
use router_env::{tracing_actix_web::RequestId, types::FlowMetric};
use serde::Serialize;
use time::OffsetDateTime;
use super::EventType;
#[cfg(feature = "dummy_connector")]
use crate::routes::dummy_connector::types::{
DummyConnectorPaymentCompleteRequest, DummyConnectorPaymentConfirmRequest,
DummyConnectorPaymentRequest, DummyConnectorPaymentResponse,
DummyConnectorPaymentRetrieveRequest, DummyConnectorRefundRequest,
DummyConnectorRefundResponse, DummyConnectorRefundRetrieveRequest,
};
use crate::{
core::payments::PaymentsRedirectResponseData,
services::{authentication::AuthenticationType, kafka::KafkaMessage},
types::api::{
AttachEvidenceRequest, Config, ConfigUpdate, CreateFileRequest, DisputeFetchQueryData,
DisputeId, FileId, FileRetrieveRequest, PollId,
},
};
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct ApiEvent {
tenant_id: common_utils::id_type::TenantId,
merchant_id: Option<common_utils::id_type::MerchantId>,
api_flow: String,
created_at_timestamp: i128,
request_id: String,
latency: u128,
status_code: i64,
#[serde(flatten)]
auth_type: AuthenticationType,
request: String,
user_agent: Option<String>,
ip_addr: Option<String>,
url_path: String,
response: Option<String>,
error: Option<serde_json::Value>,
#[serde(flatten)]
event_type: ApiEventsType,
hs_latency: Option<u128>,
http_method: String,
#[serde(flatten)]
infra_components: Option<serde_json::Value>,
}
impl ApiEvent {
#[allow(clippy::too_many_arguments)]
pub fn new(
tenant_id: common_utils::id_type::TenantId,
merchant_id: Option<common_utils::id_type::MerchantId>,
api_flow: &impl FlowMetric,
request_id: &RequestId,
latency: u128,
status_code: i64,
request: serde_json::Value,
response: Option<serde_json::Value>,
hs_latency: Option<u128>,
auth_type: AuthenticationType,
error: Option<serde_json::Value>,
event_type: ApiEventsType,
http_req: &HttpRequest,
http_method: &http::Method,
infra_components: Option<serde_json::Value>,
) -> Self {
Self {
tenant_id,
merchant_id,
api_flow: api_flow.to_string(),
created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,
request_id: request_id.as_hyphenated().to_string(),
latency,
status_code,
request: request.to_string(),
response: response.map(|resp| resp.to_string()),
auth_type,
error,
ip_addr: http_req
.connection_info()
.realip_remote_addr()
.map(ToOwned::to_owned),
user_agent: http_req
.headers()
.get("user-agent")
.and_then(|user_agent_value| user_agent_value.to_str().ok().map(ToOwned::to_owned)),
url_path: http_req.path().to_string(),
event_type,
hs_latency,
http_method: http_method.to_string(),
infra_components,
}
}
}
impl KafkaMessage for ApiEvent {
fn event_type(&self) -> EventType {
EventType::ApiLogs
}
fn key(&self) -> String {
self.request_id.clone()
}
}
impl_api_event_type!(
Miscellaneous,
(
Config,
CreateFileRequest,
FileId,
FileRetrieveRequest,
AttachEvidenceRequest,
DisputeFetchQueryData,
ConfigUpdate
)
);
#[cfg(feature = "dummy_connector")]
impl_api_event_type!(
Miscellaneous,
(
DummyConnectorPaymentCompleteRequest,
DummyConnectorPaymentRequest,
DummyConnectorPaymentResponse,
DummyConnectorPaymentRetrieveRequest,
DummyConnectorPaymentConfirmRequest,
DummyConnectorRefundRetrieveRequest,
DummyConnectorRefundResponse,
DummyConnectorRefundRequest
)
);
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsRedirectResponseData {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentRedirectionResponse {
connector: self.connector.clone(),
payment_id: match &self.resource_id {
api_models::payments::PaymentIdType::PaymentIntentId(id) => Some(id.clone()),
_ => None,
},
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentsRedirectResponseData {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentRedirectionResponse {
payment_id: self.payment_id.clone(),
})
}
}
impl ApiEventMetric for DisputeId {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Dispute {
dispute_id: self.dispute_id.clone(),
})
}
}
impl ApiEventMetric for PollId {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Poll {
poll_id: self.poll_id.clone(),
})
}
}
| {
"crate": "router",
"file": "crates/router/src/events/api_logs.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-4790762968591139000 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/events/audit_events.rs
// Contains: 1 structs, 1 enums
use api_models::payments::Amount;
use common_utils::types::MinorUnit;
use diesel_models::fraud_check::FraudCheck;
use events::{Event, EventInfo};
use serde::Serialize;
use time::PrimitiveDateTime;
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "event_type")]
pub enum AuditEventType {
Error {
error_message: String,
},
PaymentCreated,
ConnectorDecided,
ConnectorCalled,
RefundCreated,
RefundSuccess,
RefundFail,
PaymentConfirm {
client_src: Option<String>,
client_ver: Option<String>,
frm_message: Box<Option<FraudCheck>>,
},
PaymentCancelled {
cancellation_reason: Option<String>,
},
PaymentCapture {
capture_amount: Option<MinorUnit>,
multiple_capture_count: Option<i16>,
},
PaymentUpdate {
amount: Amount,
},
PaymentApprove,
PaymentCreate,
PaymentStatus,
PaymentCompleteAuthorize,
PaymentReject {
error_code: Option<String>,
error_message: Option<String>,
},
}
#[derive(Debug, Clone, Serialize)]
pub struct AuditEvent {
#[serde(flatten)]
event_type: AuditEventType,
#[serde(with = "common_utils::custom_serde::iso8601")]
created_at: PrimitiveDateTime,
}
impl AuditEvent {
pub fn new(event_type: AuditEventType) -> Self {
Self {
event_type,
created_at: common_utils::date_time::now(),
}
}
}
impl Event for AuditEvent {
type EventType = super::EventType;
fn timestamp(&self) -> PrimitiveDateTime {
self.created_at
}
fn identifier(&self) -> String {
let event_type = match &self.event_type {
AuditEventType::Error { .. } => "error",
AuditEventType::PaymentCreated => "payment_created",
AuditEventType::PaymentConfirm { .. } => "payment_confirm",
AuditEventType::ConnectorDecided => "connector_decided",
AuditEventType::ConnectorCalled => "connector_called",
AuditEventType::PaymentCapture { .. } => "payment_capture",
AuditEventType::RefundCreated => "refund_created",
AuditEventType::RefundSuccess => "refund_success",
AuditEventType::RefundFail => "refund_fail",
AuditEventType::PaymentCancelled { .. } => "payment_cancelled",
AuditEventType::PaymentUpdate { .. } => "payment_update",
AuditEventType::PaymentApprove => "payment_approve",
AuditEventType::PaymentCreate => "payment_create",
AuditEventType::PaymentStatus => "payment_status",
AuditEventType::PaymentCompleteAuthorize => "payment_complete_authorize",
AuditEventType::PaymentReject { .. } => "payment_rejected",
};
format!(
"{event_type}-{}",
self.timestamp().assume_utc().unix_timestamp_nanos()
)
}
fn class(&self) -> Self::EventType {
super::EventType::AuditEvent
}
}
impl EventInfo for AuditEvent {
type Data = Self;
fn data(&self) -> error_stack::Result<Self::Data, events::EventsError> {
Ok(self.clone())
}
fn key(&self) -> String {
"event".to_string()
}
}
| {
"crate": "router",
"file": "crates/router/src/events/audit_events.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-6141988151262387940 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/events/event_logger.rs
// Contains: 1 structs, 0 enums
use std::collections::HashMap;
use events::{EventsError, Message, MessagingInterface};
use masking::ErasedMaskSerialize;
use time::PrimitiveDateTime;
use super::EventType;
use crate::services::{kafka::KafkaMessage, logger};
#[derive(Clone, Debug, Default)]
pub struct EventLogger {}
impl EventLogger {
#[track_caller]
pub(super) fn log_event<T: KafkaMessage>(&self, event: &T) {
logger::info!(event = ?event.masked_serialize().unwrap_or_else(|e| serde_json::json!({"error": e.to_string()})), event_type =? event.event_type(), event_id =? event.key(), log_type =? "event");
}
}
impl MessagingInterface for EventLogger {
type MessageClass = EventType;
fn send_message<T>(
&self,
data: T,
metadata: HashMap<String, String>,
_timestamp: PrimitiveDateTime,
) -> error_stack::Result<(), EventsError>
where
T: Message<Class = Self::MessageClass> + ErasedMaskSerialize,
{
logger::info!(event =? data.masked_serialize().unwrap_or_else(|e| serde_json::json!({"error": e.to_string()})), event_type =? data.get_message_class(), event_id =? data.identifier(), log_type =? "event", metadata = ?metadata);
Ok(())
}
}
| {
"crate": "router",
"file": "crates/router/src/events/event_logger.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-9146544046283768386 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/routes/payment_methods.rs
// Contains: 3 structs, 0 enums
use ::payment_methods::{
controller::PaymentMethodsController,
core::{migration, migration::payment_methods::migrate_payment_method},
};
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpRequest, HttpResponse};
use common_utils::{errors::CustomResult, id_type, transformers::ForeignFrom};
use diesel_models::enums::IntentStatus;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
bulk_tokenization::CardNetworkTokenizeRequest, merchant_key_store::MerchantKeyStore,
payment_methods::PaymentMethodCustomerMigrate, transformers::ForeignTryFrom,
};
use router_env::{instrument, logger, tracing, Flow};
use super::app::{AppState, SessionState};
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
use crate::core::{customers, payment_methods::tokenize};
use crate::{
core::{
api_locking,
errors::{self, utils::StorageErrorExt},
payment_methods::{self as payment_methods_routes, cards, migration as update_migration},
},
services::{self, api, authentication as auth, authorization::permissions::Permission},
types::{
api::payment_methods::{self, PaymentMethodId},
domain,
storage::payment_method::PaymentTokenData,
},
};
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
pub async fn create_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCreate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| async move {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
Box::pin(cards::get_client_secret_or_add_payment_method(
&state,
req,
&merchant_context,
))
.await
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
pub async fn create_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCreate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, req_state| async move {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
Box::pin(payment_methods_routes::create_payment_method(
&state,
&req_state,
req,
&merchant_context,
&auth.profile,
))
.await
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
pub async fn create_payment_method_intent_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodIntentCreate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| async move {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
Box::pin(payment_methods_routes::payment_method_intent_create(
&state,
req,
&merchant_context,
))
.await
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
/// This struct is used internally only
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct PaymentMethodIntentConfirmInternal {
pub id: id_type::GlobalPaymentMethodId,
pub request: payment_methods::PaymentMethodIntentConfirm,
}
#[cfg(feature = "v2")]
impl From<PaymentMethodIntentConfirmInternal> for payment_methods::PaymentMethodIntentConfirm {
fn from(item: PaymentMethodIntentConfirmInternal) -> Self {
item.request
}
}
#[cfg(feature = "v2")]
impl common_utils::events::ApiEventMetric for PaymentMethodIntentConfirmInternal {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::PaymentMethod {
payment_method_id: self.id.clone(),
payment_method_type: Some(self.request.payment_method_type),
payment_method_subtype: Some(self.request.payment_method_subtype),
})
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))]
pub async fn payment_method_update_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodId>,
json_payload: web::Json<payment_methods::PaymentMethodUpdate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsUpdate;
let payment_method_id = path.into_inner();
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::update_payment_method(
state,
merchant_context,
auth.profile,
req,
&payment_method_id,
)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsRetrieve))]
pub async fn payment_method_retrieve_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsRetrieve;
let payload = web::Json(PaymentMethodId {
payment_method_id: path.into_inner(),
})
.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, pm, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::retrieve_payment_method(state, pm, merchant_context)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsDelete))]
pub async fn payment_method_delete_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsDelete;
let payload = web::Json(PaymentMethodId {
payment_method_id: path.into_inner(),
})
.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, pm, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::delete_payment_method(state, pm, merchant_context, auth.profile)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))]
pub async fn migrate_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodMigrate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsMigrate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| async move {
let merchant_id = req.merchant_id.clone();
let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(merchant_account, key_store),
));
Box::pin(migrate_payment_method(
&(&state).into(),
req,
&merchant_id,
&merchant_context,
&cards::PmCards {
state: &state,
merchant_context: &merchant_context,
},
))
.await
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
async fn get_merchant_account(
state: &SessionState,
merchant_id: &id_type::MerchantId,
) -> CustomResult<(MerchantKeyStore, domain::MerchantAccount), errors::ApiErrorResponse> {
let key_manager_state = &state.into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
Ok((key_store, merchant_account))
}
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))]
pub async fn migrate_payment_methods(
state: web::Data<AppState>,
req: HttpRequest,
MultipartForm(form): MultipartForm<migration::PaymentMethodsMigrateForm>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsMigrate;
let (merchant_id, records, merchant_connector_ids) =
match form.validate_and_get_payment_method_records() {
Ok((merchant_id, records, merchant_connector_ids)) => {
(merchant_id, records, merchant_connector_ids)
}
Err(e) => return api::log_and_return_error_response(e.into()),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
records,
|state, _, req, _| {
let merchant_id = merchant_id.clone();
let merchant_connector_ids = merchant_connector_ids.clone();
async move {
let (key_store, merchant_account) =
get_merchant_account(&state, &merchant_id).await?;
// Create customers if they are not already present
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(merchant_account.clone(), key_store.clone()),
));
let mut mca_cache = std::collections::HashMap::new();
let customers = Vec::<PaymentMethodCustomerMigrate>::foreign_try_from((
&req,
merchant_id.clone(),
))
.map_err(|e| errors::ApiErrorResponse::InvalidRequestData {
message: e.to_string(),
})?;
for record in &customers {
if let Some(connector_customer_details) = &record.connector_customer_details {
for connector_customer in connector_customer_details {
if !mca_cache.contains_key(&connector_customer.merchant_connector_id) {
let mca = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&(&state).into(),
&merchant_id,
&connector_customer.merchant_connector_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_customer.merchant_connector_id.get_string_repr().to_string(),
},
)?;
mca_cache
.insert(connector_customer.merchant_connector_id.clone(), mca);
}
}
}
}
customers::migrate_customers(state.clone(), customers, merchant_context.clone())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let controller = cards::PmCards {
state: &state,
merchant_context: &merchant_context,
};
Box::pin(migration::migrate_payment_methods(
&(&state).into(),
req,
&merchant_id,
&merchant_context,
merchant_connector_ids,
&controller,
))
.await
}
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsBatchUpdate))]
pub async fn update_payment_methods(
state: web::Data<AppState>,
req: HttpRequest,
MultipartForm(form): MultipartForm<update_migration::PaymentMethodsUpdateForm>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsBatchUpdate;
let (merchant_id, records) = match form.validate_and_get_payment_method_records() {
Ok((merchant_id, records)) => (merchant_id, records),
Err(e) => return api::log_and_return_error_response(e.into()),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
records,
|state, _, req, _| {
let merchant_id = merchant_id.clone();
async move {
let (key_store, merchant_account) =
get_merchant_account(&state, &merchant_id).await?;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(merchant_account.clone(), key_store.clone()),
));
Box::pin(update_migration::update_payment_methods(
&state,
req,
&merchant_id,
&merchant_context,
))
.await
}
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSave))]
pub async fn save_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCreate>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSave;
let payload = json_payload.into_inner();
let pm_id = path.into_inner();
let api_auth = auth::ApiKeyAuth::default();
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth)
{
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
Box::pin(cards::add_payment_method_data(
state,
req,
merchant_context,
pm_id.clone(),
))
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))]
pub async fn list_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Query<payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsList;
let payload = json_payload.into_inner();
let api_auth = auth::ApiKeyAuth::default();
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth)
{
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
// TODO (#7195): Fill platform_merchant_account in the client secret auth and pass it here.
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
cards::list_payment_methods(state, merchant_context, req)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// List payment methods for a Customer
///
/// To filter and list the applicable payment methods for a particular Customer ID
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_api(
state: web::Data<AppState>,
customer_id: web::Path<(id_type::CustomerId,)>,
req: HttpRequest,
query_payload: web::Query<payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
let flow = Flow::CustomerPaymentMethodsList;
let payload = query_payload.into_inner();
let customer_id = customer_id.into_inner().0;
let api_auth = auth::ApiKeyAuth::default();
let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
cards::do_list_customer_pm_fetch_customer_if_not_passed(
state,
merchant_context,
Some(req),
Some(&customer_id),
None,
)
},
&*ephemeral_auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// List payment methods for a Customer
///
/// To filter and list the applicable payment methods for a particular Customer ID
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_api_client(
state: web::Data<AppState>,
req: HttpRequest,
query_payload: web::Query<payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
let flow = Flow::CustomerPaymentMethodsList;
let payload = query_payload.into_inner();
let api_key = auth::get_api_key(req.headers()).ok();
let api_auth = auth::ApiKeyAuth::default();
let (auth, _, is_ephemeral_auth) =
match auth::get_ephemeral_or_other_auth(req.headers(), false, Some(&payload), api_auth)
.await
{
Ok((auth, _auth_flow, is_ephemeral_auth)) => (auth, _auth_flow, is_ephemeral_auth),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
cards::do_list_customer_pm_fetch_customer_if_not_passed(
state,
merchant_context,
Some(req),
None,
is_ephemeral_auth.then_some(api_key).flatten(),
)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
/// Generate a form link for collecting payment methods for a customer
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodCollectLink))]
pub async fn initiate_pm_collect_link_flow(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCollectLinkRequest>,
) -> HttpResponse {
let flow = Flow::PaymentMethodCollectLink;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::initiate_pm_collect_link(state, merchant_context, req)
},
&auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_api(
state: web::Data<AppState>,
customer_id: web::Path<id_type::GlobalCustomerId>,
req: HttpRequest,
query_payload: web::Query<api_models::payment_methods::ListMethodsForPaymentMethodsRequest>,
) -> HttpResponse {
let flow = Flow::CustomerPaymentMethodsList;
let payload = query_payload.into_inner();
let customer_id = customer_id.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, _, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::list_saved_payment_methods_for_customer(
state,
merchant_context,
customer_id.clone(),
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::GetPaymentMethodTokenData))]
pub async fn get_payment_method_token_data(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodId>,
json_payload: web::Json<api_models::payment_methods::GetTokenDataRequest>,
) -> HttpResponse {
let flow = Flow::GetPaymentMethodTokenData;
let payment_method_id = path.into_inner();
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payment_methods_routes::get_token_data_for_payment_method(
state,
auth.merchant_account,
auth.key_store,
auth.profile,
req,
payment_method_id.clone(),
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::TotalPaymentMethodCount))]
pub async fn get_total_payment_method_count(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::TotalPaymentMethodCount;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::get_total_saved_payment_methods_for_merchant(
state,
merchant_context,
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Generate a form link for collecting payment methods for a customer
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodCollectLink))]
pub async fn render_pm_collect_link(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(id_type::MerchantId, String)>,
) -> HttpResponse {
let flow = Flow::PaymentMethodCollectLink;
let (merchant_id, pm_collect_link_id) = path.into_inner();
let payload = payment_methods::PaymentMethodCollectLinkRenderRequest {
merchant_id: merchant_id.clone(),
pm_collect_link_id,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::render_pm_collect_link(state, merchant_context, req)
},
&auth::MerchantIdAuth(merchant_id),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsRetrieve))]
pub async fn payment_method_retrieve_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsRetrieve;
let payload = web::Json(PaymentMethodId {
payment_method_id: path.into_inner(),
})
.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, pm, _| async move {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
cards::PmCards {
state: &state,
merchant_context: &merchant_context,
}
.retrieve_payment_method(pm)
.await
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))]
pub async fn payment_method_update_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
json_payload: web::Json<payment_methods::PaymentMethodUpdate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsUpdate;
let payment_method_id = path.into_inner();
let payload = json_payload.into_inner();
let api_auth = auth::ApiKeyAuth::default();
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth)
{
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
cards::update_customer_payment_method(state, merchant_context, req, &payment_method_id)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsDelete))]
pub async fn payment_method_delete_api(
state: web::Data<AppState>,
req: HttpRequest,
payment_method_id: web::Path<(String,)>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsDelete;
let pm = PaymentMethodId {
payment_method_id: payment_method_id.into_inner().0,
};
let api_auth = auth::ApiKeyAuth::default();
let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
pm,
|state, auth: auth::AuthenticationData, req, _| async move {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
cards::PmCards {
state: &state,
merchant_context: &merchant_context,
}
.delete_payment_method(req)
.await
},
&*ephemeral_auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::ListCountriesCurrencies))]
pub async fn list_countries_currencies_for_connector_payment_method(
state: web::Data<AppState>,
req: HttpRequest,
query_payload: web::Query<payment_methods::ListCountriesCurrenciesRequest>,
) -> HttpResponse {
let flow = Flow::ListCountriesCurrencies;
let payload = query_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
cards::list_countries_currencies_for_connector_payment_method(
state,
req,
auth.profile_id,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileConnectorWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::ProfileConnectorWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::ListCountriesCurrencies))]
pub async fn list_countries_currencies_for_connector_payment_method(
state: web::Data<AppState>,
req: HttpRequest,
query_payload: web::Query<payment_methods::ListCountriesCurrenciesRequest>,
) -> HttpResponse {
let flow = Flow::ListCountriesCurrencies;
let payload = query_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
cards::list_countries_currencies_for_connector_payment_method(
state,
req,
Some(auth.profile.get_id().clone()),
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileConnectorRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::ProfileConnectorRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::DefaultPaymentMethodsSet))]
pub async fn default_payment_method_set_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<payment_methods::DefaultPaymentMethod>,
) -> HttpResponse {
let flow = Flow::DefaultPaymentMethodsSet;
let payload = path.into_inner();
let pc = payload.clone();
let customer_id = &pc.customer_id;
let api_auth = auth::ApiKeyAuth::default();
let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, default_payment_method, _| async move {
let merchant_id = auth.merchant_account.get_id();
cards::PmCards {
state: &state,
merchant_context: &domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account.clone(), auth.key_store),
)),
}
.set_default_payment_method(
merchant_id,
customer_id,
default_payment_method.payment_method_id,
)
.await
},
&*ephemeral_auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use api_models::payment_methods::PaymentMethodListRequest;
use super::*;
// #[test]
// fn test_custom_list_deserialization() {
// let dummy_data = "amount=120&recurring_enabled=true&installment_payment_enabled=true";
// let de_query: web::Query<PaymentMethodListRequest> =
// web::Query::from_query(dummy_data).unwrap();
// let de_struct = de_query.into_inner();
// assert_eq!(de_struct.installment_payment_enabled, Some(true))
// }
#[test]
fn test_custom_list_deserialization_multi_amount() {
let dummy_data = "amount=120&recurring_enabled=true&amount=1000";
let de_query: Result<web::Query<PaymentMethodListRequest>, _> =
web::Query::from_query(dummy_data);
assert!(de_query.is_err())
}
}
#[derive(Clone)]
pub struct ParentPaymentMethodToken {
key_for_token: String,
}
impl ParentPaymentMethodToken {
pub fn create_key_for_token(
(parent_pm_token, payment_method): (&String, api_models::enums::PaymentMethod),
) -> Self {
Self {
key_for_token: format!("pm_token_{parent_pm_token}_{payment_method}_hyperswitch"),
}
}
#[cfg(feature = "v2")]
pub fn return_key_for_token(
(parent_pm_token, payment_method): (&String, api_models::enums::PaymentMethod),
) -> String {
format!("pm_token_{parent_pm_token}_{payment_method}_hyperswitch")
}
pub async fn insert(
&self,
fulfillment_time: i64,
token: PaymentTokenData,
state: &SessionState,
) -> CustomResult<(), errors::ApiErrorResponse> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
redis_conn
.serialize_and_set_key_with_expiry(
&self.key_for_token.as_str().into(),
token,
fulfillment_time,
)
.await
.change_context(errors::StorageError::KVError)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add token in redis")?;
Ok(())
}
pub fn should_delete_payment_method_token(&self, status: IntentStatus) -> bool {
// RequiresMerchantAction: When the payment goes for merchant review incase of potential fraud allow payment_method_token to be stored until resolved
![
IntentStatus::RequiresCustomerAction,
IntentStatus::RequiresMerchantAction,
]
.contains(&status)
}
pub async fn delete(&self, state: &SessionState) -> CustomResult<(), errors::ApiErrorResponse> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
match redis_conn
.delete_key(&self.key_for_token.as_str().into())
.await
{
Ok(_) => Ok(()),
Err(err) => {
{
logger::info!("Error while deleting redis key: {:?}", err)
};
Ok(())
}
}
}
}
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
#[instrument(skip_all, fields(flow = ?Flow::TokenizeCard))]
pub async fn tokenize_card_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::CardNetworkTokenizeRequest>,
) -> HttpResponse {
let flow = Flow::TokenizeCard;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| async move {
let merchant_id = req.merchant_id.clone();
let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(merchant_account, key_store),
));
let res = Box::pin(cards::tokenize_card_flow(
&state,
CardNetworkTokenizeRequest::foreign_from(req),
&merchant_context,
))
.await?;
Ok(services::ApplicationResponse::Json(res))
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
#[instrument(skip_all, fields(flow = ?Flow::TokenizeCardUsingPaymentMethodId))]
pub async fn tokenize_card_using_pm_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
json_payload: web::Json<payment_methods::CardNetworkTokenizeRequest>,
) -> HttpResponse {
let flow = Flow::TokenizeCardUsingPaymentMethodId;
let pm_id = path.into_inner();
let mut payload = json_payload.into_inner();
if let payment_methods::TokenizeDataRequest::ExistingPaymentMethod(ref mut pm_data) =
payload.data
{
pm_data.payment_method_id = pm_id;
} else {
return api::log_and_return_error_response(error_stack::report!(
errors::ApiErrorResponse::InvalidDataValue { field_name: "card" }
));
}
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, req, _| async move {
let merchant_id = req.merchant_id.clone();
let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(merchant_account, key_store),
));
let res = Box::pin(cards::tokenize_card_flow(
&state,
CardNetworkTokenizeRequest::foreign_from(req),
&merchant_context,
))
.await?;
Ok(services::ApplicationResponse::Json(res))
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
#[instrument(skip_all, fields(flow = ?Flow::TokenizeCardBatch))]
pub async fn tokenize_card_batch_api(
state: web::Data<AppState>,
req: HttpRequest,
MultipartForm(form): MultipartForm<tokenize::CardNetworkTokenizeForm>,
) -> HttpResponse {
let flow = Flow::TokenizeCardBatch;
let (merchant_id, records) = match tokenize::get_tokenize_card_form_records(form) {
Ok(res) => res,
Err(e) => return api::log_and_return_error_response(e.into()),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
records,
|state, _, req, _| {
let merchant_id = merchant_id.clone();
async move {
let (key_store, merchant_account) =
get_merchant_account(&state, &merchant_id).await?;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(merchant_account, key_store),
));
Box::pin(tokenize::tokenize_cards(&state, req, &merchant_context)).await
}
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionCreate))]
pub async fn payment_methods_session_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_models::payment_methods::PaymentMethodSessionRequest>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSessionCreate;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, request, _| async move {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::payment_methods_session_create(state, merchant_context, request)
.await
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionUpdate))]
pub async fn payment_methods_session_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodSessionId>,
json_payload: web::Json<api_models::payment_methods::PaymentMethodsSessionUpdateRequest>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSessionUpdate;
let payment_method_session_id = path.into_inner();
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let value = payment_method_session_id.clone();
async move {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::payment_methods_session_update(
state,
merchant_context,
value.clone(),
req,
)
.await
}
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionRetrieve))]
pub async fn payment_methods_session_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodSessionId>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSessionRetrieve;
let payment_method_session_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payment_method_session_id.clone(),
|state, auth: auth::AuthenticationData, payment_method_session_id, _| async move {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::payment_methods_session_retrieve(
state,
merchant_context,
payment_method_session_id,
)
.await
},
auth::api_or_client_auth(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::V2ClientAuth(
common_utils::types::authentication::ResourceId::PaymentMethodSession(
payment_method_session_id,
),
),
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))]
pub async fn payment_method_session_list_payment_methods(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodSessionId>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsList;
let payment_method_session_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payment_method_session_id.clone(),
|state, auth: auth::AuthenticationData, payment_method_session_id, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::list_payment_methods_for_session(
state,
merchant_context,
auth.profile,
payment_method_session_id,
)
},
&auth::V2ClientAuth(
common_utils::types::authentication::ResourceId::PaymentMethodSession(
payment_method_session_id,
),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize)]
struct PaymentMethodsSessionGenericRequest<T: serde::Serialize> {
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
#[serde(flatten)]
request: T,
}
#[cfg(feature = "v2")]
impl<T: serde::Serialize> common_utils::events::ApiEventMetric
for PaymentMethodsSessionGenericRequest<T>
{
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::PaymentMethodSession {
payment_method_session_id: self.payment_method_session_id.clone(),
})
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionConfirm))]
pub async fn payment_method_session_confirm(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodSessionId>,
json_payload: web::Json<api_models::payment_methods::PaymentMethodSessionConfirmRequest>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSessionConfirm;
let payload = json_payload.into_inner();
let payment_method_session_id = path.into_inner();
let request = PaymentMethodsSessionGenericRequest {
payment_method_session_id: payment_method_session_id.clone(),
request: payload,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
request,
|state, auth: auth::AuthenticationData, request, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::payment_methods_session_confirm(
state,
req_state,
merchant_context,
auth.profile,
request.payment_method_session_id,
request.request,
)
},
&auth::V2ClientAuth(
common_utils::types::authentication::ResourceId::PaymentMethodSession(
payment_method_session_id,
),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionUpdateSavedPaymentMethod))]
pub async fn payment_method_session_update_saved_payment_method(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodSessionId>,
json_payload: web::Json<
api_models::payment_methods::PaymentMethodSessionUpdateSavedPaymentMethod,
>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSessionUpdateSavedPaymentMethod;
let payload = json_payload.into_inner();
let payment_method_session_id = path.into_inner();
let request = PaymentMethodsSessionGenericRequest {
payment_method_session_id: payment_method_session_id.clone(),
request: payload,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
request,
|state, auth: auth::AuthenticationData, request, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::payment_methods_session_update_payment_method(
state,
merchant_context,
auth.profile,
request.payment_method_session_id,
request.request,
)
},
&auth::V2ClientAuth(
common_utils::types::authentication::ResourceId::PaymentMethodSession(
payment_method_session_id,
),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionUpdateSavedPaymentMethod))]
pub async fn payment_method_session_delete_saved_payment_method(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodSessionId>,
json_payload: web::Json<
api_models::payment_methods::PaymentMethodSessionDeleteSavedPaymentMethod,
>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSessionDeleteSavedPaymentMethod;
let payload = json_payload.into_inner();
let payment_method_session_id = path.into_inner();
let request = PaymentMethodsSessionGenericRequest {
payment_method_session_id: payment_method_session_id.clone(),
request: payload,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
request,
|state, auth: auth::AuthenticationData, request, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::payment_methods_session_delete_payment_method(
state,
merchant_context,
auth.profile,
request.request.payment_method_id,
request.payment_method_session_id,
)
},
&auth::V2ClientAuth(
common_utils::types::authentication::ResourceId::PaymentMethodSession(
payment_method_session_id,
),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::NetworkTokenStatusCheck))]
pub async fn network_token_status_check_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodId>,
) -> HttpResponse {
let flow = Flow::NetworkTokenStatusCheck;
let payment_method_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payment_method_id,
|state, auth: auth::AuthenticationData, payment_method_id, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payment_methods_routes::check_network_token_status(
state,
merchant_context,
payment_method_id,
)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": "crates/router/src/routes/payment_methods.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 3,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-3434732895852124504 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/routes/refunds.rs
// Contains: 1 structs, 0 enums
use actix_web::{web, HttpRequest, HttpResponse};
use common_utils;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
#[cfg(feature = "v1")]
use crate::core::refunds::*;
#[cfg(feature = "v2")]
use crate::core::refunds_v2::*;
use crate::{
core::api_locking,
services::{api, authentication as auth, authorization::permissions::Permission},
types::{api::refunds, domain},
};
#[cfg(feature = "v2")]
/// A private module to hold internal types to be used in route handlers.
/// This is because we will need to implement certain traits on these types which will have the resource id
/// But the api payload will not contain the resource id
/// So these types can hold the resource id along with actual api payload, on which api event and locking action traits can be implemented
mod internal_payload_types {
use super::*;
// Serialize is implemented because of api events
#[derive(Debug, serde::Serialize)]
pub struct RefundsGenericRequestWithResourceId<T: serde::Serialize> {
pub global_refund_id: common_utils::id_type::GlobalRefundId,
pub payment_id: Option<common_utils::id_type::GlobalPaymentId>,
#[serde(flatten)]
pub payload: T,
}
impl<T: serde::Serialize> common_utils::events::ApiEventMetric
for RefundsGenericRequestWithResourceId<T>
{
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
let refund_id = self.global_refund_id.clone();
let payment_id = self.payment_id.clone();
Some(common_utils::events::ApiEventsType::Refund {
payment_id,
refund_id,
})
}
}
}
/// Refunds - Create
///
/// To create a refund against an already processed payment
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::RefundsCreate))]
// #[post("")]
pub async fn refunds_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<refunds::RefundRequest>,
) -> HttpResponse {
let flow = Flow::RefundsCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
refund_create_core(state, merchant_context, auth.profile_id, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRefundWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::RefundsCreate))]
// #[post("")]
pub async fn refunds_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<refunds::RefundsCreateRequest>,
) -> HttpResponse {
let flow = Flow::RefundsCreate;
let global_refund_id =
common_utils::id_type::GlobalRefundId::generate(&state.conf.cell_information.id);
let payload = json_payload.into_inner();
let internal_refund_create_payload =
internal_payload_types::RefundsGenericRequestWithResourceId {
global_refund_id: global_refund_id.clone(),
payment_id: Some(payload.payment_id.clone()),
payload,
};
let auth_type = if state.conf.merchant_id_auth.merchant_id_auth_enabled {
&auth::MerchantIdAuth
} else {
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileRefundWrite,
},
req.headers(),
)
};
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_refund_create_payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
refund_create_core(
state,
merchant_context,
req.payload,
global_refund_id.clone(),
)
},
auth_type,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Refunds - Retrieve (GET)
///
/// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment
#[instrument(skip_all, fields(flow))]
// #[get("/{id}")]
pub async fn refunds_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
query_params: web::Query<api_models::refunds::RefundsRetrieveBody>,
) -> HttpResponse {
let refund_request = refunds::RefundsRetrieveRequest {
refund_id: path.into_inner(),
force_sync: query_params.force_sync,
merchant_connector_details: None,
};
let flow = match query_params.force_sync {
Some(true) => Flow::RefundsRetrieveForceSync,
_ => Flow::RefundsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
Box::pin(api::server_wrap(
flow,
state,
&req,
refund_request,
|state, auth: auth::AuthenticationData, refund_request, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
refund_response_wrapper(
state,
merchant_context,
auth.profile_id,
refund_request,
refund_retrieve_core_with_refund_id,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow))]
pub async fn refunds_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::GlobalRefundId>,
query_params: web::Query<api_models::refunds::RefundsRetrieveBody>,
) -> HttpResponse {
let refund_request = refunds::RefundsRetrieveRequest {
refund_id: path.into_inner(),
force_sync: query_params.force_sync,
merchant_connector_details: None,
};
let flow = match query_params.force_sync {
Some(true) => Flow::RefundsRetrieveForceSync,
_ => Flow::RefundsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
Box::pin(api::server_wrap(
flow,
state,
&req,
refund_request,
|state, auth: auth::AuthenticationData, refund_request, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
refund_retrieve_core_with_refund_id(
state,
merchant_context,
auth.profile,
refund_request,
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow))]
pub async fn refunds_retrieve_with_gateway_creds(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::GlobalRefundId>,
payload: web::Json<api_models::refunds::RefundsRetrievePayload>,
) -> HttpResponse {
let flow = match payload.force_sync {
Some(true) => Flow::RefundsRetrieveForceSync,
_ => Flow::RefundsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
let refund_request = refunds::RefundsRetrieveRequest {
refund_id: path.into_inner(),
force_sync: payload.force_sync,
merchant_connector_details: payload.merchant_connector_details.clone(),
};
let auth_type = if state.conf.merchant_id_auth.merchant_id_auth_enabled {
&auth::MerchantIdAuth
} else {
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
)
};
Box::pin(api::server_wrap(
flow,
state,
&req,
refund_request,
|state, auth: auth::AuthenticationData, refund_request, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
refund_retrieve_core_with_refund_id(
state,
merchant_context,
auth.profile,
refund_request,
)
},
auth_type,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Refunds - Retrieve (POST)
///
/// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment
#[instrument(skip_all, fields(flow))]
// #[post("/sync")]
pub async fn refunds_retrieve_with_body(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<refunds::RefundsRetrieveRequest>,
) -> HttpResponse {
let flow = match json_payload.force_sync {
Some(true) => Flow::RefundsRetrieveForceSync,
_ => Flow::RefundsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
refund_response_wrapper(
state,
merchant_context,
auth.profile_id,
req,
refund_retrieve_core_with_refund_id,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Refunds - Update
///
/// To update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields
#[instrument(skip_all, fields(flow = ?Flow::RefundsUpdate))]
// #[post("/{id}")]
pub async fn refunds_update(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<refunds::RefundUpdateRequest>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::RefundsUpdate;
let mut refund_update_req = json_payload.into_inner();
refund_update_req.refund_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
refund_update_req,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
refund_update_core(state, merchant_context, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::RefundsUpdate))]
pub async fn refunds_metadata_update(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<refunds::RefundMetadataUpdateRequest>,
path: web::Path<common_utils::id_type::GlobalRefundId>,
) -> HttpResponse {
let flow = Flow::RefundsUpdate;
let global_refund_id = path.into_inner();
let internal_payload = internal_payload_types::RefundsGenericRequestWithResourceId {
global_refund_id: global_refund_id.clone(),
payment_id: None,
payload: json_payload.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, _| {
refund_metadata_update_core(
state,
auth.merchant_account,
req.payload,
global_refund_id.clone(),
)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
/// Refunds - List
///
/// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided
#[instrument(skip_all, fields(flow = ?Flow::RefundsList))]
pub async fn refunds_list(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<api_models::refunds::RefundListRequest>,
) -> HttpResponse {
let flow = Flow::RefundsList;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
refund_list(state, merchant_context, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::RefundsList))]
pub async fn refunds_list(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<api_models::refunds::RefundListRequest>,
) -> HttpResponse {
let flow = Flow::RefundsList;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
refund_list(state, auth.merchant_account, auth.profile, req)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
/// Refunds - List at profile level
///
/// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided
#[instrument(skip_all, fields(flow = ?Flow::RefundsList))]
pub async fn refunds_list_profile(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<api_models::refunds::RefundListRequest>,
) -> HttpResponse {
let flow = Flow::RefundsList;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
refund_list(
state,
merchant_context,
auth.profile_id.map(|profile_id| vec![profile_id]),
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
/// Refunds - Filter
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
#[instrument(skip_all, fields(flow = ?Flow::RefundsList))]
pub async fn refunds_filter_list(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::RefundsList;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
refund_filter_list(state, merchant_context, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
/// Refunds - Filter V2
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
#[instrument(skip_all, fields(flow = ?Flow::RefundsFilters))]
pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::RefundsFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
get_filters_for_refunds(state, merchant_context, None)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
/// Refunds - Filter V2 at profile level
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
#[instrument(skip_all, fields(flow = ?Flow::RefundsFilters))]
pub async fn get_refunds_filters_profile(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::RefundsFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
get_filters_for_refunds(
state,
merchant_context,
auth.profile_id.map(|profile_id| vec![profile_id]),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::RefundsAggregate))]
pub async fn get_refunds_aggregates(
state: web::Data<AppState>,
req: HttpRequest,
query_params: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::RefundsAggregate;
let query_params = query_params.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
query_params,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
get_aggregates_for_refunds(state, merchant_context, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::RefundsManualUpdate))]
pub async fn refunds_manual_update(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<api_models::refunds::RefundManualUpdateRequest>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::RefundsManualUpdate;
let mut refund_manual_update_req = payload.into_inner();
refund_manual_update_req.refund_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
refund_manual_update_req,
|state, _auth, req, _| refund_manual_update(state, req),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::RefundsAggregate))]
pub async fn get_refunds_aggregate_profile(
state: web::Data<AppState>,
req: HttpRequest,
query_params: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::RefundsAggregate;
let query_params = query_params.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
query_params,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
get_aggregates_for_refunds(
state,
merchant_context,
auth.profile_id.map(|profile_id| vec![profile_id]),
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": "crates/router/src/routes/refunds.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-8753031381447175088 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/routes/payments.rs
// Contains: 1 structs, 0 enums
use crate::{
core::api_locking::{self, GetLockingInput},
services::authorization::permissions::Permission,
};
pub mod helpers;
use actix_web::{web, Responder};
use error_stack::report;
use hyperswitch_domain_models::payments::HeaderPayload;
use masking::PeekInterface;
use router_env::{env, instrument, logger, tracing, types, Flow};
use super::app::ReqState;
#[cfg(feature = "v2")]
use crate::core::gift_card;
#[cfg(feature = "v2")]
use crate::core::revenue_recovery::api as recovery;
use crate::{
self as app,
core::{
errors::{self, http_not_implemented},
payments::{self, PaymentRedirectFlow},
},
routes::lock_utils,
services::{api, authentication as auth},
types::{
api::{
self as api_types, enums as api_enums,
payments::{self as payment_types, PaymentIdTypeExt},
},
domain,
transformers::ForeignTryFrom,
},
};
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCreate, payment_id))]
pub async fn payments_create(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRequest>,
) -> impl Responder {
let flow = Flow::PaymentsCreate;
let mut payload = json_payload.into_inner();
if let Err(err) = payload
.validate()
.map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message })
{
return api::log_and_return_error_response(err.into());
};
if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method {
return http_not_implemented();
};
if let Err(err) = get_or_generate_payment_id(&mut payload) {
return api::log_and_return_error_response(err);
}
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
tracing::Span::current().record(
"payment_id",
payload
.payment_id
.as_ref()
.map(|payment_id_type| payment_id_type.get_payment_intent_id())
.transpose()
.unwrap_or_default()
.as_ref()
.map(|id| id.get_string_repr())
.unwrap_or_default(),
);
let locking_action = payload.get_locking_input(flow.clone());
let auth_type = match env::which() {
env::Env::Production => {
&auth::InternalMerchantIdProfileIdAuth(auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}))
}
_ => auth::auth_type(
&auth::InternalMerchantIdProfileIdAuth(auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
})),
&auth::InternalMerchantIdProfileIdAuth(auth::JWTAuth {
permission: Permission::ProfilePaymentWrite,
}),
req.headers(),
),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
authorize_verify_select::<_>(
payments::PaymentCreate,
state,
req_state,
merchant_context,
auth.profile_id,
header_payload.clone(),
req,
api::AuthFlow::Client,
)
},
auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v2")]
pub async fn recovery_payments_create(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::RecoveryPaymentsCreate>,
) -> impl Responder {
let flow = Flow::RecoveryPaymentsCreate;
let mut payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req.clone(),
payload,
|state, auth: auth::AuthenticationData, req_payload, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
recovery::custom_revenue_recovery_core(
state.to_owned(),
req_state,
merchant_context,
auth.profile,
req_payload,
)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCreateIntent, payment_id))]
pub async fn payments_create_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsCreateIntentRequest>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentIntentData;
let flow = Flow::PaymentsCreateIntent;
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let global_payment_id =
common_utils::id_type::GlobalPaymentId::generate(&state.conf.cell_information.id);
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_intent_core::<
api_types::PaymentCreateIntent,
payment_types::PaymentsIntentResponse,
_,
_,
PaymentIntentData<api_types::PaymentCreateIntent>,
>(
state,
req_state,
merchant_context,
auth.profile,
payments::operations::PaymentIntentCreate,
req,
global_payment_id.clone(),
header_payload.clone(),
)
},
match env::which() {
env::Env::Production => &auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
_ => auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentWrite,
},
req.headers(),
),
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsGetIntent, payment_id))]
pub async fn payments_get_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use api_models::payments::PaymentsGetIntentRequest;
use hyperswitch_domain_models::payments::PaymentIntentData;
let flow = Flow::PaymentsGetIntent;
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let payload = PaymentsGetIntentRequest {
id: path.into_inner(),
};
let global_payment_id = payload.id.clone();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_intent_core::<
api_types::PaymentGetIntent,
payment_types::PaymentsIntentResponse,
_,
_,
PaymentIntentData<api_types::PaymentGetIntent>,
>(
state,
req_state,
merchant_context,
auth.profile,
payments::operations::PaymentGetIntent,
req,
global_payment_id.clone(),
header_payload.clone(),
)
},
auth::api_or_client_or_jwt_auth(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment(
global_payment_id.clone(),
)),
&auth::JWTAuth {
permission: Permission::ProfileRevenueRecoveryRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentAttemptsList, payment_id,))]
pub async fn list_payment_attempts(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
let flow = Flow::PaymentAttemptsList;
let payment_intent_id = path.into_inner();
let payload = api_models::payments::PaymentAttemptListRequest {
payment_intent_id: payment_intent_id.clone(),
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.clone(),
|session_state, auth, req_payload, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_list_attempts_using_payment_intent_id::<
payments::operations::PaymentGetListAttempts,
api_models::payments::PaymentAttemptListResponse,
api_models::payments::PaymentAttemptListRequest,
payments::operations::payment_attempt_list::PaymentGetListAttempts,
hyperswitch_domain_models::payments::PaymentAttemptListData<
payments::operations::PaymentGetListAttempts,
>,
>(
session_state,
req_state,
merchant_context,
auth.profile,
payments::operations::PaymentGetListAttempts,
payload.clone(),
req_payload.payment_intent_id,
header_payload.clone(),
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCreateAndConfirmIntent, payment_id))]
pub async fn payments_create_and_confirm_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRequest>,
) -> impl Responder {
let flow = Flow::PaymentsCreateAndConfirmIntent;
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let auth_type = if state.conf.merchant_id_auth.merchant_id_auth_enabled {
&auth::MerchantIdAuth
} else {
match env::which() {
env::Env::Production => &auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
_ => auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentWrite,
},
req.headers(),
),
}
};
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, request, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_create_and_confirm_intent(
state,
req_state,
merchant_context,
auth.profile,
request,
header_payload.clone(),
)
},
auth_type,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdateIntent, payment_id))]
pub async fn payments_update_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsUpdateIntentRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentIntentData;
let flow = Flow::PaymentsUpdateIntent;
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id: path.into_inner(),
payload: json_payload.into_inner(),
};
let global_payment_id = internal_payload.global_payment_id.clone();
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account.clone(), auth.key_store.clone()),
));
payments::payments_intent_core::<
api_types::PaymentUpdateIntent,
payment_types::PaymentsIntentResponse,
_,
_,
PaymentIntentData<api_types::PaymentUpdateIntent>,
>(
state,
req_state,
merchant_context,
auth.profile,
payments::operations::PaymentUpdateIntent,
req.payload,
global_payment_id.clone(),
header_payload.clone(),
)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip(state, req), fields(flow = ?Flow::PaymentsStart, payment_id))]
pub async fn payments_start(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<(
common_utils::id_type::PaymentId,
common_utils::id_type::MerchantId,
String,
)>,
) -> impl Responder {
let flow = Flow::PaymentsStart;
let (payment_id, merchant_id, attempt_id) = path.into_inner();
let payload = payment_types::PaymentsStartRequest {
payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
attempt_id: attempt_id.clone(),
};
let locking_action = payload.get_locking_input(flow.clone());
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::Authorize,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Authorize>,
>(
state,
req_state,
merchant_context,
auth.profile_id,
payments::operations::PaymentStart,
req,
api::AuthFlow::Client,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
)
},
&auth::MerchantIdAuth(merchant_id),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip(state, req), fields(flow, payment_id))]
pub async fn payments_retrieve(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::PaymentId>,
json_payload: web::Query<payment_types::PaymentRetrieveBody>,
) -> impl Responder {
let flow = match json_payload.force_sync {
Some(true) => Flow::PaymentsRetrieveForceSync,
_ => Flow::PaymentsRetrieve,
};
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let payload = payment_types::PaymentsRetrieveRequest {
resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id),
merchant_id: json_payload.merchant_id.clone(),
force_sync: json_payload.force_sync.unwrap_or(false),
client_secret: json_payload.client_secret.clone(),
expand_attempts: json_payload.expand_attempts,
expand_captures: json_payload.expand_captures,
all_keys_required: json_payload.all_keys_required,
..Default::default()
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
tracing::Span::current().record("flow", flow.to_string());
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
};
let (auth_type, auth_flow) = match auth::check_internal_api_key_auth(
req.headers(),
&payload,
api_auth,
state.conf.internal_merchant_id_profile_id_auth.clone(),
) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::PSync,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::PSync>,
>(
state,
req_state,
merchant_context,
auth.profile_id,
payments::PaymentStatus,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
None,
header_payload.clone(),
)
},
auth::auth_type(
&*auth_type,
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
req.headers(),
),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip(state, req), fields(flow, payment_id))]
pub async fn payments_retrieve_with_gateway_creds(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentRetrieveBodyWithCredentials>,
) -> impl Responder {
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
};
let (auth_type, _auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
tracing::Span::current().record("payment_id", json_payload.payment_id.get_string_repr());
let payload = payment_types::PaymentsRetrieveRequest {
resource_id: payment_types::PaymentIdType::PaymentIntentId(json_payload.payment_id.clone()),
merchant_id: json_payload.merchant_id.clone(),
force_sync: json_payload.force_sync.unwrap_or(false),
merchant_connector_details: json_payload.merchant_connector_details.clone(),
..Default::default()
};
let flow = match json_payload.force_sync {
Some(true) => Flow::PaymentsRetrieveForceSync,
_ => Flow::PaymentsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::PSync,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::PSync>,
>(
state,
req_state,
merchant_context,
auth.profile_id,
payments::PaymentStatus,
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdate, payment_id))]
pub async fn payments_update(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsUpdate;
let mut payload = json_payload.into_inner();
if let Err(err) = payload
.validate()
.map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message })
{
return api::log_and_return_error_response(err.into());
};
if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method {
return http_not_implemented();
};
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id));
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
};
let (auth_type, auth_flow) = match auth::check_internal_api_key_auth_no_client_secret(
req.headers(),
api_auth,
state.conf.internal_merchant_id_profile_id_auth.clone(),
) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
authorize_verify_select::<_>(
payments::PaymentUpdate,
state,
req_state,
merchant_context,
auth.profile_id,
HeaderPayload::default(),
req,
auth_flow,
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsPostSessionTokens, payment_id))]
pub async fn payments_post_session_tokens(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsPostSessionTokensRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsPostSessionTokens;
let payment_id = path.into_inner();
let payload = payment_types::PaymentsPostSessionTokensRequest {
payment_id,
..json_payload.into_inner()
};
tracing::Span::current().record("payment_id", payload.payment_id.get_string_repr());
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::PostSessionTokens,
payment_types::PaymentsPostSessionTokensResponse,
_,
_,
_,
payments::PaymentData<api_types::PostSessionTokens>,
>(
state,
req_state,
merchant_context,
auth.profile_id,
payments::PaymentPostSessionTokens,
req,
api::AuthFlow::Client,
payments::CallConnectorAction::Trigger,
None,
header_payload.clone(),
)
},
&auth::PublishableKeyAuth,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdateMetadata, payment_id))]
pub async fn payments_update_metadata(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsUpdateMetadataRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsUpdateMetadata;
let payment_id = path.into_inner();
let payload = payment_types::PaymentsUpdateMetadataRequest {
payment_id,
..json_payload.into_inner()
};
tracing::Span::current().record("payment_id", payload.payment_id.get_string_repr());
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::UpdateMetadata,
payment_types::PaymentsUpdateMetadataResponse,
_,
_,
_,
payments::PaymentData<api_types::UpdateMetadata>,
>(
state,
req_state,
merchant_context,
auth.profile_id,
payments::PaymentUpdateMetadata,
req,
api::AuthFlow::Client,
payments::CallConnectorAction::Trigger,
None,
header_payload.clone(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm, payment_id))]
pub async fn payments_confirm(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsConfirm;
let mut payload = json_payload.into_inner();
if let Err(err) = payload
.validate()
.map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message })
{
return api::log_and_return_error_response(err.into());
};
if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method {
return http_not_implemented();
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
if let Err(err) = helpers::populate_browser_info(&req, &mut payload, &header_payload) {
return api::log_and_return_error_response(err);
}
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id));
payload.confirm = Some(true);
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
};
let (auth_type, auth_flow) = match auth::check_internal_api_key_auth(
req.headers(),
&payload,
api_auth,
state.conf.internal_merchant_id_profile_id_auth.clone(),
) {
Ok(auth) => auth,
Err(e) => return api::log_and_return_error_response(e),
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
authorize_verify_select::<_>(
payments::PaymentConfirm,
state,
req_state,
merchant_context,
auth.profile_id,
header_payload.clone(),
req,
auth_flow,
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCapture, payment_id))]
pub async fn payments_capture(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsCaptureRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let flow = Flow::PaymentsCapture;
let payload = payment_types::PaymentsCaptureRequest {
payment_id,
..json_payload.into_inner()
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, payload, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::Capture,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Capture>,
>(
state,
req_state,
merchant_context,
auth.profile_id,
payments::PaymentCapture,
payload,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::SessionUpdateTaxCalculation, payment_id))]
pub async fn payments_dynamic_tax_calculation(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsDynamicTaxCalculationRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::SessionUpdateTaxCalculation;
let payment_id = path.into_inner();
let payload = payment_types::PaymentsDynamicTaxCalculationRequest {
payment_id,
..json_payload.into_inner()
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(error) => {
logger::error!(
?error,
"Failed to get headers in payments_connector_session"
);
HeaderPayload::default()
}
};
tracing::Span::current().record("payment_id", payload.payment_id.get_string_repr());
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, payload, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::SdkSessionUpdate,
payment_types::PaymentsDynamicTaxCalculationResponse,
_,
_,
_,
_,
>(
state,
req_state,
merchant_context,
auth.profile_id,
payments::PaymentSessionUpdate,
payload,
api::AuthFlow::Client,
payments::CallConnectorAction::Trigger,
None,
header_payload.clone(),
)
},
&auth::PublishableKeyAuth,
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsSessionToken, payment_id))]
pub async fn payments_connector_session(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsSessionRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentIntentData;
let flow = Flow::PaymentsSessionToken;
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id: global_payment_id.clone(),
payload: json_payload.into_inner(),
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let locking_action = internal_payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let payment_id = req.global_payment_id;
let request = req.payload;
let operation = payments::operations::PaymentSessionIntent;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_session_core::<
api_types::Session,
payment_types::PaymentsSessionResponse,
_,
_,
_,
PaymentIntentData<api_types::Session>,
>(
state,
req_state,
merchant_context,
auth.profile,
operation,
request,
payment_id,
payments::CallConnectorAction::Trigger,
header_payload.clone(),
)
},
&auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment(
global_payment_id,
)),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsSessionToken, payment_id))]
pub async fn payments_connector_session(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsSessionRequest>,
) -> impl Responder {
let flow = Flow::PaymentsSessionToken;
let payload = json_payload.into_inner();
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(error) => {
logger::error!(
?error,
"Failed to get headers in payments_connector_session"
);
HeaderPayload::default()
}
};
tracing::Span::current().record("payment_id", payload.payment_id.get_string_repr());
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, payload, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::Session,
payment_types::PaymentsSessionResponse,
_,
_,
_,
payments::PaymentData<api_types::Session>,
>(
state,
req_state,
merchant_context,
auth.profile_id,
payments::PaymentSession,
payload,
api::AuthFlow::Client,
payments::CallConnectorAction::Trigger,
None,
header_payload.clone(),
)
},
&auth::HeaderAuth(auth::PublishableKeyAuth),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsRedirect, payment_id))]
pub async fn payments_redirect_response(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
path: web::Path<(
common_utils::id_type::PaymentId,
common_utils::id_type::MerchantId,
String,
)>,
) -> impl Responder {
let flow = Flow::PaymentsRedirect;
let (payment_id, merchant_id, connector) = path.into_inner();
let param_string = req.query_string();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let payload = payments::PaymentsRedirectResponseData {
resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id),
merchant_id: Some(merchant_id.clone()),
force_sync: true,
json_payload: json_payload.map(|payload| payload.0),
param: Some(param_string.to_string()),
connector: Some(connector),
creds_identifier: None,
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
<payments::PaymentRedirectSync as PaymentRedirectFlow>::handle_payments_redirect_response(
&payments::PaymentRedirectSync {},
state,
req_state,
merchant_context,
req,
)
},
&auth::MerchantIdAuth(merchant_id),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsRedirect, payment_id))]
pub async fn payments_redirect_response_with_creds_identifier(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<(
common_utils::id_type::PaymentId,
common_utils::id_type::MerchantId,
String,
String,
)>,
) -> impl Responder {
let (payment_id, merchant_id, connector, creds_identifier) = path.into_inner();
let param_string = req.query_string();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let payload = payments::PaymentsRedirectResponseData {
resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id),
merchant_id: Some(merchant_id.clone()),
force_sync: true,
json_payload: None,
param: Some(param_string.to_string()),
connector: Some(connector),
creds_identifier: Some(creds_identifier),
};
let flow = Flow::PaymentsRedirect;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
<payments::PaymentRedirectSync as PaymentRedirectFlow>::handle_payments_redirect_response(
&payments::PaymentRedirectSync {},
state,
req_state,
merchant_context,
req,
)
},
&auth::MerchantIdAuth(merchant_id),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow =? Flow::PaymentsRedirect, payment_id))]
pub async fn payments_complete_authorize_redirect(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
path: web::Path<(
common_utils::id_type::PaymentId,
common_utils::id_type::MerchantId,
String,
)>,
) -> impl Responder {
let flow = Flow::PaymentsRedirect;
let (payment_id, merchant_id, connector) = path.into_inner();
let param_string = req.query_string();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let payload = payments::PaymentsRedirectResponseData {
resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id),
merchant_id: Some(merchant_id.clone()),
param: Some(param_string.to_string()),
json_payload: json_payload.map(|s| s.0),
force_sync: false,
connector: Some(connector),
creds_identifier: None,
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
<payments::PaymentRedirectCompleteAuthorize as PaymentRedirectFlow>::handle_payments_redirect_response(
&payments::PaymentRedirectCompleteAuthorize {},
state,
req_state,
merchant_context,
req,
)
},
&auth::MerchantIdAuth(merchant_id),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow =? Flow::PaymentsRedirect, payment_id))]
pub async fn payments_complete_authorize_redirect_with_creds_identifier(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
path: web::Path<(
common_utils::id_type::PaymentId,
common_utils::id_type::MerchantId,
String,
String,
)>,
) -> impl Responder {
let flow = Flow::PaymentsRedirect;
let (payment_id, merchant_id, connector, creds_identifier) = path.into_inner();
let param_string = req.query_string();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let payload = payments::PaymentsRedirectResponseData {
resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id),
merchant_id: Some(merchant_id.clone()),
param: Some(param_string.to_string()),
json_payload: json_payload.map(|s| s.0),
force_sync: false,
connector: Some(connector),
creds_identifier: Some(creds_identifier),
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
<payments::PaymentRedirectCompleteAuthorize as PaymentRedirectFlow>::handle_payments_redirect_response(
&payments::PaymentRedirectCompleteAuthorize {},
state,
req_state,
merchant_context,
req,
)
},
&auth::MerchantIdAuth(merchant_id),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow =? Flow::PaymentsCompleteAuthorize, payment_id))]
pub async fn payments_complete_authorize(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsCompleteAuthorizeRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsCompleteAuthorize;
let mut payload = json_payload.into_inner();
let payment_id = path.into_inner();
payload.payment_id.clone_from(&payment_id);
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let payment_confirm_req = payment_types::PaymentsRequest {
payment_id: Some(payment_types::PaymentIdType::PaymentIntentId(
payment_id.clone(),
)),
shipping: payload.shipping.clone(),
client_secret: Some(payload.client_secret.peek().clone()),
threeds_method_comp_ind: payload.threeds_method_comp_ind.clone(),
..Default::default()
};
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
};
let (auth_type, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payment_confirm_req, api_auth)
{
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, _req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::CompleteAuthorize,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::CompleteAuthorize>,
>(
state.clone(),
req_state,
merchant_context,
auth.profile_id,
payments::operations::payment_complete_authorize::CompleteAuthorize,
payment_confirm_req.clone(),
auth_flow,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCancel, payment_id))]
pub async fn payments_cancel(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsCancelRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsCancel;
let mut payload = json_payload.into_inner();
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = payment_id;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::Void,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Void>,
>(
state,
req_state,
merchant_context,
auth.profile_id,
payments::PaymentCancel,
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCancel, payment_id))]
pub async fn payments_cancel(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsCancelRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsCancel;
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id: global_payment_id.clone(),
payload: json_payload.into_inner(),
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let locking_action = internal_payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| async {
let payment_id = req.global_payment_id;
let request = req.payload;
let operation = payments::operations::payment_cancel_v2::PaymentsCancel;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
Box::pin(payments::payments_core::<
hyperswitch_domain_models::router_flow_types::Void,
api_models::payments::PaymentsCancelResponse,
_,
_,
_,
hyperswitch_domain_models::payments::PaymentCancelData<
hyperswitch_domain_models::router_flow_types::Void,
>,
>(
state,
req_state,
merchant_context,
auth.profile,
operation,
request,
payment_id,
payments::CallConnectorAction::Trigger,
header_payload.clone(),
))
.await
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentWrite,
},
req.headers(),
),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCancelPostCapture, payment_id))]
pub async fn payments_cancel_post_capture(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsCancelPostCaptureRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsCancelPostCapture;
let mut payload = json_payload.into_inner();
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = payment_id;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::PostCaptureVoid,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::PostCaptureVoid>,
>(
state,
req_state,
merchant_context,
auth.profile_id,
payments::PaymentCancelPostCapture,
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
locking_action,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn payments_list(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<payment_types::PaymentListConstraints>,
) -> impl Responder {
let flow = Flow::PaymentsList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::list_payments(state, merchant_context, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(all(feature = "olap", feature = "v2"))]
pub async fn payments_list(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<payment_types::PaymentListConstraints>,
) -> impl Responder {
let flow = Flow::PaymentsList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::list_payments(state, merchant_context, req)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn profile_payments_list(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<payment_types::PaymentListConstraints>,
) -> impl Responder {
let flow = Flow::PaymentsList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::list_payments(
state,
merchant_context,
auth.profile_id.map(|profile_id| vec![profile_id]),
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn payments_list_by_filter(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Json<payment_types::PaymentListFilterConstraints>,
) -> impl Responder {
let flow = Flow::PaymentsList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::apply_filters_on_payments(state, merchant_context, None, req)
},
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn profile_payments_list_by_filter(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Json<payment_types::PaymentListFilterConstraints>,
) -> impl Responder {
let flow = Flow::PaymentsList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::apply_filters_on_payments(
state,
merchant_context,
auth.profile_id.map(|profile_id| vec![profile_id]),
req,
)
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn get_filters_for_payments(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Json<common_utils::types::TimeRange>,
) -> impl Responder {
let flow = Flow::PaymentsList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::get_filters_for_payments(state, merchant_context, req)
},
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsFilters))]
#[cfg(feature = "olap")]
pub async fn get_payment_filters(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
) -> impl Responder {
let flow = Flow::PaymentsFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::get_payment_filters(state, merchant_context, None)
},
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsFilters))]
#[cfg(all(feature = "olap", feature = "v2"))]
pub async fn get_payment_filters_profile(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
) -> impl Responder {
let flow = Flow::PaymentsFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::get_payment_filters(
state,
merchant_context,
Some(vec![auth.profile.get_id().clone()]),
)
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsFilters))]
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn get_payment_filters_profile(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
) -> impl Responder {
let flow = Flow::PaymentsFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::get_payment_filters(
state,
merchant_context,
auth.profile_id.map(|profile_id| vec![profile_id]),
)
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsAggregate))]
#[cfg(feature = "olap")]
pub async fn get_payments_aggregates(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<common_utils::types::TimeRange>,
) -> impl Responder {
let flow = Flow::PaymentsAggregate;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::get_aggregates_for_payments(state, merchant_context, None, req)
},
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "oltp", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsApprove, payment_id))]
pub async fn payments_approve(
state: web::Data<app::AppState>,
http_req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsApproveRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let mut payload = json_payload.into_inner();
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = payment_id;
let flow = Flow::PaymentsApprove;
let fpayload = FPaymentsApproveRequest(&payload);
let locking_action = fpayload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
payload.clone(),
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::Capture,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Capture>,
>(
state,
req_state,
merchant_context,
auth.profile_id,
payments::PaymentApprove,
payment_types::PaymentsCaptureRequest {
payment_id: req.payment_id,
..Default::default()
},
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
)
},
match env::which() {
env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
_ => auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
&auth::JWTAuth {
permission: Permission::ProfilePaymentWrite,
},
http_req.headers(),
),
},
locking_action,
))
.await
}
#[cfg(all(feature = "oltp", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsReject, payment_id))]
pub async fn payments_reject(
state: web::Data<app::AppState>,
http_req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRejectRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let mut payload = json_payload.into_inner();
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = payment_id;
let flow = Flow::PaymentsReject;
let fpayload = FPaymentsRejectRequest(&payload);
let locking_action = fpayload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
payload.clone(),
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::Void,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Void>,
>(
state,
req_state,
merchant_context,
auth.profile_id,
payments::PaymentReject,
payment_types::PaymentsCancelRequest {
payment_id: req.payment_id,
cancellation_reason: Some("Rejected by merchant".to_string()),
..Default::default()
},
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
)
},
match env::which() {
env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
_ => auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
&auth::JWTAuth {
permission: Permission::ProfilePaymentWrite,
},
http_req.headers(),
),
},
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn authorize_verify_select<Op>(
operation: Op,
state: app::SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile_id: Option<common_utils::id_type::ProfileId>,
header_payload: HeaderPayload,
req: api_models::payments::PaymentsRequest,
auth_flow: api::AuthFlow,
) -> errors::RouterResponse<api_models::payments::PaymentsResponse>
where
Op: Sync
+ Clone
+ std::fmt::Debug
+ payments::operations::Operation<
api_types::Authorize,
api_models::payments::PaymentsRequest,
Data = payments::PaymentData<api_types::Authorize>,
> + payments::operations::Operation<
api_types::SetupMandate,
api_models::payments::PaymentsRequest,
Data = payments::PaymentData<api_types::SetupMandate>,
>,
{
// TODO: Change for making it possible for the flow to be inferred internally or through validation layer
// This is a temporary fix.
// After analyzing the code structure,
// the operation are flow agnostic, and the flow is only required in the post_update_tracker
// Thus the flow can be generated just before calling the connector instead of explicitly passing it here.
let is_recurring_details_type_nti_and_card_details = req
.recurring_details
.clone()
.map(|recurring_details| {
recurring_details.is_network_transaction_id_and_card_details_flow()
})
.unwrap_or(false);
if is_recurring_details_type_nti_and_card_details {
// no list of eligible connectors will be passed in the confirm call
logger::debug!("Authorize call for NTI and Card Details flow");
payments::proxy_for_payments_core::<
api_types::Authorize,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Authorize>,
>(
state,
req_state,
merchant_context,
profile_id,
operation,
req.clone(),
auth_flow,
payments::CallConnectorAction::Trigger,
header_payload,
req.all_keys_required,
)
.await
} else {
let eligible_connectors = req.connector.clone();
match req.payment_type.unwrap_or_default() {
api_models::enums::PaymentType::Normal
| api_models::enums::PaymentType::RecurringMandate
| api_models::enums::PaymentType::NewMandate => {
payments::payments_core::<
api_types::Authorize,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Authorize>,
>(
state,
req_state,
merchant_context,
profile_id,
operation,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
eligible_connectors,
header_payload,
)
.await
}
api_models::enums::PaymentType::SetupMandate => {
payments::payments_core::<
api_types::SetupMandate,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::SetupMandate>,
>(
state,
req_state,
merchant_context,
profile_id,
operation,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
eligible_connectors,
header_payload,
)
.await
}
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsIncrementalAuthorization, payment_id))]
pub async fn payments_incremental_authorization(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsIncrementalAuthorizationRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsIncrementalAuthorization;
let mut payload = json_payload.into_inner();
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = payment_id;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::IncrementalAuthorization,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::IncrementalAuthorization>,
>(
state,
req_state,
merchant_context,
auth.profile_id,
payments::PaymentIncrementalAuthorization,
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsExtendAuthorization, payment_id))]
pub async fn payments_extend_authorization(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsExtendAuthorization;
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let payload = payment_types::PaymentsExtendAuthorizationRequest { payment_id };
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::ExtendAuthorization,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::ExtendAuthorization>,
>(
state,
req_state,
merchant_context,
auth.profile_id,
payments::PaymentExtendAuthorization,
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsExternalAuthentication, payment_id))]
pub async fn payments_external_authentication(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsExternalAuthenticationRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsExternalAuthentication;
let mut payload = json_payload.into_inner();
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = payment_id;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payment_external_authentication::<
hyperswitch_domain_models::router_flow_types::Authenticate,
>(state, merchant_context, req)
},
&auth::HeaderAuth(auth::PublishableKeyAuth),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsAuthorize, payment_id))]
pub async fn post_3ds_payments_authorize(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
path: web::Path<(
common_utils::id_type::PaymentId,
common_utils::id_type::MerchantId,
String,
)>,
) -> impl Responder {
let flow = Flow::PaymentsAuthorize;
let (payment_id, merchant_id, connector) = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let param_string = req.query_string();
let payload = payments::PaymentsRedirectResponseData {
resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id),
merchant_id: Some(merchant_id.clone()),
force_sync: true,
json_payload: json_payload.map(|payload| payload.0),
param: Some(param_string.to_string()),
connector: Some(connector),
creds_identifier: None,
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
<payments::PaymentAuthenticateCompleteAuthorize as PaymentRedirectFlow>::handle_payments_redirect_response(
&payments::PaymentAuthenticateCompleteAuthorize {},
state,
req_state,
merchant_context,
req,
)
},
&auth::MerchantIdAuth(merchant_id),
locking_action,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn payments_manual_update(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsManualUpdateRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsManualUpdate;
let mut payload = json_payload.into_inner();
let payment_id = path.into_inner();
let locking_action = payload.get_locking_input(flow.clone());
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = payment_id;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _auth, req, _req_state| payments::payments_manual_update(state, req),
&auth::AdminApiAuthWithMerchantIdFromHeader,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
/// Retrieve endpoint for merchant to fetch the encrypted customer payment method data
#[instrument(skip_all, fields(flow = ?Flow::GetExtendedCardInfo, payment_id))]
pub async fn retrieve_extended_card_info(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::GetExtendedCardInfo;
let payment_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payment_id,
|state, auth: auth::AuthenticationData, payment_id, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::get_extended_card_info(
state,
merchant_context.get_merchant_account().get_id().to_owned(),
payment_id,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "oltp", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsSubmitEligibility, payment_id))]
pub async fn payments_submit_eligibility(
state: web::Data<app::AppState>,
http_req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsEligibilityRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsSubmitEligibility;
let payment_id = path.into_inner();
let mut payload = json_payload.into_inner();
payload.payment_id = payment_id.clone();
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
};
let (auth_type, _auth_flow) =
match auth::check_client_secret_and_get_auth(http_req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
Box::pin(api::server_wrap(
flow,
state,
&http_req,
payment_id,
|state, auth: auth::AuthenticationData, payment_id, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_submit_eligibility(
state,
merchant_context,
payload.clone(),
payment_id,
)
},
&*auth_type,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub fn get_or_generate_payment_id(
payload: &mut payment_types::PaymentsRequest,
) -> errors::RouterResult<()> {
let given_payment_id = payload
.payment_id
.clone()
.map(|payment_id| {
payment_id
.get_payment_intent_id()
.map_err(|err| err.change_context(errors::ApiErrorResponse::PaymentNotFound))
})
.transpose()?;
let payment_id = given_payment_id.unwrap_or(common_utils::id_type::PaymentId::default());
payload.is_payment_id_from_merchant = matches!(
&payload.payment_id,
Some(payment_types::PaymentIdType::PaymentIntentId(_))
);
payload.payment_id = Some(api_models::payments::PaymentIdType::PaymentIntentId(
payment_id,
));
Ok(())
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
match self.payment_id {
Some(payment_types::PaymentIdType::PaymentIntentId(ref id)) => {
let api_identifier = lock_utils::ApiIdentifier::from(flow);
let intent_id_locking_input = api_locking::LockingInput {
unique_locking_key: id.get_string_repr().to_owned(),
api_identifier: api_identifier.clone(),
override_lock_retries: None,
};
if let Some(customer_id) = self
.customer_id
.as_ref()
.or(self.customer.as_ref().map(|customer| &customer.id))
{
api_locking::LockAction::HoldMultiple {
inputs: vec![
intent_id_locking_input,
api_locking::LockingInput {
unique_locking_key: customer_id.get_string_repr().to_owned(),
api_identifier,
override_lock_retries: None,
},
],
}
} else {
api_locking::LockAction::Hold {
input: intent_id_locking_input,
}
}
}
_ => api_locking::LockAction::NotApplicable,
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsStartRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsRetrieveRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
match self.resource_id {
payment_types::PaymentIdType::PaymentIntentId(ref id) if self.force_sync => {
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
_ => api_locking::LockAction::NotApplicable,
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsSessionRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v2")]
impl GetLockingInput for payment_types::PaymentsSessionRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
{
api_locking::LockAction::NotApplicable
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsDynamicTaxCalculationRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsPostSessionTokensRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsUpdateMetadataRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payments::PaymentsRedirectResponseData {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
match self.resource_id {
payment_types::PaymentIdType::PaymentIntentId(ref id) => {
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
_ => api_locking::LockAction::NotApplicable,
}
}
}
#[cfg(feature = "v2")]
impl GetLockingInput for payments::PaymentsRedirectResponseData {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsCompleteAuthorizeRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsCancelRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsCancelPostCaptureRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsExtendAuthorizationRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsCaptureRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "oltp")]
struct FPaymentsApproveRequest<'a>(&'a payment_types::PaymentsApproveRequest);
#[cfg(feature = "oltp")]
impl GetLockingInput for FPaymentsApproveRequest<'_> {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.0.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "oltp")]
struct FPaymentsRejectRequest<'a>(&'a payment_types::PaymentsRejectRequest);
#[cfg(feature = "oltp")]
impl GetLockingInput for FPaymentsRejectRequest<'_> {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.0.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsIncrementalAuthorizationRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsExternalAuthenticationRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsManualUpdateRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsAggregate))]
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn get_payments_aggregates_profile(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<common_utils::types::TimeRange>,
) -> impl Responder {
let flow = Flow::PaymentsAggregate;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::get_aggregates_for_payments(
state,
merchant_context,
auth.profile_id.map(|profile_id| vec![profile_id]),
req,
)
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsAggregate))]
#[cfg(all(feature = "olap", feature = "v2"))]
pub async fn get_payments_aggregates_profile(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<common_utils::types::TimeRange>,
) -> impl Responder {
let flow = Flow::PaymentsAggregate;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::get_aggregates_for_payments(
state,
merchant_context,
Some(vec![auth.profile.get_id().clone()]),
req,
)
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
/// A private module to hold internal types to be used in route handlers.
/// This is because we will need to implement certain traits on these types which will have the resource id
/// But the api payload will not contain the resource id
/// So these types can hold the resource id along with actual api payload, on which api event and locking action traits can be implemented
mod internal_payload_types {
use super::*;
// Serialize is implemented because of api events
#[derive(Debug, serde::Serialize)]
pub struct PaymentsGenericRequestWithResourceId<T: serde::Serialize> {
pub global_payment_id: common_utils::id_type::GlobalPaymentId,
#[serde(flatten)]
pub payload: T,
}
impl<T: serde::Serialize> GetLockingInput for PaymentsGenericRequestWithResourceId<T> {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.global_payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
impl<T: serde::Serialize> common_utils::events::ApiEventMetric
for PaymentsGenericRequestWithResourceId<T>
{
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Payment {
payment_id: self.global_payment_id.clone(),
})
}
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentStartRedirection, payment_id))]
pub async fn payments_start_redirection(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<api_models::payments::PaymentStartRedirectionParams>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
let flow = Flow::PaymentStartRedirection;
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
let publishable_key = &payload.publishable_key;
let profile_id = &payload.profile_id;
let payment_start_redirection_request = api_models::payments::PaymentStartRedirectionRequest {
id: global_payment_id.clone(),
};
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id: global_payment_id.clone(),
payload: payment_start_redirection_request.clone(),
};
let locking_action = internal_payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payment_start_redirection_request.clone(),
|state, auth: auth::AuthenticationData, _req, req_state| async {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payment_start_redirection(
state,
merchant_context,
payment_start_redirection_request.clone(),
)
.await
},
&auth::PublishableKeyAndProfileIdAuth {
publishable_key: publishable_key.clone(),
profile_id: profile_id.clone(),
},
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirmIntent, payment_id))]
pub async fn payment_confirm_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<api_models::payments::PaymentsConfirmIntentRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentConfirmData;
let flow = Flow::PaymentsConfirmIntent;
// TODO: Populate browser information into the payload
// if let Err(err) = helpers::populate_ip_into_browser_info(&req, &mut payload) {
// return api::log_and_return_error_response(err);
// }
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id: global_payment_id.clone(),
payload: json_payload.into_inner(),
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let locking_action = internal_payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| async {
let payment_id = req.global_payment_id;
let request = req.payload;
let operation = payments::operations::PaymentIntentConfirm;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
Box::pin(payments::payments_core::<
api_types::Authorize,
api_models::payments::PaymentsResponse,
_,
_,
_,
PaymentConfirmData<api_types::Authorize>,
>(
state,
req_state,
merchant_context,
auth.profile,
operation,
request,
payment_id,
payments::CallConnectorAction::Trigger,
header_payload.clone(),
))
.await
},
auth::api_or_client_auth(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment(
global_payment_id,
)),
req.headers(),
),
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::GiftCardBalanceCheck, payment_id))]
pub async fn payment_check_gift_card_balance(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<api_models::payments::PaymentsGiftCardBalanceCheckRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
let flow = Flow::GiftCardBalanceCheck;
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id: global_payment_id.clone(),
payload: json_payload.into_inner(),
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| async {
let payment_id = req.global_payment_id;
let request = req.payload;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
Box::pin(gift_card::payments_check_gift_card_balance_core(
state,
merchant_context,
auth.profile,
req_state,
request,
header_payload.clone(),
payment_id,
))
.await
},
auth::api_or_client_auth(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment(
global_payment_id,
)),
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::ProxyConfirmIntent, payment_id))]
pub async fn proxy_confirm_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<api_models::payments::ProxyPaymentsRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentConfirmData;
let flow = Flow::ProxyConfirmIntent;
// Extract the payment ID from the path
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
// Parse and validate headers
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
// Prepare the internal payload
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id,
payload: json_payload.into_inner(),
};
// Determine the locking action, if required
let locking_action = internal_payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let payment_id = req.global_payment_id;
let request = req.payload;
// Define the operation for proxy payments intent
let operation = payments::operations::proxy_payments_intent::PaymentProxyIntent;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
// Call the core proxy logic
Box::pin(payments::proxy_for_payments_core::<
api_types::Authorize,
api_models::payments::PaymentsResponse,
_,
_,
_,
PaymentConfirmData<api_types::Authorize>,
>(
state,
req_state,
merchant_context,
auth.profile,
operation,
request,
payment_id,
payments::CallConnectorAction::Trigger,
header_payload.clone(),
None,
))
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::ProxyConfirmIntent, payment_id))]
pub async fn confirm_intent_with_external_vault_proxy(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<api_models::payments::ExternalVaultProxyPaymentsRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentConfirmData;
let flow = Flow::ProxyConfirmIntent;
// Extract the payment ID from the path
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
// Parse and validate headers
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
// Prepare the internal payload
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id: global_payment_id.clone(),
payload: json_payload.into_inner(),
};
// Determine the locking action, if required
let locking_action = internal_payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let payment_id = req.global_payment_id;
let request = req.payload;
// Define the operation for proxy payments intent
let operation = payments::operations::external_vault_proxy_payment_intent::ExternalVaultProxyPaymentIntent;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
// Call the core proxy logic
Box::pin(payments::external_vault_proxy_for_payments_core::<
api_types::ExternalVaultProxy,
api_models::payments::PaymentsResponse,
_,
_,
_,
PaymentConfirmData<api_types::ExternalVaultProxy>,
>(
state,
req_state,
merchant_context,
auth.profile,
operation,
request,
payment_id,
payments::CallConnectorAction::Trigger,
header_payload.clone(),
None,
))
},
auth::api_or_client_auth(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment(
global_payment_id,
)),
req.headers(),
),
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip(state, req), fields(flow, payment_id))]
pub async fn payment_status(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<api_models::payments::PaymentsStatusRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentStatusData;
let flow = match payload.force_sync {
true => Flow::PaymentsRetrieveForceSync,
false => Flow::PaymentsRetrieve,
};
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
let payload = payment_types::PaymentsRetrieveRequest {
force_sync: payload.force_sync,
expand_attempts: payload.expand_attempts,
param: payload.param.clone(),
return_raw_connector_response: payload.return_raw_connector_response,
merchant_connector_details: None,
};
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id,
payload,
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let locking_action = internal_payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| async {
let payment_id = req.global_payment_id;
let request = req.payload;
let operation = payments::operations::PaymentGet;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
Box::pin(payments::payments_core::<
api_types::PSync,
api_models::payments::PaymentsResponse,
_,
_,
_,
PaymentStatusData<api_types::PSync>,
>(
state,
req_state,
merchant_context,
auth.profile,
operation,
request,
payment_id,
payments::CallConnectorAction::Trigger,
header_payload.clone(),
))
.await
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
req.headers(),
),
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip(state, req), fields(flow, payment_id))]
pub async fn payments_status_with_gateway_creds(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Json<api_models::payments::PaymentsRetrieveRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentStatusData;
let flow = match payload.force_sync {
true => Flow::PaymentsRetrieveForceSync,
false => Flow::PaymentsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id,
payload: payload.into_inner(),
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let locking_action = internal_payload.get_locking_input(flow.clone());
let auth_type = if state.conf.merchant_id_auth.merchant_id_auth_enabled {
&auth::MerchantIdAuth
} else {
match env::which() {
env::Env::Production => &auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
_ => auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentWrite,
},
req.headers(),
),
}
};
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| async {
let payment_id = req.global_payment_id;
let request = req.payload;
let operation = payments::operations::PaymentGet;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
Box::pin(payments::payments_core::<
api_types::PSync,
api_models::payments::PaymentsResponse,
_,
_,
_,
PaymentStatusData<api_types::PSync>,
>(
state,
req_state,
merchant_context,
auth.profile,
operation,
request,
payment_id,
payments::CallConnectorAction::Trigger,
header_payload.clone(),
))
.await
},
auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip(state, req), fields(flow, payment_id))]
pub async fn payment_get_intent_using_merchant_reference_id(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::PaymentReferenceId>,
) -> impl Responder {
use crate::db::domain::merchant_context;
let flow = Flow::PaymentsRetrieveUsingMerchantReferenceId;
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let merchant_reference_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, req_state| async {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
Box::pin(payments::payments_get_intent_using_merchant_reference(
state,
merchant_context,
auth.profile,
req_state,
&merchant_reference_id,
header_payload.clone(),
))
.await
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsRedirect, payment_id))]
pub async fn payments_finish_redirection(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
path: web::Path<(
common_utils::id_type::GlobalPaymentId,
String,
common_utils::id_type::ProfileId,
)>,
) -> impl Responder {
let flow = Flow::PaymentsRedirect;
let (payment_id, publishable_key, profile_id) = path.into_inner();
let param_string = req.query_string();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let payload = payments::PaymentsRedirectResponseData {
payment_id,
json_payload: json_payload.map(|payload| payload.0),
query_params: param_string.to_string(),
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
<payments::PaymentRedirectSync as PaymentRedirectFlow>::handle_payments_redirect_response(
&payments::PaymentRedirectSync {},
state,
req_state,
merchant_context,
auth.profile,
req,
)
},
&auth::PublishableKeyAndProfileIdAuth {
publishable_key: publishable_key.clone(),
profile_id: profile_id.clone(),
},
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip(state, req), fields(flow, payment_id))]
pub async fn payments_capture(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Json<api_models::payments::PaymentsCaptureRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentCaptureData;
let flow = Flow::PaymentsCapture;
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id,
payload: payload.into_inner(),
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let locking_action = internal_payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| async {
let payment_id = req.global_payment_id;
let request = req.payload;
let operation = payments::operations::payment_capture_v2::PaymentsCapture;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
Box::pin(payments::payments_core::<
api_types::Capture,
api_models::payments::PaymentsCaptureResponse,
_,
_,
_,
PaymentCaptureData<api_types::Capture>,
>(
state,
req_state,
merchant_context,
auth.profile,
operation,
request,
payment_id,
payments::CallConnectorAction::Trigger,
header_payload.clone(),
))
.await
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileAccountWrite,
},
req.headers(),
),
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))]
pub async fn list_payment_methods(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
query_payload: web::Query<api_models::payments::ListMethodsForPaymentsRequest>,
) -> impl Responder {
use crate::db::domain::merchant_context;
let flow = Flow::PaymentMethodsList;
let payload = query_payload.into_inner();
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id: global_payment_id.clone(),
payload,
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payment_methods::list_payment_methods(
state,
merchant_context,
auth.profile,
req.global_payment_id,
req.payload,
&header_payload,
)
},
&auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment(
global_payment_id,
)),
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": "crates/router/src/routes/payments.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_2125169837521839707 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/routes/app.rs
// Contains: 3 structs, 0 enums
use std::{collections::HashMap, sync::Arc};
use actix_web::{web, Scope};
#[cfg(all(feature = "olap", feature = "v1"))]
use api_models::routing::RoutingRetrieveQuery;
use api_models::routing::RuleMigrationQuery;
#[cfg(feature = "olap")]
use common_enums::{ExecutionMode, TransactionType};
#[cfg(feature = "partial-auth")]
use common_utils::crypto::Blake3;
use common_utils::{id_type, types::TenantConfig};
#[cfg(feature = "email")]
use external_services::email::{
no_email::NoEmailClient, ses::AwsSes, smtp::SmtpServer, EmailClientConfigs, EmailService,
};
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
use external_services::grpc_client::revenue_recovery::GrpcRecoveryHeaders;
use external_services::{
file_storage::FileStorageInterface,
grpc_client::{GrpcClients, GrpcHeaders, GrpcHeadersUcs, GrpcHeadersUcsBuilderInitial},
superposition::SuperpositionClient,
};
use hyperswitch_interfaces::{
crm::CrmInterface,
encryption_interface::EncryptionManagementInterface,
secrets_interface::secret_state::{RawSecret, SecuredSecret},
};
use router_env::tracing_actix_web::RequestId;
use scheduler::SchedulerInterface;
use storage_impl::{redis::RedisStore, MockDb};
use tokio::sync::oneshot;
use self::settings::Tenant;
#[cfg(any(feature = "olap", feature = "oltp"))]
use super::currency;
#[cfg(feature = "dummy_connector")]
use super::dummy_connector::*;
#[cfg(all(any(feature = "v1", feature = "v2"), feature = "oltp"))]
use super::ephemeral_key::*;
#[cfg(any(feature = "olap", feature = "oltp"))]
use super::payment_methods;
#[cfg(feature = "payouts")]
use super::payout_link::*;
#[cfg(feature = "payouts")]
use super::payouts::*;
#[cfg(all(feature = "oltp", feature = "v1"))]
use super::pm_auth;
#[cfg(feature = "oltp")]
use super::poll;
#[cfg(feature = "v2")]
use super::proxy;
#[cfg(all(feature = "v2", feature = "revenue_recovery", feature = "oltp"))]
use super::recovery_webhooks::*;
#[cfg(all(feature = "oltp", feature = "v2"))]
use super::refunds;
#[cfg(feature = "olap")]
use super::routing;
#[cfg(all(feature = "oltp", feature = "v2"))]
use super::tokenization as tokenization_routes;
#[cfg(all(feature = "olap", any(feature = "v1", feature = "v2")))]
use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains};
#[cfg(feature = "oltp")]
use super::webhooks::*;
use super::{
admin, api_keys, cache::*, chat, connector_onboarding, disputes, files, gsm, health::*,
profiles, relay, user, user_role,
};
#[cfg(feature = "v1")]
use super::{
apple_pay_certificates_migration, blocklist, payment_link, subscription, webhook_events,
};
#[cfg(any(feature = "olap", feature = "oltp"))]
use super::{configs::*, customers, payments};
#[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v1"))]
use super::{mandates::*, refunds::*};
#[cfg(feature = "olap")]
pub use crate::analytics::opensearch::OpenSearchClient;
#[cfg(feature = "olap")]
use crate::analytics::AnalyticsProvider;
#[cfg(feature = "partial-auth")]
use crate::errors::RouterResult;
#[cfg(feature = "oltp")]
use crate::routes::authentication;
#[cfg(feature = "v1")]
use crate::routes::cards_info::{
card_iin_info, create_cards_info, migrate_cards_info, update_cards_info,
};
#[cfg(all(feature = "olap", feature = "v1"))]
use crate::routes::feature_matrix;
#[cfg(all(feature = "frm", feature = "oltp"))]
use crate::routes::fraud_check as frm_routes;
#[cfg(all(feature = "olap", feature = "v1"))]
use crate::routes::profile_acquirer;
#[cfg(all(feature = "recon", feature = "olap"))]
use crate::routes::recon as recon_routes;
pub use crate::{
configs::settings,
db::{
AccountsStorageInterface, CommonStorageInterface, GlobalStorageInterface, StorageImpl,
StorageInterface,
},
events::EventsHandler,
services::{get_cache_store, get_store},
};
use crate::{
configs::{secrets_transformers, Settings},
db::kafka_store::{KafkaStore, TenantID},
routes::{hypersense as hypersense_routes, three_ds_decision_rule},
};
#[derive(Clone)]
pub struct ReqState {
pub event_context: events::EventContext<crate::events::EventType, EventsHandler>,
}
#[derive(Clone)]
pub struct SessionState {
pub store: Box<dyn StorageInterface>,
/// Global store is used for global schema operations in tables like Users and Tenants
pub global_store: Box<dyn GlobalStorageInterface>,
pub accounts_store: Box<dyn AccountsStorageInterface>,
pub conf: Arc<settings::Settings<RawSecret>>,
pub api_client: Box<dyn crate::services::ApiClient>,
pub event_handler: EventsHandler,
#[cfg(feature = "email")]
pub email_client: Arc<Box<dyn EmailService>>,
#[cfg(feature = "olap")]
pub pool: AnalyticsProvider,
pub file_storage_client: Arc<dyn FileStorageInterface>,
pub request_id: Option<RequestId>,
pub base_url: String,
pub tenant: Tenant,
#[cfg(feature = "olap")]
pub opensearch_client: Option<Arc<OpenSearchClient>>,
pub grpc_client: Arc<GrpcClients>,
pub theme_storage_client: Arc<dyn FileStorageInterface>,
pub locale: String,
pub crm_client: Arc<dyn CrmInterface>,
pub infra_components: Option<serde_json::Value>,
pub enhancement: Option<HashMap<String, String>>,
pub superposition_service: Option<Arc<SuperpositionClient>>,
}
impl scheduler::SchedulerSessionState for SessionState {
fn get_db(&self) -> Box<dyn SchedulerInterface> {
self.store.get_scheduler_db()
}
}
impl SessionState {
pub fn get_req_state(&self) -> ReqState {
ReqState {
event_context: events::EventContext::new(self.event_handler.clone()),
}
}
pub fn get_grpc_headers(&self) -> GrpcHeaders {
GrpcHeaders {
tenant_id: self.tenant.tenant_id.get_string_repr().to_string(),
request_id: self.request_id.map(|req_id| (*req_id).to_string()),
}
}
pub fn get_grpc_headers_ucs(
&self,
unified_connector_service_execution_mode: ExecutionMode,
) -> GrpcHeadersUcsBuilderInitial {
let tenant_id = self.tenant.tenant_id.get_string_repr().to_string();
let request_id = self.request_id.map(|req_id| (*req_id).to_string());
let shadow_mode = match unified_connector_service_execution_mode {
ExecutionMode::Primary => false,
ExecutionMode::Shadow => true,
};
GrpcHeadersUcs::builder()
.tenant_id(tenant_id)
.request_id(request_id)
.shadow_mode(Some(shadow_mode))
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
pub fn get_recovery_grpc_headers(&self) -> GrpcRecoveryHeaders {
GrpcRecoveryHeaders {
request_id: self.request_id.map(|req_id| (*req_id).to_string()),
}
}
}
pub trait SessionStateInfo {
fn conf(&self) -> settings::Settings<RawSecret>;
fn store(&self) -> Box<dyn StorageInterface>;
fn event_handler(&self) -> EventsHandler;
fn get_request_id(&self) -> Option<String>;
fn add_request_id(&mut self, request_id: RequestId);
#[cfg(feature = "partial-auth")]
fn get_detached_auth(&self) -> RouterResult<(Blake3, &[u8])>;
fn session_state(&self) -> SessionState;
fn global_store(&self) -> Box<dyn GlobalStorageInterface>;
}
impl SessionStateInfo for SessionState {
fn store(&self) -> Box<dyn StorageInterface> {
self.store.to_owned()
}
fn conf(&self) -> settings::Settings<RawSecret> {
self.conf.as_ref().to_owned()
}
fn event_handler(&self) -> EventsHandler {
self.event_handler.clone()
}
fn get_request_id(&self) -> Option<String> {
self.api_client.get_request_id_str()
}
fn add_request_id(&mut self, request_id: RequestId) {
self.api_client.add_request_id(request_id);
self.store.add_request_id(request_id.to_string());
self.request_id.replace(request_id);
}
#[cfg(feature = "partial-auth")]
fn get_detached_auth(&self) -> RouterResult<(Blake3, &[u8])> {
use error_stack::ResultExt;
use hyperswitch_domain_models::errors::api_error_response as errors;
use masking::prelude::PeekInterface as _;
use router_env::logger;
let output = CHECKSUM_KEY.get_or_try_init(|| {
let conf = self.conf();
let context = conf
.api_keys
.get_inner()
.checksum_auth_context
.peek()
.clone();
let key = conf.api_keys.get_inner().checksum_auth_key.peek();
hex::decode(key).map(|key| {
(
masking::StrongSecret::new(context),
masking::StrongSecret::new(key),
)
})
});
match output {
Ok((context, key)) => Ok((Blake3::new(context.peek().clone()), key.peek())),
Err(err) => {
logger::error!("Failed to get checksum key");
Err(err).change_context(errors::ApiErrorResponse::InternalServerError)
}
}
}
fn session_state(&self) -> SessionState {
self.clone()
}
fn global_store(&self) -> Box<dyn GlobalStorageInterface> {
self.global_store.to_owned()
}
}
impl hyperswitch_interfaces::api_client::ApiClientWrapper for SessionState {
fn get_api_client(&self) -> &dyn crate::services::ApiClient {
self.api_client.as_ref()
}
fn get_proxy(&self) -> hyperswitch_interfaces::types::Proxy {
self.conf.proxy.clone()
}
fn get_request_id(&self) -> Option<RequestId> {
self.request_id
}
fn get_request_id_str(&self) -> Option<String> {
self.request_id
.map(|req_id| req_id.as_hyphenated().to_string())
}
fn get_tenant(&self) -> Tenant {
self.tenant.clone()
}
fn get_connectors(&self) -> hyperswitch_domain_models::connector_endpoints::Connectors {
self.conf.connectors.clone()
}
fn event_handler(&self) -> &dyn hyperswitch_interfaces::events::EventHandlerInterface {
&self.event_handler
}
}
#[derive(Clone)]
pub struct AppState {
pub flow_name: String,
pub global_store: Box<dyn GlobalStorageInterface>,
// TODO: use a separate schema for accounts_store
pub accounts_store: HashMap<id_type::TenantId, Box<dyn AccountsStorageInterface>>,
pub stores: HashMap<id_type::TenantId, Box<dyn StorageInterface>>,
pub conf: Arc<settings::Settings<RawSecret>>,
pub event_handler: EventsHandler,
#[cfg(feature = "email")]
pub email_client: Arc<Box<dyn EmailService>>,
pub api_client: Box<dyn crate::services::ApiClient>,
#[cfg(feature = "olap")]
pub pools: HashMap<id_type::TenantId, AnalyticsProvider>,
#[cfg(feature = "olap")]
pub opensearch_client: Option<Arc<OpenSearchClient>>,
pub request_id: Option<RequestId>,
pub file_storage_client: Arc<dyn FileStorageInterface>,
pub encryption_client: Arc<dyn EncryptionManagementInterface>,
pub grpc_client: Arc<GrpcClients>,
pub theme_storage_client: Arc<dyn FileStorageInterface>,
pub crm_client: Arc<dyn CrmInterface>,
pub infra_components: Option<serde_json::Value>,
pub enhancement: Option<HashMap<String, String>>,
pub superposition_service: Option<Arc<SuperpositionClient>>,
}
impl scheduler::SchedulerAppState for AppState {
fn get_tenants(&self) -> Vec<id_type::TenantId> {
self.conf.multitenancy.get_tenant_ids()
}
}
pub trait AppStateInfo {
fn conf(&self) -> settings::Settings<RawSecret>;
fn event_handler(&self) -> EventsHandler;
#[cfg(feature = "email")]
fn email_client(&self) -> Arc<Box<dyn EmailService>>;
fn add_request_id(&mut self, request_id: RequestId);
fn add_flow_name(&mut self, flow_name: String);
fn get_request_id(&self) -> Option<String>;
}
#[cfg(feature = "partial-auth")]
static CHECKSUM_KEY: once_cell::sync::OnceCell<(
masking::StrongSecret<String>,
masking::StrongSecret<Vec<u8>>,
)> = once_cell::sync::OnceCell::new();
impl AppStateInfo for AppState {
fn conf(&self) -> settings::Settings<RawSecret> {
self.conf.as_ref().to_owned()
}
#[cfg(feature = "email")]
fn email_client(&self) -> Arc<Box<dyn EmailService>> {
self.email_client.to_owned()
}
fn event_handler(&self) -> EventsHandler {
self.event_handler.clone()
}
fn add_request_id(&mut self, request_id: RequestId) {
self.api_client.add_request_id(request_id);
self.request_id.replace(request_id);
}
fn add_flow_name(&mut self, flow_name: String) {
self.api_client.add_flow_name(flow_name);
}
fn get_request_id(&self) -> Option<String> {
self.api_client.get_request_id_str()
}
}
impl AsRef<Self> for AppState {
fn as_ref(&self) -> &Self {
self
}
}
#[cfg(feature = "email")]
pub async fn create_email_client(
settings: &settings::Settings<RawSecret>,
) -> Box<dyn EmailService> {
match &settings.email.client_config {
EmailClientConfigs::Ses { aws_ses } => Box::new(
AwsSes::create(
&settings.email,
aws_ses,
settings.proxy.https_url.to_owned(),
)
.await,
),
EmailClientConfigs::Smtp { smtp } => {
Box::new(SmtpServer::create(&settings.email, smtp.clone()).await)
}
EmailClientConfigs::NoEmailClient => Box::new(NoEmailClient::create().await),
}
}
impl AppState {
/// # Panics
///
/// Panics if Store can't be created or JWE decryption fails
pub async fn with_storage(
conf: settings::Settings<SecuredSecret>,
storage_impl: StorageImpl,
shut_down_signal: oneshot::Sender<()>,
api_client: Box<dyn crate::services::ApiClient>,
) -> Self {
#[allow(clippy::expect_used)]
let secret_management_client = conf
.secrets_management
.get_secret_management_client()
.await
.expect("Failed to create secret management client");
let conf = Box::pin(secrets_transformers::fetch_raw_secrets(
conf,
&*secret_management_client,
))
.await;
#[allow(clippy::expect_used)]
let encryption_client = conf
.encryption_management
.get_encryption_management_client()
.await
.expect("Failed to create encryption client");
Box::pin(async move {
let testable = storage_impl == StorageImpl::PostgresqlTest;
#[allow(clippy::expect_used)]
let event_handler = conf
.events
.get_event_handler()
.await
.expect("Failed to create event handler");
#[allow(clippy::expect_used)]
#[cfg(feature = "olap")]
let opensearch_client = conf
.opensearch
.get_opensearch_client()
.await
.expect("Failed to initialize OpenSearch client.")
.map(Arc::new);
#[allow(clippy::expect_used)]
let cache_store = get_cache_store(&conf.clone(), shut_down_signal, testable)
.await
.expect("Failed to create store");
let global_store: Box<dyn GlobalStorageInterface> = Self::get_store_interface(
&storage_impl,
&event_handler,
&conf,
&conf.multitenancy.global_tenant,
Arc::clone(&cache_store),
testable,
)
.await
.get_global_storage_interface();
#[cfg(feature = "olap")]
let pools = conf
.multitenancy
.tenants
.get_pools_map(conf.analytics.get_inner())
.await;
let stores = conf
.multitenancy
.tenants
.get_store_interface_map(&storage_impl, &conf, Arc::clone(&cache_store), testable)
.await;
let accounts_store = conf
.multitenancy
.tenants
.get_accounts_store_interface_map(
&storage_impl,
&conf,
Arc::clone(&cache_store),
testable,
)
.await;
#[cfg(feature = "email")]
let email_client = Arc::new(create_email_client(&conf).await);
let file_storage_client = conf.file_storage.get_file_storage_client().await;
let theme_storage_client = conf.theme.storage.get_file_storage_client().await;
let crm_client = conf.crm.get_crm_client().await;
let grpc_client = conf.grpc_client.get_grpc_client_interface().await;
let infra_component_values = Self::process_env_mappings(conf.infra_values.clone());
let enhancement = conf.enhancement.clone();
let superposition_service = if conf.superposition.get_inner().enabled {
match SuperpositionClient::new(conf.superposition.get_inner().clone()).await {
Ok(client) => {
router_env::logger::info!("Superposition client initialized successfully");
Some(Arc::new(client))
}
Err(err) => {
router_env::logger::warn!(
"Failed to initialize superposition client: {:?}. Continuing without superposition support.",
err
);
None
}
}
} else {
None
};
Self {
flow_name: String::from("default"),
stores,
global_store,
accounts_store,
conf: Arc::new(conf),
#[cfg(feature = "email")]
email_client,
api_client,
event_handler,
#[cfg(feature = "olap")]
pools,
#[cfg(feature = "olap")]
opensearch_client,
request_id: None,
file_storage_client,
encryption_client,
grpc_client,
theme_storage_client,
crm_client,
infra_components: infra_component_values,
enhancement,
superposition_service,
}
})
.await
}
/// # Panics
///
/// Panics if Failed to create store
pub async fn get_store_interface(
storage_impl: &StorageImpl,
event_handler: &EventsHandler,
conf: &Settings,
tenant: &dyn TenantConfig,
cache_store: Arc<RedisStore>,
testable: bool,
) -> Box<dyn CommonStorageInterface> {
match storage_impl {
StorageImpl::Postgresql | StorageImpl::PostgresqlTest => match event_handler {
EventsHandler::Kafka(kafka_client) => Box::new(
KafkaStore::new(
#[allow(clippy::expect_used)]
get_store(&conf.clone(), tenant, Arc::clone(&cache_store), testable)
.await
.expect("Failed to create store"),
kafka_client.clone(),
TenantID(tenant.get_tenant_id().get_string_repr().to_owned()),
tenant,
)
.await,
),
EventsHandler::Logs(_) => Box::new(
#[allow(clippy::expect_used)]
get_store(conf, tenant, Arc::clone(&cache_store), testable)
.await
.expect("Failed to create store"),
),
},
#[allow(clippy::expect_used)]
StorageImpl::Mock => Box::new(
MockDb::new(&conf.redis)
.await
.expect("Failed to create mock store"),
),
}
}
pub async fn new(
conf: settings::Settings<SecuredSecret>,
shut_down_signal: oneshot::Sender<()>,
api_client: Box<dyn crate::services::ApiClient>,
) -> Self {
Box::pin(Self::with_storage(
conf,
StorageImpl::Postgresql,
shut_down_signal,
api_client,
))
.await
}
pub fn get_session_state<E, F>(
self: Arc<Self>,
tenant: &id_type::TenantId,
locale: Option<String>,
err: F,
) -> Result<SessionState, E>
where
F: FnOnce() -> E + Copy,
{
let tenant_conf = self.conf.multitenancy.get_tenant(tenant).ok_or_else(err)?;
let mut event_handler = self.event_handler.clone();
event_handler.add_tenant(tenant_conf);
let store = self.stores.get(tenant).ok_or_else(err)?.clone();
Ok(SessionState {
store,
global_store: self.global_store.clone(),
accounts_store: self.accounts_store.get(tenant).ok_or_else(err)?.clone(),
conf: Arc::clone(&self.conf),
api_client: self.api_client.clone(),
event_handler,
#[cfg(feature = "olap")]
pool: self.pools.get(tenant).ok_or_else(err)?.clone(),
file_storage_client: self.file_storage_client.clone(),
request_id: self.request_id,
base_url: tenant_conf.base_url.clone(),
tenant: tenant_conf.clone(),
#[cfg(feature = "email")]
email_client: Arc::clone(&self.email_client),
#[cfg(feature = "olap")]
opensearch_client: self.opensearch_client.clone(),
grpc_client: Arc::clone(&self.grpc_client),
theme_storage_client: self.theme_storage_client.clone(),
locale: locale.unwrap_or(common_utils::consts::DEFAULT_LOCALE.to_string()),
crm_client: self.crm_client.clone(),
infra_components: self.infra_components.clone(),
enhancement: self.enhancement.clone(),
superposition_service: self.superposition_service.clone(),
})
}
pub fn process_env_mappings(
mappings: Option<HashMap<String, String>>,
) -> Option<serde_json::Value> {
let result: HashMap<String, String> = mappings?
.into_iter()
.filter_map(|(key, env_var)| std::env::var(&env_var).ok().map(|value| (key, value)))
.collect();
if result.is_empty() {
None
} else {
Some(serde_json::Value::Object(
result
.into_iter()
.map(|(k, v)| (k, serde_json::Value::String(v)))
.collect(),
))
}
}
}
pub struct Health;
#[cfg(feature = "v1")]
impl Health {
pub fn server(state: AppState) -> Scope {
web::scope("health")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::get().to(health)))
.service(web::resource("/ready").route(web::get().to(deep_health_check)))
}
}
#[cfg(feature = "v2")]
impl Health {
pub fn server(state: AppState) -> Scope {
web::scope("/v2/health")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::get().to(health)))
.service(web::resource("/ready").route(web::get().to(deep_health_check)))
}
}
#[cfg(feature = "dummy_connector")]
pub struct DummyConnector;
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
impl DummyConnector {
pub fn server(state: AppState) -> Scope {
let mut routes_with_restricted_access = web::scope("");
#[cfg(not(feature = "external_access_dc"))]
{
routes_with_restricted_access =
routes_with_restricted_access.guard(actix_web::guard::Host("localhost"));
}
routes_with_restricted_access = routes_with_restricted_access
.service(web::resource("/payment").route(web::post().to(dummy_connector_payment)))
.service(
web::resource("/payments/{payment_id}")
.route(web::get().to(dummy_connector_payment_data)),
)
.service(
web::resource("/{payment_id}/refund").route(web::post().to(dummy_connector_refund)),
)
.service(
web::resource("/refunds/{refund_id}")
.route(web::get().to(dummy_connector_refund_data)),
);
web::scope("/dummy-connector")
.app_data(web::Data::new(state))
.service(
web::resource("/authorize/{attempt_id}")
.route(web::get().to(dummy_connector_authorize_payment)),
)
.service(
web::resource("/complete/{attempt_id}")
.route(web::get().to(dummy_connector_complete_payment)),
)
.service(routes_with_restricted_access)
}
}
#[cfg(all(feature = "dummy_connector", feature = "v2"))]
impl DummyConnector {
pub fn server(state: AppState) -> Scope {
let mut routes_with_restricted_access = web::scope("");
#[cfg(not(feature = "external_access_dc"))]
{
routes_with_restricted_access =
routes_with_restricted_access.guard(actix_web::guard::Host("localhost"));
}
routes_with_restricted_access = routes_with_restricted_access
.service(web::resource("/payment").route(web::post().to(dummy_connector_payment)));
web::scope("/dummy-connector")
.app_data(web::Data::new(state))
.service(routes_with_restricted_access)
}
}
pub struct Payments;
#[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v2"))]
impl Payments {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/v2/payments").app_data(web::Data::new(state));
route = route
.service(
web::resource("/create-intent")
.route(web::post().to(payments::payments_create_intent)),
)
.service(web::resource("/filter").route(web::get().to(payments::get_payment_filters)))
.service(
web::resource("/profile/filter")
.route(web::get().to(payments::get_payment_filters_profile)),
)
.service(
web::resource("")
.route(web::post().to(payments::payments_create_and_confirm_intent)),
)
.service(web::resource("/list").route(web::get().to(payments::payments_list)))
.service(
web::resource("/aggregate").route(web::get().to(payments::get_payments_aggregates)),
)
.service(
web::resource("/recovery")
.route(web::post().to(payments::recovery_payments_create)),
)
.service(
web::resource("/profile/aggregate")
.route(web::get().to(payments::get_payments_aggregates_profile)),
);
route =
route
.service(web::resource("/ref/{merchant_reference_id}").route(
web::get().to(payments::payment_get_intent_using_merchant_reference_id),
));
route = route.service(
web::scope("/{payment_id}")
.service(
web::resource("/confirm-intent")
.route(web::post().to(payments::payment_confirm_intent)),
)
// TODO: Deprecated. Remove this in favour of /list-attempts
.service(
web::resource("/list_attempts")
.route(web::get().to(payments::list_payment_attempts)),
)
.service(
web::resource("/list-attempts")
.route(web::get().to(payments::list_payment_attempts)),
)
.service(
web::resource("/proxy-confirm-intent")
.route(web::post().to(payments::proxy_confirm_intent)),
)
.service(
web::resource("/confirm-intent/external-vault-proxy")
.route(web::post().to(payments::confirm_intent_with_external_vault_proxy)),
)
.service(
web::resource("/get-intent")
.route(web::get().to(payments::payments_get_intent)),
)
.service(
web::resource("/update-intent")
.route(web::put().to(payments::payments_update_intent)),
)
.service(
web::resource("/create-external-sdk-tokens")
.route(web::post().to(payments::payments_connector_session)),
)
.service(
web::resource("")
.route(web::get().to(payments::payment_status))
.route(web::post().to(payments::payments_status_with_gateway_creds)),
)
.service(
web::resource("/start-redirection")
.route(web::get().to(payments::payments_start_redirection)),
)
.service(
web::resource("/payment-methods")
.route(web::get().to(payments::list_payment_methods)),
)
.service(
web::resource("/finish-redirection/{publishable_key}/{profile_id}")
.route(web::get().to(payments::payments_finish_redirection)),
)
.service(
web::resource("/capture").route(web::post().to(payments::payments_capture)),
)
.service(
web::resource("/check-gift-card-balance")
.route(web::post().to(payments::payment_check_gift_card_balance)),
)
.service(web::resource("/cancel").route(web::post().to(payments::payments_cancel))),
);
route
}
}
pub struct Relay;
#[cfg(feature = "oltp")]
impl Relay {
pub fn server(state: AppState) -> Scope {
web::scope("/relay")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(relay::relay)))
.service(web::resource("/{relay_id}").route(web::get().to(relay::relay_retrieve)))
}
}
#[cfg(feature = "v2")]
pub struct Proxy;
#[cfg(all(feature = "oltp", feature = "v2"))]
impl Proxy {
pub fn server(state: AppState) -> Scope {
web::scope("/v2/proxy")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(proxy::proxy)))
}
}
#[cfg(feature = "v1")]
impl Payments {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/payments").app_data(web::Data::new(state));
#[cfg(feature = "olap")]
{
route = route
.service(
web::resource("/list")
.route(web::get().to(payments::payments_list))
.route(web::post().to(payments::payments_list_by_filter)),
)
.service(
web::resource("/profile/list")
.route(web::get().to(payments::profile_payments_list))
.route(web::post().to(payments::profile_payments_list_by_filter)),
)
.service(
web::resource("/filter")
.route(web::post().to(payments::get_filters_for_payments)),
)
.service(
web::resource("/v2/filter").route(web::get().to(payments::get_payment_filters)),
)
.service(
web::resource("/aggregate")
.route(web::get().to(payments::get_payments_aggregates)),
)
.service(
web::resource("/profile/aggregate")
.route(web::get().to(payments::get_payments_aggregates_profile)),
)
.service(
web::resource("/v2/profile/filter")
.route(web::get().to(payments::get_payment_filters_profile)),
)
.service(
web::resource("/{payment_id}/manual-update")
.route(web::put().to(payments::payments_manual_update)),
)
}
#[cfg(feature = "oltp")]
{
route = route
.service(web::resource("").route(web::post().to(payments::payments_create)))
.service(
web::resource("/session_tokens")
.route(web::post().to(payments::payments_connector_session)),
)
.service(
web::resource("/sync")
.route(web::post().to(payments::payments_retrieve_with_gateway_creds)),
)
.service(
web::resource("/{payment_id}")
.route(web::get().to(payments::payments_retrieve))
.route(web::post().to(payments::payments_update)),
)
.service(
web::resource("/{payment_id}/post_session_tokens").route(web::post().to(payments::payments_post_session_tokens)),
)
.service(
web::resource("/{payment_id}/confirm").route(web::post().to(payments::payments_confirm)),
)
.service(
web::resource("/{payment_id}/cancel").route(web::post().to(payments::payments_cancel)),
)
.service(
web::resource("/{payment_id}/cancel_post_capture").route(web::post().to(payments::payments_cancel_post_capture)),
)
.service(
web::resource("/{payment_id}/capture").route(web::post().to(payments::payments_capture)),
)
.service(
web::resource("/{payment_id}/approve")
.route(web::post().to(payments::payments_approve)),
)
.service(
web::resource("/{payment_id}/reject")
.route(web::post().to(payments::payments_reject)),
)
.service(
web::resource("/{payment_id}/eligibility")
.route(web::post().to(payments::payments_submit_eligibility)),
)
.service(
web::resource("/redirect/{payment_id}/{merchant_id}/{attempt_id}")
.route(web::get().to(payments::payments_start)),
)
.service(
web::resource(
"/{payment_id}/{merchant_id}/redirect/response/{connector}/{creds_identifier}",
)
.route(web::get().to(payments::payments_redirect_response_with_creds_identifier)),
)
.service(
web::resource("/{payment_id}/{merchant_id}/redirect/response/{connector}")
.route(web::get().to(payments::payments_redirect_response))
.route(web::post().to(payments::payments_redirect_response))
)
.service(
web::resource("/{payment_id}/{merchant_id}/redirect/complete/{connector}/{creds_identifier}")
.route(web::get().to(payments::payments_complete_authorize_redirect_with_creds_identifier))
.route(web::post().to(payments::payments_complete_authorize_redirect_with_creds_identifier))
)
.service(
web::resource("/{payment_id}/{merchant_id}/redirect/complete/{connector}")
.route(web::get().to(payments::payments_complete_authorize_redirect))
.route(web::post().to(payments::payments_complete_authorize_redirect)),
)
.service(
web::resource("/{payment_id}/complete_authorize")
.route(web::post().to(payments::payments_complete_authorize)),
)
.service(
web::resource("/{payment_id}/incremental_authorization").route(web::post().to(payments::payments_incremental_authorization)),
)
.service(
web::resource("/{payment_id}/extend_authorization").route(web::post().to(payments::payments_extend_authorization)),
)
.service(
web::resource("/{payment_id}/{merchant_id}/authorize/{connector}")
.route(web::post().to(payments::post_3ds_payments_authorize))
.route(web::get().to(payments::post_3ds_payments_authorize))
)
.service(
web::resource("/{payment_id}/3ds/authentication").route(web::post().to(payments::payments_external_authentication)),
)
.service(
web::resource("/{payment_id}/extended_card_info").route(web::get().to(payments::retrieve_extended_card_info)),
)
.service(
web::resource("{payment_id}/calculate_tax")
.route(web::post().to(payments::payments_dynamic_tax_calculation)),
)
.service(
web::resource("{payment_id}/update_metadata")
.route(web::post().to(payments::payments_update_metadata)),
);
}
route
}
}
#[cfg(any(feature = "olap", feature = "oltp"))]
pub struct Forex;
#[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v1"))]
impl Forex {
pub fn server(state: AppState) -> Scope {
web::scope("/forex")
.app_data(web::Data::new(state.clone()))
.app_data(web::Data::new(state.clone()))
.service(web::resource("/rates").route(web::get().to(currency::retrieve_forex)))
.service(
web::resource("/convert_from_minor").route(web::get().to(currency::convert_forex)),
)
}
}
#[cfg(feature = "olap")]
pub struct Routing;
#[cfg(all(feature = "olap", feature = "v2"))]
impl Routing {
pub fn server(state: AppState) -> Scope {
web::scope("/v2/routing-algorithms")
.app_data(web::Data::new(state.clone()))
.service(
web::resource("").route(web::post().to(|state, req, payload| {
routing::routing_create_config(state, req, payload, TransactionType::Payment)
})),
)
.service(
web::resource("/{algorithm_id}")
.route(web::get().to(routing::routing_retrieve_config)),
)
}
}
#[cfg(all(feature = "olap", feature = "v1"))]
impl Routing {
pub fn server(state: AppState) -> Scope {
#[allow(unused_mut)]
let mut route = web::scope("/routing")
.app_data(web::Data::new(state.clone()))
.service(
web::resource("/active").route(web::get().to(|state, req, query_params| {
routing::routing_retrieve_linked_config(state, req, query_params, None)
})),
)
.service(
web::resource("")
.route(
web::get().to(|state, req, path: web::Query<RoutingRetrieveQuery>| {
routing::list_routing_configs(state, req, path, None)
}),
)
.route(web::post().to(|state, req, payload| {
routing::routing_create_config(state, req, payload, None)
})),
)
.service(web::resource("/list/profile").route(web::get().to(
|state, req, query: web::Query<RoutingRetrieveQuery>| {
routing::list_routing_configs_for_profile(state, req, query, None)
},
)))
.service(
web::resource("/default").route(web::post().to(|state, req, payload| {
routing::routing_update_default_config(
state,
req,
payload,
&TransactionType::Payment,
)
})),
)
.service(web::resource("/rule/migrate").route(web::post().to(
|state, req, query: web::Query<RuleMigrationQuery>| {
routing::migrate_routing_rules_for_profile(state, req, query)
},
)))
.service(
web::resource("/deactivate").route(web::post().to(|state, req, payload| {
routing::routing_unlink_config(state, req, payload, None)
})),
)
.service(
web::resource("/decision")
.route(web::put().to(routing::upsert_decision_manager_config))
.route(web::get().to(routing::retrieve_decision_manager_config))
.route(web::delete().to(routing::delete_decision_manager_config)),
)
.service(
web::resource("/decision/surcharge")
.route(web::put().to(routing::upsert_surcharge_decision_manager_config))
.route(web::get().to(routing::retrieve_surcharge_decision_manager_config))
.route(web::delete().to(routing::delete_surcharge_decision_manager_config)),
)
.service(
web::resource("/default/profile/{profile_id}").route(web::post().to(
|state, req, path, payload| {
routing::routing_update_default_config_for_profile(
state,
req,
path,
payload,
&TransactionType::Payment,
)
},
)),
)
.service(
web::resource("/default/profile").route(web::get().to(|state, req| {
routing::routing_retrieve_default_config(state, req, &TransactionType::Payment)
})),
);
#[cfg(feature = "dynamic_routing")]
{
route = route
.service(
web::resource("/evaluate")
.route(web::post().to(routing::call_decide_gateway_open_router)),
)
.service(
web::resource("/feedback")
.route(web::post().to(routing::call_update_gateway_score_open_router)),
)
}
#[cfg(feature = "payouts")]
{
route = route
.service(
web::resource("/payouts")
.route(web::get().to(
|state, req, path: web::Query<RoutingRetrieveQuery>| {
routing::list_routing_configs(
state,
req,
path,
Some(TransactionType::Payout),
)
},
))
.route(web::post().to(|state, req, payload| {
routing::routing_create_config(
state,
req,
payload,
Some(TransactionType::Payout),
)
})),
)
.service(web::resource("/payouts/list/profile").route(web::get().to(
|state, req, query: web::Query<RoutingRetrieveQuery>| {
routing::list_routing_configs_for_profile(
state,
req,
query,
Some(TransactionType::Payout),
)
},
)))
.service(web::resource("/payouts/active").route(web::get().to(
|state, req, query_params| {
routing::routing_retrieve_linked_config(
state,
req,
query_params,
Some(TransactionType::Payout),
)
},
)))
.service(
web::resource("/payouts/default")
.route(web::get().to(|state, req| {
routing::routing_retrieve_default_config(
state,
req,
&TransactionType::Payout,
)
}))
.route(web::post().to(|state, req, payload| {
routing::routing_update_default_config(
state,
req,
payload,
&TransactionType::Payout,
)
})),
)
.service(
web::resource("/payouts/{algorithm_id}/activate").route(web::post().to(
|state, req, path, payload| {
routing::routing_link_config(
state,
req,
path,
payload,
Some(TransactionType::Payout),
)
},
)),
)
.service(web::resource("/payouts/deactivate").route(web::post().to(
|state, req, payload| {
routing::routing_unlink_config(
state,
req,
payload,
Some(TransactionType::Payout),
)
},
)))
.service(
web::resource("/payouts/default/profile/{profile_id}").route(web::post().to(
|state, req, path, payload| {
routing::routing_update_default_config_for_profile(
state,
req,
path,
payload,
&TransactionType::Payout,
)
},
)),
)
.service(
web::resource("/payouts/default/profile").route(web::get().to(|state, req| {
routing::routing_retrieve_default_config_for_profiles(
state,
req,
&TransactionType::Payout,
)
})),
);
}
route = route
.service(
web::resource("/{algorithm_id}")
.route(web::get().to(routing::routing_retrieve_config)),
)
.service(
web::resource("/{algorithm_id}/activate").route(web::post().to(
|state, req, payload, path| {
routing::routing_link_config(state, req, path, payload, None)
},
)),
)
.service(
web::resource("/rule/evaluate")
.route(web::post().to(routing::evaluate_routing_rule)),
);
route
}
}
#[cfg(feature = "oltp")]
pub struct Subscription;
#[cfg(all(feature = "oltp", feature = "v1"))]
impl Subscription {
pub fn server(state: AppState) -> Scope {
let route = web::scope("/subscriptions").app_data(web::Data::new(state.clone()));
route
.service(
web::resource("").route(web::post().to(|state, req, payload| {
subscription::create_and_confirm_subscription(state, req, payload)
})),
)
.service(web::resource("/create").route(
web::post().to(|state, req, payload| {
subscription::create_subscription(state, req, payload)
}),
))
.service(web::resource("/estimate").route(web::get().to(subscription::get_estimate)))
.service(
web::resource("/plans").route(web::get().to(subscription::get_subscription_plans)),
)
.service(
web::resource("/{subscription_id}/confirm").route(web::post().to(
|state, req, id, payload| {
subscription::confirm_subscription(state, req, id, payload)
},
)),
)
.service(
web::resource("/{subscription_id}/update").route(web::put().to(
|state, req, id, payload| {
subscription::update_subscription(state, req, id, payload)
},
)),
)
.service(
web::resource("/{subscription_id}")
.route(web::get().to(subscription::get_subscription)),
)
}
}
pub struct Customers;
#[cfg(all(feature = "v2", any(feature = "olap", feature = "oltp")))]
impl Customers {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/v2/customers").app_data(web::Data::new(state));
#[cfg(all(feature = "olap", feature = "v2"))]
{
route = route
.service(web::resource("/list").route(web::get().to(customers::customers_list)))
.service(
web::resource("/list_with_count")
.route(web::get().to(customers::customers_list_with_count)),
)
.service(
web::resource("/total-payment-methods")
.route(web::get().to(payment_methods::get_total_payment_method_count)),
)
.service(
web::resource("/{id}/saved-payment-methods")
.route(web::get().to(payment_methods::list_customer_payment_method_api)),
)
}
#[cfg(all(feature = "oltp", feature = "v2"))]
{
route = route
.service(web::resource("").route(web::post().to(customers::customers_create)))
.service(
web::resource("/{id}")
.route(web::put().to(customers::customers_update))
.route(web::get().to(customers::customers_retrieve))
.route(web::delete().to(customers::customers_delete)),
)
}
route
}
}
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
impl Customers {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/customers").app_data(web::Data::new(state));
#[cfg(feature = "olap")]
{
route = route
.service(
web::resource("/{customer_id}/mandates")
.route(web::get().to(customers::get_customer_mandates)),
)
.service(web::resource("/list").route(web::get().to(customers::customers_list)))
.service(
web::resource("/list_with_count")
.route(web::get().to(customers::customers_list_with_count)),
)
}
#[cfg(feature = "oltp")]
{
route = route
.service(web::resource("").route(web::post().to(customers::customers_create)))
.service(
web::resource("/payment_methods").route(
web::get().to(payment_methods::list_customer_payment_method_api_client),
),
)
.service(
web::resource("/{customer_id}/payment_methods")
.route(web::get().to(payment_methods::list_customer_payment_method_api)),
)
.service(
web::resource("/{customer_id}/payment_methods/{payment_method_id}/default")
.route(web::post().to(payment_methods::default_payment_method_set_api)),
)
.service(
web::resource("/{customer_id}")
.route(web::get().to(customers::customers_retrieve))
.route(web::post().to(customers::customers_update))
.route(web::delete().to(customers::customers_delete)),
)
}
route
}
}
pub struct Refunds;
#[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v1"))]
impl Refunds {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/refunds").app_data(web::Data::new(state));
#[cfg(feature = "olap")]
{
route = route
.service(web::resource("/list").route(web::post().to(refunds_list)))
.service(web::resource("/profile/list").route(web::post().to(refunds_list_profile)))
.service(web::resource("/filter").route(web::post().to(refunds_filter_list)))
.service(web::resource("/v2/filter").route(web::get().to(get_refunds_filters)))
.service(web::resource("/aggregate").route(web::get().to(get_refunds_aggregates)))
.service(
web::resource("/profile/aggregate")
.route(web::get().to(get_refunds_aggregate_profile)),
)
.service(
web::resource("/v2/profile/filter")
.route(web::get().to(get_refunds_filters_profile)),
)
.service(
web::resource("/{id}/manual-update")
.route(web::put().to(refunds_manual_update)),
);
}
#[cfg(feature = "oltp")]
{
route = route
.service(web::resource("").route(web::post().to(refunds_create)))
.service(web::resource("/sync").route(web::post().to(refunds_retrieve_with_body)))
.service(
web::resource("/{id}")
.route(web::get().to(refunds_retrieve))
.route(web::post().to(refunds_update)),
);
}
route
}
}
#[cfg(all(feature = "v2", any(feature = "olap", feature = "oltp")))]
impl Refunds {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/v2/refunds").app_data(web::Data::new(state));
#[cfg(feature = "olap")]
{
route =
route.service(web::resource("/list").route(web::post().to(refunds::refunds_list)));
}
#[cfg(feature = "oltp")]
{
route = route
.service(web::resource("").route(web::post().to(refunds::refunds_create)))
.service(
web::resource("/{id}")
.route(web::get().to(refunds::refunds_retrieve))
.route(web::post().to(refunds::refunds_retrieve_with_gateway_creds)),
)
.service(
web::resource("/{id}/update-metadata")
.route(web::put().to(refunds::refunds_metadata_update)),
);
}
route
}
}
#[cfg(feature = "payouts")]
pub struct Payouts;
#[cfg(all(feature = "payouts", feature = "v1"))]
impl Payouts {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/payouts").app_data(web::Data::new(state));
route = route.service(web::resource("/create").route(web::post().to(payouts_create)));
#[cfg(feature = "olap")]
{
route = route
.service(
web::resource("/list")
.route(web::get().to(payouts_list))
.route(web::post().to(payouts_list_by_filter)),
)
.service(
web::resource("/profile/list")
.route(web::get().to(payouts_list_profile))
.route(web::post().to(payouts_list_by_filter_profile)),
)
.service(
web::resource("/filter")
.route(web::post().to(payouts_list_available_filters_for_merchant)),
)
.service(
web::resource("/profile/filter")
.route(web::post().to(payouts_list_available_filters_for_profile)),
);
}
route = route
.service(
web::resource("/{payout_id}")
.route(web::get().to(payouts_retrieve))
.route(web::put().to(payouts_update)),
)
.service(web::resource("/{payout_id}/confirm").route(web::post().to(payouts_confirm)))
.service(web::resource("/{payout_id}/cancel").route(web::post().to(payouts_cancel)))
.service(web::resource("/{payout_id}/fulfill").route(web::post().to(payouts_fulfill)));
route
}
}
#[cfg(all(feature = "v2", any(feature = "olap", feature = "oltp")))]
impl PaymentMethods {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/v2/payment-methods").app_data(web::Data::new(state));
#[cfg(feature = "olap")]
{
route =
route.service(web::resource("/filter").route(
web::get().to(
payment_methods::list_countries_currencies_for_connector_payment_method,
),
));
}
#[cfg(feature = "oltp")]
{
route = route
.service(
web::resource("")
.route(web::post().to(payment_methods::create_payment_method_api)),
)
.service(
web::resource("/create-intent")
.route(web::post().to(payment_methods::create_payment_method_intent_api)),
)
.service(
web::resource("/{payment_method_id}/check-network-token-status")
.route(web::get().to(payment_methods::network_token_status_check_api)),
);
route = route.service(
web::scope("/{id}")
.service(
web::resource("")
.route(web::get().to(payment_methods::payment_method_retrieve_api))
.route(web::delete().to(payment_methods::payment_method_delete_api)),
)
.service(web::resource("/list-enabled-payment-methods").route(
web::get().to(payment_methods::payment_method_session_list_payment_methods),
))
.service(
web::resource("/update-saved-payment-method")
.route(web::put().to(payment_methods::payment_method_update_api)),
)
.service(
web::resource("/get-token")
.route(web::get().to(payment_methods::get_payment_method_token_data)),
),
);
}
route
}
}
pub struct PaymentMethods;
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
impl PaymentMethods {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/payment_methods").app_data(web::Data::new(state));
#[cfg(feature = "olap")]
{
route =
route.service(web::resource("/filter").route(
web::get().to(
payment_methods::list_countries_currencies_for_connector_payment_method,
),
));
}
#[cfg(feature = "oltp")]
{
route = route
.service(
web::resource("")
.route(web::post().to(payment_methods::create_payment_method_api))
.route(web::get().to(payment_methods::list_payment_method_api)), // TODO : added for sdk compatibility for now, need to deprecate this later
)
.service(
web::resource("/migrate")
.route(web::post().to(payment_methods::migrate_payment_method_api)),
)
.service(
web::resource("/migrate-batch")
.route(web::post().to(payment_methods::migrate_payment_methods)),
)
.service(
web::resource("/update-batch")
.route(web::post().to(payment_methods::update_payment_methods)),
)
.service(
web::resource("/tokenize-card")
.route(web::post().to(payment_methods::tokenize_card_api)),
)
.service(
web::resource("/tokenize-card-batch")
.route(web::post().to(payment_methods::tokenize_card_batch_api)),
)
.service(
web::resource("/collect")
.route(web::post().to(payment_methods::initiate_pm_collect_link_flow)),
)
.service(
web::resource("/collect/{merchant_id}/{collect_id}")
.route(web::get().to(payment_methods::render_pm_collect_link)),
)
.service(
web::resource("/{payment_method_id}")
.route(web::get().to(payment_methods::payment_method_retrieve_api))
.route(web::delete().to(payment_methods::payment_method_delete_api)),
)
.service(
web::resource("/{payment_method_id}/tokenize-card")
.route(web::post().to(payment_methods::tokenize_card_using_pm_api)),
)
.service(
web::resource("/{payment_method_id}/update")
.route(web::post().to(payment_methods::payment_method_update_api)),
)
.service(
web::resource("/{payment_method_id}/save")
.route(web::post().to(payment_methods::save_payment_method_api)),
)
.service(
web::resource("/auth/link").route(web::post().to(pm_auth::link_token_create)),
)
.service(
web::resource("/auth/exchange").route(web::post().to(pm_auth::exchange_token)),
)
}
route
}
}
#[cfg(all(feature = "v2", feature = "oltp"))]
pub struct PaymentMethodSession;
#[cfg(all(feature = "v2", feature = "oltp"))]
impl PaymentMethodSession {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/v2/payment-method-sessions").app_data(web::Data::new(state));
route = route.service(
web::resource("")
.route(web::post().to(payment_methods::payment_methods_session_create)),
);
route =
route.service(
web::scope("/{payment_method_session_id}")
.service(
web::resource("")
.route(web::get().to(payment_methods::payment_methods_session_retrieve))
.route(web::put().to(payment_methods::payment_methods_session_update))
.route(web::delete().to(
payment_methods::payment_method_session_delete_saved_payment_method,
)),
)
.service(web::resource("/list-payment-methods").route(
web::get().to(payment_methods::payment_method_session_list_payment_methods),
))
.service(
web::resource("/confirm")
.route(web::post().to(payment_methods::payment_method_session_confirm)),
)
.service(web::resource("/update-saved-payment-method").route(
web::put().to(
payment_methods::payment_method_session_update_saved_payment_method,
),
)),
);
route
}
}
#[cfg(all(feature = "v2", feature = "oltp"))]
pub struct Tokenization;
#[cfg(all(feature = "v2", feature = "oltp"))]
impl Tokenization {
pub fn server(state: AppState) -> Scope {
web::scope("/v2/tokenize")
.app_data(web::Data::new(state))
.service(
web::resource("")
.route(web::post().to(tokenization_routes::create_token_vault_api)),
)
.service(
web::resource("/{id}")
.route(web::delete().to(tokenization_routes::delete_tokenized_data_api)),
)
}
}
#[cfg(all(feature = "olap", feature = "recon", feature = "v1"))]
pub struct Recon;
#[cfg(all(feature = "olap", feature = "recon", feature = "v1"))]
impl Recon {
pub fn server(state: AppState) -> Scope {
web::scope("/recon")
.app_data(web::Data::new(state))
.service(
web::resource("/{merchant_id}/update")
.route(web::post().to(recon_routes::update_merchant)),
)
.service(web::resource("/token").route(web::get().to(recon_routes::get_recon_token)))
.service(
web::resource("/request").route(web::post().to(recon_routes::request_for_recon)),
)
.service(
web::resource("/verify_token")
.route(web::get().to(recon_routes::verify_recon_token)),
)
}
}
pub struct Hypersense;
impl Hypersense {
pub fn server(state: AppState) -> Scope {
web::scope("/hypersense")
.app_data(web::Data::new(state))
.service(
web::resource("/token")
.route(web::get().to(hypersense_routes::get_hypersense_token)),
)
.service(
web::resource("/verify_token")
.route(web::post().to(hypersense_routes::verify_hypersense_token)),
)
.service(
web::resource("/signout")
.route(web::post().to(hypersense_routes::signout_hypersense_token)),
)
}
}
#[cfg(feature = "olap")]
pub struct Blocklist;
#[cfg(all(feature = "olap", feature = "v1"))]
impl Blocklist {
pub fn server(state: AppState) -> Scope {
web::scope("/blocklist")
.app_data(web::Data::new(state))
.service(
web::resource("")
.route(web::get().to(blocklist::list_blocked_payment_methods))
.route(web::post().to(blocklist::add_entry_to_blocklist))
.route(web::delete().to(blocklist::remove_entry_from_blocklist)),
)
.service(
web::resource("/toggle").route(web::post().to(blocklist::toggle_blocklist_guard)),
)
}
}
#[cfg(feature = "olap")]
pub struct Organization;
#[cfg(all(feature = "olap", feature = "v1"))]
impl Organization {
pub fn server(state: AppState) -> Scope {
web::scope("/organization")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(admin::organization_create)))
.service(
web::resource("/{id}")
.route(web::get().to(admin::organization_retrieve))
.route(web::put().to(admin::organization_update)),
)
}
}
#[cfg(all(feature = "v2", feature = "olap"))]
impl Organization {
pub fn server(state: AppState) -> Scope {
web::scope("/v2/organizations")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(admin::organization_create)))
.service(
web::scope("/{id}")
.service(
web::resource("")
.route(web::get().to(admin::organization_retrieve))
.route(web::put().to(admin::organization_update)),
)
.service(
web::resource("/merchant-accounts")
.route(web::get().to(admin::merchant_account_list)),
),
)
}
}
pub struct MerchantAccount;
#[cfg(all(feature = "v2", feature = "olap"))]
impl MerchantAccount {
pub fn server(state: AppState) -> Scope {
web::scope("/v2/merchant-accounts")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(admin::merchant_account_create)))
.service(
web::scope("/{id}")
.service(
web::resource("")
.route(web::get().to(admin::retrieve_merchant_account))
.route(web::put().to(admin::update_merchant_account)),
)
.service(
web::resource("/profiles").route(web::get().to(profiles::profiles_list)),
)
.service(
web::resource("/kv")
.route(web::post().to(admin::merchant_account_toggle_kv))
.route(web::get().to(admin::merchant_account_kv_status)),
),
)
}
}
#[cfg(all(feature = "olap", feature = "v1"))]
impl MerchantAccount {
pub fn server(state: AppState) -> Scope {
let mut routes = web::scope("/accounts")
.service(web::resource("").route(web::post().to(admin::merchant_account_create)))
.service(web::resource("/list").route(web::get().to(admin::merchant_account_list)))
.service(
web::resource("/{id}/kv")
.route(web::post().to(admin::merchant_account_toggle_kv))
.route(web::get().to(admin::merchant_account_kv_status)),
)
.service(
web::resource("/transfer")
.route(web::post().to(admin::merchant_account_transfer_keys)),
)
.service(
web::resource("/kv").route(web::post().to(admin::merchant_account_toggle_all_kv)),
)
.service(
web::resource("/{id}")
.route(web::get().to(admin::retrieve_merchant_account))
.route(web::post().to(admin::update_merchant_account))
.route(web::delete().to(admin::delete_merchant_account)),
);
if state.conf.platform.enabled {
routes = routes.service(
web::resource("/{id}/platform")
.route(web::post().to(admin::merchant_account_enable_platform_account)),
)
}
routes.app_data(web::Data::new(state))
}
}
pub struct MerchantConnectorAccount;
#[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v2"))]
impl MerchantConnectorAccount {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/v2/connector-accounts").app_data(web::Data::new(state));
#[cfg(feature = "olap")]
{
use super::admin::*;
route = route
.service(web::resource("").route(web::post().to(connector_create)))
.service(
web::resource("/{id}")
.route(web::put().to(connector_update))
.route(web::get().to(connector_retrieve))
.route(web::delete().to(connector_delete)),
);
}
route
}
}
#[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v1"))]
impl MerchantConnectorAccount {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/account").app_data(web::Data::new(state));
#[cfg(feature = "olap")]
{
use super::admin::*;
route = route
.service(
web::resource("/connectors/verify")
.route(web::post().to(super::verify_connector::payment_connector_verify)),
)
.service(
web::resource("/{merchant_id}/connectors")
.route(web::post().to(connector_create))
.route(web::get().to(connector_list)),
)
.service(
web::resource("/{merchant_id}/connectors/{merchant_connector_id}")
.route(web::get().to(connector_retrieve))
.route(web::post().to(connector_update))
.route(web::delete().to(connector_delete)),
);
}
#[cfg(feature = "oltp")]
{
route = route.service(
web::resource("/payment_methods")
.route(web::get().to(payment_methods::list_payment_method_api)),
);
}
route
}
}
pub struct EphemeralKey;
#[cfg(all(feature = "v1", feature = "oltp"))]
impl EphemeralKey {
pub fn server(config: AppState) -> Scope {
web::scope("/ephemeral_keys")
.app_data(web::Data::new(config))
.service(web::resource("").route(web::post().to(ephemeral_key_create)))
.service(web::resource("/{id}").route(web::delete().to(ephemeral_key_delete)))
}
}
#[cfg(feature = "v2")]
impl EphemeralKey {
pub fn server(config: AppState) -> Scope {
web::scope("/v2/client-secret")
.app_data(web::Data::new(config))
.service(web::resource("").route(web::post().to(client_secret_create)))
.service(web::resource("/{id}").route(web::delete().to(client_secret_delete)))
}
}
pub struct Mandates;
#[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v1"))]
impl Mandates {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/mandates").app_data(web::Data::new(state));
#[cfg(feature = "olap")]
{
route =
route.service(web::resource("/list").route(web::get().to(retrieve_mandates_list)));
route = route.service(web::resource("/{id}").route(web::get().to(get_mandate)));
}
#[cfg(feature = "oltp")]
{
route =
route.service(web::resource("/revoke/{id}").route(web::post().to(revoke_mandate)));
}
route
}
}
pub struct Webhooks;
#[cfg(all(feature = "oltp", feature = "v1"))]
impl Webhooks {
pub fn server(config: AppState) -> Scope {
use api_models::webhooks as webhook_type;
#[allow(unused_mut)]
let mut route = web::scope("/webhooks")
.app_data(web::Data::new(config))
.service(
web::resource("/network_token_requestor/ref")
.route(
web::post().to(receive_network_token_requestor_incoming_webhook::<
webhook_type::OutgoingWebhook,
>),
)
.route(
web::get().to(receive_network_token_requestor_incoming_webhook::<
webhook_type::OutgoingWebhook,
>),
)
.route(
web::put().to(receive_network_token_requestor_incoming_webhook::<
webhook_type::OutgoingWebhook,
>),
),
)
.service(
web::resource("/{merchant_id}/{connector_id_or_name}")
.route(
web::post().to(receive_incoming_webhook::<webhook_type::OutgoingWebhook>),
)
.route(web::get().to(receive_incoming_webhook::<webhook_type::OutgoingWebhook>))
.route(
web::put().to(receive_incoming_webhook::<webhook_type::OutgoingWebhook>),
),
);
#[cfg(feature = "frm")]
{
route = route.service(
web::resource("/frm_fulfillment")
.route(web::post().to(frm_routes::frm_fulfillment)),
);
}
route
}
}
pub struct RelayWebhooks;
#[cfg(feature = "oltp")]
impl RelayWebhooks {
pub fn server(state: AppState) -> Scope {
use api_models::webhooks as webhook_type;
web::scope("/webhooks/relay")
.app_data(web::Data::new(state))
.service(web::resource("/{merchant_id}/{connector_id}").route(
web::post().to(receive_incoming_relay_webhook::<webhook_type::OutgoingWebhook>),
))
}
}
#[cfg(all(feature = "oltp", feature = "v2"))]
impl Webhooks {
pub fn server(config: AppState) -> Scope {
use api_models::webhooks as webhook_type;
#[allow(unused_mut)]
let mut route = web::scope("/v2/webhooks")
.app_data(web::Data::new(config))
.service(
web::resource("/{merchant_id}/{profile_id}/{connector_id}")
.route(
web::post().to(receive_incoming_webhook::<webhook_type::OutgoingWebhook>),
)
.route(web::get().to(receive_incoming_webhook::<webhook_type::OutgoingWebhook>))
.route(
web::put().to(receive_incoming_webhook::<webhook_type::OutgoingWebhook>),
),
);
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
{
route = route.service(
web::resource("/recovery/{merchant_id}/{profile_id}/{connector_id}").route(
web::post()
.to(recovery_receive_incoming_webhook::<webhook_type::OutgoingWebhook>),
),
);
}
route
}
}
pub struct Configs;
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
impl Configs {
pub fn server(config: AppState) -> Scope {
web::scope("/configs")
.app_data(web::Data::new(config))
.service(web::resource("/").route(web::post().to(config_key_create)))
.service(
web::resource("/{key}")
.route(web::get().to(config_key_retrieve))
.route(web::post().to(config_key_update))
.route(web::delete().to(config_key_delete)),
)
}
}
#[cfg(all(feature = "v2", any(feature = "olap", feature = "oltp")))]
impl Configs {
pub fn server(config: AppState) -> Scope {
web::scope("/v2/configs")
.app_data(web::Data::new(config))
.service(web::resource("/").route(web::post().to(config_key_create)))
.service(
web::resource("/{key}")
.route(web::get().to(config_key_retrieve))
.route(web::post().to(config_key_update))
.route(web::delete().to(config_key_delete)),
)
}
}
pub struct ApplePayCertificatesMigration;
#[cfg(all(feature = "olap", feature = "v1"))]
impl ApplePayCertificatesMigration {
pub fn server(state: AppState) -> Scope {
web::scope("/apple_pay_certificates_migration")
.app_data(web::Data::new(state))
.service(web::resource("").route(
web::post().to(apple_pay_certificates_migration::apple_pay_certificates_migration),
))
}
}
pub struct Poll;
#[cfg(all(feature = "oltp", feature = "v1"))]
impl Poll {
pub fn server(config: AppState) -> Scope {
web::scope("/poll")
.app_data(web::Data::new(config))
.service(
web::resource("/status/{poll_id}").route(web::get().to(poll::retrieve_poll_status)),
)
}
}
pub struct ApiKeys;
#[cfg(all(feature = "olap", feature = "v2"))]
impl ApiKeys {
pub fn server(state: AppState) -> Scope {
web::scope("/v2/api-keys")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(api_keys::api_key_create)))
.service(web::resource("/list").route(web::get().to(api_keys::api_key_list)))
.service(
web::resource("/{key_id}")
.route(web::get().to(api_keys::api_key_retrieve))
.route(web::put().to(api_keys::api_key_update))
.route(web::delete().to(api_keys::api_key_revoke)),
)
}
}
#[cfg(all(feature = "olap", feature = "v1"))]
impl ApiKeys {
pub fn server(state: AppState) -> Scope {
web::scope("/api_keys/{merchant_id}")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(api_keys::api_key_create)))
.service(web::resource("/list").route(web::get().to(api_keys::api_key_list)))
.service(
web::resource("/{key_id}")
.route(web::get().to(api_keys::api_key_retrieve))
.route(web::post().to(api_keys::api_key_update))
.route(web::delete().to(api_keys::api_key_revoke)),
)
}
}
pub struct Disputes;
#[cfg(all(feature = "olap", feature = "v1"))]
impl Disputes {
pub fn server(state: AppState) -> Scope {
web::scope("/disputes")
.app_data(web::Data::new(state))
.service(web::resource("/list").route(web::get().to(disputes::retrieve_disputes_list)))
.service(
web::resource("/profile/list")
.route(web::get().to(disputes::retrieve_disputes_list_profile)),
)
.service(web::resource("/filter").route(web::get().to(disputes::get_disputes_filters)))
.service(
web::resource("/profile/filter")
.route(web::get().to(disputes::get_disputes_filters_profile)),
)
.service(
web::resource("/accept/{dispute_id}")
.route(web::post().to(disputes::accept_dispute)),
)
.service(
web::resource("/aggregate").route(web::get().to(disputes::get_disputes_aggregate)),
)
.service(
web::resource("/profile/aggregate")
.route(web::get().to(disputes::get_disputes_aggregate_profile)),
)
.service(
web::resource("/evidence")
.route(web::post().to(disputes::submit_dispute_evidence))
.route(web::put().to(disputes::attach_dispute_evidence))
.route(web::delete().to(disputes::delete_dispute_evidence)),
)
.service(
web::resource("/evidence/{dispute_id}")
.route(web::get().to(disputes::retrieve_dispute_evidence)),
)
.service(
web::resource("/{dispute_id}").route(web::get().to(disputes::retrieve_dispute)),
)
.service(
web::resource("/{connector_id}/fetch")
.route(web::get().to(disputes::fetch_disputes)),
)
}
}
pub struct Cards;
#[cfg(all(feature = "oltp", feature = "v1"))]
impl Cards {
pub fn server(state: AppState) -> Scope {
web::scope("/cards")
.app_data(web::Data::new(state))
.service(web::resource("/create").route(web::post().to(create_cards_info)))
.service(web::resource("/update").route(web::post().to(update_cards_info)))
.service(web::resource("/update-batch").route(web::post().to(migrate_cards_info)))
.service(web::resource("/{bin}").route(web::get().to(card_iin_info)))
}
}
pub struct Files;
#[cfg(all(feature = "olap", feature = "v1"))]
impl Files {
pub fn server(state: AppState) -> Scope {
web::scope("/files")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(files::files_create)))
.service(
web::resource("/{file_id}")
.route(web::delete().to(files::files_delete))
.route(web::get().to(files::files_retrieve)),
)
}
}
pub struct Cache;
impl Cache {
pub fn server(state: AppState) -> Scope {
web::scope("/cache")
.app_data(web::Data::new(state))
.service(web::resource("/invalidate/{key}").route(web::post().to(invalidate)))
}
}
pub struct PaymentLink;
#[cfg(all(feature = "olap", feature = "v1"))]
impl PaymentLink {
pub fn server(state: AppState) -> Scope {
web::scope("/payment_link")
.app_data(web::Data::new(state))
.service(web::resource("/list").route(web::post().to(payment_link::payments_link_list)))
.service(
web::resource("/{payment_link_id}")
.route(web::get().to(payment_link::payment_link_retrieve)),
)
.service(
web::resource("{merchant_id}/{payment_id}")
.route(web::get().to(payment_link::initiate_payment_link)),
)
.service(
web::resource("s/{merchant_id}/{payment_id}")
.route(web::get().to(payment_link::initiate_secure_payment_link)),
)
.service(
web::resource("status/{merchant_id}/{payment_id}")
.route(web::get().to(payment_link::payment_link_status)),
)
}
}
#[cfg(feature = "payouts")]
pub struct PayoutLink;
#[cfg(all(feature = "payouts", feature = "v1"))]
impl PayoutLink {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/payout_link").app_data(web::Data::new(state));
route = route.service(
web::resource("/{merchant_id}/{payout_id}").route(web::get().to(render_payout_link)),
);
route
}
}
pub struct Profile;
#[cfg(all(feature = "olap", feature = "v2"))]
impl Profile {
pub fn server(state: AppState) -> Scope {
web::scope("/v2/profiles")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(profiles::profile_create)))
.service(
web::scope("/{profile_id}")
.service(
web::resource("")
.route(web::get().to(profiles::profile_retrieve))
.route(web::put().to(profiles::profile_update)),
)
.service(
web::resource("/connector-accounts")
.route(web::get().to(admin::connector_list)),
)
.service(
web::resource("/fallback-routing")
.route(web::get().to(routing::routing_retrieve_default_config))
.route(web::patch().to(routing::routing_update_default_config)),
)
.service(
web::resource("/activate-routing-algorithm").route(web::patch().to(
|state, req, path, payload| {
routing::routing_link_config(
state,
req,
path,
payload,
&TransactionType::Payment,
)
},
)),
)
.service(
web::resource("/deactivate-routing-algorithm").route(web::patch().to(
|state, req, path| {
routing::routing_unlink_config(
state,
req,
path,
&TransactionType::Payment,
)
},
)),
)
.service(web::resource("/routing-algorithm").route(web::get().to(
|state, req, query_params, path| {
routing::routing_retrieve_linked_config(
state,
req,
query_params,
path,
&TransactionType::Payment,
)
},
)))
.service(
web::resource("/decision")
.route(web::put().to(routing::upsert_decision_manager_config))
.route(web::get().to(routing::retrieve_decision_manager_config)),
),
)
}
}
#[cfg(all(feature = "olap", feature = "v1"))]
impl Profile {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/account/{account_id}/business_profile")
.app_data(web::Data::new(state))
.service(
web::resource("")
.route(web::post().to(profiles::profile_create))
.route(web::get().to(profiles::profiles_list)),
);
#[cfg(feature = "dynamic_routing")]
{
route = route.service(
web::scope("/{profile_id}/dynamic_routing")
.service(
web::scope("/success_based")
.service(
web::resource("/toggle")
.route(web::post().to(routing::toggle_success_based_routing)),
)
.service(
web::resource("/create")
.route(web::post().to(routing::create_success_based_routing)),
)
.service(web::resource("/config/{algorithm_id}").route(
web::patch().to(|state, req, path, payload| {
routing::success_based_routing_update_configs(
state, req, path, payload,
)
}),
)),
)
.service(
web::resource("/set_volume_split")
.route(web::post().to(routing::set_dynamic_routing_volume_split)),
)
.service(
web::resource("/get_volume_split")
.route(web::get().to(routing::get_dynamic_routing_volume_split)),
)
.service(
web::scope("/elimination")
.service(
web::resource("/toggle")
.route(web::post().to(routing::toggle_elimination_routing)),
)
.service(
web::resource("/create")
.route(web::post().to(routing::create_elimination_routing)),
)
.service(web::resource("config/{algorithm_id}").route(
web::patch().to(|state, req, path, payload| {
routing::elimination_routing_update_configs(
state, req, path, payload,
)
}),
)),
)
.service(
web::scope("/contracts")
.service(web::resource("/toggle").route(
web::post().to(routing::contract_based_routing_setup_config),
))
.service(web::resource("/config/{algorithm_id}").route(
web::patch().to(|state, req, path, payload| {
routing::contract_based_routing_update_configs(
state, req, path, payload,
)
}),
)),
),
);
}
route = route.service(
web::scope("/{profile_id}")
.service(
web::resource("")
.route(web::get().to(profiles::profile_retrieve))
.route(web::post().to(profiles::profile_update))
.route(web::delete().to(profiles::profile_delete)),
)
.service(
web::resource("/toggle_extended_card_info")
.route(web::post().to(profiles::toggle_extended_card_info)),
)
.service(
web::resource("/toggle_connector_agnostic_mit")
.route(web::post().to(profiles::toggle_connector_agnostic_mit)),
),
);
route
}
}
pub struct ProfileNew;
#[cfg(feature = "olap")]
impl ProfileNew {
#[cfg(feature = "v1")]
pub fn server(state: AppState) -> Scope {
web::scope("/account/{account_id}/profile")
.app_data(web::Data::new(state))
.service(
web::resource("").route(web::get().to(profiles::profiles_list_at_profile_level)),
)
.service(
web::resource("/connectors").route(web::get().to(admin::connector_list_profile)),
)
}
#[cfg(feature = "v2")]
pub fn server(state: AppState) -> Scope {
web::scope("/account/{account_id}/profile").app_data(web::Data::new(state))
}
}
pub struct Gsm;
#[cfg(all(feature = "v1", feature = "olap"))]
impl Gsm {
pub fn server(state: AppState) -> Scope {
web::scope("/gsm")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(gsm::create_gsm_rule)))
.service(web::resource("/get").route(web::post().to(gsm::get_gsm_rule)))
.service(web::resource("/update").route(web::post().to(gsm::update_gsm_rule)))
.service(web::resource("/delete").route(web::post().to(gsm::delete_gsm_rule)))
}
}
#[cfg(all(feature = "v2", feature = "olap"))]
impl Gsm {
pub fn server(state: AppState) -> Scope {
web::scope("/v2/gsm")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(gsm::create_gsm_rule)))
.service(web::resource("/get").route(web::post().to(gsm::get_gsm_rule)))
.service(web::resource("/update").route(web::post().to(gsm::update_gsm_rule)))
.service(web::resource("/delete").route(web::post().to(gsm::delete_gsm_rule)))
}
}
pub struct Chat;
#[cfg(feature = "olap")]
impl Chat {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/chat").app_data(web::Data::new(state.clone()));
if state.conf.chat.get_inner().enabled {
route = route.service(
web::scope("/ai")
.service(
web::resource("/data")
.route(web::post().to(chat::get_data_from_hyperswitch_ai_workflow)),
)
.service(
web::resource("/list").route(web::get().to(chat::get_all_conversations)),
),
);
}
route
}
}
pub struct ThreeDsDecisionRule;
#[cfg(feature = "oltp")]
impl ThreeDsDecisionRule {
pub fn server(state: AppState) -> Scope {
web::scope("/three_ds_decision")
.app_data(web::Data::new(state))
.service(
web::resource("/execute")
.route(web::post().to(three_ds_decision_rule::execute_decision_rule)),
)
}
}
#[cfg(feature = "olap")]
pub struct Verify;
#[cfg(all(feature = "olap", feature = "v1"))]
impl Verify {
pub fn server(state: AppState) -> Scope {
web::scope("/verify")
.app_data(web::Data::new(state))
.service(
web::resource("/apple_pay/{merchant_id}")
.route(web::post().to(apple_pay_merchant_registration)),
)
.service(
web::resource("/applepay_verified_domains")
.route(web::get().to(retrieve_apple_pay_verified_domains)),
)
}
}
#[cfg(all(feature = "olap", feature = "v2"))]
impl Verify {
pub fn server(state: AppState) -> Scope {
web::scope("/v2/verify")
.app_data(web::Data::new(state))
.service(
web::resource("/apple-pay/{merchant_id}")
.route(web::post().to(apple_pay_merchant_registration)),
)
.service(
web::resource("/applepay-verified-domains")
.route(web::get().to(retrieve_apple_pay_verified_domains)),
)
}
}
pub struct UserDeprecated;
#[cfg(all(feature = "olap", feature = "v2"))]
impl UserDeprecated {
pub fn server(state: AppState) -> Scope {
// TODO: Deprecated. Remove this in favour of /v2/users
let mut route = web::scope("/v2/user").app_data(web::Data::new(state));
route = route.service(
web::resource("/create_merchant")
.route(web::post().to(user::user_merchant_account_create)),
);
route = route.service(
web::scope("/list")
.service(
web::resource("/merchant")
.route(web::get().to(user::list_merchants_for_user_in_org)),
)
.service(
web::resource("/profile")
.route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)),
),
);
route = route.service(
web::scope("/switch")
.service(
web::resource("/merchant")
.route(web::post().to(user::switch_merchant_for_user_in_org)),
)
.service(
web::resource("/profile")
.route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)),
),
);
route = route.service(
web::resource("/data")
.route(web::get().to(user::get_multiple_dashboard_metadata))
.route(web::post().to(user::set_dashboard_metadata)),
);
route
}
}
pub struct User;
#[cfg(all(feature = "olap", feature = "v2"))]
impl User {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/v2/users").app_data(web::Data::new(state));
route = route.service(
web::resource("/create-merchant")
.route(web::post().to(user::user_merchant_account_create)),
);
route = route.service(
web::scope("/list")
.service(
web::resource("/merchant")
.route(web::get().to(user::list_merchants_for_user_in_org)),
)
.service(
web::resource("/profile")
.route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)),
),
);
route = route.service(
web::scope("/switch")
.service(
web::resource("/merchant")
.route(web::post().to(user::switch_merchant_for_user_in_org)),
)
.service(
web::resource("/profile")
.route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)),
),
);
route = route.service(
web::resource("/data")
.route(web::get().to(user::get_multiple_dashboard_metadata))
.route(web::post().to(user::set_dashboard_metadata)),
);
route
}
}
#[cfg(all(feature = "olap", feature = "v1"))]
impl User {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/user").app_data(web::Data::new(state.clone()));
route = route
.service(web::resource("").route(web::get().to(user::get_user_details)))
.service(web::resource("/signin").route(web::post().to(user::user_signin)))
.service(web::resource("/v2/signin").route(web::post().to(user::user_signin)))
// signin/signup with sso using openidconnect
.service(web::resource("/oidc").route(web::post().to(user::sso_sign)))
.service(web::resource("/signout").route(web::post().to(user::signout)))
.service(web::resource("/rotate_password").route(web::post().to(user::rotate_password)))
.service(web::resource("/change_password").route(web::post().to(user::change_password)))
.service(
web::resource("/internal_signup").route(web::post().to(user::internal_user_signup)),
)
.service(
web::resource("/tenant_signup").route(web::post().to(user::create_tenant_user)),
)
.service(web::resource("/create_org").route(web::post().to(user::user_org_create)))
.service(
web::resource("/create_merchant")
.route(web::post().to(user::user_merchant_account_create)),
)
// TODO: To be deprecated
.service(
web::resource("/permission_info")
.route(web::get().to(user_role::get_authorization_info)),
)
// TODO: To be deprecated
.service(
web::resource("/module/list").route(web::get().to(user_role::get_role_information)),
)
.service(
web::resource("/parent/list")
.route(web::get().to(user_role::get_parent_group_info)),
)
.service(
web::resource("/update").route(web::post().to(user::update_user_account_details)),
)
.service(
web::resource("/data")
.route(web::get().to(user::get_multiple_dashboard_metadata))
.route(web::post().to(user::set_dashboard_metadata)),
);
if state.conf.platform.enabled {
route = route.service(
web::resource("/create_platform").route(web::post().to(user::create_platform)),
)
}
route = route
.service(web::scope("/key").service(
web::resource("/transfer").route(web::post().to(user::transfer_user_key)),
));
route = route.service(
web::scope("/list")
.service(web::resource("/org").route(web::get().to(user::list_orgs_for_user)))
.service(
web::resource("/merchant")
.route(web::get().to(user::list_merchants_for_user_in_org)),
)
.service(
web::resource("/profile")
.route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)),
)
.service(
web::resource("/invitation")
.route(web::get().to(user_role::list_invitations_for_user)),
),
);
route = route.service(
web::scope("/switch")
.service(web::resource("/org").route(web::post().to(user::switch_org_for_user)))
.service(
web::resource("/merchant")
.route(web::post().to(user::switch_merchant_for_user_in_org)),
)
.service(
web::resource("/profile")
.route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)),
),
);
// Two factor auth routes
route = route.service(
web::scope("/2fa")
// TODO: to be deprecated
.service(web::resource("").route(web::get().to(user::check_two_factor_auth_status)))
.service(
web::resource("/v2")
.route(web::get().to(user::check_two_factor_auth_status_with_attempts)),
)
.service(
web::scope("/totp")
.service(web::resource("/begin").route(web::get().to(user::totp_begin)))
.service(web::resource("/reset").route(web::get().to(user::totp_reset)))
.service(
web::resource("/verify")
.route(web::post().to(user::totp_verify))
.route(web::put().to(user::totp_update)),
),
)
.service(
web::scope("/recovery_code")
.service(
web::resource("/verify")
.route(web::post().to(user::verify_recovery_code)),
)
.service(
web::resource("/generate")
.route(web::get().to(user::generate_recovery_codes)),
),
)
.service(
web::resource("/terminate")
.route(web::get().to(user::terminate_two_factor_auth)),
),
);
route = route.service(
web::scope("/auth")
.service(
web::resource("")
.route(web::post().to(user::create_user_authentication_method))
.route(web::put().to(user::update_user_authentication_method)),
)
.service(
web::resource("/list")
.route(web::get().to(user::list_user_authentication_methods)),
)
.service(web::resource("/url").route(web::get().to(user::get_sso_auth_url)))
.service(
web::resource("/select").route(web::post().to(user::terminate_auth_select)),
),
);
#[cfg(feature = "email")]
{
route = route
.service(web::resource("/from_email").route(web::post().to(user::user_from_email)))
.service(
web::resource("/connect_account")
.route(web::post().to(user::user_connect_account)),
)
.service(
web::resource("/forgot_password").route(web::post().to(user::forgot_password)),
)
.service(
web::resource("/reset_password").route(web::post().to(user::reset_password)),
)
.service(
web::resource("/signup_with_merchant_id")
.route(web::post().to(user::user_signup_with_merchant_id)),
)
.service(web::resource("/verify_email").route(web::post().to(user::verify_email)))
.service(
web::resource("/v2/verify_email").route(web::post().to(user::verify_email)),
)
.service(
web::resource("/verify_email_request")
.route(web::post().to(user::verify_email_request)),
)
.service(
web::resource("/user/resend_invite").route(web::post().to(user::resend_invite)),
)
.service(
web::resource("/accept_invite_from_email")
.route(web::post().to(user::accept_invite_from_email)),
);
}
#[cfg(not(feature = "email"))]
{
route = route.service(web::resource("/signup").route(web::post().to(user::user_signup)))
}
// User management
route = route.service(
web::scope("/user")
.service(web::resource("").route(web::post().to(user::list_user_roles_details)))
// TODO: To be deprecated
.service(web::resource("/v2").route(web::post().to(user::list_user_roles_details)))
.service(
web::resource("/list").route(web::get().to(user_role::list_users_in_lineage)),
)
// TODO: To be deprecated
.service(
web::resource("/v2/list")
.route(web::get().to(user_role::list_users_in_lineage)),
)
.service(
web::resource("/invite_multiple")
.route(web::post().to(user::invite_multiple_user)),
)
.service(
web::scope("/invite/accept")
.service(
web::resource("")
.route(web::post().to(user_role::accept_invitations_v2)),
)
.service(
web::resource("/pre_auth")
.route(web::post().to(user_role::accept_invitations_pre_auth)),
)
.service(
web::scope("/v2")
.service(
web::resource("")
.route(web::post().to(user_role::accept_invitations_v2)),
)
.service(
web::resource("/pre_auth").route(
web::post().to(user_role::accept_invitations_pre_auth),
),
),
),
)
.service(
web::resource("/update_role")
.route(web::post().to(user_role::update_user_role)),
)
.service(
web::resource("/delete").route(web::delete().to(user_role::delete_user_role)),
),
);
if state.conf().clone_connector_allowlist.is_some() {
route = route.service(
web::resource("/clone_connector").route(web::post().to(user::clone_connector)),
);
}
// Role information
route =
route.service(
web::scope("/role")
.service(
web::resource("")
.route(web::get().to(user_role::get_role_from_token))
// TODO: To be deprecated
.route(web::post().to(user_role::create_role)),
)
.service(
web::resource("/v2")
.route(web::post().to(user_role::create_role_v2))
.route(
web::get()
.to(user_role::get_groups_and_resources_for_role_from_token),
),
)
.service(web::resource("/v3").route(
web::get().to(user_role::get_parent_groups_info_for_role_from_token),
))
// TODO: To be deprecated
.service(
web::resource("/v2/list")
.route(web::get().to(user_role::list_roles_with_info)),
)
.service(
web::scope("/list")
.service(
web::resource("")
.route(web::get().to(user_role::list_roles_with_info)),
)
.service(web::resource("/invite").route(
web::get().to(user_role::list_invitable_roles_at_entity_level),
))
.service(web::resource("/update").route(
web::get().to(user_role::list_updatable_roles_at_entity_level),
)),
)
.service(
web::resource("/{role_id}")
.route(web::get().to(user_role::get_role))
.route(web::put().to(user_role::update_role)),
)
.service(
web::resource("/{role_id}/v2")
.route(web::get().to(user_role::get_parent_info_for_role)),
),
);
#[cfg(feature = "dummy_connector")]
{
route = route.service(
web::resource("/sample_data")
.route(web::post().to(user::generate_sample_data))
.route(web::delete().to(user::delete_sample_data)),
)
}
// Admin Theme
// TODO: To be deprecated
route = route.service(
web::scope("/admin/theme")
.service(
web::resource("")
.route(web::get().to(user::theme::get_theme_using_lineage))
.route(web::post().to(user::theme::create_theme)),
)
.service(
web::resource("/{theme_id}")
.route(web::get().to(user::theme::get_theme_using_theme_id))
.route(web::put().to(user::theme::update_theme))
.route(web::post().to(user::theme::upload_file_to_theme_storage))
.route(web::delete().to(user::theme::delete_theme)),
),
);
// User Theme
route = route.service(
web::scope("/theme")
.service(
web::resource("")
.route(web::post().to(user::theme::create_user_theme))
.route(web::get().to(user::theme::get_user_theme_using_lineage)),
)
.service(
web::resource("/list")
.route(web::get().to(user::theme::list_all_themes_in_lineage)),
)
.service(
web::resource("/{theme_id}")
.route(web::get().to(user::theme::get_user_theme_using_theme_id))
.route(web::put().to(user::theme::update_user_theme))
.route(web::post().to(user::theme::upload_file_to_user_theme_storage))
.route(web::delete().to(user::theme::delete_user_theme)),
),
);
route
}
}
pub struct ConnectorOnboarding;
#[cfg(all(feature = "olap", feature = "v1"))]
impl ConnectorOnboarding {
pub fn server(state: AppState) -> Scope {
web::scope("/connector_onboarding")
.app_data(web::Data::new(state))
.service(
web::resource("/action_url")
.route(web::post().to(connector_onboarding::get_action_url)),
)
.service(
web::resource("/sync")
.route(web::post().to(connector_onboarding::sync_onboarding_status)),
)
.service(
web::resource("/reset_tracking_id")
.route(web::post().to(connector_onboarding::reset_tracking_id)),
)
}
}
#[cfg(feature = "olap")]
pub struct WebhookEvents;
#[cfg(all(feature = "olap", feature = "v1"))]
impl WebhookEvents {
pub fn server(config: AppState) -> Scope {
web::scope("/events")
.app_data(web::Data::new(config))
.service(web::scope("/profile/list").service(web::resource("").route(
web::post().to(webhook_events::list_initial_webhook_delivery_attempts_with_jwtauth),
)))
.service(
web::scope("/{merchant_id}")
.service(web::resource("").route(
web::post().to(webhook_events::list_initial_webhook_delivery_attempts),
))
.service(
web::scope("/{event_id}")
.service(web::resource("attempts").route(
web::get().to(webhook_events::list_webhook_delivery_attempts),
))
.service(web::resource("retry").route(
web::post().to(webhook_events::retry_webhook_delivery_attempt),
)),
),
)
}
}
#[cfg(feature = "olap")]
pub struct FeatureMatrix;
#[cfg(all(feature = "olap", feature = "v1"))]
impl FeatureMatrix {
pub fn server(state: AppState) -> Scope {
web::scope("/feature_matrix")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::get().to(feature_matrix::fetch_feature_matrix)))
}
}
#[cfg(feature = "olap")]
pub struct ProcessTrackerDeprecated;
#[cfg(all(feature = "olap", feature = "v2"))]
impl ProcessTrackerDeprecated {
pub fn server(state: AppState) -> Scope {
use super::process_tracker::revenue_recovery;
// TODO: Deprecated. Remove this in favour of /v2/process-trackers
web::scope("/v2/process_tracker/revenue_recovery_workflow")
.app_data(web::Data::new(state.clone()))
.service(
web::resource("/{revenue_recovery_id}")
.route(web::get().to(revenue_recovery::revenue_recovery_pt_retrieve_api)),
)
}
}
#[cfg(feature = "olap")]
pub struct ProcessTracker;
#[cfg(all(feature = "olap", feature = "v2"))]
impl ProcessTracker {
pub fn server(state: AppState) -> Scope {
use super::process_tracker::revenue_recovery;
web::scope("/v2/process-trackers/revenue-recovery-workflow")
.app_data(web::Data::new(state.clone()))
.service(
web::scope("/{revenue_recovery_id}")
.service(
web::resource("").route(
web::get().to(revenue_recovery::revenue_recovery_pt_retrieve_api),
),
)
.service(
web::resource("/resume")
.route(web::post().to(revenue_recovery::revenue_recovery_resume_api)),
),
)
}
}
pub struct Authentication;
#[cfg(feature = "v1")]
impl Authentication {
pub fn server(state: AppState) -> Scope {
web::scope("/authentication")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(authentication::authentication_create)))
.service(
web::resource("/{authentication_id}/eligibility")
.route(web::post().to(authentication::authentication_eligibility)),
)
.service(
web::resource("/{authentication_id}/authenticate")
.route(web::post().to(authentication::authentication_authenticate)),
)
.service(
web::resource("{merchant_id}/{authentication_id}/redirect")
.route(web::post().to(authentication::authentication_sync_post_update)),
)
.service(
web::resource("{merchant_id}/{authentication_id}/sync")
.route(web::post().to(authentication::authentication_sync)),
)
}
}
#[cfg(feature = "olap")]
pub struct ProfileAcquirer;
#[cfg(all(feature = "olap", feature = "v1"))]
impl ProfileAcquirer {
pub fn server(state: AppState) -> Scope {
web::scope("/profile_acquirer")
.app_data(web::Data::new(state))
.service(
web::resource("").route(web::post().to(profile_acquirer::create_profile_acquirer)),
)
.service(
web::resource("/{profile_id}/{profile_acquirer_id}")
.route(web::post().to(profile_acquirer::profile_acquirer_update)),
)
}
}
#[cfg(feature = "v2")]
pub struct RecoveryDataBackfill;
#[cfg(feature = "v2")]
impl RecoveryDataBackfill {
pub fn server(state: AppState) -> Scope {
web::scope("/v2/recovery/data-backfill")
.app_data(web::Data::new(state))
.service(
web::resource("").route(
web::post()
.to(super::revenue_recovery_data_backfill::revenue_recovery_data_backfill),
),
)
.service(web::resource("/status/{token_id}").route(
web::post().to(
super::revenue_recovery_data_backfill::revenue_recovery_data_backfill_status,
),
))
.service(web::resource("/redis-data/{token_id}").route(
web::get().to(
super::revenue_recovery_redis::get_revenue_recovery_redis_data,
),
))
.service(web::resource("/update-token").route(
web::put().to(
super::revenue_recovery_data_backfill::update_revenue_recovery_additional_redis_data,
),
))
}
}
| {
"crate": "router",
"file": "crates/router/src/routes/app.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 3,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_3175557744800189003 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/routes/dummy_connector/types.rs
// Contains: 13 structs, 10 enums
use api_models::enums::Currency;
use common_utils::{errors::CustomResult, generate_id_with_default_len, pii};
use error_stack::report;
use masking::Secret;
use router_env::types::FlowMetric;
use strum::Display;
use time::PrimitiveDateTime;
use super::{consts, errors::DummyConnectorErrors};
use crate::services;
#[derive(Debug, Display, Clone, PartialEq, Eq)]
#[allow(clippy::enum_variant_names)]
pub enum Flow {
DummyPaymentCreate,
DummyPaymentRetrieve,
DummyPaymentAuthorize,
DummyPaymentComplete,
DummyRefundCreate,
DummyRefundRetrieve,
}
impl FlowMetric for Flow {}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, strum::Display, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum DummyConnectors {
#[serde(rename = "phonypay")]
#[strum(serialize = "phonypay")]
PhonyPay,
#[serde(rename = "fauxpay")]
#[strum(serialize = "fauxpay")]
FauxPay,
#[serde(rename = "pretendpay")]
#[strum(serialize = "pretendpay")]
PretendPay,
StripeTest,
AdyenTest,
CheckoutTest,
PaypalTest,
}
impl DummyConnectors {
pub fn get_connector_image_link(self, base_url: &str) -> String {
let image_name = match self {
Self::PhonyPay => "PHONYPAY.svg",
Self::FauxPay => "FAUXPAY.svg",
Self::PretendPay => "PRETENDPAY.svg",
Self::StripeTest => "STRIPE_TEST.svg",
Self::PaypalTest => "PAYPAL_TEST.svg",
_ => "PHONYPAY.svg",
};
format!("{base_url}{image_name}")
}
}
#[derive(
Default, serde::Serialize, serde::Deserialize, strum::Display, Clone, PartialEq, Debug, Eq,
)]
#[serde(rename_all = "lowercase")]
pub enum DummyConnectorStatus {
Succeeded,
#[default]
Processing,
Failed,
}
#[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub struct DummyConnectorPaymentAttempt {
pub timestamp: PrimitiveDateTime,
pub attempt_id: String,
pub payment_id: common_utils::id_type::PaymentId,
pub payment_request: DummyConnectorPaymentRequest,
}
impl From<DummyConnectorPaymentRequest> for DummyConnectorPaymentAttempt {
fn from(payment_request: DummyConnectorPaymentRequest) -> Self {
let timestamp = common_utils::date_time::now();
let payment_id = common_utils::id_type::PaymentId::default();
let attempt_id = generate_id_with_default_len(consts::ATTEMPT_ID_PREFIX);
Self {
timestamp,
attempt_id,
payment_id,
payment_request,
}
}
}
impl DummyConnectorPaymentAttempt {
pub fn build_payment_data(
self,
status: DummyConnectorStatus,
next_action: Option<DummyConnectorNextAction>,
return_url: Option<String>,
) -> DummyConnectorPaymentData {
DummyConnectorPaymentData {
attempt_id: self.attempt_id,
payment_id: self.payment_id,
status,
amount: self.payment_request.amount,
eligible_amount: self.payment_request.amount,
connector: self.payment_request.connector,
created: self.timestamp,
currency: self.payment_request.currency,
payment_method_type: self.payment_request.payment_method_data.into(),
next_action,
return_url,
}
}
}
#[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub struct DummyConnectorPaymentRequest {
pub amount: i64,
pub currency: Currency,
pub payment_method_data: DummyConnectorPaymentMethodData,
pub return_url: Option<String>,
pub connector: DummyConnectors,
}
pub trait GetPaymentMethodDetails {
fn get_name(&self) -> &'static str;
fn get_image_link(&self, base_url: &str) -> String;
}
#[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DummyConnectorPaymentMethodData {
Card(DummyConnectorCard),
Upi(DummyConnectorUpi),
Wallet(DummyConnectorWallet),
PayLater(DummyConnectorPayLater),
}
#[derive(
Default, serde::Serialize, serde::Deserialize, strum::Display, PartialEq, Debug, Clone,
)]
#[serde(rename_all = "lowercase")]
pub enum DummyConnectorPaymentMethodType {
#[default]
Card,
Upi(DummyConnectorUpiType),
Wallet(DummyConnectorWallet),
PayLater(DummyConnectorPayLater),
}
impl From<DummyConnectorPaymentMethodData> for DummyConnectorPaymentMethodType {
fn from(value: DummyConnectorPaymentMethodData) -> Self {
match value {
DummyConnectorPaymentMethodData::Card(_) => Self::Card,
DummyConnectorPaymentMethodData::Upi(upi_data) => match upi_data {
DummyConnectorUpi::UpiCollect(_) => Self::Upi(DummyConnectorUpiType::UpiCollect),
},
DummyConnectorPaymentMethodData::Wallet(wallet) => Self::Wallet(wallet),
DummyConnectorPaymentMethodData::PayLater(pay_later) => Self::PayLater(pay_later),
}
}
}
impl GetPaymentMethodDetails for DummyConnectorPaymentMethodType {
fn get_name(&self) -> &'static str {
match self {
Self::Card => "3D Secure",
Self::Upi(upi_type) => upi_type.get_name(),
Self::Wallet(wallet) => wallet.get_name(),
Self::PayLater(pay_later) => pay_later.get_name(),
}
}
fn get_image_link(&self, base_url: &str) -> String {
match self {
Self::Card => format!("{}{}", base_url, "CARD.svg"),
Self::Upi(upi_type) => upi_type.get_image_link(base_url),
Self::Wallet(wallet) => wallet.get_image_link(base_url),
Self::PayLater(pay_later) => pay_later.get_image_link(base_url),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DummyConnectorCard {
pub name: Secret<String>,
pub number: cards::CardNumber,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub cvc: Secret<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DummyConnectorUpiCollect {
pub vpa_id: Secret<String, pii::UpiVpaMaskingStrategy>,
}
#[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DummyConnectorUpi {
UpiCollect(DummyConnectorUpiCollect),
}
pub enum DummyConnectorCardFlow {
NoThreeDS(DummyConnectorStatus, Option<DummyConnectorErrors>),
ThreeDS(DummyConnectorStatus, Option<DummyConnectorErrors>),
}
#[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub enum DummyConnectorWallet {
GooglePay,
Paypal,
WeChatPay,
MbWay,
AliPay,
AliPayHK,
}
#[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub enum DummyConnectorUpiType {
UpiCollect,
}
impl GetPaymentMethodDetails for DummyConnectorUpiType {
fn get_name(&self) -> &'static str {
match self {
Self::UpiCollect => "UPI Collect",
}
}
fn get_image_link(&self, base_url: &str) -> String {
let image_name = match self {
Self::UpiCollect => "UPI_COLLECT.svg",
};
format!("{base_url}{image_name}")
}
}
impl GetPaymentMethodDetails for DummyConnectorWallet {
fn get_name(&self) -> &'static str {
match self {
Self::GooglePay => "Google Pay",
Self::Paypal => "PayPal",
Self::WeChatPay => "WeChat Pay",
Self::MbWay => "Mb Way",
Self::AliPay => "Alipay",
Self::AliPayHK => "Alipay HK",
}
}
fn get_image_link(&self, base_url: &str) -> String {
let image_name = match self {
Self::GooglePay => "GOOGLE_PAY.svg",
Self::Paypal => "PAYPAL.svg",
Self::WeChatPay => "WECHAT_PAY.svg",
Self::MbWay => "MBWAY.svg",
Self::AliPay => "ALIPAY.svg",
Self::AliPayHK => "ALIPAY.svg",
};
format!("{base_url}{image_name}")
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
pub enum DummyConnectorPayLater {
Klarna,
Affirm,
AfterPayClearPay,
}
impl GetPaymentMethodDetails for DummyConnectorPayLater {
fn get_name(&self) -> &'static str {
match self {
Self::Klarna => "Klarna",
Self::Affirm => "Affirm",
Self::AfterPayClearPay => "Afterpay Clearpay",
}
}
fn get_image_link(&self, base_url: &str) -> String {
let image_name = match self {
Self::Klarna => "KLARNA.svg",
Self::Affirm => "AFFIRM.svg",
Self::AfterPayClearPay => "AFTERPAY.svg",
};
format!("{base_url}{image_name}")
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
pub struct DummyConnectorPaymentData {
pub attempt_id: String,
pub payment_id: common_utils::id_type::PaymentId,
pub status: DummyConnectorStatus,
pub amount: i64,
pub eligible_amount: i64,
pub currency: Currency,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created: PrimitiveDateTime,
pub payment_method_type: DummyConnectorPaymentMethodType,
pub connector: DummyConnectors,
pub next_action: Option<DummyConnectorNextAction>,
pub return_url: Option<String>,
}
impl DummyConnectorPaymentData {
pub fn is_eligible_for_refund(&self, refund_amount: i64) -> DummyConnectorResult<()> {
if self.eligible_amount < refund_amount {
return Err(
report!(DummyConnectorErrors::RefundAmountExceedsPaymentAmount)
.attach_printable("Eligible amount is lesser than refund amount"),
);
}
if self.status != DummyConnectorStatus::Succeeded {
return Err(report!(DummyConnectorErrors::PaymentNotSuccessful)
.attach_printable("Payment is not successful to process the refund"));
}
Ok(())
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum DummyConnectorNextAction {
RedirectToUrl(String),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DummyConnectorPaymentResponse {
pub status: DummyConnectorStatus,
pub id: common_utils::id_type::PaymentId,
pub amount: i64,
pub currency: Currency,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created: PrimitiveDateTime,
pub payment_method_type: DummyConnectorPaymentMethodType,
pub next_action: Option<DummyConnectorNextAction>,
}
impl From<DummyConnectorPaymentData> for DummyConnectorPaymentResponse {
fn from(value: DummyConnectorPaymentData) -> Self {
Self {
status: value.status,
id: value.payment_id,
amount: value.amount,
currency: value.currency,
created: value.created,
payment_method_type: value.payment_method_type,
next_action: value.next_action,
}
}
}
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DummyConnectorPaymentRetrieveRequest {
pub payment_id: String,
}
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DummyConnectorPaymentConfirmRequest {
pub attempt_id: String,
}
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DummyConnectorPaymentCompleteRequest {
pub attempt_id: String,
pub confirm: bool,
}
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DummyConnectorPaymentCompleteBody {
pub confirm: bool,
}
#[derive(Default, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub struct DummyConnectorRefundRequest {
pub amount: i64,
pub payment_id: Option<common_utils::id_type::PaymentId>,
}
#[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub struct DummyConnectorRefundResponse {
pub status: DummyConnectorStatus,
pub id: String,
pub currency: Currency,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created: PrimitiveDateTime,
pub payment_amount: i64,
pub refund_amount: i64,
}
impl DummyConnectorRefundResponse {
pub fn new(
status: DummyConnectorStatus,
id: String,
currency: Currency,
created: PrimitiveDateTime,
payment_amount: i64,
refund_amount: i64,
) -> Self {
Self {
status,
id,
currency,
created,
payment_amount,
refund_amount,
}
}
}
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DummyConnectorRefundRetrieveRequest {
pub refund_id: String,
}
pub type DummyConnectorResponse<T> =
CustomResult<services::ApplicationResponse<T>, DummyConnectorErrors>;
pub type DummyConnectorResult<T> = CustomResult<T, DummyConnectorErrors>;
pub struct DummyConnectorUpiFlow {
pub status: DummyConnectorStatus,
pub error: Option<DummyConnectorErrors>,
pub is_next_action_required: bool,
}
| {
"crate": "router",
"file": "crates/router/src/routes/dummy_connector/types.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 10,
"num_structs": 13,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_5260431726881870065 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/encryption.rs
// Contains: 2 structs, 1 enums
use std::str;
use error_stack::{report, ResultExt};
use josekit::{jwe, jws};
use serde::{Deserialize, Serialize};
use crate::{
core::errors::{self, CustomResult},
utils,
};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JwsBody {
pub header: String,
pub payload: String,
pub signature: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JweBody {
pub header: String,
pub iv: String,
pub encrypted_payload: String,
pub tag: String,
pub encrypted_key: String,
}
#[derive(Debug, Eq, PartialEq, Copy, Clone, strum::AsRefStr, strum::Display)]
pub enum EncryptionAlgorithm {
A128GCM,
A256GCM,
}
pub async fn encrypt_jwe(
payload: &[u8],
public_key: impl AsRef<[u8]>,
algorithm: EncryptionAlgorithm,
key_id: Option<&str>,
) -> CustomResult<String, errors::EncryptionError> {
let alg = jwe::RSA_OAEP_256;
let mut src_header = jwe::JweHeader::new();
let enc_str = algorithm.as_ref();
src_header.set_content_encryption(enc_str);
src_header.set_token_type("JWT");
if let Some(key_id) = key_id {
src_header.set_key_id(key_id);
}
let encrypter = alg
.encrypter_from_pem(public_key)
.change_context(errors::EncryptionError)
.attach_printable("Error getting JweEncryptor")?;
jwe::serialize_compact(payload, &src_header, &encrypter)
.change_context(errors::EncryptionError)
.attach_printable("Error getting jwt string")
}
pub enum KeyIdCheck<'a> {
RequestResponseKeyId((&'a str, &'a str)),
SkipKeyIdCheck,
}
pub async fn decrypt_jwe(
jwt: &str,
key_ids: KeyIdCheck<'_>,
private_key: impl AsRef<[u8]>,
alg: jwe::alg::rsaes::RsaesJweAlgorithm,
) -> CustomResult<String, errors::EncryptionError> {
if let KeyIdCheck::RequestResponseKeyId((req_key_id, resp_key_id)) = key_ids {
utils::when(req_key_id.ne(resp_key_id), || {
Err(report!(errors::EncryptionError)
.attach_printable("key_id mismatch, Error authenticating response"))
})?;
}
let decrypter = alg
.decrypter_from_pem(private_key)
.change_context(errors::EncryptionError)
.attach_printable("Error getting JweDecryptor")?;
let (dst_payload, _dst_header) = jwe::deserialize_compact(jwt, &decrypter)
.change_context(errors::EncryptionError)
.attach_printable("Error getting Decrypted jwe")?;
String::from_utf8(dst_payload)
.change_context(errors::EncryptionError)
.attach_printable("Could not decode JWE payload from UTF-8")
}
pub async fn jws_sign_payload(
payload: &[u8],
kid: &str,
private_key: impl AsRef<[u8]>,
) -> CustomResult<String, errors::EncryptionError> {
let alg = jws::RS256;
let mut src_header = jws::JwsHeader::new();
src_header.set_key_id(kid);
let signer = alg
.signer_from_pem(private_key)
.change_context(errors::EncryptionError)
.attach_printable("Error getting signer")?;
let jwt = jws::serialize_compact(payload, &src_header, &signer)
.change_context(errors::EncryptionError)
.attach_printable("Error getting signed jwt string")?;
Ok(jwt)
}
pub fn verify_sign(
jws_body: String,
key: impl AsRef<[u8]>,
) -> CustomResult<String, errors::EncryptionError> {
let alg = jws::RS256;
let input = jws_body.as_bytes();
let verifier = alg
.verifier_from_pem(key)
.change_context(errors::EncryptionError)
.attach_printable("Error getting verifier")?;
let (dst_payload, _dst_header) = jws::deserialize_compact(input, &verifier)
.change_context(errors::EncryptionError)
.attach_printable("Error getting Decrypted jws")?;
let resp = String::from_utf8(dst_payload)
.change_context(errors::EncryptionError)
.attach_printable("Could not convert to UTF-8")?;
Ok(resp)
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::*;
// Keys used for tests
// Can be generated using the following commands:
// `openssl genrsa -out private_key.pem 2048`
// `openssl rsa -in private_key.pem -pubout -out public_key.pem`
const ENCRYPTION_KEY: &str = "\
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwa6siKaSYqD1o4J3AbHq
Km8oVTvep7GoN/C45qY60C7DO72H1O7Ujt6ZsSiK83EyI0CaUg3ORPS3ayobFNmu
zR366ckK8GIf3BG7sVI6u/9751z4OvBHZMM9JFWa7Bx/RCPQ8aeM+iJoqf9auuQm
3NCTlfaZJif45pShswR+xuZTR/bqnsOSP/MFROI9ch0NE7KRogy0tvrZe21lP24i
Ro2LJJG+bYshxBddhxQf2ryJ85+/Trxdu16PunodGzCl6EMT3bvb4ZC41i15omqU
aXXV1Z1wYUhlsO0jyd1bVvjyuE/KE1TbBS0gfR/RkacODmmE2zEdZ0EyyiXwqkmc
oQIDAQAB
-----END PUBLIC KEY-----
";
const DECRYPTION_KEY: &str = "\
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAwa6siKaSYqD1o4J3AbHqKm8oVTvep7GoN/C45qY60C7DO72H
1O7Ujt6ZsSiK83EyI0CaUg3ORPS3ayobFNmuzR366ckK8GIf3BG7sVI6u/9751z4
OvBHZMM9JFWa7Bx/RCPQ8aeM+iJoqf9auuQm3NCTlfaZJif45pShswR+xuZTR/bq
nsOSP/MFROI9ch0NE7KRogy0tvrZe21lP24iRo2LJJG+bYshxBddhxQf2ryJ85+/
Trxdu16PunodGzCl6EMT3bvb4ZC41i15omqUaXXV1Z1wYUhlsO0jyd1bVvjyuE/K
E1TbBS0gfR/RkacODmmE2zEdZ0EyyiXwqkmcoQIDAQABAoIBAEavZwxgLmCMedl4
zdHyipF+C+w/c10kO05fLjwPQrujtWDiJOaTW0Pg/ZpoP33lO/UdqLR1kWgdH6ue
rE+Jun/lhyM3WiSsyw/X8PYgGotuDFw90+I+uu+NSY0vKOEu7UuC/siS66KGWEhi
h0xZ480G2jYKz43bXL1aVUEuTM5tsjtt0a/zm08DEluYwrmxaaTvHW2+8FOn3z8g
UMClV2mN9X3rwlRhKAI1RVlymV95LmkTgzA4wW/M4j0kk108ouY8bo9vowoqidpo
0zKGfnqbQCIZP1QY6Xj8f3fqMY7IrFDdFHCEBXs29DnRz4oS8gYCAUXDx5iEVa1R
KVxic5kCgYEA4vGWOANuv+RoxSnNQNnZjqHKjhd+9lXARnK6qVVXcJGTps72ILGJ
CNrS/L6ndBePQGhtLtVyrvtS3ZvYhsAzJeMeeFUSZhQ2SOP5SCFWRnLJIBObJ5/x
fFwrCbp38qsEBlqJXue4JQCOxqO4P6YYUmeE8fxLPmdVNWq5fNe2YtsCgYEA2nrl
iMfttvNfQGX4pB3yEh/eWwqq4InFQdmWVDYPKJFG4TtUKJ48vzQXJqKfCBZ2q387
bH4KaKNWD7rYz4NBfE6z6lUc8We9w1tjVaqs5omBKUuovz8/8miUtxf2W5T2ta1/
zl9NyQ57duO423PeaCgPKKz3ftaxlz8G1CKYMTMCgYEAqkR7YhchNpOWD6cnOeq4
kYzNvgHe3c7EbZaSeY1wByMR1mscura4i44yEjKwzCcI8Vfn4uV+H86sA1xz/dWi
CmD2cW3SWgf8GoAAfZ+VbVGdmJVdKUOVGKrGF4xxhf3NDT9MJYpQ3GIovNwE1qw1
P04vrqaNhYpdobAq7oGhc1UCgYAkimNzcgTHEYM/0Q453KxM7bmRvoH/1esA7XRg
Fz6HyWxyZSrZNEXysLKiipZQkvk8C6aTqazx/Ud6kASNCGXedYdPzPZvRauOTe2a
OVZ7pEnO71GE0v5N+8HLsZ1JieuNTTxP9s6aruplYwba5VEwWGrYob0vIJdJNYhd
2H9d0wKBgFzqGPvG8u1lVOLYDU9BjhA/3l00C97WHIG0Aal70PVyhFhm5ILNSHU1
Sau7H1Bhzy5G7rwt05LNpU6nFcAGVaZtzl4/+FYfYIulubYjuSEh72yuBHHyvi1/
4Zql8DXhF5kkKx75cMcIxZ/ceiRiQyjzYv3LoTTADHHjzsiBEiQY
-----END RSA PRIVATE KEY-----
";
const SIGNATURE_VERIFICATION_KEY: &str = "\
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5Z/K0JWds8iHhWCa+rj0
rhOQX1nVs/ArQ1D0vh3UlSPR2vZUTrkdP7i3amv4d2XDC+3+5/YWExTkpxqnfl1T
9J37leN2guAARed6oYoTDEP/OoKtnUrKK2xk/+V5DNOWcRiSpcCrJOOIEoACOlPI
rXQSg16KDZQb0QTMntnsiPIJDbsOGcdKytRAcNaokiKLnia1v13N3bk6dSplrj1Y
zawslZfgqD0eov4FjzBMoA19yNtlVLLf6kOkLcFQjTKXJLP1tLflLUBPTg8fm9wg
APK2BjMQ2AMkUxx0ubbtw/9CeJ+bFWrqGnEhlvfDMlyAV77sAiIdQ4mXs3TLcLb/
AQIDAQAB
-----END PUBLIC KEY-----
";
const SIGNING_KEY: &str = "\
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA5Z/K0JWds8iHhWCa+rj0rhOQX1nVs/ArQ1D0vh3UlSPR2vZU
TrkdP7i3amv4d2XDC+3+5/YWExTkpxqnfl1T9J37leN2guAARed6oYoTDEP/OoKt
nUrKK2xk/+V5DNOWcRiSpcCrJOOIEoACOlPIrXQSg16KDZQb0QTMntnsiPIJDbsO
GcdKytRAcNaokiKLnia1v13N3bk6dSplrj1YzawslZfgqD0eov4FjzBMoA19yNtl
VLLf6kOkLcFQjTKXJLP1tLflLUBPTg8fm9wgAPK2BjMQ2AMkUxx0ubbtw/9CeJ+b
FWrqGnEhlvfDMlyAV77sAiIdQ4mXs3TLcLb/AQIDAQABAoIBAGNekD1N0e5AZG1S
zh6cNb6zVrH8xV9WGtLJ0PAJJrrXwnQYT4m10DOIM0+Jo/+/ePXLq5kkRI9DZmPu
Q/eKWc+tInfN9LZUS6n0r3wCrZWMQ4JFlO5RtEWwZdDbtFPZqOwObz/treKL2JHw
9YXaRijR50UUf3e61YLRqd9AfX0RNuuG8H+WgU3Gwuh5TwRnljM3JGaDPHsf7HLS
tNkqJuByp26FEbOLTokZDbHN0sy7/6hufxnIS9AK4vp8y9mZAjghG26Rbg/H71mp
Z+Q6P1y7xdgAKbhq7usG3/o4Y1e9wnghHvFS7DPwGekHQH2+LsYNEYOir1iRjXxH
GUXOhfUCgYEA+cR9jONQFco8Zp6z0wdGlBeYoUHVMjThQWEblWL2j4RG/qQd/y0j
uhVeU0/PmkYK2mgcjrh/pgDTtPymc+QuxBi+lexs89ppuJIAgMvLUiJT67SBHguP
l4+oL9U78KGh7PfJpMKH+Pk5yc1xucAevk0wWmr5Tz2vKRDavFTPV+MCgYEA61qg
Y7yN0cDtxtqlZdMC8BJPFCQ1+s3uB0wetAY3BEKjfYc2O/4sMbixXzt5PkZqZy96
QBUBxhcM/rIolpM3nrgN7h1nmJdk9ljCTjWoTJ6fDk8BUh8+0GrVhTbe7xZ+bFUN
UioIqvfapr/q/k7Ah2mCBE04wTZFry9fndrH2ssCgYEAh1T2Cj6oiAX6UEgxe2h3
z4oxgz6efAO3AavSPFFQ81Zi+VqHflpA/3TQlSerfxXwj4LV5mcFkzbjfy9eKXE7
/bjCm41tQ3vWyNEjQKYr1qcO/aniRBtThHWsVa6eObX6fOGN+p4E+txfeX693j3A
6q/8QSGxUERGAmRFgMIbTq0CgYAmuTeQkXKII4U75be3BDwEgg6u0rJq/L0ASF74
4djlg41g1wFuZ4if+bJ9Z8ywGWfiaGZl6s7q59oEgg25kKljHQd1uTLVYXuEKOB3
e86gJK0o7ojaGTf9lMZi779IeVv9uRTDAxWAA93e987TXuPAo/R3frkq2SIoC9Rg
paGidwKBgBqYd/iOJWsUZ8cWEhSE1Huu5rDEpjra8JPXHqQdILirxt1iCA5aEQou
BdDGaDr8sepJbGtjwTyiG8gEaX1DD+KsF2+dQRQdQfcYC40n8fKkvpFwrKjDj1ac
VuY3OeNxi+dC2r7HppP3O/MJ4gX/RJJfSrcaGP8/Ke1W5+jE97Qy
-----END RSA PRIVATE KEY-----
";
#[actix_rt::test]
async fn test_jwe() {
let jwt = encrypt_jwe(
"request_payload".as_bytes(),
ENCRYPTION_KEY,
EncryptionAlgorithm::A256GCM,
None,
)
.await
.unwrap();
let alg = jwe::RSA_OAEP_256;
let payload = decrypt_jwe(&jwt, KeyIdCheck::SkipKeyIdCheck, DECRYPTION_KEY, alg)
.await
.unwrap();
assert_eq!("request_payload".to_string(), payload)
}
#[actix_rt::test]
async fn test_jws() {
let jwt = jws_sign_payload("jws payload".as_bytes(), "1", SIGNING_KEY)
.await
.unwrap();
let payload = verify_sign(jwt, SIGNATURE_VERIFICATION_KEY).unwrap();
assert_eq!("jws payload".to_string(), payload)
}
}
| {
"crate": "router",
"file": "crates/router/src/services/encryption.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_8259361696943312044 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/kafka.rs
// Contains: 5 structs, 1 enums
use std::{collections::HashMap, sync::Arc};
use common_utils::{errors::CustomResult, types::TenantConfig};
use error_stack::{report, ResultExt};
use events::{EventsError, Message, MessagingInterface};
use num_traits::ToPrimitive;
use rdkafka::{
config::FromClientConfig,
message::{Header, OwnedHeaders},
producer::{BaseRecord, DefaultProducerContext, Producer, ThreadedProducer},
};
use serde_json::Value;
#[cfg(feature = "payouts")]
pub mod payout;
use diesel_models::fraud_check::FraudCheck;
use crate::{events::EventType, services::kafka::fraud_check_event::KafkaFraudCheckEvent};
mod authentication;
mod authentication_event;
mod dispute;
mod dispute_event;
mod fraud_check;
mod fraud_check_event;
mod payment_attempt;
mod payment_attempt_event;
mod payment_intent;
mod payment_intent_event;
mod refund;
mod refund_event;
pub mod revenue_recovery;
use diesel_models::{authentication::Authentication, refund::Refund};
use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
use serde::Serialize;
use time::{OffsetDateTime, PrimitiveDateTime};
#[cfg(feature = "payouts")]
use self::payout::KafkaPayout;
use self::{
authentication::KafkaAuthentication, authentication_event::KafkaAuthenticationEvent,
dispute::KafkaDispute, dispute_event::KafkaDisputeEvent, payment_attempt::KafkaPaymentAttempt,
payment_attempt_event::KafkaPaymentAttemptEvent, payment_intent::KafkaPaymentIntent,
payment_intent_event::KafkaPaymentIntentEvent, refund::KafkaRefund,
refund_event::KafkaRefundEvent,
};
use crate::{services::kafka::fraud_check::KafkaFraudCheck, types::storage::Dispute};
// Using message queue result here to avoid confusion with Kafka result provided by library
pub type MQResult<T> = CustomResult<T, KafkaError>;
use crate::db::kafka_store::TenantID;
pub trait KafkaMessage
where
Self: Serialize + std::fmt::Debug,
{
fn value(&self) -> MQResult<Vec<u8>> {
// Add better error logging here
serde_json::to_vec(&self).change_context(KafkaError::GenericError)
}
fn key(&self) -> String;
fn event_type(&self) -> EventType;
fn creation_timestamp(&self) -> Option<i64> {
None
}
}
#[derive(serde::Serialize, Debug)]
struct KafkaEvent<'a, T: KafkaMessage> {
#[serde(flatten)]
event: &'a T,
sign_flag: i32,
tenant_id: TenantID,
clickhouse_database: Option<String>,
}
impl<'a, T: KafkaMessage> KafkaEvent<'a, T> {
fn new(event: &'a T, tenant_id: TenantID, clickhouse_database: Option<String>) -> Self {
Self {
event,
sign_flag: 1,
tenant_id,
clickhouse_database,
}
}
fn old(event: &'a T, tenant_id: TenantID, clickhouse_database: Option<String>) -> Self {
Self {
event,
sign_flag: -1,
tenant_id,
clickhouse_database,
}
}
}
impl<T: KafkaMessage> KafkaMessage for KafkaEvent<'_, T> {
fn key(&self) -> String {
self.event.key()
}
fn event_type(&self) -> EventType {
self.event.event_type()
}
fn creation_timestamp(&self) -> Option<i64> {
self.event.creation_timestamp()
}
}
#[derive(serde::Serialize, Debug)]
struct KafkaConsolidatedLog<'a, T: KafkaMessage> {
#[serde(flatten)]
event: &'a T,
tenant_id: TenantID,
}
#[derive(serde::Serialize, Debug)]
struct KafkaConsolidatedEvent<'a, T: KafkaMessage> {
log: KafkaConsolidatedLog<'a, T>,
log_type: EventType,
}
impl<'a, T: KafkaMessage> KafkaConsolidatedEvent<'a, T> {
fn new(event: &'a T, tenant_id: TenantID) -> Self {
Self {
log: KafkaConsolidatedLog { event, tenant_id },
log_type: event.event_type(),
}
}
}
impl<T: KafkaMessage> KafkaMessage for KafkaConsolidatedEvent<'_, T> {
fn key(&self) -> String {
self.log.event.key()
}
fn event_type(&self) -> EventType {
EventType::Consolidated
}
fn creation_timestamp(&self) -> Option<i64> {
self.log.event.creation_timestamp()
}
}
#[derive(Debug, serde::Deserialize, Clone, Default)]
#[serde(default)]
pub struct KafkaSettings {
brokers: Vec<String>,
fraud_check_analytics_topic: String,
intent_analytics_topic: String,
attempt_analytics_topic: String,
refund_analytics_topic: String,
api_logs_topic: String,
connector_logs_topic: String,
outgoing_webhook_logs_topic: String,
dispute_analytics_topic: String,
audit_events_topic: String,
#[cfg(feature = "payouts")]
payout_analytics_topic: String,
consolidated_events_topic: String,
authentication_analytics_topic: String,
routing_logs_topic: String,
revenue_recovery_topic: String,
}
impl KafkaSettings {
pub fn validate(&self) -> Result<(), crate::core::errors::ApplicationError> {
use common_utils::ext_traits::ConfigExt;
use crate::core::errors::ApplicationError;
common_utils::fp_utils::when(self.brokers.is_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka brokers must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.intent_analytics_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Intent Analytics topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.attempt_analytics_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Attempt Analytics topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.refund_analytics_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Refund Analytics topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.api_logs_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka API event Analytics topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.connector_logs_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Connector Logs topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(
self.outgoing_webhook_logs_topic.is_default_or_empty(),
|| {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Outgoing Webhook Logs topic must not be empty".into(),
))
},
)?;
common_utils::fp_utils::when(self.dispute_analytics_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Dispute Logs topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.audit_events_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Audit Events topic must not be empty".into(),
))
})?;
#[cfg(feature = "payouts")]
common_utils::fp_utils::when(self.payout_analytics_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Payout Analytics topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.consolidated_events_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Consolidated Events topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(
self.authentication_analytics_topic.is_default_or_empty(),
|| {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Authentication Analytics topic must not be empty".into(),
))
},
)?;
common_utils::fp_utils::when(self.routing_logs_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Routing Logs topic must not be empty".into(),
))
})?;
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct KafkaProducer {
producer: Arc<RdKafkaProducer>,
intent_analytics_topic: String,
fraud_check_analytics_topic: String,
attempt_analytics_topic: String,
refund_analytics_topic: String,
api_logs_topic: String,
connector_logs_topic: String,
outgoing_webhook_logs_topic: String,
dispute_analytics_topic: String,
audit_events_topic: String,
#[cfg(feature = "payouts")]
payout_analytics_topic: String,
consolidated_events_topic: String,
authentication_analytics_topic: String,
ckh_database_name: Option<String>,
routing_logs_topic: String,
revenue_recovery_topic: String,
}
struct RdKafkaProducer(ThreadedProducer<DefaultProducerContext>);
impl std::fmt::Debug for RdKafkaProducer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("RdKafkaProducer")
}
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum KafkaError {
#[error("Generic Kafka Error")]
GenericError,
#[error("Kafka not implemented")]
NotImplemented,
#[error("Kafka Initialization Error")]
InitializationError,
}
#[allow(unused)]
impl KafkaProducer {
pub fn set_tenancy(&mut self, tenant_config: &dyn TenantConfig) {
self.ckh_database_name = Some(tenant_config.get_clickhouse_database().to_string());
}
pub async fn create(conf: &KafkaSettings) -> MQResult<Self> {
Ok(Self {
producer: Arc::new(RdKafkaProducer(
ThreadedProducer::from_config(
rdkafka::ClientConfig::new().set("bootstrap.servers", conf.brokers.join(",")),
)
.change_context(KafkaError::InitializationError)?,
)),
fraud_check_analytics_topic: conf.fraud_check_analytics_topic.clone(),
intent_analytics_topic: conf.intent_analytics_topic.clone(),
attempt_analytics_topic: conf.attempt_analytics_topic.clone(),
refund_analytics_topic: conf.refund_analytics_topic.clone(),
api_logs_topic: conf.api_logs_topic.clone(),
connector_logs_topic: conf.connector_logs_topic.clone(),
outgoing_webhook_logs_topic: conf.outgoing_webhook_logs_topic.clone(),
dispute_analytics_topic: conf.dispute_analytics_topic.clone(),
audit_events_topic: conf.audit_events_topic.clone(),
#[cfg(feature = "payouts")]
payout_analytics_topic: conf.payout_analytics_topic.clone(),
consolidated_events_topic: conf.consolidated_events_topic.clone(),
authentication_analytics_topic: conf.authentication_analytics_topic.clone(),
ckh_database_name: None,
routing_logs_topic: conf.routing_logs_topic.clone(),
revenue_recovery_topic: conf.revenue_recovery_topic.clone(),
})
}
pub fn log_event<T: KafkaMessage>(&self, event: &T) -> MQResult<()> {
router_env::logger::debug!("Logging Kafka Event {event:?}");
let topic = self.get_topic(event.event_type());
self.producer
.0
.send(
BaseRecord::to(topic)
.key(&event.key())
.payload(&event.value()?)
.timestamp(event.creation_timestamp().unwrap_or_else(|| {
(OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000)
.try_into()
.unwrap_or_else(|_| {
// kafka producer accepts milliseconds
// try converting nanos to millis if that fails convert seconds to millis
OffsetDateTime::now_utc().unix_timestamp() * 1_000
})
})),
)
.map_err(|(error, record)| report!(error).attach_printable(format!("{record:?}")))
.change_context(KafkaError::GenericError)
}
pub async fn log_fraud_check(
&self,
attempt: &FraudCheck,
old_attempt: Option<FraudCheck>,
tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_attempt {
self.log_event(&KafkaEvent::old(
&KafkaFraudCheck::from_storage(&negative_event),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative fraud check event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
&KafkaFraudCheck::from_storage(attempt),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add positive fraud check event {attempt:?}")
})?;
self.log_event(&KafkaConsolidatedEvent::new(
&KafkaFraudCheckEvent::from_storage(attempt),
tenant_id.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add consolidated fraud check event {attempt:?}")
})
}
pub async fn log_payment_attempt(
&self,
attempt: &PaymentAttempt,
old_attempt: Option<PaymentAttempt>,
tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_attempt {
self.log_event(&KafkaEvent::old(
&KafkaPaymentAttempt::from_storage(&negative_event),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative attempt event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
&KafkaPaymentAttempt::from_storage(attempt),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| format!("Failed to add positive attempt event {attempt:?}"))?;
self.log_event(&KafkaConsolidatedEvent::new(
&KafkaPaymentAttemptEvent::from_storage(attempt),
tenant_id.clone(),
))
.attach_printable_lazy(|| format!("Failed to add consolidated attempt event {attempt:?}"))
}
pub async fn log_payment_attempt_delete(
&self,
delete_old_attempt: &PaymentAttempt,
tenant_id: TenantID,
) -> MQResult<()> {
self.log_event(&KafkaEvent::old(
&KafkaPaymentAttempt::from_storage(delete_old_attempt),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative attempt event {delete_old_attempt:?}")
})
}
pub async fn log_authentication(
&self,
authentication: &Authentication,
old_authentication: Option<Authentication>,
tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_authentication {
self.log_event(&KafkaEvent::old(
&KafkaAuthentication::from_storage(&negative_event),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative authentication event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
&KafkaAuthentication::from_storage(authentication),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add positive authentication event {authentication:?}")
})?;
self.log_event(&KafkaConsolidatedEvent::new(
&KafkaAuthenticationEvent::from_storage(authentication),
tenant_id.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add consolidated authentication event {authentication:?}")
})
}
pub async fn log_payment_intent(
&self,
intent: &PaymentIntent,
old_intent: Option<PaymentIntent>,
tenant_id: TenantID,
infra_values: Option<Value>,
) -> MQResult<()> {
if let Some(negative_event) = old_intent {
self.log_event(&KafkaEvent::old(
&KafkaPaymentIntent::from_storage(&negative_event, infra_values.clone()),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative intent event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
&KafkaPaymentIntent::from_storage(intent, infra_values.clone()),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| format!("Failed to add positive intent event {intent:?}"))?;
self.log_event(&KafkaConsolidatedEvent::new(
&KafkaPaymentIntentEvent::from_storage(intent, infra_values.clone()),
tenant_id.clone(),
))
.attach_printable_lazy(|| format!("Failed to add consolidated intent event {intent:?}"))
}
pub async fn log_payment_intent_delete(
&self,
delete_old_intent: &PaymentIntent,
tenant_id: TenantID,
infra_values: Option<Value>,
) -> MQResult<()> {
self.log_event(&KafkaEvent::old(
&KafkaPaymentIntent::from_storage(delete_old_intent, infra_values),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative intent event {delete_old_intent:?}")
})
}
pub async fn log_refund(
&self,
refund: &Refund,
old_refund: Option<Refund>,
tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_refund {
self.log_event(&KafkaEvent::old(
&KafkaRefund::from_storage(&negative_event),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative refund event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
&KafkaRefund::from_storage(refund),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| format!("Failed to add positive refund event {refund:?}"))?;
self.log_event(&KafkaConsolidatedEvent::new(
&KafkaRefundEvent::from_storage(refund),
tenant_id.clone(),
))
.attach_printable_lazy(|| format!("Failed to add consolidated refund event {refund:?}"))
}
pub async fn log_refund_delete(
&self,
delete_old_refund: &Refund,
tenant_id: TenantID,
) -> MQResult<()> {
self.log_event(&KafkaEvent::old(
&KafkaRefund::from_storage(delete_old_refund),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative refund event {delete_old_refund:?}")
})
}
pub async fn log_dispute(
&self,
dispute: &Dispute,
old_dispute: Option<Dispute>,
tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_dispute {
self.log_event(&KafkaEvent::old(
&KafkaDispute::from_storage(&negative_event),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative dispute event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
&KafkaDispute::from_storage(dispute),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| format!("Failed to add positive dispute event {dispute:?}"))?;
self.log_event(&KafkaConsolidatedEvent::new(
&KafkaDisputeEvent::from_storage(dispute),
tenant_id.clone(),
))
.attach_printable_lazy(|| format!("Failed to add consolidated dispute event {dispute:?}"))
}
pub async fn log_dispute_delete(
&self,
delete_old_dispute: &Dispute,
tenant_id: TenantID,
) -> MQResult<()> {
self.log_event(&KafkaEvent::old(
&KafkaDispute::from_storage(delete_old_dispute),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative dispute event {delete_old_dispute:?}")
})
}
#[cfg(feature = "payouts")]
pub async fn log_payout(
&self,
payout: &KafkaPayout<'_>,
old_payout: Option<KafkaPayout<'_>>,
tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_payout {
self.log_event(&KafkaEvent::old(
&negative_event,
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative payout event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
payout,
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| format!("Failed to add positive payout event {payout:?}"))
}
#[cfg(feature = "payouts")]
pub async fn log_payout_delete(
&self,
delete_old_payout: &KafkaPayout<'_>,
tenant_id: TenantID,
) -> MQResult<()> {
self.log_event(&KafkaEvent::old(
delete_old_payout,
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative payout event {delete_old_payout:?}")
})
}
pub fn get_topic(&self, event: EventType) -> &str {
match event {
EventType::FraudCheck => &self.fraud_check_analytics_topic,
EventType::ApiLogs => &self.api_logs_topic,
EventType::PaymentAttempt => &self.attempt_analytics_topic,
EventType::PaymentIntent => &self.intent_analytics_topic,
EventType::Refund => &self.refund_analytics_topic,
EventType::ConnectorApiLogs => &self.connector_logs_topic,
EventType::OutgoingWebhookLogs => &self.outgoing_webhook_logs_topic,
EventType::Dispute => &self.dispute_analytics_topic,
EventType::AuditEvent => &self.audit_events_topic,
#[cfg(feature = "payouts")]
EventType::Payout => &self.payout_analytics_topic,
EventType::Consolidated => &self.consolidated_events_topic,
EventType::Authentication => &self.authentication_analytics_topic,
EventType::RoutingApiLogs => &self.routing_logs_topic,
EventType::RevenueRecovery => &self.revenue_recovery_topic,
}
}
}
impl Drop for RdKafkaProducer {
fn drop(&mut self) {
// Flush the producer to send any pending messages
match self.0.flush(rdkafka::util::Timeout::After(
std::time::Duration::from_secs(5),
)) {
Ok(_) => router_env::logger::info!("Kafka events flush Successful"),
Err(error) => router_env::logger::error!("Failed to flush Kafka Events {error:?}"),
}
}
}
impl MessagingInterface for KafkaProducer {
type MessageClass = EventType;
fn send_message<T>(
&self,
data: T,
metadata: HashMap<String, String>,
timestamp: PrimitiveDateTime,
) -> error_stack::Result<(), EventsError>
where
T: Message<Class = Self::MessageClass> + masking::ErasedMaskSerialize,
{
let topic = self.get_topic(data.get_message_class());
let json_data = data
.masked_serialize()
.and_then(|mut value| {
if let Value::Object(ref mut map) = value {
if let Some(db_name) = self.ckh_database_name.clone() {
map.insert("clickhouse_database".to_string(), Value::String(db_name));
}
}
serde_json::to_vec(&value)
})
.change_context(EventsError::SerializationError)?;
let mut headers = OwnedHeaders::new();
for (k, v) in metadata.iter() {
headers = headers.insert(Header {
key: k.as_str(),
value: Some(v),
});
}
headers = headers.insert(Header {
key: "clickhouse_database",
value: self.ckh_database_name.as_ref(),
});
self.producer
.0
.send(
BaseRecord::to(topic)
.key(&data.identifier())
.payload(&json_data)
.headers(headers)
.timestamp(
(timestamp.assume_utc().unix_timestamp_nanos() / 1_000_000)
.to_i64()
.unwrap_or_else(|| {
// kafka producer accepts milliseconds
// try converting nanos to millis if that fails convert seconds to millis
timestamp.assume_utc().unix_timestamp() * 1_000
}),
),
)
.map_err(|(error, record)| report!(error).attach_printable(format!("{record:?}")))
.change_context(KafkaError::GenericError)
.change_context(EventsError::PublishError)
}
}
| {
"crate": "router",
"file": "crates/router/src/services/kafka.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 5,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_3143730847672236501 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/authentication.rs
// Contains: 36 structs, 2 enums
use std::str::FromStr;
use actix_web::http::header::HeaderMap;
#[cfg(feature = "v2")]
use api_models::payment_methods::PaymentMethodIntentConfirm;
#[cfg(feature = "v1")]
use api_models::payment_methods::{PaymentMethodCreate, PaymentMethodListRequest};
use api_models::payments;
#[cfg(feature = "payouts")]
use api_models::payouts;
use async_trait::async_trait;
use common_enums::TokenPurpose;
use common_utils::{date_time, fp_utils, id_type};
#[cfg(feature = "v2")]
use diesel_models::ephemeral_key;
use error_stack::{report, ResultExt};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
#[cfg(feature = "v2")]
use masking::ExposeInterface;
use masking::PeekInterface;
use router_env::logger;
use serde::Serialize;
use self::blacklist::BlackList;
#[cfg(all(feature = "partial-auth", feature = "v1"))]
use self::detached::ExtractedPayload;
#[cfg(feature = "partial-auth")]
use self::detached::GetAuthType;
use super::authorization::{self, permissions::Permission};
#[cfg(feature = "olap")]
use super::jwt;
#[cfg(feature = "olap")]
use crate::configs::Settings;
#[cfg(feature = "olap")]
use crate::consts;
#[cfg(feature = "olap")]
use crate::core::errors::UserResult;
#[cfg(all(feature = "partial-auth", feature = "v1"))]
use crate::core::metrics;
use crate::{
configs::settings,
core::{
api_keys,
errors::{self, utils::StorageErrorExt, RouterResult},
},
headers,
routes::app::SessionStateInfo,
services::api,
types::{domain, storage},
utils::OptionExt,
};
pub mod blacklist;
pub mod cookies;
pub mod decision;
#[cfg(feature = "partial-auth")]
mod detached;
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub struct AuthenticationData {
pub merchant_account: domain::MerchantAccount,
pub platform_merchant_account: Option<domain::MerchantAccount>,
pub key_store: domain::MerchantKeyStore,
pub profile_id: Option<id_type::ProfileId>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct AuthenticationData {
pub merchant_account: domain::MerchantAccount,
pub key_store: domain::MerchantKeyStore,
pub profile: domain::Profile,
pub platform_merchant_account: Option<domain::MerchantAccount>,
}
#[derive(Clone, Debug)]
pub struct AuthenticationDataWithoutProfile {
pub merchant_account: domain::MerchantAccount,
pub key_store: domain::MerchantKeyStore,
}
#[derive(Clone, Debug)]
pub struct AuthenticationDataWithMultipleProfiles {
pub merchant_account: domain::MerchantAccount,
pub key_store: domain::MerchantKeyStore,
pub profile_id_list: Option<Vec<id_type::ProfileId>>,
}
#[derive(Clone, Debug)]
pub struct AuthenticationDataWithUser {
pub merchant_account: domain::MerchantAccount,
pub key_store: domain::MerchantKeyStore,
pub user: storage::User,
pub profile_id: id_type::ProfileId,
}
#[derive(Clone, Debug)]
pub struct AuthenticationDataWithOrg {
pub organization_id: id_type::OrganizationId,
}
#[derive(Clone)]
pub struct UserFromTokenWithRoleInfo {
pub user: UserFromToken,
pub role_info: authorization::roles::RoleInfo,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(
tag = "api_auth_type",
content = "authentication_data",
rename_all = "snake_case"
)]
pub enum AuthenticationType {
ApiKey {
merchant_id: id_type::MerchantId,
key_id: id_type::ApiKeyId,
},
AdminApiKey,
AdminApiAuthWithMerchantId {
merchant_id: id_type::MerchantId,
},
OrganizationJwt {
org_id: id_type::OrganizationId,
user_id: String,
},
MerchantJwt {
merchant_id: id_type::MerchantId,
user_id: Option<String>,
},
MerchantJwtWithProfileId {
merchant_id: id_type::MerchantId,
profile_id: Option<id_type::ProfileId>,
user_id: String,
},
UserJwt {
user_id: String,
},
SinglePurposeJwt {
user_id: String,
purpose: TokenPurpose,
},
SinglePurposeOrLoginJwt {
user_id: String,
purpose: Option<TokenPurpose>,
role_id: Option<String>,
},
MerchantId {
merchant_id: id_type::MerchantId,
},
PublishableKey {
merchant_id: id_type::MerchantId,
},
WebhookAuth {
merchant_id: id_type::MerchantId,
},
InternalMerchantIdProfileId {
merchant_id: id_type::MerchantId,
profile_id: Option<id_type::ProfileId>,
},
NoAuth,
}
impl events::EventInfo for AuthenticationType {
type Data = Self;
fn data(&self) -> error_stack::Result<Self::Data, events::EventsError> {
Ok(self.clone())
}
fn key(&self) -> String {
"auth_info".to_string()
}
}
impl AuthenticationType {
pub fn get_merchant_id(&self) -> Option<&id_type::MerchantId> {
match self {
Self::ApiKey {
merchant_id,
key_id: _,
}
| Self::AdminApiAuthWithMerchantId { merchant_id }
| Self::MerchantId { merchant_id }
| Self::PublishableKey { merchant_id }
| Self::MerchantJwt {
merchant_id,
user_id: _,
}
| Self::MerchantJwtWithProfileId { merchant_id, .. }
| Self::WebhookAuth { merchant_id }
| Self::InternalMerchantIdProfileId { merchant_id, .. } => Some(merchant_id),
Self::AdminApiKey
| Self::OrganizationJwt { .. }
| Self::UserJwt { .. }
| Self::SinglePurposeJwt { .. }
| Self::SinglePurposeOrLoginJwt { .. }
| Self::NoAuth => None,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, serde::Deserialize, strum::Display)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ExternalServiceType {
Hypersense,
}
#[cfg(feature = "olap")]
#[derive(Clone, Debug)]
pub struct UserFromSinglePurposeToken {
pub user_id: String,
pub origin: domain::Origin,
pub path: Vec<TokenPurpose>,
pub tenant_id: Option<id_type::TenantId>,
}
#[cfg(feature = "olap")]
#[derive(serde::Serialize, serde::Deserialize)]
pub struct SinglePurposeToken {
pub user_id: String,
pub purpose: TokenPurpose,
pub origin: domain::Origin,
pub path: Vec<TokenPurpose>,
pub exp: u64,
pub tenant_id: Option<id_type::TenantId>,
}
#[cfg(feature = "olap")]
impl SinglePurposeToken {
pub async fn new_token(
user_id: String,
purpose: TokenPurpose,
origin: domain::Origin,
settings: &Settings,
path: Vec<TokenPurpose>,
tenant_id: Option<id_type::TenantId>,
) -> UserResult<String> {
let exp_duration =
std::time::Duration::from_secs(consts::SINGLE_PURPOSE_TOKEN_TIME_IN_SECS);
let exp = jwt::generate_exp(exp_duration)?.as_secs();
let token_payload = Self {
user_id,
purpose,
origin,
exp,
path,
tenant_id,
};
jwt::generate_jwt(&token_payload, settings).await
}
}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct AuthToken {
pub user_id: String,
pub merchant_id: id_type::MerchantId,
pub role_id: String,
pub exp: u64,
pub org_id: id_type::OrganizationId,
pub profile_id: id_type::ProfileId,
pub tenant_id: Option<id_type::TenantId>,
}
#[cfg(feature = "olap")]
impl AuthToken {
pub async fn new_token(
user_id: String,
merchant_id: id_type::MerchantId,
role_id: String,
settings: &Settings,
org_id: id_type::OrganizationId,
profile_id: id_type::ProfileId,
tenant_id: Option<id_type::TenantId>,
) -> UserResult<String> {
let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS);
let exp = jwt::generate_exp(exp_duration)?.as_secs();
let token_payload = Self {
user_id,
merchant_id,
role_id,
exp,
org_id,
profile_id,
tenant_id,
};
jwt::generate_jwt(&token_payload, settings).await
}
}
#[derive(Clone)]
pub struct UserFromToken {
pub user_id: String,
pub merchant_id: id_type::MerchantId,
pub role_id: String,
pub org_id: id_type::OrganizationId,
pub profile_id: id_type::ProfileId,
pub tenant_id: Option<id_type::TenantId>,
}
pub struct UserIdFromAuth {
pub user_id: String,
pub tenant_id: Option<id_type::TenantId>,
}
#[cfg(feature = "olap")]
#[derive(serde::Serialize, serde::Deserialize)]
pub struct SinglePurposeOrLoginToken {
pub user_id: String,
pub role_id: Option<String>,
pub purpose: Option<TokenPurpose>,
pub exp: u64,
pub tenant_id: Option<id_type::TenantId>,
}
pub trait AuthInfo {
fn get_merchant_id(&self) -> Option<&id_type::MerchantId>;
}
impl AuthInfo for () {
fn get_merchant_id(&self) -> Option<&id_type::MerchantId> {
None
}
}
#[cfg(feature = "v1")]
impl AuthInfo for AuthenticationData {
fn get_merchant_id(&self) -> Option<&id_type::MerchantId> {
Some(self.merchant_account.get_id())
}
}
#[cfg(feature = "v2")]
impl AuthInfo for AuthenticationData {
fn get_merchant_id(&self) -> Option<&id_type::MerchantId> {
Some(self.merchant_account.get_id())
}
}
impl AuthInfo for AuthenticationDataWithMultipleProfiles {
fn get_merchant_id(&self) -> Option<&id_type::MerchantId> {
Some(self.merchant_account.get_id())
}
}
#[async_trait]
pub trait AuthenticateAndFetch<T, A>
where
A: SessionStateInfo,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(T, AuthenticationType)>;
}
#[derive(Debug, Default)]
pub struct ApiKeyAuth {
pub is_connected_allowed: bool,
pub is_platform_allowed: bool,
}
pub struct NoAuth;
#[cfg(feature = "partial-auth")]
impl GetAuthType for ApiKeyAuth {
fn get_auth_type(&self) -> detached::PayloadType {
detached::PayloadType::ApiKey
}
}
//
// # Header Auth
//
// Header Auth is a feature that allows you to authenticate requests using custom headers. This is
// done by checking whether the request contains the specified headers.
// - `x-merchant-id` header is used to authenticate the merchant.
//
// ## Checksum
// - `x-auth-checksum` header is used to authenticate the request. The checksum is calculated using the
// above mentioned headers is generated by hashing the headers mentioned above concatenated with `:` and then hashed with the detached authentication key.
//
// When the [`partial-auth`] feature is disabled the implementation for [`AuthenticateAndFetch`]
// changes where the authentication is done by the [`I`] implementation.
//
pub struct HeaderAuth<I>(pub I);
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for NoAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
_request_headers: &HeaderMap,
_state: &A,
) -> RouterResult<((), AuthenticationType)> {
Ok(((), AuthenticationType::NoAuth))
}
}
#[async_trait]
impl<A, T> AuthenticateAndFetch<Option<T>, A> for NoAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
_request_headers: &HeaderMap,
_state: &A,
) -> RouterResult<(Option<T>, AuthenticationType)> {
Ok((None, AuthenticationType::NoAuth))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let api_key = get_api_key(request_headers)
.change_context(errors::ApiErrorResponse::Unauthorized)?
.trim();
if api_key.is_empty() {
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("API key is empty");
}
let profile_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?;
let api_key = api_keys::PlaintextApiKey::from(api_key);
let hash_key = {
let config = state.conf();
config.api_keys.get_inner().get_hash_key()?
};
let hashed_api_key = api_key.keyed_hash(hash_key.peek());
let stored_api_key = state
.store()
.find_api_key_by_hash_optional(hashed_api_key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed
.attach_printable("Failed to retrieve API key")?
.ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None`
.attach_printable("Merchant not authenticated")?;
if stored_api_key
.expires_at
.map(|expires_at| expires_at < date_time::now())
.unwrap_or(false)
{
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("API key has expired");
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
// Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account
let (merchant, platform_merchant_account) = if state.conf().platform.enabled {
get_platform_merchant_account(state, request_headers, merchant).await?
} else {
(merchant, None)
};
if platform_merchant_account.is_some() && !self.is_platform_allowed {
return Err(report!(
errors::ApiErrorResponse::PlatformAccountAuthNotSupported
))
.attach_printable("Platform not authorized to access the resource");
}
let key_store = if platform_merchant_account.is_some() {
state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant.get_id(),
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?
} else {
key_store
};
let profile = state
.store()
.find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account,
key_store,
profile,
};
Ok((
auth.clone(),
AuthenticationType::ApiKey {
merchant_id: auth.merchant_account.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let api_key = get_api_key(request_headers)
.change_context(errors::ApiErrorResponse::Unauthorized)?
.trim();
if api_key.is_empty() {
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("API key is empty");
}
let api_key = api_keys::PlaintextApiKey::from(api_key);
let hash_key = {
let config = state.conf();
config.api_keys.get_inner().get_hash_key()?
};
let hashed_api_key = api_key.keyed_hash(hash_key.peek());
let stored_api_key = state
.store()
.find_api_key_by_hash_optional(hashed_api_key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed
.attach_printable("Failed to retrieve API key")?
.ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None`
.attach_printable("Merchant not authenticated")?;
if stored_api_key
.expires_at
.map(|expires_at| expires_at < date_time::now())
.unwrap_or(false)
{
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("API key has expired");
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let profile_id =
get_header_value_by_key(headers::X_PROFILE_ID.to_string(), request_headers)?
.map(id_type::ProfileId::from_str)
.transpose()
.change_context(errors::ValidationError::IncorrectValueProvided {
field_name: "X-Profile-Id",
})
.change_context(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let (merchant, platform_merchant_account) = if state.conf().platform.enabled {
get_platform_merchant_account(state, request_headers, merchant).await?
} else {
(merchant, None)
};
if platform_merchant_account.is_some() && !self.is_platform_allowed {
return Err(report!(
errors::ApiErrorResponse::PlatformAccountAuthNotSupported
))
.attach_printable("Platform not authorized to access the resource");
}
let key_store = if platform_merchant_account.is_some() {
state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant.get_id(),
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?
} else {
key_store
};
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account,
key_store,
profile_id,
};
Ok((
auth.clone(),
AuthenticationType::ApiKey {
merchant_id: auth.merchant_account.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
}
}
#[derive(Debug)]
pub struct ApiKeyAuthWithMerchantIdFromRoute(pub id_type::MerchantId);
#[cfg(feature = "partial-auth")]
impl GetAuthType for ApiKeyAuthWithMerchantIdFromRoute {
fn get_auth_type(&self) -> detached::PayloadType {
detached::PayloadType::ApiKey
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuthWithMerchantIdFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let api_auth = ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_data, auth_type) = api_auth
.authenticate_and_fetch(request_headers, state)
.await?;
let merchant_id_from_route = self.0.clone();
let merchant_id_from_api_key = auth_data.merchant_account.get_id();
if merchant_id_from_route != *merchant_id_from_api_key {
return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable(
"Merchant ID from route and Merchant ID from api-key in header do not match",
);
}
Ok((auth_data, auth_type))
}
}
#[derive(Debug, Default)]
pub struct PlatformOrgAdminAuth {
pub is_admin_auth_allowed: bool,
pub organization_id: Option<id_type::OrganizationId>,
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<Option<AuthenticationDataWithOrg>, A> for PlatformOrgAdminAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(Option<AuthenticationDataWithOrg>, AuthenticationType)> {
// Step 1: Admin API Key and API Key Fallback (if allowed)
if self.is_admin_auth_allowed {
let admin_auth = AdminApiAuthWithApiKeyFallback {
organization_id: self.organization_id.clone(),
};
match admin_auth
.authenticate_and_fetch(request_headers, state)
.await
{
Ok((auth, auth_type)) => {
return Ok((auth, auth_type));
}
Err(e) => {
logger::warn!("Admin API Auth failed: {:?}", e);
}
}
}
// Step 2: Try Platform Auth
let api_key = get_api_key(request_headers)
.change_context(errors::ApiErrorResponse::Unauthorized)?
.trim();
if api_key.is_empty() {
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("API key is empty");
}
let api_key_plaintext = api_keys::PlaintextApiKey::from(api_key);
let hash_key = state.conf().api_keys.get_inner().get_hash_key()?;
let hashed_api_key = api_key_plaintext.keyed_hash(hash_key.peek());
let stored_api_key = state
.store()
.find_api_key_by_hash_optional(hashed_api_key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve API key")?
.ok_or_else(|| report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("Merchant not authenticated via API key")?;
if stored_api_key
.expires_at
.map(|expires_at| expires_at < date_time::now())
.unwrap_or(false)
{
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("API key has expired");
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant_account = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Merchant account not found")?;
if !(state.conf().platform.enabled && merchant_account.is_platform_account()) {
return Err(report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Platform authentication check failed"));
}
if let Some(ref organization_id) = self.organization_id {
if organization_id != merchant_account.get_org_id() {
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("Organization ID does not match");
}
}
Ok((
Some(AuthenticationDataWithOrg {
organization_id: merchant_account.get_org_id().clone(),
}),
AuthenticationType::ApiKey {
merchant_id: merchant_account.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for PlatformOrgAdminAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let api_key = get_api_key(request_headers)
.change_context(errors::ApiErrorResponse::Unauthorized)?
.trim();
if api_key.is_empty() {
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("API key is empty");
}
let api_key_plaintext = api_keys::PlaintextApiKey::from(api_key);
let hash_key = state.conf().api_keys.get_inner().get_hash_key()?;
let hashed_api_key = api_key_plaintext.keyed_hash(hash_key.peek());
let stored_api_key = state
.store()
.find_api_key_by_hash_optional(hashed_api_key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve API key")?
.ok_or_else(|| report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("Merchant not authenticated via API key")?;
if stored_api_key
.expires_at
.map(|expires_at| expires_at < date_time::now())
.unwrap_or(false)
{
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("API key has expired");
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant_account = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Merchant account not found")?;
if !(state.conf().platform.enabled && merchant_account.is_platform_account()) {
return Err(report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Platform authentication check failed"));
}
if let Some(ref organization_id) = self.organization_id {
if organization_id != merchant_account.get_org_id() {
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("Organization ID does not match");
}
}
let auth = AuthenticationData {
merchant_account: merchant_account.clone(),
platform_merchant_account: Some(merchant_account.clone()),
key_store,
profile_id: None,
};
Ok((
auth.clone(),
AuthenticationType::ApiKey {
merchant_id: auth.merchant_account.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
}
}
#[derive(Debug)]
pub struct PlatformOrgAdminAuthWithMerchantIdFromRoute {
pub merchant_id_from_route: id_type::MerchantId,
pub is_admin_auth_allowed: bool,
}
#[cfg(feature = "v1")]
impl PlatformOrgAdminAuthWithMerchantIdFromRoute {
async fn fetch_key_store_and_account<A: SessionStateInfo + Sync>(
merchant_id: &id_type::MerchantId,
state: &A,
) -> RouterResult<(domain::MerchantKeyStore, domain::MerchantAccount)> {
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
Ok((key_store, merchant))
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for PlatformOrgAdminAuthWithMerchantIdFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let route_merchant_id = self.merchant_id_from_route.clone();
// Step 1: Admin API Key and API Key Fallback (if allowed)
if self.is_admin_auth_allowed {
let admin_auth =
AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(route_merchant_id.clone());
match admin_auth
.authenticate_and_fetch(request_headers, state)
.await
{
Ok((auth_data, auth_type)) => return Ok((auth_data, auth_type)),
Err(e) => {
logger::warn!("Admin API Auth failed: {:?}", e);
}
}
}
// Step 2: Platform authentication
let api_key = get_api_key(request_headers)
.change_context(errors::ApiErrorResponse::Unauthorized)?
.trim();
if api_key.is_empty() {
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("API key is empty");
}
let api_key_plaintext = api_keys::PlaintextApiKey::from(api_key);
let hash_key = {
let config = state.conf();
config.api_keys.get_inner().get_hash_key()?
};
let hashed_api_key = api_key_plaintext.keyed_hash(hash_key.peek());
let stored_api_key = state
.store()
.find_api_key_by_hash_optional(hashed_api_key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve API key")?
.ok_or_else(|| report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("Merchant not authenticated via API key")?;
if stored_api_key
.expires_at
.map(|expires_at| expires_at < date_time::now())
.unwrap_or(false)
{
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("API key has expired");
}
let (_, platform_merchant) =
Self::fetch_key_store_and_account(&stored_api_key.merchant_id, state).await?;
if !(state.conf().platform.enabled && platform_merchant.is_platform_account()) {
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("Platform authentication check failed");
}
let (route_key_store, route_merchant) =
Self::fetch_key_store_and_account(&route_merchant_id, state).await?;
if platform_merchant.get_org_id() != route_merchant.get_org_id() {
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("Route merchant not under same org as platform merchant");
}
let auth = AuthenticationData {
merchant_account: route_merchant,
platform_merchant_account: Some(platform_merchant.clone()),
key_store: route_key_store,
profile_id: None,
};
Ok((
auth.clone(),
AuthenticationType::ApiKey {
merchant_id: platform_merchant.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
}
}
#[cfg(not(feature = "partial-auth"))]
#[async_trait]
impl<A, I> AuthenticateAndFetch<AuthenticationData, A> for HeaderAuth<I>
where
A: SessionStateInfo + Send + Sync,
I: AuthenticateAndFetch<AuthenticationData, A> + Sync + Send,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
self.0.authenticate_and_fetch(request_headers, state).await
}
}
#[cfg(all(feature = "partial-auth", feature = "v1"))]
#[async_trait]
impl<A, I> AuthenticateAndFetch<AuthenticationData, A> for HeaderAuth<I>
where
A: SessionStateInfo + Sync,
I: AuthenticateAndFetch<AuthenticationData, A> + GetAuthType + Sync + Send,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let enable_partial_auth = state.conf().api_keys.get_inner().enable_partial_auth;
// This is a early return if partial auth is disabled
// Preventing the need to go through the header extraction process
if !enable_partial_auth {
return self.0.authenticate_and_fetch(request_headers, state).await;
}
let report_failure = || {
metrics::PARTIAL_AUTH_FAILURE.add(1, &[]);
};
let profile_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header_if_present::<id_type::ProfileId>(headers::X_PROFILE_ID)
.change_context(errors::ValidationError::IncorrectValueProvided {
field_name: "X-Profile-Id",
})
.change_context(errors::ApiErrorResponse::Unauthorized)?;
let payload = ExtractedPayload::from_headers(request_headers)
.and_then(|value| {
let (algo, secret) = state.get_detached_auth()?;
Ok(value
.verify_checksum(request_headers, algo, secret)
.then_some(value))
})
.map(|inner_payload| {
inner_payload.and_then(|inner| {
(inner.payload_type == self.0.get_auth_type()).then_some(inner)
})
});
match payload {
Ok(Some(data)) => match data {
ExtractedPayload {
payload_type: detached::PayloadType::ApiKey,
merchant_id: Some(merchant_id),
key_id: Some(key_id),
} => {
let auth = construct_authentication_data(
state,
&merchant_id,
request_headers,
profile_id,
)
.await?;
Ok((
auth.clone(),
AuthenticationType::ApiKey {
merchant_id: auth.merchant_account.get_id().clone(),
key_id,
},
))
}
ExtractedPayload {
payload_type: detached::PayloadType::PublishableKey,
merchant_id: Some(merchant_id),
key_id: None,
} => {
let auth = construct_authentication_data(
state,
&merchant_id,
request_headers,
profile_id,
)
.await?;
Ok((
auth.clone(),
AuthenticationType::PublishableKey {
merchant_id: auth.merchant_account.get_id().clone(),
},
))
}
_ => {
report_failure();
self.0.authenticate_and_fetch(request_headers, state).await
}
},
Ok(None) => {
report_failure();
self.0.authenticate_and_fetch(request_headers, state).await
}
Err(error) => {
logger::error!(%error, "Failed to extract payload from headers");
report_failure();
self.0.authenticate_and_fetch(request_headers, state).await
}
}
}
}
#[cfg(all(feature = "partial-auth", feature = "v2"))]
#[async_trait]
impl<A, I> AuthenticateAndFetch<AuthenticationData, A> for HeaderAuth<I>
where
A: SessionStateInfo + Sync,
I: AuthenticateAndFetch<AuthenticationData, A>
+ AuthenticateAndFetch<AuthenticationData, A>
+ GetAuthType
+ Sync
+ Send,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let (auth_data, auth_type): (AuthenticationData, AuthenticationType) = self
.0
.authenticate_and_fetch(request_headers, state)
.await?;
let profile_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?;
let key_manager_state = &(&state.session_state()).into();
let profile = state
.store()
.find_business_profile_by_profile_id(
key_manager_state,
&auth_data.key_store,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth_data_v2 = AuthenticationData {
merchant_account: auth_data.merchant_account,
platform_merchant_account: auth_data.platform_merchant_account,
key_store: auth_data.key_store,
profile,
};
Ok((auth_data_v2, auth_type))
}
}
#[cfg(all(feature = "partial-auth", feature = "v1"))]
async fn construct_authentication_data<A>(
state: &A,
merchant_id: &id_type::MerchantId,
request_headers: &HeaderMap,
profile_id: Option<id_type::ProfileId>,
) -> RouterResult<AuthenticationData>
where
A: SessionStateInfo + Sync,
{
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
&(&state.session_state()).into(),
merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
&(&state.session_state()).into(),
merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
// Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account
let (merchant, platform_merchant_account) = if state.conf().platform.enabled {
get_platform_merchant_account(state, request_headers, merchant).await?
} else {
(merchant, None)
};
let key_store = if platform_merchant_account.is_some() {
state
.store()
.get_merchant_key_store_by_merchant_id(
&(&state.session_state()).into(),
merchant.get_id(),
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?
} else {
key_store
};
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account,
key_store,
profile_id,
};
Ok(auth)
}
#[cfg(feature = "olap")]
#[derive(Debug)]
pub(crate) struct SinglePurposeJWTAuth(pub TokenPurpose);
#[cfg(feature = "olap")]
#[async_trait]
impl<A> AuthenticateAndFetch<UserFromSinglePurposeToken, A> for SinglePurposeJWTAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(UserFromSinglePurposeToken, AuthenticationType)> {
let payload = parse_jwt_payload::<A, SinglePurposeToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
if self.0 != payload.purpose {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
Ok((
UserFromSinglePurposeToken {
user_id: payload.user_id.clone(),
origin: payload.origin.clone(),
path: payload.path,
tenant_id: payload.tenant_id,
},
AuthenticationType::SinglePurposeJwt {
user_id: payload.user_id,
purpose: payload.purpose,
},
))
}
}
#[cfg(feature = "olap")]
#[async_trait]
impl<A> AuthenticateAndFetch<Option<UserFromSinglePurposeToken>, A> for SinglePurposeJWTAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(Option<UserFromSinglePurposeToken>, AuthenticationType)> {
let payload = parse_jwt_payload::<A, SinglePurposeToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
if self.0 != payload.purpose {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
Ok((
Some(UserFromSinglePurposeToken {
user_id: payload.user_id.clone(),
origin: payload.origin.clone(),
path: payload.path,
tenant_id: payload.tenant_id,
}),
AuthenticationType::SinglePurposeJwt {
user_id: payload.user_id,
purpose: payload.purpose,
},
))
}
}
#[cfg(feature = "olap")]
#[derive(Debug)]
pub struct SinglePurposeOrLoginTokenAuth(pub TokenPurpose);
#[cfg(feature = "olap")]
#[async_trait]
impl<A> AuthenticateAndFetch<UserIdFromAuth, A> for SinglePurposeOrLoginTokenAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(UserIdFromAuth, AuthenticationType)> {
let payload =
parse_jwt_payload::<A, SinglePurposeOrLoginToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let is_purpose_equal = payload
.purpose
.as_ref()
.is_some_and(|purpose| purpose == &self.0);
let purpose_exists = payload.purpose.is_some();
let role_id_exists = payload.role_id.is_some();
if is_purpose_equal && !role_id_exists || role_id_exists && !purpose_exists {
Ok((
UserIdFromAuth {
user_id: payload.user_id.clone(),
tenant_id: payload.tenant_id,
},
AuthenticationType::SinglePurposeOrLoginJwt {
user_id: payload.user_id,
purpose: payload.purpose,
role_id: payload.role_id,
},
))
} else {
Err(errors::ApiErrorResponse::InvalidJwtToken.into())
}
}
}
#[cfg(feature = "olap")]
#[derive(Debug)]
pub struct AnyPurposeOrLoginTokenAuth;
#[cfg(feature = "olap")]
#[async_trait]
impl<A> AuthenticateAndFetch<UserIdFromAuth, A> for AnyPurposeOrLoginTokenAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(UserIdFromAuth, AuthenticationType)> {
let payload =
parse_jwt_payload::<A, SinglePurposeOrLoginToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
let purpose_exists = payload.purpose.is_some();
let role_id_exists = payload.role_id.is_some();
if purpose_exists ^ role_id_exists {
Ok((
UserIdFromAuth {
user_id: payload.user_id.clone(),
tenant_id: payload.tenant_id,
},
AuthenticationType::SinglePurposeOrLoginJwt {
user_id: payload.user_id,
purpose: payload.purpose,
role_id: payload.role_id,
},
))
} else {
Err(errors::ApiErrorResponse::InvalidJwtToken.into())
}
}
}
#[derive(Debug, Default)]
pub struct AdminApiAuth;
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for AdminApiAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let request_admin_api_key =
get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;
let conf = state.conf();
let admin_api_key = &conf.secrets.get_inner().admin_api_key;
if request_admin_api_key != admin_api_key.peek() {
Err(report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Admin Authentication Failure"))?;
}
Ok(((), AuthenticationType::AdminApiKey))
}
}
#[derive(Debug, Default)]
pub struct V2AdminApiAuth;
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for V2AdminApiAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let header_map_struct = HeaderMapStruct::new(request_headers);
let auth_string = header_map_struct.get_auth_string_from_header()?;
let request_admin_api_key = auth_string
.split(',')
.find_map(|part| part.trim().strip_prefix("admin-api-key="))
.ok_or_else(|| {
report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Unable to parse admin_api_key")
})?;
if request_admin_api_key.is_empty() {
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Admin Api key is empty");
}
let conf = state.conf();
let admin_api_key = &conf.secrets.get_inner().admin_api_key;
if request_admin_api_key != admin_api_key.peek() {
Err(report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Admin Authentication Failure"))?;
}
Ok(((), AuthenticationType::AdminApiKey))
}
}
#[derive(Debug)]
pub struct AdminApiAuthWithMerchantIdFromRoute(pub id_type::MerchantId);
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for AdminApiAuthWithMerchantIdFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
AdminApiAuth
.authenticate_and_fetch(request_headers, state)
.await?;
let merchant_id = self.0.clone();
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account: None,
key_store,
profile_id: None,
};
Ok((
auth,
AuthenticationType::AdminApiAuthWithMerchantId { merchant_id },
))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for AdminApiAuthWithMerchantIdFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
if state.conf().platform.enabled {
throw_error_if_platform_merchant_authentication_required(request_headers)?;
}
V2AdminApiAuth
.authenticate_and_fetch(request_headers, state)
.await?;
let merchant_id = self.0.clone();
let profile_id =
get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?
.get_required_value(headers::X_PROFILE_ID)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
profile,
platform_merchant_account: None,
};
Ok((
auth,
AuthenticationType::AdminApiAuthWithMerchantId { merchant_id },
))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationDataWithoutProfile, A>
for AdminApiAuthWithMerchantIdFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationDataWithoutProfile, AuthenticationType)> {
if state.conf().platform.enabled {
throw_error_if_platform_merchant_authentication_required(request_headers)?;
}
V2AdminApiAuth
.authenticate_and_fetch(request_headers, state)
.await?;
let merchant_id = self.0.clone();
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationDataWithoutProfile {
merchant_account: merchant,
key_store,
};
Ok((
auth,
AuthenticationType::AdminApiAuthWithMerchantId { merchant_id },
))
}
}
#[derive(Debug, Default)]
pub struct AdminApiAuthWithApiKeyFallback {
pub organization_id: Option<id_type::OrganizationId>,
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<Option<AuthenticationDataWithOrg>, A>
for AdminApiAuthWithApiKeyFallback
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(Option<AuthenticationDataWithOrg>, AuthenticationType)> {
let request_api_key =
get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;
let conf = state.conf();
let admin_api_key = &conf.secrets.get_inner().admin_api_key;
if request_api_key == admin_api_key.peek() {
return Ok((None, AuthenticationType::AdminApiKey));
}
let Some(fallback_merchant_ids) = conf.fallback_merchant_ids_api_key_auth.as_ref() else {
return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable(
"Api Key Authentication Failure: fallback merchant set not configured",
);
};
let api_key = api_keys::PlaintextApiKey::from(request_api_key);
let hash_key = conf.api_keys.get_inner().get_hash_key()?;
let hashed_api_key = api_key.keyed_hash(hash_key.peek());
let stored_api_key = state
.store()
.find_api_key_by_hash_optional(hashed_api_key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve API key")?
.ok_or(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("Merchant not authenticated")?;
if stored_api_key
.expires_at
.map(|expires_at| expires_at < date_time::now())
.unwrap_or(false)
{
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("API key has expired");
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
if let Some(ref organization_id) = self.organization_id {
if organization_id != merchant.get_org_id() {
return Err(
report!(errors::ApiErrorResponse::Unauthorized).attach_printable(
"Organization ID from request and merchant account does not match",
),
);
}
}
if fallback_merchant_ids
.merchant_ids
.contains(&stored_api_key.merchant_id)
{
return Ok((
Some(AuthenticationDataWithOrg {
organization_id: merchant.organization_id,
}),
AuthenticationType::ApiKey {
merchant_id: stored_api_key.merchant_id,
key_id: stored_api_key.key_id,
},
));
}
Err(report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Admin Authentication Failure"))
}
}
#[derive(Debug, Default)]
pub struct AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(pub id_type::MerchantId);
#[cfg(feature = "v1")]
impl AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute {
async fn fetch_merchant_key_store_and_account<A: SessionStateInfo + Sync>(
merchant_id: &id_type::MerchantId,
state: &A,
) -> RouterResult<(domain::MerchantKeyStore, domain::MerchantAccount)> {
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
Ok((key_store, merchant))
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A>
for AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let merchant_id_from_route: id_type::MerchantId = self.0.clone();
let request_api_key =
get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;
let conf = state.conf();
let admin_api_key: &masking::Secret<String> = &conf.secrets.get_inner().admin_api_key;
if request_api_key == admin_api_key.peek() {
let (key_store, merchant) =
Self::fetch_merchant_key_store_and_account(&merchant_id_from_route, state).await?;
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account: None,
key_store,
profile_id: None,
};
return Ok((
auth,
AuthenticationType::AdminApiAuthWithMerchantId {
merchant_id: merchant_id_from_route.clone(),
},
));
}
let Some(fallback_merchant_ids) = conf.fallback_merchant_ids_api_key_auth.as_ref() else {
return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable(
"Api Key Authentication Failure: fallback merchant set not configured",
);
};
let api_key = api_keys::PlaintextApiKey::from(request_api_key);
let hash_key = conf.api_keys.get_inner().get_hash_key()?;
let hashed_api_key = api_key.keyed_hash(hash_key.peek());
let stored_api_key = state
.store()
.find_api_key_by_hash_optional(hashed_api_key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve API key")?
.ok_or(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("Merchant not authenticated")?;
if stored_api_key
.expires_at
.map(|expires_at| expires_at < date_time::now())
.unwrap_or(false)
{
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("API key has expired");
}
if fallback_merchant_ids
.merchant_ids
.contains(&stored_api_key.merchant_id)
{
let (_, api_key_merchant) =
Self::fetch_merchant_key_store_and_account(&stored_api_key.merchant_id, state)
.await?;
let (route_key_store, route_merchant) =
Self::fetch_merchant_key_store_and_account(&merchant_id_from_route, state).await?;
if api_key_merchant.get_org_id() == route_merchant.get_org_id() {
let auth = AuthenticationData {
merchant_account: route_merchant,
platform_merchant_account: None,
key_store: route_key_store,
profile_id: None,
};
return Ok((
auth.clone(),
AuthenticationType::MerchantId {
merchant_id: auth.merchant_account.get_id().clone(),
},
));
}
}
Err(report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Admin Authentication Failure"))
}
}
/// A helper struct to extract headers from the request
pub(crate) struct HeaderMapStruct<'a> {
headers: &'a HeaderMap,
}
impl<'a> HeaderMapStruct<'a> {
pub fn new(headers: &'a HeaderMap) -> Self {
HeaderMapStruct { headers }
}
fn get_mandatory_header_value_by_key(
&self,
key: &str,
) -> Result<&str, error_stack::Report<errors::ApiErrorResponse>> {
self.headers
.get(key)
.ok_or(errors::ApiErrorResponse::InvalidRequestData {
message: format!("Missing header key: `{key}`"),
})
.attach_printable(format!("Failed to find header key: {key}"))?
.to_str()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "`{key}` in headers",
})
.attach_printable(format!(
"Failed to convert header value to string for header key: {key}",
))
}
/// Get the id type from the header
/// This can be used to extract lineage ids from the headers
pub fn get_id_type_from_header<
T: TryFrom<
std::borrow::Cow<'static, str>,
Error = error_stack::Report<errors::ValidationError>,
>,
>(
&self,
key: &str,
) -> RouterResult<T> {
self.get_mandatory_header_value_by_key(key)
.map(|val| val.to_owned())
.and_then(|header_value| {
T::try_from(std::borrow::Cow::Owned(header_value)).change_context(
errors::ApiErrorResponse::InvalidRequestData {
message: format!("`{key}` header is invalid"),
},
)
})
}
#[cfg(feature = "v2")]
pub fn get_organization_id_from_header(&self) -> RouterResult<id_type::OrganizationId> {
self.get_mandatory_header_value_by_key(headers::X_ORGANIZATION_ID)
.map(|val| val.to_owned())
.and_then(|organization_id| {
id_type::OrganizationId::try_from_string(organization_id).change_context(
errors::ApiErrorResponse::InvalidRequestData {
message: format!("`{}` header is invalid", headers::X_ORGANIZATION_ID),
},
)
})
}
pub fn get_header_value_by_key(&self, key: &str) -> Option<&str> {
self.headers.get(key).and_then(|value| value.to_str().ok())
}
pub fn get_auth_string_from_header(&self) -> RouterResult<&str> {
self.headers
.get(headers::AUTHORIZATION)
.get_required_value(headers::AUTHORIZATION)?
.to_str()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: headers::AUTHORIZATION,
})
.attach_printable("Failed to convert authorization header to string")
}
pub fn get_id_type_from_header_if_present<T>(&self, key: &str) -> RouterResult<Option<T>>
where
T: TryFrom<
std::borrow::Cow<'static, str>,
Error = error_stack::Report<errors::ValidationError>,
>,
{
self.headers
.get(key)
.map(|value| value.to_str())
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "`{key}` in headers",
})
.attach_printable(format!(
"Failed to convert header value to string for header key: {key}",
))?
.map(|value| {
T::try_from(std::borrow::Cow::Owned(value.to_owned())).change_context(
errors::ApiErrorResponse::InvalidRequestData {
message: format!("`{key}` header is invalid"),
},
)
})
.transpose()
}
}
/// Get the merchant-id from `x-merchant-id` header
#[derive(Debug)]
pub struct AdminApiAuthWithMerchantIdFromHeader;
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for AdminApiAuthWithMerchantIdFromHeader
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
AdminApiAuth
.authenticate_and_fetch(request_headers, state)
.await?;
let merchant_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account: None,
key_store,
profile_id: None,
};
Ok((
auth,
AuthenticationType::AdminApiAuthWithMerchantId { merchant_id },
))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for AdminApiAuthWithMerchantIdFromHeader
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
if state.conf().platform.enabled {
throw_error_if_platform_merchant_authentication_required(request_headers)?;
}
V2AdminApiAuth
.authenticate_and_fetch(request_headers, state)
.await?;
let merchant_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
let profile_id =
get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?
.get_required_value(headers::X_PROFILE_ID)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
profile,
platform_merchant_account: None,
};
Ok((
auth,
AuthenticationType::AdminApiAuthWithMerchantId { merchant_id },
))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationDataWithoutProfile, A>
for AdminApiAuthWithMerchantIdFromHeader
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationDataWithoutProfile, AuthenticationType)> {
if state.conf().platform.enabled {
throw_error_if_platform_merchant_authentication_required(request_headers)?;
}
V2AdminApiAuth
.authenticate_and_fetch(request_headers, state)
.await?;
let merchant_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationDataWithoutProfile {
merchant_account: merchant,
key_store,
};
Ok((
auth,
AuthenticationType::AdminApiAuthWithMerchantId { merchant_id },
))
}
}
#[derive(Debug)]
pub struct EphemeralKeyAuth;
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for EphemeralKeyAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let api_key =
get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;
let ephemeral_key = state
.store()
.get_ephemeral_key(api_key)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)?;
MerchantIdAuth(ephemeral_key.merchant_id)
.authenticate_and_fetch(request_headers, state)
.await
}
}
#[derive(Debug)]
#[cfg(feature = "v1")]
pub struct MerchantIdAuth(pub id_type::MerchantId);
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for MerchantIdAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
if state.conf().platform.enabled {
throw_error_if_platform_merchant_authentication_required(request_headers)?;
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&self.0,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &self.0, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account: None,
key_store,
profile_id: None,
};
Ok((
auth.clone(),
AuthenticationType::MerchantId {
merchant_id: auth.merchant_account.get_id().clone(),
},
))
}
}
#[derive(Debug)]
#[cfg(feature = "v2")]
pub struct MerchantIdAuth;
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for MerchantIdAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
if state.conf().platform.enabled {
throw_error_if_platform_merchant_authentication_required(request_headers)?;
}
let key_manager_state = &(&state.session_state()).into();
let merchant_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
let profile_id =
get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?
.get_required_value(headers::X_PROFILE_ID)?;
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
profile,
platform_merchant_account: None,
};
Ok((
auth.clone(),
AuthenticationType::MerchantId {
merchant_id: auth.merchant_account.get_id().clone(),
},
))
}
}
/// InternalMerchantIdProfileIdAuth authentication which first tries to authenticate using `X-Internal-API-Key`,
/// `X-Merchant-Id` and `X-Profile-Id` headers. If any of these headers are missing,
/// it falls back to the provided authentication mechanism.
#[cfg(feature = "v1")]
pub struct InternalMerchantIdProfileIdAuth<F>(pub F);
#[cfg(feature = "v1")]
#[async_trait]
impl<A, F> AuthenticateAndFetch<AuthenticationData, A> for InternalMerchantIdProfileIdAuth<F>
where
A: SessionStateInfo + Sync + Send,
F: AuthenticateAndFetch<AuthenticationData, A> + Sync + Send,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
if !state.conf().internal_merchant_id_profile_id_auth.enabled {
return self.0.authenticate_and_fetch(request_headers, state).await;
}
let merchant_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)
.ok();
let internal_api_key = HeaderMapStruct::new(request_headers)
.get_header_value_by_key(headers::X_INTERNAL_API_KEY)
.map(|s| s.to_string());
let profile_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)
.ok();
if let (Some(internal_api_key), Some(merchant_id), Some(profile_id)) =
(internal_api_key, merchant_id, profile_id)
{
let config = state.conf();
if internal_api_key
!= *config
.internal_merchant_id_profile_id_auth
.internal_api_key
.peek()
{
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Internal API key authentication failed");
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let _profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
profile_id: Some(profile_id.clone()),
platform_merchant_account: None,
};
Ok((
auth.clone(),
AuthenticationType::InternalMerchantIdProfileId {
merchant_id,
profile_id: Some(profile_id),
},
))
} else {
Ok(self
.0
.authenticate_and_fetch(request_headers, state)
.await?)
}
}
}
#[derive(Debug)]
#[cfg(feature = "v2")]
pub struct MerchantIdAndProfileIdAuth {
pub merchant_id: id_type::MerchantId,
pub profile_id: id_type::ProfileId,
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for MerchantIdAndProfileIdAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
if state.conf().platform.enabled {
throw_error_if_platform_merchant_authentication_required(request_headers)?;
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&self.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&self.merchant_id,
&self.profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &self.merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
profile,
platform_merchant_account: None,
};
Ok((
auth.clone(),
AuthenticationType::MerchantId {
merchant_id: auth.merchant_account.get_id().clone(),
},
))
}
}
#[derive(Debug)]
#[cfg(feature = "v2")]
pub struct PublishableKeyAndProfileIdAuth {
pub publishable_key: String,
pub profile_id: id_type::ProfileId,
}
#[async_trait]
#[cfg(feature = "v2")]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for PublishableKeyAndProfileIdAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
_request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let key_manager_state = &(&state.session_state()).into();
let (merchant_account, key_store) = state
.store()
.find_merchant_account_by_publishable_key(
key_manager_state,
self.publishable_key.as_str(),
)
.await
.map_err(|e| {
if e.current_context().is_db_not_found() {
e.change_context(errors::ApiErrorResponse::Unauthorized)
} else {
e.change_context(errors::ApiErrorResponse::InternalServerError)
}
})?;
let profile = state
.store()
.find_business_profile_by_profile_id(key_manager_state, &key_store, &self.profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: self.profile_id.get_string_repr().to_owned(),
})?;
let merchant_id = merchant_account.get_id().clone();
Ok((
AuthenticationData {
merchant_account,
key_store,
profile,
platform_merchant_account: None,
},
AuthenticationType::PublishableKey { merchant_id },
))
}
}
/// Take api-key from `Authorization` header
#[cfg(feature = "v2")]
#[derive(Debug)]
pub struct V2ApiKeyAuth {
pub is_connected_allowed: bool,
pub is_platform_allowed: bool,
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for V2ApiKeyAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let header_map_struct = HeaderMapStruct::new(request_headers);
let auth_string = header_map_struct.get_auth_string_from_header()?;
let api_key = auth_string
.split(',')
.find_map(|part| part.trim().strip_prefix("api-key="))
.ok_or_else(|| {
report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Unable to parse api_key")
})?;
if api_key.is_empty() {
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("API key is empty");
}
let profile_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?;
let api_key = api_keys::PlaintextApiKey::from(api_key);
let hash_key = {
let config = state.conf();
config.api_keys.get_inner().get_hash_key()?
};
let hashed_api_key = api_key.keyed_hash(hash_key.peek());
let stored_api_key = state
.store()
.find_api_key_by_hash_optional(hashed_api_key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed
.attach_printable("Failed to retrieve API key")?
.ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None`
.attach_printable("Merchant not authenticated")?;
if stored_api_key
.expires_at
.map(|expires_at| expires_at < date_time::now())
.unwrap_or(false)
{
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("API key has expired");
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
// Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account
let (merchant, platform_merchant_account) = if state.conf().platform.enabled {
get_platform_merchant_account(state, request_headers, merchant).await?
} else {
(merchant, None)
};
if platform_merchant_account.is_some() && !self.is_platform_allowed {
return Err(report!(
errors::ApiErrorResponse::PlatformAccountAuthNotSupported
))
.attach_printable("Platform not authorized to access the resource");
}
let key_store = if platform_merchant_account.is_some() {
state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant.get_id(),
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?
} else {
key_store
};
let profile = state
.store()
.find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account,
key_store,
profile,
};
Ok((
auth.clone(),
AuthenticationType::ApiKey {
merchant_id: auth.merchant_account.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
}
}
#[cfg(feature = "v2")]
#[derive(Debug)]
pub struct V2ClientAuth(pub common_utils::types::authentication::ResourceId);
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for V2ClientAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let header_map_struct = HeaderMapStruct::new(request_headers);
let auth_string = header_map_struct.get_auth_string_from_header()?;
let publishable_key = auth_string
.split(',')
.find_map(|part| part.trim().strip_prefix("publishable-key="))
.ok_or_else(|| {
report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Unable to parse publishable_key")
})?;
let client_secret = auth_string
.split(',')
.find_map(|part| part.trim().strip_prefix("client-secret="))
.ok_or_else(|| {
report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Unable to parse client_secret")
})?;
let key_manager_state: &common_utils::types::keymanager::KeyManagerState =
&(&state.session_state()).into();
let db_client_secret: diesel_models::ClientSecretType = state
.store()
.get_client_secret(client_secret)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Invalid ephemeral_key")?;
let profile_id =
get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?
.get_required_value(headers::X_PROFILE_ID)?;
match (&self.0, &db_client_secret.resource_id) {
(
common_utils::types::authentication::ResourceId::Payment(self_id),
common_utils::types::authentication::ResourceId::Payment(db_id),
) => {
fp_utils::when(self_id != db_id, || {
Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized)
});
}
(
common_utils::types::authentication::ResourceId::Customer(self_id),
common_utils::types::authentication::ResourceId::Customer(db_id),
) => {
fp_utils::when(self_id != db_id, || {
Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized)
});
}
(
common_utils::types::authentication::ResourceId::PaymentMethodSession(self_id),
common_utils::types::authentication::ResourceId::PaymentMethodSession(db_id),
) => {
fp_utils::when(self_id != db_id, || {
Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized)
});
}
_ => {
return Err(errors::ApiErrorResponse::Unauthorized.into());
}
}
let (merchant_account, key_store) = state
.store()
.find_merchant_account_by_publishable_key(key_manager_state, publishable_key)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant_id = merchant_account.get_id().clone();
if db_client_secret.merchant_id != merchant_id {
return Err(errors::ApiErrorResponse::Unauthorized.into());
}
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
Ok((
AuthenticationData {
merchant_account,
key_store,
profile,
platform_merchant_account: None,
},
AuthenticationType::PublishableKey { merchant_id },
))
}
}
#[cfg(feature = "v2")]
pub fn api_or_client_auth<'a, T, A>(
api_auth: &'a dyn AuthenticateAndFetch<T, A>,
client_auth: &'a dyn AuthenticateAndFetch<T, A>,
headers: &HeaderMap,
) -> &'a dyn AuthenticateAndFetch<T, A>
where
{
if let Ok(val) = HeaderMapStruct::new(headers).get_auth_string_from_header() {
if val.trim().starts_with("api-key=") {
api_auth
} else {
client_auth
}
} else {
api_auth
}
}
#[cfg(feature = "v2")]
pub fn api_or_client_or_jwt_auth<'a, T, A>(
api_auth: &'a dyn AuthenticateAndFetch<T, A>,
client_auth: &'a dyn AuthenticateAndFetch<T, A>,
jwt_auth: &'a dyn AuthenticateAndFetch<T, A>,
headers: &HeaderMap,
) -> &'a dyn AuthenticateAndFetch<T, A>
where
{
if let Ok(val) = HeaderMapStruct::new(headers).get_auth_string_from_header() {
if val.trim().starts_with("api-key=") {
api_auth
} else if is_jwt_auth(headers) {
jwt_auth
} else {
client_auth
}
} else {
api_auth
}
}
#[derive(Debug)]
pub struct PublishableKeyAuth;
#[cfg(feature = "partial-auth")]
impl GetAuthType for PublishableKeyAuth {
fn get_auth_type(&self) -> detached::PayloadType {
detached::PayloadType::PublishableKey
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for PublishableKeyAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
if state.conf().platform.enabled {
throw_error_if_platform_merchant_authentication_required(request_headers)?;
}
let publishable_key =
get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;
let key_manager_state = &(&state.session_state()).into();
state
.store()
.find_merchant_account_by_publishable_key(key_manager_state, publishable_key)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)
.map(|(merchant_account, key_store)| {
let merchant_id = merchant_account.get_id().clone();
(
AuthenticationData {
merchant_account,
platform_merchant_account: None,
key_store,
profile_id: None,
},
AuthenticationType::PublishableKey { merchant_id },
)
})
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for PublishableKeyAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let publishable_key =
get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;
let key_manager_state = &(&state.session_state()).into();
let profile_id =
get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?
.get_required_value(headers::X_PROFILE_ID)?;
let (merchant_account, key_store) = state
.store()
.find_merchant_account_by_publishable_key(key_manager_state, publishable_key)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant_id = merchant_account.get_id().clone();
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
Ok((
AuthenticationData {
merchant_account,
key_store,
profile,
platform_merchant_account: None,
},
AuthenticationType::PublishableKey { merchant_id },
))
}
}
#[derive(Debug)]
pub(crate) struct JWTAuth {
pub permission: Permission,
}
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for JWTAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.permission, &role_info)?;
Ok((
(),
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "olap")]
#[async_trait]
impl<A> AuthenticateAndFetch<UserFromToken, A> for JWTAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(UserFromToken, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.permission, &role_info)?;
Ok((
UserFromToken {
user_id: payload.user_id.clone(),
merchant_id: payload.merchant_id.clone(),
org_id: payload.org_id,
role_id: payload.role_id,
profile_id: payload.profile_id,
tenant_id: payload.tenant_id,
},
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "olap")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationDataWithMultipleProfiles, A> for JWTAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationDataWithMultipleProfiles, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.permission, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::InvalidJwtToken)?;
Ok((
AuthenticationDataWithMultipleProfiles {
key_store,
merchant_account: merchant,
profile_id_list: None,
},
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
pub struct JWTAuthOrganizationFromRoute {
pub organization_id: id_type::OrganizationId,
pub required_permission: Permission,
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<Option<AuthenticationDataWithOrg>, A> for JWTAuthOrganizationFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(Option<AuthenticationDataWithOrg>, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
// Check if token has access to Organization that has been requested in the route
if payload.org_id != self.organization_id {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
Ok((
Some(AuthenticationDataWithOrg {
organization_id: payload.org_id.clone(),
}),
AuthenticationType::OrganizationJwt {
org_id: payload.org_id,
user_id: payload.user_id,
},
))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for JWTAuthOrganizationFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
// Check if token has access to Organization that has been requested in the route
if payload.org_id != self.organization_id {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
Ok((
(),
AuthenticationType::OrganizationJwt {
org_id: payload.org_id,
user_id: payload.user_id,
},
))
}
}
pub struct JWTAuthMerchantFromRoute {
pub merchant_id: id_type::MerchantId,
pub required_permission: Permission,
}
pub struct JWTAuthMerchantFromHeader {
pub required_permission: Permission,
}
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for JWTAuthMerchantFromHeader
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let merchant_id_from_header = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
// Check if token has access to MerchantId that has been requested through headers
if payload.merchant_id != merchant_id_from_header {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
Ok((
(),
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthMerchantFromHeader
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let merchant_id_from_header = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
// Check if token has access to MerchantId that has been requested through headers
if payload.merchant_id != merchant_id_from_header {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account: None,
key_store,
profile_id: Some(payload.profile_id),
};
Ok((
auth,
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<Option<AuthenticationDataWithOrg>, A> for JWTAuthMerchantFromHeader
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(Option<AuthenticationDataWithOrg>, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let merchant_id_from_header = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
// Check if token has access to MerchantId that has been requested through headers
if payload.merchant_id != merchant_id_from_header {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
let auth = Some(AuthenticationDataWithOrg {
organization_id: payload.org_id,
});
Ok((
auth,
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthMerchantFromHeader
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
let profile_id =
get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?
.get_required_value(headers::X_PROFILE_ID)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let merchant_id_from_header = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
// Check if token has access to MerchantId that has been requested through headers
if payload.merchant_id != merchant_id_from_header {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&payload.merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
profile,
platform_merchant_account: None,
};
Ok((
auth,
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationDataWithoutProfile, A> for JWTAuthMerchantFromHeader
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationDataWithoutProfile, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let merchant_id_from_header = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
// Check if token has access to MerchantId that has been requested through headers
if payload.merchant_id != merchant_id_from_header {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let auth = AuthenticationDataWithoutProfile {
merchant_account: merchant,
key_store,
};
Ok((
auth,
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for JWTAuthMerchantFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
// Check if token has access to MerchantId that has been requested through query param
if payload.merchant_id != self.merchant_id {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
Ok((
(),
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthMerchantFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
if payload.merchant_id != self.merchant_id {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account: None,
key_store,
profile_id: Some(payload.profile_id),
};
Ok((
auth.clone(),
AuthenticationType::MerchantJwt {
merchant_id: auth.merchant_account.get_id().clone(),
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthMerchantFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
let profile_id =
get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?
.get_required_value(headers::X_PROFILE_ID)?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
if payload.merchant_id != self.merchant_id {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&payload.merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
profile,
platform_merchant_account: None,
};
Ok((
auth.clone(),
AuthenticationType::MerchantJwt {
merchant_id: auth.merchant_account.get_id().clone(),
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationDataWithoutProfile, A> for JWTAuthMerchantFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationDataWithoutProfile, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
if payload.merchant_id != self.merchant_id {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let auth = AuthenticationDataWithoutProfile {
merchant_account: merchant,
key_store,
};
Ok((
auth.clone(),
AuthenticationType::MerchantJwt {
merchant_id: auth.merchant_account.get_id().clone(),
user_id: Some(payload.user_id),
},
))
}
}
pub struct JWTAuthMerchantAndProfileFromRoute {
pub merchant_id: id_type::MerchantId,
pub profile_id: id_type::ProfileId,
pub required_permission: Permission,
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthMerchantAndProfileFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
if payload.merchant_id != self.merchant_id {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
if payload.profile_id != self.profile_id {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account: None,
key_store,
profile_id: Some(payload.profile_id),
};
Ok((
auth.clone(),
AuthenticationType::MerchantJwtWithProfileId {
merchant_id: auth.merchant_account.get_id().clone(),
profile_id: auth.profile_id.clone(),
user_id: payload.user_id,
},
))
}
}
pub struct JWTAuthProfileFromRoute {
pub profile_id: id_type::ProfileId,
pub required_permission: Permission,
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthProfileFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
if payload.profile_id != self.profile_id {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
} else {
// if both of them are same then proceed with the profile id present in the request
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account: None,
key_store,
profile_id: Some(self.profile_id.clone()),
};
Ok((
auth.clone(),
AuthenticationType::MerchantJwt {
merchant_id: auth.merchant_account.get_id().clone(),
user_id: Some(payload.user_id),
},
))
}
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthProfileFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
let profile_id =
get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?
.get_required_value(headers::X_PROFILE_ID)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&payload.merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
profile,
platform_merchant_account: None,
};
Ok((
auth.clone(),
AuthenticationType::MerchantJwt {
merchant_id: auth.merchant_account.get_id().clone(),
user_id: Some(payload.user_id),
},
))
}
}
pub async fn parse_jwt_payload<A, T>(headers: &HeaderMap, state: &A) -> RouterResult<T>
where
T: serde::de::DeserializeOwned,
A: SessionStateInfo + Sync,
{
let cookie_token_result =
get_cookie_from_header(headers).and_then(cookies::get_jwt_from_cookies);
let auth_header_token_result = get_jwt_from_authorization_header(headers);
let force_cookie = state.conf().user.force_cookies;
logger::info!(
user_agent = ?headers.get(headers::USER_AGENT),
header_names = ?headers.keys().collect::<Vec<_>>(),
is_token_equal =
auth_header_token_result.as_deref().ok() == cookie_token_result.as_deref().ok(),
cookie_error = ?cookie_token_result.as_ref().err(),
token_error = ?auth_header_token_result.as_ref().err(),
force_cookie,
);
let final_token = if force_cookie {
cookie_token_result?
} else {
auth_header_token_result?.to_owned()
};
decode_jwt(&final_token, state).await
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.permission, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let merchant_id = merchant.get_id().clone();
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account: None,
key_store,
profile_id: Some(payload.profile_id),
};
Ok((
auth,
AuthenticationType::MerchantJwt {
merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let profile_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.permission, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&payload.merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let merchant_id = merchant.get_id().clone();
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
profile,
platform_merchant_account: None,
};
Ok((
auth,
AuthenticationType::MerchantJwt {
merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
pub type AuthenticationDataWithUserId = (AuthenticationData, String);
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationDataWithUserId, A> for JWTAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationDataWithUserId, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.permission, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::InvalidJwtToken)?;
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account: None,
key_store,
profile_id: Some(payload.profile_id),
};
Ok((
(auth.clone(), payload.user_id.clone()),
AuthenticationType::MerchantJwt {
merchant_id: auth.merchant_account.get_id().clone(),
user_id: None,
},
))
}
}
pub struct DashboardNoPermissionAuth;
#[cfg(feature = "olap")]
#[async_trait]
impl<A> AuthenticateAndFetch<UserFromToken, A> for DashboardNoPermissionAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(UserFromToken, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
Ok((
UserFromToken {
user_id: payload.user_id.clone(),
merchant_id: payload.merchant_id.clone(),
org_id: payload.org_id,
role_id: payload.role_id,
profile_id: payload.profile_id,
tenant_id: payload.tenant_id,
},
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "olap")]
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for DashboardNoPermissionAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
Ok(((), AuthenticationType::NoAuth))
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for DashboardNoPermissionAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account: None,
key_store,
profile_id: Some(payload.profile_id),
};
Ok((
auth.clone(),
AuthenticationType::MerchantJwt {
merchant_id: auth.merchant_account.get_id().clone(),
user_id: Some(payload.user_id),
},
))
}
}
pub trait ClientSecretFetch {
fn get_client_secret(&self) -> Option<&String>;
}
#[cfg(feature = "payouts")]
impl ClientSecretFetch for payouts::PayoutCreateRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
#[cfg(feature = "v1")]
impl ClientSecretFetch for payments::PaymentsRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
#[cfg(feature = "v1")]
impl ClientSecretFetch for payments::PaymentsEligibilityRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret
.as_ref()
.map(|client_secret| client_secret.peek())
}
}
#[cfg(feature = "v1")]
impl ClientSecretFetch for api_models::blocklist::ListBlocklistQuery {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
#[cfg(feature = "v1")]
impl ClientSecretFetch for payments::PaymentsRetrieveRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
#[cfg(feature = "v1")]
impl ClientSecretFetch for PaymentMethodListRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
impl ClientSecretFetch for payments::PaymentsPostSessionTokensRequest {
fn get_client_secret(&self) -> Option<&String> {
Some(self.client_secret.peek())
}
}
#[cfg(feature = "v1")]
impl ClientSecretFetch for PaymentMethodCreate {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
impl ClientSecretFetch for api_models::cards_info::CardsInfoRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
impl ClientSecretFetch for payments::RetrievePaymentLinkRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
impl ClientSecretFetch for api_models::pm_auth::LinkTokenCreateRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
impl ClientSecretFetch for api_models::pm_auth::ExchangeTokenCreateRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
#[cfg(feature = "v1")]
impl ClientSecretFetch for api_models::payment_methods::PaymentMethodUpdate {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
#[cfg(feature = "v1")]
impl ClientSecretFetch for api_models::subscription::ConfirmSubscriptionRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref().map(|s| s.as_string())
}
}
#[cfg(feature = "v1")]
impl ClientSecretFetch for api_models::subscription::GetPlansQuery {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref().map(|s| s.as_string())
}
}
#[cfg(feature = "v1")]
impl ClientSecretFetch for api_models::authentication::AuthenticationEligibilityRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret
.as_ref()
.map(|client_secret| client_secret.peek())
}
}
impl ClientSecretFetch for api_models::authentication::AuthenticationAuthenticateRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret
.as_ref()
.map(|client_secret| client_secret.peek())
}
}
impl ClientSecretFetch for api_models::authentication::AuthenticationSyncRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret
.as_ref()
.map(|client_secret| client_secret.peek())
}
}
pub fn get_auth_type_and_flow<A: SessionStateInfo + Sync + Send>(
headers: &HeaderMap,
api_auth: ApiKeyAuth,
) -> RouterResult<(
Box<dyn AuthenticateAndFetch<AuthenticationData, A>>,
api::AuthFlow,
)> {
let api_key = get_api_key(headers)?;
if api_key.starts_with("pk_") {
return Ok((
Box::new(HeaderAuth(PublishableKeyAuth)),
api::AuthFlow::Client,
));
}
Ok((Box::new(HeaderAuth(api_auth)), api::AuthFlow::Merchant))
}
pub fn check_client_secret_and_get_auth<T>(
headers: &HeaderMap,
payload: &impl ClientSecretFetch,
api_auth: ApiKeyAuth,
) -> RouterResult<(
Box<dyn AuthenticateAndFetch<AuthenticationData, T>>,
api::AuthFlow,
)>
where
T: SessionStateInfo + Sync + Send,
ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
{
let api_key = get_api_key(headers)?;
if api_key.starts_with("pk_") {
payload
.get_client_secret()
.check_value_present("client_secret")
.map_err(|_| errors::ApiErrorResponse::MissingRequiredField {
field_name: "client_secret",
})?;
return Ok((
Box::new(HeaderAuth(PublishableKeyAuth)),
api::AuthFlow::Client,
));
}
if payload.get_client_secret().is_some() {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "client_secret is not a valid parameter".to_owned(),
}
.into());
}
Ok((Box::new(HeaderAuth(api_auth)), api::AuthFlow::Merchant))
}
pub async fn get_ephemeral_or_other_auth<T>(
headers: &HeaderMap,
is_merchant_flow: bool,
payload: Option<&impl ClientSecretFetch>,
api_auth: ApiKeyAuth,
) -> RouterResult<(
Box<dyn AuthenticateAndFetch<AuthenticationData, T>>,
api::AuthFlow,
bool,
)>
where
T: SessionStateInfo + Sync + Send,
ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
EphemeralKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
{
let api_key = get_api_key(headers)?;
if api_key.starts_with("epk") {
Ok((Box::new(EphemeralKeyAuth), api::AuthFlow::Client, true))
} else if is_merchant_flow {
Ok((
Box::new(HeaderAuth(api_auth)),
api::AuthFlow::Merchant,
false,
))
} else {
let payload = payload.get_required_value("ClientSecretFetch")?;
let (auth, auth_flow) = check_client_secret_and_get_auth(headers, payload, api_auth)?;
Ok((auth, auth_flow, false))
}
}
#[cfg(feature = "v1")]
pub fn is_ephemeral_auth<A: SessionStateInfo + Sync + Send>(
headers: &HeaderMap,
api_auth: ApiKeyAuth,
) -> RouterResult<Box<dyn AuthenticateAndFetch<AuthenticationData, A>>> {
let api_key = get_api_key(headers)?;
if !api_key.starts_with("epk") {
Ok(Box::new(HeaderAuth(api_auth)))
} else {
Ok(Box::new(EphemeralKeyAuth))
}
}
pub fn is_jwt_auth(headers: &HeaderMap) -> bool {
let header_map_struct = HeaderMapStruct::new(headers);
match header_map_struct.get_auth_string_from_header() {
Ok(auth_str) => auth_str.starts_with("Bearer"),
Err(_) => get_cookie_from_header(headers)
.and_then(cookies::get_jwt_from_cookies)
.is_ok(),
}
}
pub fn is_internal_api_key_merchant_id_profile_id_auth(
headers: &HeaderMap,
internal_api_key_auth: settings::InternalMerchantIdProfileIdAuthSettings,
) -> bool {
internal_api_key_auth.enabled
&& headers.contains_key(headers::X_INTERNAL_API_KEY)
&& headers.contains_key(headers::X_MERCHANT_ID)
&& headers.contains_key(headers::X_PROFILE_ID)
}
#[cfg(feature = "v1")]
pub fn check_internal_api_key_auth<T>(
headers: &HeaderMap,
payload: &impl ClientSecretFetch,
api_auth: ApiKeyAuth,
internal_api_key_auth: settings::InternalMerchantIdProfileIdAuthSettings,
) -> RouterResult<(
Box<dyn AuthenticateAndFetch<AuthenticationData, T>>,
api::AuthFlow,
)>
where
T: SessionStateInfo + Sync + Send,
ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
{
if is_internal_api_key_merchant_id_profile_id_auth(headers, internal_api_key_auth) {
Ok((
// HeaderAuth(api_auth) will never be called in this case as the internal auth will be checked first
Box::new(InternalMerchantIdProfileIdAuth(HeaderAuth(api_auth))),
api::AuthFlow::Merchant,
))
} else {
check_client_secret_and_get_auth(headers, payload, api_auth)
}
}
#[cfg(feature = "v1")]
pub fn check_internal_api_key_auth_no_client_secret<T>(
headers: &HeaderMap,
api_auth: ApiKeyAuth,
internal_api_key_auth: settings::InternalMerchantIdProfileIdAuthSettings,
) -> RouterResult<(
Box<dyn AuthenticateAndFetch<AuthenticationData, T>>,
api::AuthFlow,
)>
where
T: SessionStateInfo + Sync + Send,
ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
{
if is_internal_api_key_merchant_id_profile_id_auth(headers, internal_api_key_auth) {
Ok((
// HeaderAuth(api_auth) will never be called in this case as the internal auth will be checked first
Box::new(InternalMerchantIdProfileIdAuth(HeaderAuth(api_auth))),
api::AuthFlow::Merchant,
))
} else {
let (auth, auth_flow) = get_auth_type_and_flow(headers, api_auth)?;
Ok((auth, auth_flow))
}
}
pub async fn decode_jwt<T>(token: &str, state: &impl SessionStateInfo) -> RouterResult<T>
where
T: serde::de::DeserializeOwned,
{
let conf = state.conf();
let secret = conf.secrets.get_inner().jwt_secret.peek().as_bytes();
let key = DecodingKey::from_secret(secret);
decode::<T>(token, &key, &Validation::new(Algorithm::HS256))
.map(|decoded| decoded.claims)
.change_context(errors::ApiErrorResponse::InvalidJwtToken)
}
pub fn get_api_key(headers: &HeaderMap) -> RouterResult<&str> {
get_header_value_by_key("api-key".into(), headers)?.get_required_value("api_key")
}
pub fn get_header_value_by_key(key: String, headers: &HeaderMap) -> RouterResult<Option<&str>> {
headers
.get(&key)
.map(|source_str| {
source_str
.to_str()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Failed to convert header value to string for header key: {key}",
))
})
.transpose()
}
pub fn get_id_type_by_key_from_headers<T: FromStr>(
key: String,
headers: &HeaderMap,
) -> RouterResult<Option<T>> {
get_header_value_by_key(key.clone(), headers)?
.map(|str_value| T::from_str(str_value))
.transpose()
.map_err(|_err| {
error_stack::report!(errors::ApiErrorResponse::InvalidDataFormat {
field_name: key,
expected_format: "Valid Id String".to_string(),
})
})
}
pub fn get_jwt_from_authorization_header(headers: &HeaderMap) -> RouterResult<&str> {
headers
.get(headers::AUTHORIZATION)
.get_required_value(headers::AUTHORIZATION)?
.to_str()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert JWT token to string")?
.strip_prefix("Bearer ")
.ok_or(errors::ApiErrorResponse::InvalidJwtToken.into())
}
pub fn get_cookie_from_header(headers: &HeaderMap) -> RouterResult<&str> {
let cookie = headers
.get(cookies::get_cookie_header())
.ok_or(report!(errors::ApiErrorResponse::CookieNotFound))?;
cookie
.to_str()
.change_context(errors::ApiErrorResponse::InvalidCookie)
}
pub fn strip_jwt_token(token: &str) -> RouterResult<&str> {
token
.strip_prefix("Bearer ")
.ok_or_else(|| errors::ApiErrorResponse::InvalidJwtToken.into())
}
pub fn auth_type<'a, T, A>(
default_auth: &'a dyn AuthenticateAndFetch<T, A>,
jwt_auth_type: &'a dyn AuthenticateAndFetch<T, A>,
headers: &HeaderMap,
) -> &'a dyn AuthenticateAndFetch<T, A>
where
{
if is_jwt_auth(headers) {
return jwt_auth_type;
}
default_auth
}
#[cfg(feature = "recon")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationDataWithUser, A> for JWTAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationDataWithUser, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.permission, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let user_id = payload.user_id;
let user = state
.session_state()
.global_store
.find_user_by_id(&user_id)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch user for the user id")?;
let auth = AuthenticationDataWithUser {
merchant_account: merchant,
key_store,
profile_id: payload.profile_id.clone(),
user,
};
let auth_type = AuthenticationType::MerchantJwt {
merchant_id: auth.merchant_account.get_id().clone(),
user_id: Some(user_id),
};
Ok((auth, auth_type))
}
}
async fn get_connected_merchant_account<A>(
state: &A,
connected_merchant_id: id_type::MerchantId,
platform_org_id: id_type::OrganizationId,
) -> RouterResult<domain::MerchantAccount>
where
A: SessionStateInfo + Sync,
{
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&connected_merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidPlatformOperation)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let connected_merchant_account = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &connected_merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidPlatformOperation)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
if platform_org_id != connected_merchant_account.organization_id {
return Err(errors::ApiErrorResponse::InvalidPlatformOperation)
.attach_printable("Access for merchant id Unauthorized");
}
Ok(connected_merchant_account)
}
async fn get_platform_merchant_account<A>(
state: &A,
request_headers: &HeaderMap,
merchant_account: domain::MerchantAccount,
) -> RouterResult<(domain::MerchantAccount, Option<domain::MerchantAccount>)>
where
A: SessionStateInfo + Sync,
{
let connected_merchant_id =
get_and_validate_connected_merchant_id(request_headers, &merchant_account)?;
match connected_merchant_id {
Some(merchant_id) => {
let connected_merchant_account = get_connected_merchant_account(
state,
merchant_id,
merchant_account.organization_id.clone(),
)
.await?;
Ok((connected_merchant_account, Some(merchant_account)))
}
None => Ok((merchant_account, None)),
}
}
fn get_and_validate_connected_merchant_id(
request_headers: &HeaderMap,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<Option<id_type::MerchantId>> {
HeaderMapStruct::new(request_headers)
.get_id_type_from_header_if_present::<id_type::MerchantId>(
headers::X_CONNECTED_MERCHANT_ID,
)?
.map(|merchant_id| {
(merchant_account.is_platform_account())
.then_some(merchant_id)
.ok_or(errors::ApiErrorResponse::InvalidPlatformOperation)
})
.transpose()
.attach_printable("Non platform_merchant_account using X_CONNECTED_MERCHANT_ID header")
}
fn throw_error_if_platform_merchant_authentication_required(
request_headers: &HeaderMap,
) -> RouterResult<()> {
HeaderMapStruct::new(request_headers)
.get_id_type_from_header_if_present::<id_type::MerchantId>(
headers::X_CONNECTED_MERCHANT_ID,
)?
.map_or(Ok(()), |_| {
Err(errors::ApiErrorResponse::PlatformAccountAuthNotSupported.into())
})
}
#[cfg(feature = "recon")]
#[async_trait]
impl<A> AuthenticateAndFetch<UserFromTokenWithRoleInfo, A> for JWTAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(UserFromTokenWithRoleInfo, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.permission, &role_info)?;
let user = UserFromToken {
user_id: payload.user_id.clone(),
merchant_id: payload.merchant_id.clone(),
org_id: payload.org_id,
role_id: payload.role_id,
profile_id: payload.profile_id,
tenant_id: payload.tenant_id,
};
Ok((
UserFromTokenWithRoleInfo { user, role_info },
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "recon")]
#[derive(serde::Serialize, serde::Deserialize)]
pub struct ReconToken {
pub user_id: String,
pub merchant_id: id_type::MerchantId,
pub role_id: String,
pub exp: u64,
pub org_id: id_type::OrganizationId,
pub profile_id: id_type::ProfileId,
pub tenant_id: Option<id_type::TenantId>,
#[serde(skip_serializing_if = "Option::is_none")]
pub acl: Option<String>,
}
#[cfg(all(feature = "olap", feature = "recon"))]
impl ReconToken {
pub async fn new_token(
user_id: String,
merchant_id: id_type::MerchantId,
settings: &Settings,
org_id: id_type::OrganizationId,
profile_id: id_type::ProfileId,
tenant_id: Option<id_type::TenantId>,
role_info: authorization::roles::RoleInfo,
) -> UserResult<String> {
let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS);
let exp = jwt::generate_exp(exp_duration)?.as_secs();
let acl = role_info.get_recon_acl();
let optional_acl_str = serde_json::to_string(&acl)
.inspect_err(|err| logger::error!("Failed to serialize acl to string: {}", err))
.change_context(errors::UserErrors::InternalServerError)
.attach_printable("Failed to serialize acl to string. Using empty ACL")
.ok();
let token_payload = Self {
user_id,
merchant_id,
role_id: role_info.get_role_id().to_string(),
exp,
org_id,
profile_id,
tenant_id,
acl: optional_acl_str,
};
jwt::generate_jwt(&token_payload, settings).await
}
}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct ExternalToken {
pub user_id: String,
pub merchant_id: id_type::MerchantId,
pub exp: u64,
pub external_service_type: ExternalServiceType,
}
impl ExternalToken {
pub async fn new_token(
user_id: String,
merchant_id: id_type::MerchantId,
settings: &Settings,
external_service_type: ExternalServiceType,
) -> UserResult<String> {
let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS);
let exp = jwt::generate_exp(exp_duration)?.as_secs();
let token_payload = Self {
user_id,
merchant_id,
exp,
external_service_type,
};
jwt::generate_jwt(&token_payload, settings).await
}
pub fn check_service_type(
&self,
required_service_type: &ExternalServiceType,
) -> RouterResult<()> {
Ok(fp_utils::when(
&self.external_service_type != required_service_type,
|| {
Err(errors::ApiErrorResponse::AccessForbidden {
resource: required_service_type.to_string(),
})
},
)?)
}
}
| {
"crate": "router",
"file": "crates/router/src/services/authentication.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 36,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_3914027823006247013 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/api.rs
// Contains: 1 structs, 1 enums
pub mod client;
pub mod generic_link_response;
pub mod request;
use std::{
collections::{HashMap, HashSet},
fmt::Debug,
future::Future,
str,
sync::Arc,
time::{Duration, Instant},
};
use actix_http::header::HeaderMap;
use actix_web::{
body,
http::header::{HeaderName, HeaderValue},
web, FromRequest, HttpRequest, HttpResponse, Responder, ResponseError,
};
pub use client::{ApiClient, MockApiClient, ProxyClient};
pub use common_enums::enums::PaymentAction;
pub use common_utils::request::{ContentType, Method, Request, RequestBuilder};
use common_utils::{
consts::{DEFAULT_TENANT, TENANT_HEADER, X_HS_LATENCY},
errors::{ErrorSwitch, ReportSwitchExt},
};
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::router_data_v2::flow_common_types as common_types;
pub use hyperswitch_domain_models::{
api::{
ApplicationResponse, GenericExpiredLinkData, GenericLinkFormData, GenericLinkStatusData,
GenericLinks, PaymentLinkAction, PaymentLinkFormData, PaymentLinkStatusData,
RedirectionFormData,
},
payment_method_data::PaymentMethodData,
router_response_types::RedirectForm,
};
pub use hyperswitch_interfaces::{
api::{
BoxedConnectorIntegration, CaptureSyncMethod, ConnectorIntegration,
ConnectorIntegrationAny, ConnectorRedirectResponse, ConnectorSpecifications,
ConnectorValidation,
},
api_client::{
call_connector_api, execute_connector_processing_step, handle_response,
handle_ucs_response, store_raw_connector_response_if_required,
},
connector_integration_v2::{
BoxedConnectorIntegrationV2, ConnectorIntegrationAnyV2, ConnectorIntegrationV2,
},
};
use masking::{Maskable, PeekInterface};
use router_env::{instrument, tracing, tracing_actix_web::RequestId, Tag};
use serde::Serialize;
use tera::{Context, Error as TeraError, Tera};
use super::{
authentication::AuthenticateAndFetch,
connector_integration_interface::BoxedConnectorIntegrationInterface,
};
use crate::{
configs::Settings,
core::{
api_locking,
errors::{self, CustomResult},
},
events::api_logs::{ApiEvent, ApiEventMetric, ApiEventsType},
headers, logger,
routes::{
app::{AppStateInfo, ReqState, SessionStateInfo},
metrics, AppState, SessionState,
},
services::generic_link_response::build_generic_link_html,
types::api,
utils,
};
pub type BoxedPaymentConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::PaymentFlowData, Req, Resp>;
pub type BoxedRefundConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::RefundFlowData, Req, Resp>;
#[cfg(feature = "frm")]
pub type BoxedFrmConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::FrmFlowData, Req, Resp>;
pub type BoxedDisputeConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::DisputesFlowData, Req, Resp>;
pub type BoxedMandateRevokeConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::MandateRevokeFlowData, Req, Resp>;
#[cfg(feature = "payouts")]
pub type BoxedPayoutConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::PayoutFlowData, Req, Resp>;
pub type BoxedWebhookSourceVerificationConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::WebhookSourceVerifyData, Req, Resp>;
pub type BoxedExternalAuthenticationConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::ExternalAuthenticationFlowData, Req, Resp>;
pub type BoxedAuthenticationTokenConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::AuthenticationTokenFlowData, Req, Resp>;
pub type BoxedAccessTokenConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::AccessTokenFlowData, Req, Resp>;
pub type BoxedFilesConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::FilesFlowData, Req, Resp>;
pub type BoxedRevenueRecoveryRecordBackInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::InvoiceRecordBackData, Req, Res>;
pub type BoxedGetSubscriptionPlansInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::GetSubscriptionPlansData, Req, Res>;
pub type BoxedGetSubscriptionPlanPricesInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::GetSubscriptionPlanPricesData, Req, Res>;
pub type BoxedGetSubscriptionEstimateInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::GetSubscriptionEstimateData, Req, Res>;
pub type BoxedBillingConnectorInvoiceSyncIntegrationInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<
T,
common_types::BillingConnectorInvoiceSyncFlowData,
Req,
Res,
>;
pub type BoxedUnifiedAuthenticationServiceInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::UasFlowData, Req, Resp>;
pub type BoxedBillingConnectorPaymentsSyncIntegrationInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<
T,
common_types::BillingConnectorPaymentsSyncFlowData,
Req,
Res,
>;
pub type BoxedVaultConnectorIntegrationInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::VaultConnectorFlowData, Req, Res>;
pub type BoxedGiftCardBalanceCheckIntegrationInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::GiftCardBalanceCheckFlowData, Req, Res>;
pub type BoxedSubscriptionConnectorIntegrationInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::SubscriptionCreateData, Req, Res>;
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct ApplicationRedirectResponse {
pub url: String,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum AuthFlow {
Client,
Merchant,
}
#[allow(clippy::too_many_arguments)]
#[instrument(
skip(request, payload, state, func, api_auth, incoming_request_header),
fields(merchant_id)
)]
pub async fn server_wrap_util<'a, 'b, U, T, Q, F, Fut, E, OErr>(
flow: &'a impl router_env::types::FlowMetric,
state: web::Data<AppState>,
incoming_request_header: &HeaderMap,
request: &'a HttpRequest,
payload: T,
func: F,
api_auth: &dyn AuthenticateAndFetch<U, SessionState>,
lock_action: api_locking::LockAction,
) -> CustomResult<ApplicationResponse<Q>, OErr>
where
F: Fn(SessionState, U, T, ReqState) -> Fut,
'b: 'a,
Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>,
Q: Serialize + Debug + 'a + ApiEventMetric,
T: Debug + Serialize + ApiEventMetric,
E: ErrorSwitch<OErr> + error_stack::Context,
OErr: ResponseError + error_stack::Context + Serialize,
errors::ApiErrorResponse: ErrorSwitch<OErr>,
{
let request_id = RequestId::extract(request)
.await
.attach_printable("Unable to extract request id from request")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?;
let mut app_state = state.get_ref().clone();
let start_instant = Instant::now();
let serialized_request = masking::masked_serialize(&payload)
.attach_printable("Failed to serialize json request")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?;
let mut event_type = payload.get_api_event_type();
let tenant_id = if !state.conf.multitenancy.enabled {
common_utils::id_type::TenantId::try_from_string(DEFAULT_TENANT.to_owned())
.attach_printable("Unable to get default tenant id")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?
} else {
let request_tenant_id = incoming_request_header
.get(TENANT_HEADER)
.and_then(|value| value.to_str().ok())
.ok_or_else(|| errors::ApiErrorResponse::MissingTenantId.switch())
.and_then(|header_value| {
common_utils::id_type::TenantId::try_from_string(header_value.to_string()).map_err(
|_| {
errors::ApiErrorResponse::InvalidRequestData {
message: format!("`{}` header is invalid", headers::X_TENANT_ID),
}
.switch()
},
)
})?;
state
.conf
.multitenancy
.get_tenant(&request_tenant_id)
.map(|tenant| tenant.tenant_id.clone())
.ok_or(
errors::ApiErrorResponse::InvalidTenant {
tenant_id: request_tenant_id.get_string_repr().to_string(),
}
.switch(),
)?
};
let locale = utils::get_locale_from_header(&incoming_request_header.clone());
let mut session_state =
Arc::new(app_state.clone()).get_session_state(&tenant_id, Some(locale), || {
errors::ApiErrorResponse::InvalidTenant {
tenant_id: tenant_id.get_string_repr().to_string(),
}
.switch()
})?;
session_state.add_request_id(request_id);
let mut request_state = session_state.get_req_state();
request_state.event_context.record_info(request_id);
request_state
.event_context
.record_info(("flow".to_string(), flow.to_string()));
request_state.event_context.record_info((
"tenant_id".to_string(),
tenant_id.get_string_repr().to_string(),
));
// Currently auth failures are not recorded as API events
let (auth_out, auth_type) = api_auth
.authenticate_and_fetch(request.headers(), &session_state)
.await
.switch()?;
request_state.event_context.record_info(auth_type.clone());
let merchant_id = auth_type
.get_merchant_id()
.cloned()
.unwrap_or(common_utils::id_type::MerchantId::get_merchant_id_not_found());
app_state.add_flow_name(flow.to_string());
tracing::Span::current().record("merchant_id", merchant_id.get_string_repr().to_owned());
let output = {
lock_action
.clone()
.perform_locking_action(&session_state, merchant_id.to_owned())
.await
.switch()?;
let res = func(session_state.clone(), auth_out, payload, request_state)
.await
.switch();
lock_action
.free_lock_action(&session_state, merchant_id.to_owned())
.await
.switch()?;
res
};
let request_duration = Instant::now()
.saturating_duration_since(start_instant)
.as_millis();
let mut serialized_response = None;
let mut error = None;
let mut overhead_latency = None;
let status_code = match output.as_ref() {
Ok(res) => {
if let ApplicationResponse::Json(data) = res {
serialized_response.replace(
masking::masked_serialize(&data)
.attach_printable("Failed to serialize json response")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?,
);
} else if let ApplicationResponse::JsonWithHeaders((data, headers)) = res {
serialized_response.replace(
masking::masked_serialize(&data)
.attach_printable("Failed to serialize json response")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?,
);
if let Some((_, value)) = headers.iter().find(|(key, _)| key == X_HS_LATENCY) {
if let Ok(external_latency) = value.clone().into_inner().parse::<u128>() {
overhead_latency.replace(external_latency);
}
}
}
event_type = res.get_api_event_type().or(event_type);
metrics::request::track_response_status_code(res)
}
Err(err) => {
error.replace(
serde_json::to_value(err.current_context())
.attach_printable("Failed to serialize json response")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())
.ok()
.into(),
);
err.current_context().status_code().as_u16().into()
}
};
let infra = extract_mapped_fields(
&serialized_request,
state.enhancement.as_ref(),
state.infra_components.as_ref(),
);
let api_event = ApiEvent::new(
tenant_id,
Some(merchant_id.clone()),
flow,
&request_id,
request_duration,
status_code,
serialized_request,
serialized_response,
overhead_latency,
auth_type,
error,
event_type.unwrap_or(ApiEventsType::Miscellaneous),
request,
request.method(),
infra.clone(),
);
state.event_handler().log_event(&api_event);
output
}
#[instrument(
skip(request, state, func, api_auth, payload),
fields(request_method, request_url_path, status_code)
)]
pub async fn server_wrap<'a, T, U, Q, F, Fut, E>(
flow: impl router_env::types::FlowMetric,
state: web::Data<AppState>,
request: &'a HttpRequest,
payload: T,
func: F,
api_auth: &dyn AuthenticateAndFetch<U, SessionState>,
lock_action: api_locking::LockAction,
) -> HttpResponse
where
F: Fn(SessionState, U, T, ReqState) -> Fut,
Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>,
Q: Serialize + Debug + ApiEventMetric + 'a,
T: Debug + Serialize + ApiEventMetric,
ApplicationResponse<Q>: Debug,
E: ErrorSwitch<api_models::errors::types::ApiErrorResponse> + error_stack::Context,
{
let request_method = request.method().as_str();
let url_path = request.path();
let unmasked_incoming_header_keys = state.conf().unmasked_headers.keys;
let incoming_request_header = request.headers();
let incoming_header_to_log: HashMap<String, HeaderValue> =
incoming_request_header
.iter()
.fold(HashMap::new(), |mut acc, (key, value)| {
let key = key.to_string();
if unmasked_incoming_header_keys.contains(&key.as_str().to_lowercase()) {
acc.insert(key.clone(), value.clone());
} else {
acc.insert(key.clone(), HeaderValue::from_static("**MASKED**"));
}
acc
});
tracing::Span::current().record("request_method", request_method);
tracing::Span::current().record("request_url_path", url_path);
let start_instant = Instant::now();
logger::info!(
tag = ?Tag::BeginRequest, payload = ?payload,
headers = ?incoming_header_to_log);
let server_wrap_util_res = server_wrap_util(
&flow,
state.clone(),
incoming_request_header,
request,
payload,
func,
api_auth,
lock_action,
)
.await
.map(|response| {
logger::info!(api_response =? response);
response
});
let res = match server_wrap_util_res {
Ok(ApplicationResponse::Json(response)) => match serde_json::to_string(&response) {
Ok(res) => http_response_json(res),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error serializing response from connector"
}
}"#,
),
},
Ok(ApplicationResponse::StatusOk) => http_response_ok(),
Ok(ApplicationResponse::TextPlain(text)) => http_response_plaintext(text),
Ok(ApplicationResponse::FileData((file_data, content_type))) => {
http_response_file_data(file_data, content_type)
}
Ok(ApplicationResponse::JsonForRedirection(response)) => {
match serde_json::to_string(&response) {
Ok(res) => http_redirect_response(res, response),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error serializing response from connector"
}
}"#,
),
}
}
Ok(ApplicationResponse::Form(redirection_data)) => {
let config = state.conf();
build_redirection_form(
&redirection_data.redirect_form,
redirection_data.payment_method_data,
redirection_data.amount,
redirection_data.currency,
config,
)
.respond_to(request)
.map_into_boxed_body()
}
Ok(ApplicationResponse::GenericLinkForm(boxed_generic_link_data)) => {
let link_type = boxed_generic_link_data.data.to_string();
match build_generic_link_html(
boxed_generic_link_data.data,
boxed_generic_link_data.locale,
) {
Ok(rendered_html) => {
let headers = if !boxed_generic_link_data.allowed_domains.is_empty() {
let domains_str = boxed_generic_link_data
.allowed_domains
.into_iter()
.collect::<Vec<String>>()
.join(" ");
let csp_header = format!("frame-ancestors 'self' {domains_str};");
Some(HashSet::from([("content-security-policy", csp_header)]))
} else {
None
};
http_response_html_data(rendered_html, headers)
}
Err(_) => http_response_err(format!("Error while rendering {link_type} HTML page")),
}
}
Ok(ApplicationResponse::PaymentLinkForm(boxed_payment_link_data)) => {
match *boxed_payment_link_data {
PaymentLinkAction::PaymentLinkFormData(payment_link_data) => {
match build_payment_link_html(payment_link_data) {
Ok(rendered_html) => http_response_html_data(rendered_html, None),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error while rendering payment link html page"
}
}"#,
),
}
}
PaymentLinkAction::PaymentLinkStatus(payment_link_data) => {
match get_payment_link_status(payment_link_data) {
Ok(rendered_html) => http_response_html_data(rendered_html, None),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error while rendering payment link status page"
}
}"#,
),
}
}
}
}
Ok(ApplicationResponse::JsonWithHeaders((response, headers))) => {
let request_elapsed_time = request.headers().get(X_HS_LATENCY).and_then(|value| {
if value == "true" {
Some(start_instant.elapsed())
} else {
None
}
});
let proxy_connector_http_status_code = if state
.conf
.proxy_status_mapping
.proxy_connector_http_status_code
{
headers
.iter()
.find(|(key, _)| key == headers::X_CONNECTOR_HTTP_STATUS_CODE)
.and_then(|(_, value)| {
match value.clone().into_inner().parse::<u16>() {
Ok(code) => match http::StatusCode::from_u16(code) {
Ok(status_code) => Some(status_code),
Err(err) => {
logger::error!(
"Invalid HTTP status code parsed from connector_http_status_code: {:?}",
err
);
None
}
},
Err(err) => {
logger::error!(
"Failed to parse connector_http_status_code from header: {:?}",
err
);
None
}
}
})
} else {
None
};
match serde_json::to_string(&response) {
Ok(res) => http_response_json_with_headers(
res,
headers,
request_elapsed_time,
proxy_connector_http_status_code,
),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error serializing response from connector"
}
}"#,
),
}
}
Err(error) => log_and_return_error_response(error),
};
let response_code = res.status().as_u16();
tracing::Span::current().record("status_code", response_code);
let end_instant = Instant::now();
let request_duration = end_instant.saturating_duration_since(start_instant);
logger::info!(
tag = ?Tag::EndRequest,
time_taken_ms = request_duration.as_millis(),
);
res
}
pub fn log_and_return_error_response<T>(error: Report<T>) -> HttpResponse
where
T: error_stack::Context + Clone + ResponseError,
Report<T>: EmbedError,
{
logger::error!(?error);
HttpResponse::from_error(error.embed().current_context().clone())
}
pub trait EmbedError: Sized {
fn embed(self) -> Self {
self
}
}
impl EmbedError for Report<api_models::errors::types::ApiErrorResponse> {
fn embed(self) -> Self {
#[cfg(feature = "detailed_errors")]
{
let mut report = self;
let error_trace = serde_json::to_value(&report).ok().and_then(|inner| {
serde_json::from_value::<Vec<errors::NestedErrorStack<'_>>>(inner)
.ok()
.map(Into::<errors::VecLinearErrorStack<'_>>::into)
.map(serde_json::to_value)
.transpose()
.ok()
.flatten()
});
match report.downcast_mut::<api_models::errors::types::ApiErrorResponse>() {
None => {}
Some(inner) => {
inner.get_internal_error_mut().stacktrace = error_trace;
}
}
report
}
#[cfg(not(feature = "detailed_errors"))]
self
}
}
impl EmbedError
for Report<hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse>
{
}
pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::APPLICATION_JSON)
.body(response)
}
pub fn http_server_error_json_response<T: body::MessageBody + 'static>(
response: T,
) -> HttpResponse {
HttpResponse::InternalServerError()
.content_type(mime::APPLICATION_JSON)
.body(response)
}
pub fn http_response_json_with_headers<T: body::MessageBody + 'static>(
response: T,
headers: Vec<(String, Maskable<String>)>,
request_duration: Option<Duration>,
status_code: Option<http::StatusCode>,
) -> HttpResponse {
let mut response_builder = HttpResponse::build(status_code.unwrap_or(http::StatusCode::OK));
for (header_name, header_value) in headers {
let is_sensitive_header = header_value.is_masked();
let mut header_value = header_value.into_inner();
if header_name == X_HS_LATENCY {
if let Some(request_duration) = request_duration {
if let Ok(external_latency) = header_value.parse::<u128>() {
let updated_duration = request_duration.as_millis() - external_latency;
header_value = updated_duration.to_string();
}
}
}
let mut header_value = match HeaderValue::from_str(header_value.as_str()) {
Ok(header_value) => header_value,
Err(error) => {
logger::error!(?error);
return http_server_error_json_response("Something Went Wrong");
}
};
if is_sensitive_header {
header_value.set_sensitive(true);
}
response_builder.append_header((header_name, header_value));
}
response_builder
.content_type(mime::APPLICATION_JSON)
.body(response)
}
pub fn http_response_plaintext<T: body::MessageBody + 'static>(res: T) -> HttpResponse {
HttpResponse::Ok().content_type(mime::TEXT_PLAIN).body(res)
}
pub fn http_response_file_data<T: body::MessageBody + 'static>(
res: T,
content_type: mime::Mime,
) -> HttpResponse {
HttpResponse::Ok().content_type(content_type).body(res)
}
pub fn http_response_html_data<T: body::MessageBody + 'static>(
res: T,
optional_headers: Option<HashSet<(&'static str, String)>>,
) -> HttpResponse {
let mut res_builder = HttpResponse::Ok();
res_builder.content_type(mime::TEXT_HTML);
if let Some(headers) = optional_headers {
for (key, value) in headers {
if let Ok(header_val) = HeaderValue::try_from(value) {
res_builder.insert_header((HeaderName::from_static(key), header_val));
}
}
}
res_builder.body(res)
}
pub fn http_response_ok() -> HttpResponse {
HttpResponse::Ok().finish()
}
pub fn http_redirect_response<T: body::MessageBody + 'static>(
response: T,
redirection_response: api::RedirectionResponse,
) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::APPLICATION_JSON)
.append_header((
"Location",
redirection_response.return_url_with_query_params,
))
.status(http::StatusCode::FOUND)
.body(response)
}
pub fn http_response_err<T: body::MessageBody + 'static>(response: T) -> HttpResponse {
HttpResponse::BadRequest()
.content_type(mime::APPLICATION_JSON)
.body(response)
}
pub trait Authenticate {
fn get_client_secret(&self) -> Option<&String> {
None
}
fn should_return_raw_response(&self) -> Option<bool> {
None
}
}
#[cfg(feature = "v2")]
impl Authenticate for api_models::payments::PaymentsConfirmIntentRequest {
fn should_return_raw_response(&self) -> Option<bool> {
self.return_raw_connector_response
}
}
#[cfg(feature = "v2")]
impl Authenticate for api_models::payments::ProxyPaymentsRequest {}
#[cfg(feature = "v2")]
impl Authenticate for api_models::payments::ExternalVaultProxyPaymentsRequest {}
#[cfg(feature = "v1")]
impl Authenticate for api_models::payments::PaymentsRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
fn should_return_raw_response(&self) -> Option<bool> {
// In v1, this maps to `all_keys_required` to retain backward compatibility.
// The equivalent field in v2 is `return_raw_connector_response`.
self.all_keys_required
}
}
#[cfg(feature = "v1")]
impl Authenticate for api_models::payment_methods::PaymentMethodListRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
#[cfg(feature = "v1")]
impl Authenticate for api_models::payments::PaymentsSessionRequest {
fn get_client_secret(&self) -> Option<&String> {
Some(&self.client_secret)
}
}
impl Authenticate for api_models::payments::PaymentsDynamicTaxCalculationRequest {
fn get_client_secret(&self) -> Option<&String> {
Some(self.client_secret.peek())
}
}
impl Authenticate for api_models::payments::PaymentsPostSessionTokensRequest {
fn get_client_secret(&self) -> Option<&String> {
Some(self.client_secret.peek())
}
}
impl Authenticate for api_models::payments::PaymentsUpdateMetadataRequest {}
impl Authenticate for api_models::payments::PaymentsRetrieveRequest {
#[cfg(feature = "v2")]
fn should_return_raw_response(&self) -> Option<bool> {
self.return_raw_connector_response
}
#[cfg(feature = "v1")]
fn should_return_raw_response(&self) -> Option<bool> {
// In v1, this maps to `all_keys_required` to retain backward compatibility.
// The equivalent field in v2 is `return_raw_connector_response`.
self.all_keys_required
}
}
impl Authenticate for api_models::payments::PaymentsCancelRequest {}
impl Authenticate for api_models::payments::PaymentsCancelPostCaptureRequest {}
impl Authenticate for api_models::payments::PaymentsCaptureRequest {}
impl Authenticate for api_models::payments::PaymentsIncrementalAuthorizationRequest {}
impl Authenticate for api_models::payments::PaymentsExtendAuthorizationRequest {}
impl Authenticate for api_models::payments::PaymentsStartRequest {}
// impl Authenticate for api_models::payments::PaymentsApproveRequest {}
impl Authenticate for api_models::payments::PaymentsRejectRequest {}
// #[cfg(feature = "v2")]
// impl Authenticate for api_models::payments::PaymentsIntentResponse {}
pub fn build_redirection_form(
form: &RedirectForm,
payment_method_data: Option<PaymentMethodData>,
amount: String,
currency: String,
config: Settings,
) -> maud::Markup {
use maud::PreEscaped;
let logging_template =
include_str!("redirection/assets/redirect_error_logs_push.js").to_string();
match form {
RedirectForm::Form {
endpoint,
method,
form_fields,
} => maud::html! {
(maud::DOCTYPE)
html {
meta name="viewport" content="width=device-width, initial-scale=1";
head {
style {
r##"
"##
}
(PreEscaped(r##"
<style>
#loader1 {
width: 500px,
}
@media (max-width: 600px) {
#loader1 {
width: 200px
}
}
</style>
"##))
}
body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-left: auto; margin-right: auto;" { "" }
(PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#))
(PreEscaped(r#"
<script>
var anime = bodymovin.loadAnimation({
container: document.getElementById('loader1'),
renderer: 'svg',
loop: true,
autoplay: true,
name: 'hyperswitch loader',
animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]}
})
</script>
"#))
h3 style="text-align: center;" { "Please wait while we process your payment..." }
form action=(PreEscaped(endpoint)) method=(method.to_string()) #payment_form {
@for (field, value) in form_fields {
input type="hidden" name=(field) value=(value);
}
}
(PreEscaped(format!(r#"
<script type="text/javascript"> {logging_template}
var frm = document.getElementById("payment_form");
var formFields = frm.querySelectorAll("input");
if (frm.method.toUpperCase() === "GET" && formFields.length === 0) {{
window.setTimeout(function () {{
window.location.href = frm.action;
}}, 300);
}} else {{
window.setTimeout(function () {{
frm.submit();
}}, 300);
}}
</script>
"#)))
}
}
},
RedirectForm::Html { html_data } => {
PreEscaped(format!("{html_data} <script>{logging_template}</script>"))
}
RedirectForm::BarclaycardAuthSetup {
access_token,
ddc_url,
reference_id,
} => {
maud::html! {
(maud::DOCTYPE)
html {
head {
meta name="viewport" content="width=device-width, initial-scale=1";
}
body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" }
(PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#))
(PreEscaped(r#"
<script>
var anime = bodymovin.loadAnimation({
container: document.getElementById('loader1'),
renderer: 'svg',
loop: true,
autoplay: true,
name: 'hyperswitch loader',
animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]}
})
</script>
"#))
h3 style="text-align: center;" { "Please wait while we process your payment..." }
}
(PreEscaped(r#"<iframe id="cardinal_collection_iframe" name="collectionIframe" height="10" width="10" style="display: none;"></iframe>"#))
(PreEscaped(format!("<form id=\"cardinal_collection_form\" method=\"POST\" target=\"collectionIframe\" action=\"{ddc_url}\">
<input id=\"cardinal_collection_form_input\" type=\"hidden\" name=\"JWT\" value=\"{access_token}\">
</form>")))
(PreEscaped(r#"<script>
window.onload = function() {
var cardinalCollectionForm = document.querySelector('#cardinal_collection_form'); if(cardinalCollectionForm) cardinalCollectionForm.submit();
}
</script>"#))
(PreEscaped(format!("<script>
{logging_template}
window.addEventListener(\"message\", function(event) {{
if (event.origin === \"https://centinelapistag.cardinalcommerce.com\" || event.origin === \"https://centinelapi.cardinalcommerce.com\") {{
window.location.href = window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/cybersource?referenceId={reference_id}\");
}}
}}, false);
</script>
")))
}}
}
RedirectForm::BarclaycardConsumerAuth {
access_token,
step_up_url,
} => {
maud::html! {
(maud::DOCTYPE)
html {
head {
meta name="viewport" content="width=device-width, initial-scale=1";
}
body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" }
(PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#))
(PreEscaped(r#"
<script>
var anime = bodymovin.loadAnimation({
container: document.getElementById('loader1'),
renderer: 'svg',
loop: true,
autoplay: true,
name: 'hyperswitch loader',
animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]}
})
</script>
"#))
h3 style="text-align: center;" { "Please wait while we process your payment..." }
}
// This is the iframe recommended by cybersource but the redirection happens inside this iframe once otp
// is received and we lose control of the redirection on user client browser, so to avoid that we have removed this iframe and directly consumed it.
// (PreEscaped(r#"<iframe id="step_up_iframe" style="border: none; margin-left: auto; margin-right: auto; display: block" height="800px" width="400px" name="stepUpIframe"></iframe>"#))
(PreEscaped(format!("<form id=\"step-up-form\" method=\"POST\" action=\"{step_up_url}\">
<input type=\"hidden\" name=\"JWT\" value=\"{access_token}\">
</form>")))
(PreEscaped(format!("<script>
{logging_template}
window.onload = function() {{
var stepUpForm = document.querySelector('#step-up-form'); if(stepUpForm) stepUpForm.submit();
}}
</script>")))
}}
}
RedirectForm::BlueSnap {
payment_fields_token,
} => {
let card_details = if let Some(PaymentMethodData::Card(ccard)) = payment_method_data {
format!(
"var saveCardDirectly={{cvv: \"{}\",amount: {},currency: \"{}\"}};",
ccard.card_cvc.peek(),
amount,
currency
)
} else {
"".to_string()
};
let bluesnap_sdk_url = config.connectors.bluesnap.secondary_base_url;
maud::html! {
(maud::DOCTYPE)
html {
head {
meta name="viewport" content="width=device-width, initial-scale=1";
(PreEscaped(format!("<script src=\"{bluesnap_sdk_url}web-sdk/5/bluesnap.js\"></script>")))
}
body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" }
(PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#))
(PreEscaped(r#"
<script>
var anime = bodymovin.loadAnimation({
container: document.getElementById('loader1'),
renderer: 'svg',
loop: true,
autoplay: true,
name: 'hyperswitch loader',
animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]}
})
</script>
"#))
h3 style="text-align: center;" { "Please wait while we process your payment..." }
}
(PreEscaped(format!("<script>
{logging_template}
bluesnap.threeDsPaymentsSetup(\"{payment_fields_token}\",
function(sdkResponse) {{
// console.log(sdkResponse);
var f = document.createElement('form');
f.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/bluesnap?paymentToken={payment_fields_token}\");
f.method='POST';
var i=document.createElement('input');
i.type='hidden';
i.name='authentication_response';
i.value=JSON.stringify(sdkResponse);
f.appendChild(i);
document.body.appendChild(f);
f.submit();
}});
{card_details}
bluesnap.threeDsPaymentsSubmitData(saveCardDirectly);
</script>
")))
}}
}
RedirectForm::CybersourceAuthSetup {
access_token,
ddc_url,
reference_id,
} => {
maud::html! {
(maud::DOCTYPE)
html {
head {
meta name="viewport" content="width=device-width, initial-scale=1";
}
body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" }
(PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#))
(PreEscaped(r#"
<script>
var anime = bodymovin.loadAnimation({
container: document.getElementById('loader1'),
renderer: 'svg',
loop: true,
autoplay: true,
name: 'hyperswitch loader',
animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]}
})
</script>
"#))
h3 style="text-align: center;" { "Please wait while we process your payment..." }
}
(PreEscaped(r#"<iframe id="cardinal_collection_iframe" name="collectionIframe" height="10" width="10" style="display: none;"></iframe>"#))
(PreEscaped(format!("<form id=\"cardinal_collection_form\" method=\"POST\" target=\"collectionIframe\" action=\"{ddc_url}\">
<input id=\"cardinal_collection_form_input\" type=\"hidden\" name=\"JWT\" value=\"{access_token}\">
</form>")))
(PreEscaped(r#"<script>
window.onload = function() {
var cardinalCollectionForm = document.querySelector('#cardinal_collection_form'); if(cardinalCollectionForm) cardinalCollectionForm.submit();
}
</script>"#))
(PreEscaped(format!("<script>
{logging_template}
window.addEventListener(\"message\", function(event) {{
if (event.origin === \"https://centinelapistag.cardinalcommerce.com\" || event.origin === \"https://centinelapi.cardinalcommerce.com\") {{
window.location.href = window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/cybersource?referenceId={reference_id}\");
}}
}}, false);
</script>
")))
}}
}
RedirectForm::CybersourceConsumerAuth {
access_token,
step_up_url,
} => {
maud::html! {
(maud::DOCTYPE)
html {
head {
meta name="viewport" content="width=device-width, initial-scale=1";
}
body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" }
(PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#))
(PreEscaped(r#"
<script>
var anime = bodymovin.loadAnimation({
container: document.getElementById('loader1'),
renderer: 'svg',
loop: true,
autoplay: true,
name: 'hyperswitch loader',
animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]}
})
</script>
"#))
h3 style="text-align: center;" { "Please wait while we process your payment..." }
}
// This is the iframe recommended by cybersource but the redirection happens inside this iframe once otp
// is received and we lose control of the redirection on user client browser, so to avoid that we have removed this iframe and directly consumed it.
// (PreEscaped(r#"<iframe id="step_up_iframe" style="border: none; margin-left: auto; margin-right: auto; display: block" height="800px" width="400px" name="stepUpIframe"></iframe>"#))
(PreEscaped(format!("<form id=\"step-up-form\" method=\"POST\" action=\"{step_up_url}\">
<input type=\"hidden\" name=\"JWT\" value=\"{access_token}\">
</form>")))
(PreEscaped(format!("<script>
{logging_template}
window.onload = function() {{
var stepUpForm = document.querySelector('#step-up-form'); if(stepUpForm) stepUpForm.submit();
}}
</script>")))
}}
}
RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url, creq } => {
maud::html! {
(maud::DOCTYPE)
html {
head {
meta name="viewport" content="width=device-width, initial-scale=1";
}
body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" }
(PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#))
(PreEscaped(r#"
<script>
var anime = bodymovin.loadAnimation({
container: document.getElementById('loader1'),
renderer: 'svg',
loop: true,
autoplay: true,
name: 'hyperswitch loader',
animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]}
})
</script>
"#))
h3 style="text-align: center;" { "Please wait while we process your payment..." }
}
(PreEscaped(format!("<form id=\"PaReqForm\" method=\"POST\" action=\"{acs_url}\">
<input type=\"hidden\" name=\"creq\" value=\"{creq}\">
</form>")))
(PreEscaped(format!("<script>
{logging_template}
window.onload = function() {{
var paReqForm = document.querySelector('#PaReqForm'); if(paReqForm) paReqForm.submit();
}}
</script>")))
}
}
}
RedirectForm::Payme => {
maud::html! {
(maud::DOCTYPE)
head {
(PreEscaped(r#"<script src="https://cdn.paymeservice.com/hf/v1/hostedfields.js"></script>"#))
}
(PreEscaped(format!("<script>
{logging_template}
var f = document.createElement('form');
f.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/payme\");
f.method='POST';
PayMe.clientData()
.then((data) => {{
var i=document.createElement('input');
i.type='hidden';
i.name='meta_data';
i.value=data.hash;
f.appendChild(i);
document.body.appendChild(f);
f.submit();
}})
.catch((error) => {{
f.submit();
}});
</script>
")))
}
}
RedirectForm::Braintree {
client_token,
card_token,
bin,
acs_url,
} => {
maud::html! {
(maud::DOCTYPE)
html {
head {
meta name="viewport" content="width=device-width, initial-scale=1";
(PreEscaped(r#"<script src="https://js.braintreegateway.com/web/3.97.1/js/three-d-secure.js"></script>"#))
// (PreEscaped(r#"<script src="https://js.braintreegateway.com/web/3.97.1/js/hosted-fields.js"></script>"#))
}
body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" }
(PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#))
(PreEscaped(r#"
<script>
var anime = bodymovin.loadAnimation({
container: document.getElementById('loader1'),
renderer: 'svg',
loop: true,
autoplay: true,
name: 'hyperswitch loader',
animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]}
})
</script>
"#))
h3 style="text-align: center;" { "Please wait while we process your payment..." }
}
(PreEscaped(format!("<script>
{logging_template}
var my3DSContainer;
var clientToken = \"{client_token}\";
braintree.threeDSecure.create({{
authorization: clientToken,
version: 2
}}, function(err, threeDs) {{
threeDs.verifyCard({{
amount: \"{amount}\",
nonce: \"{card_token}\",
bin: \"{bin}\",
addFrame: function(err, iframe) {{
my3DSContainer = document.createElement('div');
my3DSContainer.appendChild(iframe);
document.body.appendChild(my3DSContainer);
}},
removeFrame: function() {{
if(my3DSContainer && my3DSContainer.parentNode) {{
my3DSContainer.parentNode.removeChild(my3DSContainer);
}}
}},
onLookupComplete: function(data, next) {{
// console.log(\"onLookup Complete\", data);
next();
}}
}},
function(err, payload) {{
if(err) {{
console.error(err);
var f = document.createElement('form');
f.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/response/braintree\");
var i = document.createElement('input');
i.type = 'hidden';
f.method='POST';
i.name = 'authentication_response';
i.value = JSON.stringify(err);
f.appendChild(i);
f.body = JSON.stringify(err);
document.body.appendChild(f);
f.submit();
}} else {{
// console.log(payload);
var f = document.createElement('form');
f.action=\"{acs_url}\";
var i = document.createElement('input');
i.type = 'hidden';
f.method='POST';
i.name = 'authentication_response';
i.value = JSON.stringify(payload);
f.appendChild(i);
f.body = JSON.stringify(payload);
document.body.appendChild(f);
f.submit();
}}
}});
}}); </script>"
)))
}}
}
RedirectForm::Nmi {
amount,
currency,
public_key,
customer_vault_id,
order_id,
} => {
let public_key_val = public_key.peek();
maud::html! {
(maud::DOCTYPE)
head {
(PreEscaped(r#"<script src="https://secure.networkmerchants.com/js/v1/Gateway.js"></script>"#))
}
body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader-wrapper" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" }
(PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#))
(PreEscaped(r#"
<script>
var anime = bodymovin.loadAnimation({
container: document.getElementById('loader1'),
renderer: 'svg',
loop: true,
autoplay: true,
name: 'hyperswitch loader',
animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]}
})
</script>
"#))
h3 style="text-align: center;" { "Please wait while we process your payment..." }
}
div id="threeds-wrapper" style="display: flex; width: 100%; height: 100vh; align-items: center; justify-content: center;" {""}
}
(PreEscaped(format!("<script>
{logging_template}
const gateway = Gateway.create('{public_key_val}');
// Initialize the ThreeDSService
const threeDS = gateway.get3DSecure();
const options = {{
customerVaultId: '{customer_vault_id}',
currency: '{currency}',
amount: '{amount}'
}};
const threeDSsecureInterface = threeDS.createUI(options);
threeDSsecureInterface.on('challenge', function(e) {{
document.getElementById('loader-wrapper').style.display = 'none';
}});
threeDSsecureInterface.on('complete', function(e) {{
var responseForm = document.createElement('form');
responseForm.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/nmi\");
responseForm.method='POST';
var item1=document.createElement('input');
item1.type='hidden';
item1.name='cavv';
item1.value=e.cavv;
responseForm.appendChild(item1);
var item2=document.createElement('input');
item2.type='hidden';
item2.name='xid';
item2.value=e.xid;
responseForm.appendChild(item2);
var item6=document.createElement('input');
item6.type='hidden';
item6.name='eci';
item6.value=e.eci;
responseForm.appendChild(item6);
var item7=document.createElement('input');
item7.type='hidden';
item7.name='directoryServerId';
item7.value=e.directoryServerId;
responseForm.appendChild(item7);
var item3=document.createElement('input');
item3.type='hidden';
item3.name='cardHolderAuth';
item3.value=e.cardHolderAuth;
responseForm.appendChild(item3);
var item4=document.createElement('input');
item4.type='hidden';
item4.name='threeDsVersion';
item4.value=e.threeDsVersion;
responseForm.appendChild(item4);
var item5=document.createElement('input');
item5.type='hidden';
item5.name='orderId';
item5.value='{order_id}';
responseForm.appendChild(item5);
var item6=document.createElement('input');
item6.type='hidden';
item6.name='customerVaultId';
item6.value='{customer_vault_id}';
responseForm.appendChild(item6);
document.body.appendChild(responseForm);
responseForm.submit();
}});
threeDSsecureInterface.on('failure', function(e) {{
var responseForm = document.createElement('form');
responseForm.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/nmi\");
responseForm.method='POST';
var error_code=document.createElement('input');
error_code.type='hidden';
error_code.name='code';
error_code.value= e.code;
responseForm.appendChild(error_code);
var error_message=document.createElement('input');
error_message.type='hidden';
error_message.name='message';
error_message.value= e.message;
responseForm.appendChild(error_message);
document.body.appendChild(responseForm);
responseForm.submit();
}});
threeDSsecureInterface.start('#threeds-wrapper');
</script>"
)))
}
}
RedirectForm::Mifinity {
initialization_token,
} => {
let mifinity_base_url = config.connectors.mifinity.base_url;
maud::html! {
(maud::DOCTYPE)
head {
(PreEscaped(format!(r#"<script src='{mifinity_base_url}widgets/sgpg.js?58190a411dc3'></script>"#)))
}
(PreEscaped(format!("<div id='widget-container'></div>
<script>
var widget = showPaymentIframe('widget-container', {{
token: '{initialization_token}',
complete: function() {{
var f = document.createElement('form');
f.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/response/mifinity\");
f.method='GET';
document.body.appendChild(f);
f.submit();
}}
}});
</script>")))
}
}
RedirectForm::WorldpayDDCForm {
endpoint,
method,
form_fields,
collection_id,
} => maud::html! {
(maud::DOCTYPE)
html {
meta name="viewport" content="width=device-width, initial-scale=1";
head {
(PreEscaped(r##"
<style>
#loader1 {
width: 500px;
}
@media (max-width: 600px) {
#loader1 {
width: 200px;
}
}
</style>
"##))
}
body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-left: auto; margin-right: auto;" { "" }
(PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#))
(PreEscaped(r#"
<script>
var anime = bodymovin.loadAnimation({
container: document.getElementById('loader1'),
renderer: 'svg',
loop: true,
autoplay: true,
name: 'hyperswitch loader',
animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]}
})
</script>
"#))
h3 style="text-align: center;" { "Please wait while we process your payment..." }
script {
(PreEscaped(format!(
r#"
var ddcProcessed = false;
var timeoutHandle = null;
function submitCollectionReference(collectionReference) {{
if (ddcProcessed) {{
console.log("DDC already processed, ignoring duplicate submission");
return;
}}
ddcProcessed = true;
if (timeoutHandle) {{
clearTimeout(timeoutHandle);
timeoutHandle = null;
}}
var redirectPathname = window.location.pathname.replace(/payments\/redirect\/([^\/]+)\/([^\/]+)\/[^\/]+/, "payments/$1/$2/redirect/complete/worldpay");
var redirectUrl = window.location.origin + redirectPathname;
try {{
if (typeof collectionReference === "string" && collectionReference.length > 0) {{
var form = document.createElement("form");
form.action = redirectPathname;
form.method = "GET";
var input = document.createElement("input");
input.type = "hidden";
input.name = "collectionReference";
input.value = collectionReference;
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}} else {{
window.location.replace(redirectUrl);
}}
}} catch (error) {{
console.error("Error submitting DDC:", error);
window.location.replace(redirectUrl);
}}
}}
var allowedHost = "{}";
var collectionField = "{}";
window.addEventListener("message", function(event) {{
if (ddcProcessed) {{
console.log("DDC already processed, ignoring message event");
return;
}}
if (event.origin === allowedHost) {{
try {{
var data = JSON.parse(event.data);
if (collectionField.length > 0) {{
var collectionReference = data[collectionField];
return submitCollectionReference(collectionReference);
}} else {{
console.error("Collection field not found in event data (" + collectionField + ")");
}}
}} catch (error) {{
console.error("Error parsing event data: ", error);
}}
}} else {{
console.error("Invalid origin: " + event.origin, "Expected origin: " + allowedHost);
}}
submitCollectionReference("");
}});
// Timeout after 10 seconds and will submit empty collection reference
timeoutHandle = window.setTimeout(function() {{
if (!ddcProcessed) {{
console.log("DDC timeout reached, submitting empty collection reference");
submitCollectionReference("");
}}
}}, 10000);
"#,
endpoint.host_str().map_or(endpoint.as_ref().split('/').take(3).collect::<Vec<&str>>().join("/"), |host| format!("{}://{}", endpoint.scheme(), host)),
collection_id.clone().unwrap_or("".to_string())))
)
}
iframe
style="display: none;"
srcdoc=(
maud::html! {
(maud::DOCTYPE)
html {
body {
form action=(PreEscaped(endpoint.to_string())) method=(method.to_string()) #payment_form {
@for (field, value) in form_fields {
input type="hidden" name=(field) value=(value);
}
}
(PreEscaped(format!(r#"
<script type="text/javascript"> {logging_template}
var form = document.getElementById("payment_form");
var formFields = form.querySelectorAll("input");
window.setTimeout(function () {{
if (form.method.toUpperCase() === "GET" && formFields.length === 0) {{
window.location.href = form.action;
}} else {{
form.submit();
}}
}}, 300);
</script>
"#)))
}
}
}.into_string()
)
{}
}
}
},
}
}
fn build_payment_link_template(
payment_link_data: PaymentLinkFormData,
) -> CustomResult<(Tera, Context), errors::ApiErrorResponse> {
let mut tera = Tera::default();
// Add modification to css template with dynamic data
let css_template =
include_str!("../core/payment_link/payment_link_initiate/payment_link.css").to_string();
let _ = tera.add_raw_template("payment_link_css", &css_template);
let mut context = Context::new();
context.insert("css_color_scheme", &payment_link_data.css_script);
let rendered_css = match tera.render("payment_link_css", &context) {
Ok(rendered_css) => rendered_css,
Err(tera_error) => {
crate::logger::warn!("{tera_error}");
Err(errors::ApiErrorResponse::InternalServerError)?
}
};
// Add modification to js template with dynamic data
let js_template =
include_str!("../core/payment_link/payment_link_initiate/payment_link.js").to_string();
let _ = tera.add_raw_template("payment_link_js", &js_template);
context.insert("payment_details_js_script", &payment_link_data.js_script);
let sdk_origin = payment_link_data
.sdk_url
.host_str()
.ok_or_else(|| {
logger::error!("Host missing for payment link SDK URL");
report!(errors::ApiErrorResponse::InternalServerError)
})
.and_then(|host| {
if host == "localhost" {
let port = payment_link_data.sdk_url.port().ok_or_else(|| {
logger::error!("Port missing for localhost in SDK URL");
report!(errors::ApiErrorResponse::InternalServerError)
})?;
Ok(format!(
"{}://{}:{}",
payment_link_data.sdk_url.scheme(),
host,
port
))
} else {
Ok(format!("{}://{}", payment_link_data.sdk_url.scheme(), host))
}
})?;
context.insert("sdk_origin", &sdk_origin);
let rendered_js = match tera.render("payment_link_js", &context) {
Ok(rendered_js) => rendered_js,
Err(tera_error) => {
crate::logger::warn!("{tera_error}");
Err(errors::ApiErrorResponse::InternalServerError)?
}
};
// Logging template
let logging_template =
include_str!("redirection/assets/redirect_error_logs_push.js").to_string();
//Locale template
let locale_template = include_str!("../core/payment_link/locale.js").to_string();
// Modify Html template with rendered js and rendered css files
let html_template =
include_str!("../core/payment_link/payment_link_initiate/payment_link.html").to_string();
let _ = tera.add_raw_template("payment_link", &html_template);
context.insert("rendered_meta_tag_html", &payment_link_data.html_meta_tags);
context.insert(
"preload_link_tags",
&get_preload_link_html_template(&payment_link_data.sdk_url),
);
context.insert(
"hyperloader_sdk_link",
&get_hyper_loader_sdk(&payment_link_data.sdk_url),
);
context.insert("locale_template", &locale_template);
context.insert("rendered_css", &rendered_css);
context.insert("rendered_js", &rendered_js);
context.insert("logging_template", &logging_template);
Ok((tera, context))
}
pub fn build_payment_link_html(
payment_link_data: PaymentLinkFormData,
) -> CustomResult<String, errors::ApiErrorResponse> {
let (tera, mut context) = build_payment_link_template(payment_link_data)
.attach_printable("Failed to build payment link's HTML template")?;
let payment_link_initiator =
include_str!("../core/payment_link/payment_link_initiate/payment_link_initiator.js")
.to_string();
context.insert("payment_link_initiator", &payment_link_initiator);
tera.render("payment_link", &context)
.map_err(|tera_error: TeraError| {
crate::logger::warn!("{tera_error}");
report!(errors::ApiErrorResponse::InternalServerError)
})
.attach_printable("Error while rendering open payment link's HTML template")
}
pub fn build_secure_payment_link_html(
payment_link_data: PaymentLinkFormData,
) -> CustomResult<String, errors::ApiErrorResponse> {
let (tera, mut context) = build_payment_link_template(payment_link_data)
.attach_printable("Failed to build payment link's HTML template")?;
let payment_link_initiator =
include_str!("../core/payment_link/payment_link_initiate/secure_payment_link_initiator.js")
.to_string();
context.insert("payment_link_initiator", &payment_link_initiator);
tera.render("payment_link", &context)
.map_err(|tera_error: TeraError| {
crate::logger::warn!("{tera_error}");
report!(errors::ApiErrorResponse::InternalServerError)
})
.attach_printable("Error while rendering secure payment link's HTML template")
}
fn get_hyper_loader_sdk(sdk_url: &url::Url) -> String {
format!("<script src=\"{sdk_url}\" onload=\"initializeSDK()\"></script>")
}
fn get_preload_link_html_template(sdk_url: &url::Url) -> String {
format!(
r#"<link rel="preload" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800" as="style">
<link rel="preload" href="{sdk_url}" as="script">"#,
)
}
pub fn get_payment_link_status(
payment_link_data: PaymentLinkStatusData,
) -> CustomResult<String, errors::ApiErrorResponse> {
let mut tera = Tera::default();
// Add modification to css template with dynamic data
let css_template =
include_str!("../core/payment_link/payment_link_status/status.css").to_string();
let _ = tera.add_raw_template("payment_link_css", &css_template);
let mut context = Context::new();
context.insert("css_color_scheme", &payment_link_data.css_script);
let rendered_css = match tera.render("payment_link_css", &context) {
Ok(rendered_css) => rendered_css,
Err(tera_error) => {
crate::logger::warn!("{tera_error}");
Err(errors::ApiErrorResponse::InternalServerError)?
}
};
//Locale template
let locale_template = include_str!("../core/payment_link/locale.js");
// Logging template
let logging_template =
include_str!("redirection/assets/redirect_error_logs_push.js").to_string();
// Add modification to js template with dynamic data
let js_template =
include_str!("../core/payment_link/payment_link_status/status.js").to_string();
let _ = tera.add_raw_template("payment_link_js", &js_template);
context.insert("payment_details_js_script", &payment_link_data.js_script);
let rendered_js = match tera.render("payment_link_js", &context) {
Ok(rendered_js) => rendered_js,
Err(tera_error) => {
crate::logger::warn!("{tera_error}");
Err(errors::ApiErrorResponse::InternalServerError)?
}
};
// Modify Html template with rendered js and rendered css files
let html_template =
include_str!("../core/payment_link/payment_link_status/status.html").to_string();
let _ = tera.add_raw_template("payment_link_status", &html_template);
context.insert("rendered_css", &rendered_css);
context.insert("locale_template", &locale_template);
context.insert("rendered_js", &rendered_js);
context.insert("logging_template", &logging_template);
match tera.render("payment_link_status", &context) {
Ok(rendered_html) => Ok(rendered_html),
Err(tera_error) => {
crate::logger::warn!("{tera_error}");
Err(errors::ApiErrorResponse::InternalServerError)?
}
}
}
pub fn extract_mapped_fields(
value: &serde_json::Value,
mapping: Option<&HashMap<String, String>>,
existing_enhancement: Option<&serde_json::Value>,
) -> Option<serde_json::Value> {
let mapping = mapping?;
if mapping.is_empty() {
return existing_enhancement.cloned();
}
let mut enhancement = match existing_enhancement {
Some(existing) if existing.is_object() => existing.clone(),
_ => serde_json::json!({}),
};
for (dot_path, output_key) in mapping {
if let Some(extracted_value) = extract_field_by_dot_path(value, dot_path) {
if let Some(obj) = enhancement.as_object_mut() {
obj.insert(output_key.clone(), extracted_value);
}
}
}
if enhancement.as_object().is_some_and(|obj| !obj.is_empty()) {
Some(enhancement)
} else {
None
}
}
pub fn extract_field_by_dot_path(
value: &serde_json::Value,
path: &str,
) -> Option<serde_json::Value> {
let parts: Vec<&str> = path.split('.').collect();
let mut current = value;
for part in parts {
match current {
serde_json::Value::Object(obj) => {
current = obj.get(part)?;
}
serde_json::Value::Array(arr) => {
// Try to parse part as array index
if let Ok(index) = part.parse::<usize>() {
current = arr.get(index)?;
} else {
return None;
}
}
_ => return None,
}
}
Some(current.clone())
}
#[cfg(test)]
mod tests {
#[test]
fn test_mime_essence() {
assert_eq!(mime::APPLICATION_JSON.essence_str(), "application/json");
}
}
| {
"crate": "router",
"file": "crates/router/src/services/api.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-4211416445693437665 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/kafka/refund_event.rs
// Contains: 2 structs, 0 enums
#[cfg(feature = "v2")]
use common_utils::pii;
#[cfg(feature = "v2")]
use common_utils::types::{self, ChargeRefunds};
use common_utils::{
id_type,
types::{ConnectorTransactionIdTrait, MinorUnit},
};
use diesel_models::{enums as storage_enums, refund::Refund};
use time::OffsetDateTime;
use crate::events;
#[cfg(feature = "v1")]
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaRefundEvent<'a> {
pub internal_reference_id: &'a String,
pub refund_id: &'a String, //merchant_reference id
pub payment_id: &'a id_type::PaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub connector_transaction_id: &'a String,
pub connector: &'a String,
pub connector_refund_id: Option<&'a String>,
pub external_reference_id: Option<&'a String>,
pub refund_type: &'a storage_enums::RefundType,
pub total_amount: &'a MinorUnit,
pub currency: &'a storage_enums::Currency,
pub refund_amount: &'a MinorUnit,
pub refund_status: &'a storage_enums::RefundStatus,
pub sent_to_gateway: &'a bool,
pub refund_error_message: Option<&'a String>,
pub refund_arn: Option<&'a String>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
pub description: Option<&'a String>,
pub attempt_id: &'a String,
pub refund_reason: Option<&'a String>,
pub refund_error_code: Option<&'a String>,
pub profile_id: Option<&'a id_type::ProfileId>,
pub organization_id: &'a id_type::OrganizationId,
}
#[cfg(feature = "v1")]
impl<'a> KafkaRefundEvent<'a> {
pub fn from_storage(refund: &'a Refund) -> Self {
Self {
internal_reference_id: &refund.internal_reference_id,
refund_id: &refund.refund_id,
payment_id: &refund.payment_id,
merchant_id: &refund.merchant_id,
connector_transaction_id: refund.get_connector_transaction_id(),
connector: &refund.connector,
connector_refund_id: refund.get_optional_connector_refund_id(),
external_reference_id: refund.external_reference_id.as_ref(),
refund_type: &refund.refund_type,
total_amount: &refund.total_amount,
currency: &refund.currency,
refund_amount: &refund.refund_amount,
refund_status: &refund.refund_status,
sent_to_gateway: &refund.sent_to_gateway,
refund_error_message: refund.refund_error_message.as_ref(),
refund_arn: refund.refund_arn.as_ref(),
created_at: refund.created_at.assume_utc(),
modified_at: refund.modified_at.assume_utc(),
description: refund.description.as_ref(),
attempt_id: &refund.attempt_id,
refund_reason: refund.refund_reason.as_ref(),
refund_error_code: refund.refund_error_code.as_ref(),
profile_id: refund.profile_id.as_ref(),
organization_id: &refund.organization_id,
}
}
}
#[cfg(feature = "v2")]
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaRefundEvent<'a> {
pub refund_id: &'a id_type::GlobalRefundId,
pub merchant_reference_id: &'a id_type::RefundReferenceId,
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub connector_transaction_id: &'a types::ConnectorTransactionId,
pub connector: &'a String,
pub connector_refund_id: Option<&'a types::ConnectorTransactionId>,
pub external_reference_id: Option<&'a String>,
pub refund_type: &'a storage_enums::RefundType,
pub total_amount: &'a MinorUnit,
pub currency: &'a storage_enums::Currency,
pub refund_amount: &'a MinorUnit,
pub refund_status: &'a storage_enums::RefundStatus,
pub sent_to_gateway: &'a bool,
pub refund_error_message: Option<&'a String>,
pub refund_arn: Option<&'a String>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
pub description: Option<&'a String>,
pub attempt_id: &'a id_type::GlobalAttemptId,
pub refund_reason: Option<&'a String>,
pub refund_error_code: Option<&'a String>,
pub profile_id: Option<&'a id_type::ProfileId>,
pub organization_id: &'a id_type::OrganizationId,
pub metadata: Option<&'a pii::SecretSerdeValue>,
pub updated_by: &'a String,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub charges: Option<&'a ChargeRefunds>,
pub connector_refund_data: Option<&'a String>,
pub connector_transaction_data: Option<&'a String>,
pub split_refunds: Option<&'a common_types::refunds::SplitRefund>,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub processor_refund_data: Option<&'a String>,
pub processor_transaction_data: Option<&'a String>,
}
#[cfg(feature = "v2")]
impl<'a> KafkaRefundEvent<'a> {
pub fn from_storage(refund: &'a Refund) -> Self {
let Refund {
payment_id,
merchant_id,
connector_transaction_id,
connector,
connector_refund_id,
external_reference_id,
refund_type,
total_amount,
currency,
refund_amount,
refund_status,
sent_to_gateway,
refund_error_message,
metadata,
refund_arn,
created_at,
modified_at,
description,
attempt_id,
refund_reason,
refund_error_code,
profile_id,
updated_by,
charges,
organization_id,
split_refunds,
unified_code,
unified_message,
processor_refund_data,
processor_transaction_data,
id,
merchant_reference_id,
connector_id,
} = refund;
Self {
refund_id: id,
merchant_reference_id,
payment_id,
merchant_id,
connector_transaction_id,
connector,
connector_refund_id: connector_refund_id.as_ref(),
external_reference_id: external_reference_id.as_ref(),
refund_type,
total_amount,
currency,
refund_amount,
refund_status,
sent_to_gateway,
refund_error_message: refund_error_message.as_ref(),
refund_arn: refund_arn.as_ref(),
created_at: created_at.assume_utc(),
modified_at: modified_at.assume_utc(),
description: description.as_ref(),
attempt_id,
refund_reason: refund_reason.as_ref(),
refund_error_code: refund_error_code.as_ref(),
profile_id: profile_id.as_ref(),
organization_id,
metadata: metadata.as_ref(),
updated_by,
merchant_connector_id: connector_id.as_ref(),
charges: charges.as_ref(),
connector_refund_data: processor_refund_data.as_ref(),
connector_transaction_data: processor_transaction_data.as_ref(),
split_refunds: split_refunds.as_ref(),
unified_code: unified_code.as_ref(),
unified_message: unified_message.as_ref(),
processor_refund_data: processor_refund_data.as_ref(),
processor_transaction_data: processor_transaction_data.as_ref(),
}
}
}
#[cfg(feature = "v1")]
impl super::KafkaMessage for KafkaRefundEvent<'_> {
fn key(&self) -> String {
format!(
"{}_{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id,
self.refund_id
)
}
fn event_type(&self) -> events::EventType {
events::EventType::Refund
}
}
#[cfg(feature = "v2")]
impl super::KafkaMessage for KafkaRefundEvent<'_> {
fn key(&self) -> String {
format!(
"{}_{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id.get_string_repr(),
self.merchant_reference_id.get_string_repr()
)
}
fn event_type(&self) -> events::EventType {
events::EventType::Refund
}
}
| {
"crate": "router",
"file": "crates/router/src/services/kafka/refund_event.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-8342970533531911180 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/kafka/dispute.rs
// Contains: 1 structs, 0 enums
use common_utils::{
ext_traits::StringExt,
id_type,
types::{AmountConvertor, MinorUnit, StringMinorUnitForConnector},
};
use diesel_models::enums as storage_enums;
use masking::Secret;
use time::OffsetDateTime;
use crate::types::storage::dispute::Dispute;
#[derive(serde::Serialize, Debug)]
pub struct KafkaDispute<'a> {
pub dispute_id: &'a String,
pub dispute_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub dispute_stage: &'a storage_enums::DisputeStage,
pub dispute_status: &'a storage_enums::DisputeStatus,
pub payment_id: &'a id_type::PaymentId,
pub attempt_id: &'a String,
pub merchant_id: &'a id_type::MerchantId,
pub connector_status: &'a String,
pub connector_dispute_id: &'a String,
pub connector_reason: Option<&'a String>,
pub connector_reason_code: Option<&'a String>,
#[serde(default, with = "time::serde::timestamp::option")]
pub challenge_required_by: Option<OffsetDateTime>,
#[serde(default, with = "time::serde::timestamp::option")]
pub connector_created_at: Option<OffsetDateTime>,
#[serde(default, with = "time::serde::timestamp::option")]
pub connector_updated_at: Option<OffsetDateTime>,
#[serde(default, with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
pub connector: &'a String,
pub evidence: &'a Secret<serde_json::Value>,
pub profile_id: Option<&'a id_type::ProfileId>,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub organization_id: &'a id_type::OrganizationId,
}
impl<'a> KafkaDispute<'a> {
pub fn from_storage(dispute: &'a Dispute) -> Self {
let currency = dispute.dispute_currency.unwrap_or(
dispute
.currency
.to_uppercase()
.parse_enum("Currency")
.unwrap_or_default(),
);
Self {
dispute_id: &dispute.dispute_id,
dispute_amount: StringMinorUnitForConnector::convert_back(
&StringMinorUnitForConnector,
dispute.amount.clone(),
currency,
)
.unwrap_or_else(|e| {
router_env::logger::error!("Failed to convert dispute amount: {e:?}");
MinorUnit::new(0)
}),
currency,
dispute_stage: &dispute.dispute_stage,
dispute_status: &dispute.dispute_status,
payment_id: &dispute.payment_id,
attempt_id: &dispute.attempt_id,
merchant_id: &dispute.merchant_id,
connector_status: &dispute.connector_status,
connector_dispute_id: &dispute.connector_dispute_id,
connector_reason: dispute.connector_reason.as_ref(),
connector_reason_code: dispute.connector_reason_code.as_ref(),
challenge_required_by: dispute.challenge_required_by.map(|i| i.assume_utc()),
connector_created_at: dispute.connector_created_at.map(|i| i.assume_utc()),
connector_updated_at: dispute.connector_updated_at.map(|i| i.assume_utc()),
created_at: dispute.created_at.assume_utc(),
modified_at: dispute.modified_at.assume_utc(),
connector: &dispute.connector,
evidence: &dispute.evidence,
profile_id: dispute.profile_id.as_ref(),
merchant_connector_id: dispute.merchant_connector_id.as_ref(),
organization_id: &dispute.organization_id,
}
}
}
impl super::KafkaMessage for KafkaDispute<'_> {
fn key(&self) -> String {
format!(
"{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.dispute_id
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::Dispute
}
}
| {
"crate": "router",
"file": "crates/router/src/services/kafka/dispute.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_8324576313141032013 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/kafka/payment_attempt.rs
// Contains: 2 structs, 0 enums
#[cfg(feature = "v2")]
use common_types::payments;
#[cfg(feature = "v2")]
use common_utils::types;
use common_utils::{id_type, types::MinorUnit};
use diesel_models::enums as storage_enums;
#[cfg(feature = "v2")]
use diesel_models::payment_attempt;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{
address, payments::payment_attempt::PaymentAttemptFeatureMetadata,
router_response_types::RedirectForm,
};
use hyperswitch_domain_models::{
mandates::MandateDetails, payments::payment_attempt::PaymentAttempt,
};
use time::OffsetDateTime;
#[cfg(feature = "v1")]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentAttempt<'a> {
pub payment_id: &'a id_type::PaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub attempt_id: &'a String,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub save_to_locker: Option<bool>,
pub connector: Option<&'a String>,
pub error_message: Option<&'a String>,
pub offer_amount: Option<MinorUnit>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_amount: Option<MinorUnit>,
pub payment_method_id: Option<&'a String>,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub connector_transaction_id: Option<&'a String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
#[serde(default, with = "time::serde::timestamp::option")]
pub capture_on: Option<OffsetDateTime>,
pub confirm: bool,
pub authentication_type: Option<storage_enums::AuthenticationType>,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::option")]
pub last_synced: Option<OffsetDateTime>,
pub cancellation_reason: Option<&'a String>,
pub amount_to_capture: Option<MinorUnit>,
pub mandate_id: Option<&'a String>,
pub browser_info: Option<String>,
pub error_code: Option<&'a String>,
pub connector_metadata: Option<String>,
// TODO: These types should implement copy ideally
pub payment_experience: Option<&'a storage_enums::PaymentExperience>,
pub payment_method_type: Option<&'a storage_enums::PaymentMethodType>,
pub payment_method_data: Option<String>,
pub error_reason: Option<&'a String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub net_amount: MinorUnit,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub mandate_data: Option<&'a MandateDetails>,
pub client_source: Option<&'a String>,
pub client_version: Option<&'a String>,
pub profile_id: &'a id_type::ProfileId,
pub organization_id: &'a id_type::OrganizationId,
pub card_network: Option<String>,
pub card_discovery: Option<String>,
pub routing_approach: Option<storage_enums::RoutingApproach>,
pub debit_routing_savings: Option<MinorUnit>,
pub signature_network: Option<common_enums::CardNetwork>,
pub is_issuer_regulated: Option<bool>,
}
#[cfg(feature = "v1")]
impl<'a> KafkaPaymentAttempt<'a> {
pub fn from_storage(attempt: &'a PaymentAttempt) -> Self {
let card_payment_method_data = attempt
.get_payment_method_data()
.and_then(|data| data.get_additional_card_info());
Self {
payment_id: &attempt.payment_id,
merchant_id: &attempt.merchant_id,
attempt_id: &attempt.attempt_id,
status: attempt.status,
amount: attempt.net_amount.get_order_amount(),
currency: attempt.currency,
save_to_locker: attempt.save_to_locker,
connector: attempt.connector.as_ref(),
error_message: attempt.error_message.as_ref(),
offer_amount: attempt.offer_amount,
surcharge_amount: attempt.net_amount.get_surcharge_amount(),
tax_amount: attempt.net_amount.get_tax_on_surcharge(),
payment_method_id: attempt.payment_method_id.as_ref(),
payment_method: attempt.payment_method,
connector_transaction_id: attempt.connector_transaction_id.as_ref(),
capture_method: attempt.capture_method,
capture_on: attempt.capture_on.map(|i| i.assume_utc()),
confirm: attempt.confirm,
authentication_type: attempt.authentication_type,
created_at: attempt.created_at.assume_utc(),
modified_at: attempt.modified_at.assume_utc(),
last_synced: attempt.last_synced.map(|i| i.assume_utc()),
cancellation_reason: attempt.cancellation_reason.as_ref(),
amount_to_capture: attempt.amount_to_capture,
mandate_id: attempt.mandate_id.as_ref(),
browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()),
error_code: attempt.error_code.as_ref(),
connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()),
payment_experience: attempt.payment_experience.as_ref(),
payment_method_type: attempt.payment_method_type.as_ref(),
payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()),
error_reason: attempt.error_reason.as_ref(),
multiple_capture_count: attempt.multiple_capture_count,
amount_capturable: attempt.amount_capturable,
merchant_connector_id: attempt.merchant_connector_id.as_ref(),
net_amount: attempt.net_amount.get_total_amount(),
unified_code: attempt.unified_code.as_ref(),
unified_message: attempt.unified_message.as_ref(),
mandate_data: attempt.mandate_data.as_ref(),
client_source: attempt.client_source.as_ref(),
client_version: attempt.client_version.as_ref(),
profile_id: &attempt.profile_id,
organization_id: &attempt.organization_id,
card_network: attempt
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|pm| pm.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
card_discovery: attempt
.card_discovery
.map(|discovery| discovery.to_string()),
routing_approach: attempt.routing_approach.clone(),
debit_routing_savings: attempt.debit_routing_savings,
signature_network: card_payment_method_data
.as_ref()
.and_then(|data| data.signature_network.clone()),
is_issuer_regulated: card_payment_method_data.and_then(|data| data.is_regulated),
}
}
}
#[cfg(feature = "v2")]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentAttempt<'a> {
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub attempt_id: &'a id_type::GlobalAttemptId,
pub attempts_group_id: Option<&'a String>,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
pub connector: Option<&'a String>,
pub error_message: Option<&'a String>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_amount: Option<MinorUnit>,
pub payment_method_id: Option<&'a id_type::GlobalPaymentMethodId>,
pub payment_method: storage_enums::PaymentMethod,
pub connector_transaction_id: Option<&'a String>,
pub authentication_type: storage_enums::AuthenticationType,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::option")]
pub last_synced: Option<OffsetDateTime>,
pub cancellation_reason: Option<&'a String>,
pub amount_to_capture: Option<MinorUnit>,
pub browser_info: Option<&'a types::BrowserInformation>,
pub error_code: Option<&'a String>,
pub connector_metadata: Option<String>,
// TODO: These types should implement copy ideally
pub payment_experience: Option<&'a storage_enums::PaymentExperience>,
pub payment_method_type: &'a storage_enums::PaymentMethodType,
pub payment_method_data: Option<String>,
pub error_reason: Option<&'a String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub net_amount: MinorUnit,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub client_source: Option<&'a String>,
pub client_version: Option<&'a String>,
pub profile_id: &'a id_type::ProfileId,
pub organization_id: &'a id_type::OrganizationId,
pub card_network: Option<String>,
pub card_discovery: Option<String>,
pub connector_payment_id: Option<types::ConnectorTransactionId>,
pub payment_token: Option<String>,
pub preprocessing_step_id: Option<String>,
pub connector_response_reference_id: Option<String>,
pub updated_by: &'a String,
pub encoded_data: Option<&'a masking::Secret<String>>,
pub external_three_ds_authentication_attempted: Option<bool>,
pub authentication_connector: Option<String>,
pub authentication_id: Option<String>,
pub fingerprint_id: Option<String>,
pub customer_acceptance: Option<&'a masking::Secret<payments::CustomerAcceptance>>,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
pub charges: Option<payments::ConnectorChargeResponseData>,
pub processor_merchant_id: &'a id_type::MerchantId,
pub created_by: Option<&'a types::CreatedBy>,
pub payment_method_type_v2: storage_enums::PaymentMethod,
pub payment_method_subtype: storage_enums::PaymentMethodType,
pub routing_result: Option<serde_json::Value>,
pub authentication_applied: Option<common_enums::AuthenticationType>,
pub external_reference_id: Option<String>,
pub tax_on_surcharge: Option<MinorUnit>,
pub payment_method_billing_address: Option<masking::Secret<&'a address::Address>>, // adjusted from Encryption
pub redirection_data: Option<&'a RedirectForm>,
pub connector_payment_data: Option<String>,
pub connector_token_details: Option<&'a payment_attempt::ConnectorTokenDetails>,
pub feature_metadata: Option<&'a PaymentAttemptFeatureMetadata>,
pub network_advice_code: Option<String>,
pub network_decline_code: Option<String>,
pub network_error_message: Option<String>,
pub connector_request_reference_id: Option<String>,
}
#[cfg(feature = "v2")]
impl<'a> KafkaPaymentAttempt<'a> {
pub fn from_storage(attempt: &'a PaymentAttempt) -> Self {
use masking::PeekInterface;
let PaymentAttempt {
payment_id,
merchant_id,
attempts_group_id,
amount_details,
status,
connector,
error,
authentication_type,
created_at,
modified_at,
last_synced,
cancellation_reason,
browser_info,
payment_token,
connector_metadata,
payment_experience,
payment_method_data,
routing_result,
preprocessing_step_id,
multiple_capture_count,
connector_response_reference_id,
updated_by,
redirection_data,
encoded_data,
merchant_connector_id,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
fingerprint_id,
client_source,
client_version,
customer_acceptance,
profile_id,
organization_id,
payment_method_type,
payment_method_id,
connector_payment_id,
payment_method_subtype,
authentication_applied,
external_reference_id,
payment_method_billing_address,
id,
connector_token_details,
card_discovery,
charges,
feature_metadata,
processor_merchant_id,
created_by,
connector_request_reference_id,
network_transaction_id: _,
authorized_amount: _,
} = attempt;
let (connector_payment_id, connector_payment_data) = connector_payment_id
.clone()
.map(types::ConnectorTransactionId::form_id_and_data)
.map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
.unwrap_or((None, None));
Self {
payment_id,
merchant_id,
attempt_id: id,
attempts_group_id: attempts_group_id.as_ref(),
status: *status,
amount: amount_details.get_net_amount(),
connector: connector.as_ref(),
error_message: error.as_ref().map(|error_details| &error_details.message),
surcharge_amount: amount_details.get_surcharge_amount(),
tax_amount: amount_details.get_tax_on_surcharge(),
payment_method_id: payment_method_id.as_ref(),
payment_method: *payment_method_type,
connector_transaction_id: connector_response_reference_id.as_ref(),
authentication_type: *authentication_type,
created_at: created_at.assume_utc(),
modified_at: modified_at.assume_utc(),
last_synced: last_synced.map(|i| i.assume_utc()),
cancellation_reason: cancellation_reason.as_ref(),
amount_to_capture: amount_details.get_amount_to_capture(),
browser_info: browser_info.as_ref(),
error_code: error.as_ref().map(|error_details| &error_details.code),
connector_metadata: connector_metadata.as_ref().map(|v| v.peek().to_string()),
payment_experience: payment_experience.as_ref(),
payment_method_type: payment_method_subtype,
payment_method_data: payment_method_data.as_ref().map(|v| v.peek().to_string()),
error_reason: error
.as_ref()
.and_then(|error_details| error_details.reason.as_ref()),
multiple_capture_count: *multiple_capture_count,
amount_capturable: amount_details.get_amount_capturable(),
merchant_connector_id: merchant_connector_id.as_ref(),
net_amount: amount_details.get_net_amount(),
unified_code: error
.as_ref()
.and_then(|error_details| error_details.unified_code.as_ref()),
unified_message: error
.as_ref()
.and_then(|error_details| error_details.unified_message.as_ref()),
client_source: client_source.as_ref(),
client_version: client_version.as_ref(),
profile_id,
organization_id,
card_network: payment_method_data
.as_ref()
.map(|data| data.peek())
.and_then(|data| data.as_object())
.and_then(|pm| pm.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
card_discovery: card_discovery.map(|discovery| discovery.to_string()),
payment_token: payment_token.clone(),
preprocessing_step_id: preprocessing_step_id.clone(),
connector_response_reference_id: connector_response_reference_id.clone(),
updated_by,
encoded_data: encoded_data.as_ref(),
external_three_ds_authentication_attempted: *external_three_ds_authentication_attempted,
authentication_connector: authentication_connector.clone(),
authentication_id: authentication_id
.as_ref()
.map(|id| id.get_string_repr().to_string().clone()),
fingerprint_id: fingerprint_id.clone(),
customer_acceptance: customer_acceptance.as_ref(),
shipping_cost: amount_details.get_shipping_cost(),
order_tax_amount: amount_details.get_order_tax_amount(),
charges: charges.clone(),
processor_merchant_id,
created_by: created_by.as_ref(),
payment_method_type_v2: *payment_method_type,
connector_payment_id: connector_payment_id.as_ref().cloned(),
payment_method_subtype: *payment_method_subtype,
routing_result: routing_result.clone(),
authentication_applied: *authentication_applied,
external_reference_id: external_reference_id.clone(),
tax_on_surcharge: amount_details.get_tax_on_surcharge(),
payment_method_billing_address: payment_method_billing_address
.as_ref()
.map(|v| masking::Secret::new(v.get_inner())),
redirection_data: redirection_data.as_ref(),
connector_payment_data,
connector_token_details: connector_token_details.as_ref(),
feature_metadata: feature_metadata.as_ref(),
network_advice_code: error
.as_ref()
.and_then(|details| details.network_advice_code.clone()),
network_decline_code: error
.as_ref()
.and_then(|details| details.network_decline_code.clone()),
network_error_message: error
.as_ref()
.and_then(|details| details.network_error_message.clone()),
connector_request_reference_id: connector_request_reference_id.clone(),
}
}
}
impl super::KafkaMessage for KafkaPaymentAttempt<'_> {
#[cfg(feature = "v1")]
fn key(&self) -> String {
format!(
"{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id
)
}
#[cfg(feature = "v2")]
fn key(&self) -> String {
format!(
"{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id.get_string_repr()
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::PaymentAttempt
}
}
| {
"crate": "router",
"file": "crates/router/src/services/kafka/payment_attempt.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_5415808523269420265 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/kafka/payout.rs
// Contains: 1 structs, 0 enums
use common_utils::{id_type, pii, types::MinorUnit};
use diesel_models::enums as storage_enums;
use hyperswitch_domain_models::payouts::{payout_attempt::PayoutAttempt, payouts::Payouts};
use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaPayout<'a> {
pub payout_id: &'a id_type::PayoutId,
pub payout_attempt_id: &'a String,
pub merchant_id: &'a id_type::MerchantId,
pub customer_id: Option<&'a id_type::CustomerId>,
pub address_id: Option<&'a String>,
pub profile_id: &'a id_type::ProfileId,
pub payout_method_id: Option<&'a String>,
pub payout_type: Option<storage_enums::PayoutType>,
pub amount: MinorUnit,
pub destination_currency: storage_enums::Currency,
pub source_currency: storage_enums::Currency,
pub description: Option<&'a String>,
pub recurring: bool,
pub auto_fulfill: bool,
pub return_url: Option<&'a String>,
pub entity_type: storage_enums::PayoutEntityType,
pub metadata: Option<pii::SecretSerdeValue>,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp")]
pub last_modified_at: OffsetDateTime,
pub attempt_count: i16,
pub status: storage_enums::PayoutStatus,
pub priority: Option<storage_enums::PayoutSendPriority>,
pub connector: Option<&'a String>,
pub connector_payout_id: Option<&'a String>,
pub is_eligible: Option<bool>,
pub error_message: Option<&'a String>,
pub error_code: Option<&'a String>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<&'a String>,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
}
impl<'a> KafkaPayout<'a> {
pub fn from_storage(payouts: &'a Payouts, payout_attempt: &'a PayoutAttempt) -> Self {
Self {
payout_id: &payouts.payout_id,
payout_attempt_id: &payout_attempt.payout_attempt_id,
merchant_id: &payouts.merchant_id,
customer_id: payouts.customer_id.as_ref(),
address_id: payouts.address_id.as_ref(),
profile_id: &payouts.profile_id,
payout_method_id: payouts.payout_method_id.as_ref(),
payout_type: payouts.payout_type,
amount: payouts.amount,
destination_currency: payouts.destination_currency,
source_currency: payouts.source_currency,
description: payouts.description.as_ref(),
recurring: payouts.recurring,
auto_fulfill: payouts.auto_fulfill,
return_url: payouts.return_url.as_ref(),
entity_type: payouts.entity_type,
metadata: payouts.metadata.clone(),
created_at: payouts.created_at.assume_utc(),
last_modified_at: payouts.last_modified_at.assume_utc(),
attempt_count: payouts.attempt_count,
status: payouts.status,
priority: payouts.priority,
connector: payout_attempt.connector.as_ref(),
connector_payout_id: payout_attempt.connector_payout_id.as_ref(),
is_eligible: payout_attempt.is_eligible,
error_message: payout_attempt.error_message.as_ref(),
error_code: payout_attempt.error_code.as_ref(),
business_country: payout_attempt.business_country,
business_label: payout_attempt.business_label.as_ref(),
merchant_connector_id: payout_attempt.merchant_connector_id.as_ref(),
}
}
}
impl super::KafkaMessage for KafkaPayout<'_> {
fn key(&self) -> String {
format!(
"{}_{}",
self.merchant_id.get_string_repr(),
self.payout_attempt_id
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::Payout
}
}
| {
"crate": "router",
"file": "crates/router/src/services/kafka/payout.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_779772150007080220 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/kafka/fraud_check.rs
// Contains: 1 structs, 0 enums
// use diesel_models::enums as storage_enums;
use diesel_models::{
enums as storage_enums,
enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType},
fraud_check::FraudCheck,
};
use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaFraudCheck<'a> {
pub frm_id: &'a String,
pub payment_id: &'a common_utils::id_type::PaymentId,
pub merchant_id: &'a common_utils::id_type::MerchantId,
pub attempt_id: &'a String,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
pub frm_name: &'a String,
pub frm_transaction_id: Option<&'a String>,
pub frm_transaction_type: FraudCheckType,
pub frm_status: FraudCheckStatus,
pub frm_score: Option<i32>,
pub frm_reason: Option<serde_json::Value>,
pub frm_error: Option<&'a String>,
pub payment_details: Option<serde_json::Value>,
pub metadata: Option<serde_json::Value>,
#[serde(with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
pub last_step: FraudCheckLastStep,
pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision.
}
impl<'a> KafkaFraudCheck<'a> {
pub fn from_storage(check: &'a FraudCheck) -> Self {
Self {
frm_id: &check.frm_id,
payment_id: &check.payment_id,
merchant_id: &check.merchant_id,
attempt_id: &check.attempt_id,
created_at: check.created_at.assume_utc(),
frm_name: &check.frm_name,
frm_transaction_id: check.frm_transaction_id.as_ref(),
frm_transaction_type: check.frm_transaction_type,
frm_status: check.frm_status,
frm_score: check.frm_score,
frm_reason: check.frm_reason.clone(),
frm_error: check.frm_error.as_ref(),
payment_details: check.payment_details.clone(),
metadata: check.metadata.clone(),
modified_at: check.modified_at.assume_utc(),
last_step: check.last_step,
payment_capture_method: check.payment_capture_method,
}
}
}
impl super::KafkaMessage for KafkaFraudCheck<'_> {
fn key(&self) -> String {
format!(
"{}_{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id,
self.frm_id
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::FraudCheck
}
}
| {
"crate": "router",
"file": "crates/router/src/services/kafka/fraud_check.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-1812961755580081967 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/kafka/dispute_event.rs
// Contains: 1 structs, 0 enums
use common_utils::{
ext_traits::StringExt,
types::{AmountConvertor, MinorUnit, StringMinorUnitForConnector},
};
use diesel_models::enums as storage_enums;
use masking::Secret;
use time::OffsetDateTime;
use crate::types::storage::dispute::Dispute;
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaDisputeEvent<'a> {
pub dispute_id: &'a String,
pub dispute_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub dispute_stage: &'a storage_enums::DisputeStage,
pub dispute_status: &'a storage_enums::DisputeStatus,
pub payment_id: &'a common_utils::id_type::PaymentId,
pub attempt_id: &'a String,
pub merchant_id: &'a common_utils::id_type::MerchantId,
pub connector_status: &'a String,
pub connector_dispute_id: &'a String,
pub connector_reason: Option<&'a String>,
pub connector_reason_code: Option<&'a String>,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub challenge_required_by: Option<OffsetDateTime>,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub connector_created_at: Option<OffsetDateTime>,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub connector_updated_at: Option<OffsetDateTime>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
pub connector: &'a String,
pub evidence: &'a Secret<serde_json::Value>,
pub profile_id: Option<&'a common_utils::id_type::ProfileId>,
pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>,
pub organization_id: &'a common_utils::id_type::OrganizationId,
}
impl<'a> KafkaDisputeEvent<'a> {
pub fn from_storage(dispute: &'a Dispute) -> Self {
let currency = dispute.dispute_currency.unwrap_or(
dispute
.currency
.to_uppercase()
.parse_enum("Currency")
.unwrap_or_default(),
);
Self {
dispute_id: &dispute.dispute_id,
dispute_amount: StringMinorUnitForConnector::convert_back(
&StringMinorUnitForConnector,
dispute.amount.clone(),
currency,
)
.unwrap_or_else(|e| {
router_env::logger::error!("Failed to convert dispute amount: {e:?}");
MinorUnit::new(0)
}),
currency,
dispute_stage: &dispute.dispute_stage,
dispute_status: &dispute.dispute_status,
payment_id: &dispute.payment_id,
attempt_id: &dispute.attempt_id,
merchant_id: &dispute.merchant_id,
connector_status: &dispute.connector_status,
connector_dispute_id: &dispute.connector_dispute_id,
connector_reason: dispute.connector_reason.as_ref(),
connector_reason_code: dispute.connector_reason_code.as_ref(),
challenge_required_by: dispute.challenge_required_by.map(|i| i.assume_utc()),
connector_created_at: dispute.connector_created_at.map(|i| i.assume_utc()),
connector_updated_at: dispute.connector_updated_at.map(|i| i.assume_utc()),
created_at: dispute.created_at.assume_utc(),
modified_at: dispute.modified_at.assume_utc(),
connector: &dispute.connector,
evidence: &dispute.evidence,
profile_id: dispute.profile_id.as_ref(),
merchant_connector_id: dispute.merchant_connector_id.as_ref(),
organization_id: &dispute.organization_id,
}
}
}
impl super::KafkaMessage for KafkaDisputeEvent<'_> {
fn key(&self) -> String {
format!(
"{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.dispute_id
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::Dispute
}
}
| {
"crate": "router",
"file": "crates/router/src/services/kafka/dispute_event.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_200333574140026705 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/kafka/payment_attempt_event.rs
// Contains: 2 structs, 0 enums
#[cfg(feature = "v2")]
use common_types::payments;
#[cfg(feature = "v2")]
use common_utils::types;
use common_utils::{id_type, types::MinorUnit};
use diesel_models::enums as storage_enums;
#[cfg(feature = "v2")]
use diesel_models::payment_attempt;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{
address, payments::payment_attempt::PaymentAttemptFeatureMetadata,
router_response_types::RedirectForm,
};
use hyperswitch_domain_models::{
mandates::MandateDetails, payments::payment_attempt::PaymentAttempt,
};
use time::OffsetDateTime;
#[cfg(feature = "v1")]
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentAttemptEvent<'a> {
pub payment_id: &'a id_type::PaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub attempt_id: &'a String,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub save_to_locker: Option<bool>,
pub connector: Option<&'a String>,
pub error_message: Option<&'a String>,
pub offer_amount: Option<MinorUnit>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_amount: Option<MinorUnit>,
pub payment_method_id: Option<&'a String>,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub connector_transaction_id: Option<&'a String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub capture_on: Option<OffsetDateTime>,
pub confirm: bool,
pub authentication_type: Option<storage_enums::AuthenticationType>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub last_synced: Option<OffsetDateTime>,
pub cancellation_reason: Option<&'a String>,
pub amount_to_capture: Option<MinorUnit>,
pub mandate_id: Option<&'a String>,
pub browser_info: Option<String>,
pub error_code: Option<&'a String>,
pub connector_metadata: Option<String>,
// TODO: These types should implement copy ideally
pub payment_experience: Option<&'a storage_enums::PaymentExperience>,
pub payment_method_type: Option<&'a storage_enums::PaymentMethodType>,
pub payment_method_data: Option<String>,
pub error_reason: Option<&'a String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub net_amount: MinorUnit,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub mandate_data: Option<&'a MandateDetails>,
pub client_source: Option<&'a String>,
pub client_version: Option<&'a String>,
pub profile_id: &'a id_type::ProfileId,
pub organization_id: &'a id_type::OrganizationId,
pub card_network: Option<String>,
pub card_discovery: Option<String>,
pub routing_approach: Option<storage_enums::RoutingApproach>,
pub debit_routing_savings: Option<MinorUnit>,
pub signature_network: Option<common_enums::CardNetwork>,
pub is_issuer_regulated: Option<bool>,
}
#[cfg(feature = "v1")]
impl<'a> KafkaPaymentAttemptEvent<'a> {
pub fn from_storage(attempt: &'a PaymentAttempt) -> Self {
let card_payment_method_data = attempt
.get_payment_method_data()
.and_then(|data| data.get_additional_card_info());
Self {
payment_id: &attempt.payment_id,
merchant_id: &attempt.merchant_id,
attempt_id: &attempt.attempt_id,
status: attempt.status,
amount: attempt.net_amount.get_order_amount(),
currency: attempt.currency,
save_to_locker: attempt.save_to_locker,
connector: attempt.connector.as_ref(),
error_message: attempt.error_message.as_ref(),
offer_amount: attempt.offer_amount,
surcharge_amount: attempt.net_amount.get_surcharge_amount(),
tax_amount: attempt.net_amount.get_tax_on_surcharge(),
payment_method_id: attempt.payment_method_id.as_ref(),
payment_method: attempt.payment_method,
connector_transaction_id: attempt.connector_transaction_id.as_ref(),
capture_method: attempt.capture_method,
capture_on: attempt.capture_on.map(|i| i.assume_utc()),
confirm: attempt.confirm,
authentication_type: attempt.authentication_type,
created_at: attempt.created_at.assume_utc(),
modified_at: attempt.modified_at.assume_utc(),
last_synced: attempt.last_synced.map(|i| i.assume_utc()),
cancellation_reason: attempt.cancellation_reason.as_ref(),
amount_to_capture: attempt.amount_to_capture,
mandate_id: attempt.mandate_id.as_ref(),
browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()),
error_code: attempt.error_code.as_ref(),
connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()),
payment_experience: attempt.payment_experience.as_ref(),
payment_method_type: attempt.payment_method_type.as_ref(),
payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()),
error_reason: attempt.error_reason.as_ref(),
multiple_capture_count: attempt.multiple_capture_count,
amount_capturable: attempt.amount_capturable,
merchant_connector_id: attempt.merchant_connector_id.as_ref(),
net_amount: attempt.net_amount.get_total_amount(),
unified_code: attempt.unified_code.as_ref(),
unified_message: attempt.unified_message.as_ref(),
mandate_data: attempt.mandate_data.as_ref(),
client_source: attempt.client_source.as_ref(),
client_version: attempt.client_version.as_ref(),
profile_id: &attempt.profile_id,
organization_id: &attempt.organization_id,
card_network: attempt
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|pm| pm.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
card_discovery: attempt
.card_discovery
.map(|discovery| discovery.to_string()),
routing_approach: attempt.routing_approach.clone(),
debit_routing_savings: attempt.debit_routing_savings,
signature_network: card_payment_method_data
.as_ref()
.and_then(|data| data.signature_network.clone()),
is_issuer_regulated: card_payment_method_data.and_then(|data| data.is_regulated),
}
}
}
#[cfg(feature = "v2")]
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentAttemptEvent<'a> {
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub attempt_id: &'a id_type::GlobalAttemptId,
pub attempts_group_id: Option<&'a String>,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
pub connector: Option<&'a String>,
pub error_message: Option<&'a String>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_amount: Option<MinorUnit>,
pub payment_method_id: Option<&'a id_type::GlobalPaymentMethodId>,
pub payment_method: storage_enums::PaymentMethod,
pub connector_transaction_id: Option<&'a String>,
pub authentication_type: storage_enums::AuthenticationType,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub last_synced: Option<OffsetDateTime>,
pub cancellation_reason: Option<&'a String>,
pub amount_to_capture: Option<MinorUnit>,
pub browser_info: Option<&'a types::BrowserInformation>,
pub error_code: Option<&'a String>,
pub connector_metadata: Option<String>,
// TODO: These types should implement copy ideally
pub payment_experience: Option<&'a storage_enums::PaymentExperience>,
pub payment_method_type: &'a storage_enums::PaymentMethodType,
pub payment_method_data: Option<String>,
pub error_reason: Option<&'a String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub net_amount: MinorUnit,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub client_source: Option<&'a String>,
pub client_version: Option<&'a String>,
pub profile_id: &'a id_type::ProfileId,
pub organization_id: &'a id_type::OrganizationId,
pub card_network: Option<String>,
pub card_discovery: Option<String>,
pub connector_payment_id: Option<types::ConnectorTransactionId>,
pub payment_token: Option<String>,
pub preprocessing_step_id: Option<String>,
pub connector_response_reference_id: Option<String>,
pub updated_by: &'a String,
pub encoded_data: Option<&'a masking::Secret<String>>,
pub external_three_ds_authentication_attempted: Option<bool>,
pub authentication_connector: Option<String>,
pub authentication_id: Option<String>,
pub fingerprint_id: Option<String>,
pub customer_acceptance: Option<&'a masking::Secret<payments::CustomerAcceptance>>,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
pub charges: Option<payments::ConnectorChargeResponseData>,
pub processor_merchant_id: &'a id_type::MerchantId,
pub created_by: Option<&'a types::CreatedBy>,
pub payment_method_type_v2: storage_enums::PaymentMethod,
pub payment_method_subtype: storage_enums::PaymentMethodType,
pub routing_result: Option<serde_json::Value>,
pub authentication_applied: Option<common_enums::AuthenticationType>,
pub external_reference_id: Option<String>,
pub tax_on_surcharge: Option<MinorUnit>,
pub payment_method_billing_address: Option<masking::Secret<&'a address::Address>>, // adjusted from Encryption
pub redirection_data: Option<&'a RedirectForm>,
pub connector_payment_data: Option<String>,
pub connector_token_details: Option<&'a payment_attempt::ConnectorTokenDetails>,
pub feature_metadata: Option<&'a PaymentAttemptFeatureMetadata>,
pub network_advice_code: Option<String>,
pub network_decline_code: Option<String>,
pub network_error_message: Option<String>,
pub connector_request_reference_id: Option<String>,
}
#[cfg(feature = "v2")]
impl<'a> KafkaPaymentAttemptEvent<'a> {
pub fn from_storage(attempt: &'a PaymentAttempt) -> Self {
use masking::PeekInterface;
let PaymentAttempt {
payment_id,
merchant_id,
attempts_group_id,
amount_details,
status,
connector,
error,
authentication_type,
created_at,
modified_at,
last_synced,
cancellation_reason,
browser_info,
payment_token,
connector_metadata,
payment_experience,
payment_method_data,
routing_result,
preprocessing_step_id,
multiple_capture_count,
connector_response_reference_id,
updated_by,
redirection_data,
encoded_data,
merchant_connector_id,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
fingerprint_id,
client_source,
client_version,
customer_acceptance,
profile_id,
organization_id,
payment_method_type,
payment_method_id,
connector_payment_id,
payment_method_subtype,
authentication_applied,
external_reference_id,
payment_method_billing_address,
id,
connector_token_details,
card_discovery,
charges,
feature_metadata,
processor_merchant_id,
created_by,
connector_request_reference_id,
network_transaction_id: _,
authorized_amount: _,
} = attempt;
let (connector_payment_id, connector_payment_data) = connector_payment_id
.clone()
.map(types::ConnectorTransactionId::form_id_and_data)
.map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
.unwrap_or((None, None));
Self {
payment_id,
merchant_id,
attempt_id: id,
attempts_group_id: attempts_group_id.as_ref(),
status: *status,
amount: amount_details.get_net_amount(),
connector: connector.as_ref(),
error_message: error.as_ref().map(|error_details| &error_details.message),
surcharge_amount: amount_details.get_surcharge_amount(),
tax_amount: amount_details.get_tax_on_surcharge(),
payment_method_id: payment_method_id.as_ref(),
payment_method: *payment_method_type,
connector_transaction_id: connector_response_reference_id.as_ref(),
authentication_type: *authentication_type,
created_at: created_at.assume_utc(),
modified_at: modified_at.assume_utc(),
last_synced: last_synced.map(|i| i.assume_utc()),
cancellation_reason: cancellation_reason.as_ref(),
amount_to_capture: amount_details.get_amount_to_capture(),
browser_info: browser_info.as_ref(),
error_code: error.as_ref().map(|error_details| &error_details.code),
connector_metadata: connector_metadata.as_ref().map(|v| v.peek().to_string()),
payment_experience: payment_experience.as_ref(),
payment_method_type: payment_method_subtype,
payment_method_data: payment_method_data.as_ref().map(|v| v.peek().to_string()),
error_reason: error
.as_ref()
.and_then(|error_details| error_details.reason.as_ref()),
multiple_capture_count: *multiple_capture_count,
amount_capturable: amount_details.get_amount_capturable(),
merchant_connector_id: merchant_connector_id.as_ref(),
net_amount: amount_details.get_net_amount(),
unified_code: error
.as_ref()
.and_then(|error_details| error_details.unified_code.as_ref()),
unified_message: error
.as_ref()
.and_then(|error_details| error_details.unified_message.as_ref()),
client_source: client_source.as_ref(),
client_version: client_version.as_ref(),
profile_id,
organization_id,
card_network: payment_method_data
.as_ref()
.map(|data| data.peek())
.and_then(|data| data.as_object())
.and_then(|pm| pm.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
card_discovery: card_discovery.map(|discovery| discovery.to_string()),
payment_token: payment_token.clone(),
preprocessing_step_id: preprocessing_step_id.clone(),
connector_response_reference_id: connector_response_reference_id.clone(),
updated_by,
encoded_data: encoded_data.as_ref(),
external_three_ds_authentication_attempted: *external_three_ds_authentication_attempted,
authentication_connector: authentication_connector.clone(),
authentication_id: authentication_id
.as_ref()
.map(|id| id.get_string_repr().to_string()),
fingerprint_id: fingerprint_id.clone(),
customer_acceptance: customer_acceptance.as_ref(),
shipping_cost: amount_details.get_shipping_cost(),
order_tax_amount: amount_details.get_order_tax_amount(),
charges: charges.clone(),
processor_merchant_id,
created_by: created_by.as_ref(),
payment_method_type_v2: *payment_method_type,
connector_payment_id: connector_payment_id.as_ref().cloned(),
payment_method_subtype: *payment_method_subtype,
routing_result: routing_result.clone(),
authentication_applied: *authentication_applied,
external_reference_id: external_reference_id.clone(),
tax_on_surcharge: amount_details.get_tax_on_surcharge(),
payment_method_billing_address: payment_method_billing_address
.as_ref()
.map(|v| masking::Secret::new(v.get_inner())),
redirection_data: redirection_data.as_ref(),
connector_payment_data,
connector_token_details: connector_token_details.as_ref(),
feature_metadata: feature_metadata.as_ref(),
network_advice_code: error
.as_ref()
.and_then(|details| details.network_advice_code.clone()),
network_decline_code: error
.as_ref()
.and_then(|details| details.network_decline_code.clone()),
network_error_message: error
.as_ref()
.and_then(|details| details.network_error_message.clone()),
connector_request_reference_id: connector_request_reference_id.clone(),
}
}
}
impl super::KafkaMessage for KafkaPaymentAttemptEvent<'_> {
#[cfg(feature = "v1")]
fn key(&self) -> String {
format!(
"{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id
)
}
#[cfg(feature = "v2")]
fn key(&self) -> String {
format!(
"{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id.get_string_repr()
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::PaymentAttempt
}
}
| {
"crate": "router",
"file": "crates/router/src/services/kafka/payment_attempt_event.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-3792786360726140089 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/kafka/fraud_check_event.rs
// Contains: 1 structs, 0 enums
use diesel_models::{
enums as storage_enums,
enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType},
fraud_check::FraudCheck,
};
use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaFraudCheckEvent<'a> {
pub frm_id: &'a String,
pub payment_id: &'a common_utils::id_type::PaymentId,
pub merchant_id: &'a common_utils::id_type::MerchantId,
pub attempt_id: &'a String,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
pub frm_name: &'a String,
pub frm_transaction_id: Option<&'a String>,
pub frm_transaction_type: FraudCheckType,
pub frm_status: FraudCheckStatus,
pub frm_score: Option<i32>,
pub frm_reason: Option<serde_json::Value>,
pub frm_error: Option<&'a String>,
pub payment_details: Option<serde_json::Value>,
pub metadata: Option<serde_json::Value>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
pub last_step: FraudCheckLastStep,
pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision.
}
impl<'a> KafkaFraudCheckEvent<'a> {
pub fn from_storage(check: &'a FraudCheck) -> Self {
Self {
frm_id: &check.frm_id,
payment_id: &check.payment_id,
merchant_id: &check.merchant_id,
attempt_id: &check.attempt_id,
created_at: check.created_at.assume_utc(),
frm_name: &check.frm_name,
frm_transaction_id: check.frm_transaction_id.as_ref(),
frm_transaction_type: check.frm_transaction_type,
frm_status: check.frm_status,
frm_score: check.frm_score,
frm_reason: check.frm_reason.clone(),
frm_error: check.frm_error.as_ref(),
payment_details: check.payment_details.clone(),
metadata: check.metadata.clone(),
modified_at: check.modified_at.assume_utc(),
last_step: check.last_step,
payment_capture_method: check.payment_capture_method,
}
}
}
impl super::KafkaMessage for KafkaFraudCheckEvent<'_> {
fn key(&self) -> String {
format!(
"{}_{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id,
self.frm_id
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::FraudCheck
}
}
| {
"crate": "router",
"file": "crates/router/src/services/kafka/fraud_check_event.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-1124335932061678546 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/kafka/refund.rs
// Contains: 2 structs, 0 enums
#[cfg(feature = "v2")]
use common_utils::pii;
#[cfg(feature = "v2")]
use common_utils::types::{self, ChargeRefunds};
use common_utils::{
id_type,
types::{ConnectorTransactionIdTrait, MinorUnit},
};
use diesel_models::{enums as storage_enums, refund::Refund};
use time::OffsetDateTime;
use crate::events;
#[cfg(feature = "v1")]
#[derive(serde::Serialize, Debug)]
pub struct KafkaRefund<'a> {
pub internal_reference_id: &'a String,
pub refund_id: &'a String, //merchant_reference id
pub payment_id: &'a id_type::PaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub connector_transaction_id: &'a String,
pub connector: &'a String,
pub connector_refund_id: Option<&'a String>,
pub external_reference_id: Option<&'a String>,
pub refund_type: &'a storage_enums::RefundType,
pub total_amount: &'a MinorUnit,
pub currency: &'a storage_enums::Currency,
pub refund_amount: &'a MinorUnit,
pub refund_status: &'a storage_enums::RefundStatus,
pub sent_to_gateway: &'a bool,
pub refund_error_message: Option<&'a String>,
pub refund_arn: Option<&'a String>,
#[serde(default, with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
pub description: Option<&'a String>,
pub attempt_id: &'a String,
pub refund_reason: Option<&'a String>,
pub refund_error_code: Option<&'a String>,
pub profile_id: Option<&'a id_type::ProfileId>,
pub organization_id: &'a id_type::OrganizationId,
}
#[cfg(feature = "v1")]
impl<'a> KafkaRefund<'a> {
pub fn from_storage(refund: &'a Refund) -> Self {
Self {
internal_reference_id: &refund.internal_reference_id,
refund_id: &refund.refund_id,
payment_id: &refund.payment_id,
merchant_id: &refund.merchant_id,
connector_transaction_id: refund.get_connector_transaction_id(),
connector: &refund.connector,
connector_refund_id: refund.get_optional_connector_refund_id(),
external_reference_id: refund.external_reference_id.as_ref(),
refund_type: &refund.refund_type,
total_amount: &refund.total_amount,
currency: &refund.currency,
refund_amount: &refund.refund_amount,
refund_status: &refund.refund_status,
sent_to_gateway: &refund.sent_to_gateway,
refund_error_message: refund.refund_error_message.as_ref(),
refund_arn: refund.refund_arn.as_ref(),
created_at: refund.created_at.assume_utc(),
modified_at: refund.modified_at.assume_utc(),
description: refund.description.as_ref(),
attempt_id: &refund.attempt_id,
refund_reason: refund.refund_reason.as_ref(),
refund_error_code: refund.refund_error_code.as_ref(),
profile_id: refund.profile_id.as_ref(),
organization_id: &refund.organization_id,
}
}
}
#[cfg(feature = "v2")]
#[derive(serde::Serialize, Debug)]
pub struct KafkaRefund<'a> {
pub refund_id: &'a id_type::GlobalRefundId,
pub merchant_reference_id: &'a id_type::RefundReferenceId,
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub connector_transaction_id: &'a types::ConnectorTransactionId,
pub connector: &'a String,
pub connector_refund_id: Option<&'a types::ConnectorTransactionId>,
pub external_reference_id: Option<&'a String>,
pub refund_type: &'a storage_enums::RefundType,
pub total_amount: &'a MinorUnit,
pub currency: &'a storage_enums::Currency,
pub refund_amount: &'a MinorUnit,
pub refund_status: &'a storage_enums::RefundStatus,
pub sent_to_gateway: &'a bool,
pub refund_error_message: Option<&'a String>,
pub refund_arn: Option<&'a String>,
#[serde(default, with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
pub description: Option<&'a String>,
pub attempt_id: &'a id_type::GlobalAttemptId,
pub refund_reason: Option<&'a String>,
pub refund_error_code: Option<&'a String>,
pub profile_id: Option<&'a id_type::ProfileId>,
pub organization_id: &'a id_type::OrganizationId,
pub metadata: Option<&'a pii::SecretSerdeValue>,
pub updated_by: &'a String,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub charges: Option<&'a ChargeRefunds>,
pub connector_refund_data: Option<&'a String>,
pub connector_transaction_data: Option<&'a String>,
pub split_refunds: Option<&'a common_types::refunds::SplitRefund>,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub processor_refund_data: Option<&'a String>,
pub processor_transaction_data: Option<&'a String>,
}
#[cfg(feature = "v2")]
impl<'a> KafkaRefund<'a> {
pub fn from_storage(refund: &'a Refund) -> Self {
let Refund {
payment_id,
merchant_id,
connector_transaction_id,
connector,
connector_refund_id,
external_reference_id,
refund_type,
total_amount,
currency,
refund_amount,
refund_status,
sent_to_gateway,
refund_error_message,
metadata,
refund_arn,
created_at,
modified_at,
description,
attempt_id,
refund_reason,
refund_error_code,
profile_id,
updated_by,
charges,
organization_id,
split_refunds,
unified_code,
unified_message,
processor_refund_data,
processor_transaction_data,
id,
merchant_reference_id,
connector_id,
} = refund;
Self {
refund_id: id,
merchant_reference_id,
payment_id,
merchant_id,
connector_transaction_id,
connector,
connector_refund_id: connector_refund_id.as_ref(),
external_reference_id: external_reference_id.as_ref(),
refund_type,
total_amount,
currency,
refund_amount,
refund_status,
sent_to_gateway,
refund_error_message: refund_error_message.as_ref(),
refund_arn: refund_arn.as_ref(),
created_at: created_at.assume_utc(),
modified_at: modified_at.assume_utc(),
description: description.as_ref(),
attempt_id,
refund_reason: refund_reason.as_ref(),
refund_error_code: refund_error_code.as_ref(),
profile_id: profile_id.as_ref(),
organization_id,
metadata: metadata.as_ref(),
updated_by,
merchant_connector_id: connector_id.as_ref(),
charges: charges.as_ref(),
connector_refund_data: processor_refund_data.as_ref(),
connector_transaction_data: processor_transaction_data.as_ref(),
split_refunds: split_refunds.as_ref(),
unified_code: unified_code.as_ref(),
unified_message: unified_message.as_ref(),
processor_refund_data: processor_refund_data.as_ref(),
processor_transaction_data: processor_transaction_data.as_ref(),
}
}
}
impl super::KafkaMessage for KafkaRefund<'_> {
#[cfg(feature = "v1")]
fn key(&self) -> String {
format!(
"{}_{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id,
self.refund_id
)
}
#[cfg(feature = "v2")]
fn key(&self) -> String {
format!(
"{}_{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id.get_string_repr(),
self.merchant_reference_id.get_string_repr()
)
}
fn event_type(&self) -> events::EventType {
events::EventType::Refund
}
}
| {
"crate": "router",
"file": "crates/router/src/services/kafka/refund.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-6970706245117211211 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/kafka/payment_intent_event.rs
// Contains: 2 structs, 0 enums
#[cfg(feature = "v2")]
use ::common_types::{
payments,
primitive_wrappers::{EnablePartialAuthorizationBool, RequestExtendedAuthorizationBool},
};
#[cfg(feature = "v2")]
use common_enums::{self, RequestIncrementalAuthorization};
use common_utils::{
crypto::Encryptable, hashing::HashedString, id_type, pii, types as common_types,
};
use diesel_models::enums as storage_enums;
#[cfg(feature = "v2")]
use diesel_models::{types as diesel_types, PaymentLinkConfigRequestForPayments};
#[cfg(feature = "v2")]
use diesel_models::{types::OrderDetailsWithAmount, TaxDetails};
use hyperswitch_domain_models::payments::PaymentIntent;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{address, routing};
use masking::{PeekInterface, Secret};
use serde_json::Value;
use time::OffsetDateTime;
#[cfg(feature = "v1")]
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentIntentEvent<'a> {
pub payment_id: &'a id_type::PaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: common_types::MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub amount_captured: Option<common_types::MinorUnit>,
pub customer_id: Option<&'a id_type::CustomerId>,
pub description: Option<&'a String>,
pub return_url: Option<&'a String>,
pub metadata: Option<String>,
pub connector_id: Option<&'a String>,
pub statement_descriptor_name: Option<&'a String>,
pub statement_descriptor_suffix: Option<&'a String>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub last_synced: Option<OffsetDateTime>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub off_session: Option<bool>,
pub client_secret: Option<&'a String>,
pub active_attempt_id: String,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<&'a String>,
pub attempt_count: i16,
pub profile_id: Option<&'a id_type::ProfileId>,
pub payment_confirm_source: Option<storage_enums::PaymentSource>,
pub billing_details: Option<Encryptable<Secret<Value>>>,
pub shipping_details: Option<Encryptable<Secret<Value>>>,
pub customer_email: Option<HashedString<pii::EmailStrategy>>,
pub feature_metadata: Option<&'a Value>,
pub merchant_order_reference_id: Option<&'a String>,
pub organization_id: &'a id_type::OrganizationId,
#[serde(flatten)]
pub infra_values: Option<Value>,
}
#[cfg(feature = "v2")]
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentIntentEvent<'a> {
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: common_types::MinorUnit,
pub currency: storage_enums::Currency,
pub amount_captured: Option<common_types::MinorUnit>,
pub customer_id: Option<&'a id_type::GlobalCustomerId>,
pub description: Option<&'a common_types::Description>,
pub return_url: Option<&'a common_types::Url>,
pub metadata: Option<&'a Secret<Value>>,
pub statement_descriptor: Option<&'a common_types::StatementDescriptor>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub last_synced: Option<OffsetDateTime>,
pub setup_future_usage: storage_enums::FutureUsage,
pub off_session: bool,
pub active_attempt_id: Option<&'a id_type::GlobalAttemptId>,
pub active_attempt_id_type: common_enums::ActiveAttemptIDType,
pub active_attempts_group_id: Option<&'a String>,
pub attempt_count: i16,
pub profile_id: &'a id_type::ProfileId,
pub customer_email: Option<HashedString<pii::EmailStrategy>>,
pub feature_metadata: Option<&'a diesel_types::FeatureMetadata>,
pub organization_id: &'a id_type::OrganizationId,
pub order_details: Option<&'a Vec<Secret<OrderDetailsWithAmount>>>,
pub allowed_payment_method_types: Option<&'a Vec<common_enums::PaymentMethodType>>,
pub connector_metadata: Option<&'a api_models::payments::ConnectorMetadata>,
pub payment_link_id: Option<&'a String>,
pub updated_by: &'a String,
pub surcharge_applicable: Option<bool>,
pub request_incremental_authorization: RequestIncrementalAuthorization,
pub split_txns_enabled: common_enums::SplitTxnsEnabled,
pub authorization_count: Option<i32>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub session_expiry: OffsetDateTime,
pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest,
pub frm_metadata: Option<Secret<&'a Value>>,
pub customer_details: Option<Secret<&'a Value>>,
pub shipping_cost: Option<common_types::MinorUnit>,
pub tax_details: Option<TaxDetails>,
pub skip_external_tax_calculation: bool,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>,
pub split_payments: Option<&'a payments::SplitPaymentsRequest>,
pub platform_merchant_id: Option<&'a id_type::MerchantId>,
pub force_3ds_challenge: Option<bool>,
pub force_3ds_challenge_trigger: Option<bool>,
pub processor_merchant_id: &'a id_type::MerchantId,
pub created_by: Option<&'a common_types::CreatedBy>,
pub is_iframe_redirection_enabled: Option<bool>,
pub merchant_reference_id: Option<&'a id_type::PaymentReferenceId>,
pub capture_method: storage_enums::CaptureMethod,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub prerouting_algorithm: Option<&'a routing::PaymentRoutingInfo>,
pub surcharge_amount: Option<common_types::MinorUnit>,
pub billing_address: Option<Secret<&'a address::Address>>,
pub shipping_address: Option<Secret<&'a address::Address>>,
pub tax_on_surcharge: Option<common_types::MinorUnit>,
pub frm_merchant_decision: Option<common_enums::MerchantDecision>,
pub enable_payment_link: common_enums::EnablePaymentLinkRequest,
pub apply_mit_exemption: common_enums::MitExemptionRequest,
pub customer_present: common_enums::PresenceOfCustomerDuringPayment,
pub routing_algorithm_id: Option<&'a id_type::RoutingId>,
pub payment_link_config: Option<&'a PaymentLinkConfigRequestForPayments>,
pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>,
#[serde(flatten)]
infra_values: Option<Value>,
}
impl KafkaPaymentIntentEvent<'_> {
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &id_type::PaymentId {
self.payment_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &id_type::GlobalPaymentId {
self.payment_id
}
}
#[cfg(feature = "v1")]
impl<'a> KafkaPaymentIntentEvent<'a> {
pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self {
Self {
payment_id: &intent.payment_id,
merchant_id: &intent.merchant_id,
status: intent.status,
amount: intent.amount,
currency: intent.currency,
amount_captured: intent.amount_captured,
customer_id: intent.customer_id.as_ref(),
description: intent.description.as_ref(),
return_url: intent.return_url.as_ref(),
metadata: intent.metadata.as_ref().map(|x| x.to_string()),
connector_id: intent.connector_id.as_ref(),
statement_descriptor_name: intent.statement_descriptor_name.as_ref(),
statement_descriptor_suffix: intent.statement_descriptor_suffix.as_ref(),
created_at: intent.created_at.assume_utc(),
modified_at: intent.modified_at.assume_utc(),
last_synced: intent.last_synced.map(|i| i.assume_utc()),
setup_future_usage: intent.setup_future_usage,
off_session: intent.off_session,
client_secret: intent.client_secret.as_ref(),
active_attempt_id: intent.active_attempt.get_id(),
business_country: intent.business_country,
business_label: intent.business_label.as_ref(),
attempt_count: intent.attempt_count,
profile_id: intent.profile_id.as_ref(),
payment_confirm_source: intent.payment_confirm_source,
// TODO: use typed information here to avoid PII logging
billing_details: None,
shipping_details: None,
customer_email: intent
.customer_details
.as_ref()
.and_then(|value| value.get_inner().peek().as_object())
.and_then(|obj| obj.get("email"))
.and_then(|email| email.as_str())
.map(|email| HashedString::from(Secret::new(email.to_string()))),
feature_metadata: intent.feature_metadata.as_ref(),
merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(),
organization_id: &intent.organization_id,
infra_values: infra_values.clone(),
}
}
}
#[cfg(feature = "v2")]
impl<'a> KafkaPaymentIntentEvent<'a> {
pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self {
let PaymentIntent {
id,
merchant_id,
status,
amount_details,
amount_captured,
customer_id,
description,
return_url,
metadata,
statement_descriptor,
created_at,
modified_at,
last_synced,
setup_future_usage,
active_attempt_id,
active_attempt_id_type,
active_attempts_group_id,
order_details,
allowed_payment_method_types,
connector_metadata,
feature_metadata,
attempt_count,
profile_id,
payment_link_id,
frm_merchant_decision,
updated_by,
request_incremental_authorization,
split_txns_enabled,
authorization_count,
session_expiry,
request_external_three_ds_authentication,
frm_metadata,
customer_details,
merchant_reference_id,
billing_address,
shipping_address,
capture_method,
authentication_type,
prerouting_algorithm,
organization_id,
enable_payment_link,
apply_mit_exemption,
customer_present,
payment_link_config,
routing_algorithm_id,
split_payments,
force_3ds_challenge,
force_3ds_challenge_trigger,
processor_merchant_id,
created_by,
is_iframe_redirection_enabled,
is_payment_id_from_merchant,
enable_partial_authorization,
} = intent;
Self {
payment_id: id,
merchant_id,
status: *status,
amount: amount_details.order_amount,
currency: amount_details.currency,
amount_captured: *amount_captured,
customer_id: customer_id.as_ref(),
description: description.as_ref(),
return_url: return_url.as_ref(),
metadata: metadata.as_ref(),
statement_descriptor: statement_descriptor.as_ref(),
created_at: created_at.assume_utc(),
modified_at: modified_at.assume_utc(),
last_synced: last_synced.map(|t| t.assume_utc()),
setup_future_usage: *setup_future_usage,
off_session: setup_future_usage.is_off_session(),
active_attempt_id: active_attempt_id.as_ref(),
active_attempt_id_type: *active_attempt_id_type,
active_attempts_group_id: active_attempts_group_id.as_ref(),
attempt_count: *attempt_count,
profile_id,
customer_email: None,
feature_metadata: feature_metadata.as_ref(),
organization_id,
order_details: order_details.as_ref(),
allowed_payment_method_types: allowed_payment_method_types.as_ref(),
connector_metadata: connector_metadata.as_ref(),
payment_link_id: payment_link_id.as_ref(),
updated_by,
surcharge_applicable: None,
request_incremental_authorization: *request_incremental_authorization,
split_txns_enabled: *split_txns_enabled,
authorization_count: *authorization_count,
session_expiry: session_expiry.assume_utc(),
request_external_three_ds_authentication: *request_external_three_ds_authentication,
frm_metadata: frm_metadata
.as_ref()
.map(|frm_metadata| frm_metadata.as_ref()),
customer_details: customer_details
.as_ref()
.map(|customer_details| customer_details.get_inner().as_ref()),
shipping_cost: amount_details.shipping_cost,
tax_details: amount_details.tax_details.clone(),
skip_external_tax_calculation: amount_details.get_external_tax_action_as_bool(),
request_extended_authorization: None,
psd2_sca_exemption_type: None,
split_payments: split_payments.as_ref(),
platform_merchant_id: None,
force_3ds_challenge: *force_3ds_challenge,
force_3ds_challenge_trigger: *force_3ds_challenge_trigger,
processor_merchant_id,
created_by: created_by.as_ref(),
is_iframe_redirection_enabled: *is_iframe_redirection_enabled,
merchant_reference_id: merchant_reference_id.as_ref(),
billing_address: billing_address
.as_ref()
.map(|billing_address| Secret::new(billing_address.get_inner())),
shipping_address: shipping_address
.as_ref()
.map(|shipping_address| Secret::new(shipping_address.get_inner())),
capture_method: *capture_method,
authentication_type: *authentication_type,
prerouting_algorithm: prerouting_algorithm.as_ref(),
surcharge_amount: amount_details.surcharge_amount,
tax_on_surcharge: amount_details.tax_on_surcharge,
frm_merchant_decision: *frm_merchant_decision,
enable_payment_link: *enable_payment_link,
apply_mit_exemption: *apply_mit_exemption,
customer_present: *customer_present,
routing_algorithm_id: routing_algorithm_id.as_ref(),
payment_link_config: payment_link_config.as_ref(),
infra_values,
enable_partial_authorization: *enable_partial_authorization,
}
}
}
impl super::KafkaMessage for KafkaPaymentIntentEvent<'_> {
fn key(&self) -> String {
format!(
"{}_{}",
self.merchant_id.get_string_repr(),
self.get_id().get_string_repr(),
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::PaymentIntent
}
}
| {
"crate": "router",
"file": "crates/router/src/services/kafka/payment_intent_event.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_2563048064206131822 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/kafka/authentication_event.rs
// Contains: 1 structs, 0 enums
use diesel_models::{authentication::Authentication, enums as storage_enums};
use time::OffsetDateTime;
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaAuthenticationEvent<'a> {
pub authentication_id: &'a common_utils::id_type::AuthenticationId,
pub merchant_id: &'a common_utils::id_type::MerchantId,
pub authentication_connector: Option<&'a String>,
pub connector_authentication_id: Option<&'a String>,
pub authentication_data: Option<serde_json::Value>,
pub payment_method_id: &'a String,
pub authentication_type: Option<storage_enums::DecoupledAuthenticationType>,
pub authentication_status: storage_enums::AuthenticationStatus,
pub authentication_lifecycle_status: storage_enums::AuthenticationLifecycleStatus,
#[serde(default, with = "time::serde::timestamp::milliseconds")]
pub created_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::milliseconds")]
pub modified_at: OffsetDateTime,
pub error_message: Option<&'a String>,
pub error_code: Option<&'a String>,
pub connector_metadata: Option<serde_json::Value>,
pub maximum_supported_version: Option<common_utils::types::SemanticVersion>,
pub threeds_server_transaction_id: Option<&'a String>,
pub cavv: Option<&'a String>,
pub authentication_flow_type: Option<&'a String>,
pub message_version: Option<common_utils::types::SemanticVersion>,
pub eci: Option<&'a String>,
pub trans_status: Option<storage_enums::TransactionStatus>,
pub acquirer_bin: Option<&'a String>,
pub acquirer_merchant_id: Option<&'a String>,
pub three_ds_method_data: Option<&'a String>,
pub three_ds_method_url: Option<&'a String>,
pub acs_url: Option<&'a String>,
pub challenge_request: Option<&'a String>,
pub acs_reference_number: Option<&'a String>,
pub acs_trans_id: Option<&'a String>,
pub acs_signed_content: Option<&'a String>,
pub profile_id: &'a common_utils::id_type::ProfileId,
pub payment_id: Option<&'a common_utils::id_type::PaymentId>,
pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>,
pub ds_trans_id: Option<&'a String>,
pub directory_server_id: Option<&'a String>,
pub acquirer_country_code: Option<&'a String>,
pub organization_id: &'a common_utils::id_type::OrganizationId,
}
impl<'a> KafkaAuthenticationEvent<'a> {
pub fn from_storage(authentication: &'a Authentication) -> Self {
Self {
created_at: authentication.created_at.assume_utc(),
modified_at: authentication.modified_at.assume_utc(),
authentication_id: &authentication.authentication_id,
merchant_id: &authentication.merchant_id,
authentication_status: authentication.authentication_status,
authentication_connector: authentication.authentication_connector.as_ref(),
connector_authentication_id: authentication.connector_authentication_id.as_ref(),
authentication_data: authentication.authentication_data.clone(),
payment_method_id: &authentication.payment_method_id,
authentication_type: authentication.authentication_type,
authentication_lifecycle_status: authentication.authentication_lifecycle_status,
error_code: authentication.error_code.as_ref(),
error_message: authentication.error_message.as_ref(),
connector_metadata: authentication.connector_metadata.clone(),
maximum_supported_version: authentication.maximum_supported_version.clone(),
threeds_server_transaction_id: authentication.threeds_server_transaction_id.as_ref(),
cavv: authentication.cavv.as_ref(),
authentication_flow_type: authentication.authentication_flow_type.as_ref(),
message_version: authentication.message_version.clone(),
eci: authentication.eci.as_ref(),
trans_status: authentication.trans_status.clone(),
acquirer_bin: authentication.acquirer_bin.as_ref(),
acquirer_merchant_id: authentication.acquirer_merchant_id.as_ref(),
three_ds_method_data: authentication.three_ds_method_data.as_ref(),
three_ds_method_url: authentication.three_ds_method_url.as_ref(),
acs_url: authentication.acs_url.as_ref(),
challenge_request: authentication.challenge_request.as_ref(),
acs_reference_number: authentication.acs_reference_number.as_ref(),
acs_trans_id: authentication.acs_trans_id.as_ref(),
acs_signed_content: authentication.acs_signed_content.as_ref(),
profile_id: &authentication.profile_id,
payment_id: authentication.payment_id.as_ref(),
merchant_connector_id: authentication.merchant_connector_id.as_ref(),
ds_trans_id: authentication.ds_trans_id.as_ref(),
directory_server_id: authentication.directory_server_id.as_ref(),
acquirer_country_code: authentication.acquirer_country_code.as_ref(),
organization_id: &authentication.organization_id,
}
}
}
impl super::KafkaMessage for KafkaAuthenticationEvent<'_> {
fn key(&self) -> String {
format!(
"{}_{}",
self.merchant_id.get_string_repr(),
self.authentication_id.get_string_repr()
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::Authentication
}
}
| {
"crate": "router",
"file": "crates/router/src/services/kafka/authentication_event.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-6092176921926458044 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/kafka/revenue_recovery.rs
// Contains: 1 structs, 0 enums
use common_utils::{id_type, types::MinorUnit};
use masking::Secret;
use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct RevenueRecovery<'a> {
pub merchant_id: &'a id_type::MerchantId,
pub invoice_amount: MinorUnit,
pub invoice_currency: &'a common_enums::Currency,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub invoice_due_date: Option<OffsetDateTime>,
#[serde(with = "time::serde::timestamp::nanoseconds::option")]
pub invoice_date: Option<OffsetDateTime>,
pub billing_country: Option<&'a common_enums::CountryAlpha2>,
pub billing_state: Option<Secret<String>>,
pub billing_city: Option<Secret<String>>,
pub attempt_amount: MinorUnit,
pub attempt_currency: &'a common_enums::Currency,
pub attempt_status: &'a common_enums::AttemptStatus,
pub pg_error_code: Option<String>,
pub network_advice_code: Option<String>,
pub network_error_code: Option<String>,
pub first_pg_error_code: Option<String>,
pub first_network_advice_code: Option<String>,
pub first_network_error_code: Option<String>,
#[serde(default, with = "time::serde::timestamp::nanoseconds")]
pub attempt_created_at: OffsetDateTime,
pub payment_method_type: Option<&'a common_enums::PaymentMethod>,
pub payment_method_subtype: Option<&'a common_enums::PaymentMethodType>,
pub card_network: Option<&'a common_enums::CardNetwork>,
pub card_issuer: Option<String>,
pub retry_count: Option<i32>,
pub payment_gateway: Option<common_enums::connector_enums::Connector>,
}
impl super::KafkaMessage for RevenueRecovery<'_> {
fn key(&self) -> String {
self.merchant_id.get_string_repr().to_string()
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::RevenueRecovery
}
}
| {
"crate": "router",
"file": "crates/router/src/services/kafka/revenue_recovery.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_3540639119607845716 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/kafka/authentication.rs
// Contains: 1 structs, 0 enums
use diesel_models::{authentication::Authentication, enums as storage_enums};
use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaAuthentication<'a> {
pub authentication_id: &'a common_utils::id_type::AuthenticationId,
pub merchant_id: &'a common_utils::id_type::MerchantId,
pub authentication_connector: Option<&'a String>,
pub connector_authentication_id: Option<&'a String>,
pub authentication_data: Option<serde_json::Value>,
pub payment_method_id: &'a String,
pub authentication_type: Option<storage_enums::DecoupledAuthenticationType>,
pub authentication_status: storage_enums::AuthenticationStatus,
pub authentication_lifecycle_status: storage_enums::AuthenticationLifecycleStatus,
#[serde(default, with = "time::serde::timestamp::milliseconds")]
pub created_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::milliseconds")]
pub modified_at: OffsetDateTime,
pub error_message: Option<&'a String>,
pub error_code: Option<&'a String>,
pub connector_metadata: Option<serde_json::Value>,
pub maximum_supported_version: Option<common_utils::types::SemanticVersion>,
pub threeds_server_transaction_id: Option<&'a String>,
pub cavv: Option<&'a String>,
pub authentication_flow_type: Option<&'a String>,
pub message_version: Option<common_utils::types::SemanticVersion>,
pub eci: Option<&'a String>,
pub trans_status: Option<storage_enums::TransactionStatus>,
pub acquirer_bin: Option<&'a String>,
pub acquirer_merchant_id: Option<&'a String>,
pub three_ds_method_data: Option<&'a String>,
pub three_ds_method_url: Option<&'a String>,
pub acs_url: Option<&'a String>,
pub challenge_request: Option<&'a String>,
pub acs_reference_number: Option<&'a String>,
pub acs_trans_id: Option<&'a String>,
pub acs_signed_content: Option<&'a String>,
pub profile_id: &'a common_utils::id_type::ProfileId,
pub payment_id: Option<&'a common_utils::id_type::PaymentId>,
pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>,
pub ds_trans_id: Option<&'a String>,
pub directory_server_id: Option<&'a String>,
pub acquirer_country_code: Option<&'a String>,
pub organization_id: &'a common_utils::id_type::OrganizationId,
}
impl<'a> KafkaAuthentication<'a> {
pub fn from_storage(authentication: &'a Authentication) -> Self {
Self {
created_at: authentication.created_at.assume_utc(),
modified_at: authentication.modified_at.assume_utc(),
authentication_id: &authentication.authentication_id,
merchant_id: &authentication.merchant_id,
authentication_status: authentication.authentication_status,
authentication_connector: authentication.authentication_connector.as_ref(),
connector_authentication_id: authentication.connector_authentication_id.as_ref(),
authentication_data: authentication.authentication_data.clone(),
payment_method_id: &authentication.payment_method_id,
authentication_type: authentication.authentication_type,
authentication_lifecycle_status: authentication.authentication_lifecycle_status,
error_code: authentication.error_code.as_ref(),
error_message: authentication.error_message.as_ref(),
connector_metadata: authentication.connector_metadata.clone(),
maximum_supported_version: authentication.maximum_supported_version.clone(),
threeds_server_transaction_id: authentication.threeds_server_transaction_id.as_ref(),
cavv: authentication.cavv.as_ref(),
authentication_flow_type: authentication.authentication_flow_type.as_ref(),
message_version: authentication.message_version.clone(),
eci: authentication.eci.as_ref(),
trans_status: authentication.trans_status.clone(),
acquirer_bin: authentication.acquirer_bin.as_ref(),
acquirer_merchant_id: authentication.acquirer_merchant_id.as_ref(),
three_ds_method_data: authentication.three_ds_method_data.as_ref(),
three_ds_method_url: authentication.three_ds_method_url.as_ref(),
acs_url: authentication.acs_url.as_ref(),
challenge_request: authentication.challenge_request.as_ref(),
acs_reference_number: authentication.acs_reference_number.as_ref(),
acs_trans_id: authentication.acs_trans_id.as_ref(),
acs_signed_content: authentication.acs_signed_content.as_ref(),
profile_id: &authentication.profile_id,
payment_id: authentication.payment_id.as_ref(),
merchant_connector_id: authentication.merchant_connector_id.as_ref(),
ds_trans_id: authentication.ds_trans_id.as_ref(),
directory_server_id: authentication.directory_server_id.as_ref(),
acquirer_country_code: authentication.acquirer_country_code.as_ref(),
organization_id: &authentication.organization_id,
}
}
}
impl super::KafkaMessage for KafkaAuthentication<'_> {
fn key(&self) -> String {
format!(
"{}_{}",
self.merchant_id.get_string_repr(),
self.authentication_id.get_string_repr()
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::Authentication
}
}
| {
"crate": "router",
"file": "crates/router/src/services/kafka/authentication.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-8618384601299401733 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/kafka/payment_intent.rs
// Contains: 2 structs, 0 enums
#[cfg(feature = "v2")]
use ::common_types::{
payments,
primitive_wrappers::{EnablePartialAuthorizationBool, RequestExtendedAuthorizationBool},
};
#[cfg(feature = "v2")]
use common_enums;
#[cfg(feature = "v2")]
use common_enums::RequestIncrementalAuthorization;
use common_utils::{
crypto::Encryptable, hashing::HashedString, id_type, pii, types as common_types,
};
use diesel_models::enums as storage_enums;
#[cfg(feature = "v2")]
use diesel_models::{types as diesel_types, PaymentLinkConfigRequestForPayments};
#[cfg(feature = "v2")]
use diesel_models::{types::OrderDetailsWithAmount, TaxDetails};
use hyperswitch_domain_models::payments::PaymentIntent;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{address, routing};
use masking::{PeekInterface, Secret};
use serde_json::Value;
use time::OffsetDateTime;
#[cfg(feature = "v1")]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentIntent<'a> {
pub payment_id: &'a id_type::PaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: common_types::MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub amount_captured: Option<common_types::MinorUnit>,
pub customer_id: Option<&'a id_type::CustomerId>,
pub description: Option<&'a String>,
pub return_url: Option<&'a String>,
pub metadata: Option<String>,
pub connector_id: Option<&'a String>,
pub statement_descriptor_name: Option<&'a String>,
pub statement_descriptor_suffix: Option<&'a String>,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::option")]
pub last_synced: Option<OffsetDateTime>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub off_session: Option<bool>,
pub client_secret: Option<&'a String>,
pub active_attempt_id: String,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<&'a String>,
pub attempt_count: i16,
pub profile_id: Option<&'a id_type::ProfileId>,
pub payment_confirm_source: Option<storage_enums::PaymentSource>,
pub billing_details: Option<Encryptable<Secret<Value>>>,
pub shipping_details: Option<Encryptable<Secret<Value>>>,
pub customer_email: Option<HashedString<pii::EmailStrategy>>,
pub feature_metadata: Option<&'a Value>,
pub merchant_order_reference_id: Option<&'a String>,
pub organization_id: &'a id_type::OrganizationId,
#[serde(flatten)]
infra_values: Option<Value>,
}
#[cfg(feature = "v1")]
impl<'a> KafkaPaymentIntent<'a> {
pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self {
Self {
payment_id: &intent.payment_id,
merchant_id: &intent.merchant_id,
status: intent.status,
amount: intent.amount,
currency: intent.currency,
amount_captured: intent.amount_captured,
customer_id: intent.customer_id.as_ref(),
description: intent.description.as_ref(),
return_url: intent.return_url.as_ref(),
metadata: intent.metadata.as_ref().map(|x| x.to_string()),
connector_id: intent.connector_id.as_ref(),
statement_descriptor_name: intent.statement_descriptor_name.as_ref(),
statement_descriptor_suffix: intent.statement_descriptor_suffix.as_ref(),
created_at: intent.created_at.assume_utc(),
modified_at: intent.modified_at.assume_utc(),
last_synced: intent.last_synced.map(|i| i.assume_utc()),
setup_future_usage: intent.setup_future_usage,
off_session: intent.off_session,
client_secret: intent.client_secret.as_ref(),
active_attempt_id: intent.active_attempt.get_id(),
business_country: intent.business_country,
business_label: intent.business_label.as_ref(),
attempt_count: intent.attempt_count,
profile_id: intent.profile_id.as_ref(),
payment_confirm_source: intent.payment_confirm_source,
// TODO: use typed information here to avoid PII logging
billing_details: None,
shipping_details: None,
customer_email: intent
.customer_details
.as_ref()
.and_then(|value| value.get_inner().peek().as_object())
.and_then(|obj| obj.get("email"))
.and_then(|email| email.as_str())
.map(|email| HashedString::from(Secret::new(email.to_string()))),
feature_metadata: intent.feature_metadata.as_ref(),
merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(),
organization_id: &intent.organization_id,
infra_values,
}
}
}
#[cfg(feature = "v2")]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentIntent<'a> {
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: common_types::MinorUnit,
pub currency: storage_enums::Currency,
pub amount_captured: Option<common_types::MinorUnit>,
pub customer_id: Option<&'a id_type::GlobalCustomerId>,
pub description: Option<&'a common_types::Description>,
pub return_url: Option<&'a common_types::Url>,
pub metadata: Option<&'a Secret<Value>>,
pub statement_descriptor: Option<&'a common_types::StatementDescriptor>,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::option")]
pub last_synced: Option<OffsetDateTime>,
pub setup_future_usage: storage_enums::FutureUsage,
pub off_session: bool,
pub active_attempt_id: Option<&'a id_type::GlobalAttemptId>,
pub active_attempt_id_type: common_enums::ActiveAttemptIDType,
pub active_attempts_group_id: Option<&'a String>,
pub attempt_count: i16,
pub profile_id: &'a id_type::ProfileId,
pub customer_email: Option<HashedString<pii::EmailStrategy>>,
pub feature_metadata: Option<&'a diesel_types::FeatureMetadata>,
pub organization_id: &'a id_type::OrganizationId,
pub order_details: Option<&'a Vec<Secret<OrderDetailsWithAmount>>>,
pub allowed_payment_method_types: Option<&'a Vec<common_enums::PaymentMethodType>>,
pub connector_metadata: Option<&'a api_models::payments::ConnectorMetadata>,
pub payment_link_id: Option<&'a String>,
pub updated_by: &'a String,
pub surcharge_applicable: Option<bool>,
pub request_incremental_authorization: RequestIncrementalAuthorization,
pub split_txns_enabled: common_enums::SplitTxnsEnabled,
pub authorization_count: Option<i32>,
#[serde(with = "time::serde::timestamp")]
pub session_expiry: OffsetDateTime,
pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest,
pub frm_metadata: Option<Secret<&'a Value>>,
pub customer_details: Option<Secret<&'a Value>>,
pub shipping_cost: Option<common_types::MinorUnit>,
pub tax_details: Option<TaxDetails>,
pub skip_external_tax_calculation: bool,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>,
pub split_payments: Option<&'a payments::SplitPaymentsRequest>,
pub platform_merchant_id: Option<&'a id_type::MerchantId>,
pub force_3ds_challenge: Option<bool>,
pub force_3ds_challenge_trigger: Option<bool>,
pub processor_merchant_id: &'a id_type::MerchantId,
pub created_by: Option<&'a common_types::CreatedBy>,
pub is_iframe_redirection_enabled: Option<bool>,
pub merchant_reference_id: Option<&'a id_type::PaymentReferenceId>,
pub capture_method: storage_enums::CaptureMethod,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub prerouting_algorithm: Option<&'a routing::PaymentRoutingInfo>,
pub surcharge_amount: Option<common_types::MinorUnit>,
pub billing_address: Option<Secret<&'a address::Address>>,
pub shipping_address: Option<Secret<&'a address::Address>>,
pub tax_on_surcharge: Option<common_types::MinorUnit>,
pub frm_merchant_decision: Option<common_enums::MerchantDecision>,
pub enable_payment_link: common_enums::EnablePaymentLinkRequest,
pub apply_mit_exemption: common_enums::MitExemptionRequest,
pub customer_present: common_enums::PresenceOfCustomerDuringPayment,
pub routing_algorithm_id: Option<&'a id_type::RoutingId>,
pub payment_link_config: Option<&'a PaymentLinkConfigRequestForPayments>,
pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>,
#[serde(flatten)]
infra_values: Option<Value>,
}
#[cfg(feature = "v2")]
impl<'a> KafkaPaymentIntent<'a> {
pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self {
let PaymentIntent {
id,
merchant_id,
status,
amount_details,
amount_captured,
customer_id,
description,
return_url,
metadata,
statement_descriptor,
created_at,
modified_at,
last_synced,
setup_future_usage,
active_attempt_id,
active_attempt_id_type,
active_attempts_group_id,
order_details,
allowed_payment_method_types,
connector_metadata,
feature_metadata,
attempt_count,
profile_id,
payment_link_id,
frm_merchant_decision,
updated_by,
request_incremental_authorization,
split_txns_enabled,
authorization_count,
session_expiry,
request_external_three_ds_authentication,
frm_metadata,
customer_details,
merchant_reference_id,
billing_address,
shipping_address,
capture_method,
authentication_type,
prerouting_algorithm,
organization_id,
enable_payment_link,
apply_mit_exemption,
customer_present,
payment_link_config,
routing_algorithm_id,
split_payments,
force_3ds_challenge,
force_3ds_challenge_trigger,
processor_merchant_id,
created_by,
is_iframe_redirection_enabled,
is_payment_id_from_merchant,
enable_partial_authorization,
} = intent;
Self {
payment_id: id,
merchant_id,
status: *status,
amount: amount_details.order_amount,
currency: amount_details.currency,
amount_captured: *amount_captured,
customer_id: customer_id.as_ref(),
description: description.as_ref(),
return_url: return_url.as_ref(),
metadata: metadata.as_ref(),
statement_descriptor: statement_descriptor.as_ref(),
created_at: created_at.assume_utc(),
modified_at: modified_at.assume_utc(),
last_synced: last_synced.map(|t| t.assume_utc()),
setup_future_usage: *setup_future_usage,
off_session: setup_future_usage.is_off_session(),
active_attempt_id: active_attempt_id.as_ref(),
active_attempt_id_type: *active_attempt_id_type,
active_attempts_group_id: active_attempts_group_id.as_ref(),
attempt_count: *attempt_count,
profile_id,
customer_email: None,
feature_metadata: feature_metadata.as_ref(),
organization_id,
order_details: order_details.as_ref(),
allowed_payment_method_types: allowed_payment_method_types.as_ref(),
connector_metadata: connector_metadata.as_ref(),
payment_link_id: payment_link_id.as_ref(),
updated_by,
surcharge_applicable: None,
request_incremental_authorization: *request_incremental_authorization,
split_txns_enabled: *split_txns_enabled,
authorization_count: *authorization_count,
session_expiry: session_expiry.assume_utc(),
request_external_three_ds_authentication: *request_external_three_ds_authentication,
frm_metadata: frm_metadata
.as_ref()
.map(|frm_metadata| frm_metadata.as_ref()),
customer_details: customer_details
.as_ref()
.map(|customer_details| customer_details.get_inner().as_ref()),
shipping_cost: amount_details.shipping_cost,
tax_details: amount_details.tax_details.clone(),
skip_external_tax_calculation: amount_details.get_external_tax_action_as_bool(),
request_extended_authorization: None,
psd2_sca_exemption_type: None,
split_payments: split_payments.as_ref(),
platform_merchant_id: None,
force_3ds_challenge: *force_3ds_challenge,
force_3ds_challenge_trigger: *force_3ds_challenge_trigger,
processor_merchant_id,
created_by: created_by.as_ref(),
is_iframe_redirection_enabled: *is_iframe_redirection_enabled,
merchant_reference_id: merchant_reference_id.as_ref(),
billing_address: billing_address
.as_ref()
.map(|billing_address| Secret::new(billing_address.get_inner())),
shipping_address: shipping_address
.as_ref()
.map(|shipping_address| Secret::new(shipping_address.get_inner())),
capture_method: *capture_method,
authentication_type: *authentication_type,
prerouting_algorithm: prerouting_algorithm.as_ref(),
surcharge_amount: amount_details.surcharge_amount,
tax_on_surcharge: amount_details.tax_on_surcharge,
frm_merchant_decision: *frm_merchant_decision,
enable_payment_link: *enable_payment_link,
apply_mit_exemption: *apply_mit_exemption,
customer_present: *customer_present,
routing_algorithm_id: routing_algorithm_id.as_ref(),
payment_link_config: payment_link_config.as_ref(),
infra_values,
enable_partial_authorization: *enable_partial_authorization,
}
}
}
impl KafkaPaymentIntent<'_> {
#[cfg(feature = "v1")]
fn get_id(&self) -> &id_type::PaymentId {
self.payment_id
}
#[cfg(feature = "v2")]
fn get_id(&self) -> &id_type::GlobalPaymentId {
self.payment_id
}
}
impl super::KafkaMessage for KafkaPaymentIntent<'_> {
fn key(&self) -> String {
format!(
"{}_{}",
self.merchant_id.get_string_repr(),
self.get_id().get_string_repr(),
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::PaymentIntent
}
}
| {
"crate": "router",
"file": "crates/router/src/services/kafka/payment_intent.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_4409583424003581789 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/api/client.rs
// Contains: 2 structs, 0 enums
use std::time::Duration;
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
pub use external_services::http_client::{self, client};
use http::{HeaderValue, Method};
pub use hyperswitch_interfaces::{
api_client::{ApiClient, ApiClientWrapper, RequestBuilder},
types::Proxy,
};
use masking::PeekInterface;
use reqwest::multipart::Form;
use router_env::tracing_actix_web::RequestId;
use super::{request::Maskable, Request};
use crate::core::errors::{ApiClientError, CustomResult};
#[derive(Clone)]
pub struct ProxyClient {
proxy_config: Proxy,
client: reqwest::Client,
request_id: Option<RequestId>,
}
impl ProxyClient {
pub fn new(proxy_config: &Proxy) -> CustomResult<Self, ApiClientError> {
let client = client::get_client_builder(proxy_config)
.switch()?
.build()
.change_context(ApiClientError::InvalidProxyConfiguration)?;
Ok(Self {
proxy_config: proxy_config.clone(),
client,
request_id: None,
})
}
pub fn get_reqwest_client(
&self,
client_certificate: Option<masking::Secret<String>>,
client_certificate_key: Option<masking::Secret<String>>,
) -> CustomResult<reqwest::Client, ApiClientError> {
match (client_certificate, client_certificate_key) {
(Some(certificate), Some(certificate_key)) => {
let client_builder = client::get_client_builder(&self.proxy_config).switch()?;
let identity =
client::create_identity_from_certificate_and_key(certificate, certificate_key)
.switch()?;
Ok(client_builder
.identity(identity)
.build()
.change_context(ApiClientError::ClientConstructionFailed)
.attach_printable(
"Failed to construct client with certificate and certificate key",
)?)
}
(_, _) => Ok(self.client.clone()),
}
}
}
pub struct RouterRequestBuilder {
// Using option here to get around the reinitialization problem
// request builder follows a chain pattern where the value is consumed and a newer requestbuilder is returned
// Since for this brief period of time between the value being consumed & newer request builder
// since requestbuilder does not allow moving the value
// leaves our struct in an inconsistent state, we are using option to get around rust semantics
inner: Option<reqwest::RequestBuilder>,
}
impl RequestBuilder for RouterRequestBuilder {
fn json(&mut self, body: serde_json::Value) {
self.inner = self.inner.take().map(|r| r.json(&body));
}
fn url_encoded_form(&mut self, body: serde_json::Value) {
self.inner = self.inner.take().map(|r| r.form(&body));
}
fn timeout(&mut self, timeout: Duration) {
self.inner = self.inner.take().map(|r| r.timeout(timeout));
}
fn multipart(&mut self, form: Form) {
self.inner = self.inner.take().map(|r| r.multipart(form));
}
fn header(&mut self, key: String, value: Maskable<String>) -> CustomResult<(), ApiClientError> {
let header_value = match value {
Maskable::Masked(hvalue) => HeaderValue::from_str(hvalue.peek()).map(|mut h| {
h.set_sensitive(true);
h
}),
Maskable::Normal(hvalue) => HeaderValue::from_str(&hvalue),
}
.change_context(ApiClientError::HeaderMapConstructionFailed)?;
self.inner = self.inner.take().map(|r| r.header(key, header_value));
Ok(())
}
fn send(
self,
) -> CustomResult<
Box<dyn core::future::Future<Output = Result<reqwest::Response, reqwest::Error>> + 'static>,
ApiClientError,
> {
Ok(Box::new(
self.inner.ok_or(ApiClientError::UnexpectedState)?.send(),
))
}
}
#[async_trait::async_trait]
impl ApiClient for ProxyClient {
fn request(
&self,
method: Method,
url: String,
) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError> {
self.request_with_certificate(method, url, None, None)
}
fn request_with_certificate(
&self,
method: Method,
url: String,
certificate: Option<masking::Secret<String>>,
certificate_key: Option<masking::Secret<String>>,
) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError> {
let client_builder = self
.get_reqwest_client(certificate, certificate_key)
.change_context(ApiClientError::ClientConstructionFailed)?;
Ok(Box::new(RouterRequestBuilder {
inner: Some(client_builder.request(method, url)),
}))
}
async fn send_request(
&self,
api_client: &dyn ApiClientWrapper,
request: Request,
option_timeout_secs: Option<u64>,
_forward_to_kafka: bool,
) -> CustomResult<reqwest::Response, ApiClientError> {
http_client::send_request(&api_client.get_proxy(), request, option_timeout_secs)
.await
.switch()
}
fn add_request_id(&mut self, request_id: RequestId) {
self.request_id = Some(request_id);
}
fn get_request_id(&self) -> Option<RequestId> {
self.request_id
}
fn get_request_id_str(&self) -> Option<String> {
self.request_id.map(|id| id.as_hyphenated().to_string())
}
fn add_flow_name(&mut self, _flow_name: String) {}
}
/// Api client for testing sending request
#[derive(Clone)]
pub struct MockApiClient;
#[async_trait::async_trait]
impl ApiClient for MockApiClient {
fn request(
&self,
_method: Method,
_url: String,
) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError> {
// [#2066]: Add Mock implementation for ApiClient
Err(ApiClientError::UnexpectedState.into())
}
fn request_with_certificate(
&self,
_method: Method,
_url: String,
_certificate: Option<masking::Secret<String>>,
_certificate_key: Option<masking::Secret<String>>,
) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError> {
// [#2066]: Add Mock implementation for ApiClient
Err(ApiClientError::UnexpectedState.into())
}
async fn send_request(
&self,
_state: &dyn ApiClientWrapper,
_request: Request,
_option_timeout_secs: Option<u64>,
_forward_to_kafka: bool,
) -> CustomResult<reqwest::Response, ApiClientError> {
// [#2066]: Add Mock implementation for ApiClient
Err(ApiClientError::UnexpectedState.into())
}
fn add_request_id(&mut self, _request_id: RequestId) {
// [#2066]: Add Mock implementation for ApiClient
}
fn get_request_id(&self) -> Option<RequestId> {
// [#2066]: Add Mock implementation for ApiClient
None
}
fn get_request_id_str(&self) -> Option<String> {
// [#2066]: Add Mock implementation for ApiClient
None
}
fn add_flow_name(&mut self, _flow_name: String) {}
}
| {
"crate": "router",
"file": "crates/router/src/services/api/client.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_2888154095906497787 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/authorization/roles.rs
// Contains: 1 structs, 0 enums
#[cfg(feature = "recon")]
use std::collections::HashMap;
use std::collections::HashSet;
#[cfg(feature = "recon")]
use api_models::enums::ReconPermissionScope;
use common_enums::{EntityType, PermissionGroup, Resource, RoleScope};
use common_utils::{errors::CustomResult, id_type};
#[cfg(feature = "recon")]
use super::permission_groups::{RECON_OPS, RECON_REPORTS};
use super::{permission_groups::PermissionGroupExt, permissions::Permission};
use crate::{core::errors, routes::SessionState};
pub mod predefined_roles;
#[derive(Clone, serde::Serialize, serde::Deserialize, Debug)]
pub struct RoleInfo {
role_id: String,
role_name: String,
groups: Vec<PermissionGroup>,
scope: RoleScope,
entity_type: EntityType,
is_invitable: bool,
is_deletable: bool,
is_updatable: bool,
is_internal: bool,
}
impl RoleInfo {
pub fn get_role_id(&self) -> &str {
&self.role_id
}
pub fn get_role_name(&self) -> &str {
&self.role_name
}
pub fn get_permission_groups(&self) -> Vec<PermissionGroup> {
self.groups
.iter()
.flat_map(|group| group.accessible_groups())
.collect::<HashSet<_>>()
.into_iter()
.collect()
}
pub fn get_scope(&self) -> RoleScope {
self.scope
}
pub fn get_entity_type(&self) -> EntityType {
self.entity_type
}
pub fn is_invitable(&self) -> bool {
self.is_invitable
}
pub fn is_deletable(&self) -> bool {
self.is_deletable
}
pub fn is_internal(&self) -> bool {
self.is_internal
}
pub fn is_updatable(&self) -> bool {
self.is_updatable
}
pub fn get_resources_set(&self) -> HashSet<Resource> {
self.get_permission_groups()
.iter()
.flat_map(|group| group.resources())
.collect()
}
pub fn check_permission_exists(&self, required_permission: Permission) -> bool {
required_permission.entity_type() <= self.entity_type
&& self.get_permission_groups().iter().any(|group| {
required_permission.scope() <= group.scope()
&& group.resources().contains(&required_permission.resource())
})
}
#[cfg(feature = "recon")]
pub fn get_recon_acl(&self) -> HashMap<Resource, ReconPermissionScope> {
let mut acl: HashMap<Resource, ReconPermissionScope> = HashMap::new();
let mut recon_resources = RECON_OPS.to_vec();
recon_resources.extend(RECON_REPORTS);
let recon_internal_resources = [Resource::ReconToken];
self.get_permission_groups()
.iter()
.for_each(|permission_group| {
permission_group.resources().iter().for_each(|resource| {
if recon_resources.contains(resource)
&& !recon_internal_resources.contains(resource)
{
let scope = match resource {
Resource::ReconAndSettlementAnalytics => ReconPermissionScope::Read,
_ => ReconPermissionScope::from(permission_group.scope()),
};
acl.entry(*resource)
.and_modify(|curr_scope| {
*curr_scope = if (*curr_scope) < scope {
scope
} else {
*curr_scope
}
})
.or_insert(scope);
}
})
});
acl
}
pub fn from_predefined_roles(role_id: &str) -> Option<Self> {
predefined_roles::PREDEFINED_ROLES.get(role_id).cloned()
}
pub async fn from_role_id_in_lineage(
state: &SessionState,
role_id: &str,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
profile_id: &id_type::ProfileId,
tenant_id: &id_type::TenantId,
) -> CustomResult<Self, errors::StorageError> {
if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) {
Ok(role.clone())
} else {
state
.global_store
.find_role_by_role_id_in_lineage(
role_id,
merchant_id,
org_id,
profile_id,
tenant_id,
)
.await
.map(Self::from)
}
}
// TODO: To evaluate whether we can omit org_id and tenant_id for this function
pub async fn from_role_id_org_id_tenant_id(
state: &SessionState,
role_id: &str,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
) -> CustomResult<Self, errors::StorageError> {
if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) {
Ok(role.clone())
} else {
state
.global_store
.find_by_role_id_org_id_tenant_id(role_id, org_id, tenant_id)
.await
.map(Self::from)
}
}
}
impl From<diesel_models::role::Role> for RoleInfo {
fn from(role: diesel_models::role::Role) -> Self {
Self {
role_id: role.role_id,
role_name: role.role_name,
groups: role.groups,
scope: role.scope,
entity_type: role.entity_type,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
}
}
}
| {
"crate": "router",
"file": "crates/router/src/services/authorization/roles.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-8979609677605548351 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/authentication/decision.rs
// Contains: 2 structs, 3 enums
use common_utils::{errors::CustomResult, request::RequestContent};
use masking::{ErasedMaskSerialize, Secret};
use serde::Serialize;
use storage_impl::errors::ApiClientError;
use crate::{
core::metrics,
routes::{app::settings::DecisionConfig, SessionState},
};
// # Consts
//
const DECISION_ENDPOINT: &str = "/rule";
const RULE_ADD_METHOD: common_utils::request::Method = common_utils::request::Method::Post;
const RULE_DELETE_METHOD: common_utils::request::Method = common_utils::request::Method::Delete;
pub const REVOKE: &str = "REVOKE";
pub const ADD: &str = "ADD";
// # Types
//
/// [`RuleRequest`] is a request body used to register a new authentication method in the proxy.
#[derive(Debug, Serialize)]
pub struct RuleRequest {
/// [`tag`] similar to a partition key, which can be used by the decision service to tag rules
/// by partitioning identifiers. (e.g. `tenant_id`)
pub tag: String,
/// [`variant`] is the type of authentication method to be registered.
#[serde(flatten)]
pub variant: AuthRuleType,
/// [`expiry`] is the time **in seconds** after which the rule should be removed
pub expiry: Option<u64>,
}
#[derive(Debug, Serialize)]
pub struct RuleDeleteRequest {
pub tag: String,
#[serde(flatten)]
pub variant: AuthType,
}
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AuthType {
/// [`ApiKey`] is an authentication method that uses an API key. This is used with [`ApiKey`]
ApiKey { api_key: Secret<String> },
}
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AuthRuleType {
/// [`ApiKey`] is an authentication method that uses an API key. This is used with [`ApiKey`]
/// and [`PublishableKey`] authentication methods.
ApiKey {
api_key: Secret<String>,
identifiers: Identifiers,
},
}
#[allow(clippy::enum_variant_names)]
#[derive(Debug, Serialize, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Identifiers {
/// [`ApiKey`] is an authentication method that uses an API key. This is used with [`ApiKey`]
ApiKey {
merchant_id: common_utils::id_type::MerchantId,
key_id: common_utils::id_type::ApiKeyId,
},
/// [`PublishableKey`] is an authentication method that uses a publishable key. This is used with [`PublishableKey`]
PublishableKey { merchant_id: String },
}
// # Decision Service
//
pub async fn add_api_key(
state: &SessionState,
api_key: Secret<String>,
merchant_id: common_utils::id_type::MerchantId,
key_id: common_utils::id_type::ApiKeyId,
expiry: Option<u64>,
) -> CustomResult<(), ApiClientError> {
let decision_config = if let Some(config) = &state.conf.decision {
config
} else {
return Ok(());
};
let rule = RuleRequest {
tag: state.tenant.schema.clone(),
expiry,
variant: AuthRuleType::ApiKey {
api_key,
identifiers: Identifiers::ApiKey {
merchant_id,
key_id,
},
},
};
call_decision_service(state, decision_config, rule, RULE_ADD_METHOD).await
}
pub async fn add_publishable_key(
state: &SessionState,
api_key: Secret<String>,
merchant_id: common_utils::id_type::MerchantId,
expiry: Option<u64>,
) -> CustomResult<(), ApiClientError> {
let decision_config = if let Some(config) = &state.conf.decision {
config
} else {
return Ok(());
};
let rule = RuleRequest {
tag: state.tenant.schema.clone(),
expiry,
variant: AuthRuleType::ApiKey {
api_key,
identifiers: Identifiers::PublishableKey {
merchant_id: merchant_id.get_string_repr().to_owned(),
},
},
};
call_decision_service(state, decision_config, rule, RULE_ADD_METHOD).await
}
async fn call_decision_service<T: ErasedMaskSerialize + Send + 'static>(
state: &SessionState,
decision_config: &DecisionConfig,
rule: T,
method: common_utils::request::Method,
) -> CustomResult<(), ApiClientError> {
let mut request = common_utils::request::Request::new(
method,
&(decision_config.base_url.clone() + DECISION_ENDPOINT),
);
request.set_body(RequestContent::Json(Box::new(rule)));
request.add_default_headers();
let response = state
.api_client
.send_request(state, request, None, false)
.await;
match response {
Err(error) => {
router_env::error!("Failed while calling the decision service: {:?}", error);
Err(error)
}
Ok(response) => {
router_env::info!("Decision service response: {:?}", response);
Ok(())
}
}
}
pub async fn revoke_api_key(
state: &SessionState,
api_key: Secret<String>,
) -> CustomResult<(), ApiClientError> {
let decision_config = if let Some(config) = &state.conf.decision {
config
} else {
return Ok(());
};
let rule = RuleDeleteRequest {
tag: state.tenant.schema.clone(),
variant: AuthType::ApiKey { api_key },
};
call_decision_service(state, decision_config, rule, RULE_DELETE_METHOD).await
}
/// Safety: i64::MAX < u64::MAX
#[allow(clippy::as_conversions)]
pub fn convert_expiry(expiry: time::PrimitiveDateTime) -> u64 {
let now = common_utils::date_time::now();
let duration = expiry - now;
let output = duration.whole_seconds();
match output {
i64::MIN..=0 => 0,
_ => output as u64,
}
}
pub fn spawn_tracked_job<E, F>(future: F, request_type: &'static str)
where
E: std::fmt::Debug,
F: futures::Future<Output = Result<(), E>> + Send + 'static,
{
metrics::API_KEY_REQUEST_INITIATED
.add(1, router_env::metric_attributes!(("type", request_type)));
tokio::spawn(async move {
match future.await {
Ok(_) => {
metrics::API_KEY_REQUEST_COMPLETED
.add(1, router_env::metric_attributes!(("type", request_type)));
}
Err(e) => {
router_env::error!("Error in tracked job: {:?}", e);
}
}
});
}
| {
"crate": "router",
"file": "crates/router/src/services/authentication/decision.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 3,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-3996966848351704021 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/authentication/detached.rs
// Contains: 1 structs, 1 enums
use std::{borrow::Cow, string::ToString};
use actix_web::http::header::HeaderMap;
use common_utils::{
crypto::VerifySignature,
id_type::{ApiKeyId, MerchantId},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
use crate::core::errors::RouterResult;
const HEADER_AUTH_TYPE: &str = "x-auth-type";
const HEADER_MERCHANT_ID: &str = "x-merchant-id";
const HEADER_KEY_ID: &str = "x-key-id";
const HEADER_CHECKSUM: &str = "x-checksum";
#[derive(Debug)]
pub struct ExtractedPayload {
pub payload_type: PayloadType,
pub merchant_id: Option<MerchantId>,
pub key_id: Option<ApiKeyId>,
}
#[derive(strum::EnumString, strum::Display, PartialEq, Debug)]
#[strum(serialize_all = "snake_case")]
pub enum PayloadType {
ApiKey,
PublishableKey,
}
pub trait GetAuthType {
fn get_auth_type(&self) -> PayloadType;
}
impl ExtractedPayload {
pub fn from_headers(headers: &HeaderMap) -> RouterResult<Self> {
let merchant_id = headers
.get(HEADER_MERCHANT_ID)
.and_then(|value| value.to_str().ok())
.ok_or_else(|| ApiErrorResponse::InvalidRequestData {
message: format!("`{HEADER_MERCHANT_ID}` header is invalid or not present"),
})
.map_err(error_stack::Report::from)
.and_then(|merchant_id| {
MerchantId::try_from(Cow::from(merchant_id.to_string())).change_context(
ApiErrorResponse::InvalidRequestData {
message: format!(
"`{HEADER_MERCHANT_ID}` header is invalid or not present",
),
},
)
})?;
let auth_type: PayloadType = headers
.get(HEADER_AUTH_TYPE)
.and_then(|inner| inner.to_str().ok())
.ok_or_else(|| ApiErrorResponse::InvalidRequestData {
message: format!("`{HEADER_AUTH_TYPE}` header not present"),
})?
.parse::<PayloadType>()
.change_context(ApiErrorResponse::InvalidRequestData {
message: format!("`{HEADER_AUTH_TYPE}` header not present"),
})?;
let key_id = headers
.get(HEADER_KEY_ID)
.and_then(|value| value.to_str().ok())
.map(|key_id| ApiKeyId::try_from(Cow::from(key_id.to_string())))
.transpose()
.change_context(ApiErrorResponse::InvalidRequestData {
message: format!("`{HEADER_KEY_ID}` header is invalid or not present"),
})?;
Ok(Self {
payload_type: auth_type,
merchant_id: Some(merchant_id),
key_id,
})
}
pub fn verify_checksum(
&self,
headers: &HeaderMap,
algo: impl VerifySignature,
secret: &[u8],
) -> bool {
let output = || {
let checksum = headers.get(HEADER_CHECKSUM)?.to_str().ok()?;
let payload = self.generate_payload();
algo.verify_signature(secret, &hex::decode(checksum).ok()?, payload.as_bytes())
.ok()
};
output().unwrap_or(false)
}
// The payload should be `:` separated strings of all the fields
fn generate_payload(&self) -> String {
append_option(
&self.payload_type.to_string(),
&self
.merchant_id
.as_ref()
.map(|inner| append_api_key(inner.get_string_repr(), &self.key_id)),
)
}
}
#[inline]
fn append_option(prefix: &str, data: &Option<String>) -> String {
match data {
Some(inner) => format!("{prefix}:{inner}"),
None => prefix.to_string(),
}
}
#[inline]
fn append_api_key(prefix: &str, data: &Option<ApiKeyId>) -> String {
match data {
Some(inner) => format!("{}:{}", prefix, inner.get_string_repr()),
None => prefix.to_string(),
}
}
| {
"crate": "router",
"file": "crates/router/src/services/authentication/detached.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_-5747820369745626779 | clm | file | // Repository: hyperswitch
// Crate: router
// File: crates/router/src/services/email/types.rs
// Contains: 2 structs, 0 enums
use api_models::user::dashboard_metadata::ProdIntent;
use common_enums::{EntityType, MerchantProductType};
use common_utils::{errors::CustomResult, pii, types::user::EmailThemeConfig};
use error_stack::ResultExt;
use external_services::email::{EmailContents, EmailData, EmailError};
use masking::{ExposeInterface, PeekInterface, Secret};
use crate::{configs, consts, routes::SessionState};
#[cfg(feature = "olap")]
use crate::{
core::errors::{UserErrors, UserResult},
services::jwt,
types::domain,
};
pub enum EmailBody {
Verify {
link: String,
entity_name: String,
entity_logo_url: String,
primary_color: String,
background_color: String,
foreground_color: String,
},
Reset {
link: String,
user_name: String,
entity_name: String,
entity_logo_url: String,
primary_color: String,
background_color: String,
foreground_color: String,
},
MagicLink {
link: String,
user_name: String,
entity_name: String,
entity_logo_url: String,
primary_color: String,
background_color: String,
foreground_color: String,
},
InviteUser {
link: String,
user_name: String,
entity_name: String,
entity_logo_url: String,
primary_color: String,
background_color: String,
foreground_color: String,
},
AcceptInviteFromEmail {
link: String,
user_name: String,
entity_name: String,
entity_logo_url: String,
primary_color: String,
background_color: String,
foreground_color: String,
},
BizEmailProd {
user_name: String,
poc_email: String,
legal_business_name: String,
business_location: String,
business_website: String,
product_type: MerchantProductType,
},
ReconActivation {
user_name: String,
},
ProFeatureRequest {
feature_name: String,
merchant_id: common_utils::id_type::MerchantId,
user_name: String,
user_email: String,
},
ApiKeyExpiryReminder {
expires_in: u8,
api_key_name: String,
prefix: String,
},
WelcomeToCommunity,
}
pub mod html {
use crate::services::email::types::EmailBody;
pub fn get_html_body(email_body: EmailBody) -> String {
match email_body {
EmailBody::Verify {
link,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/verify.html"),
link = link,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
EmailBody::Reset {
link,
user_name,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/reset.html"),
link = link,
username = user_name,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
EmailBody::MagicLink {
link,
user_name,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/magic_link.html"),
username = user_name,
link = link,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
EmailBody::InviteUser {
link,
user_name,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/invite.html"),
username = user_name,
link = link,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
// TODO: Change the linked html for accept invite from email
EmailBody::AcceptInviteFromEmail {
link,
user_name,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/invite.html"),
username = user_name,
link = link,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
EmailBody::ReconActivation { user_name } => {
format!(
include_str!("assets/recon_activation.html"),
username = user_name,
)
}
EmailBody::BizEmailProd {
user_name,
poc_email,
legal_business_name,
business_location,
business_website,
product_type,
} => {
format!(
include_str!("assets/bizemailprod.html"),
poc_email = poc_email,
legal_business_name = legal_business_name,
business_location = business_location,
business_website = business_website,
username = user_name,
product_type = product_type
)
}
EmailBody::ProFeatureRequest {
feature_name,
merchant_id,
user_name,
user_email,
} => format!(
"Dear Hyperswitch Support Team,
Dashboard Pro Feature Request,
Feature name : {feature_name}
Merchant ID : {}
Merchant Name : {user_name}
Email : {user_email}
(note: This is an auto generated email. Use merchant email for any further communications)",
merchant_id.get_string_repr()
),
EmailBody::ApiKeyExpiryReminder {
expires_in,
api_key_name,
prefix,
} => format!(
include_str!("assets/api_key_expiry_reminder.html"),
api_key_name = api_key_name,
prefix = prefix,
expires_in = expires_in,
),
EmailBody::WelcomeToCommunity => {
include_str!("assets/welcome_to_community.html").to_string()
}
}
}
}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct EmailToken {
email: String,
flow: domain::Origin,
exp: u64,
entity: Option<Entity>,
}
#[derive(serde::Serialize, serde::Deserialize, Clone)]
pub struct Entity {
pub entity_id: String,
pub entity_type: EntityType,
}
impl Entity {
pub fn get_entity_type(&self) -> EntityType {
self.entity_type
}
pub fn get_entity_id(&self) -> &str {
&self.entity_id
}
}
impl EmailToken {
pub async fn new_token(
email: domain::UserEmail,
entity: Option<Entity>,
flow: domain::Origin,
settings: &configs::Settings,
) -> UserResult<String> {
let expiration_duration = std::time::Duration::from_secs(consts::EMAIL_TOKEN_TIME_IN_SECS);
let exp = jwt::generate_exp(expiration_duration)?.as_secs();
let token_payload = Self {
email: email.get_secret().expose(),
flow,
exp,
entity,
};
jwt::generate_jwt(&token_payload, settings).await
}
pub fn get_email(&self) -> UserResult<domain::UserEmail> {
pii::Email::try_from(self.email.clone())
.change_context(UserErrors::InternalServerError)
.and_then(domain::UserEmail::from_pii_email)
}
pub fn get_entity(&self) -> Option<&Entity> {
self.entity.as_ref()
}
pub fn get_flow(&self) -> domain::Origin {
self.flow.clone()
}
}
pub fn get_link_with_token(
base_url: impl std::fmt::Display,
token: impl std::fmt::Display,
action: impl std::fmt::Display,
auth_id: &Option<impl std::fmt::Display>,
theme_id: &Option<impl std::fmt::Display>,
) -> String {
let mut email_url = format!("{base_url}/user/{action}?token={token}");
if let Some(auth_id) = auth_id {
email_url = format!("{email_url}&auth_id={auth_id}");
}
if let Some(theme_id) = theme_id {
email_url = format!("{email_url}&theme_id={theme_id}");
}
email_url
}
pub struct VerifyEmail {
pub recipient_email: domain::UserEmail,
pub settings: std::sync::Arc<configs::Settings>,
pub auth_id: Option<String>,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
}
/// Currently only HTML is supported
#[async_trait::async_trait]
impl EmailData for VerifyEmail {
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> {
let token = EmailToken::new_token(
self.recipient_email.clone(),
None,
domain::Origin::VerifyEmail,
&self.settings,
)
.await
.change_context(EmailError::TokenGenerationFailure)?;
let verify_email_link = get_link_with_token(
base_url,
token,
"verify_email",
&self.auth_id,
&self.theme_id,
);
let body = html::get_html_body(EmailBody::Verify {
link: verify_email_link,
entity_name: self.theme_config.entity_name.clone(),
entity_logo_url: self.theme_config.entity_logo_url.clone(),
primary_color: self.theme_config.primary_color.clone(),
background_color: self.theme_config.background_color.clone(),
foreground_color: self.theme_config.foreground_color.clone(),
});
Ok(EmailContents {
subject: format!(
"Welcome to the {} community!",
self.theme_config.entity_name
),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
}
pub struct ResetPassword {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
pub settings: std::sync::Arc<configs::Settings>,
pub auth_id: Option<String>,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
impl EmailData for ResetPassword {
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> {
let token = EmailToken::new_token(
self.recipient_email.clone(),
None,
domain::Origin::ResetPassword,
&self.settings,
)
.await
.change_context(EmailError::TokenGenerationFailure)?;
let reset_password_link = get_link_with_token(
base_url,
token,
"set_password",
&self.auth_id,
&self.theme_id,
);
let body = html::get_html_body(EmailBody::Reset {
link: reset_password_link,
user_name: self.user_name.clone().get_secret().expose(),
entity_name: self.theme_config.entity_name.clone(),
entity_logo_url: self.theme_config.entity_logo_url.clone(),
primary_color: self.theme_config.primary_color.clone(),
background_color: self.theme_config.background_color.clone(),
foreground_color: self.theme_config.foreground_color.clone(),
});
Ok(EmailContents {
subject: format!(
"Get back to {} - Reset Your Password Now!",
self.theme_config.entity_name
),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
}
pub struct MagicLink {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
pub settings: std::sync::Arc<configs::Settings>,
pub auth_id: Option<String>,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
impl EmailData for MagicLink {
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> {
let token = EmailToken::new_token(
self.recipient_email.clone(),
None,
domain::Origin::MagicLink,
&self.settings,
)
.await
.change_context(EmailError::TokenGenerationFailure)?;
let magic_link_login = get_link_with_token(
base_url,
token,
"verify_email",
&self.auth_id,
&self.theme_id,
);
let body = html::get_html_body(EmailBody::MagicLink {
link: magic_link_login,
user_name: self.user_name.clone().get_secret().expose(),
entity_name: self.theme_config.entity_name.clone(),
entity_logo_url: self.theme_config.entity_logo_url.clone(),
primary_color: self.theme_config.primary_color.clone(),
background_color: self.theme_config.background_color.clone(),
foreground_color: self.theme_config.foreground_color.clone(),
});
Ok(EmailContents {
subject: format!(
"Unlock {}: Use Your Magic Link to Sign In",
self.theme_config.entity_name
),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
}
pub struct InviteUser {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
pub settings: std::sync::Arc<configs::Settings>,
pub entity: Entity,
pub auth_id: Option<String>,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
impl EmailData for InviteUser {
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> {
let token = EmailToken::new_token(
self.recipient_email.clone(),
Some(self.entity.clone()),
domain::Origin::AcceptInvitationFromEmail,
&self.settings,
)
.await
.change_context(EmailError::TokenGenerationFailure)?;
let invite_user_link = get_link_with_token(
base_url,
token,
"accept_invite_from_email",
&self.auth_id,
&self.theme_id,
);
let body = html::get_html_body(EmailBody::AcceptInviteFromEmail {
link: invite_user_link,
user_name: self.user_name.clone().get_secret().expose(),
entity_name: self.theme_config.entity_name.clone(),
entity_logo_url: self.theme_config.entity_logo_url.clone(),
primary_color: self.theme_config.primary_color.clone(),
background_color: self.theme_config.background_color.clone(),
foreground_color: self.theme_config.foreground_color.clone(),
});
Ok(EmailContents {
subject: format!(
"You have been invited to join {} Community!",
self.theme_config.entity_name
),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
}
pub struct ReconActivation {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
pub subject: &'static str,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
impl EmailData for ReconActivation {
async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> {
let body = html::get_html_body(EmailBody::ReconActivation {
user_name: self.user_name.clone().get_secret().expose(),
});
Ok(EmailContents {
subject: self.subject.to_string(),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
}
pub struct BizEmailProd {
pub recipient_email: domain::UserEmail,
pub user_name: Secret<String>,
pub poc_email: Secret<String>,
pub legal_business_name: String,
pub business_location: String,
pub business_website: String,
pub settings: std::sync::Arc<configs::Settings>,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
pub product_type: MerchantProductType,
}
impl BizEmailProd {
pub fn new(
state: &SessionState,
data: ProdIntent,
theme_id: Option<String>,
theme_config: EmailThemeConfig,
) -> UserResult<Self> {
Ok(Self {
recipient_email: domain::UserEmail::from_pii_email(
state.conf.email.prod_intent_recipient_email.clone(),
)?,
settings: state.conf.clone(),
user_name: data
.poc_name
.map(|s| Secret::new(s.peek().clone().into_inner()))
.unwrap_or_default(),
poc_email: data
.poc_email
.map(|s| Secret::new(s.peek().clone()))
.unwrap_or_default(),
legal_business_name: data
.legal_business_name
.map(|s| s.into_inner())
.unwrap_or_default(),
business_location: data
.business_location
.unwrap_or(common_enums::CountryAlpha2::AD)
.to_string(),
business_website: data
.business_website
.map(|s| s.into_inner())
.unwrap_or_default(),
theme_id,
theme_config,
product_type: data.product_type,
})
}
}
#[async_trait::async_trait]
impl EmailData for BizEmailProd {
async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> {
let body = html::get_html_body(EmailBody::BizEmailProd {
user_name: self.user_name.clone().expose(),
poc_email: self.poc_email.clone().expose(),
legal_business_name: self.legal_business_name.clone(),
business_location: self.business_location.clone(),
business_website: self.business_website.clone(),
product_type: self.product_type,
});
Ok(EmailContents {
subject: "New Prod Intent".to_string(),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
}
pub struct ProFeatureRequest {
pub recipient_email: domain::UserEmail,
pub feature_name: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub user_name: domain::UserName,
pub user_email: domain::UserEmail,
pub subject: String,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
impl EmailData for ProFeatureRequest {
async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> {
let recipient = self.recipient_email.clone().into_inner();
let body = html::get_html_body(EmailBody::ProFeatureRequest {
user_name: self.user_name.clone().get_secret().expose(),
feature_name: self.feature_name.clone(),
merchant_id: self.merchant_id.clone(),
user_email: self.user_email.clone().get_secret().expose(),
});
Ok(EmailContents {
subject: self.subject.clone(),
body: external_services::email::IntermediateString::new(body),
recipient,
})
}
}
pub struct ApiKeyExpiryReminder {
pub recipient_email: domain::UserEmail,
pub subject: &'static str,
pub expires_in: u8,
pub api_key_name: String,
pub prefix: String,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
impl EmailData for ApiKeyExpiryReminder {
async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> {
let recipient = self.recipient_email.clone().into_inner();
let body = html::get_html_body(EmailBody::ApiKeyExpiryReminder {
expires_in: self.expires_in,
api_key_name: self.api_key_name.clone(),
prefix: self.prefix.clone(),
});
Ok(EmailContents {
subject: self.subject.to_string(),
body: external_services::email::IntermediateString::new(body),
recipient,
})
}
}
pub struct WelcomeToCommunity {
pub recipient_email: domain::UserEmail,
}
#[async_trait::async_trait]
impl EmailData for WelcomeToCommunity {
async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> {
let body = html::get_html_body(EmailBody::WelcomeToCommunity);
Ok(EmailContents {
subject: "Thank you for signing up on Hyperswitch Dashboard!".to_string(),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
}
| {
"crate": "router",
"file": "crates/router/src/services/email/types.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_storage_impl_-4207627762066632946 | clm | file | // Repository: hyperswitch
// Crate: storage_impl
// File: crates/storage_impl/src/errors.rs
// Contains: 0 structs, 9 enums
pub use common_enums::{ApiClientError, ApplicationError, ApplicationResult};
pub use redis_interface::errors::RedisError;
use crate::store::errors::DatabaseError;
pub type StorageResult<T> = error_stack::Result<T, StorageError>;
#[derive(Debug, thiserror::Error)]
pub enum StorageError {
#[error("Initialization Error")]
InitializationError,
#[error("DatabaseError: {0:?}")]
DatabaseError(error_stack::Report<DatabaseError>),
#[error("ValueNotFound: {0}")]
ValueNotFound(String),
#[error("DuplicateValue: {entity} already exists {key:?}")]
DuplicateValue {
entity: &'static str,
key: Option<String>,
},
#[error("Timed out while trying to connect to the database")]
DatabaseConnectionError,
#[error("KV error")]
KVError,
#[error("Serialization failure")]
SerializationFailed,
#[error("MockDb error")]
MockDbError,
#[error("Kafka error")]
KafkaError,
#[error("Customer with this id is Redacted")]
CustomerRedacted,
#[error("Deserialization failure")]
DeserializationFailed,
#[error("Error while encrypting data")]
EncryptionError,
#[error("Error while decrypting data from database")]
DecryptionError,
#[error("RedisError: {0:?}")]
RedisError(error_stack::Report<RedisError>),
}
impl From<error_stack::Report<RedisError>> for StorageError {
fn from(err: error_stack::Report<RedisError>) -> Self {
match err.current_context() {
RedisError::NotFound => Self::ValueNotFound("redis value not found".to_string()),
RedisError::JsonSerializationFailed => Self::SerializationFailed,
RedisError::JsonDeserializationFailed => Self::DeserializationFailed,
_ => Self::RedisError(err),
}
}
}
impl From<diesel::result::Error> for StorageError {
fn from(err: diesel::result::Error) -> Self {
Self::from(error_stack::report!(DatabaseError::from(err)))
}
}
impl From<error_stack::Report<DatabaseError>> for StorageError {
fn from(err: error_stack::Report<DatabaseError>) -> Self {
match err.current_context() {
DatabaseError::DatabaseConnectionError => Self::DatabaseConnectionError,
DatabaseError::NotFound => Self::ValueNotFound(String::from("db value not found")),
DatabaseError::UniqueViolation => Self::DuplicateValue {
entity: "db entity",
key: None,
},
_ => Self::DatabaseError(err),
}
}
}
impl StorageError {
pub fn is_db_not_found(&self) -> bool {
match self {
Self::DatabaseError(err) => matches!(err.current_context(), DatabaseError::NotFound),
Self::ValueNotFound(_) => true,
Self::RedisError(err) => matches!(err.current_context(), RedisError::NotFound),
_ => false,
}
}
pub fn is_db_unique_violation(&self) -> bool {
match self {
Self::DatabaseError(err) => {
matches!(err.current_context(), DatabaseError::UniqueViolation,)
}
Self::DuplicateValue { .. } => true,
_ => false,
}
}
}
pub trait RedisErrorExt {
#[track_caller]
fn to_redis_failed_response(self, key: &str) -> error_stack::Report<StorageError>;
}
impl RedisErrorExt for error_stack::Report<RedisError> {
fn to_redis_failed_response(self, key: &str) -> error_stack::Report<StorageError> {
match self.current_context() {
RedisError::NotFound => self.change_context(StorageError::ValueNotFound(format!(
"Data does not exist for key {key}",
))),
RedisError::SetNxFailed | RedisError::SetAddMembersFailed => {
self.change_context(StorageError::DuplicateValue {
entity: "redis",
key: Some(key.to_string()),
})
}
_ => self.change_context(StorageError::KVError),
}
}
}
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum ConnectorError {
#[error("Error while obtaining URL for the integration")]
FailedToObtainIntegrationUrl,
#[error("Failed to encode connector request")]
RequestEncodingFailed,
#[error("Request encoding failed : {0}")]
RequestEncodingFailedWithReason(String),
#[error("Parsing failed")]
ParsingFailed,
#[error("Failed to deserialize connector response")]
ResponseDeserializationFailed,
#[error("Failed to execute a processing step: {0:?}")]
ProcessingStepFailed(Option<bytes::Bytes>),
#[error("The connector returned an unexpected response: {0:?}")]
UnexpectedResponseError(bytes::Bytes),
#[error("Failed to parse custom routing rules from merchant account")]
RoutingRulesParsingError,
#[error("Failed to obtain preferred connector from merchant account")]
FailedToObtainPreferredConnector,
#[error("An invalid connector name was provided")]
InvalidConnectorName,
#[error("An invalid Wallet was used")]
InvalidWallet,
#[error("Failed to handle connector response")]
ResponseHandlingFailed,
#[error("Missing required field: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error("Missing required fields: {field_names:?}")]
MissingRequiredFields { field_names: Vec<&'static str> },
#[error("Failed to obtain authentication type")]
FailedToObtainAuthType,
#[error("Failed to obtain certificate")]
FailedToObtainCertificate,
#[error("Connector meta data not found")]
NoConnectorMetaData,
#[error("Failed to obtain certificate key")]
FailedToObtainCertificateKey,
#[error("This step has not been implemented for: {0}")]
NotImplemented(String),
#[error("{message} is not supported by {connector}")]
NotSupported {
message: String,
connector: &'static str,
payment_experience: String,
},
#[error("{flow} flow not supported by {connector} connector")]
FlowNotSupported { flow: String, connector: String },
#[error("Connector '{connector}' rejected field '{field_name}': length {received_length} exceeds maximum of {max_length}'")]
MaxFieldLengthViolated {
connector: String,
field_name: String,
max_length: usize,
received_length: usize,
},
#[error("Capture method not supported")]
CaptureMethodNotSupported,
#[error("Missing connector transaction ID")]
MissingConnectorTransactionID,
#[error("Missing connector refund ID")]
MissingConnectorRefundID,
#[error("Webhooks not implemented for this connector")]
WebhooksNotImplemented,
#[error("Failed to decode webhook event body")]
WebhookBodyDecodingFailed,
#[error("Signature not found for incoming webhook")]
WebhookSignatureNotFound,
#[error("Failed to verify webhook source")]
WebhookSourceVerificationFailed,
#[error("Could not find merchant secret in DB for incoming webhook source verification")]
WebhookVerificationSecretNotFound,
#[error("Incoming webhook object reference ID not found")]
WebhookReferenceIdNotFound,
#[error("Incoming webhook event type not found")]
WebhookEventTypeNotFound,
#[error("Incoming webhook event resource object not found")]
WebhookResourceObjectNotFound,
#[error("Could not respond to the incoming webhook event")]
WebhookResponseEncodingFailed,
#[error("Invalid Date/time format")]
InvalidDateFormat,
#[error("Date Formatting Failed")]
DateFormattingFailed,
#[error("Invalid Data format")]
InvalidDataFormat { field_name: &'static str },
#[error("Payment Method data / Payment Method Type / Payment Experience Mismatch ")]
MismatchedPaymentData,
#[error("Field {fields} doesn't match with the ones used during mandate creation")]
MandatePaymentDataMismatch { fields: String },
#[error("Failed to parse Wallet token")]
InvalidWalletToken { wallet_name: String },
#[error("Missing Connector Related Transaction ID")]
MissingConnectorRelatedTransactionID { id: String },
#[error("File Validation failed")]
FileValidationFailed { reason: String },
#[error("Missing 3DS redirection payload: {field_name}")]
MissingConnectorRedirectionPayload { field_name: &'static str },
}
#[derive(Debug, thiserror::Error)]
pub enum HealthCheckDBError {
#[error("Error while connecting to database")]
DBError,
#[error("Error while writing to database")]
DBWriteError,
#[error("Error while reading element in the database")]
DBReadError,
#[error("Error while deleting element in the database")]
DBDeleteError,
#[error("Unpredictable error occurred")]
UnknownError,
#[error("Error in database transaction")]
TransactionError,
#[error("Error while executing query in Sqlx Analytics")]
SqlxAnalyticsError,
#[error("Error while executing query in Clickhouse Analytics")]
ClickhouseAnalyticsError,
#[error("Error while executing query in Opensearch")]
OpensearchError,
}
impl From<diesel::result::Error> for HealthCheckDBError {
fn from(error: diesel::result::Error) -> Self {
match error {
diesel::result::Error::DatabaseError(_, _) => Self::DBError,
diesel::result::Error::RollbackErrorOnCommit { .. }
| diesel::result::Error::RollbackTransaction
| diesel::result::Error::AlreadyInTransaction
| diesel::result::Error::NotInTransaction
| diesel::result::Error::BrokenTransactionManager => Self::TransactionError,
_ => Self::UnknownError,
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum HealthCheckRedisError {
#[error("Failed to establish Redis connection")]
RedisConnectionError,
#[error("Failed to set key value in Redis")]
SetFailed,
#[error("Failed to get key value in Redis")]
GetFailed,
#[error("Failed to delete key value in Redis")]
DeleteFailed,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum HealthCheckLockerError {
#[error("Failed to establish Locker connection")]
FailedToCallLocker,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum HealthCheckGRPCServiceError {
#[error("Failed to establish connection with gRPC service")]
FailedToCallService,
}
#[derive(thiserror::Error, Debug, Clone)]
pub enum RecoveryError {
#[error("Failed to make a recovery payment")]
PaymentCallFailed,
#[error("Encountered a Process Tracker Task Failure")]
ProcessTrackerFailure,
#[error("The encountered task is invalid")]
InvalidTask,
#[error("The Process Tracker data was not found")]
ValueNotFound,
#[error("Failed to update billing connector")]
RecordBackToBillingConnectorFailed,
#[error("Failed to fetch billing connector account id")]
BillingMerchantConnectorAccountIdNotFound,
#[error("Failed to generate payment sync data")]
PaymentsResponseGenerationFailed,
#[error("Outgoing Webhook Failed")]
RevenueRecoveryOutgoingWebhookFailed,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum HealthCheckDecisionEngineError {
#[error("Failed to establish Decision Engine connection")]
FailedToCallDecisionEngineService,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum HealthCheckUnifiedConnectorServiceError {
#[error("Failed to establish Unified Connector Service connection")]
FailedToCallUnifiedConnectorService,
}
| {
"crate": "storage_impl",
"file": "crates/storage_impl/src/errors.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 9,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_storage_impl_-4220580783552402933 | clm | file | // Repository: hyperswitch
// Crate: storage_impl
// File: crates/storage_impl/src/redis/kv_store.rs
// Contains: 0 structs, 2 enums
use std::{fmt::Debug, sync::Arc};
use common_utils::errors::CustomResult;
use diesel_models::enums::MerchantStorageScheme;
use error_stack::report;
use redis_interface::errors::RedisError;
use router_derive::TryGetEnumVariant;
use router_env::logger;
use serde::de;
use crate::{kv_router_store::KVRouterStore, metrics, store::kv::TypedSql, UniqueConstraints};
pub trait KvStorePartition {
fn partition_number(key: PartitionKey<'_>, num_partitions: u8) -> u32 {
crc32fast::hash(key.to_string().as_bytes()) % u32::from(num_partitions)
}
fn shard_key(key: PartitionKey<'_>, num_partitions: u8) -> String {
format!("shard_{}", Self::partition_number(key, num_partitions))
}
}
#[allow(unused)]
#[derive(Clone)]
pub enum PartitionKey<'a> {
MerchantIdPaymentId {
merchant_id: &'a common_utils::id_type::MerchantId,
payment_id: &'a common_utils::id_type::PaymentId,
},
CombinationKey {
combination: &'a str,
},
MerchantIdCustomerId {
merchant_id: &'a common_utils::id_type::MerchantId,
customer_id: &'a common_utils::id_type::CustomerId,
},
#[cfg(feature = "v2")]
MerchantIdMerchantReferenceId {
merchant_id: &'a common_utils::id_type::MerchantId,
merchant_reference_id: &'a str,
},
MerchantIdPayoutId {
merchant_id: &'a common_utils::id_type::MerchantId,
payout_id: &'a common_utils::id_type::PayoutId,
},
MerchantIdPayoutAttemptId {
merchant_id: &'a common_utils::id_type::MerchantId,
payout_attempt_id: &'a str,
},
MerchantIdMandateId {
merchant_id: &'a common_utils::id_type::MerchantId,
mandate_id: &'a str,
},
#[cfg(feature = "v2")]
GlobalId {
id: &'a str,
},
#[cfg(feature = "v2")]
GlobalPaymentId {
id: &'a common_utils::id_type::GlobalPaymentId,
},
}
// PartitionKey::MerchantIdPaymentId {merchant_id, payment_id}
impl std::fmt::Display for PartitionKey<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
PartitionKey::MerchantIdPaymentId {
merchant_id,
payment_id,
} => f.write_str(&format!(
"mid_{}_pid_{}",
merchant_id.get_string_repr(),
payment_id.get_string_repr()
)),
PartitionKey::CombinationKey { combination } => f.write_str(combination),
PartitionKey::MerchantIdCustomerId {
merchant_id,
customer_id,
} => f.write_str(&format!(
"mid_{}_cust_{}",
merchant_id.get_string_repr(),
customer_id.get_string_repr()
)),
#[cfg(feature = "v2")]
PartitionKey::MerchantIdMerchantReferenceId {
merchant_id,
merchant_reference_id,
} => f.write_str(&format!(
"mid_{}_cust_{merchant_reference_id}",
merchant_id.get_string_repr()
)),
PartitionKey::MerchantIdPayoutId {
merchant_id,
payout_id,
} => f.write_str(&format!(
"mid_{}_po_{}",
merchant_id.get_string_repr(),
payout_id.get_string_repr()
)),
PartitionKey::MerchantIdPayoutAttemptId {
merchant_id,
payout_attempt_id,
} => f.write_str(&format!(
"mid_{}_poa_{payout_attempt_id}",
merchant_id.get_string_repr()
)),
PartitionKey::MerchantIdMandateId {
merchant_id,
mandate_id,
} => f.write_str(&format!(
"mid_{}_mandate_{mandate_id}",
merchant_id.get_string_repr()
)),
#[cfg(feature = "v2")]
PartitionKey::GlobalId { id } => f.write_str(&format!("global_cust_{id}")),
#[cfg(feature = "v2")]
PartitionKey::GlobalPaymentId { id } => {
f.write_str(&format!("global_payment_{}", id.get_string_repr()))
}
}
}
}
pub trait RedisConnInterface {
fn get_redis_conn(
&self,
) -> error_stack::Result<Arc<redis_interface::RedisConnectionPool>, RedisError>;
}
/// An enum to represent what operation to do on
pub enum KvOperation<'a, S: serde::Serialize + Debug> {
Hset((&'a str, String), TypedSql),
SetNx(&'a S, TypedSql),
HSetNx(&'a str, &'a S, TypedSql),
HGet(&'a str),
Get,
Scan(&'a str),
}
#[derive(TryGetEnumVariant)]
#[error(RedisError::UnknownResult)]
pub enum KvResult<T: de::DeserializeOwned> {
HGet(T),
Get(T),
Hset(()),
SetNx(redis_interface::SetnxReply),
HSetNx(redis_interface::HsetnxReply),
Scan(Vec<T>),
}
impl<T> std::fmt::Display for KvOperation<'_, T>
where
T: serde::Serialize + Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
KvOperation::Hset(_, _) => f.write_str("Hset"),
KvOperation::SetNx(_, _) => f.write_str("Setnx"),
KvOperation::HSetNx(_, _, _) => f.write_str("HSetNx"),
KvOperation::HGet(_) => f.write_str("Hget"),
KvOperation::Get => f.write_str("Get"),
KvOperation::Scan(_) => f.write_str("Scan"),
}
}
}
pub async fn kv_wrapper<'a, T, D, S>(
store: &KVRouterStore<D>,
op: KvOperation<'a, S>,
partition_key: PartitionKey<'a>,
) -> CustomResult<KvResult<T>, RedisError>
where
T: de::DeserializeOwned,
D: crate::database::store::DatabaseStore,
S: serde::Serialize + Debug + KvStorePartition + UniqueConstraints + Sync,
{
let redis_conn = store.get_redis_conn()?;
let key = format!("{partition_key}");
let type_name = std::any::type_name::<T>();
let operation = op.to_string();
let ttl = store.ttl_for_kv;
let result = async {
match op {
KvOperation::Hset(value, sql) => {
logger::debug!(kv_operation= %operation, value = ?value);
redis_conn
.set_hash_fields(&key.into(), value, Some(ttl.into()))
.await?;
store
.push_to_drainer_stream::<S>(sql, partition_key)
.await?;
Ok(KvResult::Hset(()))
}
KvOperation::HGet(field) => {
let result = redis_conn
.get_hash_field_and_deserialize(&key.into(), field, type_name)
.await?;
Ok(KvResult::HGet(result))
}
KvOperation::Scan(pattern) => {
let result: Vec<T> = redis_conn
.hscan_and_deserialize(&key.into(), pattern, None)
.await
.and_then(|result| {
if result.is_empty() {
Err(report!(RedisError::NotFound))
} else {
Ok(result)
}
})?;
Ok(KvResult::Scan(result))
}
KvOperation::HSetNx(field, value, sql) => {
logger::debug!(kv_operation= %operation, value = ?value);
value.check_for_constraints(&redis_conn).await?;
let result = redis_conn
.serialize_and_set_hash_field_if_not_exist(&key.into(), field, value, Some(ttl))
.await?;
if matches!(result, redis_interface::HsetnxReply::KeySet) {
store
.push_to_drainer_stream::<S>(sql, partition_key)
.await?;
Ok(KvResult::HSetNx(result))
} else {
Err(report!(RedisError::SetNxFailed))
}
}
KvOperation::SetNx(value, sql) => {
logger::debug!(kv_operation= %operation, value = ?value);
let result = redis_conn
.serialize_and_set_key_if_not_exist(&key.into(), value, Some(ttl.into()))
.await?;
value.check_for_constraints(&redis_conn).await?;
if matches!(result, redis_interface::SetnxReply::KeySet) {
store
.push_to_drainer_stream::<S>(sql, partition_key)
.await?;
Ok(KvResult::SetNx(result))
} else {
Err(report!(RedisError::SetNxFailed))
}
}
KvOperation::Get => {
let result = redis_conn
.get_and_deserialize_key(&key.into(), type_name)
.await?;
Ok(KvResult::Get(result))
}
}
};
let attributes = router_env::metric_attributes!(("operation", operation.clone()));
result
.await
.inspect(|_| {
logger::debug!(kv_operation= %operation, status="success");
metrics::KV_OPERATION_SUCCESSFUL.add(1, attributes);
})
.inspect_err(|err| {
logger::error!(kv_operation = %operation, status="error", error = ?err);
metrics::KV_OPERATION_FAILED.add(1, attributes);
})
}
pub enum Op<'a> {
Insert,
Update(PartitionKey<'a>, &'a str, Option<&'a str>),
Find,
}
impl std::fmt::Display for Op<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Op::Insert => f.write_str("insert"),
Op::Find => f.write_str("find"),
Op::Update(p_key, _, updated_by) => {
f.write_str(&format!("update_{p_key} for updated_by_{updated_by:?}"))
}
}
}
}
pub async fn decide_storage_scheme<T, D>(
store: &KVRouterStore<T>,
storage_scheme: MerchantStorageScheme,
operation: Op<'_>,
) -> MerchantStorageScheme
where
D: de::DeserializeOwned
+ serde::Serialize
+ Debug
+ KvStorePartition
+ UniqueConstraints
+ Sync,
T: crate::database::store::DatabaseStore,
{
if store.soft_kill_mode {
let ops = operation.to_string();
let updated_scheme = match operation {
Op::Insert => MerchantStorageScheme::PostgresOnly,
Op::Find => MerchantStorageScheme::RedisKv,
Op::Update(_, _, Some("postgres_only")) => MerchantStorageScheme::PostgresOnly,
Op::Update(partition_key, field, Some(_updated_by)) => {
match Box::pin(kv_wrapper::<D, _, _>(
store,
KvOperation::<D>::HGet(field),
partition_key,
))
.await
{
Ok(_) => {
metrics::KV_SOFT_KILL_ACTIVE_UPDATE.add(1, &[]);
MerchantStorageScheme::RedisKv
}
Err(_) => MerchantStorageScheme::PostgresOnly,
}
}
Op::Update(_, _, None) => MerchantStorageScheme::PostgresOnly,
};
let type_name = std::any::type_name::<D>();
logger::info!(soft_kill_mode = "decide_storage_scheme", decided_scheme = %updated_scheme, configured_scheme = %storage_scheme,entity = %type_name, operation = %ops);
updated_scheme
} else {
storage_scheme
}
}
| {
"crate": "storage_impl",
"file": "crates/storage_impl/src/redis/kv_store.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_common_utils_-4727525284573942609 | clm | file | // Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/events.rs
// Contains: 0 structs, 1 enums
use serde::Serialize;
use crate::{id_type, types::TimeRange};
pub trait ApiEventMetric {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(tag = "flow_type", rename_all = "snake_case")]
pub enum ApiEventsType {
Payout {
payout_id: id_type::PayoutId,
},
#[cfg(feature = "v1")]
Payment {
payment_id: id_type::PaymentId,
},
#[cfg(feature = "v2")]
Payment {
payment_id: id_type::GlobalPaymentId,
},
#[cfg(feature = "v1")]
Refund {
payment_id: Option<id_type::PaymentId>,
refund_id: String,
},
#[cfg(feature = "v2")]
Refund {
payment_id: Option<id_type::GlobalPaymentId>,
refund_id: id_type::GlobalRefundId,
},
#[cfg(feature = "v1")]
PaymentMethod {
payment_method_id: String,
payment_method: Option<common_enums::PaymentMethod>,
payment_method_type: Option<common_enums::PaymentMethodType>,
},
#[cfg(feature = "v2")]
PaymentMethod {
payment_method_id: id_type::GlobalPaymentMethodId,
payment_method_type: Option<common_enums::PaymentMethod>,
payment_method_subtype: Option<common_enums::PaymentMethodType>,
},
#[cfg(feature = "v2")]
PaymentMethodCreate,
#[cfg(feature = "v2")]
Customer {
customer_id: Option<id_type::GlobalCustomerId>,
},
#[cfg(feature = "v1")]
Customer {
customer_id: id_type::CustomerId,
},
BusinessProfile {
profile_id: id_type::ProfileId,
},
ApiKey {
key_id: id_type::ApiKeyId,
},
User {
user_id: String,
},
PaymentMethodList {
payment_id: Option<String>,
},
#[cfg(feature = "v2")]
PaymentMethodListForPaymentMethods {
payment_method_id: id_type::GlobalPaymentMethodId,
},
#[cfg(feature = "v1")]
Webhooks {
connector: String,
payment_id: Option<id_type::PaymentId>,
},
#[cfg(feature = "v1")]
NetworkTokenWebhook {
payment_method_id: Option<String>,
},
#[cfg(feature = "v2")]
Webhooks {
connector: id_type::MerchantConnectorAccountId,
payment_id: Option<id_type::GlobalPaymentId>,
},
Routing,
Subscription,
Invoice,
ResourceListAPI,
#[cfg(feature = "v1")]
PaymentRedirectionResponse {
connector: Option<String>,
payment_id: Option<id_type::PaymentId>,
},
#[cfg(feature = "v2")]
PaymentRedirectionResponse {
payment_id: id_type::GlobalPaymentId,
},
Gsm,
// TODO: This has to be removed once the corresponding apiEventTypes are created
Miscellaneous,
Keymanager,
RustLocker,
ApplePayCertificatesMigration,
FraudCheck,
Recon,
ExternalServiceAuth,
Dispute {
dispute_id: String,
},
Events {
merchant_id: id_type::MerchantId,
},
PaymentMethodCollectLink {
link_id: String,
},
Poll {
poll_id: String,
},
Analytics,
#[cfg(feature = "v2")]
ClientSecret {
key_id: id_type::ClientSecretId,
},
#[cfg(feature = "v2")]
PaymentMethodSession {
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
},
#[cfg(feature = "v2")]
Token {
token_id: Option<id_type::GlobalTokenId>,
},
ProcessTracker,
Authentication {
authentication_id: id_type::AuthenticationId,
},
ProfileAcquirer {
profile_acquirer_id: id_type::ProfileAcquirerId,
},
ThreeDsDecisionRule,
Chat,
}
impl ApiEventMetric for serde_json::Value {}
impl ApiEventMetric for () {}
#[cfg(feature = "v1")]
impl ApiEventMetric for id_type::PaymentId {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for id_type::GlobalPaymentId {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.clone(),
})
}
}
impl<Q: ApiEventMetric, E> ApiEventMetric for Result<Q, E> {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
match self {
Ok(q) => q.get_api_event_type(),
Err(_) => None,
}
}
}
// TODO: Ideally all these types should be replaced by newtype responses
impl<T> ApiEventMetric for Vec<T> {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Miscellaneous)
}
}
#[macro_export]
macro_rules! impl_api_event_type {
($event: ident, ($($type:ty),+))=> {
$(
impl ApiEventMetric for $type {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::$event)
}
}
)+
};
}
impl_api_event_type!(
Miscellaneous,
(
String,
id_type::MerchantId,
(Option<i64>, Option<i64>, String),
(Option<i64>, Option<i64>, id_type::MerchantId),
bool
)
);
impl<T: ApiEventMetric> ApiEventMetric for &T {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
T::get_api_event_type(self)
}
}
impl ApiEventMetric for TimeRange {}
| {
"crate": "common_utils",
"file": "crates/common_utils/src/events.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_common_utils_-1265641935597532155 | clm | file | // Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/ucs_types.rs
// Contains: 0 structs, 1 enums
use crate::id_type;
/// Represents a reference ID for the Unified Connector Service (UCS).
///
/// This enum can hold either a payment reference ID or a refund reference ID,
/// allowing for a unified way to handle different types of transaction references
/// when interacting with the UCS.
#[derive(Debug)]
pub enum UcsReferenceId {
/// A payment reference ID.
///
/// This variant wraps a [`PaymentReferenceId`](id_type::PaymentReferenceId)
/// and is used to identify a payment transaction within the UCS.
Payment(id_type::PaymentReferenceId),
/// A refund reference ID.
///
/// This variant wraps a [`RefundReferenceId`](id_type::RefundReferenceId)
/// and is used to identify a refund transaction within the UCS.
Refund(id_type::RefundReferenceId),
}
impl UcsReferenceId {
/// Returns the string representation of the reference ID.
///
/// This method matches the enum variant and calls the `get_string_repr`
/// method of the underlying ID type (either `PaymentReferenceId` or `RefundReferenceId`)
/// to get its string representation.
///
/// # Returns
///
/// A string slice (`&str`) representing the reference ID.
pub fn get_string_repr(&self) -> &str {
match self {
Self::Payment(id) => id.get_string_repr(),
Self::Refund(id) => id.get_string_repr(),
}
}
}
| {
"crate": "common_utils",
"file": "crates/common_utils/src/ucs_types.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_common_utils_8983164366300277219 | clm | file | // Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/types/authentication.rs
// Contains: 0 structs, 2 enums
use crate::id_type;
/// Enum for different levels of authentication
#[derive(
Clone,
Debug,
Hash,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
)]
pub enum AuthInfo {
/// OrgLevel: Authentication at the organization level
OrgLevel {
/// org_id: OrganizationId
org_id: id_type::OrganizationId,
},
/// MerchantLevel: Authentication at the merchant level
MerchantLevel {
/// org_id: OrganizationId
org_id: id_type::OrganizationId,
/// merchant_ids: Vec<MerchantId>
merchant_ids: Vec<id_type::MerchantId>,
},
/// ProfileLevel: Authentication at the profile level
ProfileLevel {
/// org_id: OrganizationId
org_id: id_type::OrganizationId,
/// merchant_id: MerchantId
merchant_id: id_type::MerchantId,
/// profile_ids: Vec<ProfileId>
profile_ids: Vec<id_type::ProfileId>,
},
}
/// Enum for different resource types supported in client secret
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ResourceId {
/// Global Payment ID (Not exposed in api_models version of enum)
Payment(id_type::GlobalPaymentId),
/// Global Customer ID
Customer(id_type::GlobalCustomerId),
/// Global Payment Methods Session ID
PaymentMethodSession(id_type::GlobalPaymentMethodSessionId),
}
#[cfg(feature = "v2")]
impl ResourceId {
/// Get string representation of enclosed ID type
pub fn to_str(&self) -> &str {
match self {
Self::Payment(id) => id.get_string_repr(),
Self::Customer(id) => id.get_string_repr(),
Self::PaymentMethodSession(id) => id.get_string_repr(),
}
}
}
| {
"crate": "common_utils",
"file": "crates/common_utils/src/types/authentication.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_hyperswitch_domain_models_-8818908692104103279 | clm | file | // Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/lib.rs
// Contains: 0 structs, 1 enums
pub mod address;
pub mod api;
pub mod authentication;
pub mod behaviour;
pub mod bulk_tokenization;
pub mod business_profile;
pub mod callback_mapper;
pub mod card_testing_guard_data;
pub mod cards_info;
pub mod chat;
pub mod configs;
pub mod connector_endpoints;
pub mod consts;
pub mod customer;
pub mod disputes;
pub mod errors;
pub mod ext_traits;
pub mod gsm;
pub mod invoice;
pub mod mandates;
pub mod master_key;
pub mod merchant_account;
pub mod merchant_connector_account;
pub mod merchant_context;
pub mod merchant_key_store;
pub mod network_tokenization;
pub mod payment_address;
pub mod payment_method_data;
pub mod payment_methods;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payouts;
pub mod refunds;
pub mod relay;
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
pub mod revenue_recovery;
pub mod router_data;
pub mod router_data_v2;
pub mod router_flow_types;
pub mod router_request_types;
pub mod router_response_types;
pub mod routing;
pub mod subscription;
#[cfg(feature = "tokenization_v2")]
pub mod tokenization;
pub mod transformers;
pub mod type_encryption;
pub mod types;
pub mod vault;
#[cfg(not(feature = "payouts"))]
pub trait PayoutAttemptInterface {}
#[cfg(not(feature = "payouts"))]
pub trait PayoutsInterface {}
use api_models::payments::{
ApplePayRecurringDetails as ApiApplePayRecurringDetails,
ApplePayRegularBillingDetails as ApiApplePayRegularBillingDetails,
FeatureMetadata as ApiFeatureMetadata, OrderDetailsWithAmount as ApiOrderDetailsWithAmount,
RecurringPaymentIntervalUnit as ApiRecurringPaymentIntervalUnit,
RedirectResponse as ApiRedirectResponse,
};
#[cfg(feature = "v2")]
use api_models::payments::{
BillingConnectorAdditionalCardInfo as ApiBillingConnectorAdditionalCardInfo,
BillingConnectorPaymentDetails as ApiBillingConnectorPaymentDetails,
BillingConnectorPaymentMethodDetails as ApiBillingConnectorPaymentMethodDetails,
PaymentRevenueRecoveryMetadata as ApiRevenueRecoveryMetadata,
};
use diesel_models::types::{
ApplePayRecurringDetails, ApplePayRegularBillingDetails, FeatureMetadata,
OrderDetailsWithAmount, RecurringPaymentIntervalUnit, RedirectResponse,
};
#[cfg(feature = "v2")]
use diesel_models::types::{
BillingConnectorAdditionalCardInfo, BillingConnectorPaymentDetails,
BillingConnectorPaymentMethodDetails, PaymentRevenueRecoveryMetadata,
};
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
pub enum RemoteStorageObject<T: ForeignIDRef> {
ForeignID(String),
Object(T),
}
impl<T: ForeignIDRef> From<T> for RemoteStorageObject<T> {
fn from(value: T) -> Self {
Self::Object(value)
}
}
pub trait ForeignIDRef {
fn foreign_id(&self) -> String;
}
impl<T: ForeignIDRef> RemoteStorageObject<T> {
pub fn get_id(&self) -> String {
match self {
Self::ForeignID(id) => id.clone(),
Self::Object(i) => i.foreign_id(),
}
}
}
use std::fmt::Debug;
pub trait ApiModelToDieselModelConvertor<F> {
/// Convert from a foreign type to the current type
fn convert_from(from: F) -> Self;
fn convert_back(self) -> F;
}
#[cfg(feature = "v1")]
impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata {
fn convert_from(from: ApiFeatureMetadata) -> Self {
let ApiFeatureMetadata {
redirect_response,
search_tags,
apple_pay_recurring_details,
} = from;
Self {
redirect_response: redirect_response.map(RedirectResponse::convert_from),
search_tags,
apple_pay_recurring_details: apple_pay_recurring_details
.map(ApplePayRecurringDetails::convert_from),
gateway_system: None,
}
}
fn convert_back(self) -> ApiFeatureMetadata {
let Self {
redirect_response,
search_tags,
apple_pay_recurring_details,
..
} = self;
ApiFeatureMetadata {
redirect_response: redirect_response
.map(|redirect_response| redirect_response.convert_back()),
search_tags,
apple_pay_recurring_details: apple_pay_recurring_details
.map(|value| value.convert_back()),
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata {
fn convert_from(from: ApiFeatureMetadata) -> Self {
let ApiFeatureMetadata {
redirect_response,
search_tags,
apple_pay_recurring_details,
revenue_recovery: payment_revenue_recovery_metadata,
} = from;
Self {
redirect_response: redirect_response.map(RedirectResponse::convert_from),
search_tags,
apple_pay_recurring_details: apple_pay_recurring_details
.map(ApplePayRecurringDetails::convert_from),
payment_revenue_recovery_metadata: payment_revenue_recovery_metadata
.map(PaymentRevenueRecoveryMetadata::convert_from),
}
}
fn convert_back(self) -> ApiFeatureMetadata {
let Self {
redirect_response,
search_tags,
apple_pay_recurring_details,
payment_revenue_recovery_metadata,
} = self;
ApiFeatureMetadata {
redirect_response: redirect_response
.map(|redirect_response| redirect_response.convert_back()),
search_tags,
apple_pay_recurring_details: apple_pay_recurring_details
.map(|value| value.convert_back()),
revenue_recovery: payment_revenue_recovery_metadata.map(|value| value.convert_back()),
}
}
}
impl ApiModelToDieselModelConvertor<ApiRedirectResponse> for RedirectResponse {
fn convert_from(from: ApiRedirectResponse) -> Self {
let ApiRedirectResponse {
param,
json_payload,
} = from;
Self {
param,
json_payload,
}
}
fn convert_back(self) -> ApiRedirectResponse {
let Self {
param,
json_payload,
} = self;
ApiRedirectResponse {
param,
json_payload,
}
}
}
impl ApiModelToDieselModelConvertor<ApiRecurringPaymentIntervalUnit>
for RecurringPaymentIntervalUnit
{
fn convert_from(from: ApiRecurringPaymentIntervalUnit) -> Self {
match from {
ApiRecurringPaymentIntervalUnit::Year => Self::Year,
ApiRecurringPaymentIntervalUnit::Month => Self::Month,
ApiRecurringPaymentIntervalUnit::Day => Self::Day,
ApiRecurringPaymentIntervalUnit::Hour => Self::Hour,
ApiRecurringPaymentIntervalUnit::Minute => Self::Minute,
}
}
fn convert_back(self) -> ApiRecurringPaymentIntervalUnit {
match self {
Self::Year => ApiRecurringPaymentIntervalUnit::Year,
Self::Month => ApiRecurringPaymentIntervalUnit::Month,
Self::Day => ApiRecurringPaymentIntervalUnit::Day,
Self::Hour => ApiRecurringPaymentIntervalUnit::Hour,
Self::Minute => ApiRecurringPaymentIntervalUnit::Minute,
}
}
}
impl ApiModelToDieselModelConvertor<ApiApplePayRegularBillingDetails>
for ApplePayRegularBillingDetails
{
fn convert_from(from: ApiApplePayRegularBillingDetails) -> Self {
Self {
label: from.label,
recurring_payment_start_date: from.recurring_payment_start_date,
recurring_payment_end_date: from.recurring_payment_end_date,
recurring_payment_interval_unit: from
.recurring_payment_interval_unit
.map(RecurringPaymentIntervalUnit::convert_from),
recurring_payment_interval_count: from.recurring_payment_interval_count,
}
}
fn convert_back(self) -> ApiApplePayRegularBillingDetails {
ApiApplePayRegularBillingDetails {
label: self.label,
recurring_payment_start_date: self.recurring_payment_start_date,
recurring_payment_end_date: self.recurring_payment_end_date,
recurring_payment_interval_unit: self
.recurring_payment_interval_unit
.map(|value| value.convert_back()),
recurring_payment_interval_count: self.recurring_payment_interval_count,
}
}
}
impl ApiModelToDieselModelConvertor<ApiApplePayRecurringDetails> for ApplePayRecurringDetails {
fn convert_from(from: ApiApplePayRecurringDetails) -> Self {
Self {
payment_description: from.payment_description,
regular_billing: ApplePayRegularBillingDetails::convert_from(from.regular_billing),
billing_agreement: from.billing_agreement,
management_url: from.management_url,
}
}
fn convert_back(self) -> ApiApplePayRecurringDetails {
ApiApplePayRecurringDetails {
payment_description: self.payment_description,
regular_billing: self.regular_billing.convert_back(),
billing_agreement: self.billing_agreement,
management_url: self.management_url,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<ApiBillingConnectorAdditionalCardInfo>
for BillingConnectorAdditionalCardInfo
{
fn convert_from(from: ApiBillingConnectorAdditionalCardInfo) -> Self {
Self {
card_issuer: from.card_issuer,
card_network: from.card_network,
}
}
fn convert_back(self) -> ApiBillingConnectorAdditionalCardInfo {
ApiBillingConnectorAdditionalCardInfo {
card_issuer: self.card_issuer,
card_network: self.card_network,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<ApiBillingConnectorPaymentMethodDetails>
for BillingConnectorPaymentMethodDetails
{
fn convert_from(from: ApiBillingConnectorPaymentMethodDetails) -> Self {
match from {
ApiBillingConnectorPaymentMethodDetails::Card(data) => {
Self::Card(BillingConnectorAdditionalCardInfo::convert_from(data))
}
}
}
fn convert_back(self) -> ApiBillingConnectorPaymentMethodDetails {
match self {
Self::Card(data) => ApiBillingConnectorPaymentMethodDetails::Card(data.convert_back()),
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentRevenueRecoveryMetadata {
fn convert_from(from: ApiRevenueRecoveryMetadata) -> Self {
Self {
total_retry_count: from.total_retry_count,
payment_connector_transmission: from.payment_connector_transmission.unwrap_or_default(),
billing_connector_id: from.billing_connector_id,
active_attempt_payment_connector_id: from.active_attempt_payment_connector_id,
billing_connector_payment_details: BillingConnectorPaymentDetails::convert_from(
from.billing_connector_payment_details,
),
payment_method_type: from.payment_method_type,
payment_method_subtype: from.payment_method_subtype,
connector: from.connector,
invoice_next_billing_time: from.invoice_next_billing_time,
billing_connector_payment_method_details: from
.billing_connector_payment_method_details
.map(BillingConnectorPaymentMethodDetails::convert_from),
first_payment_attempt_network_advice_code: from
.first_payment_attempt_network_advice_code,
first_payment_attempt_network_decline_code: from
.first_payment_attempt_network_decline_code,
first_payment_attempt_pg_error_code: from.first_payment_attempt_pg_error_code,
invoice_billing_started_at_time: from.invoice_billing_started_at_time,
}
}
fn convert_back(self) -> ApiRevenueRecoveryMetadata {
ApiRevenueRecoveryMetadata {
total_retry_count: self.total_retry_count,
payment_connector_transmission: Some(self.payment_connector_transmission),
billing_connector_id: self.billing_connector_id,
active_attempt_payment_connector_id: self.active_attempt_payment_connector_id,
billing_connector_payment_details: self
.billing_connector_payment_details
.convert_back(),
payment_method_type: self.payment_method_type,
payment_method_subtype: self.payment_method_subtype,
connector: self.connector,
invoice_next_billing_time: self.invoice_next_billing_time,
billing_connector_payment_method_details: self
.billing_connector_payment_method_details
.map(|data| data.convert_back()),
first_payment_attempt_network_advice_code: self
.first_payment_attempt_network_advice_code,
first_payment_attempt_network_decline_code: self
.first_payment_attempt_network_decline_code,
first_payment_attempt_pg_error_code: self.first_payment_attempt_pg_error_code,
invoice_billing_started_at_time: self.invoice_billing_started_at_time,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<ApiBillingConnectorPaymentDetails>
for BillingConnectorPaymentDetails
{
fn convert_from(from: ApiBillingConnectorPaymentDetails) -> Self {
Self {
payment_processor_token: from.payment_processor_token,
connector_customer_id: from.connector_customer_id,
}
}
fn convert_back(self) -> ApiBillingConnectorPaymentDetails {
ApiBillingConnectorPaymentDetails {
payment_processor_token: self.payment_processor_token,
connector_customer_id: self.connector_customer_id,
}
}
}
impl ApiModelToDieselModelConvertor<ApiOrderDetailsWithAmount> for OrderDetailsWithAmount {
fn convert_from(from: ApiOrderDetailsWithAmount) -> Self {
let ApiOrderDetailsWithAmount {
product_name,
quantity,
amount,
requires_shipping,
product_img_link,
product_id,
category,
sub_category,
brand,
product_type,
product_tax_code,
tax_rate,
total_tax_amount,
description,
sku,
upc,
commodity_code,
unit_of_measure,
total_amount,
unit_discount_amount,
} = from;
Self {
product_name,
quantity,
amount,
requires_shipping,
product_img_link,
product_id,
category,
sub_category,
brand,
product_type,
product_tax_code,
tax_rate,
total_tax_amount,
description,
sku,
upc,
commodity_code,
unit_of_measure,
total_amount,
unit_discount_amount,
}
}
fn convert_back(self) -> ApiOrderDetailsWithAmount {
let Self {
product_name,
quantity,
amount,
requires_shipping,
product_img_link,
product_id,
category,
sub_category,
brand,
product_type,
product_tax_code,
tax_rate,
total_tax_amount,
description,
sku,
upc,
commodity_code,
unit_of_measure,
total_amount,
unit_discount_amount,
} = self;
ApiOrderDetailsWithAmount {
product_name,
quantity,
amount,
requires_shipping,
product_img_link,
product_id,
category,
sub_category,
brand,
product_type,
product_tax_code,
tax_rate,
total_tax_amount,
description,
sku,
upc,
commodity_code,
unit_of_measure,
total_amount,
unit_discount_amount,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest>
for diesel_models::payment_intent::PaymentLinkConfigRequestForPayments
{
fn convert_from(item: api_models::admin::PaymentLinkConfigRequest) -> Self {
Self {
theme: item.theme,
logo: item.logo,
seller_name: item.seller_name,
sdk_layout: item.sdk_layout,
display_sdk_only: item.display_sdk_only,
enabled_saved_payment_method: item.enabled_saved_payment_method,
hide_card_nickname_field: item.hide_card_nickname_field,
show_card_form_by_default: item.show_card_form_by_default,
details_layout: item.details_layout,
transaction_details: item.transaction_details.map(|transaction_details| {
transaction_details
.into_iter()
.map(|transaction_detail| {
diesel_models::PaymentLinkTransactionDetails::convert_from(
transaction_detail,
)
})
.collect()
}),
background_image: item.background_image.map(|background_image| {
diesel_models::business_profile::PaymentLinkBackgroundImageConfig::convert_from(
background_image,
)
}),
payment_button_text: item.payment_button_text,
custom_message_for_card_terms: item.custom_message_for_card_terms,
payment_button_colour: item.payment_button_colour,
skip_status_screen: item.skip_status_screen,
background_colour: item.background_colour,
payment_button_text_colour: item.payment_button_text_colour,
sdk_ui_rules: item.sdk_ui_rules,
payment_link_ui_rules: item.payment_link_ui_rules,
enable_button_only_on_form_ready: item.enable_button_only_on_form_ready,
payment_form_header_text: item.payment_form_header_text,
payment_form_label_type: item.payment_form_label_type,
show_card_terms: item.show_card_terms,
is_setup_mandate_flow: item.is_setup_mandate_flow,
color_icon_card_cvc_error: item.color_icon_card_cvc_error,
}
}
fn convert_back(self) -> api_models::admin::PaymentLinkConfigRequest {
let Self {
theme,
logo,
seller_name,
sdk_layout,
display_sdk_only,
enabled_saved_payment_method,
hide_card_nickname_field,
show_card_form_by_default,
transaction_details,
background_image,
details_layout,
payment_button_text,
custom_message_for_card_terms,
payment_button_colour,
skip_status_screen,
background_colour,
payment_button_text_colour,
sdk_ui_rules,
payment_link_ui_rules,
enable_button_only_on_form_ready,
payment_form_header_text,
payment_form_label_type,
show_card_terms,
is_setup_mandate_flow,
color_icon_card_cvc_error,
} = self;
api_models::admin::PaymentLinkConfigRequest {
theme,
logo,
seller_name,
sdk_layout,
display_sdk_only,
enabled_saved_payment_method,
hide_card_nickname_field,
show_card_form_by_default,
details_layout,
transaction_details: transaction_details.map(|transaction_details| {
transaction_details
.into_iter()
.map(|transaction_detail| transaction_detail.convert_back())
.collect()
}),
background_image: background_image
.map(|background_image| background_image.convert_back()),
payment_button_text,
custom_message_for_card_terms,
payment_button_colour,
skip_status_screen,
background_colour,
payment_button_text_colour,
sdk_ui_rules,
payment_link_ui_rules,
enable_button_only_on_form_ready,
payment_form_header_text,
payment_form_label_type,
show_card_terms,
is_setup_mandate_flow,
color_icon_card_cvc_error,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkTransactionDetails>
for diesel_models::PaymentLinkTransactionDetails
{
fn convert_from(from: api_models::admin::PaymentLinkTransactionDetails) -> Self {
Self {
key: from.key,
value: from.value,
ui_configuration: from
.ui_configuration
.map(diesel_models::TransactionDetailsUiConfiguration::convert_from),
}
}
fn convert_back(self) -> api_models::admin::PaymentLinkTransactionDetails {
let Self {
key,
value,
ui_configuration,
} = self;
api_models::admin::PaymentLinkTransactionDetails {
key,
value,
ui_configuration: ui_configuration
.map(|ui_configuration| ui_configuration.convert_back()),
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkBackgroundImageConfig>
for diesel_models::business_profile::PaymentLinkBackgroundImageConfig
{
fn convert_from(from: api_models::admin::PaymentLinkBackgroundImageConfig) -> Self {
Self {
url: from.url,
position: from.position,
size: from.size,
}
}
fn convert_back(self) -> api_models::admin::PaymentLinkBackgroundImageConfig {
let Self {
url,
position,
size,
} = self;
api_models::admin::PaymentLinkBackgroundImageConfig {
url,
position,
size,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<api_models::admin::TransactionDetailsUiConfiguration>
for diesel_models::TransactionDetailsUiConfiguration
{
fn convert_from(from: api_models::admin::TransactionDetailsUiConfiguration) -> Self {
Self {
position: from.position,
is_key_bold: from.is_key_bold,
is_value_bold: from.is_value_bold,
}
}
fn convert_back(self) -> api_models::admin::TransactionDetailsUiConfiguration {
let Self {
position,
is_key_bold,
is_value_bold,
} = self;
api_models::admin::TransactionDetailsUiConfiguration {
position,
is_key_bold,
is_value_bold,
}
}
}
#[cfg(feature = "v2")]
impl From<api_models::payments::AmountDetails> for payments::AmountDetails {
fn from(amount_details: api_models::payments::AmountDetails) -> Self {
Self {
order_amount: amount_details.order_amount().into(),
currency: amount_details.currency(),
shipping_cost: amount_details.shipping_cost(),
tax_details: amount_details.order_tax_amount().map(|order_tax_amount| {
diesel_models::TaxDetails {
default: Some(diesel_models::DefaultTax { order_tax_amount }),
payment_method_type: None,
}
}),
skip_external_tax_calculation: amount_details.skip_external_tax_calculation(),
skip_surcharge_calculation: amount_details.skip_surcharge_calculation(),
surcharge_amount: amount_details.surcharge_amount(),
tax_on_surcharge: amount_details.tax_on_surcharge(),
// We will not receive this in the request. This will be populated after calling the connector / processor
amount_captured: None,
}
}
}
#[cfg(feature = "v2")]
impl From<payments::AmountDetails> for api_models::payments::AmountDetailsSetter {
fn from(amount_details: payments::AmountDetails) -> Self {
Self {
order_amount: amount_details.order_amount.into(),
currency: amount_details.currency,
shipping_cost: amount_details.shipping_cost,
order_tax_amount: amount_details
.tax_details
.and_then(|tax_detail| tax_detail.get_default_tax_amount()),
skip_external_tax_calculation: amount_details.skip_external_tax_calculation,
skip_surcharge_calculation: amount_details.skip_surcharge_calculation,
surcharge_amount: amount_details.surcharge_amount,
tax_on_surcharge: amount_details.tax_on_surcharge,
}
}
}
#[cfg(feature = "v2")]
impl From<&api_models::payments::PaymentAttemptAmountDetails>
for payments::payment_attempt::AttemptAmountDetailsSetter
{
fn from(amount: &api_models::payments::PaymentAttemptAmountDetails) -> Self {
Self {
net_amount: amount.net_amount,
amount_to_capture: amount.amount_to_capture,
surcharge_amount: amount.surcharge_amount,
tax_on_surcharge: amount.tax_on_surcharge,
amount_capturable: amount.amount_capturable,
shipping_cost: amount.shipping_cost,
order_tax_amount: amount.order_tax_amount,
}
}
}
#[cfg(feature = "v2")]
impl From<&payments::payment_attempt::AttemptAmountDetailsSetter>
for api_models::payments::PaymentAttemptAmountDetails
{
fn from(amount: &payments::payment_attempt::AttemptAmountDetailsSetter) -> Self {
Self {
net_amount: amount.net_amount,
amount_to_capture: amount.amount_to_capture,
surcharge_amount: amount.surcharge_amount,
tax_on_surcharge: amount.tax_on_surcharge,
amount_capturable: amount.amount_capturable,
shipping_cost: amount.shipping_cost,
order_tax_amount: amount.order_tax_amount,
}
}
}
#[cfg(feature = "v2")]
impl From<&api_models::payments::RecordAttemptErrorDetails>
for payments::payment_attempt::ErrorDetails
{
fn from(error: &api_models::payments::RecordAttemptErrorDetails) -> Self {
Self {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message.clone()),
unified_code: None,
unified_message: None,
network_advice_code: error.network_advice_code.clone(),
network_decline_code: error.network_decline_code.clone(),
network_error_message: error.network_error_message.clone(),
}
}
}
| {
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/lib.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_hyperswitch_domain_models_7493760414875075975 | clm | file | // Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/vault.rs
// Contains: 0 structs, 1 enums
use api_models::payment_methods;
#[cfg(feature = "v2")]
use error_stack;
use serde::{Deserialize, Serialize};
#[cfg(feature = "v2")]
use crate::errors;
use crate::payment_method_data;
#[derive(Debug, Deserialize, Serialize, Clone)]
pub enum PaymentMethodVaultingData {
Card(payment_methods::CardDetail),
#[cfg(feature = "v2")]
NetworkToken(payment_method_data::NetworkTokenDetails),
CardNumber(cards::CardNumber),
}
impl PaymentMethodVaultingData {
pub fn get_card(&self) -> Option<&payment_methods::CardDetail> {
match self {
Self::Card(card) => Some(card),
#[cfg(feature = "v2")]
Self::NetworkToken(_) => None,
Self::CardNumber(_) => None,
}
}
pub fn get_payment_methods_data(&self) -> payment_method_data::PaymentMethodsData {
match self {
Self::Card(card) => payment_method_data::PaymentMethodsData::Card(
payment_method_data::CardDetailsPaymentMethod::from(card.clone()),
),
#[cfg(feature = "v2")]
Self::NetworkToken(network_token) => {
payment_method_data::PaymentMethodsData::NetworkToken(
payment_method_data::NetworkTokenDetailsPaymentMethod::from(
network_token.clone(),
),
)
}
Self::CardNumber(_card_number) => payment_method_data::PaymentMethodsData::Card(
payment_method_data::CardDetailsPaymentMethod {
last4_digits: None,
issuer_country: None,
expiry_month: None,
expiry_year: None,
nick_name: None,
card_holder_name: None,
card_isin: None,
card_issuer: None,
card_network: None,
card_type: None,
saved_to_locker: false,
#[cfg(feature = "v1")]
co_badged_card_data: None,
},
),
}
}
}
pub trait VaultingDataInterface {
fn get_vaulting_data_key(&self) -> String;
}
impl VaultingDataInterface for PaymentMethodVaultingData {
fn get_vaulting_data_key(&self) -> String {
match &self {
Self::Card(card) => card.card_number.to_string(),
#[cfg(feature = "v2")]
Self::NetworkToken(network_token) => network_token.network_token.to_string(),
Self::CardNumber(card_number) => card_number.to_string(),
}
}
}
#[cfg(feature = "v2")]
impl TryFrom<payment_methods::PaymentMethodCreateData> for PaymentMethodVaultingData {
type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>;
fn try_from(item: payment_methods::PaymentMethodCreateData) -> Result<Self, Self::Error> {
match item {
payment_methods::PaymentMethodCreateData::Card(card) => Ok(Self::Card(card)),
payment_methods::PaymentMethodCreateData::ProxyCard(card) => Err(
errors::api_error_response::ApiErrorResponse::UnprocessableEntity {
message: "Proxy Card for PaymentMethodCreateData".to_string(),
}
.into(),
),
}
}
}
| {
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/vault.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_hyperswitch_domain_models_8584568522995261952 | clm | file | // Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_response_types/fraud_check.rs
// Contains: 0 structs, 1 enums
use serde::Serialize;
use crate::router_response_types::ResponseId;
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum FraudCheckResponseData {
TransactionResponse {
resource_id: ResponseId,
status: diesel_models::enums::FraudCheckStatus,
connector_metadata: Option<serde_json::Value>,
reason: Option<serde_json::Value>,
score: Option<i32>,
},
FulfillmentResponse {
order_id: String,
shipment_ids: Vec<String>,
},
RecordReturnResponse {
resource_id: ResponseId,
connector_metadata: Option<serde_json::Value>,
return_id: Option<String>,
},
}
impl common_utils::events::ApiEventMetric for FraudCheckResponseData {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::FraudCheck)
}
}
| {
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_response_types/fraud_check.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_hyperswitch_domain_models_-4271311096126242454 | clm | file | // Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/errors/api_error_response.rs
// Contains: 0 structs, 3 enums
use api_models::errors::types::Extra;
use common_utils::errors::ErrorSwitch;
use http::StatusCode;
use crate::router_data;
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorType {
InvalidRequestError,
ObjectNotFound,
RouterError,
ProcessingError,
BadGateway,
ServerNotAvailable,
DuplicateRequest,
ValidationError,
ConnectorError,
LockTimeout,
}
// CE Connector Error Errors originating from connector's end
// HE Hyperswitch Error Errors originating from Hyperswitch's end
// IR Invalid Request Error Error caused due to invalid fields and values in API request
// WE Webhook Error Errors related to Webhooks
#[derive(Debug, Clone, router_derive::ApiError)]
#[error(error_type_enum = ErrorType)]
pub enum ApiErrorResponse {
#[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "{code}: {message}", ignore = "status_code")]
ExternalConnectorError {
code: String,
message: String,
connector: String,
status_code: u16,
reason: Option<String>,
},
#[error(error_type = ErrorType::ProcessingError, code = "CE_01", message = "Payment failed during authorization with connector. Retry payment")]
PaymentAuthorizationFailed { data: Option<serde_json::Value> },
#[error(error_type = ErrorType::ProcessingError, code = "CE_02", message = "Payment failed during authentication with connector. Retry payment")]
PaymentAuthenticationFailed { data: Option<serde_json::Value> },
#[error(error_type = ErrorType::ProcessingError, code = "CE_03", message = "Capture attempt failed while processing with connector")]
PaymentCaptureFailed { data: Option<serde_json::Value> },
#[error(error_type = ErrorType::ProcessingError, code = "CE_04", message = "The card data is invalid")]
InvalidCardData { data: Option<serde_json::Value> },
#[error(error_type = ErrorType::ProcessingError, code = "CE_05", message = "The card has expired")]
CardExpired { data: Option<serde_json::Value> },
#[error(error_type = ErrorType::ProcessingError, code = "CE_06", message = "Refund failed while processing with connector. Retry refund")]
RefundFailed { data: Option<serde_json::Value> },
#[error(error_type = ErrorType::ProcessingError, code = "CE_07", message = "Verification failed while processing with connector. Retry operation")]
VerificationFailed { data: Option<serde_json::Value> },
#[error(error_type = ErrorType::ProcessingError, code = "CE_08", message = "Dispute operation failed while processing with connector. Retry operation")]
DisputeFailed { data: Option<serde_json::Value> },
#[error(error_type = ErrorType::LockTimeout, code = "HE_00", message = "Resource is busy. Please try again later.")]
ResourceBusy,
#[error(error_type = ErrorType::ServerNotAvailable, code = "HE_00", message = "Something went wrong")]
InternalServerError,
#[error(error_type = ErrorType::ServerNotAvailable, code= "HE_00", message = "{component} health check is failing with error: {message}")]
HealthCheckError {
component: &'static str,
message: String,
},
#[error(error_type = ErrorType::ValidationError, code = "HE_00", message = "Failed to convert currency to minor unit")]
CurrencyConversionFailed,
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate refund request. Refund already attempted with the refund ID")]
DuplicateRefundRequest,
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID")]
DuplicateMandate,
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant account with the specified details already exists in our records")]
DuplicateMerchantAccount,
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", 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 = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment method with the specified details already exists in our records")]
DuplicatePaymentMethod,
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment with the specified payment_id already exists in our records")]
DuplicatePayment {
payment_id: common_utils::id_type::PaymentId,
},
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payout with the specified payout_id '{payout_id:?}' already exists in our records")]
DuplicatePayout {
payout_id: common_utils::id_type::PayoutId,
},
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The config with the specified key already exists in our records")]
DuplicateConfig,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Refund does not exist in our records")]
RefundNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment Link does not exist in our records")]
PaymentLinkNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Customer does not exist in our records")]
CustomerNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Config key does not exist in our records.")]
ConfigNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment does not exist in our records")]
PaymentNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment method does not exist in our records")]
PaymentMethodNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant account does not exist in our records")]
MerchantAccountNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant connector account does not exist in our records")]
MerchantConnectorAccountNotFound { id: String },
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Business profile with the given id '{id}' does not exist in our records")]
ProfileNotFound { id: String },
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Profile acquirer with id '{profile_acquirer_id}' not found for profile '{profile_id}'.")]
ProfileAcquirerNotFound {
profile_acquirer_id: String,
profile_id: String,
},
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Poll with the given id '{id}' does not exist in our records")]
PollNotFound { id: String },
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Resource ID does not exist in our records")]
ResourceIdNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Mandate does not exist in our records")]
MandateNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Authentication does not exist in our records")]
AuthenticationNotFound { id: String },
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Failed to update mandate")]
MandateUpdateFailed,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "API Key does not exist in our records")]
ApiKeyNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payout does not exist in our records")]
PayoutNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Event does not exist in our records")]
EventNotFound,
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Invalid mandate id passed from connector")]
MandateSerializationFailed,
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Unable to parse the mandate identifier passed from connector")]
MandateDeserializationFailed,
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Return URL is not configured and not passed in payments request")]
ReturnUrlUnavailable,
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard")]
RefundNotPossible { connector: String },
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Mandate Validation Failed" )]
MandateValidationFailed { reason: String },
#[error(error_type= ErrorType::ValidationError, code = "HE_03", message = "The payment has not succeeded yet. Please pass a successful payment to initiate refund")]
PaymentNotSucceeded,
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "The specified merchant connector account is disabled")]
MerchantConnectorAccountDisabled,
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "{code}: {message}")]
PaymentBlockedError {
code: u16,
message: String,
status: String,
reason: String,
},
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "File validation failed")]
FileValidationFailed { reason: String },
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Dispute status validation failed")]
DisputeStatusValidationFailed { reason: String },
#[error(error_type= ErrorType::ObjectNotFound, code = "HE_04", message = "Successful payment not found for the given payment id")]
SuccessfulPaymentNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "The connector provided in the request is incorrect or not available")]
IncorrectConnectorNameGiven,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "Address does not exist in our records")]
AddressNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "Dispute does not exist in our records")]
DisputeNotFound { dispute_id: String },
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "File does not exist in our records")]
FileNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "File not available")]
FileNotAvailable,
#[error(error_type = ErrorType::ProcessingError, code = "HE_05", message = "Missing tenant id")]
MissingTenantId,
#[error(error_type = ErrorType::ProcessingError, code = "HE_05", message = "Invalid tenant id: {tenant_id}")]
InvalidTenant { tenant_id: String },
#[error(error_type = ErrorType::ValidationError, code = "HE_06", message = "Failed to convert amount to {amount_type} type")]
AmountConversionFailed { amount_type: &'static str },
#[error(error_type = ErrorType::ServerNotAvailable, code = "IR_00", message = "{message:?}")]
NotImplemented { message: NotImplementedMessage },
#[error(
error_type = ErrorType::InvalidRequestError, code = "IR_01",
message = "API key not provided or invalid API key used"
)]
Unauthorized,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_02", message = "Unrecognized request URL")]
InvalidRequestUrl,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_03", message = "The HTTP method is not applicable for this API")]
InvalidHttpMethod,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_04", message = "Missing required param: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error(
error_type = ErrorType::InvalidRequestError, code = "IR_05",
message = "{field_name} contains invalid data. Expected format is {expected_format}"
)]
InvalidDataFormat {
field_name: String,
expected_format: String,
},
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_06", message = "{message}")]
InvalidRequestData { message: String },
/// Typically used when a field has invalid value, or deserialization of the value contained in a field fails.
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_07", message = "Invalid value provided: {field_name}")]
InvalidDataValue { field_name: &'static str },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret was not provided")]
ClientSecretNotGiven,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret has expired")]
ClientSecretExpired,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_09", message = "The client_secret provided does not match the client_secret associated with the Payment")]
ClientSecretInvalid,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_10", message = "Customer has active mandate/subsciption")]
MandateActive,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_11", message = "Customer has already been redacted")]
CustomerRedacted,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_12", message = "Reached maximum refund attempts")]
MaximumRefundCount,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_13", message = "The refund amount exceeds the amount captured")]
RefundAmountExceedsPaymentAmount,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_14", message = "This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}")]
PaymentUnexpectedState {
current_flow: String,
field_name: String,
current_value: String,
states: String,
},
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_15", message = "Invalid Ephemeral Key for the customer")]
InvalidEphemeralKey,
/// Typically used when information involving multiple fields or previously provided information doesn't satisfy a condition.
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_16", message = "{message}")]
PreconditionFailed { message: String },
#[error(
error_type = ErrorType::InvalidRequestError, code = "IR_17",
message = "Access forbidden, invalid JWT token was used"
)]
InvalidJwtToken,
#[error(
error_type = ErrorType::InvalidRequestError, code = "IR_18",
message = "{message}",
)]
GenericUnauthorized { message: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")]
NotSupported { message: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_20", message = "{flow} flow not supported by the {connector} connector")]
FlowNotSupported { flow: String, connector: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_21", message = "Missing required params")]
MissingRequiredFields { field_names: Vec<&'static str> },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_22", message = "Access forbidden. Not authorized to access this resource {resource}")]
AccessForbidden { resource: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_23", message = "{message}")]
FileProviderNotSupported { message: String },
#[error(
error_type = ErrorType::ProcessingError, code = "IR_24",
message = "Invalid {wallet_name} wallet token"
)]
InvalidWalletToken { wallet_name: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")]
PaymentMethodDeleteFailed,
#[error(
error_type = ErrorType::InvalidRequestError, code = "IR_26",
message = "Invalid Cookie"
)]
InvalidCookie,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_27", message = "Extended card info does not exist")]
ExtendedCardInfoNotFound,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_28", message = "{message}")]
CurrencyNotSupported { message: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_29", message = "{message}")]
UnprocessableEntity { message: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_30", message = "Merchant connector account is configured with invalid {config}")]
InvalidConnectorConfiguration { config: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_31", message = "Card with the provided iin does not exist")]
InvalidCardIin,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_32", message = "The provided card IIN length is invalid, please provide an iin with 6 or 8 digits")]
InvalidCardIinLength,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_33", message = "File not found / valid in the request")]
MissingFile,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_34", message = "Dispute id not found in the request")]
MissingDisputeId,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_35", message = "File purpose not found in the request or is invalid")]
MissingFilePurpose,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_36", message = "File content type not found / valid")]
MissingFileContentType,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_37", message = "{message}")]
GenericNotFoundError { message: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_38", message = "{message}")]
GenericDuplicateError { message: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_39", message = "required payment method is not configured or configured incorrectly for all configured connectors")]
IncorrectPaymentMethodConfiguration,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_40", message = "{message}")]
LinkConfigurationError { message: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_41", message = "Payout validation failed")]
PayoutFailed { data: Option<serde_json::Value> },
#[error(
error_type = ErrorType::InvalidRequestError, code = "IR_42",
message = "Cookies are not found in the request"
)]
CookieNotFound,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_43", message = "API does not support platform account operation")]
PlatformAccountAuthNotSupported,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_44", message = "Invalid platform account operation")]
InvalidPlatformOperation,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_45", message = "External vault failed during processing with connector")]
ExternalVaultFailed,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_46", message = "Field {fields} doesn't match with the ones used during mandate creation")]
MandatePaymentDataMismatch { fields: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_47", message = "Connector '{connector}' rejected field '{field_name}': length {received_length} exceeds maximum of {max_length}")]
MaxFieldLengthViolated {
connector: String,
field_name: String,
max_length: usize,
received_length: usize,
},
#[error(error_type = ErrorType::InvalidRequestError, code = "WE_01", message = "Failed to authenticate the webhook")]
WebhookAuthenticationFailed,
#[error(error_type = ErrorType::InvalidRequestError, code = "WE_02", message = "Bad request received in webhook")]
WebhookBadRequest,
#[error(error_type = ErrorType::RouterError, code = "WE_03", message = "There was some issue processing the webhook")]
WebhookProcessingFailure,
#[error(error_type = ErrorType::ObjectNotFound, code = "WE_04", message = "Webhook resource not found")]
WebhookResourceNotFound,
#[error(error_type = ErrorType::InvalidRequestError, code = "WE_05", message = "Unable to process the webhook body")]
WebhookUnprocessableEntity,
#[error(error_type = ErrorType::InvalidRequestError, code = "WE_06", message = "Merchant Secret set my merchant for webhook source verification is invalid")]
WebhookInvalidMerchantSecret,
#[error(error_type = ErrorType::ServerNotAvailable, code = "IE", message = "{reason} as data mismatched for {field_names}")]
IntegrityCheckFailed {
reason: String,
field_names: String,
connector_transaction_id: Option<String>,
},
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Tokenization record not found for the given token_id {id}")]
TokenizationRecordNotFound { id: String },
#[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "Subscription operation: {operation} failed with connector")]
SubscriptionError { operation: String },
}
#[derive(Clone)]
pub enum NotImplementedMessage {
Reason(String),
Default,
}
impl std::fmt::Debug for NotImplementedMessage {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Reason(message) => write!(fmt, "{message} is not implemented"),
Self::Default => {
write!(
fmt,
"This API is under development and will be made available soon."
)
}
}
}
}
impl ::core::fmt::Display for ApiErrorResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
r#"{{"error":{}}}"#,
serde_json::to_string(self).unwrap_or_else(|_| "API error response".to_string())
)
}
}
impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponse {
fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
match self {
Self::ExternalConnectorError {
code,
message,
connector,
reason,
status_code,
} => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), reason: reason.to_owned(), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)),
Self::PaymentAuthorizationFailed { data } => {
AER::BadRequest(ApiError::new("CE", 1, "Payment failed during authorization with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()})))
}
Self::PaymentAuthenticationFailed { data } => {
AER::BadRequest(ApiError::new("CE", 2, "Payment failed during authentication with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()})))
}
Self::PaymentCaptureFailed { data } => {
AER::BadRequest(ApiError::new("CE", 3, "Capture attempt failed while processing with connector", Some(Extra { data: data.clone(), ..Default::default()})))
}
Self::InvalidCardData { data } => AER::BadRequest(ApiError::new("CE", 4, "The card data is invalid", Some(Extra { data: data.clone(), ..Default::default()}))),
Self::CardExpired { data } => AER::BadRequest(ApiError::new("CE", 5, "The card has expired", Some(Extra { data: data.clone(), ..Default::default()}))),
Self::RefundFailed { data } => AER::BadRequest(ApiError::new("CE", 6, "Refund failed while processing with connector. Retry refund", Some(Extra { data: data.clone(), ..Default::default()}))),
Self::VerificationFailed { data } => {
AER::BadRequest(ApiError::new("CE", 7, "Verification failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()})))
},
Self::DisputeFailed { data } => {
AER::BadRequest(ApiError::new("CE", 8, "Dispute operation failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()})))
}
Self::ResourceBusy => {
AER::Unprocessable(ApiError::new("HE", 0, "There was an issue processing the webhook body", None))
}
Self::CurrencyConversionFailed => {
AER::Unprocessable(ApiError::new("HE", 0, "Failed to convert currency to minor unit", None))
}
Self::InternalServerError => {
AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None))
},
Self::HealthCheckError { message,component } => {
AER::InternalServerError(ApiError::new("HE",0,format!("{component} health check failed with error: {message}"),None))
},
Self::DuplicateRefundRequest => AER::BadRequest(ApiError::new("HE", 1, "Duplicate refund request. Refund already attempted with the refund ID", None)),
Self::DuplicateMandate => AER::BadRequest(ApiError::new("HE", 1, "Duplicate mandate request. Mandate already attempted with the Mandate ID", None)),
Self::DuplicateMerchantAccount => AER::BadRequest(ApiError::new("HE", 1, "The merchant account with the specified details already exists in our records", None)),
Self::DuplicateMerchantConnectorAccount { profile_id, connector_label: connector_name } => {
AER::BadRequest(ApiError::new("HE", 1, format!("The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_name}' already exists in our records"), None))
}
Self::DuplicatePaymentMethod => AER::BadRequest(ApiError::new("HE", 1, "The payment method with the specified details already exists in our records", None)),
Self::DuplicatePayment { payment_id } => {
AER::BadRequest(ApiError::new("HE", 1, "The payment with the specified payment_id already exists in our records", Some(Extra {reason: Some(format!("{payment_id:?} already exists")), ..Default::default()})))
}
Self::DuplicatePayout { payout_id } => {
AER::BadRequest(ApiError::new("HE", 1, format!("The payout with the specified payout_id '{payout_id:?}' already exists in our records"), None))
}
Self::DuplicateConfig => {
AER::BadRequest(ApiError::new("HE", 1, "The config with the specified key already exists in our records", None))
}
Self::RefundNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Refund does not exist in our records.", None))
}
Self::PaymentLinkNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Payment Link does not exist in our records", None))
}
Self::CustomerNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Customer does not exist in our records", None))
}
Self::ConfigNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Config key does not exist in our records.", None))
},
Self::PaymentNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Payment does not exist in our records", None))
}
Self::PaymentMethodNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Payment method does not exist in our records", None))
}
Self::MerchantAccountNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Merchant account does not exist in our records", None))
}
Self::MerchantConnectorAccountNotFound {id } => {
AER::NotFound(ApiError::new("HE", 2, "Merchant connector account does not exist in our records", Some(Extra {reason: Some(format!("{id} does not exist")), ..Default::default()})))
}
Self::ProfileNotFound { id } => {
AER::NotFound(ApiError::new("HE", 2, format!("Business profile with the given id {id} does not exist"), None))
}
Self::ProfileAcquirerNotFound { profile_acquirer_id, profile_id } => {
AER::NotFound(ApiError::new("HE", 2, format!("Profile acquirer with id '{profile_acquirer_id}' not found for profile '{profile_id}'."), None))
}
Self::PollNotFound { .. } => {
AER::NotFound(ApiError::new("HE", 2, "Poll does not exist in our records", None))
},
Self::ResourceIdNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Resource ID does not exist in our records", None))
}
Self::MandateNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Mandate does not exist in our records", None))
}
Self::AuthenticationNotFound { .. } => {
AER::NotFound(ApiError::new("HE", 2, "Authentication does not exist in our records", None))
},
Self::MandateUpdateFailed => {
AER::InternalServerError(ApiError::new("HE", 2, "Mandate update failed", None))
},
Self::ApiKeyNotFound => {
AER::NotFound(ApiError::new("HE", 2, "API Key does not exist in our records", None))
}
Self::PayoutNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Payout does not exist in our records", None))
}
Self::EventNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Event does not exist in our records", None))
}
Self::MandateSerializationFailed | Self::MandateDeserializationFailed => {
AER::InternalServerError(ApiError::new("HE", 3, "Something went wrong", None))
},
Self::ReturnUrlUnavailable => AER::NotFound(ApiError::new("HE", 3, "Return URL is not configured and not passed in payments request", None)),
Self::RefundNotPossible { connector } => {
AER::BadRequest(ApiError::new("HE", 3, format!("This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard"), None))
}
Self::MandateValidationFailed { reason } => {
AER::BadRequest(ApiError::new("HE", 3, "Mandate Validation Failed", Some(Extra { reason: Some(reason.to_owned()), ..Default::default() })))
}
Self::PaymentNotSucceeded => AER::BadRequest(ApiError::new("HE", 3, "The payment has not succeeded yet. Please pass a successful payment to initiate refund", None)),
Self::MerchantConnectorAccountDisabled => {
AER::BadRequest(ApiError::new("HE", 3, "The selected merchant connector account is disabled", None))
}
Self::PaymentBlockedError {
message,
reason,
..
} => AER::DomainError(ApiError::new("HE", 3, message, Some(Extra { reason: Some(reason.clone()), ..Default::default() }))),
Self::FileValidationFailed { reason } => {
AER::BadRequest(ApiError::new("HE", 3, format!("File validation failed {reason}"), None))
}
Self::DisputeStatusValidationFailed { .. } => {
AER::BadRequest(ApiError::new("HE", 3, "Dispute status validation failed", None))
}
Self::SuccessfulPaymentNotFound => {
AER::NotFound(ApiError::new("HE", 4, "Successful payment not found for the given payment id", None))
}
Self::IncorrectConnectorNameGiven => {
AER::NotFound(ApiError::new("HE", 4, "The connector provided in the request is incorrect or not available", None))
}
Self::AddressNotFound => {
AER::NotFound(ApiError::new("HE", 4, "Address does not exist in our records", None))
},
Self::DisputeNotFound { .. } => {
AER::NotFound(ApiError::new("HE", 4, "Dispute does not exist in our records", None))
},
Self::FileNotFound => {
AER::NotFound(ApiError::new("HE", 4, "File does not exist in our records", None))
}
Self::FileNotAvailable => {
AER::NotFound(ApiError::new("HE", 4, "File not available", None))
}
Self::MissingTenantId => {
AER::InternalServerError(ApiError::new("HE", 5, "Missing Tenant ID in the request".to_string(), None))
}
Self::InvalidTenant { tenant_id } => {
AER::InternalServerError(ApiError::new("HE", 5, format!("Invalid Tenant {tenant_id}"), None))
}
Self::AmountConversionFailed { amount_type } => {
AER::InternalServerError(ApiError::new("HE", 6, format!("Failed to convert amount to {amount_type} type"), None))
}
Self::NotImplemented { message } => {
AER::NotImplemented(ApiError::new("IR", 0, format!("{message:?}"), None))
}
Self::Unauthorized => AER::Unauthorized(ApiError::new(
"IR",
1,
"API key not provided or invalid API key used", None
)),
Self::InvalidRequestUrl => {
AER::NotFound(ApiError::new("IR", 2, "Unrecognized request URL", None))
}
Self::InvalidHttpMethod => AER::MethodNotAllowed(ApiError::new(
"IR",
3,
"The HTTP method is not applicable for this API", None
)),
Self::MissingRequiredField { field_name } => AER::BadRequest(
ApiError::new("IR", 4, format!("Missing required param: {field_name}"), None),
),
Self::InvalidDataFormat {
field_name,
expected_format,
} => AER::Unprocessable(ApiError::new(
"IR",
5,
format!(
"{field_name} contains invalid data. Expected format is {expected_format}"
), None
)),
Self::InvalidRequestData { message } => {
AER::Unprocessable(ApiError::new("IR", 6, message.to_string(), None))
}
Self::InvalidDataValue { field_name } => AER::BadRequest(ApiError::new(
"IR",
7,
format!("Invalid value provided: {field_name}"), None
)),
Self::ClientSecretNotGiven => AER::BadRequest(ApiError::new(
"IR",
8,
"client_secret was not provided", None
)),
Self::ClientSecretExpired => AER::BadRequest(ApiError::new(
"IR",
8,
"The provided client_secret has expired", None
)),
Self::ClientSecretInvalid => {
AER::BadRequest(ApiError::new("IR", 9, "The client_secret provided does not match the client_secret associated with the Payment", None))
}
Self::MandateActive => {
AER::BadRequest(ApiError::new("IR", 10, "Customer has active mandate/subsciption", None))
}
Self::CustomerRedacted => {
AER::BadRequest(ApiError::new("IR", 11, "Customer has already been redacted", None))
}
Self::MaximumRefundCount => AER::BadRequest(ApiError::new("IR", 12, "Reached maximum refund attempts", None)),
Self::RefundAmountExceedsPaymentAmount => {
AER::BadRequest(ApiError::new("IR", 13, "The refund amount exceeds the amount captured", None))
}
Self::PaymentUnexpectedState {
current_flow,
field_name,
current_value,
states,
} => AER::BadRequest(ApiError::new("IR", 14, format!("This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}"), None)),
Self::InvalidEphemeralKey => AER::Unauthorized(ApiError::new("IR", 15, "Invalid Ephemeral Key for the customer", None)),
Self::PreconditionFailed { message } => {
AER::BadRequest(ApiError::new("IR", 16, message.to_string(), None))
}
Self::InvalidJwtToken => AER::Unauthorized(ApiError::new("IR", 17, "Access forbidden, invalid JWT token was used", None)),
Self::GenericUnauthorized { message } => {
AER::Unauthorized(ApiError::new("IR", 18, message.to_string(), None))
},
Self::NotSupported { message } => {
AER::BadRequest(ApiError::new("IR", 19, "Payment method type not supported", Some(Extra {reason: Some(message.to_owned()), ..Default::default()})))
},
Self::FlowNotSupported { flow, connector } => {
AER::BadRequest(ApiError::new("IR", 20, format!("{flow} flow not supported"), Some(Extra {connector: Some(connector.to_owned()), ..Default::default()}))) //FIXME: error message
}
Self::MissingRequiredFields { field_names } => AER::BadRequest(
ApiError::new("IR", 21, "Missing required params".to_string(), Some(Extra {data: Some(serde_json::json!(field_names)), ..Default::default() })),
),
Self::AccessForbidden {resource} => {
AER::ForbiddenCommonResource(ApiError::new("IR", 22, format!("Access forbidden. Not authorized to access this resource {resource}"), None))
},
Self::FileProviderNotSupported { message } => {
AER::BadRequest(ApiError::new("IR", 23, message.to_string(), None))
},
Self::InvalidWalletToken { wallet_name} => AER::Unprocessable(ApiError::new(
"IR",
24,
format!("Invalid {wallet_name} wallet token"), None
)),
Self::PaymentMethodDeleteFailed => {
AER::BadRequest(ApiError::new("IR", 25, "Cannot delete the default payment method", None))
}
Self::InvalidCookie => {
AER::BadRequest(ApiError::new("IR", 26, "Invalid Cookie", None))
}
Self::ExtendedCardInfoNotFound => {
AER::NotFound(ApiError::new("IR", 27, "Extended card info does not exist", None))
}
Self::CurrencyNotSupported { message } => {
AER::BadRequest(ApiError::new("IR", 28, message, None))
}
Self::UnprocessableEntity {message} => AER::Unprocessable(ApiError::new("IR", 29, message.to_string(), None)),
Self::InvalidConnectorConfiguration {config} => {
AER::BadRequest(ApiError::new("IR", 30, format!("Merchant connector account is configured with invalid {config}"), None))
}
Self::InvalidCardIin => AER::BadRequest(ApiError::new("IR", 31, "The provided card IIN does not exist", None)),
Self::InvalidCardIinLength => AER::BadRequest(ApiError::new("IR", 32, "The provided card IIN length is invalid, please provide an IIN with 6 digits", None)),
Self::MissingFile => {
AER::BadRequest(ApiError::new("IR", 33, "File not found in the request", None))
}
Self::MissingDisputeId => {
AER::BadRequest(ApiError::new("IR", 34, "Dispute id not found in the request", None))
}
Self::MissingFilePurpose => {
AER::BadRequest(ApiError::new("IR", 35, "File purpose not found in the request or is invalid", None))
}
Self::MissingFileContentType => {
AER::BadRequest(ApiError::new("IR", 36, "File content type not found", None))
}
Self::GenericNotFoundError { message } => {
AER::NotFound(ApiError::new("IR", 37, message, None))
},
Self::GenericDuplicateError { message } => {
AER::BadRequest(ApiError::new("IR", 38, message, None))
}
Self::IncorrectPaymentMethodConfiguration => {
AER::BadRequest(ApiError::new("IR", 39, "No eligible connector was found for the current payment method configuration", None))
}
Self::LinkConfigurationError { message } => {
AER::BadRequest(ApiError::new("IR", 40, message, None))
},
Self::PayoutFailed { data } => {
AER::BadRequest(ApiError::new("IR", 41, "Payout failed while processing with connector.", Some(Extra { data: data.clone(), ..Default::default()})))
},
Self::CookieNotFound => {
AER::Unauthorized(ApiError::new("IR", 42, "Cookies are not found in the request", None))
},
Self::ExternalVaultFailed => {
AER::BadRequest(ApiError::new("IR", 45, "External Vault failed while processing with connector.", None))
},
Self::MandatePaymentDataMismatch { fields} => {
AER::BadRequest(ApiError::new("IR", 46, format!("Field {fields} doesn't match with the ones used during mandate creation"), Some(Extra {fields: Some(fields.to_owned()), ..Default::default()}))) //FIXME: error message
}
Self::MaxFieldLengthViolated { connector, field_name, max_length, received_length} => {
AER::BadRequest(ApiError::new("IR", 47, format!("Connector '{connector}' rejected field '{field_name}': length {received_length} exceeds maximum of {max_length}"), Some(Extra {connector: Some(connector.to_string()), ..Default::default()})))
}
Self::WebhookAuthenticationFailed => {
AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None))
}
Self::WebhookBadRequest => {
AER::BadRequest(ApiError::new("WE", 2, "Bad request body received", None))
}
Self::WebhookProcessingFailure => {
AER::InternalServerError(ApiError::new("WE", 3, "There was an issue processing the webhook", None))
},
Self::WebhookResourceNotFound => {
AER::NotFound(ApiError::new("WE", 4, "Webhook resource was not found", None))
}
Self::WebhookUnprocessableEntity => {
AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None))
},
Self::WebhookInvalidMerchantSecret => {
AER::BadRequest(ApiError::new("WE", 6, "Merchant Secret set for webhook source verification is invalid", None))
}
Self::IntegrityCheckFailed {
reason,
field_names,
connector_transaction_id
} => AER::InternalServerError(ApiError::new(
"IE",
0,
format!("{reason} as data mismatched for {field_names}"),
Some(Extra {
connector_transaction_id: connector_transaction_id.to_owned(),
..Default::default()
})
)),
Self::PlatformAccountAuthNotSupported => {
AER::BadRequest(ApiError::new("IR", 43, "API does not support platform operation", None))
}
Self::InvalidPlatformOperation => {
AER::Unauthorized(ApiError::new("IR", 44, "Invalid platform account operation", None))
}
Self::TokenizationRecordNotFound{ id } => {
AER::NotFound(ApiError::new("HE", 2, format!("Tokenization record not found for the given token_id '{id}' "), None))
}
Self::SubscriptionError { operation } => {
AER::BadRequest(ApiError::new("CE", 9, format!("Subscription operation: {operation} failed with connector"), None))
}
}
}
}
impl actix_web::ResponseError for ApiErrorResponse {
fn status_code(&self) -> StatusCode {
ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(self).status_code()
}
fn error_response(&self) -> actix_web::HttpResponse {
ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(self).error_response()
}
}
impl From<ApiErrorResponse> for router_data::ErrorResponse {
fn from(error: ApiErrorResponse) -> Self {
Self {
code: error.error_code(),
message: error.error_message(),
reason: None,
status_code: match error {
ApiErrorResponse::ExternalConnectorError { status_code, .. } => status_code,
_ => 500,
},
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
}
| {
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/errors/api_error_response.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 3,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_common_enums_1493483185144760050 | clm | file | // Repository: hyperswitch
// Crate: common_enums
// File: crates/common_enums/src/connector_enums.rs
// Contains: 0 structs, 2 enums
use std::collections::HashSet;
use utoipa::ToSchema;
pub use super::enums::{PaymentMethod, PayoutType};
pub use crate::PaymentMethodType;
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
strum::VariantNames,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
/// RoutableConnectors are the subset of Connectors that are eligible for payments routing
pub enum RoutableConnectors {
Authipay,
Adyenplatform,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "stripe_billing_test")]
#[strum(serialize = "stripe_billing_test")]
DummyBillingConnector,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "phonypay")]
#[strum(serialize = "phonypay")]
DummyConnector1,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "fauxpay")]
#[strum(serialize = "fauxpay")]
DummyConnector2,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "pretendpay")]
#[strum(serialize = "pretendpay")]
DummyConnector3,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "stripe_test")]
#[strum(serialize = "stripe_test")]
DummyConnector4,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "adyen_test")]
#[strum(serialize = "adyen_test")]
DummyConnector5,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "checkout_test")]
#[strum(serialize = "checkout_test")]
DummyConnector6,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "paypal_test")]
#[strum(serialize = "paypal_test")]
DummyConnector7,
Aci,
Adyen,
Affirm,
Airwallex,
Amazonpay,
Archipel,
Authorizedotnet,
Bankofamerica,
Barclaycard,
Billwerk,
Bitpay,
Bambora,
Blackhawknetwork,
Bamboraapac,
Bluesnap,
#[serde(alias = "bluecode")]
Calida,
Boku,
Braintree,
Breadpay,
Cashtocode,
Celero,
Chargebee,
Custombilling,
Checkbook,
Checkout,
Coinbase,
Coingate,
Cryptopay,
Cybersource,
Datatrans,
Deutschebank,
Digitalvirgo,
Dlocal,
Dwolla,
Ebanx,
Elavon,
Facilitapay,
Finix,
Fiserv,
Fiservemea,
Fiuu,
Flexiti,
Forte,
Getnet,
Gigadat,
Globalpay,
Globepay,
Gocardless,
Hipay,
Helcim,
Iatapay,
Inespay,
Itaubank,
Jpmorgan,
Klarna,
Loonio,
Mifinity,
Mollie,
Moneris,
Multisafepay,
Nexinets,
Nexixpay,
Nmi,
Nomupay,
Noon,
Nordea,
Novalnet,
Nuvei,
// Opayo, added as template code for future usage
Opennode,
// Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage
Paybox,
Payme,
Payload,
Payone,
Paypal,
Paysafe,
Paystack,
Paytm,
Payu,
Peachpayments,
Phonepe,
Placetopay,
Powertranz,
Prophetpay,
Rapyd,
Razorpay,
Recurly,
Redsys,
Riskified,
Santander,
Shift4,
Signifyd,
Silverflow,
Square,
Stax,
Stripe,
Stripebilling,
Tesouro,
// Taxjar,
Trustpay,
Trustpayments,
// Thunes
Tokenio,
// Tsys,
Tsys,
// UnifiedAuthenticationService,
// Vgs
Volt,
Wellsfargo,
// Wellsfargopayout,
Wise,
Worldline,
Worldpay,
Worldpayvantiv,
Worldpayxml,
Xendit,
Zen,
Plaid,
Zsl,
}
// A connector is an integration to fulfill payments
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
ToSchema,
serde::Deserialize,
serde::Serialize,
strum::VariantNames,
strum::EnumIter,
strum::Display,
strum::EnumString,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum Connector {
Authipay,
Adyenplatform,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "stripe_billing_test")]
#[strum(serialize = "stripe_billing_test")]
DummyBillingConnector,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "phonypay")]
#[strum(serialize = "phonypay")]
DummyConnector1,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "fauxpay")]
#[strum(serialize = "fauxpay")]
DummyConnector2,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "pretendpay")]
#[strum(serialize = "pretendpay")]
DummyConnector3,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "stripe_test")]
#[strum(serialize = "stripe_test")]
DummyConnector4,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "adyen_test")]
#[strum(serialize = "adyen_test")]
DummyConnector5,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "checkout_test")]
#[strum(serialize = "checkout_test")]
DummyConnector6,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "paypal_test")]
#[strum(serialize = "paypal_test")]
DummyConnector7,
Aci,
Adyen,
Affirm,
Airwallex,
Amazonpay,
Archipel,
Authorizedotnet,
Bambora,
Bamboraapac,
Bankofamerica,
Barclaycard,
Billwerk,
Bitpay,
Bluesnap,
Blackhawknetwork,
#[serde(alias = "bluecode")]
Calida,
Boku,
Braintree,
Breadpay,
Cardinal,
Cashtocode,
Celero,
Chargebee,
Checkbook,
Checkout,
Coinbase,
Coingate,
Custombilling,
Cryptopay,
CtpMastercard,
CtpVisa,
Cybersource,
Datatrans,
Deutschebank,
Digitalvirgo,
Dlocal,
Dwolla,
Ebanx,
Elavon,
Facilitapay,
Finix,
Fiserv,
Fiservemea,
Fiuu,
Flexiti,
Forte,
Getnet,
Gigadat,
Globalpay,
Globepay,
Gocardless,
Gpayments,
Hipay,
Helcim,
HyperswitchVault,
// Hyperwallet, added as template code for future usage
Inespay,
Iatapay,
Itaubank,
Jpmorgan,
Juspaythreedsserver,
Klarna,
Loonio,
Mifinity,
Mollie,
Moneris,
Multisafepay,
Netcetera,
Nexinets,
Nexixpay,
Nmi,
Nomupay,
Noon,
Nordea,
Novalnet,
Nuvei,
// Opayo, added as template code for future usage
Opennode,
Paybox,
// Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage
Payload,
Payme,
Payone,
Paypal,
Paysafe,
Paystack,
Paytm,
Payu,
Peachpayments,
Phonepe,
Placetopay,
Powertranz,
Prophetpay,
Rapyd,
Razorpay,
Recurly,
Redsys,
Santander,
Shift4,
Silverflow,
Square,
Stax,
Stripe,
Stripebilling,
Taxjar,
Threedsecureio,
// Tokenio,
//Thunes,
Tesouro,
Tokenex,
Tokenio,
Trustpay,
Trustpayments,
Tsys,
// UnifiedAuthenticationService,
Vgs,
Volt,
Wellsfargo,
// Wellsfargopayout,
Wise,
Worldline,
Worldpay,
Worldpayvantiv,
Worldpayxml,
Signifyd,
Plaid,
Riskified,
Xendit,
Zen,
Zsl,
}
impl Connector {
#[cfg(feature = "payouts")]
pub fn supports_instant_payout(self, payout_method: Option<PayoutType>) -> bool {
matches!(
(self, payout_method),
(Self::Paypal, Some(PayoutType::Wallet))
| (_, Some(PayoutType::Card))
| (Self::Adyenplatform, _)
| (Self::Nomupay, _)
| (Self::Loonio, _)
| (Self::Worldpay, Some(PayoutType::Wallet))
)
}
#[cfg(feature = "payouts")]
pub fn supports_create_recipient(self, payout_method: Option<PayoutType>) -> bool {
matches!((self, payout_method), (_, Some(PayoutType::Bank)))
}
#[cfg(feature = "payouts")]
pub fn supports_payout_eligibility(self, payout_method: Option<PayoutType>) -> bool {
matches!((self, payout_method), (_, Some(PayoutType::Card)))
}
#[cfg(feature = "payouts")]
pub fn is_payout_quote_call_required(self) -> bool {
matches!(self, Self::Wise | Self::Gigadat)
}
#[cfg(feature = "payouts")]
pub fn supports_access_token_for_payout(self, payout_method: Option<PayoutType>) -> bool {
matches!((self, payout_method), (Self::Paypal, _))
}
#[cfg(feature = "payouts")]
pub fn supports_vendor_disburse_account_create_for_payout(self) -> bool {
matches!(self, Self::Stripe | Self::Nomupay)
}
pub fn supports_access_token(self, payment_method: PaymentMethod) -> bool {
matches!(
(self, payment_method),
(Self::Airwallex, _)
| (Self::Deutschebank, _)
| (Self::Globalpay, _)
| (Self::Jpmorgan, _)
| (Self::Moneris, _)
| (Self::Nordea, _)
| (Self::Paypal, _)
| (Self::Payu, _)
| (
Self::Trustpay,
PaymentMethod::BankRedirect | PaymentMethod::BankTransfer
)
| (Self::Tesouro, _)
| (Self::Iatapay, _)
| (Self::Volt, _)
| (Self::Itaubank, _)
| (Self::Facilitapay, _)
| (Self::Dwolla, _)
)
}
pub fn requires_order_creation_before_payment(self, payment_method: PaymentMethod) -> bool {
matches!((self, payment_method), (Self::Razorpay, PaymentMethod::Upi))
}
pub fn supports_file_storage_module(self) -> bool {
matches!(self, Self::Stripe | Self::Checkout | Self::Worldpayvantiv)
}
pub fn requires_defend_dispute(self) -> bool {
matches!(self, Self::Checkout)
}
pub fn is_separate_authentication_supported(self) -> bool {
match self {
#[cfg(feature = "dummy_connector")]
Self::DummyBillingConnector => false,
#[cfg(feature = "dummy_connector")]
Self::DummyConnector1
| Self::DummyConnector2
| Self::DummyConnector3
| Self::DummyConnector4
| Self::DummyConnector5
| Self::DummyConnector6
| Self::DummyConnector7 => false,
Self::Aci
// Add Separate authentication support for connectors
| Self::Authipay
| Self::Adyen
| Self::Affirm
| Self::Adyenplatform
| Self::Airwallex
| Self::Amazonpay
| Self::Authorizedotnet
| Self::Bambora
| Self::Bamboraapac
| Self::Bankofamerica
| Self::Barclaycard
| Self::Billwerk
| Self::Bitpay
| Self::Bluesnap
| Self::Blackhawknetwork
| Self::Calida
| Self::Boku
| Self::Braintree
| Self::Breadpay
| Self::Cashtocode
| Self::Celero
| Self::Chargebee
| Self::Checkbook
| Self::Coinbase
| Self::Coingate
| Self::Cryptopay
| Self::Custombilling
| Self::Deutschebank
| Self::Digitalvirgo
| Self::Dlocal
| Self::Dwolla
| Self::Ebanx
| Self::Elavon
| Self::Facilitapay
| Self::Finix
| Self::Fiserv
| Self::Fiservemea
| Self::Fiuu
| Self::Flexiti
| Self::Forte
| Self::Getnet
| Self::Gigadat
| Self::Globalpay
| Self::Globepay
| Self::Gocardless
| Self::Gpayments
| Self::Hipay
| Self::Helcim
| Self::HyperswitchVault
| Self::Iatapay
| Self::Inespay
| Self::Itaubank
| Self::Jpmorgan
| Self::Juspaythreedsserver
| Self::Klarna
| Self::Loonio
| Self::Mifinity
| Self::Mollie
| Self::Moneris
| Self::Multisafepay
| Self::Nexinets
| Self::Nexixpay
| Self::Nomupay
| Self::Nordea
| Self::Novalnet
| Self::Opennode
| Self::Paybox
| Self::Payload
| Self::Payme
| Self::Payone
| Self::Paypal
| Self::Paysafe
| Self::Paystack
| Self::Payu
| Self::Peachpayments
| Self::Placetopay
| Self::Powertranz
| Self::Prophetpay
| Self::Rapyd
| Self::Recurly
| Self::Redsys
| Self::Santander
| Self::Shift4
| Self::Silverflow
| Self::Square
| Self::Stax
| Self::Stripebilling
| Self::Taxjar
| Self::Tesouro
// | Self::Thunes
| Self::Trustpay
| Self::Trustpayments
// | Self::Tokenio
| Self::Tsys
// | Self::UnifiedAuthenticationService
| Self::Vgs
| Self::Volt
| Self::Wellsfargo
// | Self::Wellsfargopayout
| Self::Wise
| Self::Worldline
| Self::Worldpay
| Self::Worldpayvantiv
| Self::Worldpayxml
| Self::Xendit
| Self::Zen
| Self::Zsl
| Self::Signifyd
| Self::Plaid
| Self::Razorpay
| Self::Riskified
| Self::Threedsecureio
| Self::Netcetera
| Self::CtpMastercard
| Self::Cardinal
| Self::CtpVisa
| Self::Noon
| Self::Tokenex
| Self::Tokenio
| Self::Stripe
| Self::Datatrans
| Self::Paytm
| Self::Phonepe => false,
Self::Checkout | Self::Nmi |Self::Cybersource | Self::Archipel | Self::Nuvei => true,
}
}
pub fn is_pre_processing_required_before_authorize(self) -> bool {
matches!(self, Self::Airwallex)
}
pub fn get_payment_methods_supporting_extended_authorization(self) -> HashSet<PaymentMethod> {
HashSet::from([PaymentMethod::Card])
}
pub fn get_payment_method_types_supporting_extended_authorization(
self,
) -> HashSet<PaymentMethodType> {
HashSet::from([PaymentMethodType::Credit, PaymentMethodType::Debit])
}
pub fn is_overcapture_supported_by_connector(self) -> bool {
matches!(self, Self::Stripe | Self::Adyen)
}
pub fn should_acknowledge_webhook_for_resource_not_found_errors(self) -> bool {
matches!(self, Self::Adyenplatform | Self::Adyen)
}
/// Validates if dummy connector can be created
/// Dummy connectors can be created only if dummy_connector feature is enabled in the configs
#[cfg(feature = "dummy_connector")]
pub fn validate_dummy_connector_create(self, is_dummy_connector_enabled: bool) -> bool {
matches!(
self,
Self::DummyConnector1
| Self::DummyConnector2
| Self::DummyConnector3
| Self::DummyConnector4
| Self::DummyConnector5
| Self::DummyConnector6
| Self::DummyConnector7
) && !is_dummy_connector_enabled
}
}
/// Convert the RoutableConnectors to Connector
impl From<RoutableConnectors> for Connector {
fn from(routable_connector: RoutableConnectors) -> Self {
match routable_connector {
RoutableConnectors::Authipay => Self::Authipay,
RoutableConnectors::Adyenplatform => Self::Adyenplatform,
#[cfg(feature = "dummy_connector")]
RoutableConnectors::DummyBillingConnector => Self::DummyBillingConnector,
#[cfg(feature = "dummy_connector")]
RoutableConnectors::DummyConnector1 => Self::DummyConnector1,
#[cfg(feature = "dummy_connector")]
RoutableConnectors::DummyConnector2 => Self::DummyConnector2,
#[cfg(feature = "dummy_connector")]
RoutableConnectors::DummyConnector3 => Self::DummyConnector3,
#[cfg(feature = "dummy_connector")]
RoutableConnectors::DummyConnector4 => Self::DummyConnector4,
#[cfg(feature = "dummy_connector")]
RoutableConnectors::DummyConnector5 => Self::DummyConnector5,
#[cfg(feature = "dummy_connector")]
RoutableConnectors::DummyConnector6 => Self::DummyConnector6,
#[cfg(feature = "dummy_connector")]
RoutableConnectors::DummyConnector7 => Self::DummyConnector7,
RoutableConnectors::Aci => Self::Aci,
RoutableConnectors::Adyen => Self::Adyen,
RoutableConnectors::Affirm => Self::Affirm,
RoutableConnectors::Airwallex => Self::Airwallex,
RoutableConnectors::Amazonpay => Self::Amazonpay,
RoutableConnectors::Archipel => Self::Archipel,
RoutableConnectors::Authorizedotnet => Self::Authorizedotnet,
RoutableConnectors::Bankofamerica => Self::Bankofamerica,
RoutableConnectors::Barclaycard => Self::Barclaycard,
RoutableConnectors::Billwerk => Self::Billwerk,
RoutableConnectors::Bitpay => Self::Bitpay,
RoutableConnectors::Bambora => Self::Bambora,
RoutableConnectors::Bamboraapac => Self::Bamboraapac,
RoutableConnectors::Bluesnap => Self::Bluesnap,
RoutableConnectors::Blackhawknetwork => Self::Blackhawknetwork,
RoutableConnectors::Calida => Self::Calida,
RoutableConnectors::Boku => Self::Boku,
RoutableConnectors::Braintree => Self::Braintree,
RoutableConnectors::Breadpay => Self::Breadpay,
RoutableConnectors::Cashtocode => Self::Cashtocode,
RoutableConnectors::Celero => Self::Celero,
RoutableConnectors::Chargebee => Self::Chargebee,
RoutableConnectors::Custombilling => Self::Custombilling,
RoutableConnectors::Checkbook => Self::Checkbook,
RoutableConnectors::Checkout => Self::Checkout,
RoutableConnectors::Coinbase => Self::Coinbase,
RoutableConnectors::Cryptopay => Self::Cryptopay,
RoutableConnectors::Cybersource => Self::Cybersource,
RoutableConnectors::Datatrans => Self::Datatrans,
RoutableConnectors::Deutschebank => Self::Deutschebank,
RoutableConnectors::Digitalvirgo => Self::Digitalvirgo,
RoutableConnectors::Dlocal => Self::Dlocal,
RoutableConnectors::Dwolla => Self::Dwolla,
RoutableConnectors::Ebanx => Self::Ebanx,
RoutableConnectors::Elavon => Self::Elavon,
RoutableConnectors::Facilitapay => Self::Facilitapay,
RoutableConnectors::Finix => Self::Finix,
RoutableConnectors::Fiserv => Self::Fiserv,
RoutableConnectors::Fiservemea => Self::Fiservemea,
RoutableConnectors::Fiuu => Self::Fiuu,
RoutableConnectors::Flexiti => Self::Flexiti,
RoutableConnectors::Forte => Self::Forte,
RoutableConnectors::Getnet => Self::Getnet,
RoutableConnectors::Gigadat => Self::Gigadat,
RoutableConnectors::Globalpay => Self::Globalpay,
RoutableConnectors::Globepay => Self::Globepay,
RoutableConnectors::Gocardless => Self::Gocardless,
RoutableConnectors::Helcim => Self::Helcim,
RoutableConnectors::Iatapay => Self::Iatapay,
RoutableConnectors::Itaubank => Self::Itaubank,
RoutableConnectors::Jpmorgan => Self::Jpmorgan,
RoutableConnectors::Klarna => Self::Klarna,
RoutableConnectors::Loonio => Self::Loonio,
RoutableConnectors::Mifinity => Self::Mifinity,
RoutableConnectors::Mollie => Self::Mollie,
RoutableConnectors::Moneris => Self::Moneris,
RoutableConnectors::Multisafepay => Self::Multisafepay,
RoutableConnectors::Nexinets => Self::Nexinets,
RoutableConnectors::Nexixpay => Self::Nexixpay,
RoutableConnectors::Nmi => Self::Nmi,
RoutableConnectors::Nomupay => Self::Nomupay,
RoutableConnectors::Noon => Self::Noon,
RoutableConnectors::Nordea => Self::Nordea,
RoutableConnectors::Novalnet => Self::Novalnet,
RoutableConnectors::Nuvei => Self::Nuvei,
RoutableConnectors::Opennode => Self::Opennode,
RoutableConnectors::Paybox => Self::Paybox,
RoutableConnectors::Payload => Self::Payload,
RoutableConnectors::Payme => Self::Payme,
RoutableConnectors::Payone => Self::Payone,
RoutableConnectors::Paypal => Self::Paypal,
RoutableConnectors::Paysafe => Self::Paysafe,
RoutableConnectors::Paystack => Self::Paystack,
RoutableConnectors::Payu => Self::Payu,
RoutableConnectors::Peachpayments => Self::Peachpayments,
RoutableConnectors::Placetopay => Self::Placetopay,
RoutableConnectors::Powertranz => Self::Powertranz,
RoutableConnectors::Prophetpay => Self::Prophetpay,
RoutableConnectors::Rapyd => Self::Rapyd,
RoutableConnectors::Razorpay => Self::Razorpay,
RoutableConnectors::Recurly => Self::Recurly,
RoutableConnectors::Redsys => Self::Redsys,
RoutableConnectors::Riskified => Self::Riskified,
RoutableConnectors::Santander => Self::Santander,
RoutableConnectors::Shift4 => Self::Shift4,
RoutableConnectors::Signifyd => Self::Signifyd,
RoutableConnectors::Silverflow => Self::Silverflow,
RoutableConnectors::Square => Self::Square,
RoutableConnectors::Stax => Self::Stax,
RoutableConnectors::Stripe => Self::Stripe,
RoutableConnectors::Stripebilling => Self::Stripebilling,
RoutableConnectors::Tesouro => Self::Tesouro,
RoutableConnectors::Tokenio => Self::Tokenio,
RoutableConnectors::Trustpay => Self::Trustpay,
RoutableConnectors::Trustpayments => Self::Trustpayments,
// RoutableConnectors::Tokenio => Self::Tokenio,
RoutableConnectors::Tsys => Self::Tsys,
RoutableConnectors::Volt => Self::Volt,
RoutableConnectors::Wellsfargo => Self::Wellsfargo,
RoutableConnectors::Wise => Self::Wise,
RoutableConnectors::Worldline => Self::Worldline,
RoutableConnectors::Worldpay => Self::Worldpay,
RoutableConnectors::Worldpayvantiv => Self::Worldpayvantiv,
RoutableConnectors::Worldpayxml => Self::Worldpayxml,
RoutableConnectors::Zen => Self::Zen,
RoutableConnectors::Plaid => Self::Plaid,
RoutableConnectors::Zsl => Self::Zsl,
RoutableConnectors::Xendit => Self::Xendit,
RoutableConnectors::Inespay => Self::Inespay,
RoutableConnectors::Coingate => Self::Coingate,
RoutableConnectors::Hipay => Self::Hipay,
RoutableConnectors::Paytm => Self::Paytm,
RoutableConnectors::Phonepe => Self::Phonepe,
}
}
}
impl TryFrom<Connector> for RoutableConnectors {
type Error = &'static str;
fn try_from(connector: Connector) -> Result<Self, Self::Error> {
match connector {
Connector::Authipay => Ok(Self::Authipay),
Connector::Adyenplatform => Ok(Self::Adyenplatform),
#[cfg(feature = "dummy_connector")]
Connector::DummyBillingConnector => Ok(Self::DummyBillingConnector),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector1 => Ok(Self::DummyConnector1),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector2 => Ok(Self::DummyConnector2),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector3 => Ok(Self::DummyConnector3),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector4 => Ok(Self::DummyConnector4),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector5 => Ok(Self::DummyConnector5),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector6 => Ok(Self::DummyConnector6),
#[cfg(feature = "dummy_connector")]
Connector::DummyConnector7 => Ok(Self::DummyConnector7),
Connector::Aci => Ok(Self::Aci),
Connector::Adyen => Ok(Self::Adyen),
Connector::Affirm => Ok(Self::Affirm),
Connector::Airwallex => Ok(Self::Airwallex),
Connector::Amazonpay => Ok(Self::Amazonpay),
Connector::Archipel => Ok(Self::Archipel),
Connector::Authorizedotnet => Ok(Self::Authorizedotnet),
Connector::Bankofamerica => Ok(Self::Bankofamerica),
Connector::Barclaycard => Ok(Self::Barclaycard),
Connector::Billwerk => Ok(Self::Billwerk),
Connector::Bitpay => Ok(Self::Bitpay),
Connector::Bambora => Ok(Self::Bambora),
Connector::Bamboraapac => Ok(Self::Bamboraapac),
Connector::Bluesnap => Ok(Self::Bluesnap),
Connector::Blackhawknetwork => Ok(Self::Blackhawknetwork),
Connector::Calida => Ok(Self::Calida),
Connector::Boku => Ok(Self::Boku),
Connector::Braintree => Ok(Self::Braintree),
Connector::Breadpay => Ok(Self::Breadpay),
Connector::Cashtocode => Ok(Self::Cashtocode),
Connector::Celero => Ok(Self::Celero),
Connector::Chargebee => Ok(Self::Chargebee),
Connector::Checkbook => Ok(Self::Checkbook),
Connector::Checkout => Ok(Self::Checkout),
Connector::Coinbase => Ok(Self::Coinbase),
Connector::Coingate => Ok(Self::Coingate),
Connector::Cryptopay => Ok(Self::Cryptopay),
Connector::Custombilling => Ok(Self::Custombilling),
Connector::Cybersource => Ok(Self::Cybersource),
Connector::Datatrans => Ok(Self::Datatrans),
Connector::Deutschebank => Ok(Self::Deutschebank),
Connector::Digitalvirgo => Ok(Self::Digitalvirgo),
Connector::Dlocal => Ok(Self::Dlocal),
Connector::Dwolla => Ok(Self::Dwolla),
Connector::Ebanx => Ok(Self::Ebanx),
Connector::Elavon => Ok(Self::Elavon),
Connector::Facilitapay => Ok(Self::Facilitapay),
Connector::Finix => Ok(Self::Finix),
Connector::Fiserv => Ok(Self::Fiserv),
Connector::Fiservemea => Ok(Self::Fiservemea),
Connector::Fiuu => Ok(Self::Fiuu),
Connector::Flexiti => Ok(Self::Flexiti),
Connector::Forte => Ok(Self::Forte),
Connector::Globalpay => Ok(Self::Globalpay),
Connector::Globepay => Ok(Self::Globepay),
Connector::Gocardless => Ok(Self::Gocardless),
Connector::Helcim => Ok(Self::Helcim),
Connector::Iatapay => Ok(Self::Iatapay),
Connector::Itaubank => Ok(Self::Itaubank),
Connector::Jpmorgan => Ok(Self::Jpmorgan),
Connector::Klarna => Ok(Self::Klarna),
Connector::Loonio => Ok(Self::Loonio),
Connector::Mifinity => Ok(Self::Mifinity),
Connector::Mollie => Ok(Self::Mollie),
Connector::Moneris => Ok(Self::Moneris),
Connector::Multisafepay => Ok(Self::Multisafepay),
Connector::Nexinets => Ok(Self::Nexinets),
Connector::Nexixpay => Ok(Self::Nexixpay),
Connector::Nmi => Ok(Self::Nmi),
Connector::Nomupay => Ok(Self::Nomupay),
Connector::Noon => Ok(Self::Noon),
Connector::Nordea => Ok(Self::Nordea),
Connector::Novalnet => Ok(Self::Novalnet),
Connector::Nuvei => Ok(Self::Nuvei),
Connector::Opennode => Ok(Self::Opennode),
Connector::Paybox => Ok(Self::Paybox),
Connector::Payload => Ok(Self::Payload),
Connector::Payme => Ok(Self::Payme),
Connector::Payone => Ok(Self::Payone),
Connector::Paypal => Ok(Self::Paypal),
Connector::Paysafe => Ok(Self::Paysafe),
Connector::Paystack => Ok(Self::Paystack),
Connector::Payu => Ok(Self::Payu),
Connector::Peachpayments => Ok(Self::Peachpayments),
Connector::Placetopay => Ok(Self::Placetopay),
Connector::Powertranz => Ok(Self::Powertranz),
Connector::Prophetpay => Ok(Self::Prophetpay),
Connector::Rapyd => Ok(Self::Rapyd),
Connector::Razorpay => Ok(Self::Razorpay),
Connector::Riskified => Ok(Self::Riskified),
Connector::Santander => Ok(Self::Santander),
Connector::Shift4 => Ok(Self::Shift4),
Connector::Signifyd => Ok(Self::Signifyd),
Connector::Silverflow => Ok(Self::Silverflow),
Connector::Square => Ok(Self::Square),
Connector::Stax => Ok(Self::Stax),
Connector::Stripe => Ok(Self::Stripe),
Connector::Stripebilling => Ok(Self::Stripebilling),
Connector::Tokenio => Ok(Self::Tokenio),
Connector::Tesouro => Ok(Self::Tesouro),
Connector::Trustpay => Ok(Self::Trustpay),
Connector::Trustpayments => Ok(Self::Trustpayments),
Connector::Tsys => Ok(Self::Tsys),
Connector::Volt => Ok(Self::Volt),
Connector::Wellsfargo => Ok(Self::Wellsfargo),
Connector::Wise => Ok(Self::Wise),
Connector::Worldline => Ok(Self::Worldline),
Connector::Worldpay => Ok(Self::Worldpay),
Connector::Worldpayvantiv => Ok(Self::Worldpayvantiv),
Connector::Worldpayxml => Ok(Self::Worldpayxml),
Connector::Xendit => Ok(Self::Xendit),
Connector::Zen => Ok(Self::Zen),
Connector::Plaid => Ok(Self::Plaid),
Connector::Zsl => Ok(Self::Zsl),
Connector::Recurly => Ok(Self::Recurly),
Connector::Getnet => Ok(Self::Getnet),
Connector::Gigadat => Ok(Self::Gigadat),
Connector::Hipay => Ok(Self::Hipay),
Connector::Inespay => Ok(Self::Inespay),
Connector::Redsys => Ok(Self::Redsys),
Connector::Paytm => Ok(Self::Paytm),
Connector::Phonepe => Ok(Self::Phonepe),
Connector::CtpMastercard
| Connector::Gpayments
| Connector::HyperswitchVault
| Connector::Juspaythreedsserver
| Connector::Netcetera
| Connector::Taxjar
| Connector::Threedsecureio
| Connector::Vgs
| Connector::CtpVisa
| Connector::Cardinal
| Connector::Tokenex => Err("Invalid conversion. Not a routable connector"),
}
}
}
// Enum representing different status an invoice can have.
#[derive(
Debug,
Clone,
PartialEq,
Eq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum InvoiceStatus {
InvoiceCreated,
PaymentPending,
PaymentPendingTimeout,
PaymentSucceeded,
PaymentFailed,
PaymentCanceled,
InvoicePaid,
ManualReview,
Voided,
}
| {
"crate": "common_enums",
"file": "crates/common_enums/src/connector_enums.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_common_enums_5626928884562679668 | clm | file | // Repository: hyperswitch
// Crate: common_enums
// File: crates/common_enums/src/enums.rs
// Contains: 0 structs, 61 enums
mod accounts;
mod payments;
mod ui;
use std::{
collections::HashSet,
num::{ParseFloatError, TryFromIntError},
};
pub use accounts::{
MerchantAccountRequestType, MerchantAccountType, MerchantProductType, OrganizationType,
};
pub use payments::ProductType;
use serde::{Deserialize, Serialize};
pub use ui::*;
use utoipa::ToSchema;
pub use super::connector_enums::{InvoiceStatus, RoutableConnectors};
#[doc(hidden)]
pub mod diesel_exports {
pub use super::{
DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus,
DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind,
DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus,
DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency,
DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage,
DbDisputeStatus as DisputeStatus, DbFraudCheckStatus as FraudCheckStatus,
DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus,
DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode,
DbPaymentType as PaymentType, DbProcessTrackerStatus as ProcessTrackerStatus,
DbRefundStatus as RefundStatus,
DbRequestIncrementalAuthorization as RequestIncrementalAuthorization,
DbRoutingApproach as RoutingApproach, DbScaExemptionType as ScaExemptionType,
DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState,
DbTokenizationFlag as TokenizationFlag, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt,
};
}
pub type ApplicationResult<T> = Result<T, ApplicationError>;
#[derive(Debug, thiserror::Error)]
pub enum ApplicationError {
#[error("Application configuration error")]
ConfigurationError,
#[error("Invalid configuration value provided: {0}")]
InvalidConfigurationValueError(String),
#[error("Metrics error")]
MetricsError,
#[error("I/O: {0}")]
IoError(std::io::Error),
#[error("Error while constructing api client: {0}")]
ApiClientError(ApiClientError),
}
#[derive(Debug, thiserror::Error, PartialEq, Clone)]
pub enum ApiClientError {
#[error("Header map construction failed")]
HeaderMapConstructionFailed,
#[error("Invalid proxy configuration")]
InvalidProxyConfiguration,
#[error("Client construction failed")]
ClientConstructionFailed,
#[error("Certificate decode failed")]
CertificateDecodeFailed,
#[error("Request body serialization failed")]
BodySerializationFailed,
#[error("Unexpected state reached/Invariants conflicted")]
UnexpectedState,
#[error("Failed to parse URL")]
UrlParsingFailed,
#[error("URL encoding of request payload failed")]
UrlEncodingFailed,
#[error("Failed to send request to connector {0}")]
RequestNotSent(String),
#[error("Failed to decode response")]
ResponseDecodingFailed,
#[error("Server responded with Request Timeout")]
RequestTimeoutReceived,
#[error("connection closed before a message could complete")]
ConnectionClosedIncompleteMessage,
#[error("Server responded with Internal Server Error")]
InternalServerErrorReceived,
#[error("Server responded with Bad Gateway")]
BadGatewayReceived,
#[error("Server responded with Service Unavailable")]
ServiceUnavailableReceived,
#[error("Server responded with Gateway Timeout")]
GatewayTimeoutReceived,
#[error("Server responded with unexpected response")]
UnexpectedServerResponse,
}
impl ApiClientError {
pub fn is_upstream_timeout(&self) -> bool {
self == &Self::RequestTimeoutReceived
}
pub fn is_connection_closed_before_message_could_complete(&self) -> bool {
self == &Self::ConnectionClosedIncompleteMessage
}
}
impl From<std::io::Error> for ApplicationError {
fn from(err: std::io::Error) -> Self {
Self::IoError(err)
}
}
/// The status of the attempt
#[derive(
Clone,
Copy,
Debug,
Default,
Hash,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum AttemptStatus {
Started,
AuthenticationFailed,
RouterDeclined,
AuthenticationPending,
AuthenticationSuccessful,
Authorized,
AuthorizationFailed,
Charged,
Authorizing,
CodInitiated,
Voided,
VoidedPostCharge,
VoidInitiated,
CaptureInitiated,
CaptureFailed,
VoidFailed,
AutoRefunded,
PartialCharged,
PartiallyAuthorized,
PartialChargedAndChargeable,
Unresolved,
#[default]
Pending,
Failure,
PaymentMethodAwaited,
ConfirmationAwaited,
DeviceDataCollectionPending,
IntegrityFailure,
Expired,
}
impl AttemptStatus {
pub fn is_terminal_status(self) -> bool {
match self {
Self::RouterDeclined
| Self::Charged
| Self::AutoRefunded
| Self::Voided
| Self::VoidedPostCharge
| Self::VoidFailed
| Self::CaptureFailed
| Self::Failure
| Self::PartialCharged
| Self::Expired => true,
Self::Started
| Self::AuthenticationFailed
| Self::AuthenticationPending
| Self::AuthenticationSuccessful
| Self::Authorized
| Self::PartiallyAuthorized
| Self::AuthorizationFailed
| Self::Authorizing
| Self::CodInitiated
| Self::VoidInitiated
| Self::CaptureInitiated
| Self::PartialChargedAndChargeable
| Self::Unresolved
| Self::Pending
| Self::PaymentMethodAwaited
| Self::ConfirmationAwaited
| Self::DeviceDataCollectionPending
| Self::IntegrityFailure => false,
}
}
pub fn is_success(self) -> bool {
matches!(self, Self::Charged | Self::PartialCharged)
}
}
#[derive(
Clone,
Copy,
Debug,
Hash,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ApplePayPaymentMethodType {
Debit,
Credit,
Prepaid,
Store,
}
/// Indicates the method by which a card is discovered during a payment
#[derive(
Clone,
Copy,
Debug,
Default,
Hash,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CardDiscovery {
#[default]
Manual,
SavedCard,
ClickToPay,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Hash,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RevenueRecoveryAlgorithmType {
#[default]
Monitoring,
Smart,
Cascading,
}
#[derive(
Default,
Clone,
Copy,
Debug,
strum::Display,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum GsmDecision {
Retry,
#[default]
DoDefault,
}
#[derive(
Clone,
Copy,
Debug,
strum::Display,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
#[router_derive::diesel_enum(storage_type = "text")]
pub enum GsmFeature {
Retry,
}
/// Specifies the type of cardholder authentication to be applied for a payment.
///
/// - `ThreeDs`: Requests 3D Secure (3DS) authentication. If the card is enrolled, 3DS authentication will be activated, potentially shifting chargeback liability to the issuer.
/// - `NoThreeDs`: Indicates that 3D Secure authentication should not be performed. The liability for chargebacks typically remains with the merchant. This is often the default if not specified.
///
/// Note: The actual authentication behavior can also be influenced by merchant configuration and specific connector defaults. Some connectors might still enforce 3DS or bypass it regardless of this parameter.
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum AuthenticationType {
/// If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer
ThreeDs,
/// 3DS based authentication will not be activated. The liability of chargeback stays with the merchant.
#[default]
NoThreeDs,
}
/// The status of the capture
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "snake_case")]
pub enum FraudCheckStatus {
Fraud,
ManualReview,
#[default]
Pending,
Legit,
TransactionFailure,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CaptureStatus {
// Capture request initiated
#[default]
Started,
// Capture request was successful
Charged,
// Capture is pending at connector side
Pending,
// Capture request failed
Failed,
}
#[derive(
Default,
Clone,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum AuthorizationStatus {
Success,
Failure,
// Processing state is before calling connector
#[default]
Processing,
// Requires merchant action
Unresolved,
}
#[derive(
Clone,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PaymentResourceUpdateStatus {
Success,
Failure,
}
impl PaymentResourceUpdateStatus {
pub fn is_success(&self) -> bool {
matches!(self, Self::Success)
}
}
#[derive(
Clone,
Debug,
PartialEq,
Eq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum BlocklistDataKind {
PaymentMethod,
CardBin,
ExtendedCardBin,
}
/// Specifies how the payment is captured.
/// - `automatic`: Funds are captured immediately after successful authorization. This is the default behavior if the field is omitted.
/// - `manual`: Funds are authorized but not captured. A separate request to the `/payments/{payment_id}/capture` endpoint is required to capture the funds.
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CaptureMethod {
/// Post the payment authorization, the capture will be executed on the full amount immediately.
#[default]
Automatic,
/// The capture will happen only if the merchant triggers a Capture API request. Allows for a single capture of the authorized amount.
Manual,
/// The capture will happen only if the merchant triggers a Capture API request. Allows for multiple partial captures up to the authorized amount.
ManualMultiple,
/// The capture can be scheduled to automatically get triggered at a specific date & time.
Scheduled,
/// Handles separate auth and capture sequentially; effectively the same as `Automatic` for most connectors.
SequentialAutomatic,
}
/// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking.
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
strum::Display,
strum::EnumString,
serde::Deserialize,
serde::Serialize,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum ConnectorType {
/// PayFacs, Acquirers, Gateways, BNPL etc
PaymentProcessor,
/// Fraud, Currency Conversion, Crypto etc
PaymentVas,
/// Accounting, Billing, Invoicing, Tax etc
FinOperations,
/// Inventory, ERP, CRM, KYC etc
FizOperations,
/// Payment Networks like Visa, MasterCard etc
Networks,
/// All types of banks including corporate / commercial / personal / neo banks
BankingEntities,
/// All types of non-banking financial institutions including Insurance, Credit / Lending etc
NonBankingFinance,
/// Acquirers, Gateways etc
PayoutProcessor,
/// PaymentMethods Auth Services
PaymentMethodAuth,
/// 3DS Authentication Service Providers
AuthenticationProcessor,
/// Tax Calculation Processor
TaxProcessor,
/// Represents billing processors that handle subscription management, invoicing,
/// and recurring payments. Examples include Chargebee, Recurly, and Stripe Billing.
BillingProcessor,
/// Represents vaulting processors that handle the storage and management of payment method data
VaultProcessor,
}
#[derive(Debug, Eq, PartialEq)]
pub enum PaymentAction {
PSync,
CompleteAuthorize,
PaymentAuthenticateCompleteAuthorize,
}
#[derive(Clone, PartialEq)]
pub enum CallConnectorAction {
Trigger,
Avoid,
StatusUpdate {
status: AttemptStatus,
error_code: Option<String>,
error_message: Option<String>,
},
HandleResponse(Vec<u8>),
UCSHandleResponse(Vec<u8>),
}
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "UPPERCASE")]
pub enum DocumentKind {
Cnpj,
Cpf,
}
/// The three-letter ISO 4217 currency code (e.g., "USD", "EUR") for the payment amount. This field is mandatory for creating a payment.
#[allow(clippy::upper_case_acronyms)]
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
strum::VariantNames,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
pub enum Currency {
AED,
AFN,
ALL,
AMD,
ANG,
AOA,
ARS,
AUD,
AWG,
AZN,
BAM,
BBD,
BDT,
BGN,
BHD,
BIF,
BMD,
BND,
BOB,
BRL,
BSD,
BTN,
BWP,
BYN,
BZD,
CAD,
CDF,
CHF,
CLF,
CLP,
CNY,
COP,
CRC,
CUC,
CUP,
CVE,
CZK,
DJF,
DKK,
DOP,
DZD,
EGP,
ERN,
ETB,
EUR,
FJD,
FKP,
GBP,
GEL,
GHS,
GIP,
GMD,
GNF,
GTQ,
GYD,
HKD,
HNL,
HRK,
HTG,
HUF,
IDR,
ILS,
INR,
IQD,
IRR,
ISK,
JMD,
JOD,
JPY,
KES,
KGS,
KHR,
KMF,
KPW,
KRW,
KWD,
KYD,
KZT,
LAK,
LBP,
LKR,
LRD,
LSL,
LYD,
MAD,
MDL,
MGA,
MKD,
MMK,
MNT,
MOP,
MRU,
MUR,
MVR,
MWK,
MXN,
MYR,
MZN,
NAD,
NGN,
NIO,
NOK,
NPR,
NZD,
OMR,
PAB,
PEN,
PGK,
PHP,
PKR,
PLN,
PYG,
QAR,
RON,
RSD,
RUB,
RWF,
SAR,
SBD,
SCR,
SDG,
SEK,
SGD,
SHP,
SLE,
SLL,
SOS,
SRD,
SSP,
STD,
STN,
SVC,
SYP,
SZL,
THB,
TJS,
TMT,
TND,
TOP,
TRY,
TTD,
TWD,
TZS,
UAH,
UGX,
#[default]
USD,
UYU,
UZS,
VES,
VND,
VUV,
WST,
XAF,
XCD,
XOF,
XPF,
YER,
ZAR,
ZMW,
ZWL,
}
impl Currency {
/// Convert the amount to its base denomination based on Currency and return String
pub fn to_currency_base_unit(self, amount: i64) -> Result<String, TryFromIntError> {
let amount_f64 = self.to_currency_base_unit_asf64(amount)?;
Ok(format!("{amount_f64:.2}"))
}
/// Convert the amount to its base denomination based on Currency and return f64
pub fn to_currency_base_unit_asf64(self, amount: i64) -> Result<f64, TryFromIntError> {
let amount_f64: f64 = u32::try_from(amount)?.into();
let amount = if self.is_zero_decimal_currency() {
amount_f64
} else if self.is_three_decimal_currency() {
amount_f64 / 1000.00
} else {
amount_f64 / 100.00
};
Ok(amount)
}
///Convert the higher decimal amount to its base absolute units
pub fn to_currency_lower_unit(self, amount: String) -> Result<String, ParseFloatError> {
let amount_f64 = amount.parse::<f64>()?;
let amount_string = if self.is_zero_decimal_currency() {
amount_f64
} else if self.is_three_decimal_currency() {
amount_f64 * 1000.00
} else {
amount_f64 * 100.00
};
Ok(amount_string.to_string())
}
/// Convert the amount to its base denomination based on Currency and check for zero decimal currency and return String
/// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies.
/// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/
pub fn to_currency_base_unit_with_zero_decimal_check(
self,
amount: i64,
) -> Result<String, TryFromIntError> {
let amount_f64 = self.to_currency_base_unit_asf64(amount)?;
if self.is_zero_decimal_currency() {
Ok(amount_f64.to_string())
} else {
Ok(format!("{amount_f64:.2}"))
}
}
pub fn iso_4217(self) -> &'static str {
match self {
Self::AED => "784",
Self::AFN => "971",
Self::ALL => "008",
Self::AMD => "051",
Self::ANG => "532",
Self::AOA => "973",
Self::ARS => "032",
Self::AUD => "036",
Self::AWG => "533",
Self::AZN => "944",
Self::BAM => "977",
Self::BBD => "052",
Self::BDT => "050",
Self::BGN => "975",
Self::BHD => "048",
Self::BIF => "108",
Self::BMD => "060",
Self::BND => "096",
Self::BOB => "068",
Self::BRL => "986",
Self::BSD => "044",
Self::BTN => "064",
Self::BWP => "072",
Self::BYN => "933",
Self::BZD => "084",
Self::CAD => "124",
Self::CDF => "976",
Self::CHF => "756",
Self::CLF => "990",
Self::CLP => "152",
Self::COP => "170",
Self::CRC => "188",
Self::CUC => "931",
Self::CUP => "192",
Self::CVE => "132",
Self::CZK => "203",
Self::DJF => "262",
Self::DKK => "208",
Self::DOP => "214",
Self::DZD => "012",
Self::EGP => "818",
Self::ERN => "232",
Self::ETB => "230",
Self::EUR => "978",
Self::FJD => "242",
Self::FKP => "238",
Self::GBP => "826",
Self::GEL => "981",
Self::GHS => "936",
Self::GIP => "292",
Self::GMD => "270",
Self::GNF => "324",
Self::GTQ => "320",
Self::GYD => "328",
Self::HKD => "344",
Self::HNL => "340",
Self::HTG => "332",
Self::HUF => "348",
Self::HRK => "191",
Self::IDR => "360",
Self::ILS => "376",
Self::INR => "356",
Self::IQD => "368",
Self::IRR => "364",
Self::ISK => "352",
Self::JMD => "388",
Self::JOD => "400",
Self::JPY => "392",
Self::KES => "404",
Self::KGS => "417",
Self::KHR => "116",
Self::KMF => "174",
Self::KPW => "408",
Self::KRW => "410",
Self::KWD => "414",
Self::KYD => "136",
Self::KZT => "398",
Self::LAK => "418",
Self::LBP => "422",
Self::LKR => "144",
Self::LRD => "430",
Self::LSL => "426",
Self::LYD => "434",
Self::MAD => "504",
Self::MDL => "498",
Self::MGA => "969",
Self::MKD => "807",
Self::MMK => "104",
Self::MNT => "496",
Self::MOP => "446",
Self::MRU => "929",
Self::MUR => "480",
Self::MVR => "462",
Self::MWK => "454",
Self::MXN => "484",
Self::MYR => "458",
Self::MZN => "943",
Self::NAD => "516",
Self::NGN => "566",
Self::NIO => "558",
Self::NOK => "578",
Self::NPR => "524",
Self::NZD => "554",
Self::OMR => "512",
Self::PAB => "590",
Self::PEN => "604",
Self::PGK => "598",
Self::PHP => "608",
Self::PKR => "586",
Self::PLN => "985",
Self::PYG => "600",
Self::QAR => "634",
Self::RON => "946",
Self::CNY => "156",
Self::RSD => "941",
Self::RUB => "643",
Self::RWF => "646",
Self::SAR => "682",
Self::SBD => "090",
Self::SCR => "690",
Self::SDG => "938",
Self::SEK => "752",
Self::SGD => "702",
Self::SHP => "654",
Self::SLE => "925",
Self::SLL => "694",
Self::SOS => "706",
Self::SRD => "968",
Self::SSP => "728",
Self::STD => "678",
Self::STN => "930",
Self::SVC => "222",
Self::SYP => "760",
Self::SZL => "748",
Self::THB => "764",
Self::TJS => "972",
Self::TMT => "934",
Self::TND => "788",
Self::TOP => "776",
Self::TRY => "949",
Self::TTD => "780",
Self::TWD => "901",
Self::TZS => "834",
Self::UAH => "980",
Self::UGX => "800",
Self::USD => "840",
Self::UYU => "858",
Self::UZS => "860",
Self::VES => "928",
Self::VND => "704",
Self::VUV => "548",
Self::WST => "882",
Self::XAF => "950",
Self::XCD => "951",
Self::XOF => "952",
Self::XPF => "953",
Self::YER => "886",
Self::ZAR => "710",
Self::ZMW => "967",
Self::ZWL => "932",
}
}
pub fn is_zero_decimal_currency(self) -> bool {
match self {
Self::BIF
| Self::CLP
| Self::DJF
| Self::GNF
| Self::IRR
| Self::JPY
| Self::KMF
| Self::KRW
| Self::MGA
| Self::PYG
| Self::RWF
| Self::UGX
| Self::VND
| Self::VUV
| Self::XAF
| Self::XOF
| Self::XPF => true,
Self::AED
| Self::AFN
| Self::ALL
| Self::AMD
| Self::ANG
| Self::AOA
| Self::ARS
| Self::AUD
| Self::AWG
| Self::AZN
| Self::BAM
| Self::BBD
| Self::BDT
| Self::BGN
| Self::BHD
| Self::BMD
| Self::BND
| Self::BOB
| Self::BRL
| Self::BSD
| Self::BTN
| Self::BWP
| Self::BYN
| Self::BZD
| Self::CAD
| Self::CDF
| Self::CHF
| Self::CLF
| Self::CNY
| Self::COP
| Self::CRC
| Self::CUC
| Self::CUP
| Self::CVE
| Self::CZK
| Self::DKK
| Self::DOP
| Self::DZD
| Self::EGP
| Self::ERN
| Self::ETB
| Self::EUR
| Self::FJD
| Self::FKP
| Self::GBP
| Self::GEL
| Self::GHS
| Self::GIP
| Self::GMD
| Self::GTQ
| Self::GYD
| Self::HKD
| Self::HNL
| Self::HRK
| Self::HTG
| Self::HUF
| Self::IDR
| Self::ILS
| Self::INR
| Self::IQD
| Self::ISK
| Self::JMD
| Self::JOD
| Self::KES
| Self::KGS
| Self::KHR
| Self::KPW
| Self::KWD
| Self::KYD
| Self::KZT
| Self::LAK
| Self::LBP
| Self::LKR
| Self::LRD
| Self::LSL
| Self::LYD
| Self::MAD
| Self::MDL
| Self::MKD
| Self::MMK
| Self::MNT
| Self::MOP
| Self::MRU
| Self::MUR
| Self::MVR
| Self::MWK
| Self::MXN
| Self::MYR
| Self::MZN
| Self::NAD
| Self::NGN
| Self::NIO
| Self::NOK
| Self::NPR
| Self::NZD
| Self::OMR
| Self::PAB
| Self::PEN
| Self::PGK
| Self::PHP
| Self::PKR
| Self::PLN
| Self::QAR
| Self::RON
| Self::RSD
| Self::RUB
| Self::SAR
| Self::SBD
| Self::SCR
| Self::SDG
| Self::SEK
| Self::SGD
| Self::SHP
| Self::SLE
| Self::SLL
| Self::SOS
| Self::SRD
| Self::SSP
| Self::STD
| Self::STN
| Self::SVC
| Self::SYP
| Self::SZL
| Self::THB
| Self::TJS
| Self::TMT
| Self::TND
| Self::TOP
| Self::TRY
| Self::TTD
| Self::TWD
| Self::TZS
| Self::UAH
| Self::USD
| Self::UYU
| Self::UZS
| Self::VES
| Self::WST
| Self::XCD
| Self::YER
| Self::ZAR
| Self::ZMW
| Self::ZWL => false,
}
}
pub fn is_three_decimal_currency(self) -> bool {
match self {
Self::BHD | Self::IQD | Self::JOD | Self::KWD | Self::LYD | Self::OMR | Self::TND => {
true
}
Self::AED
| Self::AFN
| Self::ALL
| Self::AMD
| Self::AOA
| Self::ANG
| Self::ARS
| Self::AUD
| Self::AWG
| Self::AZN
| Self::BAM
| Self::BBD
| Self::BDT
| Self::BGN
| Self::BIF
| Self::BMD
| Self::BND
| Self::BOB
| Self::BRL
| Self::BSD
| Self::BTN
| Self::BWP
| Self::BYN
| Self::BZD
| Self::CAD
| Self::CDF
| Self::CHF
| Self::CLF
| Self::CLP
| Self::CNY
| Self::COP
| Self::CRC
| Self::CUC
| Self::CUP
| Self::CVE
| Self::CZK
| Self::DJF
| Self::DKK
| Self::DOP
| Self::DZD
| Self::EGP
| Self::ERN
| Self::ETB
| Self::EUR
| Self::FJD
| Self::FKP
| Self::GBP
| Self::GEL
| Self::GHS
| Self::GIP
| Self::GMD
| Self::GNF
| Self::GTQ
| Self::GYD
| Self::HKD
| Self::HNL
| Self::HRK
| Self::HTG
| Self::HUF
| Self::IDR
| Self::ILS
| Self::INR
| Self::IRR
| Self::ISK
| Self::JMD
| Self::JPY
| Self::KES
| Self::KGS
| Self::KHR
| Self::KMF
| Self::KPW
| Self::KRW
| Self::KYD
| Self::KZT
| Self::LAK
| Self::LBP
| Self::LKR
| Self::LRD
| Self::LSL
| Self::MAD
| Self::MDL
| Self::MGA
| Self::MKD
| Self::MMK
| Self::MNT
| Self::MOP
| Self::MRU
| Self::MUR
| Self::MVR
| Self::MWK
| Self::MXN
| Self::MYR
| Self::MZN
| Self::NAD
| Self::NGN
| Self::NIO
| Self::NOK
| Self::NPR
| Self::NZD
| Self::PAB
| Self::PEN
| Self::PGK
| Self::PHP
| Self::PKR
| Self::PLN
| Self::PYG
| Self::QAR
| Self::RON
| Self::RSD
| Self::RUB
| Self::RWF
| Self::SAR
| Self::SBD
| Self::SCR
| Self::SDG
| Self::SEK
| Self::SGD
| Self::SHP
| Self::SLE
| Self::SLL
| Self::SOS
| Self::SRD
| Self::SSP
| Self::STD
| Self::STN
| Self::SVC
| Self::SYP
| Self::SZL
| Self::THB
| Self::TJS
| Self::TMT
| Self::TOP
| Self::TRY
| Self::TTD
| Self::TWD
| Self::TZS
| Self::UAH
| Self::UGX
| Self::USD
| Self::UYU
| Self::UZS
| Self::VES
| Self::VND
| Self::VUV
| Self::WST
| Self::XAF
| Self::XCD
| Self::XPF
| Self::XOF
| Self::YER
| Self::ZAR
| Self::ZMW
| Self::ZWL => false,
}
}
pub fn is_four_decimal_currency(self) -> bool {
match self {
Self::CLF => true,
Self::AED
| Self::AFN
| Self::ALL
| Self::AMD
| Self::AOA
| Self::ANG
| Self::ARS
| Self::AUD
| Self::AWG
| Self::AZN
| Self::BAM
| Self::BBD
| Self::BDT
| Self::BGN
| Self::BHD
| Self::BIF
| Self::BMD
| Self::BND
| Self::BOB
| Self::BRL
| Self::BSD
| Self::BTN
| Self::BWP
| Self::BYN
| Self::BZD
| Self::CAD
| Self::CDF
| Self::CHF
| Self::CLP
| Self::CNY
| Self::COP
| Self::CRC
| Self::CUC
| Self::CUP
| Self::CVE
| Self::CZK
| Self::DJF
| Self::DKK
| Self::DOP
| Self::DZD
| Self::EGP
| Self::ERN
| Self::ETB
| Self::EUR
| Self::FJD
| Self::FKP
| Self::GBP
| Self::GEL
| Self::GHS
| Self::GIP
| Self::GMD
| Self::GNF
| Self::GTQ
| Self::GYD
| Self::HKD
| Self::HNL
| Self::HRK
| Self::HTG
| Self::HUF
| Self::IDR
| Self::ILS
| Self::INR
| Self::IQD
| Self::IRR
| Self::ISK
| Self::JMD
| Self::JOD
| Self::JPY
| Self::KES
| Self::KGS
| Self::KHR
| Self::KMF
| Self::KPW
| Self::KRW
| Self::KWD
| Self::KYD
| Self::KZT
| Self::LAK
| Self::LBP
| Self::LKR
| Self::LRD
| Self::LSL
| Self::LYD
| Self::MAD
| Self::MDL
| Self::MGA
| Self::MKD
| Self::MMK
| Self::MNT
| Self::MOP
| Self::MRU
| Self::MUR
| Self::MVR
| Self::MWK
| Self::MXN
| Self::MYR
| Self::MZN
| Self::NAD
| Self::NGN
| Self::NIO
| Self::NOK
| Self::NPR
| Self::NZD
| Self::OMR
| Self::PAB
| Self::PEN
| Self::PGK
| Self::PHP
| Self::PKR
| Self::PLN
| Self::PYG
| Self::QAR
| Self::RON
| Self::RSD
| Self::RUB
| Self::RWF
| Self::SAR
| Self::SBD
| Self::SCR
| Self::SDG
| Self::SEK
| Self::SGD
| Self::SHP
| Self::SLE
| Self::SLL
| Self::SOS
| Self::SRD
| Self::SSP
| Self::STD
| Self::STN
| Self::SVC
| Self::SYP
| Self::SZL
| Self::THB
| Self::TJS
| Self::TMT
| Self::TND
| Self::TOP
| Self::TRY
| Self::TTD
| Self::TWD
| Self::TZS
| Self::UAH
| Self::UGX
| Self::USD
| Self::UYU
| Self::UZS
| Self::VES
| Self::VND
| Self::VUV
| Self::WST
| Self::XAF
| Self::XCD
| Self::XPF
| Self::XOF
| Self::YER
| Self::ZAR
| Self::ZMW
| Self::ZWL => false,
}
}
pub fn number_of_digits_after_decimal_point(self) -> u8 {
if self.is_zero_decimal_currency() {
0
} else if self.is_three_decimal_currency() {
3
} else if self.is_four_decimal_currency() {
4
} else {
2
}
}
}
#[derive(
Clone,
Copy,
Debug,
Hash,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum EventClass {
Payments,
Refunds,
Disputes,
Mandates,
#[cfg(feature = "payouts")]
Payouts,
}
impl EventClass {
#[inline]
pub fn event_types(self) -> HashSet<EventType> {
match self {
Self::Payments => HashSet::from([
EventType::PaymentSucceeded,
EventType::PaymentFailed,
EventType::PaymentProcessing,
EventType::PaymentCancelled,
EventType::PaymentCancelledPostCapture,
EventType::PaymentAuthorized,
EventType::PaymentCaptured,
EventType::PaymentExpired,
EventType::ActionRequired,
]),
Self::Refunds => HashSet::from([EventType::RefundSucceeded, EventType::RefundFailed]),
Self::Disputes => HashSet::from([
EventType::DisputeOpened,
EventType::DisputeExpired,
EventType::DisputeAccepted,
EventType::DisputeCancelled,
EventType::DisputeChallenged,
EventType::DisputeWon,
EventType::DisputeLost,
]),
Self::Mandates => HashSet::from([EventType::MandateActive, EventType::MandateRevoked]),
#[cfg(feature = "payouts")]
Self::Payouts => HashSet::from([
EventType::PayoutSuccess,
EventType::PayoutFailed,
EventType::PayoutInitiated,
EventType::PayoutProcessing,
EventType::PayoutCancelled,
EventType::PayoutExpired,
EventType::PayoutReversed,
]),
}
}
}
#[derive(
Clone,
Copy,
Debug,
Hash,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
// Reminder: Whenever an EventType variant is added or removed, make sure to update the `event_types` method in `EventClass`
pub enum EventType {
/// Authorize + Capture success
PaymentSucceeded,
/// Authorize + Capture failed
PaymentFailed,
PaymentProcessing,
PaymentCancelled,
PaymentCancelledPostCapture,
PaymentAuthorized,
PaymentPartiallyAuthorized,
PaymentCaptured,
PaymentExpired,
ActionRequired,
RefundSucceeded,
RefundFailed,
DisputeOpened,
DisputeExpired,
DisputeAccepted,
DisputeCancelled,
DisputeChallenged,
DisputeWon,
DisputeLost,
MandateActive,
MandateRevoked,
#[cfg(feature = "payouts")]
PayoutSuccess,
#[cfg(feature = "payouts")]
PayoutFailed,
#[cfg(feature = "payouts")]
PayoutInitiated,
#[cfg(feature = "payouts")]
PayoutProcessing,
#[cfg(feature = "payouts")]
PayoutCancelled,
#[cfg(feature = "payouts")]
PayoutExpired,
#[cfg(feature = "payouts")]
PayoutReversed,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum WebhookDeliveryAttempt {
InitialAttempt,
AutomaticRetry,
ManualRetry,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum OutgoingWebhookEndpointStatus {
/// The webhook endpoint is active and operational.
Active,
/// The webhook endpoint is temporarily disabled.
Inactive,
/// The webhook endpoint is deprecated and can no longer be reactivated.
Deprecated,
}
// TODO: This decision about using KV mode or not,
// should be taken at a top level rather than pushing it down to individual functions via an enum.
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum MerchantStorageScheme {
#[default]
PostgresOnly,
RedisKv,
}
/// Represents the overall status of a payment intent.
/// The status transitions through various states depending on the payment method, confirmation, capture method, and any subsequent actions (like customer authentication or manual capture).
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
ToSchema,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumIter,
strum::EnumString,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum IntentStatus {
/// The payment has succeeded. Refunds and disputes can be initiated.
/// Manual retries are not allowed to be performed.
Succeeded,
/// The payment has failed. Refunds and disputes cannot be initiated.
/// This payment can be retried manually with a new payment attempt.
Failed,
/// This payment has been cancelled.
Cancelled,
/// This payment has been cancelled post capture.
CancelledPostCapture,
/// This payment is still being processed by the payment processor.
/// The status update might happen through webhooks or polling with the connector.
Processing,
/// The payment is waiting on some action from the customer.
RequiresCustomerAction,
/// The payment is waiting on some action from the merchant
/// This would be in case of manual fraud approval
RequiresMerchantAction,
/// The payment is waiting to be confirmed with the payment method by the customer.
RequiresPaymentMethod,
#[default]
RequiresConfirmation,
/// The payment has been authorized, and it waiting to be captured.
RequiresCapture,
/// The payment has been captured partially. The remaining amount is cannot be captured.
PartiallyCaptured,
/// The payment has been captured partially and the remaining amount is capturable
PartiallyCapturedAndCapturable,
/// The payment has been authorized for a partial amount and requires capture
PartiallyAuthorizedAndRequiresCapture,
/// There has been a discrepancy between the amount/currency sent in the request and the amount/currency received by the processor
Conflicted,
/// The payment expired before it could be captured.
Expired,
}
impl IntentStatus {
/// Indicates whether the payment intent is in terminal state or not
pub fn is_in_terminal_state(self) -> bool {
match self {
Self::Succeeded
| Self::Failed
| Self::Cancelled
| Self::CancelledPostCapture
| Self::PartiallyCaptured
| Self::Expired => true,
Self::Processing
| Self::RequiresCustomerAction
| Self::RequiresMerchantAction
| Self::RequiresPaymentMethod
| Self::RequiresConfirmation
| Self::RequiresCapture
| Self::PartiallyCapturedAndCapturable
| Self::PartiallyAuthorizedAndRequiresCapture
| Self::Conflicted => false,
}
}
/// Indicates whether the syncing with the connector should be allowed or not
pub fn should_force_sync_with_connector(self) -> bool {
match self {
// Confirm has not happened yet
Self::RequiresConfirmation
| Self::RequiresPaymentMethod
// Once the status is success, failed or cancelled need not force sync with the connector
| Self::Succeeded
| Self::Failed
| Self::Cancelled
| Self::CancelledPostCapture
| Self::PartiallyCaptured
| Self::RequiresCapture | Self::Conflicted | Self::Expired=> false,
Self::Processing
| Self::RequiresCustomerAction
| Self::RequiresMerchantAction
| Self::PartiallyCapturedAndCapturable
| Self::PartiallyAuthorizedAndRequiresCapture => true,
}
}
}
/// Specifies how the payment method can be used for future payments.
/// - `off_session`: The payment method can be used for future payments when the customer is not present.
/// - `on_session`: The payment method is intended for use only when the customer is present during checkout.
/// If omitted, defaults to `on_session`.
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum FutureUsage {
OffSession,
#[default]
OnSession,
}
impl FutureUsage {
/// Indicates whether the payment method should be saved for future use or not
pub fn is_off_session(self) -> bool {
match self {
Self::OffSession => true,
Self::OnSession => false,
}
}
}
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum PaymentMethodIssuerCode {
JpHdfc,
JpIcici,
JpGooglepay,
JpApplepay,
JpPhonepay,
JpWechat,
JpSofort,
JpGiropay,
JpSepa,
JpBacs,
}
/// Payment Method Status
#[derive(
Clone,
Copy,
Debug,
PartialEq,
Eq,
Hash,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum PaymentMethodStatus {
/// Indicates that the payment method is active and can be used for payments.
Active,
/// Indicates that the payment method is not active and hence cannot be used for payments.
Inactive,
/// Indicates that the payment method is awaiting some data or action before it can be marked
/// as 'active'.
Processing,
/// Indicates that the payment method is awaiting some data before changing state to active
AwaitingData,
}
impl From<AttemptStatus> for PaymentMethodStatus {
fn from(attempt_status: AttemptStatus) -> Self {
match attempt_status {
AttemptStatus::Failure
| AttemptStatus::Voided
| AttemptStatus::VoidedPostCharge
| AttemptStatus::Started
| AttemptStatus::Pending
| AttemptStatus::Unresolved
| AttemptStatus::CodInitiated
| AttemptStatus::Authorizing
| AttemptStatus::VoidInitiated
| AttemptStatus::AuthorizationFailed
| AttemptStatus::RouterDeclined
| AttemptStatus::AuthenticationSuccessful
| AttemptStatus::PaymentMethodAwaited
| AttemptStatus::AuthenticationFailed
| AttemptStatus::AuthenticationPending
| AttemptStatus::CaptureInitiated
| AttemptStatus::CaptureFailed
| AttemptStatus::VoidFailed
| AttemptStatus::AutoRefunded
| AttemptStatus::PartialCharged
| AttemptStatus::PartialChargedAndChargeable
| AttemptStatus::PartiallyAuthorized
| AttemptStatus::ConfirmationAwaited
| AttemptStatus::DeviceDataCollectionPending
| AttemptStatus::IntegrityFailure
| AttemptStatus::Expired => Self::Inactive,
AttemptStatus::Charged | AttemptStatus::Authorized => Self::Active,
}
}
}
/// To indicate the type of payment experience that the customer would go through
#[derive(
Eq,
strum::EnumString,
PartialEq,
Hash,
Copy,
Clone,
Debug,
serde::Serialize,
serde::Deserialize,
strum::Display,
ToSchema,
Default,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum PaymentExperience {
/// The URL to which the customer needs to be redirected for completing the payment.
#[default]
RedirectToUrl,
/// Contains the data for invoking the sdk client for completing the payment.
InvokeSdkClient,
/// The QR code data to be displayed to the customer.
DisplayQrCode,
/// Contains data to finish one click payment.
OneClick,
/// Redirect customer to link wallet
LinkWallet,
/// Contains the data for invoking the sdk client for completing the payment.
InvokePaymentApp,
/// Contains the data for displaying wait screen
DisplayWaitScreen,
/// Represents that otp needs to be collect and contains if consent is required
CollectOtp,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display)]
#[serde(rename_all = "lowercase")]
pub enum SamsungPayCardBrand {
Visa,
MasterCard,
Amex,
Discover,
Unknown,
}
/// Indicates the sub type of payment method. Eg: 'google_pay' & 'apple_pay' for wallets.
#[derive(
Clone,
Copy,
Debug,
Eq,
Ord,
Hash,
PartialOrd,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PaymentMethodType {
Ach,
Affirm,
AfterpayClearpay,
Alfamart,
AliPay,
AliPayHk,
Alma,
AmazonPay,
Paysera,
ApplePay,
Atome,
Bacs,
BancontactCard,
Becs,
Benefit,
Bizum,
Blik,
Bluecode,
Boleto,
BcaBankTransfer,
BniVa,
Breadpay,
BriVa,
BhnCardNetwork,
#[cfg(feature = "v2")]
Card,
CardRedirect,
CimbVa,
#[serde(rename = "classic")]
ClassicReward,
Credit,
CryptoCurrency,
Cashapp,
Dana,
DanamonVa,
Debit,
DuitNow,
Efecty,
Eft,
Eps,
Flexiti,
Fps,
Evoucher,
Giropay,
Givex,
GooglePay,
GoPay,
Gcash,
Ideal,
Interac,
Indomaret,
Klarna,
KakaoPay,
LocalBankRedirect,
MandiriVa,
Knet,
MbWay,
MobilePay,
Momo,
MomoAtm,
Multibanco,
OnlineBankingThailand,
OnlineBankingCzechRepublic,
OnlineBankingFinland,
OnlineBankingFpx,
OnlineBankingPoland,
OnlineBankingSlovakia,
Oxxo,
PagoEfectivo,
PermataBankTransfer,
OpenBankingUk,
PayBright,
Paypal,
Paze,
Pix,
PaySafeCard,
Przelewy24,
PromptPay,
Pse,
RedCompra,
RedPagos,
SamsungPay,
Sepa,
SepaBankTransfer,
SepaGuarenteedDebit,
Skrill,
Sofort,
Swish,
TouchNGo,
Trustly,
Twint,
UpiCollect,
UpiIntent,
UpiQr,
Vipps,
VietQr,
Venmo,
Walley,
WeChatPay,
SevenEleven,
Lawson,
MiniStop,
FamilyMart,
Seicomart,
PayEasy,
LocalBankTransfer,
Mifinity,
#[serde(rename = "open_banking_pis")]
OpenBankingPIS,
DirectCarrierBilling,
InstantBankTransfer,
InstantBankTransferFinland,
InstantBankTransferPoland,
RevolutPay,
IndonesianBankTransfer,
}
impl PaymentMethodType {
pub fn should_check_for_customer_saved_payment_method_type(self) -> bool {
matches!(
self,
Self::ApplePay | Self::GooglePay | Self::SamsungPay | Self::Paypal | Self::Klarna
)
}
pub fn to_display_name(&self) -> String {
let display_name = match self {
Self::Ach => "ACH Direct Debit",
Self::Bacs => "BACS Direct Debit",
Self::Affirm => "Affirm",
Self::AfterpayClearpay => "Afterpay Clearpay",
Self::Alfamart => "Alfamart",
Self::AliPay => "Alipay",
Self::AliPayHk => "AlipayHK",
Self::Alma => "Alma",
Self::AmazonPay => "Amazon Pay",
Self::Paysera => "Paysera",
Self::ApplePay => "Apple Pay",
Self::Atome => "Atome",
Self::BancontactCard => "Bancontact Card",
Self::Becs => "BECS Direct Debit",
Self::Benefit => "Benefit",
Self::Bizum => "Bizum",
Self::Blik => "BLIK",
Self::Bluecode => "Bluecode",
Self::Boleto => "Boleto Bancário",
Self::BcaBankTransfer => "BCA Bank Transfer",
Self::BniVa => "BNI Virtual Account",
Self::Breadpay => "Breadpay",
Self::BriVa => "BRI Virtual Account",
Self::BhnCardNetwork => "BHN Card Network",
Self::CardRedirect => "Card Redirect",
Self::CimbVa => "CIMB Virtual Account",
Self::ClassicReward => "Classic Reward",
#[cfg(feature = "v2")]
Self::Card => "Card",
Self::Credit => "Credit Card",
Self::CryptoCurrency => "Crypto",
Self::Cashapp => "Cash App",
Self::Dana => "DANA",
Self::DanamonVa => "Danamon Virtual Account",
Self::Debit => "Debit Card",
Self::DuitNow => "DuitNow",
Self::Efecty => "Efecty",
Self::Eft => "EFT",
Self::Eps => "EPS",
Self::Flexiti => "Flexiti",
Self::Fps => "FPS",
Self::Evoucher => "Evoucher",
Self::Giropay => "Giropay",
Self::Givex => "Givex",
Self::GooglePay => "Google Pay",
Self::GoPay => "GoPay",
Self::Gcash => "GCash",
Self::Ideal => "iDEAL",
Self::Interac => "Interac",
Self::Indomaret => "Indomaret",
Self::InstantBankTransfer => "Instant Bank Transfer",
Self::InstantBankTransferFinland => "Instant Bank Transfer Finland",
Self::InstantBankTransferPoland => "Instant Bank Transfer Poland",
Self::Klarna => "Klarna",
Self::KakaoPay => "KakaoPay",
Self::LocalBankRedirect => "Local Bank Redirect",
Self::MandiriVa => "Mandiri Virtual Account",
Self::Knet => "KNET",
Self::MbWay => "MB WAY",
Self::MobilePay => "MobilePay",
Self::Momo => "MoMo",
Self::MomoAtm => "MoMo ATM",
Self::Multibanco => "Multibanco",
Self::OnlineBankingThailand => "Online Banking Thailand",
Self::OnlineBankingCzechRepublic => "Online Banking Czech Republic",
Self::OnlineBankingFinland => "Online Banking Finland",
Self::OnlineBankingFpx => "Online Banking FPX",
Self::OnlineBankingPoland => "Online Banking Poland",
Self::OnlineBankingSlovakia => "Online Banking Slovakia",
Self::Oxxo => "OXXO",
Self::PagoEfectivo => "PagoEfectivo",
Self::PermataBankTransfer => "Permata Bank Transfer",
Self::OpenBankingUk => "Open Banking UK",
Self::PayBright => "PayBright",
Self::Paypal => "PayPal",
Self::Paze => "Paze",
Self::Pix => "Pix",
Self::PaySafeCard => "PaySafeCard",
Self::Przelewy24 => "Przelewy24",
Self::PromptPay => "PromptPay",
Self::Pse => "PSE",
Self::RedCompra => "RedCompra",
Self::RedPagos => "RedPagos",
Self::SamsungPay => "Samsung Pay",
Self::Sepa => "SEPA Direct Debit",
Self::SepaGuarenteedDebit => "SEPA Guarenteed Direct Debit",
Self::SepaBankTransfer => "SEPA Bank Transfer",
Self::Sofort => "Sofort",
Self::Skrill => "Skrill",
Self::Swish => "Swish",
Self::TouchNGo => "Touch 'n Go",
Self::Trustly => "Trustly",
Self::Twint => "TWINT",
Self::UpiCollect => "UPI Collect",
Self::UpiIntent => "UPI Intent",
Self::UpiQr => "UPI QR",
Self::Vipps => "Vipps",
Self::VietQr => "VietQR",
Self::Venmo => "Venmo",
Self::Walley => "Walley",
Self::WeChatPay => "WeChat Pay",
Self::SevenEleven => "7-Eleven",
Self::Lawson => "Lawson",
Self::MiniStop => "Mini Stop",
Self::FamilyMart => "FamilyMart",
Self::Seicomart => "Seicomart",
Self::PayEasy => "PayEasy",
Self::LocalBankTransfer => "Local Bank Transfer",
Self::Mifinity => "MiFinity",
Self::OpenBankingPIS => "Open Banking PIS",
Self::DirectCarrierBilling => "Direct Carrier Billing",
Self::RevolutPay => "RevolutPay",
Self::IndonesianBankTransfer => "Indonesian Bank Transfer",
};
display_name.to_string()
}
}
impl masking::SerializableSecret for PaymentMethodType {}
/// Indicates the type of payment method. Eg: 'card', 'wallet', etc.
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialOrd,
Ord,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PaymentMethod {
#[default]
Card,
CardRedirect,
PayLater,
Wallet,
BankRedirect,
BankTransfer,
Crypto,
BankDebit,
Reward,
RealTimePayment,
Upi,
Voucher,
GiftCard,
OpenBanking,
MobilePayment,
}
/// Indicates the gateway system through which the payment is processed.
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialOrd,
Ord,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum GatewaySystem {
#[default]
Direct,
UnifiedConnectorService,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialOrd,
Ord,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
/// Indicates the execution path through which the payment is processed.
pub enum ExecutionPath {
#[default]
Direct,
UnifiedConnectorService,
ShadowUnifiedConnectorService,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialOrd,
Ord,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ShadowRolloutAvailability {
IsAvailable,
NotAvailable,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialOrd,
Ord,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum UcsAvailability {
Enabled,
Disabled,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialOrd,
Ord,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ExecutionMode {
#[default]
Primary,
Shadow,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialOrd,
Ord,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ConnectorIntegrationType {
UcsConnector,
DirectConnector,
}
/// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow.
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PaymentType {
#[default]
Normal,
NewMandate,
SetupMandate,
RecurringMandate,
}
/// SCA Exemptions types available for authentication
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ScaExemptionType {
#[default]
LowValue,
TransactionRiskAnalysis,
}
#[derive(
Clone,
Debug,
Default,
Eq,
PartialOrd,
Ord,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
/// Describes the channel through which the payment was initiated.
pub enum PaymentChannel {
#[default]
Ecommerce,
MailOrder,
TelephoneOrder,
#[serde(untagged)]
#[strum(default)]
Other(String),
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CtpServiceProvider {
Visa,
Mastercard,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
strum::Display,
strum::EnumString,
strum::EnumIter,
serde::Serialize,
serde::Deserialize,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum RefundStatus {
#[serde(alias = "Failure")]
Failure,
#[serde(alias = "ManualReview")]
ManualReview,
#[default]
#[serde(alias = "Pending")]
Pending,
#[serde(alias = "Success")]
Success,
#[serde(alias = "TransactionFailure")]
TransactionFailure,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
strum::Display,
strum::EnumString,
strum::EnumIter,
serde::Serialize,
serde::Deserialize,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum RelayStatus {
Created,
#[default]
Pending,
Success,
Failure,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
strum::Display,
strum::EnumString,
strum::EnumIter,
serde::Serialize,
serde::Deserialize,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum RelayType {
Refund,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
strum::Display,
strum::EnumString,
strum::EnumIter,
serde::Serialize,
serde::Deserialize,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "snake_case")]
pub enum FrmTransactionType {
#[default]
PreFrm,
PostFrm,
}
/// The status of the mandate, which indicates whether it can be used to initiate a payment.
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
Default,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum MandateStatus {
#[default]
Active,
Inactive,
Pending,
Revoked,
}
/// Indicates the card network.
#[derive(
Clone,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
pub enum CardNetwork {
#[serde(alias = "VISA")]
Visa,
#[serde(alias = "MASTERCARD")]
Mastercard,
#[serde(alias = "AMERICANEXPRESS")]
#[serde(alias = "AMEX")]
AmericanExpress,
JCB,
#[serde(alias = "DINERSCLUB")]
DinersClub,
#[serde(alias = "DISCOVER")]
Discover,
#[serde(alias = "CARTESBANCAIRES")]
CartesBancaires,
#[serde(alias = "UNIONPAY")]
UnionPay,
#[serde(alias = "INTERAC")]
Interac,
#[serde(alias = "RUPAY")]
RuPay,
#[serde(alias = "MAESTRO")]
Maestro,
#[serde(alias = "STAR")]
Star,
#[serde(alias = "PULSE")]
Pulse,
#[serde(alias = "ACCEL")]
Accel,
#[serde(alias = "NYCE")]
Nyce,
}
#[derive(
Clone,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumIter,
strum::EnumString,
utoipa::ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
pub enum RegulatedName {
#[serde(rename = "GOVERNMENT NON-EXEMPT INTERCHANGE FEE (WITH FRAUD)")]
#[strum(serialize = "GOVERNMENT NON-EXEMPT INTERCHANGE FEE (WITH FRAUD)")]
NonExemptWithFraud,
#[serde(untagged)]
#[strum(default)]
Unknown(String),
}
#[derive(
Clone,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumIter,
strum::EnumString,
utoipa::ToSchema,
Copy,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "lowercase")]
pub enum PanOrToken {
Pan,
Token,
}
#[derive(
Clone,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumIter,
strum::EnumString,
utoipa::ToSchema,
Copy,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "UPPERCASE")]
#[serde(rename_all = "snake_case")]
pub enum CardType {
Credit,
Debit,
}
#[derive(Debug, Clone, Serialize, Deserialize, strum::EnumString, strum::Display)]
#[serde(rename_all = "snake_case")]
pub enum DecisionEngineMerchantCategoryCode {
#[serde(rename = "merchant_category_code_0001")]
Mcc0001,
}
impl CardNetwork {
pub fn is_signature_network(&self) -> bool {
match self {
Self::Interac
| Self::Star
| Self::Pulse
| Self::Accel
| Self::Nyce
| Self::CartesBancaires => false,
Self::Visa
| Self::Mastercard
| Self::AmericanExpress
| Self::JCB
| Self::DinersClub
| Self::Discover
| Self::UnionPay
| Self::RuPay
| Self::Maestro => true,
}
}
pub fn is_us_local_network(&self) -> bool {
match self {
Self::Star | Self::Pulse | Self::Accel | Self::Nyce => true,
Self::Interac
| Self::CartesBancaires
| Self::Visa
| Self::Mastercard
| Self::AmericanExpress
| Self::JCB
| Self::DinersClub
| Self::Discover
| Self::UnionPay
| Self::RuPay
| Self::Maestro => false,
}
}
}
/// Stage of the dispute
#[derive(
Clone,
Copy,
Default,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum DisputeStage {
PreDispute,
#[default]
Dispute,
PreArbitration,
Arbitration,
DisputeReversal,
}
/// Status of the dispute
#[derive(
Clone,
Debug,
Copy,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum DisputeStatus {
#[default]
DisputeOpened,
DisputeExpired,
DisputeAccepted,
DisputeCancelled,
DisputeChallenged,
// dispute has been successfully challenged by the merchant
DisputeWon,
// dispute has been unsuccessfully challenged
DisputeLost,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
strum::VariantNames,
ToSchema,
)]
pub enum MerchantCategory {
#[serde(rename = "Grocery Stores, Supermarkets (5411)")]
GroceryStoresSupermarkets,
#[serde(rename = "Lodging-Hotels, Motels, Resorts-not elsewhere classified (7011)")]
LodgingHotelsMotelsResorts,
#[serde(rename = "Agricultural Cooperatives (0763)")]
AgriculturalCooperatives,
#[serde(rename = "Attorneys, Legal Services (8111)")]
AttorneysLegalServices,
#[serde(rename = "Office and Commercial Furniture (5021)")]
OfficeAndCommercialFurniture,
#[serde(rename = "Computer Network/Information Services (4816)")]
ComputerNetworkInformationServices,
#[serde(rename = "Shoe Stores (5661)")]
ShoeStores,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
strum::VariantNames,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
pub enum MerchantCategoryCode {
#[serde(rename = "5411")]
#[strum(serialize = "5411")]
Mcc5411,
#[serde(rename = "7011")]
#[strum(serialize = "7011")]
Mcc7011,
#[serde(rename = "0763")]
#[strum(serialize = "0763")]
Mcc0763,
#[serde(rename = "8111")]
#[strum(serialize = "8111")]
Mcc8111,
#[serde(rename = "5021")]
#[strum(serialize = "5021")]
Mcc5021,
#[serde(rename = "4816")]
#[strum(serialize = "4816")]
Mcc4816,
#[serde(rename = "5661")]
#[strum(serialize = "5661")]
Mcc5661,
}
impl MerchantCategoryCode {
pub fn to_merchant_category_name(&self) -> MerchantCategory {
match self {
Self::Mcc5411 => MerchantCategory::GroceryStoresSupermarkets,
Self::Mcc7011 => MerchantCategory::LodgingHotelsMotelsResorts,
Self::Mcc0763 => MerchantCategory::AgriculturalCooperatives,
Self::Mcc8111 => MerchantCategory::AttorneysLegalServices,
Self::Mcc5021 => MerchantCategory::OfficeAndCommercialFurniture,
Self::Mcc4816 => MerchantCategory::ComputerNetworkInformationServices,
Self::Mcc5661 => MerchantCategory::ShoeStores,
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)]
pub struct MerchantCategoryCodeWithName {
pub code: MerchantCategoryCode,
pub name: MerchantCategory,
}
#[derive(
Clone,
Debug,
Eq,
Default,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumIter,
strum::EnumString,
utoipa::ToSchema,
Copy
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[rustfmt::skip]
pub enum CountryAlpha2 {
AF, AX, AL, DZ, AS, AD, AO, AI, AQ, AG, AR, AM, AW, AU, AT,
AZ, BS, BH, BD, BB, BY, BE, BZ, BJ, BM, BT, BO, BQ, BA, BW,
BV, BR, IO, BN, BG, BF, BI, KH, CM, CA, CV, KY, CF, TD, CL,
CN, CX, CC, CO, KM, CG, CD, CK, CR, CI, HR, CU, CW, CY, CZ,
DK, DJ, DM, DO, EC, EG, SV, GQ, ER, EE, ET, FK, FO, FJ, FI,
FR, GF, PF, TF, GA, GM, GE, DE, GH, GI, GR, GL, GD, GP, GU,
GT, GG, GN, GW, GY, HT, HM, VA, HN, HK, HU, IS, IN, ID, IR,
IQ, IE, IM, IL, IT, JM, JP, JE, JO, KZ, KE, KI, KP, KR, KW,
KG, LA, LV, LB, LS, LR, LY, LI, LT, LU, MO, MK, MG, MW, MY,
MV, ML, MT, MH, MQ, MR, MU, YT, MX, FM, MD, MC, MN, ME, MS,
MA, MZ, MM, NA, NR, NP, NL, NC, NZ, NI, NE, NG, NU, NF, MP,
NO, OM, PK, PW, PS, PA, PG, PY, PE, PH, PN, PL, PT, PR, QA,
RE, RO, RU, RW, BL, SH, KN, LC, MF, PM, VC, WS, SM, ST, SA,
SN, RS, SC, SL, SG, SX, SK, SI, SB, SO, ZA, GS, SS, ES, LK,
SD, SR, SJ, SZ, SE, CH, SY, TW, TJ, TZ, TH, TL, TG, TK, TO,
TT, TN, TR, TM, TC, TV, UG, UA, AE, GB, UM, UY, UZ, VU,
VE, VN, VG, VI, WF, EH, YE, ZM, ZW,
#[default]
US
}
#[derive(
Clone,
Debug,
Copy,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RequestIncrementalAuthorization {
True,
#[default]
False,
Default,
}
#[derive(
Clone,
Debug,
Copy,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum SplitTxnsEnabled {
Enable,
#[default]
Skip,
}
#[derive(
Clone,
Debug,
Copy,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ActiveAttemptIDType {
AttemptsGroupID,
#[default]
AttemptID,
}
#[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize, strum::Display, ToSchema,)]
#[rustfmt::skip]
pub enum CountryAlpha3 {
AFG, ALA, ALB, DZA, ASM, AND, AGO, AIA, ATA, ATG, ARG, ARM, ABW, AUS, AUT,
AZE, BHS, BHR, BGD, BRB, BLR, BEL, BLZ, BEN, BMU, BTN, BOL, BES, BIH, BWA,
BVT, BRA, IOT, BRN, BGR, BFA, BDI, CPV, KHM, CMR, CAN, CYM, CAF, TCD, CHL,
CHN, CXR, CCK, COL, COM, COG, COD, COK, CRI, CIV, HRV, CUB, CUW, CYP, CZE,
DNK, DJI, DMA, DOM, ECU, EGY, SLV, GNQ, ERI, EST, ETH, FLK, FRO, FJI, FIN,
FRA, GUF, PYF, ATF, GAB, GMB, GEO, DEU, GHA, GIB, GRC, GRL, GRD, GLP, GUM,
GTM, GGY, GIN, GNB, GUY, HTI, HMD, VAT, HND, HKG, HUN, ISL, IND, IDN, IRN,
IRQ, IRL, IMN, ISR, ITA, JAM, JPN, JEY, JOR, KAZ, KEN, KIR, PRK, KOR, KWT,
KGZ, LAO, LVA, LBN, LSO, LBR, LBY, LIE, LTU, LUX, MAC, MKD, MDG, MWI, MYS,
MDV, MLI, MLT, MHL, MTQ, MRT, MUS, MYT, MEX, FSM, MDA, MCO, MNG, MNE, MSR,
MAR, MOZ, MMR, NAM, NRU, NPL, NLD, NCL, NZL, NIC, NER, NGA, NIU, NFK, MNP,
NOR, OMN, PAK, PLW, PSE, PAN, PNG, PRY, PER, PHL, PCN, POL, PRT, PRI, QAT,
REU, ROU, RUS, RWA, BLM, SHN, KNA, LCA, MAF, SPM, VCT, WSM, SMR, STP, SAU,
SEN, SRB, SYC, SLE, SGP, SXM, SVK, SVN, SLB, SOM, ZAF, SGS, SSD, ESP, LKA,
SDN, SUR, SJM, SWZ, SWE, CHE, SYR, TWN, TJK, TZA, THA, TLS, TGO, TKL, TON,
TTO, TUN, TUR, TKM, TCA, TUV, UGA, UKR, ARE, GBR, USA, UMI, URY, UZB, VUT,
VEN, VNM, VGB, VIR, WLF, ESH, YEM, ZMB, ZWE
}
#[derive(
Clone,
Copy,
Debug,
PartialEq,
Eq,
Hash,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
Deserialize,
Serialize,
utoipa::ToSchema,
)]
pub enum Country {
Afghanistan,
AlandIslands,
Albania,
Algeria,
AmericanSamoa,
Andorra,
Angola,
Anguilla,
Antarctica,
AntiguaAndBarbuda,
Argentina,
Armenia,
Aruba,
Australia,
Austria,
Azerbaijan,
Bahamas,
Bahrain,
Bangladesh,
Barbados,
Belarus,
Belgium,
Belize,
Benin,
Bermuda,
Bhutan,
BoliviaPlurinationalState,
BonaireSintEustatiusAndSaba,
BosniaAndHerzegovina,
Botswana,
BouvetIsland,
Brazil,
BritishIndianOceanTerritory,
BruneiDarussalam,
Bulgaria,
BurkinaFaso,
Burundi,
CaboVerde,
Cambodia,
Cameroon,
Canada,
CaymanIslands,
CentralAfricanRepublic,
Chad,
Chile,
China,
ChristmasIsland,
CocosKeelingIslands,
Colombia,
Comoros,
Congo,
CongoDemocraticRepublic,
CookIslands,
CostaRica,
CotedIvoire,
Croatia,
Cuba,
Curacao,
Cyprus,
Czechia,
Denmark,
Djibouti,
Dominica,
DominicanRepublic,
Ecuador,
Egypt,
ElSalvador,
EquatorialGuinea,
Eritrea,
Estonia,
Ethiopia,
FalklandIslandsMalvinas,
FaroeIslands,
Fiji,
Finland,
France,
FrenchGuiana,
FrenchPolynesia,
FrenchSouthernTerritories,
Gabon,
Gambia,
Georgia,
Germany,
Ghana,
Gibraltar,
Greece,
Greenland,
Grenada,
Guadeloupe,
Guam,
Guatemala,
Guernsey,
Guinea,
GuineaBissau,
Guyana,
Haiti,
HeardIslandAndMcDonaldIslands,
HolySee,
Honduras,
HongKong,
Hungary,
Iceland,
India,
Indonesia,
IranIslamicRepublic,
Iraq,
Ireland,
IsleOfMan,
Israel,
Italy,
Jamaica,
Japan,
Jersey,
Jordan,
Kazakhstan,
Kenya,
Kiribati,
KoreaDemocraticPeoplesRepublic,
KoreaRepublic,
Kuwait,
Kyrgyzstan,
LaoPeoplesDemocraticRepublic,
Latvia,
Lebanon,
Lesotho,
Liberia,
Libya,
Liechtenstein,
Lithuania,
Luxembourg,
Macao,
MacedoniaTheFormerYugoslavRepublic,
Madagascar,
Malawi,
Malaysia,
Maldives,
Mali,
Malta,
MarshallIslands,
Martinique,
Mauritania,
Mauritius,
Mayotte,
Mexico,
MicronesiaFederatedStates,
MoldovaRepublic,
Monaco,
Mongolia,
Montenegro,
Montserrat,
Morocco,
Mozambique,
Myanmar,
Namibia,
Nauru,
Nepal,
Netherlands,
NewCaledonia,
NewZealand,
Nicaragua,
Niger,
Nigeria,
Niue,
NorfolkIsland,
NorthernMarianaIslands,
Norway,
Oman,
Pakistan,
Palau,
PalestineState,
Panama,
PapuaNewGuinea,
Paraguay,
Peru,
Philippines,
Pitcairn,
Poland,
Portugal,
PuertoRico,
Qatar,
Reunion,
Romania,
RussianFederation,
Rwanda,
SaintBarthelemy,
SaintHelenaAscensionAndTristandaCunha,
SaintKittsAndNevis,
SaintLucia,
SaintMartinFrenchpart,
SaintPierreAndMiquelon,
SaintVincentAndTheGrenadines,
Samoa,
SanMarino,
SaoTomeAndPrincipe,
SaudiArabia,
Senegal,
Serbia,
Seychelles,
SierraLeone,
Singapore,
SintMaartenDutchpart,
Slovakia,
Slovenia,
SolomonIslands,
Somalia,
SouthAfrica,
SouthGeorgiaAndTheSouthSandwichIslands,
SouthSudan,
Spain,
SriLanka,
Sudan,
Suriname,
SvalbardAndJanMayen,
Swaziland,
Sweden,
Switzerland,
SyrianArabRepublic,
TaiwanProvinceOfChina,
Tajikistan,
TanzaniaUnitedRepublic,
Thailand,
TimorLeste,
Togo,
Tokelau,
Tonga,
TrinidadAndTobago,
Tunisia,
Turkey,
Turkmenistan,
TurksAndCaicosIslands,
Tuvalu,
Uganda,
Ukraine,
UnitedArabEmirates,
UnitedKingdomOfGreatBritainAndNorthernIreland,
UnitedStatesOfAmerica,
UnitedStatesMinorOutlyingIslands,
Uruguay,
Uzbekistan,
Vanuatu,
VenezuelaBolivarianRepublic,
Vietnam,
VirginIslandsBritish,
VirginIslandsUS,
WallisAndFutuna,
WesternSahara,
Yemen,
Zambia,
Zimbabwe,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
Default,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum FileUploadProvider {
#[default]
Router,
Stripe,
Checkout,
Worldpayvantiv,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum UsStatesAbbreviation {
AL,
AK,
AS,
AZ,
AR,
CA,
CO,
CT,
DE,
DC,
FM,
FL,
GA,
GU,
HI,
ID,
IL,
IN,
IA,
KS,
KY,
LA,
ME,
MH,
MD,
MA,
MI,
MN,
MS,
MO,
MT,
NE,
NV,
NH,
NJ,
NM,
NY,
NC,
ND,
MP,
OH,
OK,
OR,
PW,
PA,
PR,
RI,
SC,
SD,
TN,
TX,
UT,
VT,
VI,
VA,
WA,
WV,
WI,
WY,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum AustraliaStatesAbbreviation {
ACT,
NT,
NSW,
QLD,
SA,
TAS,
VIC,
WA,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum JapanStatesAbbreviation {
#[strum(serialize = "23")]
Aichi,
#[strum(serialize = "05")]
Akita,
#[strum(serialize = "02")]
Aomori,
#[strum(serialize = "38")]
Ehime,
#[strum(serialize = "21")]
Gifu,
#[strum(serialize = "10")]
Gunma,
#[strum(serialize = "34")]
Hiroshima,
#[strum(serialize = "01")]
Hokkaido,
#[strum(serialize = "18")]
Fukui,
#[strum(serialize = "40")]
Fukuoka,
#[strum(serialize = "07")]
Fukushima,
#[strum(serialize = "28")]
Hyogo,
#[strum(serialize = "08")]
Ibaraki,
#[strum(serialize = "17")]
Ishikawa,
#[strum(serialize = "03")]
Iwate,
#[strum(serialize = "37")]
Kagawa,
#[strum(serialize = "46")]
Kagoshima,
#[strum(serialize = "14")]
Kanagawa,
#[strum(serialize = "39")]
Kochi,
#[strum(serialize = "43")]
Kumamoto,
#[strum(serialize = "26")]
Kyoto,
#[strum(serialize = "24")]
Mie,
#[strum(serialize = "04")]
Miyagi,
#[strum(serialize = "45")]
Miyazaki,
#[strum(serialize = "20")]
Nagano,
#[strum(serialize = "42")]
Nagasaki,
#[strum(serialize = "29")]
Nara,
#[strum(serialize = "15")]
Niigata,
#[strum(serialize = "44")]
Oita,
#[strum(serialize = "33")]
Okayama,
#[strum(serialize = "47")]
Okinawa,
#[strum(serialize = "27")]
Osaka,
#[strum(serialize = "41")]
Saga,
#[strum(serialize = "11")]
Saitama,
#[strum(serialize = "25")]
Shiga,
#[strum(serialize = "32")]
Shimane,
#[strum(serialize = "22")]
Shizuoka,
#[strum(serialize = "12")]
Chiba,
#[strum(serialize = "36")]
Tokusima,
#[strum(serialize = "13")]
Tokyo,
#[strum(serialize = "09")]
Tochigi,
#[strum(serialize = "31")]
Tottori,
#[strum(serialize = "16")]
Toyama,
#[strum(serialize = "30")]
Wakayama,
#[strum(serialize = "06")]
Yamagata,
#[strum(serialize = "35")]
Yamaguchi,
#[strum(serialize = "19")]
Yamanashi,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum NewZealandStatesAbbreviation {
#[strum(serialize = "AUK")]
Auckland,
#[strum(serialize = "BOP")]
BayOfPlenty,
#[strum(serialize = "CAN")]
Canterbury,
#[strum(serialize = "GIS")]
Gisborne,
#[strum(serialize = "HKB")]
HawkesBay,
#[strum(serialize = "MWT")]
ManawatūWhanganui,
#[strum(serialize = "MBH")]
Marlborough,
#[strum(serialize = "NSN")]
Nelson,
#[strum(serialize = "NTL")]
Northland,
#[strum(serialize = "OTA")]
Otago,
#[strum(serialize = "STL")]
Southland,
#[strum(serialize = "TKI")]
Taranaki,
#[strum(serialize = "TAS")]
Tasman,
#[strum(serialize = "WKO")]
Waikato,
#[strum(serialize = "CIT")]
ChathamIslandsTerritory,
#[strum(serialize = "WGN")]
GreaterWellington,
#[strum(serialize = "WTC")]
WestCoast,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum SingaporeStatesAbbreviation {
#[strum(serialize = "01")]
CentralSingapore,
#[strum(serialize = "02")]
NorthEast,
#[strum(serialize = "03")]
NorthWest,
#[strum(serialize = "04")]
SouthEast,
#[strum(serialize = "05")]
SouthWest,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum ThailandStatesAbbreviation {
#[strum(serialize = "37")]
AmnatCharoen,
#[strum(serialize = "15")]
AngThong,
#[strum(serialize = "10")]
Bangkok,
#[strum(serialize = "38")]
BuengKan,
#[strum(serialize = "31")]
BuriRam,
#[strum(serialize = "24")]
Chachoengsao,
#[strum(serialize = "18")]
ChaiNat,
#[strum(serialize = "36")]
Chaiyaphum,
#[strum(serialize = "22")]
Chanthaburi,
#[strum(serialize = "57")]
ChiangRai,
#[strum(serialize = "50")]
ChiangMai,
#[strum(serialize = "20")]
ChonBuri,
#[strum(serialize = "86")]
Chumphon,
#[strum(serialize = "46")]
Kalasin,
#[strum(serialize = "62")]
KamphaengPhet,
#[strum(serialize = "71")]
Kanchanaburi,
#[strum(serialize = "40")]
KhonKaen,
#[strum(serialize = "81")]
Krabi,
#[strum(serialize = "52")]
Lampang,
#[strum(serialize = "51")]
Lamphun,
#[strum(serialize = "42")]
Loei,
#[strum(serialize = "16")]
LopBuri,
#[strum(serialize = "58")]
MaeHongSon,
#[strum(serialize = "44")]
MahaSarakham,
#[strum(serialize = "49")]
Mukdahan,
#[strum(serialize = "26")]
NakhonNayok,
#[strum(serialize = "73")]
NakhonPathom,
#[strum(serialize = "48")]
NakhonPhanom,
#[strum(serialize = "30")]
NakhonRatchasima,
#[strum(serialize = "60")]
NakhonSawan,
#[strum(serialize = "80")]
NakhonSiThammarat,
#[strum(serialize = "55")]
Nan,
#[strum(serialize = "96")]
Narathiwat,
#[strum(serialize = "39")]
NongBuaLamPhu,
#[strum(serialize = "43")]
NongKhai,
#[strum(serialize = "12")]
Nonthaburi,
#[strum(serialize = "13")]
PathumThani,
#[strum(serialize = "94")]
Pattani,
#[strum(serialize = "82")]
Phangnga,
#[strum(serialize = "93")]
Phatthalung,
#[strum(serialize = "56")]
Phayao,
#[strum(serialize = "S")]
Phatthaya,
#[strum(serialize = "67")]
Phetchabun,
#[strum(serialize = "76")]
Phetchaburi,
#[strum(serialize = "66")]
Phichit,
#[strum(serialize = "65")]
Phitsanulok,
#[strum(serialize = "54")]
Phrae,
#[strum(serialize = "14")]
PhraNakhonSiAyutthaya,
#[strum(serialize = "83")]
Phuket,
#[strum(serialize = "25")]
PrachinBuri,
#[strum(serialize = "77")]
PrachuapKhiriKhan,
#[strum(serialize = "85")]
Ranong,
#[strum(serialize = "70")]
Ratchaburi,
#[strum(serialize = "21")]
Rayong,
#[strum(serialize = "45")]
RoiEt,
#[strum(serialize = "27")]
SaKaeo,
#[strum(serialize = "47")]
SakonNakhon,
#[strum(serialize = "11")]
SamutPrakan,
#[strum(serialize = "74")]
SamutSakhon,
#[strum(serialize = "75")]
SamutSongkhram,
#[strum(serialize = "19")]
Saraburi,
#[strum(serialize = "91")]
Satun,
#[strum(serialize = "33")]
SiSaKet,
#[strum(serialize = "17")]
SingBuri,
#[strum(serialize = "90")]
Songkhla,
#[strum(serialize = "64")]
Sukhothai,
#[strum(serialize = "72")]
SuphanBuri,
#[strum(serialize = "84")]
SuratThani,
#[strum(serialize = "32")]
Surin,
#[strum(serialize = "63")]
Tak,
#[strum(serialize = "92")]
Trang,
#[strum(serialize = "23")]
Trat,
#[strum(serialize = "34")]
UbonRatchathani,
#[strum(serialize = "41")]
UdonThani,
#[strum(serialize = "61")]
UthaiThani,
#[strum(serialize = "53")]
Uttaradit,
#[strum(serialize = "95")]
Yala,
#[strum(serialize = "35")]
Yasothon,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum PhilippinesStatesAbbreviation {
#[strum(serialize = "ABR")]
Abra,
#[strum(serialize = "AGN")]
AgusanDelNorte,
#[strum(serialize = "AGS")]
AgusanDelSur,
#[strum(serialize = "AKL")]
Aklan,
#[strum(serialize = "ALB")]
Albay,
#[strum(serialize = "ANT")]
Antique,
#[strum(serialize = "APA")]
Apayao,
#[strum(serialize = "AUR")]
Aurora,
#[strum(serialize = "14")]
AutonomousRegionInMuslimMindanao,
#[strum(serialize = "BAS")]
Basilan,
#[strum(serialize = "BAN")]
Bataan,
#[strum(serialize = "BTN")]
Batanes,
#[strum(serialize = "BTG")]
Batangas,
#[strum(serialize = "BEN")]
Benguet,
#[strum(serialize = "05")]
Bicol,
#[strum(serialize = "BIL")]
Biliran,
#[strum(serialize = "BOH")]
Bohol,
#[strum(serialize = "BUK")]
Bukidnon,
#[strum(serialize = "BUL")]
Bulacan,
#[strum(serialize = "CAG")]
Cagayan,
#[strum(serialize = "02")]
CagayanValley,
#[strum(serialize = "40")]
Calabarzon,
#[strum(serialize = "CAN")]
CamarinesNorte,
#[strum(serialize = "CAS")]
CamarinesSur,
#[strum(serialize = "CAM")]
Camiguin,
#[strum(serialize = "CAP")]
Capiz,
#[strum(serialize = "13")]
Caraga,
#[strum(serialize = "CAT")]
Catanduanes,
#[strum(serialize = "CAV")]
Cavite,
#[strum(serialize = "CEB")]
Cebu,
#[strum(serialize = "03")]
CentralLuzon,
#[strum(serialize = "07")]
CentralVisayas,
#[strum(serialize = "15")]
CordilleraAdministrativeRegion,
#[strum(serialize = "NCO")]
Cotabato,
#[strum(serialize = "11")]
Davao,
#[strum(serialize = "DVO")]
DavaoOccidental,
#[strum(serialize = "DAO")]
DavaoOriental,
#[strum(serialize = "COM")]
DavaoDeOro,
#[strum(serialize = "DAV")]
DavaoDelNorte,
#[strum(serialize = "DAS")]
DavaoDelSur,
#[strum(serialize = "DIN")]
DinagatIslands,
#[strum(serialize = "EAS")]
EasternSamar,
#[strum(serialize = "08")]
EasternVisayas,
#[strum(serialize = "GUI")]
Guimaras,
#[strum(serialize = "ILN")]
HilagangIloko,
#[strum(serialize = "LAN")]
HilagangLanaw,
#[strum(serialize = "MGN")]
HilagangMagindanaw,
#[strum(serialize = "NSA")]
HilagangSamar,
#[strum(serialize = "ZAN")]
HilagangSambuwangga,
#[strum(serialize = "SUN")]
HilagangSurigaw,
#[strum(serialize = "IFU")]
Ifugao,
#[strum(serialize = "01")]
Ilocos,
#[strum(serialize = "ILS")]
IlocosSur,
#[strum(serialize = "ILI")]
Iloilo,
#[strum(serialize = "ISA")]
Isabela,
#[strum(serialize = "KAL")]
Kalinga,
#[strum(serialize = "MDC")]
KanlurangMindoro,
#[strum(serialize = "MSC")]
KanlurangMisamis,
#[strum(serialize = "NEC")]
KanlurangNegros,
#[strum(serialize = "SLE")]
KatimogangLeyte,
#[strum(serialize = "QUE")]
Keson,
#[strum(serialize = "QUI")]
Kirino,
#[strum(serialize = "LUN")]
LaUnion,
#[strum(serialize = "LAG")]
Laguna,
#[strum(serialize = "MOU")]
LalawigangBulubundukin,
#[strum(serialize = "LAS")]
LanaoDelSur,
#[strum(serialize = "LEY")]
Leyte,
#[strum(serialize = "MGS")]
MaguindanaoDelSur,
#[strum(serialize = "MAD")]
Marinduque,
#[strum(serialize = "MAS")]
Masbate,
#[strum(serialize = "41")]
Mimaropa,
#[strum(serialize = "MDR")]
MindoroOriental,
#[strum(serialize = "MSR")]
MisamisOccidental,
#[strum(serialize = "00")]
NationalCapitalRegion,
#[strum(serialize = "NER")]
NegrosOriental,
#[strum(serialize = "10")]
NorthernMindanao,
#[strum(serialize = "NUE")]
NuevaEcija,
#[strum(serialize = "NUV")]
NuevaVizcaya,
#[strum(serialize = "PLW")]
Palawan,
#[strum(serialize = "PAM")]
Pampanga,
#[strum(serialize = "PAN")]
Pangasinan,
#[strum(serialize = "06")]
RehiyonNgKanlurangBisaya,
#[strum(serialize = "12")]
RehiyonNgSoccsksargen,
#[strum(serialize = "09")]
RehiyonNgTangwayNgSambuwangga,
#[strum(serialize = "RIZ")]
Risal,
#[strum(serialize = "ROM")]
Romblon,
#[strum(serialize = "WSA")]
Samar,
#[strum(serialize = "ZMB")]
Sambales,
#[strum(serialize = "ZSI")]
SambuwanggaSibugay,
#[strum(serialize = "SAR")]
Sarangani,
#[strum(serialize = "SIG")]
Sikihor,
#[strum(serialize = "SOR")]
Sorsogon,
#[strum(serialize = "SCO")]
SouthCotabato,
#[strum(serialize = "SUK")]
SultanKudarat,
#[strum(serialize = "SLU")]
Sulu,
#[strum(serialize = "SUR")]
SurigaoDelSur,
#[strum(serialize = "TAR")]
Tarlac,
#[strum(serialize = "TAW")]
TawiTawi,
#[strum(serialize = "ZAS")]
TimogSambuwangga,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum IndiaStatesAbbreviation {
#[strum(serialize = "AN")]
AndamanAndNicobarIslands,
#[strum(serialize = "AP")]
AndhraPradesh,
#[strum(serialize = "AR")]
ArunachalPradesh,
#[strum(serialize = "AS")]
Assam,
#[strum(serialize = "BR")]
Bihar,
#[strum(serialize = "CH")]
Chandigarh,
#[strum(serialize = "CG")]
Chhattisgarh,
#[strum(serialize = "DL")]
Delhi,
#[strum(serialize = "DH")]
DadraAndNagarHaveliAndDamanAndDiu,
#[strum(serialize = "GA")]
Goa,
#[strum(serialize = "GJ")]
Gujarat,
#[strum(serialize = "HR")]
Haryana,
#[strum(serialize = "HP")]
HimachalPradesh,
#[strum(serialize = "JK")]
JammuAndKashmir,
#[strum(serialize = "JH")]
Jharkhand,
#[strum(serialize = "KA")]
Karnataka,
#[strum(serialize = "KL")]
Kerala,
#[strum(serialize = "LA")]
Ladakh,
#[strum(serialize = "LD")]
Lakshadweep,
#[strum(serialize = "MP")]
MadhyaPradesh,
#[strum(serialize = "MH")]
Maharashtra,
#[strum(serialize = "MN")]
Manipur,
#[strum(serialize = "ML")]
Meghalaya,
#[strum(serialize = "MZ")]
Mizoram,
#[strum(serialize = "NL")]
Nagaland,
#[strum(serialize = "OD")]
Odisha,
#[strum(serialize = "PY")]
Puducherry,
#[strum(serialize = "PB")]
Punjab,
#[strum(serialize = "RJ")]
Rajasthan,
#[strum(serialize = "SK")]
Sikkim,
#[strum(serialize = "TN")]
TamilNadu,
#[strum(serialize = "TG")]
Telangana,
#[strum(serialize = "TR")]
Tripura,
#[strum(serialize = "UP")]
UttarPradesh,
#[strum(serialize = "UK")]
Uttarakhand,
#[strum(serialize = "WB")]
WestBengal,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum CanadaStatesAbbreviation {
AB,
BC,
MB,
NB,
NL,
NT,
NS,
NU,
ON,
PE,
QC,
SK,
YT,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum AlbaniaStatesAbbreviation {
#[strum(serialize = "01")]
Berat,
#[strum(serialize = "09")]
Diber,
#[strum(serialize = "02")]
Durres,
#[strum(serialize = "03")]
Elbasan,
#[strum(serialize = "04")]
Fier,
#[strum(serialize = "05")]
Gjirokaster,
#[strum(serialize = "06")]
Korce,
#[strum(serialize = "07")]
Kukes,
#[strum(serialize = "08")]
Lezhe,
#[strum(serialize = "10")]
Shkoder,
#[strum(serialize = "11")]
Tirane,
#[strum(serialize = "12")]
Vlore,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum AndorraStatesAbbreviation {
#[strum(serialize = "07")]
AndorraLaVella,
#[strum(serialize = "02")]
Canillo,
#[strum(serialize = "03")]
Encamp,
#[strum(serialize = "08")]
EscaldesEngordany,
#[strum(serialize = "04")]
LaMassana,
#[strum(serialize = "05")]
Ordino,
#[strum(serialize = "06")]
SantJuliaDeLoria,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum AustriaStatesAbbreviation {
#[strum(serialize = "1")]
Burgenland,
#[strum(serialize = "2")]
Carinthia,
#[strum(serialize = "3")]
LowerAustria,
#[strum(serialize = "5")]
Salzburg,
#[strum(serialize = "6")]
Styria,
#[strum(serialize = "7")]
Tyrol,
#[strum(serialize = "4")]
UpperAustria,
#[strum(serialize = "9")]
Vienna,
#[strum(serialize = "8")]
Vorarlberg,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum BelarusStatesAbbreviation {
#[strum(serialize = "BR")]
BrestRegion,
#[strum(serialize = "HO")]
GomelRegion,
#[strum(serialize = "HR")]
GrodnoRegion,
#[strum(serialize = "HM")]
Minsk,
#[strum(serialize = "MI")]
MinskRegion,
#[strum(serialize = "MA")]
MogilevRegion,
#[strum(serialize = "VI")]
VitebskRegion,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum BosniaAndHerzegovinaStatesAbbreviation {
#[strum(serialize = "05")]
BosnianPodrinjeCanton,
#[strum(serialize = "BRC")]
BrckoDistrict,
#[strum(serialize = "10")]
Canton10,
#[strum(serialize = "06")]
CentralBosniaCanton,
#[strum(serialize = "BIH")]
FederationOfBosniaAndHerzegovina,
#[strum(serialize = "07")]
HerzegovinaNeretvaCanton,
#[strum(serialize = "02")]
PosavinaCanton,
#[strum(serialize = "SRP")]
RepublikaSrpska,
#[strum(serialize = "09")]
SarajevoCanton,
#[strum(serialize = "03")]
TuzlaCanton,
#[strum(serialize = "01")]
UnaSanaCanton,
#[strum(serialize = "08")]
WestHerzegovinaCanton,
#[strum(serialize = "04")]
ZenicaDobojCanton,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum BulgariaStatesAbbreviation {
#[strum(serialize = "01")]
BlagoevgradProvince,
#[strum(serialize = "02")]
BurgasProvince,
#[strum(serialize = "08")]
DobrichProvince,
#[strum(serialize = "07")]
GabrovoProvince,
#[strum(serialize = "26")]
HaskovoProvince,
#[strum(serialize = "09")]
KardzhaliProvince,
#[strum(serialize = "10")]
KyustendilProvince,
#[strum(serialize = "11")]
LovechProvince,
#[strum(serialize = "12")]
MontanaProvince,
#[strum(serialize = "13")]
PazardzhikProvince,
#[strum(serialize = "14")]
PernikProvince,
#[strum(serialize = "15")]
PlevenProvince,
#[strum(serialize = "16")]
PlovdivProvince,
#[strum(serialize = "17")]
RazgradProvince,
#[strum(serialize = "18")]
RuseProvince,
#[strum(serialize = "27")]
Shumen,
#[strum(serialize = "19")]
SilistraProvince,
#[strum(serialize = "20")]
SlivenProvince,
#[strum(serialize = "21")]
SmolyanProvince,
#[strum(serialize = "22")]
SofiaCityProvince,
#[strum(serialize = "23")]
SofiaProvince,
#[strum(serialize = "24")]
StaraZagoraProvince,
#[strum(serialize = "25")]
TargovishteProvince,
#[strum(serialize = "03")]
VarnaProvince,
#[strum(serialize = "04")]
VelikoTarnovoProvince,
#[strum(serialize = "05")]
VidinProvince,
#[strum(serialize = "06")]
VratsaProvince,
#[strum(serialize = "28")]
YambolProvince,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum CroatiaStatesAbbreviation {
#[strum(serialize = "07")]
BjelovarBilogoraCounty,
#[strum(serialize = "12")]
BrodPosavinaCounty,
#[strum(serialize = "19")]
DubrovnikNeretvaCounty,
#[strum(serialize = "18")]
IstriaCounty,
#[strum(serialize = "06")]
KoprivnicaKrizevciCounty,
#[strum(serialize = "02")]
KrapinaZagorjeCounty,
#[strum(serialize = "09")]
LikaSenjCounty,
#[strum(serialize = "20")]
MedimurjeCounty,
#[strum(serialize = "14")]
OsijekBaranjaCounty,
#[strum(serialize = "11")]
PozegaSlavoniaCounty,
#[strum(serialize = "08")]
PrimorjeGorskiKotarCounty,
#[strum(serialize = "03")]
SisakMoslavinaCounty,
#[strum(serialize = "17")]
SplitDalmatiaCounty,
#[strum(serialize = "05")]
VarazdinCounty,
#[strum(serialize = "10")]
ViroviticaPodravinaCounty,
#[strum(serialize = "16")]
VukovarSyrmiaCounty,
#[strum(serialize = "13")]
ZadarCounty,
#[strum(serialize = "21")]
Zagreb,
#[strum(serialize = "01")]
ZagrebCounty,
#[strum(serialize = "15")]
SibenikKninCounty,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum CzechRepublicStatesAbbreviation {
#[strum(serialize = "201")]
BenesovDistrict,
#[strum(serialize = "202")]
BerounDistrict,
#[strum(serialize = "641")]
BlanskoDistrict,
#[strum(serialize = "642")]
BrnoCityDistrict,
#[strum(serialize = "643")]
BrnoCountryDistrict,
#[strum(serialize = "801")]
BruntalDistrict,
#[strum(serialize = "644")]
BreclavDistrict,
#[strum(serialize = "20")]
CentralBohemianRegion,
#[strum(serialize = "411")]
ChebDistrict,
#[strum(serialize = "422")]
ChomutovDistrict,
#[strum(serialize = "531")]
ChrudimDistrict,
#[strum(serialize = "321")]
DomazliceDistrict,
#[strum(serialize = "421")]
DecinDistrict,
#[strum(serialize = "802")]
FrydekMistekDistrict,
#[strum(serialize = "631")]
HavlickuvBrodDistrict,
#[strum(serialize = "645")]
HodoninDistrict,
#[strum(serialize = "120")]
HorniPocernice,
#[strum(serialize = "521")]
HradecKraloveDistrict,
#[strum(serialize = "52")]
HradecKraloveRegion,
#[strum(serialize = "512")]
JablonecNadNisouDistrict,
#[strum(serialize = "711")]
JesenikDistrict,
#[strum(serialize = "632")]
JihlavaDistrict,
#[strum(serialize = "313")]
JindrichuvHradecDistrict,
#[strum(serialize = "522")]
JicinDistrict,
#[strum(serialize = "412")]
KarlovyVaryDistrict,
#[strum(serialize = "41")]
KarlovyVaryRegion,
#[strum(serialize = "803")]
KarvinaDistrict,
#[strum(serialize = "203")]
KladnoDistrict,
#[strum(serialize = "322")]
KlatovyDistrict,
#[strum(serialize = "204")]
KolinDistrict,
#[strum(serialize = "721")]
KromerizDistrict,
#[strum(serialize = "513")]
LiberecDistrict,
#[strum(serialize = "51")]
LiberecRegion,
#[strum(serialize = "423")]
LitomericeDistrict,
#[strum(serialize = "424")]
LounyDistrict,
#[strum(serialize = "207")]
MladaBoleslavDistrict,
#[strum(serialize = "80")]
MoravianSilesianRegion,
#[strum(serialize = "425")]
MostDistrict,
#[strum(serialize = "206")]
MelnikDistrict,
#[strum(serialize = "804")]
NovyJicinDistrict,
#[strum(serialize = "208")]
NymburkDistrict,
#[strum(serialize = "523")]
NachodDistrict,
#[strum(serialize = "712")]
OlomoucDistrict,
#[strum(serialize = "71")]
OlomoucRegion,
#[strum(serialize = "805")]
OpavaDistrict,
#[strum(serialize = "806")]
OstravaCityDistrict,
#[strum(serialize = "532")]
PardubiceDistrict,
#[strum(serialize = "53")]
PardubiceRegion,
#[strum(serialize = "633")]
PelhrimovDistrict,
#[strum(serialize = "32")]
PlzenRegion,
#[strum(serialize = "323")]
PlzenCityDistrict,
#[strum(serialize = "325")]
PlzenNorthDistrict,
#[strum(serialize = "324")]
PlzenSouthDistrict,
#[strum(serialize = "315")]
PrachaticeDistrict,
#[strum(serialize = "10")]
Prague,
#[strum(serialize = "101")]
Prague1,
#[strum(serialize = "110")]
Prague10,
#[strum(serialize = "111")]
Prague11,
#[strum(serialize = "112")]
Prague12,
#[strum(serialize = "113")]
Prague13,
#[strum(serialize = "114")]
Prague14,
#[strum(serialize = "115")]
Prague15,
#[strum(serialize = "116")]
Prague16,
#[strum(serialize = "102")]
Prague2,
#[strum(serialize = "121")]
Prague21,
#[strum(serialize = "103")]
Prague3,
#[strum(serialize = "104")]
Prague4,
#[strum(serialize = "105")]
Prague5,
#[strum(serialize = "106")]
Prague6,
#[strum(serialize = "107")]
Prague7,
#[strum(serialize = "108")]
Prague8,
#[strum(serialize = "109")]
Prague9,
#[strum(serialize = "209")]
PragueEastDistrict,
#[strum(serialize = "20A")]
PragueWestDistrict,
#[strum(serialize = "713")]
ProstejovDistrict,
#[strum(serialize = "314")]
PisekDistrict,
#[strum(serialize = "714")]
PrerovDistrict,
#[strum(serialize = "20B")]
PribramDistrict,
#[strum(serialize = "20C")]
RakovnikDistrict,
#[strum(serialize = "326")]
RokycanyDistrict,
#[strum(serialize = "524")]
RychnovNadKneznouDistrict,
#[strum(serialize = "514")]
SemilyDistrict,
#[strum(serialize = "413")]
SokolovDistrict,
#[strum(serialize = "31")]
SouthBohemianRegion,
#[strum(serialize = "64")]
SouthMoravianRegion,
#[strum(serialize = "316")]
StrakoniceDistrict,
#[strum(serialize = "533")]
SvitavyDistrict,
#[strum(serialize = "327")]
TachovDistrict,
#[strum(serialize = "426")]
TepliceDistrict,
#[strum(serialize = "525")]
TrutnovDistrict,
#[strum(serialize = "317")]
TaborDistrict,
#[strum(serialize = "634")]
TrebicDistrict,
#[strum(serialize = "722")]
UherskeHradisteDistrict,
#[strum(serialize = "723")]
VsetinDistrict,
#[strum(serialize = "63")]
VysocinaRegion,
#[strum(serialize = "646")]
VyskovDistrict,
#[strum(serialize = "724")]
ZlinDistrict,
#[strum(serialize = "72")]
ZlinRegion,
#[strum(serialize = "647")]
ZnojmoDistrict,
#[strum(serialize = "427")]
UstiNadLabemDistrict,
#[strum(serialize = "42")]
UstiNadLabemRegion,
#[strum(serialize = "534")]
UstiNadOrliciDistrict,
#[strum(serialize = "511")]
CeskaLipaDistrict,
#[strum(serialize = "311")]
CeskeBudejoviceDistrict,
#[strum(serialize = "312")]
CeskyKrumlovDistrict,
#[strum(serialize = "715")]
SumperkDistrict,
#[strum(serialize = "635")]
ZdarNadSazavouDistrict,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum DenmarkStatesAbbreviation {
#[strum(serialize = "84")]
CapitalRegionOfDenmark,
#[strum(serialize = "82")]
CentralDenmarkRegion,
#[strum(serialize = "81")]
NorthDenmarkRegion,
#[strum(serialize = "85")]
RegionZealand,
#[strum(serialize = "83")]
RegionOfSouthernDenmark,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum FinlandStatesAbbreviation {
#[strum(serialize = "08")]
CentralFinland,
#[strum(serialize = "07")]
CentralOstrobothnia,
#[strum(serialize = "IS")]
EasternFinlandProvince,
#[strum(serialize = "19")]
FinlandProper,
#[strum(serialize = "05")]
Kainuu,
#[strum(serialize = "09")]
Kymenlaakso,
#[strum(serialize = "LL")]
Lapland,
#[strum(serialize = "13")]
NorthKarelia,
#[strum(serialize = "14")]
NorthernOstrobothnia,
#[strum(serialize = "15")]
NorthernSavonia,
#[strum(serialize = "12")]
Ostrobothnia,
#[strum(serialize = "OL")]
OuluProvince,
#[strum(serialize = "11")]
Pirkanmaa,
#[strum(serialize = "16")]
PaijanneTavastia,
#[strum(serialize = "17")]
Satakunta,
#[strum(serialize = "02")]
SouthKarelia,
#[strum(serialize = "03")]
SouthernOstrobothnia,
#[strum(serialize = "04")]
SouthernSavonia,
#[strum(serialize = "06")]
TavastiaProper,
#[strum(serialize = "18")]
Uusimaa,
#[strum(serialize = "01")]
AlandIslands,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum FranceStatesAbbreviation {
#[strum(serialize = "01")]
Ain,
#[strum(serialize = "02")]
Aisne,
#[strum(serialize = "03")]
Allier,
#[strum(serialize = "04")]
AlpesDeHauteProvence,
#[strum(serialize = "06")]
AlpesMaritimes,
#[strum(serialize = "6AE")]
Alsace,
#[strum(serialize = "07")]
Ardeche,
#[strum(serialize = "08")]
Ardennes,
#[strum(serialize = "09")]
Ariege,
#[strum(serialize = "10")]
Aube,
#[strum(serialize = "11")]
Aude,
#[strum(serialize = "ARA")]
AuvergneRhoneAlpes,
#[strum(serialize = "12")]
Aveyron,
#[strum(serialize = "67")]
BasRhin,
#[strum(serialize = "13")]
BouchesDuRhone,
#[strum(serialize = "BFC")]
BourgogneFrancheComte,
#[strum(serialize = "BRE")]
Bretagne,
#[strum(serialize = "14")]
Calvados,
#[strum(serialize = "15")]
Cantal,
#[strum(serialize = "CVL")]
CentreValDeLoire,
#[strum(serialize = "16")]
Charente,
#[strum(serialize = "17")]
CharenteMaritime,
#[strum(serialize = "18")]
Cher,
#[strum(serialize = "CP")]
Clipperton,
#[strum(serialize = "19")]
Correze,
#[strum(serialize = "20R")]
Corse,
#[strum(serialize = "2A")]
CorseDuSud,
#[strum(serialize = "21")]
CoteDor,
#[strum(serialize = "22")]
CotesDarmor,
#[strum(serialize = "23")]
Creuse,
#[strum(serialize = "79")]
DeuxSevres,
#[strum(serialize = "24")]
Dordogne,
#[strum(serialize = "25")]
Doubs,
#[strum(serialize = "26")]
Drome,
#[strum(serialize = "91")]
Essonne,
#[strum(serialize = "27")]
Eure,
#[strum(serialize = "28")]
EureEtLoir,
#[strum(serialize = "29")]
Finistere,
#[strum(serialize = "973")]
FrenchGuiana,
#[strum(serialize = "PF")]
FrenchPolynesia,
#[strum(serialize = "TF")]
FrenchSouthernAndAntarcticLands,
#[strum(serialize = "30")]
Gard,
#[strum(serialize = "32")]
Gers,
#[strum(serialize = "33")]
Gironde,
#[strum(serialize = "GES")]
GrandEst,
#[strum(serialize = "971")]
Guadeloupe,
#[strum(serialize = "68")]
HautRhin,
#[strum(serialize = "2B")]
HauteCorse,
#[strum(serialize = "31")]
HauteGaronne,
#[strum(serialize = "43")]
HauteLoire,
#[strum(serialize = "52")]
HauteMarne,
#[strum(serialize = "70")]
HauteSaone,
#[strum(serialize = "74")]
HauteSavoie,
#[strum(serialize = "87")]
HauteVienne,
#[strum(serialize = "05")]
HautesAlpes,
#[strum(serialize = "65")]
HautesPyrenees,
#[strum(serialize = "HDF")]
HautsDeFrance,
#[strum(serialize = "92")]
HautsDeSeine,
#[strum(serialize = "34")]
Herault,
#[strum(serialize = "IDF")]
IleDeFrance,
#[strum(serialize = "35")]
IlleEtVilaine,
#[strum(serialize = "36")]
Indre,
#[strum(serialize = "37")]
IndreEtLoire,
#[strum(serialize = "38")]
Isere,
#[strum(serialize = "39")]
Jura,
#[strum(serialize = "974")]
LaReunion,
#[strum(serialize = "40")]
Landes,
#[strum(serialize = "41")]
LoirEtCher,
#[strum(serialize = "42")]
Loire,
#[strum(serialize = "44")]
LoireAtlantique,
#[strum(serialize = "45")]
Loiret,
#[strum(serialize = "46")]
Lot,
#[strum(serialize = "47")]
LotEtGaronne,
#[strum(serialize = "48")]
Lozere,
#[strum(serialize = "49")]
MaineEtLoire,
#[strum(serialize = "50")]
Manche,
#[strum(serialize = "51")]
Marne,
#[strum(serialize = "972")]
Martinique,
#[strum(serialize = "53")]
Mayenne,
#[strum(serialize = "976")]
Mayotte,
#[strum(serialize = "69M")]
MetropoleDeLyon,
#[strum(serialize = "54")]
MeurtheEtMoselle,
#[strum(serialize = "55")]
Meuse,
#[strum(serialize = "56")]
Morbihan,
#[strum(serialize = "57")]
Moselle,
#[strum(serialize = "58")]
Nievre,
#[strum(serialize = "59")]
Nord,
#[strum(serialize = "NOR")]
Normandie,
#[strum(serialize = "NAQ")]
NouvelleAquitaine,
#[strum(serialize = "OCC")]
Occitanie,
#[strum(serialize = "60")]
Oise,
#[strum(serialize = "61")]
Orne,
#[strum(serialize = "75C")]
Paris,
#[strum(serialize = "62")]
PasDeCalais,
#[strum(serialize = "PDL")]
PaysDeLaLoire,
#[strum(serialize = "PAC")]
ProvenceAlpesCoteDazur,
#[strum(serialize = "63")]
PuyDeDome,
#[strum(serialize = "64")]
PyreneesAtlantiques,
#[strum(serialize = "66")]
PyreneesOrientales,
#[strum(serialize = "69")]
Rhone,
#[strum(serialize = "PM")]
SaintPierreAndMiquelon,
#[strum(serialize = "BL")]
SaintBarthelemy,
#[strum(serialize = "MF")]
SaintMartin,
#[strum(serialize = "71")]
SaoneEtLoire,
#[strum(serialize = "72")]
Sarthe,
#[strum(serialize = "73")]
Savoie,
#[strum(serialize = "77")]
SeineEtMarne,
#[strum(serialize = "76")]
SeineMaritime,
#[strum(serialize = "93")]
SeineSaintDenis,
#[strum(serialize = "80")]
Somme,
#[strum(serialize = "81")]
Tarn,
#[strum(serialize = "82")]
TarnEtGaronne,
#[strum(serialize = "90")]
TerritoireDeBelfort,
#[strum(serialize = "95")]
ValDoise,
#[strum(serialize = "94")]
ValDeMarne,
#[strum(serialize = "83")]
Var,
#[strum(serialize = "84")]
Vaucluse,
#[strum(serialize = "85")]
Vendee,
#[strum(serialize = "86")]
Vienne,
#[strum(serialize = "88")]
Vosges,
#[strum(serialize = "WF")]
WallisAndFutuna,
#[strum(serialize = "89")]
Yonne,
#[strum(serialize = "78")]
Yvelines,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum GermanyStatesAbbreviation {
BW,
BY,
BE,
BB,
HB,
HH,
HE,
NI,
MV,
NW,
RP,
SL,
SN,
ST,
SH,
TH,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum GreeceStatesAbbreviation {
#[strum(serialize = "13")]
AchaeaRegionalUnit,
#[strum(serialize = "01")]
AetoliaAcarnaniaRegionalUnit,
#[strum(serialize = "12")]
ArcadiaPrefecture,
#[strum(serialize = "11")]
ArgolisRegionalUnit,
#[strum(serialize = "I")]
AtticaRegion,
#[strum(serialize = "03")]
BoeotiaRegionalUnit,
#[strum(serialize = "H")]
CentralGreeceRegion,
#[strum(serialize = "B")]
CentralMacedonia,
#[strum(serialize = "94")]
ChaniaRegionalUnit,
#[strum(serialize = "22")]
CorfuPrefecture,
#[strum(serialize = "15")]
CorinthiaRegionalUnit,
#[strum(serialize = "M")]
CreteRegion,
#[strum(serialize = "52")]
DramaRegionalUnit,
#[strum(serialize = "A2")]
EastAtticaRegionalUnit,
#[strum(serialize = "A")]
EastMacedoniaAndThrace,
#[strum(serialize = "D")]
EpirusRegion,
#[strum(serialize = "04")]
Euboea,
#[strum(serialize = "51")]
GrevenaPrefecture,
#[strum(serialize = "53")]
ImathiaRegionalUnit,
#[strum(serialize = "33")]
IoanninaRegionalUnit,
#[strum(serialize = "F")]
IonianIslandsRegion,
#[strum(serialize = "41")]
KarditsaRegionalUnit,
#[strum(serialize = "56")]
KastoriaRegionalUnit,
#[strum(serialize = "23")]
KefaloniaPrefecture,
#[strum(serialize = "57")]
KilkisRegionalUnit,
#[strum(serialize = "58")]
KozaniPrefecture,
#[strum(serialize = "16")]
Laconia,
#[strum(serialize = "42")]
LarissaPrefecture,
#[strum(serialize = "24")]
LefkadaRegionalUnit,
#[strum(serialize = "59")]
PellaRegionalUnit,
#[strum(serialize = "J")]
PeloponneseRegion,
#[strum(serialize = "06")]
PhthiotisPrefecture,
#[strum(serialize = "34")]
PrevezaPrefecture,
#[strum(serialize = "62")]
SerresPrefecture,
#[strum(serialize = "L")]
SouthAegean,
#[strum(serialize = "54")]
ThessalonikiRegionalUnit,
#[strum(serialize = "G")]
WestGreeceRegion,
#[strum(serialize = "C")]
WestMacedoniaRegion,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum HungaryStatesAbbreviation {
#[strum(serialize = "BA")]
BaranyaCounty,
#[strum(serialize = "BZ")]
BorsodAbaujZemplenCounty,
#[strum(serialize = "BU")]
Budapest,
#[strum(serialize = "BK")]
BacsKiskunCounty,
#[strum(serialize = "BE")]
BekesCounty,
#[strum(serialize = "BC")]
Bekescsaba,
#[strum(serialize = "CS")]
CsongradCounty,
#[strum(serialize = "DE")]
Debrecen,
#[strum(serialize = "DU")]
Dunaujvaros,
#[strum(serialize = "EG")]
Eger,
#[strum(serialize = "FE")]
FejerCounty,
#[strum(serialize = "GY")]
Gyor,
#[strum(serialize = "GS")]
GyorMosonSopronCounty,
#[strum(serialize = "HB")]
HajduBiharCounty,
#[strum(serialize = "HE")]
HevesCounty,
#[strum(serialize = "HV")]
Hodmezovasarhely,
#[strum(serialize = "JN")]
JaszNagykunSzolnokCounty,
#[strum(serialize = "KV")]
Kaposvar,
#[strum(serialize = "KM")]
Kecskemet,
#[strum(serialize = "MI")]
Miskolc,
#[strum(serialize = "NK")]
Nagykanizsa,
#[strum(serialize = "NY")]
Nyiregyhaza,
#[strum(serialize = "NO")]
NogradCounty,
#[strum(serialize = "PE")]
PestCounty,
#[strum(serialize = "PS")]
Pecs,
#[strum(serialize = "ST")]
Salgotarjan,
#[strum(serialize = "SO")]
SomogyCounty,
#[strum(serialize = "SN")]
Sopron,
#[strum(serialize = "SZ")]
SzabolcsSzatmarBeregCounty,
#[strum(serialize = "SD")]
Szeged,
#[strum(serialize = "SS")]
Szekszard,
#[strum(serialize = "SK")]
Szolnok,
#[strum(serialize = "SH")]
Szombathely,
#[strum(serialize = "SF")]
Szekesfehervar,
#[strum(serialize = "TB")]
Tatabanya,
#[strum(serialize = "TO")]
TolnaCounty,
#[strum(serialize = "VA")]
VasCounty,
#[strum(serialize = "VM")]
Veszprem,
#[strum(serialize = "VE")]
VeszpremCounty,
#[strum(serialize = "ZA")]
ZalaCounty,
#[strum(serialize = "ZE")]
Zalaegerszeg,
#[strum(serialize = "ER")]
Erd,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum IcelandStatesAbbreviation {
#[strum(serialize = "1")]
CapitalRegion,
#[strum(serialize = "7")]
EasternRegion,
#[strum(serialize = "6")]
NortheasternRegion,
#[strum(serialize = "5")]
NorthwesternRegion,
#[strum(serialize = "2")]
SouthernPeninsulaRegion,
#[strum(serialize = "8")]
SouthernRegion,
#[strum(serialize = "3")]
WesternRegion,
#[strum(serialize = "4")]
Westfjords,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum IrelandStatesAbbreviation {
#[strum(serialize = "C")]
Connacht,
#[strum(serialize = "CW")]
CountyCarlow,
#[strum(serialize = "CN")]
CountyCavan,
#[strum(serialize = "CE")]
CountyClare,
#[strum(serialize = "CO")]
CountyCork,
#[strum(serialize = "DL")]
CountyDonegal,
#[strum(serialize = "D")]
CountyDublin,
#[strum(serialize = "G")]
CountyGalway,
#[strum(serialize = "KY")]
CountyKerry,
#[strum(serialize = "KE")]
CountyKildare,
#[strum(serialize = "KK")]
CountyKilkenny,
#[strum(serialize = "LS")]
CountyLaois,
#[strum(serialize = "LK")]
CountyLimerick,
#[strum(serialize = "LD")]
CountyLongford,
#[strum(serialize = "LH")]
CountyLouth,
#[strum(serialize = "MO")]
CountyMayo,
#[strum(serialize = "MH")]
CountyMeath,
#[strum(serialize = "MN")]
CountyMonaghan,
#[strum(serialize = "OY")]
CountyOffaly,
#[strum(serialize = "RN")]
CountyRoscommon,
#[strum(serialize = "SO")]
CountySligo,
#[strum(serialize = "TA")]
CountyTipperary,
#[strum(serialize = "WD")]
CountyWaterford,
#[strum(serialize = "WH")]
CountyWestmeath,
#[strum(serialize = "WX")]
CountyWexford,
#[strum(serialize = "WW")]
CountyWicklow,
#[strum(serialize = "L")]
Leinster,
#[strum(serialize = "M")]
Munster,
#[strum(serialize = "U")]
Ulster,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum LatviaStatesAbbreviation {
#[strum(serialize = "001")]
AglonaMunicipality,
#[strum(serialize = "002")]
AizkraukleMunicipality,
#[strum(serialize = "003")]
AizputeMunicipality,
#[strum(serialize = "004")]
AknīsteMunicipality,
#[strum(serialize = "005")]
AlojaMunicipality,
#[strum(serialize = "006")]
AlsungaMunicipality,
#[strum(serialize = "007")]
AlūksneMunicipality,
#[strum(serialize = "008")]
AmataMunicipality,
#[strum(serialize = "009")]
ApeMunicipality,
#[strum(serialize = "010")]
AuceMunicipality,
#[strum(serialize = "012")]
BabīteMunicipality,
#[strum(serialize = "013")]
BaldoneMunicipality,
#[strum(serialize = "014")]
BaltinavaMunicipality,
#[strum(serialize = "015")]
BalviMunicipality,
#[strum(serialize = "016")]
BauskaMunicipality,
#[strum(serialize = "017")]
BeverīnaMunicipality,
#[strum(serialize = "018")]
BrocēniMunicipality,
#[strum(serialize = "019")]
BurtniekiMunicipality,
#[strum(serialize = "020")]
CarnikavaMunicipality,
#[strum(serialize = "021")]
CesvaineMunicipality,
#[strum(serialize = "023")]
CiblaMunicipality,
#[strum(serialize = "022")]
CēsisMunicipality,
#[strum(serialize = "024")]
DagdaMunicipality,
#[strum(serialize = "DGV")]
Daugavpils,
#[strum(serialize = "025")]
DaugavpilsMunicipality,
#[strum(serialize = "026")]
DobeleMunicipality,
#[strum(serialize = "027")]
DundagaMunicipality,
#[strum(serialize = "028")]
DurbeMunicipality,
#[strum(serialize = "029")]
EngureMunicipality,
#[strum(serialize = "031")]
GarkalneMunicipality,
#[strum(serialize = "032")]
GrobiņaMunicipality,
#[strum(serialize = "033")]
GulbeneMunicipality,
#[strum(serialize = "034")]
IecavaMunicipality,
#[strum(serialize = "035")]
IkšķileMunicipality,
#[strum(serialize = "036")]
IlūksteMunicipality,
#[strum(serialize = "037")]
InčukalnsMunicipality,
#[strum(serialize = "038")]
JaunjelgavaMunicipality,
#[strum(serialize = "039")]
JaunpiebalgaMunicipality,
#[strum(serialize = "040")]
JaunpilsMunicipality,
#[strum(serialize = "JEL")]
Jelgava,
#[strum(serialize = "041")]
JelgavaMunicipality,
#[strum(serialize = "JKB")]
Jēkabpils,
#[strum(serialize = "042")]
JēkabpilsMunicipality,
#[strum(serialize = "JUR")]
Jūrmala,
#[strum(serialize = "043")]
KandavaMunicipality,
#[strum(serialize = "045")]
KocēniMunicipality,
#[strum(serialize = "046")]
KokneseMunicipality,
#[strum(serialize = "048")]
KrimuldaMunicipality,
#[strum(serialize = "049")]
KrustpilsMunicipality,
#[strum(serialize = "047")]
KrāslavaMunicipality,
#[strum(serialize = "050")]
KuldīgaMunicipality,
#[strum(serialize = "044")]
KārsavaMunicipality,
#[strum(serialize = "053")]
LielvārdeMunicipality,
#[strum(serialize = "LPX")]
Liepāja,
#[strum(serialize = "054")]
LimbažiMunicipality,
#[strum(serialize = "057")]
LubānaMunicipality,
#[strum(serialize = "058")]
LudzaMunicipality,
#[strum(serialize = "055")]
LīgatneMunicipality,
#[strum(serialize = "056")]
LīvāniMunicipality,
#[strum(serialize = "059")]
MadonaMunicipality,
#[strum(serialize = "060")]
MazsalacaMunicipality,
#[strum(serialize = "061")]
MālpilsMunicipality,
#[strum(serialize = "062")]
MārupeMunicipality,
#[strum(serialize = "063")]
MērsragsMunicipality,
#[strum(serialize = "064")]
NaukšēniMunicipality,
#[strum(serialize = "065")]
NeretaMunicipality,
#[strum(serialize = "066")]
NīcaMunicipality,
#[strum(serialize = "067")]
OgreMunicipality,
#[strum(serialize = "068")]
OlaineMunicipality,
#[strum(serialize = "069")]
OzolniekiMunicipality,
#[strum(serialize = "073")]
PreiļiMunicipality,
#[strum(serialize = "074")]
PriekuleMunicipality,
#[strum(serialize = "075")]
PriekuļiMunicipality,
#[strum(serialize = "070")]
PārgaujaMunicipality,
#[strum(serialize = "071")]
PāvilostaMunicipality,
#[strum(serialize = "072")]
PļaviņasMunicipality,
#[strum(serialize = "076")]
RaunaMunicipality,
#[strum(serialize = "078")]
RiebiņiMunicipality,
#[strum(serialize = "RIX")]
Riga,
#[strum(serialize = "079")]
RojaMunicipality,
#[strum(serialize = "080")]
RopažiMunicipality,
#[strum(serialize = "081")]
RucavaMunicipality,
#[strum(serialize = "082")]
RugājiMunicipality,
#[strum(serialize = "083")]
RundāleMunicipality,
#[strum(serialize = "REZ")]
Rēzekne,
#[strum(serialize = "077")]
RēzekneMunicipality,
#[strum(serialize = "084")]
RūjienaMunicipality,
#[strum(serialize = "085")]
SalaMunicipality,
#[strum(serialize = "086")]
SalacgrīvaMunicipality,
#[strum(serialize = "087")]
SalaspilsMunicipality,
#[strum(serialize = "088")]
SaldusMunicipality,
#[strum(serialize = "089")]
SaulkrastiMunicipality,
#[strum(serialize = "091")]
SiguldaMunicipality,
#[strum(serialize = "093")]
SkrundaMunicipality,
#[strum(serialize = "092")]
SkrīveriMunicipality,
#[strum(serialize = "094")]
SmilteneMunicipality,
#[strum(serialize = "095")]
StopiņiMunicipality,
#[strum(serialize = "096")]
StrenčiMunicipality,
#[strum(serialize = "090")]
SējaMunicipality,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum ItalyStatesAbbreviation {
#[strum(serialize = "65")]
Abruzzo,
#[strum(serialize = "23")]
AostaValley,
#[strum(serialize = "75")]
Apulia,
#[strum(serialize = "77")]
Basilicata,
#[strum(serialize = "BN")]
BeneventoProvince,
#[strum(serialize = "78")]
Calabria,
#[strum(serialize = "72")]
Campania,
#[strum(serialize = "45")]
EmiliaRomagna,
#[strum(serialize = "36")]
FriuliVeneziaGiulia,
#[strum(serialize = "62")]
Lazio,
#[strum(serialize = "42")]
Liguria,
#[strum(serialize = "25")]
Lombardy,
#[strum(serialize = "57")]
Marche,
#[strum(serialize = "67")]
Molise,
#[strum(serialize = "21")]
Piedmont,
#[strum(serialize = "88")]
Sardinia,
#[strum(serialize = "82")]
Sicily,
#[strum(serialize = "32")]
TrentinoSouthTyrol,
#[strum(serialize = "52")]
Tuscany,
#[strum(serialize = "55")]
Umbria,
#[strum(serialize = "34")]
Veneto,
#[strum(serialize = "AG")]
Agrigento,
#[strum(serialize = "CL")]
Caltanissetta,
#[strum(serialize = "EN")]
Enna,
#[strum(serialize = "RG")]
Ragusa,
#[strum(serialize = "SR")]
Siracusa,
#[strum(serialize = "TP")]
Trapani,
#[strum(serialize = "BA")]
Bari,
#[strum(serialize = "BO")]
Bologna,
#[strum(serialize = "CA")]
Cagliari,
#[strum(serialize = "CT")]
Catania,
#[strum(serialize = "FI")]
Florence,
#[strum(serialize = "GE")]
Genoa,
#[strum(serialize = "ME")]
Messina,
#[strum(serialize = "MI")]
Milan,
#[strum(serialize = "NA")]
Naples,
#[strum(serialize = "PA")]
Palermo,
#[strum(serialize = "RC")]
ReggioCalabria,
#[strum(serialize = "RM")]
Rome,
#[strum(serialize = "TO")]
Turin,
#[strum(serialize = "VE")]
Venice,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum LiechtensteinStatesAbbreviation {
#[strum(serialize = "01")]
Balzers,
#[strum(serialize = "02")]
Eschen,
#[strum(serialize = "03")]
Gamprin,
#[strum(serialize = "04")]
Mauren,
#[strum(serialize = "05")]
Planken,
#[strum(serialize = "06")]
Ruggell,
#[strum(serialize = "07")]
Schaan,
#[strum(serialize = "08")]
Schellenberg,
#[strum(serialize = "09")]
Triesen,
#[strum(serialize = "10")]
Triesenberg,
#[strum(serialize = "11")]
Vaduz,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum LithuaniaStatesAbbreviation {
#[strum(serialize = "01")]
AkmeneDistrictMunicipality,
#[strum(serialize = "02")]
AlytusCityMunicipality,
#[strum(serialize = "AL")]
AlytusCounty,
#[strum(serialize = "03")]
AlytusDistrictMunicipality,
#[strum(serialize = "05")]
BirstonasMunicipality,
#[strum(serialize = "06")]
BirzaiDistrictMunicipality,
#[strum(serialize = "07")]
DruskininkaiMunicipality,
#[strum(serialize = "08")]
ElektrenaiMunicipality,
#[strum(serialize = "09")]
IgnalinaDistrictMunicipality,
#[strum(serialize = "10")]
JonavaDistrictMunicipality,
#[strum(serialize = "11")]
JoniskisDistrictMunicipality,
#[strum(serialize = "12")]
JurbarkasDistrictMunicipality,
#[strum(serialize = "13")]
KaisiadorysDistrictMunicipality,
#[strum(serialize = "14")]
KalvarijaMunicipality,
#[strum(serialize = "15")]
KaunasCityMunicipality,
#[strum(serialize = "KU")]
KaunasCounty,
#[strum(serialize = "16")]
KaunasDistrictMunicipality,
#[strum(serialize = "17")]
KazluRudaMunicipality,
#[strum(serialize = "19")]
KelmeDistrictMunicipality,
#[strum(serialize = "20")]
KlaipedaCityMunicipality,
#[strum(serialize = "KL")]
KlaipedaCounty,
#[strum(serialize = "21")]
KlaipedaDistrictMunicipality,
#[strum(serialize = "22")]
KretingaDistrictMunicipality,
#[strum(serialize = "23")]
KupiskisDistrictMunicipality,
#[strum(serialize = "18")]
KedainiaiDistrictMunicipality,
#[strum(serialize = "24")]
LazdijaiDistrictMunicipality,
#[strum(serialize = "MR")]
MarijampoleCounty,
#[strum(serialize = "25")]
MarijampoleMunicipality,
#[strum(serialize = "26")]
MazeikiaiDistrictMunicipality,
#[strum(serialize = "27")]
MoletaiDistrictMunicipality,
#[strum(serialize = "28")]
NeringaMunicipality,
#[strum(serialize = "29")]
PagegiaiMunicipality,
#[strum(serialize = "30")]
PakruojisDistrictMunicipality,
#[strum(serialize = "31")]
PalangaCityMunicipality,
#[strum(serialize = "32")]
PanevezysCityMunicipality,
#[strum(serialize = "PN")]
PanevezysCounty,
#[strum(serialize = "33")]
PanevezysDistrictMunicipality,
#[strum(serialize = "34")]
PasvalysDistrictMunicipality,
#[strum(serialize = "35")]
PlungeDistrictMunicipality,
#[strum(serialize = "36")]
PrienaiDistrictMunicipality,
#[strum(serialize = "37")]
RadviliskisDistrictMunicipality,
#[strum(serialize = "38")]
RaseiniaiDistrictMunicipality,
#[strum(serialize = "39")]
RietavasMunicipality,
#[strum(serialize = "40")]
RokiskisDistrictMunicipality,
#[strum(serialize = "48")]
SkuodasDistrictMunicipality,
#[strum(serialize = "TA")]
TaurageCounty,
#[strum(serialize = "50")]
TaurageDistrictMunicipality,
#[strum(serialize = "TE")]
TelsiaiCounty,
#[strum(serialize = "51")]
TelsiaiDistrictMunicipality,
#[strum(serialize = "52")]
TrakaiDistrictMunicipality,
#[strum(serialize = "53")]
UkmergeDistrictMunicipality,
#[strum(serialize = "UT")]
UtenaCounty,
#[strum(serialize = "54")]
UtenaDistrictMunicipality,
#[strum(serialize = "55")]
VarenaDistrictMunicipality,
#[strum(serialize = "56")]
VilkaviskisDistrictMunicipality,
#[strum(serialize = "57")]
VilniusCityMunicipality,
#[strum(serialize = "VL")]
VilniusCounty,
#[strum(serialize = "58")]
VilniusDistrictMunicipality,
#[strum(serialize = "59")]
VisaginasMunicipality,
#[strum(serialize = "60")]
ZarasaiDistrictMunicipality,
#[strum(serialize = "41")]
SakiaiDistrictMunicipality,
#[strum(serialize = "42")]
SalcininkaiDistrictMunicipality,
#[strum(serialize = "43")]
SiauliaiCityMunicipality,
#[strum(serialize = "SA")]
SiauliaiCounty,
#[strum(serialize = "44")]
SiauliaiDistrictMunicipality,
#[strum(serialize = "45")]
SilaleDistrictMunicipality,
#[strum(serialize = "46")]
SiluteDistrictMunicipality,
#[strum(serialize = "47")]
SirvintosDistrictMunicipality,
#[strum(serialize = "49")]
SvencionysDistrictMunicipality,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum MaltaStatesAbbreviation {
#[strum(serialize = "01")]
Attard,
#[strum(serialize = "02")]
Balzan,
#[strum(serialize = "03")]
Birgu,
#[strum(serialize = "04")]
Birkirkara,
#[strum(serialize = "05")]
Birżebbuġa,
#[strum(serialize = "06")]
Cospicua,
#[strum(serialize = "07")]
Dingli,
#[strum(serialize = "08")]
Fgura,
#[strum(serialize = "09")]
Floriana,
#[strum(serialize = "10")]
Fontana,
#[strum(serialize = "11")]
Gudja,
#[strum(serialize = "12")]
Gżira,
#[strum(serialize = "13")]
Għajnsielem,
#[strum(serialize = "14")]
Għarb,
#[strum(serialize = "15")]
Għargħur,
#[strum(serialize = "16")]
Għasri,
#[strum(serialize = "17")]
Għaxaq,
#[strum(serialize = "18")]
Ħamrun,
#[strum(serialize = "19")]
Iklin,
#[strum(serialize = "20")]
Senglea,
#[strum(serialize = "21")]
Kalkara,
#[strum(serialize = "22")]
Kerċem,
#[strum(serialize = "23")]
Kirkop,
#[strum(serialize = "24")]
Lija,
#[strum(serialize = "25")]
Luqa,
#[strum(serialize = "26")]
Marsa,
#[strum(serialize = "27")]
Marsaskala,
#[strum(serialize = "28")]
Marsaxlokk,
#[strum(serialize = "29")]
Mdina,
#[strum(serialize = "30")]
Mellieħa,
#[strum(serialize = "31")]
Mġarr,
#[strum(serialize = "32")]
Mosta,
#[strum(serialize = "33")]
Mqabba,
#[strum(serialize = "34")]
Msida,
#[strum(serialize = "35")]
Mtarfa,
#[strum(serialize = "36")]
Munxar,
#[strum(serialize = "37")]
Nadur,
#[strum(serialize = "38")]
Naxxar,
#[strum(serialize = "39")]
Paola,
#[strum(serialize = "40")]
Pembroke,
#[strum(serialize = "41")]
Pietà,
#[strum(serialize = "42")]
Qala,
#[strum(serialize = "43")]
Qormi,
#[strum(serialize = "44")]
Qrendi,
#[strum(serialize = "45")]
Victoria,
#[strum(serialize = "46")]
Rabat,
#[strum(serialize = "48")]
StJulians,
#[strum(serialize = "49")]
SanĠwann,
#[strum(serialize = "50")]
SaintLawrence,
#[strum(serialize = "51")]
StPaulsBay,
#[strum(serialize = "52")]
Sannat,
#[strum(serialize = "53")]
SantaLuċija,
#[strum(serialize = "54")]
SantaVenera,
#[strum(serialize = "55")]
Siġġiewi,
#[strum(serialize = "56")]
Sliema,
#[strum(serialize = "57")]
Swieqi,
#[strum(serialize = "58")]
TaXbiex,
#[strum(serialize = "59")]
Tarxien,
#[strum(serialize = "60")]
Valletta,
#[strum(serialize = "61")]
Xagħra,
#[strum(serialize = "62")]
Xewkija,
#[strum(serialize = "63")]
Xgħajra,
#[strum(serialize = "64")]
Żabbar,
#[strum(serialize = "65")]
ŻebbuġGozo,
#[strum(serialize = "66")]
ŻebbuġMalta,
#[strum(serialize = "67")]
Żejtun,
#[strum(serialize = "68")]
Żurrieq,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum MoldovaStatesAbbreviation {
#[strum(serialize = "AN")]
AneniiNoiDistrict,
#[strum(serialize = "BS")]
BasarabeascaDistrict,
#[strum(serialize = "BD")]
BenderMunicipality,
#[strum(serialize = "BR")]
BriceniDistrict,
#[strum(serialize = "BA")]
BălțiMunicipality,
#[strum(serialize = "CA")]
CahulDistrict,
#[strum(serialize = "CT")]
CantemirDistrict,
#[strum(serialize = "CU")]
ChișinăuMunicipality,
#[strum(serialize = "CM")]
CimișliaDistrict,
#[strum(serialize = "CR")]
CriuleniDistrict,
#[strum(serialize = "CL")]
CălărașiDistrict,
#[strum(serialize = "CS")]
CăușeniDistrict,
#[strum(serialize = "DO")]
DondușeniDistrict,
#[strum(serialize = "DR")]
DrochiaDistrict,
#[strum(serialize = "DU")]
DubăsariDistrict,
#[strum(serialize = "ED")]
EdinețDistrict,
#[strum(serialize = "FL")]
FloreștiDistrict,
#[strum(serialize = "FA")]
FăleștiDistrict,
#[strum(serialize = "GA")]
Găgăuzia,
#[strum(serialize = "GL")]
GlodeniDistrict,
#[strum(serialize = "HI")]
HînceștiDistrict,
#[strum(serialize = "IA")]
IaloveniDistrict,
#[strum(serialize = "NI")]
NisporeniDistrict,
#[strum(serialize = "OC")]
OcnițaDistrict,
#[strum(serialize = "OR")]
OrheiDistrict,
#[strum(serialize = "RE")]
RezinaDistrict,
#[strum(serialize = "RI")]
RîșcaniDistrict,
#[strum(serialize = "SO")]
SorocaDistrict,
#[strum(serialize = "ST")]
StrășeniDistrict,
#[strum(serialize = "SI")]
SîngereiDistrict,
#[strum(serialize = "TA")]
TaracliaDistrict,
#[strum(serialize = "TE")]
TeleneștiDistrict,
#[strum(serialize = "SN")]
TransnistriaAutonomousTerritorialUnit,
#[strum(serialize = "UN")]
UngheniDistrict,
#[strum(serialize = "SD")]
ȘoldăneștiDistrict,
#[strum(serialize = "SV")]
ȘtefanVodăDistrict,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum MonacoStatesAbbreviation {
Monaco,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum MontenegroStatesAbbreviation {
#[strum(serialize = "01")]
AndrijevicaMunicipality,
#[strum(serialize = "02")]
BarMunicipality,
#[strum(serialize = "03")]
BeraneMunicipality,
#[strum(serialize = "04")]
BijeloPoljeMunicipality,
#[strum(serialize = "05")]
BudvaMunicipality,
#[strum(serialize = "07")]
DanilovgradMunicipality,
#[strum(serialize = "22")]
GusinjeMunicipality,
#[strum(serialize = "09")]
KolasinMunicipality,
#[strum(serialize = "10")]
KotorMunicipality,
#[strum(serialize = "11")]
MojkovacMunicipality,
#[strum(serialize = "12")]
NiksicMunicipality,
#[strum(serialize = "06")]
OldRoyalCapitalCetinje,
#[strum(serialize = "23")]
PetnjicaMunicipality,
#[strum(serialize = "13")]
PlavMunicipality,
#[strum(serialize = "14")]
PljevljaMunicipality,
#[strum(serialize = "15")]
PlužineMunicipality,
#[strum(serialize = "16")]
PodgoricaMunicipality,
#[strum(serialize = "17")]
RožajeMunicipality,
#[strum(serialize = "19")]
TivatMunicipality,
#[strum(serialize = "20")]
UlcinjMunicipality,
#[strum(serialize = "18")]
SavnikMunicipality,
#[strum(serialize = "21")]
ŽabljakMunicipality,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum NetherlandsStatesAbbreviation {
#[strum(serialize = "BQ1")]
Bonaire,
#[strum(serialize = "DR")]
Drenthe,
#[strum(serialize = "FL")]
Flevoland,
#[strum(serialize = "FR")]
Friesland,
#[strum(serialize = "GE")]
Gelderland,
#[strum(serialize = "GR")]
Groningen,
#[strum(serialize = "LI")]
Limburg,
#[strum(serialize = "NB")]
NorthBrabant,
#[strum(serialize = "NH")]
NorthHolland,
#[strum(serialize = "OV")]
Overijssel,
#[strum(serialize = "BQ2")]
Saba,
#[strum(serialize = "BQ3")]
SintEustatius,
#[strum(serialize = "ZH")]
SouthHolland,
#[strum(serialize = "UT")]
Utrecht,
#[strum(serialize = "ZE")]
Zeeland,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum NorthMacedoniaStatesAbbreviation {
#[strum(serialize = "01")]
AerodromMunicipality,
#[strum(serialize = "02")]
AracinovoMunicipality,
#[strum(serialize = "03")]
BerovoMunicipality,
#[strum(serialize = "04")]
BitolaMunicipality,
#[strum(serialize = "05")]
BogdanciMunicipality,
#[strum(serialize = "06")]
BogovinjeMunicipality,
#[strum(serialize = "07")]
BosilovoMunicipality,
#[strum(serialize = "08")]
BrvenicaMunicipality,
#[strum(serialize = "09")]
ButelMunicipality,
#[strum(serialize = "77")]
CentarMunicipality,
#[strum(serialize = "78")]
CentarZupaMunicipality,
#[strum(serialize = "22")]
DebarcaMunicipality,
#[strum(serialize = "23")]
DelcevoMunicipality,
#[strum(serialize = "25")]
DemirHisarMunicipality,
#[strum(serialize = "24")]
DemirKapijaMunicipality,
#[strum(serialize = "26")]
DojranMunicipality,
#[strum(serialize = "27")]
DolneniMunicipality,
#[strum(serialize = "28")]
DrugovoMunicipality,
#[strum(serialize = "17")]
GaziBabaMunicipality,
#[strum(serialize = "18")]
GevgelijaMunicipality,
#[strum(serialize = "29")]
GjorcePetrovMunicipality,
#[strum(serialize = "19")]
GostivarMunicipality,
#[strum(serialize = "20")]
GradskoMunicipality,
#[strum(serialize = "85")]
GreaterSkopje,
#[strum(serialize = "34")]
IlindenMunicipality,
#[strum(serialize = "35")]
JegunovceMunicipality,
#[strum(serialize = "37")]
Karbinci,
#[strum(serialize = "38")]
KarposMunicipality,
#[strum(serialize = "36")]
KavadarciMunicipality,
#[strum(serialize = "39")]
KiselaVodaMunicipality,
#[strum(serialize = "40")]
KicevoMunicipality,
#[strum(serialize = "41")]
KonceMunicipality,
#[strum(serialize = "42")]
KocaniMunicipality,
#[strum(serialize = "43")]
KratovoMunicipality,
#[strum(serialize = "44")]
KrivaPalankaMunicipality,
#[strum(serialize = "45")]
KrivogastaniMunicipality,
#[strum(serialize = "46")]
KrusevoMunicipality,
#[strum(serialize = "47")]
KumanovoMunicipality,
#[strum(serialize = "48")]
LipkovoMunicipality,
#[strum(serialize = "49")]
LozovoMunicipality,
#[strum(serialize = "51")]
MakedonskaKamenicaMunicipality,
#[strum(serialize = "52")]
MakedonskiBrodMunicipality,
#[strum(serialize = "50")]
MavrovoAndRostusaMunicipality,
#[strum(serialize = "53")]
MogilaMunicipality,
#[strum(serialize = "54")]
NegotinoMunicipality,
#[strum(serialize = "55")]
NovaciMunicipality,
#[strum(serialize = "56")]
NovoSeloMunicipality,
#[strum(serialize = "58")]
OhridMunicipality,
#[strum(serialize = "57")]
OslomejMunicipality,
#[strum(serialize = "60")]
PehcevoMunicipality,
#[strum(serialize = "59")]
PetrovecMunicipality,
#[strum(serialize = "61")]
PlasnicaMunicipality,
#[strum(serialize = "62")]
PrilepMunicipality,
#[strum(serialize = "63")]
ProbishtipMunicipality,
#[strum(serialize = "64")]
RadovisMunicipality,
#[strum(serialize = "65")]
RankovceMunicipality,
#[strum(serialize = "66")]
ResenMunicipality,
#[strum(serialize = "67")]
RosomanMunicipality,
#[strum(serialize = "68")]
SarajMunicipality,
#[strum(serialize = "70")]
SopisteMunicipality,
#[strum(serialize = "71")]
StaroNagoricaneMunicipality,
#[strum(serialize = "72")]
StrugaMunicipality,
#[strum(serialize = "73")]
StrumicaMunicipality,
#[strum(serialize = "74")]
StudenicaniMunicipality,
#[strum(serialize = "69")]
SvetiNikoleMunicipality,
#[strum(serialize = "75")]
TearceMunicipality,
#[strum(serialize = "76")]
TetovoMunicipality,
#[strum(serialize = "10")]
ValandovoMunicipality,
#[strum(serialize = "11")]
VasilevoMunicipality,
#[strum(serialize = "13")]
VelesMunicipality,
#[strum(serialize = "12")]
VevcaniMunicipality,
#[strum(serialize = "14")]
VinicaMunicipality,
#[strum(serialize = "15")]
VranesticaMunicipality,
#[strum(serialize = "16")]
VrapcisteMunicipality,
#[strum(serialize = "31")]
ZajasMunicipality,
#[strum(serialize = "32")]
ZelenikovoMunicipality,
#[strum(serialize = "33")]
ZrnovciMunicipality,
#[strum(serialize = "79")]
CairMunicipality,
#[strum(serialize = "80")]
CaskaMunicipality,
#[strum(serialize = "81")]
CesinovoOblesevoMunicipality,
#[strum(serialize = "82")]
CucerSandevoMunicipality,
#[strum(serialize = "83")]
StipMunicipality,
#[strum(serialize = "84")]
ShutoOrizariMunicipality,
#[strum(serialize = "30")]
ZelinoMunicipality,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum NorwayStatesAbbreviation {
#[strum(serialize = "02")]
Akershus,
#[strum(serialize = "06")]
Buskerud,
#[strum(serialize = "20")]
Finnmark,
#[strum(serialize = "04")]
Hedmark,
#[strum(serialize = "12")]
Hordaland,
#[strum(serialize = "22")]
JanMayen,
#[strum(serialize = "15")]
MoreOgRomsdal,
#[strum(serialize = "17")]
NordTrondelag,
#[strum(serialize = "18")]
Nordland,
#[strum(serialize = "05")]
Oppland,
#[strum(serialize = "03")]
Oslo,
#[strum(serialize = "11")]
Rogaland,
#[strum(serialize = "14")]
SognOgFjordane,
#[strum(serialize = "21")]
Svalbard,
#[strum(serialize = "16")]
SorTrondelag,
#[strum(serialize = "08")]
Telemark,
#[strum(serialize = "19")]
Troms,
#[strum(serialize = "50")]
Trondelag,
#[strum(serialize = "10")]
VestAgder,
#[strum(serialize = "07")]
Vestfold,
#[strum(serialize = "01")]
Ostfold,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum PolandStatesAbbreviation {
#[strum(serialize = "30")]
GreaterPoland,
#[strum(serialize = "26")]
HolyCross,
#[strum(serialize = "04")]
KuyaviaPomerania,
#[strum(serialize = "12")]
LesserPoland,
#[strum(serialize = "02")]
LowerSilesia,
#[strum(serialize = "06")]
Lublin,
#[strum(serialize = "08")]
Lubusz,
#[strum(serialize = "10")]
Łódź,
#[strum(serialize = "14")]
Mazovia,
#[strum(serialize = "20")]
Podlaskie,
#[strum(serialize = "22")]
Pomerania,
#[strum(serialize = "24")]
Silesia,
#[strum(serialize = "18")]
Subcarpathia,
#[strum(serialize = "16")]
UpperSilesia,
#[strum(serialize = "28")]
WarmiaMasuria,
#[strum(serialize = "32")]
WestPomerania,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum PortugalStatesAbbreviation {
#[strum(serialize = "01")]
AveiroDistrict,
#[strum(serialize = "20")]
Azores,
#[strum(serialize = "02")]
BejaDistrict,
#[strum(serialize = "03")]
BragaDistrict,
#[strum(serialize = "04")]
BragancaDistrict,
#[strum(serialize = "05")]
CasteloBrancoDistrict,
#[strum(serialize = "06")]
CoimbraDistrict,
#[strum(serialize = "08")]
FaroDistrict,
#[strum(serialize = "09")]
GuardaDistrict,
#[strum(serialize = "10")]
LeiriaDistrict,
#[strum(serialize = "11")]
LisbonDistrict,
#[strum(serialize = "30")]
Madeira,
#[strum(serialize = "12")]
PortalegreDistrict,
#[strum(serialize = "13")]
PortoDistrict,
#[strum(serialize = "14")]
SantaremDistrict,
#[strum(serialize = "15")]
SetubalDistrict,
#[strum(serialize = "16")]
VianaDoCasteloDistrict,
#[strum(serialize = "17")]
VilaRealDistrict,
#[strum(serialize = "18")]
ViseuDistrict,
#[strum(serialize = "07")]
EvoraDistrict,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum SpainStatesAbbreviation {
#[strum(serialize = "C")]
ACorunaProvince,
#[strum(serialize = "AB")]
AlbaceteProvince,
#[strum(serialize = "A")]
AlicanteProvince,
#[strum(serialize = "AL")]
AlmeriaProvince,
#[strum(serialize = "AN")]
Andalusia,
#[strum(serialize = "VI")]
ArabaAlava,
#[strum(serialize = "AR")]
Aragon,
#[strum(serialize = "BA")]
BadajozProvince,
#[strum(serialize = "PM")]
BalearicIslands,
#[strum(serialize = "B")]
BarcelonaProvince,
#[strum(serialize = "PV")]
BasqueCountry,
#[strum(serialize = "BI")]
Biscay,
#[strum(serialize = "BU")]
BurgosProvince,
#[strum(serialize = "CN")]
CanaryIslands,
#[strum(serialize = "S")]
Cantabria,
#[strum(serialize = "CS")]
CastellonProvince,
#[strum(serialize = "CL")]
CastileAndLeon,
#[strum(serialize = "CM")]
CastileLaMancha,
#[strum(serialize = "CT")]
Catalonia,
#[strum(serialize = "CE")]
Ceuta,
#[strum(serialize = "CR")]
CiudadRealProvince,
#[strum(serialize = "MD")]
CommunityOfMadrid,
#[strum(serialize = "CU")]
CuencaProvince,
#[strum(serialize = "CC")]
CaceresProvince,
#[strum(serialize = "CA")]
CadizProvince,
#[strum(serialize = "CO")]
CordobaProvince,
#[strum(serialize = "EX")]
Extremadura,
#[strum(serialize = "GA")]
Galicia,
#[strum(serialize = "SS")]
Gipuzkoa,
#[strum(serialize = "GI")]
GironaProvince,
#[strum(serialize = "GR")]
GranadaProvince,
#[strum(serialize = "GU")]
GuadalajaraProvince,
#[strum(serialize = "H")]
HuelvaProvince,
#[strum(serialize = "HU")]
HuescaProvince,
#[strum(serialize = "J")]
JaenProvince,
#[strum(serialize = "RI")]
LaRioja,
#[strum(serialize = "GC")]
LasPalmasProvince,
#[strum(serialize = "LE")]
LeonProvince,
#[strum(serialize = "L")]
LleidaProvince,
#[strum(serialize = "LU")]
LugoProvince,
#[strum(serialize = "M")]
MadridProvince,
#[strum(serialize = "ML")]
Melilla,
#[strum(serialize = "MU")]
MurciaProvince,
#[strum(serialize = "MA")]
MalagaProvince,
#[strum(serialize = "NC")]
Navarre,
#[strum(serialize = "OR")]
OurenseProvince,
#[strum(serialize = "P")]
PalenciaProvince,
#[strum(serialize = "PO")]
PontevedraProvince,
#[strum(serialize = "O")]
ProvinceOfAsturias,
#[strum(serialize = "AV")]
ProvinceOfAvila,
#[strum(serialize = "MC")]
RegionOfMurcia,
#[strum(serialize = "SA")]
SalamancaProvince,
#[strum(serialize = "TF")]
SantaCruzDeTenerifeProvince,
#[strum(serialize = "SG")]
SegoviaProvince,
#[strum(serialize = "SE")]
SevilleProvince,
#[strum(serialize = "SO")]
SoriaProvince,
#[strum(serialize = "T")]
TarragonaProvince,
#[strum(serialize = "TE")]
TeruelProvince,
#[strum(serialize = "TO")]
ToledoProvince,
#[strum(serialize = "V")]
ValenciaProvince,
#[strum(serialize = "VC")]
ValencianCommunity,
#[strum(serialize = "VA")]
ValladolidProvince,
#[strum(serialize = "ZA")]
ZamoraProvince,
#[strum(serialize = "Z")]
ZaragozaProvince,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum SwitzerlandStatesAbbreviation {
#[strum(serialize = "AG")]
Aargau,
#[strum(serialize = "AR")]
AppenzellAusserrhoden,
#[strum(serialize = "AI")]
AppenzellInnerrhoden,
#[strum(serialize = "BL")]
BaselLandschaft,
#[strum(serialize = "FR")]
CantonOfFribourg,
#[strum(serialize = "GE")]
CantonOfGeneva,
#[strum(serialize = "JU")]
CantonOfJura,
#[strum(serialize = "LU")]
CantonOfLucerne,
#[strum(serialize = "NE")]
CantonOfNeuchatel,
#[strum(serialize = "SH")]
CantonOfSchaffhausen,
#[strum(serialize = "SO")]
CantonOfSolothurn,
#[strum(serialize = "SG")]
CantonOfStGallen,
#[strum(serialize = "VS")]
CantonOfValais,
#[strum(serialize = "VD")]
CantonOfVaud,
#[strum(serialize = "ZG")]
CantonOfZug,
#[strum(serialize = "GL")]
Glarus,
#[strum(serialize = "GR")]
Graubunden,
#[strum(serialize = "NW")]
Nidwalden,
#[strum(serialize = "OW")]
Obwalden,
#[strum(serialize = "SZ")]
Schwyz,
#[strum(serialize = "TG")]
Thurgau,
#[strum(serialize = "TI")]
Ticino,
#[strum(serialize = "UR")]
Uri,
#[strum(serialize = "BE")]
CantonOfBern,
#[strum(serialize = "ZH")]
CantonOfZurich,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum UnitedKingdomStatesAbbreviation {
#[strum(serialize = "ABE")]
Aberdeen,
#[strum(serialize = "ABD")]
Aberdeenshire,
#[strum(serialize = "ANS")]
Angus,
#[strum(serialize = "ANT")]
Antrim,
#[strum(serialize = "ANN")]
AntrimAndNewtownabbey,
#[strum(serialize = "ARD")]
Ards,
#[strum(serialize = "AND")]
ArdsAndNorthDown,
#[strum(serialize = "AGB")]
ArgyllAndBute,
#[strum(serialize = "ARM")]
ArmaghCityAndDistrictCouncil,
#[strum(serialize = "ABC")]
ArmaghBanbridgeAndCraigavon,
#[strum(serialize = "SH-AC")]
AscensionIsland,
#[strum(serialize = "BLA")]
BallymenaBorough,
#[strum(serialize = "BLY")]
Ballymoney,
#[strum(serialize = "BNB")]
Banbridge,
#[strum(serialize = "BNS")]
Barnsley,
#[strum(serialize = "BAS")]
BathAndNorthEastSomerset,
#[strum(serialize = "BDF")]
Bedford,
#[strum(serialize = "BFS")]
BelfastDistrict,
#[strum(serialize = "BIR")]
Birmingham,
#[strum(serialize = "BBD")]
BlackburnWithDarwen,
#[strum(serialize = "BPL")]
Blackpool,
#[strum(serialize = "BGW")]
BlaenauGwentCountyBorough,
#[strum(serialize = "BOL")]
Bolton,
#[strum(serialize = "BMH")]
Bournemouth,
#[strum(serialize = "BRC")]
BracknellForest,
#[strum(serialize = "BRD")]
Bradford,
#[strum(serialize = "BGE")]
BridgendCountyBorough,
#[strum(serialize = "BNH")]
BrightonAndHove,
#[strum(serialize = "BKM")]
Buckinghamshire,
#[strum(serialize = "BUR")]
Bury,
#[strum(serialize = "CAY")]
CaerphillyCountyBorough,
#[strum(serialize = "CLD")]
Calderdale,
#[strum(serialize = "CAM")]
Cambridgeshire,
#[strum(serialize = "CMN")]
Carmarthenshire,
#[strum(serialize = "CKF")]
CarrickfergusBoroughCouncil,
#[strum(serialize = "CSR")]
Castlereagh,
#[strum(serialize = "CCG")]
CausewayCoastAndGlens,
#[strum(serialize = "CBF")]
CentralBedfordshire,
#[strum(serialize = "CGN")]
Ceredigion,
#[strum(serialize = "CHE")]
CheshireEast,
#[strum(serialize = "CHW")]
CheshireWestAndChester,
#[strum(serialize = "CRF")]
CityAndCountyOfCardiff,
#[strum(serialize = "SWA")]
CityAndCountyOfSwansea,
#[strum(serialize = "BST")]
CityOfBristol,
#[strum(serialize = "DER")]
CityOfDerby,
#[strum(serialize = "KHL")]
CityOfKingstonUponHull,
#[strum(serialize = "LCE")]
CityOfLeicester,
#[strum(serialize = "LND")]
CityOfLondon,
#[strum(serialize = "NGM")]
CityOfNottingham,
#[strum(serialize = "PTE")]
CityOfPeterborough,
#[strum(serialize = "PLY")]
CityOfPlymouth,
#[strum(serialize = "POR")]
CityOfPortsmouth,
#[strum(serialize = "STH")]
CityOfSouthampton,
#[strum(serialize = "STE")]
CityOfStokeOnTrent,
#[strum(serialize = "SND")]
CityOfSunderland,
#[strum(serialize = "WSM")]
CityOfWestminster,
#[strum(serialize = "WLV")]
CityOfWolverhampton,
#[strum(serialize = "YOR")]
CityOfYork,
#[strum(serialize = "CLK")]
Clackmannanshire,
#[strum(serialize = "CLR")]
ColeraineBoroughCouncil,
#[strum(serialize = "CWY")]
ConwyCountyBorough,
#[strum(serialize = "CKT")]
CookstownDistrictCouncil,
#[strum(serialize = "CON")]
Cornwall,
#[strum(serialize = "DUR")]
CountyDurham,
#[strum(serialize = "COV")]
Coventry,
#[strum(serialize = "CGV")]
CraigavonBoroughCouncil,
#[strum(serialize = "CMA")]
Cumbria,
#[strum(serialize = "DAL")]
Darlington,
#[strum(serialize = "DEN")]
Denbighshire,
#[strum(serialize = "DBY")]
Derbyshire,
#[strum(serialize = "DRS")]
DerryCityAndStrabane,
#[strum(serialize = "DRY")]
DerryCityCouncil,
#[strum(serialize = "DEV")]
Devon,
#[strum(serialize = "DNC")]
Doncaster,
#[strum(serialize = "DOR")]
Dorset,
#[strum(serialize = "DOW")]
DownDistrictCouncil,
#[strum(serialize = "DUD")]
Dudley,
#[strum(serialize = "DGY")]
DumfriesAndGalloway,
#[strum(serialize = "DND")]
Dundee,
#[strum(serialize = "DGN")]
DungannonAndSouthTyroneBoroughCouncil,
#[strum(serialize = "EAY")]
EastAyrshire,
#[strum(serialize = "EDU")]
EastDunbartonshire,
#[strum(serialize = "ELN")]
EastLothian,
#[strum(serialize = "ERW")]
EastRenfrewshire,
#[strum(serialize = "ERY")]
EastRidingOfYorkshire,
#[strum(serialize = "ESX")]
EastSussex,
#[strum(serialize = "EDH")]
Edinburgh,
#[strum(serialize = "ENG")]
England,
#[strum(serialize = "ESS")]
Essex,
#[strum(serialize = "FAL")]
Falkirk,
#[strum(serialize = "FMO")]
FermanaghAndOmagh,
#[strum(serialize = "FER")]
FermanaghDistrictCouncil,
#[strum(serialize = "FIF")]
Fife,
#[strum(serialize = "FLN")]
Flintshire,
#[strum(serialize = "GAT")]
Gateshead,
#[strum(serialize = "GLG")]
Glasgow,
#[strum(serialize = "GLS")]
Gloucestershire,
#[strum(serialize = "GWN")]
Gwynedd,
#[strum(serialize = "HAL")]
Halton,
#[strum(serialize = "HAM")]
Hampshire,
#[strum(serialize = "HPL")]
Hartlepool,
#[strum(serialize = "HEF")]
Herefordshire,
#[strum(serialize = "HRT")]
Hertfordshire,
#[strum(serialize = "HLD")]
Highland,
#[strum(serialize = "IVC")]
Inverclyde,
#[strum(serialize = "IOW")]
IsleOfWight,
#[strum(serialize = "IOS")]
IslesOfScilly,
#[strum(serialize = "KEN")]
Kent,
#[strum(serialize = "KIR")]
Kirklees,
#[strum(serialize = "KWL")]
Knowsley,
#[strum(serialize = "LAN")]
Lancashire,
#[strum(serialize = "LRN")]
LarneBoroughCouncil,
#[strum(serialize = "LDS")]
Leeds,
#[strum(serialize = "LEC")]
Leicestershire,
#[strum(serialize = "LMV")]
LimavadyBoroughCouncil,
#[strum(serialize = "LIN")]
Lincolnshire,
#[strum(serialize = "LBC")]
LisburnAndCastlereagh,
#[strum(serialize = "LSB")]
LisburnCityCouncil,
#[strum(serialize = "LIV")]
Liverpool,
#[strum(serialize = "BDG")]
LondonBoroughOfBarkingAndDagenham,
#[strum(serialize = "BNE")]
LondonBoroughOfBarnet,
#[strum(serialize = "BEX")]
LondonBoroughOfBexley,
#[strum(serialize = "BEN")]
LondonBoroughOfBrent,
#[strum(serialize = "BRY")]
LondonBoroughOfBromley,
#[strum(serialize = "CMD")]
LondonBoroughOfCamden,
#[strum(serialize = "CRY")]
LondonBoroughOfCroydon,
#[strum(serialize = "EAL")]
LondonBoroughOfEaling,
#[strum(serialize = "ENF")]
LondonBoroughOfEnfield,
#[strum(serialize = "HCK")]
LondonBoroughOfHackney,
#[strum(serialize = "HMF")]
LondonBoroughOfHammersmithAndFulham,
#[strum(serialize = "HRY")]
LondonBoroughOfHaringey,
#[strum(serialize = "HRW")]
LondonBoroughOfHarrow,
#[strum(serialize = "HAV")]
LondonBoroughOfHavering,
#[strum(serialize = "HIL")]
LondonBoroughOfHillingdon,
#[strum(serialize = "HNS")]
LondonBoroughOfHounslow,
#[strum(serialize = "ISL")]
LondonBoroughOfIslington,
#[strum(serialize = "LBH")]
LondonBoroughOfLambeth,
#[strum(serialize = "LEW")]
LondonBoroughOfLewisham,
#[strum(serialize = "MRT")]
LondonBoroughOfMerton,
#[strum(serialize = "NWM")]
LondonBoroughOfNewham,
#[strum(serialize = "RDB")]
LondonBoroughOfRedbridge,
#[strum(serialize = "RIC")]
LondonBoroughOfRichmondUponThames,
#[strum(serialize = "SWK")]
LondonBoroughOfSouthwark,
#[strum(serialize = "STN")]
LondonBoroughOfSutton,
#[strum(serialize = "TWH")]
LondonBoroughOfTowerHamlets,
#[strum(serialize = "WFT")]
LondonBoroughOfWalthamForest,
#[strum(serialize = "WND")]
LondonBoroughOfWandsworth,
#[strum(serialize = "MFT")]
MagherafeltDistrictCouncil,
#[strum(serialize = "MAN")]
Manchester,
#[strum(serialize = "MDW")]
Medway,
#[strum(serialize = "MTY")]
MerthyrTydfilCountyBorough,
#[strum(serialize = "WGN")]
MetropolitanBoroughOfWigan,
#[strum(serialize = "MEA")]
MidAndEastAntrim,
#[strum(serialize = "MUL")]
MidUlster,
#[strum(serialize = "MDB")]
Middlesbrough,
#[strum(serialize = "MLN")]
Midlothian,
#[strum(serialize = "MIK")]
MiltonKeynes,
#[strum(serialize = "MON")]
Monmouthshire,
#[strum(serialize = "MRY")]
Moray,
#[strum(serialize = "MYL")]
MoyleDistrictCouncil,
#[strum(serialize = "NTL")]
NeathPortTalbotCountyBorough,
#[strum(serialize = "NET")]
NewcastleUponTyne,
#[strum(serialize = "NWP")]
Newport,
#[strum(serialize = "NYM")]
NewryAndMourneDistrictCouncil,
#[strum(serialize = "NMD")]
NewryMourneAndDown,
#[strum(serialize = "NTA")]
NewtownabbeyBoroughCouncil,
#[strum(serialize = "NFK")]
Norfolk,
#[strum(serialize = "NAY")]
NorthAyrshire,
#[strum(serialize = "NDN")]
NorthDownBoroughCouncil,
#[strum(serialize = "NEL")]
NorthEastLincolnshire,
#[strum(serialize = "NLK")]
NorthLanarkshire,
#[strum(serialize = "NLN")]
NorthLincolnshire,
#[strum(serialize = "NSM")]
NorthSomerset,
#[strum(serialize = "NTY")]
NorthTyneside,
#[strum(serialize = "NYK")]
NorthYorkshire,
#[strum(serialize = "NTH")]
Northamptonshire,
#[strum(serialize = "NIR")]
NorthernIreland,
#[strum(serialize = "NBL")]
Northumberland,
#[strum(serialize = "NTT")]
Nottinghamshire,
#[strum(serialize = "OLD")]
Oldham,
#[strum(serialize = "OMH")]
OmaghDistrictCouncil,
#[strum(serialize = "ORK")]
OrkneyIslands,
#[strum(serialize = "ELS")]
OuterHebrides,
#[strum(serialize = "OXF")]
Oxfordshire,
#[strum(serialize = "PEM")]
Pembrokeshire,
#[strum(serialize = "PKN")]
PerthAndKinross,
#[strum(serialize = "POL")]
Poole,
#[strum(serialize = "POW")]
Powys,
#[strum(serialize = "RDG")]
Reading,
#[strum(serialize = "RCC")]
RedcarAndCleveland,
#[strum(serialize = "RFW")]
Renfrewshire,
#[strum(serialize = "RCT")]
RhonddaCynonTaf,
#[strum(serialize = "RCH")]
Rochdale,
#[strum(serialize = "ROT")]
Rotherham,
#[strum(serialize = "GRE")]
RoyalBoroughOfGreenwich,
#[strum(serialize = "KEC")]
RoyalBoroughOfKensingtonAndChelsea,
#[strum(serialize = "KTT")]
RoyalBoroughOfKingstonUponThames,
#[strum(serialize = "RUT")]
Rutland,
#[strum(serialize = "SH-HL")]
SaintHelena,
#[strum(serialize = "SLF")]
Salford,
#[strum(serialize = "SAW")]
Sandwell,
#[strum(serialize = "SCT")]
Scotland,
#[strum(serialize = "SCB")]
ScottishBorders,
#[strum(serialize = "SFT")]
Sefton,
#[strum(serialize = "SHF")]
Sheffield,
#[strum(serialize = "ZET")]
ShetlandIslands,
#[strum(serialize = "SHR")]
Shropshire,
#[strum(serialize = "SLG")]
Slough,
#[strum(serialize = "SOL")]
Solihull,
#[strum(serialize = "SOM")]
Somerset,
#[strum(serialize = "SAY")]
SouthAyrshire,
#[strum(serialize = "SGC")]
SouthGloucestershire,
#[strum(serialize = "SLK")]
SouthLanarkshire,
#[strum(serialize = "STY")]
SouthTyneside,
#[strum(serialize = "SOS")]
SouthendOnSea,
#[strum(serialize = "SHN")]
StHelens,
#[strum(serialize = "STS")]
Staffordshire,
#[strum(serialize = "STG")]
Stirling,
#[strum(serialize = "SKP")]
Stockport,
#[strum(serialize = "STT")]
StocktonOnTees,
#[strum(serialize = "STB")]
StrabaneDistrictCouncil,
#[strum(serialize = "SFK")]
Suffolk,
#[strum(serialize = "SRY")]
Surrey,
#[strum(serialize = "SWD")]
Swindon,
#[strum(serialize = "TAM")]
Tameside,
#[strum(serialize = "TFW")]
TelfordAndWrekin,
#[strum(serialize = "THR")]
Thurrock,
#[strum(serialize = "TOB")]
Torbay,
#[strum(serialize = "TOF")]
Torfaen,
#[strum(serialize = "TRF")]
Trafford,
#[strum(serialize = "UKM")]
UnitedKingdom,
#[strum(serialize = "VGL")]
ValeOfGlamorgan,
#[strum(serialize = "WKF")]
Wakefield,
#[strum(serialize = "WLS")]
Wales,
#[strum(serialize = "WLL")]
Walsall,
#[strum(serialize = "WRT")]
Warrington,
#[strum(serialize = "WAR")]
Warwickshire,
#[strum(serialize = "WBK")]
WestBerkshire,
#[strum(serialize = "WDU")]
WestDunbartonshire,
#[strum(serialize = "WLN")]
WestLothian,
#[strum(serialize = "WSX")]
WestSussex,
#[strum(serialize = "WIL")]
Wiltshire,
#[strum(serialize = "WNM")]
WindsorAndMaidenhead,
#[strum(serialize = "WRL")]
Wirral,
#[strum(serialize = "WOK")]
Wokingham,
#[strum(serialize = "WOR")]
Worcestershire,
#[strum(serialize = "WRX")]
WrexhamCountyBorough,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum BelgiumStatesAbbreviation {
#[strum(serialize = "VAN")]
Antwerp,
#[strum(serialize = "BRU")]
BrusselsCapitalRegion,
#[strum(serialize = "VOV")]
EastFlanders,
#[strum(serialize = "VLG")]
Flanders,
#[strum(serialize = "VBR")]
FlemishBrabant,
#[strum(serialize = "WHT")]
Hainaut,
#[strum(serialize = "VLI")]
Limburg,
#[strum(serialize = "WLG")]
Liege,
#[strum(serialize = "WLX")]
Luxembourg,
#[strum(serialize = "WNA")]
Namur,
#[strum(serialize = "WAL")]
Wallonia,
#[strum(serialize = "WBR")]
WalloonBrabant,
#[strum(serialize = "VWV")]
WestFlanders,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum LuxembourgStatesAbbreviation {
#[strum(serialize = "CA")]
CantonOfCapellen,
#[strum(serialize = "CL")]
CantonOfClervaux,
#[strum(serialize = "DI")]
CantonOfDiekirch,
#[strum(serialize = "EC")]
CantonOfEchternach,
#[strum(serialize = "ES")]
CantonOfEschSurAlzette,
#[strum(serialize = "GR")]
CantonOfGrevenmacher,
#[strum(serialize = "LU")]
CantonOfLuxembourg,
#[strum(serialize = "ME")]
CantonOfMersch,
#[strum(serialize = "RD")]
CantonOfRedange,
#[strum(serialize = "RM")]
CantonOfRemich,
#[strum(serialize = "VD")]
CantonOfVianden,
#[strum(serialize = "WI")]
CantonOfWiltz,
#[strum(serialize = "D")]
DiekirchDistrict,
#[strum(serialize = "G")]
GrevenmacherDistrict,
#[strum(serialize = "L")]
LuxembourgDistrict,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum RussiaStatesAbbreviation {
#[strum(serialize = "ALT")]
AltaiKrai,
#[strum(serialize = "AL")]
AltaiRepublic,
#[strum(serialize = "AMU")]
AmurOblast,
#[strum(serialize = "ARK")]
Arkhangelsk,
#[strum(serialize = "AST")]
AstrakhanOblast,
#[strum(serialize = "BEL")]
BelgorodOblast,
#[strum(serialize = "BRY")]
BryanskOblast,
#[strum(serialize = "CE")]
ChechenRepublic,
#[strum(serialize = "CHE")]
ChelyabinskOblast,
#[strum(serialize = "CHU")]
ChukotkaAutonomousOkrug,
#[strum(serialize = "CU")]
ChuvashRepublic,
#[strum(serialize = "IRK")]
Irkutsk,
#[strum(serialize = "IVA")]
IvanovoOblast,
#[strum(serialize = "YEV")]
JewishAutonomousOblast,
#[strum(serialize = "KB")]
KabardinoBalkarRepublic,
#[strum(serialize = "KGD")]
Kaliningrad,
#[strum(serialize = "KLU")]
KalugaOblast,
#[strum(serialize = "KAM")]
KamchatkaKrai,
#[strum(serialize = "KC")]
KarachayCherkessRepublic,
#[strum(serialize = "KEM")]
KemerovoOblast,
#[strum(serialize = "KHA")]
KhabarovskKrai,
#[strum(serialize = "KHM")]
KhantyMansiAutonomousOkrug,
#[strum(serialize = "KIR")]
KirovOblast,
#[strum(serialize = "KO")]
KomiRepublic,
#[strum(serialize = "KOS")]
KostromaOblast,
#[strum(serialize = "KDA")]
KrasnodarKrai,
#[strum(serialize = "KYA")]
KrasnoyarskKrai,
#[strum(serialize = "KGN")]
KurganOblast,
#[strum(serialize = "KRS")]
KurskOblast,
#[strum(serialize = "LEN")]
LeningradOblast,
#[strum(serialize = "LIP")]
LipetskOblast,
#[strum(serialize = "MAG")]
MagadanOblast,
#[strum(serialize = "ME")]
MariElRepublic,
#[strum(serialize = "MOW")]
Moscow,
#[strum(serialize = "MOS")]
MoscowOblast,
#[strum(serialize = "MUR")]
MurmanskOblast,
#[strum(serialize = "NEN")]
NenetsAutonomousOkrug,
#[strum(serialize = "NIZ")]
NizhnyNovgorodOblast,
#[strum(serialize = "NGR")]
NovgorodOblast,
#[strum(serialize = "NVS")]
Novosibirsk,
#[strum(serialize = "OMS")]
OmskOblast,
#[strum(serialize = "ORE")]
OrenburgOblast,
#[strum(serialize = "ORL")]
OryolOblast,
#[strum(serialize = "PNZ")]
PenzaOblast,
#[strum(serialize = "PER")]
PermKrai,
#[strum(serialize = "PRI")]
PrimorskyKrai,
#[strum(serialize = "PSK")]
PskovOblast,
#[strum(serialize = "AD")]
RepublicOfAdygea,
#[strum(serialize = "BA")]
RepublicOfBashkortostan,
#[strum(serialize = "BU")]
RepublicOfBuryatia,
#[strum(serialize = "DA")]
RepublicOfDagestan,
#[strum(serialize = "IN")]
RepublicOfIngushetia,
#[strum(serialize = "KL")]
RepublicOfKalmykia,
#[strum(serialize = "KR")]
RepublicOfKarelia,
#[strum(serialize = "KK")]
RepublicOfKhakassia,
#[strum(serialize = "MO")]
RepublicOfMordovia,
#[strum(serialize = "SE")]
RepublicOfNorthOssetiaAlania,
#[strum(serialize = "TA")]
RepublicOfTatarstan,
#[strum(serialize = "ROS")]
RostovOblast,
#[strum(serialize = "RYA")]
RyazanOblast,
#[strum(serialize = "SPE")]
SaintPetersburg,
#[strum(serialize = "SA")]
SakhaRepublic,
#[strum(serialize = "SAK")]
Sakhalin,
#[strum(serialize = "SAM")]
SamaraOblast,
#[strum(serialize = "SAR")]
SaratovOblast,
#[strum(serialize = "UA-40")]
Sevastopol,
#[strum(serialize = "SMO")]
SmolenskOblast,
#[strum(serialize = "STA")]
StavropolKrai,
#[strum(serialize = "SVE")]
Sverdlovsk,
#[strum(serialize = "TAM")]
TambovOblast,
#[strum(serialize = "TOM")]
TomskOblast,
#[strum(serialize = "TUL")]
TulaOblast,
#[strum(serialize = "TY")]
TuvaRepublic,
#[strum(serialize = "TVE")]
TverOblast,
#[strum(serialize = "TYU")]
TyumenOblast,
#[strum(serialize = "UD")]
UdmurtRepublic,
#[strum(serialize = "ULY")]
UlyanovskOblast,
#[strum(serialize = "VLA")]
VladimirOblast,
#[strum(serialize = "VLG")]
VologdaOblast,
#[strum(serialize = "VOR")]
VoronezhOblast,
#[strum(serialize = "YAN")]
YamaloNenetsAutonomousOkrug,
#[strum(serialize = "YAR")]
YaroslavlOblast,
#[strum(serialize = "ZAB")]
ZabaykalskyKrai,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum SanMarinoStatesAbbreviation {
#[strum(serialize = "01")]
Acquaviva,
#[strum(serialize = "06")]
BorgoMaggiore,
#[strum(serialize = "02")]
Chiesanuova,
#[strum(serialize = "03")]
Domagnano,
#[strum(serialize = "04")]
Faetano,
#[strum(serialize = "05")]
Fiorentino,
#[strum(serialize = "08")]
Montegiardino,
#[strum(serialize = "07")]
SanMarino,
#[strum(serialize = "09")]
Serravalle,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum SerbiaStatesAbbreviation {
#[strum(serialize = "00")]
Belgrade,
#[strum(serialize = "01")]
BorDistrict,
#[strum(serialize = "02")]
BraničevoDistrict,
#[strum(serialize = "03")]
CentralBanatDistrict,
#[strum(serialize = "04")]
JablanicaDistrict,
#[strum(serialize = "05")]
KolubaraDistrict,
#[strum(serialize = "06")]
MačvaDistrict,
#[strum(serialize = "07")]
MoravicaDistrict,
#[strum(serialize = "08")]
NišavaDistrict,
#[strum(serialize = "09")]
NorthBanatDistrict,
#[strum(serialize = "10")]
NorthBačkaDistrict,
#[strum(serialize = "11")]
PirotDistrict,
#[strum(serialize = "12")]
PodunavljeDistrict,
#[strum(serialize = "13")]
PomoravljeDistrict,
#[strum(serialize = "14")]
PčinjaDistrict,
#[strum(serialize = "15")]
RasinaDistrict,
#[strum(serialize = "16")]
RaškaDistrict,
#[strum(serialize = "17")]
SouthBanatDistrict,
#[strum(serialize = "18")]
SouthBačkaDistrict,
#[strum(serialize = "19")]
SremDistrict,
#[strum(serialize = "20")]
ToplicaDistrict,
#[strum(serialize = "21")]
Vojvodina,
#[strum(serialize = "22")]
WestBačkaDistrict,
#[strum(serialize = "23")]
ZaječarDistrict,
#[strum(serialize = "24")]
ZlatiborDistrict,
#[strum(serialize = "25")]
ŠumadijaDistrict,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum SlovakiaStatesAbbreviation {
#[strum(serialize = "BC")]
BanskaBystricaRegion,
#[strum(serialize = "BL")]
BratislavaRegion,
#[strum(serialize = "KI")]
KosiceRegion,
#[strum(serialize = "NI")]
NitraRegion,
#[strum(serialize = "PV")]
PresovRegion,
#[strum(serialize = "TC")]
TrencinRegion,
#[strum(serialize = "TA")]
TrnavaRegion,
#[strum(serialize = "ZI")]
ZilinaRegion,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum SloveniaStatesAbbreviation {
#[strum(serialize = "001")]
Ajdovščina,
#[strum(serialize = "213")]
Ankaran,
#[strum(serialize = "002")]
Beltinci,
#[strum(serialize = "148")]
Benedikt,
#[strum(serialize = "149")]
BistricaObSotli,
#[strum(serialize = "003")]
Bled,
#[strum(serialize = "150")]
Bloke,
#[strum(serialize = "004")]
Bohinj,
#[strum(serialize = "005")]
Borovnica,
#[strum(serialize = "006")]
Bovec,
#[strum(serialize = "151")]
Braslovče,
#[strum(serialize = "007")]
Brda,
#[strum(serialize = "008")]
Brezovica,
#[strum(serialize = "009")]
Brežice,
#[strum(serialize = "152")]
Cankova,
#[strum(serialize = "012")]
CerkljeNaGorenjskem,
#[strum(serialize = "013")]
Cerknica,
#[strum(serialize = "014")]
Cerkno,
#[strum(serialize = "153")]
Cerkvenjak,
#[strum(serialize = "011")]
CityMunicipalityOfCelje,
#[strum(serialize = "085")]
CityMunicipalityOfNovoMesto,
#[strum(serialize = "018")]
Destrnik,
#[strum(serialize = "019")]
Divača,
#[strum(serialize = "154")]
Dobje,
#[strum(serialize = "020")]
Dobrepolje,
#[strum(serialize = "155")]
Dobrna,
#[strum(serialize = "021")]
DobrovaPolhovGradec,
#[strum(serialize = "156")]
Dobrovnik,
#[strum(serialize = "022")]
DolPriLjubljani,
#[strum(serialize = "157")]
DolenjskeToplice,
#[strum(serialize = "023")]
Domžale,
#[strum(serialize = "024")]
Dornava,
#[strum(serialize = "025")]
Dravograd,
#[strum(serialize = "026")]
Duplek,
#[strum(serialize = "027")]
GorenjaVasPoljane,
#[strum(serialize = "028")]
Gorišnica,
#[strum(serialize = "207")]
Gorje,
#[strum(serialize = "029")]
GornjaRadgona,
#[strum(serialize = "030")]
GornjiGrad,
#[strum(serialize = "031")]
GornjiPetrovci,
#[strum(serialize = "158")]
Grad,
#[strum(serialize = "032")]
Grosuplje,
#[strum(serialize = "159")]
Hajdina,
#[strum(serialize = "161")]
Hodoš,
#[strum(serialize = "162")]
Horjul,
#[strum(serialize = "160")]
HočeSlivnica,
#[strum(serialize = "034")]
Hrastnik,
#[strum(serialize = "035")]
HrpeljeKozina,
#[strum(serialize = "036")]
Idrija,
#[strum(serialize = "037")]
Ig,
#[strum(serialize = "039")]
IvančnaGorica,
#[strum(serialize = "040")]
Izola,
#[strum(serialize = "041")]
Jesenice,
#[strum(serialize = "163")]
Jezersko,
#[strum(serialize = "042")]
Jursinci,
#[strum(serialize = "043")]
Kamnik,
#[strum(serialize = "044")]
KanalObSoci,
#[strum(serialize = "045")]
Kidricevo,
#[strum(serialize = "046")]
Kobarid,
#[strum(serialize = "047")]
Kobilje,
#[strum(serialize = "049")]
Komen,
#[strum(serialize = "164")]
Komenda,
#[strum(serialize = "050")]
Koper,
#[strum(serialize = "197")]
KostanjevicaNaKrki,
#[strum(serialize = "165")]
Kostel,
#[strum(serialize = "051")]
Kozje,
#[strum(serialize = "048")]
Kocevje,
#[strum(serialize = "052")]
Kranj,
#[strum(serialize = "053")]
KranjskaGora,
#[strum(serialize = "166")]
Krizevci,
#[strum(serialize = "055")]
Kungota,
#[strum(serialize = "056")]
Kuzma,
#[strum(serialize = "057")]
Lasko,
#[strum(serialize = "058")]
Lenart,
#[strum(serialize = "059")]
Lendava,
#[strum(serialize = "060")]
Litija,
#[strum(serialize = "061")]
Ljubljana,
#[strum(serialize = "062")]
Ljubno,
#[strum(serialize = "063")]
Ljutomer,
#[strum(serialize = "064")]
Logatec,
#[strum(serialize = "208")]
LogDragomer,
#[strum(serialize = "167")]
LovrencNaPohorju,
#[strum(serialize = "065")]
LoskaDolina,
#[strum(serialize = "066")]
LoskiPotok,
#[strum(serialize = "068")]
Lukovica,
#[strum(serialize = "067")]
Luče,
#[strum(serialize = "069")]
Majsperk,
#[strum(serialize = "198")]
Makole,
#[strum(serialize = "070")]
Maribor,
#[strum(serialize = "168")]
Markovci,
#[strum(serialize = "071")]
Medvode,
#[strum(serialize = "072")]
Menges,
#[strum(serialize = "073")]
Metlika,
#[strum(serialize = "074")]
Mezica,
#[strum(serialize = "169")]
MiklavzNaDravskemPolju,
#[strum(serialize = "075")]
MirenKostanjevica,
#[strum(serialize = "212")]
Mirna,
#[strum(serialize = "170")]
MirnaPec,
#[strum(serialize = "076")]
Mislinja,
#[strum(serialize = "199")]
MokronogTrebelno,
#[strum(serialize = "078")]
MoravskeToplice,
#[strum(serialize = "077")]
Moravce,
#[strum(serialize = "079")]
Mozirje,
#[strum(serialize = "195")]
Apače,
#[strum(serialize = "196")]
Cirkulane,
#[strum(serialize = "038")]
IlirskaBistrica,
#[strum(serialize = "054")]
Krsko,
#[strum(serialize = "123")]
Skofljica,
#[strum(serialize = "080")]
MurskaSobota,
#[strum(serialize = "081")]
Muta,
#[strum(serialize = "082")]
Naklo,
#[strum(serialize = "083")]
Nazarje,
#[strum(serialize = "084")]
NovaGorica,
#[strum(serialize = "086")]
Odranci,
#[strum(serialize = "171")]
Oplotnica,
#[strum(serialize = "087")]
Ormoz,
#[strum(serialize = "088")]
Osilnica,
#[strum(serialize = "089")]
Pesnica,
#[strum(serialize = "090")]
Piran,
#[strum(serialize = "091")]
Pivka,
#[strum(serialize = "172")]
Podlehnik,
#[strum(serialize = "093")]
Podvelka,
#[strum(serialize = "092")]
Podcetrtek,
#[strum(serialize = "200")]
Poljcane,
#[strum(serialize = "173")]
Polzela,
#[strum(serialize = "094")]
Postojna,
#[strum(serialize = "174")]
Prebold,
#[strum(serialize = "095")]
Preddvor,
#[strum(serialize = "175")]
Prevalje,
#[strum(serialize = "096")]
Ptuj,
#[strum(serialize = "097")]
Puconci,
#[strum(serialize = "100")]
Radenci,
#[strum(serialize = "099")]
Radece,
#[strum(serialize = "101")]
RadljeObDravi,
#[strum(serialize = "102")]
Radovljica,
#[strum(serialize = "103")]
RavneNaKoroskem,
#[strum(serialize = "176")]
Razkrizje,
#[strum(serialize = "098")]
RaceFram,
#[strum(serialize = "201")]
RenčeVogrsko,
#[strum(serialize = "209")]
RecicaObSavinji,
#[strum(serialize = "104")]
Ribnica,
#[strum(serialize = "177")]
RibnicaNaPohorju,
#[strum(serialize = "107")]
Rogatec,
#[strum(serialize = "106")]
RogaskaSlatina,
#[strum(serialize = "105")]
Rogasovci,
#[strum(serialize = "108")]
Ruse,
#[strum(serialize = "178")]
SelnicaObDravi,
#[strum(serialize = "109")]
Semic,
#[strum(serialize = "110")]
Sevnica,
#[strum(serialize = "111")]
Sezana,
#[strum(serialize = "112")]
SlovenjGradec,
#[strum(serialize = "113")]
SlovenskaBistrica,
#[strum(serialize = "114")]
SlovenskeKonjice,
#[strum(serialize = "179")]
Sodrazica,
#[strum(serialize = "180")]
Solcava,
#[strum(serialize = "202")]
SredisceObDravi,
#[strum(serialize = "115")]
Starse,
#[strum(serialize = "203")]
Straza,
#[strum(serialize = "181")]
SvetaAna,
#[strum(serialize = "204")]
SvetaTrojica,
#[strum(serialize = "182")]
SvetiAndraz,
#[strum(serialize = "116")]
SvetiJurijObScavnici,
#[strum(serialize = "210")]
SvetiJurijVSlovenskihGoricah,
#[strum(serialize = "205")]
SvetiTomaz,
#[strum(serialize = "184")]
Tabor,
#[strum(serialize = "010")]
Tišina,
#[strum(serialize = "128")]
Tolmin,
#[strum(serialize = "129")]
Trbovlje,
#[strum(serialize = "130")]
Trebnje,
#[strum(serialize = "185")]
TrnovskaVas,
#[strum(serialize = "186")]
Trzin,
#[strum(serialize = "131")]
Tržič,
#[strum(serialize = "132")]
Turnišče,
#[strum(serialize = "187")]
VelikaPolana,
#[strum(serialize = "134")]
VelikeLašče,
#[strum(serialize = "188")]
Veržej,
#[strum(serialize = "135")]
Videm,
#[strum(serialize = "136")]
Vipava,
#[strum(serialize = "137")]
Vitanje,
#[strum(serialize = "138")]
Vodice,
#[strum(serialize = "139")]
Vojnik,
#[strum(serialize = "189")]
Vransko,
#[strum(serialize = "140")]
Vrhnika,
#[strum(serialize = "141")]
Vuzenica,
#[strum(serialize = "142")]
ZagorjeObSavi,
#[strum(serialize = "143")]
Zavrč,
#[strum(serialize = "144")]
Zreče,
#[strum(serialize = "015")]
Črenšovci,
#[strum(serialize = "016")]
ČrnaNaKoroškem,
#[strum(serialize = "017")]
Črnomelj,
#[strum(serialize = "033")]
Šalovci,
#[strum(serialize = "183")]
ŠempeterVrtojba,
#[strum(serialize = "118")]
Šentilj,
#[strum(serialize = "119")]
Šentjernej,
#[strum(serialize = "120")]
Šentjur,
#[strum(serialize = "211")]
Šentrupert,
#[strum(serialize = "117")]
Šenčur,
#[strum(serialize = "121")]
Škocjan,
#[strum(serialize = "122")]
ŠkofjaLoka,
#[strum(serialize = "124")]
ŠmarjePriJelšah,
#[strum(serialize = "206")]
ŠmarješkeToplice,
#[strum(serialize = "125")]
ŠmartnoObPaki,
#[strum(serialize = "194")]
ŠmartnoPriLitiji,
#[strum(serialize = "126")]
Šoštanj,
#[strum(serialize = "127")]
Štore,
#[strum(serialize = "190")]
Žalec,
#[strum(serialize = "146")]
Železniki,
#[strum(serialize = "191")]
Žetale,
#[strum(serialize = "147")]
Žiri,
#[strum(serialize = "192")]
Žirovnica,
#[strum(serialize = "193")]
Žužemberk,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum SwedenStatesAbbreviation {
#[strum(serialize = "K")]
Blekinge,
#[strum(serialize = "W")]
DalarnaCounty,
#[strum(serialize = "I")]
GotlandCounty,
#[strum(serialize = "X")]
GävleborgCounty,
#[strum(serialize = "N")]
HallandCounty,
#[strum(serialize = "F")]
JönköpingCounty,
#[strum(serialize = "H")]
KalmarCounty,
#[strum(serialize = "G")]
KronobergCounty,
#[strum(serialize = "BD")]
NorrbottenCounty,
#[strum(serialize = "M")]
SkåneCounty,
#[strum(serialize = "AB")]
StockholmCounty,
#[strum(serialize = "D")]
SödermanlandCounty,
#[strum(serialize = "C")]
UppsalaCounty,
#[strum(serialize = "S")]
VärmlandCounty,
#[strum(serialize = "AC")]
VästerbottenCounty,
#[strum(serialize = "Y")]
VästernorrlandCounty,
#[strum(serialize = "U")]
VästmanlandCounty,
#[strum(serialize = "O")]
VästraGötalandCounty,
#[strum(serialize = "T")]
ÖrebroCounty,
#[strum(serialize = "E")]
ÖstergötlandCounty,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum UkraineStatesAbbreviation {
#[strum(serialize = "43")]
AutonomousRepublicOfCrimea,
#[strum(serialize = "71")]
CherkasyOblast,
#[strum(serialize = "74")]
ChernihivOblast,
#[strum(serialize = "77")]
ChernivtsiOblast,
#[strum(serialize = "12")]
DnipropetrovskOblast,
#[strum(serialize = "14")]
DonetskOblast,
#[strum(serialize = "26")]
IvanoFrankivskOblast,
#[strum(serialize = "63")]
KharkivOblast,
#[strum(serialize = "65")]
KhersonOblast,
#[strum(serialize = "68")]
KhmelnytskyOblast,
#[strum(serialize = "30")]
Kiev,
#[strum(serialize = "35")]
KirovohradOblast,
#[strum(serialize = "32")]
KyivOblast,
#[strum(serialize = "09")]
LuhanskOblast,
#[strum(serialize = "46")]
LvivOblast,
#[strum(serialize = "48")]
MykolaivOblast,
#[strum(serialize = "51")]
OdessaOblast,
#[strum(serialize = "56")]
RivneOblast,
#[strum(serialize = "59")]
SumyOblast,
#[strum(serialize = "61")]
TernopilOblast,
#[strum(serialize = "05")]
VinnytsiaOblast,
#[strum(serialize = "07")]
VolynOblast,
#[strum(serialize = "21")]
ZakarpattiaOblast,
#[strum(serialize = "23")]
ZaporizhzhyaOblast,
#[strum(serialize = "18")]
ZhytomyrOblast,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum RomaniaStatesAbbreviation {
#[strum(serialize = "AB")]
Alba,
#[strum(serialize = "AR")]
AradCounty,
#[strum(serialize = "AG")]
Arges,
#[strum(serialize = "BC")]
BacauCounty,
#[strum(serialize = "BH")]
BihorCounty,
#[strum(serialize = "BN")]
BistritaNasaudCounty,
#[strum(serialize = "BT")]
BotosaniCounty,
#[strum(serialize = "BR")]
Braila,
#[strum(serialize = "BV")]
BrasovCounty,
#[strum(serialize = "B")]
Bucharest,
#[strum(serialize = "BZ")]
BuzauCounty,
#[strum(serialize = "CS")]
CarasSeverinCounty,
#[strum(serialize = "CJ")]
ClujCounty,
#[strum(serialize = "CT")]
ConstantaCounty,
#[strum(serialize = "CV")]
CovasnaCounty,
#[strum(serialize = "CL")]
CalarasiCounty,
#[strum(serialize = "DJ")]
DoljCounty,
#[strum(serialize = "DB")]
DambovitaCounty,
#[strum(serialize = "GL")]
GalatiCounty,
#[strum(serialize = "GR")]
GiurgiuCounty,
#[strum(serialize = "GJ")]
GorjCounty,
#[strum(serialize = "HR")]
HarghitaCounty,
#[strum(serialize = "HD")]
HunedoaraCounty,
#[strum(serialize = "IL")]
IalomitaCounty,
#[strum(serialize = "IS")]
IasiCounty,
#[strum(serialize = "IF")]
IlfovCounty,
#[strum(serialize = "MH")]
MehedintiCounty,
#[strum(serialize = "MM")]
MuresCounty,
#[strum(serialize = "NT")]
NeamtCounty,
#[strum(serialize = "OT")]
OltCounty,
#[strum(serialize = "PH")]
PrahovaCounty,
#[strum(serialize = "SM")]
SatuMareCounty,
#[strum(serialize = "SB")]
SibiuCounty,
#[strum(serialize = "SV")]
SuceavaCounty,
#[strum(serialize = "SJ")]
SalajCounty,
#[strum(serialize = "TR")]
TeleormanCounty,
#[strum(serialize = "TM")]
TimisCounty,
#[strum(serialize = "TL")]
TulceaCounty,
#[strum(serialize = "VS")]
VasluiCounty,
#[strum(serialize = "VN")]
VranceaCounty,
#[strum(serialize = "VL")]
ValceaCounty,
}
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
pub enum BrazilStatesAbbreviation {
#[strum(serialize = "AC")]
Acre,
#[strum(serialize = "AL")]
Alagoas,
#[strum(serialize = "AP")]
Amapá,
#[strum(serialize = "AM")]
Amazonas,
#[strum(serialize = "BA")]
Bahia,
#[strum(serialize = "CE")]
Ceará,
#[strum(serialize = "DF")]
DistritoFederal,
#[strum(serialize = "ES")]
EspíritoSanto,
#[strum(serialize = "GO")]
Goiás,
#[strum(serialize = "MA")]
Maranhão,
#[strum(serialize = "MT")]
MatoGrosso,
#[strum(serialize = "MS")]
MatoGrossoDoSul,
#[strum(serialize = "MG")]
MinasGerais,
#[strum(serialize = "PA")]
Pará,
#[strum(serialize = "PB")]
Paraíba,
#[strum(serialize = "PR")]
Paraná,
#[strum(serialize = "PE")]
Pernambuco,
#[strum(serialize = "PI")]
Piauí,
#[strum(serialize = "RJ")]
RioDeJaneiro,
#[strum(serialize = "RN")]
RioGrandeDoNorte,
#[strum(serialize = "RS")]
RioGrandeDoSul,
#[strum(serialize = "RO")]
Rondônia,
#[strum(serialize = "RR")]
Roraima,
#[strum(serialize = "SC")]
SantaCatarina,
#[strum(serialize = "SP")]
SãoPaulo,
#[strum(serialize = "SE")]
Sergipe,
#[strum(serialize = "TO")]
Tocantins,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
ToSchema,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumIter,
strum::EnumString,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PayoutStatus {
Success,
Failed,
Cancelled,
Initiated,
Expired,
Reversed,
Pending,
Ineligible,
#[default]
RequiresCreation,
RequiresConfirmation,
RequiresPayoutMethodData,
RequiresFulfillment,
RequiresVendorAccountCreation,
}
/// The payout_type of the payout request is a mandatory field for confirming the payouts. It should be specified in the Create request. If not provided, it must be updated in the Payout Update request before it can be confirmed.
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PayoutType {
#[default]
Card,
Bank,
Wallet,
BankRedirect,
}
/// Type of entity to whom the payout is being carried out to, select from the given list of options
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "PascalCase")]
#[strum(serialize_all = "PascalCase")]
pub enum PayoutEntityType {
/// Adyen
#[default]
Individual,
Company,
NonProfit,
PublicSector,
NaturalPerson,
/// Wise
#[strum(serialize = "lowercase")]
#[serde(rename = "lowercase")]
Business,
Personal,
}
/// The send method which will be required for processing payouts, check options for better understanding.
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PayoutSendPriority {
Instant,
Fast,
Regular,
Wire,
CrossBorder,
Internal,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PaymentSource {
#[default]
MerchantServer,
Postman,
Dashboard,
Sdk,
Webhook,
ExternalAuthenticator,
}
#[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)]
pub enum BrowserName {
#[default]
Safari,
#[serde(other)]
Unknown,
}
#[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)]
#[strum(serialize_all = "snake_case")]
pub enum ClientPlatform {
#[default]
Web,
Ios,
Android,
#[serde(other)]
Unknown,
}
impl PaymentSource {
pub fn is_for_internal_use_only(self) -> bool {
match self {
Self::Dashboard | Self::Sdk | Self::MerchantServer | Self::Postman => false,
Self::Webhook | Self::ExternalAuthenticator => true,
}
}
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
pub enum MerchantDecision {
Approved,
Rejected,
AutoRefunded,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum TaxStatus {
Taxable,
Exempt,
}
#[derive(
Clone,
Copy,
Default,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum FrmSuggestion {
#[default]
FrmCancelTransaction,
FrmManualReview,
FrmAuthorizeTransaction, // When manual capture payment which was marked fraud and held, when approved needs to be authorized.
}
#[derive(
Clone,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
utoipa::ToSchema,
Copy,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ReconStatus {
NotRequested,
Requested,
Active,
Disabled,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum AuthenticationConnectors {
Threedsecureio,
Netcetera,
Gpayments,
CtpMastercard,
UnifiedAuthenticationService,
Juspaythreedsserver,
CtpVisa,
Cardinal,
}
impl AuthenticationConnectors {
pub fn is_separate_version_call_required(self) -> bool {
match self {
Self::Threedsecureio
| Self::Netcetera
| Self::CtpMastercard
| Self::UnifiedAuthenticationService
| Self::Juspaythreedsserver
| Self::CtpVisa
| Self::Cardinal => false,
Self::Gpayments => true,
}
}
pub fn is_jwt_flow(&self) -> bool {
match self {
Self::Threedsecureio
| Self::Netcetera
| Self::CtpMastercard
| Self::UnifiedAuthenticationService
| Self::Juspaythreedsserver
| Self::CtpVisa
| Self::Gpayments => false,
Self::Cardinal => true,
}
}
}
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum VaultSdk {
VgsSdk,
HyperswitchSdk,
}
#[derive(
Clone,
Debug,
Eq,
Default,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
utoipa::ToSchema,
Copy,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum AuthenticationStatus {
#[default]
Started,
Pending,
Success,
Failed,
}
impl AuthenticationStatus {
pub fn is_terminal_status(self) -> bool {
match self {
Self::Started | Self::Pending => false,
Self::Success | Self::Failed => true,
}
}
pub fn is_failed(self) -> bool {
self == Self::Failed
}
pub fn is_success(self) -> bool {
self == Self::Success
}
}
#[derive(
Clone,
Debug,
Eq,
Default,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
utoipa::ToSchema,
Copy,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum DecoupledAuthenticationType {
#[default]
Challenge,
Frictionless,
}
#[derive(
Clone,
Debug,
Eq,
Default,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
utoipa::ToSchema,
Copy,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum AuthenticationLifecycleStatus {
Used,
#[default]
Unused,
Expired,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
strum::Display,
strum::EnumString,
serde::Deserialize,
serde::Serialize,
ToSchema,
Default,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum ConnectorStatus {
#[default]
Inactive,
Active,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
strum::Display,
strum::EnumString,
serde::Deserialize,
serde::Serialize,
ToSchema,
Default,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum TransactionType {
#[default]
Payment,
#[cfg(feature = "payouts")]
Payout,
ThreeDsAuthentication,
}
impl TransactionType {
pub fn is_three_ds_authentication(self) -> bool {
matches!(self, Self::ThreeDsAuthentication)
}
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RoleScope {
Organization,
Merchant,
Profile,
}
impl From<RoleScope> for EntityType {
fn from(role_scope: RoleScope) -> Self {
match role_scope {
RoleScope::Organization => Self::Organization,
RoleScope::Merchant => Self::Merchant,
RoleScope::Profile => Self::Profile,
}
}
}
/// Indicates the transaction status
#[derive(
Clone,
Default,
Debug,
serde::Serialize,
serde::Deserialize,
Eq,
Hash,
PartialEq,
ToSchema,
strum::Display,
strum::EnumString,
)]
#[router_derive::diesel_enum(storage_type = "text")]
pub enum TransactionStatus {
/// Authentication/ Account Verification Successful
#[serde(rename = "Y")]
Success,
/// Not Authenticated /Account Not Verified; Transaction denied
#[default]
#[serde(rename = "N")]
Failure,
/// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in Authentication Response(ARes) or Result Request (RReq)
#[serde(rename = "U")]
VerificationNotPerformed,
/// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided
#[serde(rename = "A")]
NotVerified,
/// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted.
#[serde(rename = "R")]
Rejected,
/// Challenge Required; Additional authentication is required using the Challenge Request (CReq) / Challenge Response (CRes)
#[serde(rename = "C")]
ChallengeRequired,
/// Challenge Required; Decoupled Authentication confirmed.
#[serde(rename = "D")]
ChallengeRequiredDecoupledAuthentication,
/// Informational Only; 3DS Requestor challenge preference acknowledged.
#[serde(rename = "I")]
InformationOnly,
}
impl TransactionStatus {
pub fn is_pending(self) -> bool {
matches!(
self,
Self::ChallengeRequired | Self::ChallengeRequiredDecoupledAuthentication
)
}
pub fn is_terminal_state(self) -> bool {
matches!(self, Self::Success | Self::Failure)
}
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
Hash,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PermissionGroup {
OperationsView,
OperationsManage,
ConnectorsView,
ConnectorsManage,
WorkflowsView,
WorkflowsManage,
AnalyticsView,
UsersView,
UsersManage,
AccountView,
AccountManage,
ReconReportsView,
ReconReportsManage,
ReconOpsView,
ReconOpsManage,
InternalManage,
ThemeView,
ThemeManage,
}
#[derive(
Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, strum::EnumIter,
)]
pub enum ParentGroup {
Operations,
Connectors,
Workflows,
Analytics,
Users,
ReconOps,
ReconReports,
Account,
Internal,
Theme,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Resource {
Payment,
Refund,
ApiKey,
Account,
Connector,
Routing,
Dispute,
Mandate,
Customer,
Analytics,
ThreeDsDecisionManager,
SurchargeDecisionManager,
User,
WebhookEvent,
Payout,
Report,
ReconToken,
ReconFiles,
ReconAndSettlementAnalytics,
ReconUpload,
ReconReports,
RunRecon,
ReconConfig,
RevenueRecovery,
Subscription,
InternalConnector,
Theme,
}
#[derive(
Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, serde::Deserialize, Hash,
)]
#[serde(rename_all = "snake_case")]
pub enum PermissionScope {
Read = 0,
Write = 1,
}
/// Name of banks supported by Hyperswitch
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum BankNames {
AmericanExpress,
AffinBank,
AgroBank,
AllianceBank,
AmBank,
BankOfAmerica,
BankOfChina,
BankIslam,
BankMuamalat,
BankRakyat,
BankSimpananNasional,
Barclays,
BlikPSP,
CapitalOne,
Chase,
Citi,
CimbBank,
Discover,
NavyFederalCreditUnion,
PentagonFederalCreditUnion,
SynchronyBank,
WellsFargo,
AbnAmro,
AsnBank,
Bunq,
Handelsbanken,
HongLeongBank,
HsbcBank,
Ing,
Knab,
KuwaitFinanceHouse,
Moneyou,
Rabobank,
Regiobank,
Revolut,
SnsBank,
TriodosBank,
VanLanschot,
ArzteUndApothekerBank,
AustrianAnadiBankAg,
BankAustria,
Bank99Ag,
BankhausCarlSpangler,
BankhausSchelhammerUndSchatteraAg,
BankMillennium,
BankPEKAOSA,
BawagPskAg,
BksBankAg,
BrullKallmusBankAg,
BtvVierLanderBank,
CapitalBankGraweGruppeAg,
CeskaSporitelna,
Dolomitenbank,
EasybankAg,
EPlatbyVUB,
ErsteBankUndSparkassen,
FrieslandBank,
HypoAlpeadriabankInternationalAg,
HypoNoeLbFurNiederosterreichUWien,
HypoOberosterreichSalzburgSteiermark,
HypoTirolBankAg,
HypoVorarlbergBankAg,
HypoBankBurgenlandAktiengesellschaft,
KomercniBanka,
MBank,
MarchfelderBank,
Maybank,
OberbankAg,
OsterreichischeArzteUndApothekerbank,
OcbcBank,
PayWithING,
PlaceZIPKO,
PlatnoscOnlineKartaPlatnicza,
PosojilnicaBankEGen,
PostovaBanka,
PublicBank,
RaiffeisenBankengruppeOsterreich,
RhbBank,
SchelhammerCapitalBankAg,
StandardCharteredBank,
SchoellerbankAg,
SpardaBankWien,
SporoPay,
SantanderPrzelew24,
TatraPay,
Viamo,
VolksbankGruppe,
VolkskreditbankAg,
VrBankBraunau,
UobBank,
PayWithAliorBank,
BankiSpoldzielcze,
PayWithInteligo,
BNPParibasPoland,
BankNowySA,
CreditAgricole,
PayWithBOS,
PayWithCitiHandlowy,
PayWithPlusBank,
ToyotaBank,
VeloBank,
ETransferPocztowy24,
PlusBank,
EtransferPocztowy24,
BankiSpbdzielcze,
BankNowyBfgSa,
GetinBank,
Blik,
NoblePay,
IdeaBank,
EnveloBank,
NestPrzelew,
MbankMtransfer,
Inteligo,
PbacZIpko,
BnpParibas,
BankPekaoSa,
VolkswagenBank,
AliorBank,
Boz,
BangkokBank,
KrungsriBank,
KrungThaiBank,
TheSiamCommercialBank,
KasikornBank,
OpenBankSuccess,
OpenBankFailure,
OpenBankCancelled,
Aib,
BankOfScotland,
DanskeBank,
FirstDirect,
FirstTrust,
Halifax,
Lloyds,
Monzo,
NatWest,
NationwideBank,
RoyalBankOfScotland,
Starling,
TsbBank,
TescoBank,
UlsterBank,
Yoursafe,
N26,
NationaleNederlanden,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum BankType {
Checking,
Savings,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum BankHolderType {
Personal,
Business,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
strum::Display,
serde::Serialize,
strum::EnumIter,
strum::EnumString,
strum::VariantNames,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum GenericLinkType {
#[default]
PaymentMethodCollect,
PayoutLink,
}
#[derive(Debug, Clone, PartialEq, Eq, strum::Display, serde::Deserialize, serde::Serialize)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum TokenPurpose {
AuthSelect,
#[serde(rename = "sso")]
#[strum(serialize = "sso")]
SSO,
#[serde(rename = "totp")]
#[strum(serialize = "totp")]
TOTP,
VerifyEmail,
AcceptInvitationFromEmail,
ForceSetPassword,
ResetPassword,
AcceptInvite,
UserInfo,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum UserAuthType {
OpenIdConnect,
MagicLink,
#[default]
Password,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum Owner {
Organization,
Tenant,
Internal,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum ApiVersion {
V1,
V2,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
Ord,
PartialOrd,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
ToSchema,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum EntityType {
Tenant = 3,
Organization = 2,
Merchant = 1,
Profile = 0,
}
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PayoutRetryType {
SingleConnector,
MultiConnector,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum OrderFulfillmentTimeOrigin {
Create,
Confirm,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum UIWidgetFormLayout {
Tabs,
Journey,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum DeleteStatus {
#[default]
Active,
Redacted,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
Hash,
strum::EnumString,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
#[router_derive::diesel_enum(storage_type = "db_enum")]
pub enum SuccessBasedRoutingConclusiveState {
// pc: payment connector
// sc: success based routing outcome/first connector
// status: payment status
//
// status = success && pc == sc
TruePositive,
// status = failed && pc == sc
FalsePositive,
// status = failed && pc != sc
TrueNegative,
// status = success && pc != sc
FalseNegative,
// status = processing
NonDeterministic,
}
/// Whether 3ds authentication is requested or not
#[derive(
Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema,
)]
pub enum External3dsAuthenticationRequest {
/// Request for 3ds authentication
Enable,
/// Skip 3ds authentication
#[default]
Skip,
}
/// Whether payment link is requested to be enabled or not for this transaction
#[derive(
Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema,
)]
pub enum EnablePaymentLinkRequest {
/// Request for enabling payment link
Enable,
/// Skip enabling payment link
#[default]
Skip,
}
#[derive(
Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema,
)]
pub enum MitExemptionRequest {
/// Request for applying MIT exemption
Apply,
/// Skip applying MIT exemption
#[default]
Skip,
}
/// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment.
#[derive(
Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum PresenceOfCustomerDuringPayment {
/// Customer is present during the payment. This is the default value
#[default]
Present,
/// Customer is absent during the payment
Absent,
}
impl From<ConnectorType> for TransactionType {
fn from(connector_type: ConnectorType) -> Self {
match connector_type {
#[cfg(feature = "payouts")]
ConnectorType::PayoutProcessor => Self::Payout,
_ => Self::Payment,
}
}
}
impl From<RefundStatus> for RelayStatus {
fn from(refund_status: RefundStatus) -> Self {
match refund_status {
RefundStatus::Failure | RefundStatus::TransactionFailure => Self::Failure,
RefundStatus::ManualReview | RefundStatus::Pending => Self::Pending,
RefundStatus::Success => Self::Success,
}
}
}
impl From<RelayStatus> for RefundStatus {
fn from(relay_status: RelayStatus) -> Self {
match relay_status {
RelayStatus::Failure => Self::Failure,
RelayStatus::Pending | RelayStatus::Created => Self::Pending,
RelayStatus::Success => Self::Success,
}
}
}
#[derive(
Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum TaxCalculationOverride {
/// Skip calling the external tax provider
#[default]
Skip,
/// Calculate tax by calling the external tax provider
Calculate,
}
impl From<Option<bool>> for TaxCalculationOverride {
fn from(value: Option<bool>) -> Self {
match value {
Some(true) => Self::Calculate,
_ => Self::Skip,
}
}
}
impl TaxCalculationOverride {
pub fn as_bool(self) -> bool {
match self {
Self::Skip => false,
Self::Calculate => true,
}
}
}
#[derive(
Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum SurchargeCalculationOverride {
/// Skip calculating surcharge
#[default]
Skip,
/// Calculate surcharge
Calculate,
}
impl From<Option<bool>> for SurchargeCalculationOverride {
fn from(value: Option<bool>) -> Self {
match value {
Some(true) => Self::Calculate,
_ => Self::Skip,
}
}
}
impl SurchargeCalculationOverride {
pub fn as_bool(self) -> bool {
match self {
Self::Skip => false,
Self::Calculate => true,
}
}
}
/// Connector Mandate Status
#[derive(
Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum ConnectorMandateStatus {
/// Indicates that the connector mandate is active and can be used for payments.
Active,
/// Indicates that the connector mandate is not active and hence cannot be used for payments.
Inactive,
}
/// Connector Mandate Status
#[derive(
Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum ConnectorTokenStatus {
/// Indicates that the connector mandate is active and can be used for payments.
Active,
/// Indicates that the connector mandate is not active and hence cannot be used for payments.
Inactive,
}
#[derive(
Clone,
Copy,
Debug,
strum::Display,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::EnumString,
ToSchema,
PartialOrd,
Ord,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ErrorCategory {
FrmDecline,
ProcessorDowntime,
ProcessorDeclineUnauthorized,
IssueWithPaymentMethod,
ProcessorDeclineIncorrectData,
HardDecline,
SoftDecline,
}
impl ErrorCategory {
pub fn should_perform_elimination_routing(self) -> bool {
match self {
Self::ProcessorDowntime | Self::ProcessorDeclineUnauthorized => true,
Self::IssueWithPaymentMethod
| Self::ProcessorDeclineIncorrectData
| Self::FrmDecline
| Self::HardDecline
| Self::SoftDecline => false,
}
}
}
#[derive(
Clone,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
Hash,
)]
pub enum PaymentChargeType {
#[serde(untagged)]
Stripe(StripeChargeType),
}
#[derive(
Clone,
Debug,
Default,
Hash,
Eq,
PartialEq,
ToSchema,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum StripeChargeType {
#[default]
Direct,
Destination,
}
/// Authentication Products
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum AuthenticationProduct {
ClickToPay,
}
/// Connector Access Method
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
ToSchema,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum HyperswitchConnectorCategory {
PaymentGateway,
AlternativePaymentMethod,
BankAcquirer,
PayoutProcessor,
AuthenticationProvider,
FraudAndRiskManagementProvider,
TaxCalculationProvider,
RevenueGrowthManagementPlatform,
}
/// Connector Integration Status
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
ToSchema,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum ConnectorIntegrationStatus {
/// Connector is integrated and live on production
Live,
/// Connector is integrated and fully tested on sandbox
Sandbox,
/// Connector is integrated and partially tested on sandbox
Beta,
/// Connector is integrated using the online documentation but not tested yet
Alpha,
}
/// The status of the feature
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
ToSchema,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum FeatureStatus {
NotSupported,
Supported,
}
/// The type of tokenization to use for the payment method
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
ToSchema,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum TokenizationType {
/// Create a single use token for the given payment method
/// The user might have to go through additional factor authentication when using the single use token if required by the payment method
SingleUse,
/// Create a multi use token for the given payment method
/// User will have to complete the additional factor authentication only once when creating the multi use token
/// This will create a mandate at the connector which can be used for recurring payments
MultiUse,
}
/// The network tokenization toggle, whether to enable or skip the network tokenization
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]
pub enum NetworkTokenizationToggle {
/// Enable network tokenization for the payment method
Enable,
/// Skip network tokenization for the payment method
Skip,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize, ToSchema)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GooglePayAuthMethod {
/// Contain pan data only
PanOnly,
/// Contain cryptogram data along with pan data
#[serde(rename = "CRYPTOGRAM_3DS")]
Cryptogram,
}
#[derive(
Clone,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[strum(serialize_all = "PascalCase")]
#[serde(rename_all = "PascalCase")]
pub enum AdyenSplitType {
/// Books split amount to the specified account.
BalanceAccount,
/// The aggregated amount of the interchange and scheme fees.
AcquiringFees,
/// The aggregated amount of all transaction fees.
PaymentFee,
/// The aggregated amount of Adyen's commission and markup fees.
AdyenFees,
/// The transaction fees due to Adyen under blended rates.
AdyenCommission,
/// The transaction fees due to Adyen under Interchange ++ pricing.
AdyenMarkup,
/// The fees paid to the issuer for each payment made with the card network.
Interchange,
/// The fees paid to the card scheme for using their network.
SchemeFee,
/// Your platform's commission on the payment (specified in amount), booked to your liable balance account.
Commission,
/// Allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods.
TopUp,
/// The value-added tax charged on the payment, booked to your platforms liable balance account.
Vat,
}
#[derive(
Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema, Default,
)]
#[serde(rename = "snake_case")]
pub enum PaymentConnectorTransmission {
/// Failed to call the payment connector
#[default]
ConnectorCallUnsuccessful,
/// Payment Connector call succeeded
ConnectorCallSucceeded,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum TriggeredBy {
/// Denotes payment attempt is been created by internal system.
#[default]
Internal,
/// Denotes payment attempt is been created by external system.
External,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum MitCategory {
/// A fixed purchase amount split into multiple scheduled payments until the total is paid.
Installment,
/// Merchant-initiated transaction using stored credentials, but not tied to a fixed schedule
Unscheduled,
/// Merchant-initiated payments that happen at regular intervals (usually the same amount each time).
Recurring,
/// A retried MIT after a previous transaction failed or was declined.
Resubmission,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ProcessTrackerStatus {
// Picked by the producer
Processing,
// State when the task is added
New,
// Send to retry
Pending,
// Picked by consumer
ProcessStarted,
// Finished by consumer
Finish,
// Review the task
Review,
}
#[derive(
serde::Serialize,
serde::Deserialize,
Clone,
Copy,
Debug,
PartialEq,
Eq,
strum::EnumString,
strum::Display,
)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
pub enum ProcessTrackerRunner {
PaymentsSyncWorkflow,
RefundWorkflowRouter,
DeleteTokenizeDataWorkflow,
ApiKeyExpiryWorkflow,
OutgoingWebhookRetryWorkflow,
AttachPayoutAccountWorkflow,
PaymentMethodStatusUpdateWorkflow,
PassiveRecoveryWorkflow,
ProcessDisputeWorkflow,
DisputeListWorkflow,
InvoiceSyncflow,
}
#[derive(Debug)]
pub enum CryptoPadding {
PKCS7,
ZeroPadding,
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum TokenizationFlag {
/// Token is active and can be used for payments
Enabled,
/// Token is inactive and cannot be used for payments
Disabled,
}
/// The type of token data to fetch for get-token endpoint
#[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum TokenDataType {
/// Fetch single use token for the given payment method
SingleUseToken,
/// Fetch multi use token for the given payment method
MultiUseToken,
/// Fetch network token for the given payment method
NetworkToken,
}
#[derive(
Clone,
Debug,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RoutingApproach {
SuccessRateExploitation,
SuccessRateExploration,
ContractBasedRouting,
DebitRouting,
RuleBasedRouting,
VolumeBasedRouting,
StraightThroughRouting,
#[default]
DefaultFallback,
#[serde(untagged)]
#[strum(default)]
Other(String),
}
impl RoutingApproach {
pub fn from_decision_engine_approach(approach: &str) -> Self {
match approach {
"SR_SELECTION_V3_ROUTING" => Self::SuccessRateExploitation,
"SR_V3_HEDGING" | "DEFAULT" => Self::SuccessRateExploration,
"NTW_BASED_ROUTING" => Self::DebitRouting,
_ => Self::DefaultFallback,
}
}
}
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
serde::Serialize,
serde::Deserialize,
ToSchema,
strum::Display,
strum::EnumString,
Hash,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
#[router_derive::diesel_enum(storage_type = "text")]
pub enum CallbackMapperIdType {
NetworkTokenRequestorReferenceID,
}
/// Payment Method Status
#[derive(
Clone,
Copy,
Debug,
PartialEq,
Eq,
Hash,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum VaultType {
/// Indicates that the payment method is stored in internal vault.
Internal,
/// Indicates that the payment method is stored in external vault.
External,
}
#[derive(
Clone,
Debug,
Copy,
Default,
Eq,
Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ExternalVaultEnabled {
Enable,
#[default]
Skip,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "UPPERCASE")]
pub enum GooglePayCardFundingSource {
Credit,
Debit,
Prepaid,
#[serde(other)]
Unknown,
}
impl From<IntentStatus> for InvoiceStatus {
fn from(value: IntentStatus) -> Self {
match value {
IntentStatus::Succeeded => Self::InvoicePaid,
IntentStatus::RequiresCapture
| IntentStatus::PartiallyCaptured
| IntentStatus::PartiallyCapturedAndCapturable
| IntentStatus::PartiallyAuthorizedAndRequiresCapture
| IntentStatus::Processing
| IntentStatus::RequiresCustomerAction
| IntentStatus::RequiresConfirmation
| IntentStatus::RequiresPaymentMethod => Self::PaymentPending,
IntentStatus::RequiresMerchantAction => Self::ManualReview,
IntentStatus::Cancelled | IntentStatus::CancelledPostCapture => Self::PaymentCanceled,
IntentStatus::Expired => Self::PaymentPendingTimeout,
IntentStatus::Failed | IntentStatus::Conflicted => Self::PaymentFailed,
}
}
}
| {
"crate": "common_enums",
"file": "crates/common_enums/src/enums.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 61,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_common_enums_-3525744911442222224 | clm | file | // Repository: hyperswitch
// Crate: common_enums
// File: crates/common_enums/src/enums/ui.rs
// Contains: 0 structs, 6 enums
use std::fmt;
use serde::{de::Visitor, Deserialize, Deserializer, Serialize};
use utoipa::ToSchema;
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
Serialize,
Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "lowercase")]
pub enum ElementPosition {
Left,
#[default]
#[serde(rename = "top left")]
TopLeft,
Top,
#[serde(rename = "top right")]
TopRight,
Right,
#[serde(rename = "bottom right")]
BottomRight,
Bottom,
#[serde(rename = "bottom left")]
BottomLeft,
Center,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, strum::Display, strum::EnumString, ToSchema)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
pub enum ElementSize {
Variants(SizeVariants),
Percentage(u32),
Pixels(u32),
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
Serialize,
Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum SizeVariants {
#[default]
Cover,
Contain,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
Serialize,
Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum PaymentLinkDetailsLayout {
#[default]
Layout1,
Layout2,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
Serialize,
Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum PaymentLinkSdkLabelType {
#[default]
Above,
Floating,
Never,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
Serialize,
Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum PaymentLinkShowSdkTerms {
Always,
#[default]
Auto,
Never,
}
impl<'de> Deserialize<'de> for ElementSize {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct ElementSizeVisitor;
impl Visitor<'_> for ElementSizeVisitor {
type Value = ElementSize;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a string with possible values - contain, cover or values in percentage or pixels. For eg: 48px or 50%")
}
fn visit_str<E>(self, value: &str) -> Result<ElementSize, E>
where
E: serde::de::Error,
{
if let Some(percent) = value.strip_suffix('%') {
percent
.parse::<u32>()
.map(ElementSize::Percentage)
.map_err(E::custom)
} else if let Some(px) = value.strip_suffix("px") {
px.parse::<u32>()
.map(ElementSize::Pixels)
.map_err(E::custom)
} else {
match value {
"cover" => Ok(ElementSize::Variants(SizeVariants::Cover)),
"contain" => Ok(ElementSize::Variants(SizeVariants::Contain)),
_ => Err(E::custom("invalid size variant")),
}
}
}
}
deserializer.deserialize_str(ElementSizeVisitor)
}
}
impl Serialize for ElementSize {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
match self {
Self::Variants(variant) => serializer.serialize_str(variant.to_string().as_str()),
Self::Pixels(pixel_count) => {
serializer.serialize_str(format!("{pixel_count}px").as_str())
}
Self::Percentage(pixel_count) => {
serializer.serialize_str(format!("{pixel_count}%").as_str())
}
}
}
}
| {
"crate": "common_enums",
"file": "crates/common_enums/src/enums/ui.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 6,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_common_enums_8283675988491467337 | clm | file | // Repository: hyperswitch
// Crate: common_enums
// File: crates/common_enums/src/enums/payments.rs
// Contains: 0 structs, 1 enums
use serde;
use utoipa::ToSchema;
#[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ProductType {
#[default]
Physical,
Digital,
Travel,
Ride,
Event,
Accommodation,
}
| {
"crate": "common_enums",
"file": "crates/common_enums/src/enums/payments.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_common_enums_-8033882872132226795 | clm | file | // Repository: hyperswitch
// Crate: common_enums
// File: crates/common_enums/src/enums/accounts.rs
// Contains: 0 structs, 4 enums
use serde;
use utoipa::ToSchema;
#[derive(
Copy,
Default,
Clone,
Debug,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
Hash,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum MerchantProductType {
#[default]
Orchestration,
Vault,
Recon,
Recovery,
CostObservability,
DynamicRouting,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum MerchantAccountType {
#[default]
Standard,
Platform,
Connected,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum OrganizationType {
#[default]
Standard,
Platform,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum MerchantAccountRequestType {
#[default]
Standard,
Connected,
}
| {
"crate": "common_enums",
"file": "crates/common_enums/src/enums/accounts.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 4,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_hyperswitch_constraint_graph_6668336401057465465 | clm | file | // Repository: hyperswitch
// Crate: hyperswitch_constraint_graph
// File: crates/hyperswitch_constraint_graph/src/error.rs
// Contains: 0 structs, 3 enums
use std::sync::{Arc, Weak};
use crate::types::{Metadata, NodeValue, Relation, RelationResolution, ValueNode};
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "type", content = "predecessor", rename_all = "snake_case")]
pub enum ValueTracePredecessor<V: ValueNode> {
Mandatory(Box<Weak<AnalysisTrace<V>>>),
OneOf(Vec<Weak<AnalysisTrace<V>>>),
}
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "type", content = "trace", rename_all = "snake_case")]
pub enum AnalysisTrace<V: ValueNode> {
Value {
value: NodeValue<V>,
relation: Relation,
predecessors: Option<ValueTracePredecessor<V>>,
info: Option<&'static str>,
metadata: Option<Arc<dyn Metadata>>,
},
AllAggregation {
unsatisfied: Vec<Weak<AnalysisTrace<V>>>,
info: Option<&'static str>,
metadata: Option<Arc<dyn Metadata>>,
},
AnyAggregation {
unsatisfied: Vec<Weak<AnalysisTrace<V>>>,
info: Option<&'static str>,
metadata: Option<Arc<dyn Metadata>>,
},
InAggregation {
expected: Vec<V>,
found: Option<V>,
relation: Relation,
info: Option<&'static str>,
metadata: Option<Arc<dyn Metadata>>,
},
Contradiction {
relation: RelationResolution,
},
}
#[derive(Debug, Clone, serde::Serialize, thiserror::Error)]
#[serde(tag = "type", content = "info", rename_all = "snake_case")]
pub enum GraphError<V: ValueNode> {
#[error("An edge was not found in the graph")]
EdgeNotFound,
#[error("Attempted to create a conflicting edge between two nodes")]
ConflictingEdgeCreated,
#[error("Cycle detected in graph")]
CycleDetected,
#[error("Domain wasn't found in the Graph")]
DomainNotFound,
#[error("Malformed Graph: {reason}")]
MalformedGraph { reason: String },
#[error("A node was not found in the graph")]
NodeNotFound,
#[error("A value node was not found: {0:#?}")]
ValueNodeNotFound(V),
#[error("No values provided for an 'in' aggregator node")]
NoInAggregatorValues,
#[error("Error during analysis: {0:#?}")]
AnalysisError(Weak<AnalysisTrace<V>>),
}
impl<V: ValueNode> GraphError<V> {
pub fn get_analysis_trace(self) -> Result<Weak<AnalysisTrace<V>>, Self> {
match self {
Self::AnalysisError(trace) => Ok(trace),
_ => Err(self),
}
}
}
| {
"crate": "hyperswitch_constraint_graph",
"file": "crates/hyperswitch_constraint_graph/src/error.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 3,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_currency_conversion_8510942061051265719 | clm | file | // Repository: hyperswitch
// Crate: currency_conversion
// File: crates/currency_conversion/src/error.rs
// Contains: 0 structs, 1 enums
#[derive(Debug, thiserror::Error, serde::Serialize)]
#[serde(tag = "type", content = "info", rename_all = "snake_case")]
pub enum CurrencyConversionError {
#[error("Currency Conversion isn't possible")]
DecimalMultiplicationFailed,
#[error("Currency not supported: '{0}'")]
ConversionNotSupported(String),
}
| {
"crate": "currency_conversion",
"file": "crates/currency_conversion/src/error.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_diesel_models_340566911855115603 | clm | file | // Repository: hyperswitch
// Crate: diesel_models
// File: crates/diesel_models/src/errors.rs
// Contains: 0 structs, 1 enums
#[derive(Copy, Clone, Debug, thiserror::Error)]
pub enum DatabaseError {
#[error("An error occurred when obtaining database connection")]
DatabaseConnectionError,
#[error("The requested resource was not found in the database")]
NotFound,
#[error("A unique constraint violation occurred")]
UniqueViolation,
#[error("No fields were provided to be updated")]
NoFieldsToUpdate,
#[error("An error occurred when generating typed SQL query")]
QueryGenerationFailed,
// InsertFailed,
#[error("An unknown error occurred")]
Others,
}
impl From<diesel::result::Error> for DatabaseError {
fn from(error: diesel::result::Error) -> Self {
match error {
diesel::result::Error::DatabaseError(
diesel::result::DatabaseErrorKind::UniqueViolation,
_,
) => Self::UniqueViolation,
diesel::result::Error::NotFound => Self::NotFound,
diesel::result::Error::QueryBuilderError(_) => Self::QueryGenerationFailed,
_ => Self::Others,
}
}
}
| {
"crate": "diesel_models",
"file": "crates/diesel_models/src/errors.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_diesel_models_-4832011483828889735 | clm | file | // Repository: hyperswitch
// Crate: diesel_models
// File: crates/diesel_models/src/query/generics.rs
// Contains: 0 structs, 1 enums
use std::fmt::Debug;
use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{
associations::HasTable,
debug_query,
dsl::{count_star, Find, IsNotNull, Limit},
helper_types::{Filter, IntoBoxed},
insertable::CanInsertInSingleQuery,
pg::{Pg, PgConnection},
query_builder::{
AsChangeset, AsQuery, DeleteStatement, InsertStatement, IntoUpdateTarget, QueryFragment,
QueryId, UpdateStatement,
},
query_dsl::{
methods::{BoxedDsl, FilterDsl, FindDsl, LimitDsl, OffsetDsl, OrderDsl, SelectDsl},
LoadQuery, RunQueryDsl,
},
result::Error as DieselError,
Expression, ExpressionMethods, Insertable, QueryDsl, QuerySource, Table,
};
use error_stack::{report, ResultExt};
use router_env::logger;
use crate::{errors, query::utils::GetPrimaryKey, PgPooledConn, StorageResult};
pub mod db_metrics {
#[derive(Debug)]
pub enum DatabaseOperation {
FindOne,
Filter,
Update,
Insert,
Delete,
DeleteWithResult,
UpdateWithResults,
UpdateOne,
Count,
}
#[inline]
pub async fn track_database_call<T, Fut, U>(future: Fut, operation: DatabaseOperation) -> U
where
Fut: std::future::Future<Output = U>,
{
let start = std::time::Instant::now();
let output = future.await;
let time_elapsed = start.elapsed();
let table_name = std::any::type_name::<T>().rsplit("::").nth(1);
let attributes = router_env::metric_attributes!(
("table", table_name.unwrap_or("undefined")),
("operation", format!("{:?}", operation))
);
crate::metrics::DATABASE_CALLS_COUNT.add(1, attributes);
crate::metrics::DATABASE_CALL_TIME.record(time_elapsed.as_secs_f64(), attributes);
output
}
}
use db_metrics::*;
pub async fn generic_insert<T, V, R>(conn: &PgPooledConn, values: V) -> StorageResult<R>
where
T: HasTable<Table = T> + Table + 'static + Debug,
V: Debug + Insertable<T>,
<T as QuerySource>::FromClause: QueryFragment<Pg> + Debug,
<V as Insertable<T>>::Values: CanInsertInSingleQuery<Pg> + QueryFragment<Pg> + 'static,
InsertStatement<T, <V as Insertable<T>>::Values>:
AsQuery + LoadQuery<'static, PgConnection, R> + Send,
R: Send + 'static,
{
let debug_values = format!("{values:?}");
let query = diesel::insert_into(<T as HasTable>::table()).values(values);
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
match track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Insert)
.await
{
Ok(value) => Ok(value),
Err(err) => match err {
DieselError::DatabaseError(diesel::result::DatabaseErrorKind::UniqueViolation, _) => {
Err(report!(err)).change_context(errors::DatabaseError::UniqueViolation)
}
_ => Err(report!(err)).change_context(errors::DatabaseError::Others),
},
}
.attach_printable_lazy(|| format!("Error while inserting {debug_values}"))
}
pub async fn generic_update<T, V, P>(
conn: &PgPooledConn,
predicate: P,
values: V,
) -> StorageResult<usize>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug,
Filter<T, P>: IntoUpdateTarget,
UpdateStatement<
<Filter<T, P> as HasTable>::Table,
<Filter<T, P> as IntoUpdateTarget>::WhereClause,
<V as AsChangeset>::Changeset,
>: AsQuery + QueryFragment<Pg> + QueryId + Send + 'static,
{
let debug_values = format!("{values:?}");
let query = diesel::update(<T as HasTable>::table().filter(predicate)).set(values);
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<T, _, _>(query.execute_async(conn), DatabaseOperation::Update)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable_lazy(|| format!("Error while updating {debug_values}"))
}
pub async fn generic_update_with_results<T, V, P, R>(
conn: &PgPooledConn,
predicate: P,
values: V,
) -> StorageResult<Vec<R>>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug + 'static,
Filter<T, P>: IntoUpdateTarget + 'static,
UpdateStatement<
<Filter<T, P> as HasTable>::Table,
<Filter<T, P> as IntoUpdateTarget>::WhereClause,
<V as AsChangeset>::Changeset,
>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + Clone,
R: Send + 'static,
// For cloning query (UpdateStatement)
<Filter<T, P> as HasTable>::Table: Clone,
<Filter<T, P> as IntoUpdateTarget>::WhereClause: Clone,
<V as AsChangeset>::Changeset: Clone,
<<Filter<T, P> as HasTable>::Table as QuerySource>::FromClause: Clone,
{
let debug_values = format!("{values:?}");
let query = diesel::update(<T as HasTable>::table().filter(predicate)).set(values);
match track_database_call::<T, _, _>(
query.to_owned().get_results_async(conn),
DatabaseOperation::UpdateWithResults,
)
.await
{
Ok(result) => {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
Ok(result)
}
Err(DieselError::QueryBuilderError(_)) => {
Err(report!(errors::DatabaseError::NoFieldsToUpdate))
.attach_printable_lazy(|| format!("Error while updating {debug_values}"))
}
Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound))
.attach_printable_lazy(|| format!("Error while updating {debug_values}")),
Err(error) => Err(error)
.change_context(errors::DatabaseError::Others)
.attach_printable_lazy(|| format!("Error while updating {debug_values}")),
}
}
pub async fn generic_update_with_unique_predicate_get_result<T, V, P, R>(
conn: &PgPooledConn,
predicate: P,
values: V,
) -> StorageResult<R>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug + 'static,
Filter<T, P>: IntoUpdateTarget + 'static,
UpdateStatement<
<Filter<T, P> as HasTable>::Table,
<Filter<T, P> as IntoUpdateTarget>::WhereClause,
<V as AsChangeset>::Changeset,
>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send,
R: Send + 'static,
// For cloning query (UpdateStatement)
<Filter<T, P> as HasTable>::Table: Clone,
<Filter<T, P> as IntoUpdateTarget>::WhereClause: Clone,
<V as AsChangeset>::Changeset: Clone,
<<Filter<T, P> as HasTable>::Table as QuerySource>::FromClause: Clone,
{
generic_update_with_results::<<T as HasTable>::Table, _, _, _>(conn, predicate, values)
.await
.map(|mut vec_r| {
if vec_r.is_empty() {
Err(errors::DatabaseError::NotFound)
} else if vec_r.len() != 1 {
Err(errors::DatabaseError::Others)
} else {
vec_r.pop().ok_or(errors::DatabaseError::Others)
}
.attach_printable("Maybe not queried using a unique key")
})?
}
pub async fn generic_update_by_id<T, V, Pk, R>(
conn: &PgPooledConn,
id: Pk,
values: V,
) -> StorageResult<R>
where
T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,
V: AsChangeset<Target = <Find<T, Pk> as HasTable>::Table> + Debug,
Find<T, Pk>: IntoUpdateTarget + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,
UpdateStatement<
<Find<T, Pk> as HasTable>::Table,
<Find<T, Pk> as IntoUpdateTarget>::WhereClause,
<V as AsChangeset>::Changeset,
>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,
Find<T, Pk>: LimitDsl,
Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,
R: Send + 'static,
Pk: Clone + Debug,
// For cloning query (UpdateStatement)
<Find<T, Pk> as HasTable>::Table: Clone,
<Find<T, Pk> as IntoUpdateTarget>::WhereClause: Clone,
<V as AsChangeset>::Changeset: Clone,
<<Find<T, Pk> as HasTable>::Table as QuerySource>::FromClause: Clone,
{
let debug_values = format!("{values:?}");
let query = diesel::update(<T as HasTable>::table().find(id.to_owned())).set(values);
match track_database_call::<T, _, _>(
query.to_owned().get_result_async(conn),
DatabaseOperation::UpdateOne,
)
.await
{
Ok(result) => {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
Ok(result)
}
Err(DieselError::QueryBuilderError(_)) => {
Err(report!(errors::DatabaseError::NoFieldsToUpdate))
.attach_printable_lazy(|| format!("Error while updating by ID {debug_values}"))
}
Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound))
.attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")),
Err(error) => Err(error)
.change_context(errors::DatabaseError::Others)
.attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")),
}
}
pub async fn generic_delete<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<bool>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: IntoUpdateTarget,
DeleteStatement<
<Filter<T, P> as HasTable>::Table,
<Filter<T, P> as IntoUpdateTarget>::WhereClause,
>: AsQuery + QueryFragment<Pg> + QueryId + Send + 'static,
{
let query = diesel::delete(<T as HasTable>::table().filter(predicate));
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<T, _, _>(query.execute_async(conn), DatabaseOperation::Delete)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting")
.and_then(|result| match result {
n if n > 0 => {
logger::debug!("{n} records deleted");
Ok(true)
}
0 => {
Err(report!(errors::DatabaseError::NotFound).attach_printable("No records deleted"))
}
_ => Ok(true), // n is usize, rustc requires this for exhaustive check
})
}
pub async fn generic_delete_one_with_result<T, P, R>(
conn: &PgPooledConn,
predicate: P,
) -> StorageResult<R>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: IntoUpdateTarget,
DeleteStatement<
<Filter<T, P> as HasTable>::Table,
<Filter<T, P> as IntoUpdateTarget>::WhereClause,
>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,
R: Send + Clone + 'static,
{
let query = diesel::delete(<T as HasTable>::table().filter(predicate));
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<T, _, _>(
query.get_results_async(conn),
DatabaseOperation::DeleteWithResult,
)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting")
.and_then(|result| {
result.first().cloned().ok_or_else(|| {
report!(errors::DatabaseError::NotFound)
.attach_printable("Object to be deleted does not exist")
})
})
}
async fn generic_find_by_id_core<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R>
where
T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,
Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,
Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,
Pk: Clone + Debug,
R: Send + 'static,
{
let query = <T as HasTable>::table().find(id.to_owned());
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
match track_database_call::<T, _, _>(query.first_async(conn), DatabaseOperation::FindOne).await
{
Ok(value) => Ok(value),
Err(err) => match err {
DieselError::NotFound => {
Err(report!(err)).change_context(errors::DatabaseError::NotFound)
}
_ => Err(report!(err)).change_context(errors::DatabaseError::Others),
},
}
.attach_printable_lazy(|| format!("Error finding record by primary key: {id:?}"))
}
pub async fn generic_find_by_id<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R>
where
T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,
Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,
Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,
Pk: Clone + Debug,
R: Send + 'static,
{
generic_find_by_id_core::<T, _, _>(conn, id).await
}
pub async fn generic_find_by_id_optional<T, Pk, R>(
conn: &PgPooledConn,
id: Pk,
) -> StorageResult<Option<R>>
where
T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,
<T as HasTable>::Table: FindDsl<Pk>,
Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,
Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,
Pk: Clone + Debug,
R: Send + 'static,
{
to_optional(generic_find_by_id_core::<T, _, _>(conn, id).await)
}
async fn generic_find_one_core<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,
R: Send + 'static,
{
let query = <T as HasTable>::table().filter(predicate);
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::FindOne)
.await
.map_err(|err| match err {
DieselError::NotFound => report!(err).change_context(errors::DatabaseError::NotFound),
_ => report!(err).change_context(errors::DatabaseError::Others),
})
.attach_printable("Error finding record by predicate")
}
pub async fn generic_find_one<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,
R: Send + 'static,
{
generic_find_one_core::<T, _, _>(conn, predicate).await
}
pub async fn generic_find_one_optional<T, P, R>(
conn: &PgPooledConn,
predicate: P,
) -> StorageResult<Option<R>>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,
R: Send + 'static,
{
to_optional(generic_find_one_core::<T, _, _>(conn, predicate).await)
}
pub(super) async fn generic_filter<T, P, O, R>(
conn: &PgPooledConn,
predicate: P,
limit: Option<i64>,
offset: Option<i64>,
order: Option<O>,
) -> StorageResult<Vec<R>>
where
T: HasTable<Table = T> + Table + BoxedDsl<'static, Pg> + GetPrimaryKey + 'static,
IntoBoxed<'static, T, Pg>: FilterDsl<P, Output = IntoBoxed<'static, T, Pg>>
+ FilterDsl<IsNotNull<T::PK>, Output = IntoBoxed<'static, T, Pg>>
+ LimitDsl<Output = IntoBoxed<'static, T, Pg>>
+ OffsetDsl<Output = IntoBoxed<'static, T, Pg>>
+ OrderDsl<O, Output = IntoBoxed<'static, T, Pg>>
+ LoadQuery<'static, PgConnection, R>
+ QueryFragment<Pg>
+ Send,
O: Expression,
R: Send + 'static,
{
let mut query = T::table().into_boxed();
query = query
.filter(predicate)
.filter(T::table().get_primary_key().is_not_null());
if let Some(limit) = limit {
query = query.limit(limit);
}
if let Some(offset) = offset {
query = query.offset(offset);
}
if let Some(order) = order {
query = query.order(order);
}
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<T, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering records by predicate")
}
pub async fn generic_count<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<usize>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + SelectDsl<count_star> + 'static,
Filter<T, P>: SelectDsl<count_star>,
diesel::dsl::Select<Filter<T, P>, count_star>:
LoadQuery<'static, PgConnection, i64> + QueryFragment<Pg> + Send + 'static,
{
let query = <T as HasTable>::table()
.filter(predicate)
.select(count_star());
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
let count_i64: i64 =
track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Count)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error counting records by predicate")?;
let count_usize = usize::try_from(count_i64).map_err(|_| {
report!(errors::DatabaseError::Others).attach_printable("Count value does not fit in usize")
})?;
Ok(count_usize)
}
fn to_optional<T>(arg: StorageResult<T>) -> StorageResult<Option<T>> {
match arg {
Ok(value) => Ok(Some(value)),
Err(err) => match err.current_context() {
errors::DatabaseError::NotFound => Ok(None),
_ => Err(err),
},
}
}
| {
"crate": "diesel_models",
"file": "crates/diesel_models/src/query/generics.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_scheduler_-2435782081737021017 | clm | file | // Repository: hyperswitch
// Crate: scheduler
// File: crates/scheduler/src/flow.rs
// Contains: 0 structs, 1 enums
#[derive(Copy, Clone, Debug, strum::Display, strum::EnumString)]
#[strum(serialize_all = "snake_case")]
pub enum SchedulerFlow {
Producer,
Consumer,
Cleaner,
}
| {
"crate": "scheduler",
"file": "crates/scheduler/src/flow.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_scheduler_-767246926535872741 | clm | file | // Repository: hyperswitch
// Crate: scheduler
// File: crates/scheduler/src/errors.rs
// Contains: 0 structs, 1 enums
pub use common_utils::errors::{ParsingError, ValidationError};
#[cfg(feature = "email")]
use external_services::email::EmailError;
use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
pub use redis_interface::errors::RedisError;
pub use storage_impl::errors::ApplicationError;
use storage_impl::errors::{RecoveryError, StorageError};
use crate::env::logger::{self, error};
#[derive(Debug, thiserror::Error)]
pub enum ProcessTrackerError {
#[error("An unexpected flow was specified")]
UnexpectedFlow,
#[error("Failed to serialize object")]
SerializationFailed,
#[error("Failed to deserialize object")]
DeserializationFailed,
#[error("Missing required field")]
MissingRequiredField,
#[error("Failed to insert process batch into stream")]
BatchInsertionFailed,
#[error("Failed to insert process into stream")]
ProcessInsertionFailed,
#[error("The process batch with the specified details was not found")]
BatchNotFound,
#[error("Failed to update process batch in stream")]
BatchUpdateFailed,
#[error("Failed to delete process batch from stream")]
BatchDeleteFailed,
#[error("An error occurred when trying to read process tracker configuration")]
ConfigurationError,
#[error("Failed to update process in database")]
ProcessUpdateFailed,
#[error("Failed to fetch processes from database")]
ProcessFetchingFailed,
#[error("Failed while fetching: {resource_name}")]
ResourceFetchingFailed { resource_name: String },
#[error("Failed while executing: {flow}")]
FlowExecutionError { flow: &'static str },
#[error("Not Implemented")]
NotImplemented,
#[error("Job not found")]
JobNotFound,
#[error("Received Error ApiResponseError")]
EApiErrorResponse,
#[error("Received Error ClientError")]
EClientError,
#[error("Received RecoveryError: {0:?}")]
ERecoveryError(error_stack::Report<RecoveryError>),
#[error("Received Error StorageError: {0:?}")]
EStorageError(error_stack::Report<StorageError>),
#[error("Received Error RedisError: {0:?}")]
ERedisError(error_stack::Report<RedisError>),
#[error("Received Error ParsingError: {0:?}")]
EParsingError(error_stack::Report<ParsingError>),
#[error("Validation Error Received: {0:?}")]
EValidationError(error_stack::Report<ValidationError>),
#[cfg(feature = "email")]
#[error("Received Error EmailError: {0:?}")]
EEmailError(error_stack::Report<EmailError>),
#[error("Type Conversion error")]
TypeConversionError,
#[error("Tenant not found")]
TenantNotFound,
}
#[macro_export]
macro_rules! error_to_process_tracker_error {
($($path: ident)::+ < $st: ident >, $($path2:ident)::* ($($inner_path2:ident)::+ <$st2:ident>) ) => {
impl From<$($path)::+ <$st>> for ProcessTrackerError {
fn from(err: $($path)::+ <$st> ) -> Self {
$($path2)::*(err)
}
}
};
($($path: ident)::+ <$($inner_path:ident)::+>, $($path2:ident)::* ($($inner_path2:ident)::+ <$st2:ident>) ) => {
impl<'a> From< $($path)::+ <$($inner_path)::+> > for ProcessTrackerError {
fn from(err: $($path)::+ <$($inner_path)::+> ) -> Self {
$($path2)::*(err)
}
}
};
}
pub trait PTError: Send + Sync + 'static {
fn to_pt_error(&self) -> ProcessTrackerError;
}
impl<T: PTError> From<T> for ProcessTrackerError {
fn from(value: T) -> Self {
value.to_pt_error()
}
}
impl PTError for ApiErrorResponse {
fn to_pt_error(&self) -> ProcessTrackerError {
ProcessTrackerError::EApiErrorResponse
}
}
impl<T: PTError + std::fmt::Debug + std::fmt::Display> From<error_stack::Report<T>>
for ProcessTrackerError
{
fn from(error: error_stack::Report<T>) -> Self {
logger::error!(?error);
error.current_context().to_pt_error()
}
}
error_to_process_tracker_error!(
error_stack::Report<StorageError>,
ProcessTrackerError::EStorageError(error_stack::Report<StorageError>)
);
error_to_process_tracker_error!(
error_stack::Report<RedisError>,
ProcessTrackerError::ERedisError(error_stack::Report<RedisError>)
);
error_to_process_tracker_error!(
error_stack::Report<ParsingError>,
ProcessTrackerError::EParsingError(error_stack::Report<ParsingError>)
);
error_to_process_tracker_error!(
error_stack::Report<ValidationError>,
ProcessTrackerError::EValidationError(error_stack::Report<ValidationError>)
);
#[cfg(feature = "email")]
error_to_process_tracker_error!(
error_stack::Report<EmailError>,
ProcessTrackerError::EEmailError(error_stack::Report<EmailError>)
);
error_to_process_tracker_error!(
error_stack::Report<RecoveryError>,
ProcessTrackerError::ERecoveryError(error_stack::Report<RecoveryError>)
);
| {
"crate": "scheduler",
"file": "crates/scheduler/src/errors.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_openapi_-1190732652523198522 | clm | file | // Repository: hyperswitch
// Crate: openapi
// File: crates/openapi/src/routes/payments.rs
// Contains: 0 structs, 1 enums
/// Payments - Create
///
/// Creates a payment resource, which represents a customer's intent to pay.
/// This endpoint is the starting point for various payment flows:
///
#[utoipa::path(
post,
path = "/payments",
request_body(
content = PaymentsCreateRequest,
examples(
(
"01. Create a payment with minimal fields" = (
value = json!({"amount": 6540,"currency": "USD"})
)
),
(
"02. Create a payment with customer details and metadata" = (
value = json!({
"amount": 6540,
"currency": "USD",
"payment_id": "abcdefghijklmnopqrstuvwxyz",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"phone": "9123456789",
"email": "john@example.com"
},
"description": "Its my first payment request",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "some-value",
"udf2": "some-value"
}
})
)
),
(
"03. Create a 3DS payment" = (
value = json!({
"amount": 6540,
"currency": "USD",
"authentication_type": "three_ds"
})
)
),
(
"04. Create a manual capture payment (basic)" = (
value = json!({
"amount": 6540,
"currency": "USD",
"capture_method": "manual"
})
)
),
(
"05. Create a setup mandate payment" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer123",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"setup_future_usage": "off_session",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"single_use": {
"amount": 6540,
"currency": "USD"
}
}
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
}
})
)
),
(
"06. Create a recurring payment with mandate_id" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer",
"authentication_type": "no_three_ds",
"mandate_id": "{{mandate_id}}",
"off_session": true
})
)
),
(
"07. Create a payment and save the card" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer123",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"setup_future_usage": "off_session"
})
)
),
(
"08. Create a payment using an already saved card's token" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"client_secret": "{{client_secret}}",
"payment_method": "card",
"payment_token": "{{payment_token}}",
"card_cvc": "123"
})
)
),
(
"09. Create a payment with billing details" = (
value = json!({
"amount": 6540,
"currency": "USD",
"customer": {
"id": "cus_abcdefgh"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+91"
}
}
})
)
),
(
"10. Create a Stripe Split Payments CIT call" = (
value = json!({
"amount": 200,
"currency": "USD",
"profile_id": "pro_abcdefghijklmnop",
"confirm": true,
"capture_method": "automatic",
"amount_to_capture": 200,
"customer_id": "StripeCustomer123",
"setup_future_usage": "off_session",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"authentication_type": "no_three_ds",
"return_url": "https://hyperswitch.io",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "09",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9999999999",
"country_code": "+91"
}
},
"split_payments": {
"stripe_split_payment": {
"charge_type": "direct",
"application_fees": 100,
"transfer_account_id": "acct_123456789"
}
}
})
)
),
(
"11. Create a Stripe Split Payments MIT call" = (
value = json!({
"amount": 200,
"currency": "USD",
"profile_id": "pro_abcdefghijklmnop",
"customer_id": "StripeCustomer123",
"description": "Subsequent Mandate Test Payment (MIT from New CIT Demo)",
"confirm": true,
"off_session": true,
"recurring_details": {
"type": "payment_method_id",
"data": "pm_123456789"
},
"split_payments": {
"stripe_split_payment": {
"charge_type": "direct",
"application_fees": 11,
"transfer_account_id": "acct_123456789"
}
}
})
)
),
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsCreateResponseOpenApi,
examples(
("01. Response for minimal payment creation (requires payment method)" = (
value = json!({
"payment_id": "pay_syxxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"client_secret": "pay_syxxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:00:00Z",
"amount_capturable": 6540,
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:15:00Z"
})
)),
("02. Response for payment with customer details (requires payment method)" = (
value = json!({
"payment_id": "pay_custmeta_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"customer_id": "cus_abcdefgh",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"email": "john@example.com",
"phone": "9123456789"
},
"description": "Its my first payment request",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "some-value",
"udf2": "some-value"
},
"client_secret": "pay_custmeta_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:05:00Z",
"ephemeral_key": {
"customer_id": "cus_abcdefgh",
"secret": "epk_ephemeralxxxxxxxxxxxx"
},
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:20:00Z"
})
)),
("03. Response for 3DS payment creation (requires payment method)" = (
value = json!({
"payment_id": "pay_3ds_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"authentication_type": "three_ds",
"client_secret": "pay_3ds_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:10:00Z",
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:25:00Z"
})
)),
("04. Response for basic manual capture payment (requires payment method)" = (
value = json!({
"payment_id": "pay_manualcap_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"capture_method": "manual",
"client_secret": "pay_manualcap_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:15:00Z",
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:30:00Z"
})
)),
("05. Response for successful setup mandate payment" = (
value = json!({
"payment_id": "pay_mandatesetup_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_capturable": 0,
"amount_received": 6540,
"connector": "fauxpay",
"customer_id": "StripeCustomer123",
"mandate_id": "man_xxxxxxxxxxxx",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" }
},
"mandate_type": { "single_use": { "amount": 6540, "currency": "USD" } }
},
"setup_future_usage": "on_session",
"payment_method": "card",
"payment_method_data": {
"card": { "last4": "4242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }
},
"authentication_type": "no_three_ds",
"client_secret": "pay_mandatesetup_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:20:00Z",
"ephemeral_key": { "customer_id": "StripeCustomer123", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"merchant_connector_id": "mca_mcaconnectorxxxx",
"connector_transaction_id": "txn_connectortransidxxxx"
})
)),
("06. Response for successful recurring payment with mandate_id" = (
value = json!({
"payment_id": "pay_recurring_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_capturable": 0,
"amount_received": 6540,
"connector": "fauxpay",
"customer_id": "StripeCustomer",
"mandate_id": "{{mandate_id}}",
"off_session": true,
"payment_method": "card",
"authentication_type": "no_three_ds",
"client_secret": "pay_recurring_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:22:00Z",
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"merchant_connector_id": "mca_mcaconnectorxxxx",
"connector_transaction_id": "txn_connectortransidxxxx"
})
)),
("07. Response for successful payment with card saved" = (
value = json!({
"payment_id": "pay_savecard_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_capturable": 0,
"amount_received": 6540,
"connector": "fauxpay",
"customer_id": "StripeCustomer123",
"setup_future_usage": "on_session",
"payment_method": "card",
"payment_method_data": {
"card": { "last4": "4242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }
},
"authentication_type": "no_three_ds",
"client_secret": "pay_savecard_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:25:00Z",
"ephemeral_key": { "customer_id": "StripeCustomer123", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"merchant_connector_id": "mca_mcaconnectorxxxx",
"connector_transaction_id": "txn_connectortransidxxxx",
"payment_token": null // Assuming payment_token is for subsequent use, not in this response.
})
)),
("08. Response for successful payment using saved card token" = (
value = json!({
"payment_id": "pay_token_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_capturable": 0,
"amount_received": 6540,
"connector": "fauxpay",
"payment_method": "card",
"payment_token": "{{payment_token}}",
"client_secret": "pay_token_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:27:00Z",
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"merchant_connector_id": "mca_mcaconnectorxxxx",
"connector_transaction_id": "txn_connectortransidxxxx"
})
)),
("09. Response for payment with billing details (requires payment method)" = (
value = json!({
"payment_id": "pay_manualbill_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"customer_id": "cus_abcdefgh",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"email": "john@example.com",
"phone": "9123456789"
},
"billing": {
"address": {
"line1": "1467", "line2": "Harrison Street", "city": "San Fransico",
"state": "California", "zip": "94122", "country": "US",
"first_name": "joseph", "last_name": "Doe"
},
"phone": { "number": "9123456789", "country_code": "+91" }
},
"client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:30:00Z",
"ephemeral_key": { "customer_id": "cus_abcdefgh", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:45:00Z"
})
)),
("10. Response for the CIT call for Stripe Split Payments" = (
value = json!({
"payment_id": "pay_manualbill_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 200,
"currency": "USD",
"customer_id": "cus_abcdefgh",
"payment_method_id": "pm_123456789",
"connector_mandate_id": "pm_abcdefgh",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"email": "john@example.com",
"phone": "9123456789"
},
"billing": {
"address": {
"line1": "1467", "line2": "Harrison Street", "city": "San Fransico",
"state": "California", "zip": "94122", "country": "US",
"first_name": "joseph", "last_name": "Doe"
},
"phone": { "number": "9123456789", "country_code": "+91" }
},
"client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:30:00Z",
"ephemeral_key": { "customer_id": "cus_abcdefgh", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:45:00Z"
})
)),
("11. Response for the MIT call for Stripe Split Payments" = (
value = json!({
"payment_id": "pay_manualbill_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 200,
"currency": "USD",
"customer_id": "cus_abcdefgh",
"payment_method_id": "pm_123456789",
"connector_mandate_id": "pm_abcdefgh",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"email": "john@example.com",
"phone": "9123456789"
},
"billing": {
"address": {
"line1": "1467", "line2": "Harrison Street", "city": "San Fransico",
"state": "California", "zip": "94122", "country": "US",
"first_name": "joseph", "last_name": "Doe"
},
"phone": { "number": "9123456789", "country_code": "+91" }
},
"client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:30:00Z",
"ephemeral_key": { "customer_id": "cus_abcdefgh", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:45:00Z"
})
))
)
),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi),
),
tag = "Payments",
operation_id = "Create a Payment",
security(("api_key" = [])),
)]
pub fn payments_create() {}
/// Payments - Retrieve
///
/// Retrieves a Payment. This API can also be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/payments/{payment_id}",
params(
("payment_id" = String, Path, description = "The identifier for payment"),
("force_sync" = Option<bool>, Query, description = "Decider to enable or disable the connector call for retrieve request"),
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("expand_attempts" = Option<bool>, Query, description = "If enabled provides list of attempts linked to payment intent"),
("expand_captures" = Option<bool>, Query, description = "If enabled provides list of captures linked to latest attempt"),
),
responses(
(status = 200, description = "Gets the payment with final status", body = PaymentsResponse),
(status = 404, description = "No payment found")
),
tag = "Payments",
operation_id = "Retrieve a Payment",
security(("api_key" = []), ("publishable_key" = []))
)]
pub fn payments_retrieve() {}
/// Payments - Update
///
/// To update the properties of a *PaymentIntent* object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created
#[utoipa::path(
post,
path = "/payments/{payment_id}",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body(
content = PaymentsUpdateRequest,
examples(
(
"Update the payment amount" = (
value = json!({
"amount": 7654,
}
)
)
),
(
"Update the shipping address" = (
value = json!(
{
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+91"
}
},
}
)
)
)
)
),
responses(
(status = 200, description = "Payment updated", body = PaymentsCreateResponseOpenApi),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Update a Payment",
security(("api_key" = []), ("publishable_key" = []))
)]
pub fn payments_update() {}
/// Payments - Confirm
///
/// Confirms a payment intent that was previously created with `confirm: false`. This action attempts to authorize the payment with the payment processor.
///
/// Expected status transitions after confirmation:
/// - `succeeded`: If authorization is successful and `capture_method` is `automatic`.
/// - `requires_capture`: If authorization is successful and `capture_method` is `manual`.
/// - `failed`: If authorization fails.
#[utoipa::path(
post,
path = "/payments/{payment_id}/confirm",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body(
content = PaymentsConfirmRequest,
examples(
(
"Confirm a payment with payment method data" = (
value = json!({
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
}
}
)
)
)
)
),
responses(
(status = 200, description = "Payment confirmed", body = PaymentsCreateResponseOpenApi),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Confirm a Payment",
security(("api_key" = []), ("publishable_key" = []))
)]
pub fn payments_confirm() {}
/// Payments - Capture
///
/// Captures the funds for a previously authorized payment intent where `capture_method` was set to `manual` and the payment is in a `requires_capture` state.
///
/// Upon successful capture, the payment status usually transitions to `succeeded`.
/// The `amount_to_capture` can be specified in the request body; it must be less than or equal to the payment's `amount_capturable`. If omitted, the full capturable amount is captured.
///
/// A payment must be in a capturable state (e.g., `requires_capture`). Attempting to capture an already `succeeded` (and fully captured) payment or one in an invalid state will lead to an error.
///
#[utoipa::path(
post,
path = "/payments/{payment_id}/capture",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body (
content = PaymentsCaptureRequest,
examples(
(
"Capture the full amount" = (
value = json!({})
)
),
(
"Capture partial amount" = (
value = json!({"amount_to_capture": 654})
)
),
)
),
responses(
(status = 200, description = "Payment captured", body = PaymentsResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Capture a Payment",
security(("api_key" = []))
)]
pub fn payments_capture() {}
#[cfg(feature = "v1")]
/// Payments - Session token
///
/// Creates a session object or a session token for wallets like Apple Pay, Google Pay, etc. These tokens are used by Hyperswitch's SDK to initiate these wallets' SDK.
#[utoipa::path(
post,
path = "/payments/session_tokens",
request_body=PaymentsSessionRequest,
responses(
(status = 200, description = "Payment session object created or session token was retrieved from wallets", body = PaymentsSessionResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create Session tokens for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_connector_session() {}
#[cfg(feature = "v2")]
/// Payments - Session token
///
/// Creates a session object or a session token for wallets like Apple Pay, Google Pay, etc. These tokens are used by Hyperswitch's SDK to initiate these wallets' SDK.
#[utoipa::path(
post,
path = "/v2/payments/{payment_id}/create-external-sdk-tokens",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body=PaymentsSessionRequest,
responses(
(status = 200, description = "Payment session object created or session token was retrieved from wallets", body = PaymentsSessionResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create V2 Session tokens for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_connector_session() {}
/// Payments - Cancel
///
/// A Payment could can be cancelled when it is in one of these statuses: `requires_payment_method`, `requires_capture`, `requires_confirmation`, `requires_customer_action`.
#[utoipa::path(
post,
path = "/payments/{payment_id}/cancel",
request_body (
content = PaymentsCancelRequest,
examples(
(
"Cancel the payment with minimal fields" = (
value = json!({})
)
),
(
"Cancel the payment with cancellation reason" = (
value = json!({"cancellation_reason": "requested_by_customer"})
)
),
)
),
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Payment canceled"),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Cancel a Payment",
security(("api_key" = []))
)]
pub fn payments_cancel() {}
/// Payments - Cancel Post Capture
///
/// A Payment could can be cancelled when it is in one of these statuses: `succeeded`, `partially_captured`, `partially_captured_and_capturable`.
#[utoipa::path(
post,
path = "/payments/{payment_id}/cancel_post_capture",
request_body (
content = PaymentsCancelPostCaptureRequest,
examples(
(
"Cancel the payment post capture with minimal fields" = (
value = json!({})
)
),
(
"Cancel the payment post capture with cancellation reason" = (
value = json!({"cancellation_reason": "requested_by_customer"})
)
),
)
),
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Payment canceled post capture"),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Cancel a Payment Post Capture",
security(("api_key" = []))
)]
pub fn payments_cancel_post_capture() {}
/// Payments - List
///
/// To list the *payments*
#[cfg(feature = "v1")]
#[utoipa::path(
get,
path = "/payments/list",
params(
("customer_id" = Option<String>, Query, description = "The identifier for the customer"),
("starting_after" = Option<String>, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
("ending_before" = Option<String>, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
("limit" = Option<i64>, Query, description = "Limit on the number of objects to return"),
("created" = Option<PrimitiveDateTime>, Query, description = "The time at which payment is created"),
("created_lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the payment created time"),
("created_gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the payment created time"),
("created_lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the payment created time"),
("created_gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the payment created time")
),
responses(
(status = 200, description = "Successfully retrieved a payment list", body = Vec<PaymentListResponse>),
(status = 404, description = "No payments found")
),
tag = "Payments",
operation_id = "List all Payments",
security(("api_key" = []))
)]
pub fn payments_list() {}
/// Profile level Payments - List
///
/// To list the payments
#[utoipa::path(
get,
path = "/payments/list",
params(
("customer_id" = String, Query, description = "The identifier for the customer"),
("starting_after" = String, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
("ending_before" = String, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
("limit" = i64, Query, description = "Limit on the number of objects to return"),
("created" = PrimitiveDateTime, Query, description = "The time at which payment is created"),
("created_lt" = PrimitiveDateTime, Query, description = "Time less than the payment created time"),
("created_gt" = PrimitiveDateTime, Query, description = "Time greater than the payment created time"),
("created_lte" = PrimitiveDateTime, Query, description = "Time less than or equals to the payment created time"),
("created_gte" = PrimitiveDateTime, Query, description = "Time greater than or equals to the payment created time")
),
responses(
(status = 200, description = "Received payment list"),
(status = 404, description = "No payments found")
),
tag = "Payments",
operation_id = "List all Payments for the Profile",
security(("api_key" = []))
)]
pub async fn profile_payments_list() {}
/// Payments - Incremental Authorization
///
/// Authorized amount for a payment can be incremented if it is in status: requires_capture
#[utoipa::path(
post,
path = "/payments/{payment_id}/incremental_authorization",
request_body=PaymentsIncrementalAuthorizationRequest,
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Payment authorized amount incremented", body = PaymentsResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Increment authorized amount for a Payment",
security(("api_key" = []))
)]
pub fn payments_incremental_authorization() {}
/// Payments - Extended Authorization
///
/// Extended authorization is available for payments currently in the `requires_capture` status
/// Call this endpoint to increase the authorization validity period
#[utoipa::path(
post,
path = "/payments/{payment_id}/extend_authorization",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Extended authorization for the payment"),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Extend authorization period for a Payment",
security(("api_key" = []))
)]
pub fn payments_extend_authorization() {}
/// Payments - External 3DS Authentication
///
/// External 3DS Authentication is performed and returns the AuthenticationResponse
#[utoipa::path(
post,
path = "/payments/{payment_id}/3ds/authentication",
request_body=PaymentsExternalAuthenticationRequest,
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Authentication created", body = PaymentsExternalAuthenticationResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Initiate external authentication for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_external_authentication() {}
/// Payments - Complete Authorize
#[utoipa::path(
post,
path = "/payments/{payment_id}/complete_authorize",
request_body=PaymentsCompleteAuthorizeRequest,
params(
("payment_id" =String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Payments Complete Authorize Success", body = PaymentsResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Complete Authorize a Payment",
security(("publishable_key" = []))
)]
pub fn payments_complete_authorize() {}
/// Dynamic Tax Calculation
#[utoipa::path(
post,
path = "/payments/{payment_id}/calculate_tax",
request_body=PaymentsDynamicTaxCalculationRequest,
responses(
(status = 200, description = "Tax Calculation is done", body = PaymentsDynamicTaxCalculationResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create Tax Calculation for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_dynamic_tax_calculation() {}
/// Payments - Post Session Tokens
#[utoipa::path(
post,
path = "/payments/{payment_id}/post_session_tokens",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body=PaymentsPostSessionTokensRequest,
responses(
(status = 200, description = "Post Session Token is done", body = PaymentsPostSessionTokensResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create Post Session Tokens for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_post_session_tokens() {}
/// Payments - Update Metadata
#[utoipa::path(
post,
path = "/payments/{payment_id}/update_metadata",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body=PaymentsUpdateMetadataRequest,
responses(
(status = 200, description = "Metadata updated successfully", body = PaymentsUpdateMetadataResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Update Metadata for a Payment",
security(("api_key" = []))
)]
pub fn payments_update_metadata() {}
/// Payments - Submit Eligibility Data
#[utoipa::path(
post,
path = "/payments/{payment_id}/eligibility",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body=PaymentsEligibilityRequest,
responses(
(status = 200, description = "Eligbility submit is successful", body = PaymentsEligibilityResponse),
(status = 400, description = "Bad Request", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Submit Eligibility data for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_submit_eligibility() {}
/// Payments - Create Intent
///
/// **Creates a payment intent object when amount_details are passed.**
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the first call, and use the 'client secret' returned in this API along with your 'publishable key' to make subsequent API calls from your client.
#[utoipa::path(
post,
path = "/v2/payments/create-intent",
request_body(
content = PaymentsCreateIntentRequest,
examples(
(
"Create a payment intent with minimal fields" = (
value = json!({"amount_details": {"order_amount": 6540, "currency": "USD"}})
)
),
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsIntentResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create a Payment Intent",
security(("api_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payments_create_intent() {}
/// Payments - Get Intent
///
/// **Get a payment intent object when id is passed in path**
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the call.
#[utoipa::path(
get,
path = "/v2/payments/{id}/get-intent",
params (("id" = String, Path, description = "The unique identifier for the Payment Intent")),
responses(
(status = 200, description = "Payment Intent", body = PaymentsIntentResponse),
(status = 404, description = "Payment Intent not found")
),
tag = "Payments",
operation_id = "Get the Payment Intent details",
security(("api_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payments_get_intent() {}
/// Payments - Update Intent
///
/// **Update a payment intent object**
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the call.
#[utoipa::path(
put,
path = "/v2/payments/{id}/update-intent",
params (("id" = String, Path, description = "The unique identifier for the Payment Intent"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
),
),
request_body(
content = PaymentsUpdateIntentRequest,
examples(
(
"Update a payment intent with minimal fields" = (
value = json!({"amount_details": {"order_amount": 6540, "currency": "USD"}})
)
),
),
),
responses(
(status = 200, description = "Payment Intent Updated", body = PaymentsIntentResponse),
(status = 404, description = "Payment Intent Not Found")
),
tag = "Payments",
operation_id = "Update a Payment Intent",
security(("api_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payments_update_intent() {}
/// Payments - Confirm Intent
///
/// **Confirms a payment intent object with the payment method data**
///
/// .
#[utoipa::path(
post,
path = "/v2/payments/{id}/confirm-intent",
params (("id" = String, Path, description = "The unique identifier for the Payment Intent"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
)
),
request_body(
content = PaymentsConfirmIntentRequest,
examples(
(
"Confirm the payment intent with card details" = (
value = json!({
"payment_method_type": "card",
"payment_method_subtype": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
})
)
),
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Confirm Payment Intent",
security(("publishable_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payments_confirm_intent() {}
/// Payments - Get
///
/// Retrieves a Payment. This API can also be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/v2/payments/{id}",
params(
("id" = String, Path, description = "The global payment id"),
("force_sync" = ForceSync, Query, description = "A boolean to indicate whether to force sync the payment status. Value can be true or false")
),
responses(
(status = 200, description = "Gets the payment with final status", body = PaymentsResponse),
(status = 404, description = "No payment found with the given id")
),
tag = "Payments",
operation_id = "Retrieve a Payment",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub fn payment_status() {}
/// Payments - Create and Confirm Intent
///
/// **Creates and confirms a payment intent object when the amount and payment method information are passed.**
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the call.
#[utoipa::path(
post,
path = "/v2/payments",
params (
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
)
),
request_body(
content = PaymentsRequest,
examples(
(
"Create and confirm the payment intent with amount and card details" = (
value = json!({
"amount_details": {
"order_amount": 6540,
"currency": "USD"
},
"payment_method_type": "card",
"payment_method_subtype": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
})
)
),
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create and Confirm Payment Intent",
security(("api_key" = [])),
)]
pub fn payments_create_and_confirm_intent() {}
#[derive(utoipa::ToSchema)]
#[schema(rename_all = "lowercase")]
pub(crate) enum ForceSync {
/// Force sync with the connector / processor to update the status
True,
/// Do not force sync with the connector / processor. Get the status which is available in the database
False,
}
/// Payments - Payment Methods List
///
/// List the payment methods eligible for a payment. This endpoint also returns the saved payment methods for the customer when the customer_id is passed when creating the payment
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payments/{id}/payment-methods",
params(
("id" = String, Path, description = "The global payment id"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
),
),
responses(
(status = 200, description = "Get the payment methods", body = PaymentMethodListResponseForPayments),
(status = 404, description = "No payment found with the given id")
),
tag = "Payments",
operation_id = "Retrieve Payment methods for a Payment",
security(("publishable_key" = []))
)]
pub fn list_payment_methods() {}
/// Payments - List
///
/// To list the *payments*
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payments/list",
params(api_models::payments::PaymentListConstraints),
responses(
(status = 200, description = "Successfully retrieved a payment list", body = PaymentListResponse),
(status = 404, description = "No payments found")
),
tag = "Payments",
operation_id = "List all Payments",
security(("api_key" = []), ("jwt_key" = []))
)]
pub fn payments_list() {}
/// Payments - Gift Card Balance Check
///
/// Check the balance of the provided gift card. This endpoint also returns whether the gift card balance is enough to cover the entire amount or another payment method is needed
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payments/{id}/check-gift-card-balance",
params(
("id" = String, Path, description = "The global payment id"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
),
),
request_body(
content = PaymentsGiftCardBalanceCheckRequest,
),
responses(
(status = 200, description = "Get the Gift Card Balance", body = GiftCardBalanceCheckResponse),
),
tag = "Payments",
operation_id = "Retrieve Gift Card Balance",
security(("publishable_key" = []))
)]
pub fn payment_check_gift_card_balance() {}
| {
"crate": "openapi",
"file": "crates/openapi/src/routes/payments.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_drainer_6634885038594302405 | clm | file | // Repository: hyperswitch
// Crate: drainer
// File: crates/drainer/src/errors.rs
// Contains: 0 structs, 2 enums
use redis_interface as redis;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum DrainerError {
#[error("Error in parsing config : {0}")]
ConfigParsingError(String),
#[error("Error during redis operation : {0:?}")]
RedisError(error_stack::Report<redis::errors::RedisError>),
#[error("Application configuration error: {0}")]
ConfigurationError(config::ConfigError),
#[error("Error while configuring signals: {0}")]
SignalError(String),
#[error("Error while parsing data from the stream: {0:?}")]
ParsingError(error_stack::Report<common_utils::errors::ParsingError>),
#[error("Unexpected error occurred: {0}")]
UnexpectedError(String),
#[error("I/O: {0}")]
IoError(std::io::Error),
}
#[derive(Debug, Error, Clone, serde::Serialize)]
pub enum HealthCheckError {
#[error("Database health check is failing with error: {message}")]
DbError { message: String },
#[error("Redis health check is failing with error: {message}")]
RedisError { message: String },
}
impl From<std::io::Error> for DrainerError {
fn from(err: std::io::Error) -> Self {
Self::IoError(err)
}
}
pub type DrainerResult<T> = error_stack::Result<T, DrainerError>;
impl From<config::ConfigError> for DrainerError {
fn from(err: config::ConfigError) -> Self {
Self::ConfigurationError(err)
}
}
impl From<error_stack::Report<redis::errors::RedisError>> for DrainerError {
fn from(err: error_stack::Report<redis::errors::RedisError>) -> Self {
Self::RedisError(err)
}
}
impl actix_web::ResponseError for HealthCheckError {
fn status_code(&self) -> reqwest::StatusCode {
use reqwest::StatusCode;
match self {
Self::DbError { .. } | Self::RedisError { .. } => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
| {
"crate": "drainer",
"file": "crates/drainer/src/errors.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_derive_-7148286678125937667 | clm | file | // Repository: hyperswitch
// Crate: router_derive
// File: crates/router_derive/src/macros/diesel.rs
// Contains: 0 structs, 2 enums
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote, ToTokens};
use syn::{parse::Parse, Data, DeriveInput, ItemEnum};
use crate::macros::helpers;
pub(crate) fn diesel_enum_text_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
match &ast.data {
Data::Enum(_) => (),
_ => return Err(helpers::non_enum_error()),
};
Ok(quote! {
#[automatically_derived]
impl #impl_generics ::diesel::serialize::ToSql<::diesel::sql_types::Text, ::diesel::pg::Pg> for #name #ty_generics
#where_clause
{
fn to_sql<'b>(&'b self, out: &mut ::diesel::serialize::Output<'b, '_, ::diesel::pg::Pg>) -> ::diesel::serialize::Result {
use ::std::io::Write;
out.write_all(self.to_string().as_bytes())?;
Ok(::diesel::serialize::IsNull::No)
}
}
#[automatically_derived]
impl #impl_generics ::diesel::deserialize::FromSql<::diesel::sql_types::Text, ::diesel::pg::Pg> for #name #ty_generics
#where_clause
{
fn from_sql(value: ::diesel::pg::PgValue) -> diesel::deserialize::Result<Self> {
use ::core::str::FromStr;
Self::from_str(::core::str::from_utf8(value.as_bytes())?)
.map_err(|_| "Unrecognized enum variant".into())
}
}
})
}
pub(crate) fn diesel_enum_db_enum_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
match &ast.data {
Data::Enum(_) => (),
_ => return Err(helpers::non_enum_error()),
};
let struct_name = format_ident!("Db{name}");
let type_name = format!("{name}");
Ok(quote! {
#[derive(::core::clone::Clone, ::core::marker::Copy, ::core::fmt::Debug, ::diesel::QueryId, ::diesel::SqlType)]
#[diesel(postgres_type(name = #type_name))]
pub struct #struct_name;
#[automatically_derived]
impl #impl_generics ::diesel::serialize::ToSql<#struct_name, ::diesel::pg::Pg> for #name #ty_generics
#where_clause
{
fn to_sql<'b>(&'b self, out: &mut ::diesel::serialize::Output<'b, '_, ::diesel::pg::Pg>) -> ::diesel::serialize::Result {
use ::std::io::Write;
out.write_all(self.to_string().as_bytes())?;
Ok(::diesel::serialize::IsNull::No)
}
}
#[automatically_derived]
impl #impl_generics ::diesel::deserialize::FromSql<#struct_name, ::diesel::pg::Pg> for #name #ty_generics
#where_clause
{
fn from_sql(value: ::diesel::pg::PgValue) -> diesel::deserialize::Result<Self> {
use ::core::str::FromStr;
Self::from_str(::core::str::from_utf8(value.as_bytes())?)
.map_err(|_| "Unrecognized enum variant".into())
}
}
})
}
mod diesel_keyword {
use syn::custom_keyword;
custom_keyword!(storage_type);
custom_keyword!(db_enum);
custom_keyword!(text);
}
#[derive(Debug, strum::EnumString, strum::EnumIter, strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum StorageType {
/// Store the Enum as Text value in the database
Text,
/// Store the Enum as Enum in the database. This requires a corresponding enum to be created
/// in the database with the same name
DbEnum,
}
#[derive(Debug)]
pub enum DieselEnumMeta {
StorageTypeEnum {
keyword: diesel_keyword::storage_type,
value: StorageType,
},
}
impl Parse for StorageType {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let text = input.parse::<syn::LitStr>()?;
let value = text.value();
value.as_str().parse().map_err(|_| {
syn::Error::new_spanned(
&text,
format!(
"Unexpected value for storage_type: `{value}`. Possible values are `{}`",
helpers::get_possible_values_for_enum::<Self>()
),
)
})
}
}
impl DieselEnumMeta {
pub fn get_storage_type(&self) -> &StorageType {
match self {
Self::StorageTypeEnum { value, .. } => value,
}
}
}
impl Parse for DieselEnumMeta {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let lookahead = input.lookahead1();
if lookahead.peek(diesel_keyword::storage_type) {
let keyword = input.parse()?;
input.parse::<syn::Token![=]>()?;
let value = input.parse()?;
Ok(Self::StorageTypeEnum { keyword, value })
} else {
Err(lookahead.error())
}
}
}
impl ToTokens for DieselEnumMeta {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::StorageTypeEnum { keyword, .. } => keyword.to_tokens(tokens),
}
}
}
trait DieselDeriveInputExt {
/// Get all the error metadata associated with an enum.
fn get_metadata(&self) -> syn::Result<Vec<DieselEnumMeta>>;
}
impl DieselDeriveInputExt for DeriveInput {
fn get_metadata(&self) -> syn::Result<Vec<DieselEnumMeta>> {
helpers::get_metadata_inner("storage_type", &self.attrs)
}
}
pub(crate) fn diesel_enum_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let storage_type = ast.get_metadata()?;
match storage_type
.first()
.ok_or(syn::Error::new(
Span::call_site(),
"Storage type must be specified",
))?
.get_storage_type()
{
StorageType::Text => diesel_enum_text_derive_inner(ast),
StorageType::DbEnum => diesel_enum_db_enum_derive_inner(ast),
}
}
/// Based on the storage type, derive appropriate diesel traits
/// This will add the appropriate #[diesel(sql_type)]
/// Since the `FromSql` and `ToSql` have to be derived for all the enums, this will add the
/// `DieselEnum` derive trait.
pub(crate) fn diesel_enum_attribute_macro(
diesel_enum_meta: DieselEnumMeta,
item: &ItemEnum,
) -> syn::Result<TokenStream> {
let diesel_derives =
quote!(#[derive(diesel::AsExpression, diesel::FromSqlRow, router_derive::DieselEnum) ]);
match diesel_enum_meta {
DieselEnumMeta::StorageTypeEnum {
value: storage_type,
..
} => match storage_type {
StorageType::Text => Ok(quote! {
#diesel_derives
#[diesel(sql_type = ::diesel::sql_types::Text)]
#[storage_type(storage_type = "text")]
#item
}),
StorageType::DbEnum => {
let name = &item.ident;
let type_name = format_ident!("Db{name}");
Ok(quote! {
#diesel_derives
#[diesel(sql_type = #type_name)]
#[storage_type(storage_type= "db_enum")]
#item
})
}
},
}
}
| {
"crate": "router_derive",
"file": "crates/router_derive/src/macros/diesel.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_derive_-1817949785604775204 | clm | file | // Repository: hyperswitch
// Crate: router_derive
// File: crates/router_derive/src/macros/to_encryptable.rs
// Contains: 0 structs, 1 enums
use std::iter::Iterator;
use quote::{format_ident, quote};
use syn::{parse::Parse, punctuated::Punctuated, token::Comma, Field, Ident, Type as SynType};
use crate::macros::{helpers::get_struct_fields, misc::get_field_type};
pub struct FieldMeta {
_meta_type: Ident,
pub value: Ident,
}
impl Parse for FieldMeta {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let _meta_type: Ident = input.parse()?;
input.parse::<syn::Token![=]>()?;
let value: Ident = input.parse()?;
Ok(Self { _meta_type, value })
}
}
impl quote::ToTokens for FieldMeta {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
self.value.to_tokens(tokens);
}
}
fn get_encryption_ty_meta(field: &Field) -> Option<FieldMeta> {
let attrs = &field.attrs;
attrs
.iter()
.flat_map(|s| s.parse_args::<FieldMeta>())
.find(|s| s._meta_type.eq("ty"))
}
fn get_inner_type(path: &syn::TypePath) -> syn::Result<syn::TypePath> {
path.path
.segments
.last()
.and_then(|segment| match &segment.arguments {
syn::PathArguments::AngleBracketed(args) => args.args.first(),
_ => None,
})
.and_then(|arg| match arg {
syn::GenericArgument::Type(SynType::Path(path)) => Some(path.clone()),
_ => None,
})
.ok_or_else(|| {
syn::Error::new(
proc_macro2::Span::call_site(),
"Only path fields are supported",
)
})
}
/// This function returns the inner most type recursively
/// For example:
///
/// In the case of `Encryptable<Secret<String>>> this returns String
fn get_inner_most_type(ty: SynType) -> syn::Result<Ident> {
fn get_inner_type_recursive(path: syn::TypePath) -> syn::Result<syn::TypePath> {
match get_inner_type(&path) {
Ok(inner_path) => get_inner_type_recursive(inner_path),
Err(_) => Ok(path),
}
}
match ty {
SynType::Path(path) => {
let inner_path = get_inner_type_recursive(path)?;
inner_path
.path
.segments
.last()
.map(|last_segment| last_segment.ident.to_owned())
.ok_or_else(|| {
syn::Error::new(
proc_macro2::Span::call_site(),
"At least one ident must be specified",
)
})
}
_ => Err(syn::Error::new(
proc_macro2::Span::call_site(),
"Only path fields are supported",
)),
}
}
/// This returns the field which implement #[encrypt] attribute
fn get_encryptable_fields(fields: Punctuated<Field, Comma>) -> Vec<Field> {
fields
.into_iter()
.filter(|field| {
field
.attrs
.iter()
.any(|attr| attr.path().is_ident("encrypt"))
})
.collect()
}
/// This function returns the inner most type of a field
fn get_field_and_inner_types(fields: &[Field]) -> Vec<(Field, Ident)> {
fields
.iter()
.flat_map(|field| {
get_inner_most_type(field.ty.clone()).map(|field_name| (field.to_owned(), field_name))
})
.collect()
}
/// The type of the struct for which the batch encryption/decryption needs to be implemented
#[derive(PartialEq, Copy, Clone)]
enum StructType {
Encrypted,
Decrypted,
DecryptedUpdate,
FromRequest,
Updated,
}
impl StructType {
/// Generates the fields for temporary structs which consists of the fields that should be
/// encrypted/decrypted
fn generate_struct_fields(self, fields: &[(Field, Ident)]) -> Vec<proc_macro2::TokenStream> {
fields
.iter()
.map(|(field, inner_ty)| {
let provided_ty = get_encryption_ty_meta(field);
let is_option = get_field_type(field.ty.clone())
.map(|f| f.eq("Option"))
.unwrap_or_default();
let ident = &field.ident;
let inner_ty = if let Some(ref ty) = provided_ty {
&ty.value
} else {
inner_ty
};
match (self, is_option) {
(Self::Encrypted, true) => quote! { pub #ident: Option<Encryption> },
(Self::Encrypted, false) => quote! { pub #ident: Encryption },
(Self::Decrypted, true) => {
quote! { pub #ident: Option<Encryptable<Secret<#inner_ty>>> }
}
(Self::Decrypted, false) => {
quote! { pub #ident: Encryptable<Secret<#inner_ty>> }
}
(Self::DecryptedUpdate, _) => {
quote! { pub #ident: Option<Encryptable<Secret<#inner_ty>>> }
}
(Self::FromRequest, true) => {
quote! { pub #ident: Option<Secret<#inner_ty>> }
}
(Self::FromRequest, false) => quote! { pub #ident: Secret<#inner_ty> },
(Self::Updated, _) => quote! { pub #ident: Option<Secret<#inner_ty>> },
}
})
.collect()
}
/// Generates the ToEncryptable trait implementation
fn generate_impls(
self,
gen1: proc_macro2::TokenStream,
gen2: proc_macro2::TokenStream,
gen3: proc_macro2::TokenStream,
impl_st: proc_macro2::TokenStream,
inner: &[Field],
) -> proc_macro2::TokenStream {
let map_length = inner.len();
let to_encryptable_impl = inner.iter().flat_map(|field| {
get_field_type(field.ty.clone()).map(|field_ty| {
let is_option = field_ty.eq("Option");
let field_ident = &field.ident;
let field_ident_string = field_ident.as_ref().map(|s| s.to_string());
if is_option || self == Self::Updated {
quote! { self.#field_ident.map(|s| map.insert(#field_ident_string.to_string(), s)) }
} else {
quote! { map.insert(#field_ident_string.to_string(), self.#field_ident) }
}
})
});
let from_encryptable_impl = inner.iter().flat_map(|field| {
get_field_type(field.ty.clone()).map(|field_ty| {
let is_option = field_ty.eq("Option");
let field_ident = &field.ident;
let field_ident_string = field_ident.as_ref().map(|s| s.to_string());
if is_option || self == Self::Updated {
quote! { #field_ident: map.remove(#field_ident_string) }
} else {
quote! {
#field_ident: map.remove(#field_ident_string).ok_or(
error_stack::report!(common_utils::errors::ParsingError::EncodeError(
"Unable to convert from HashMap",
))
)?
}
}
})
});
quote! {
impl ToEncryptable<#gen1, #gen2, #gen3> for #impl_st {
fn to_encryptable(self) -> FxHashMap<String, #gen3> {
let mut map = FxHashMap::with_capacity_and_hasher(#map_length, Default::default());
#(#to_encryptable_impl;)*
map
}
fn from_encryptable(
mut map: FxHashMap<String, Encryptable<#gen2>>,
) -> CustomResult<#gen1, common_utils::errors::ParsingError> {
Ok(#gen1 {
#(#from_encryptable_impl,)*
})
}
}
}
}
}
/// This function generates the temporary struct and ToEncryptable impls for the temporary structs
fn generate_to_encryptable(
struct_name: Ident,
fields: Vec<Field>,
) -> syn::Result<proc_macro2::TokenStream> {
let struct_types = [
// The first two are to be used as return types we do not need to implement ToEncryptable
// on it
("Decrypted", StructType::Decrypted),
("DecryptedUpdate", StructType::DecryptedUpdate),
("FromRequestEncryptable", StructType::FromRequest),
("Encrypted", StructType::Encrypted),
("UpdateEncryptable", StructType::Updated),
];
let inner_types = get_field_and_inner_types(&fields);
let inner_type = inner_types.first().ok_or_else(|| {
syn::Error::new(
proc_macro2::Span::call_site(),
"Please use the macro with attribute #[encrypt] on the fields you want to encrypt",
)
})?;
let provided_ty = get_encryption_ty_meta(&inner_type.0)
.map(|ty| ty.value.clone())
.unwrap_or(inner_type.1.clone());
let structs = struct_types.iter().map(|(prefix, struct_type)| {
let name = format_ident!("{}{}", prefix, struct_name);
let temp_fields = struct_type.generate_struct_fields(&inner_types);
quote! {
pub struct #name {
#(#temp_fields,)*
}
}
});
// These implementations shouldn't be implemented Decrypted and DecryptedUpdate temp structs
// So skip the first two entries in the list
let impls = struct_types
.iter()
.skip(2)
.map(|(prefix, struct_type)| {
let name = format_ident!("{}{}", prefix, struct_name);
let impl_block = if *struct_type != StructType::DecryptedUpdate
|| *struct_type != StructType::Decrypted
{
let (gen1, gen2, gen3) = match struct_type {
StructType::FromRequest => {
let decrypted_name = format_ident!("Decrypted{}", struct_name);
(
quote! { #decrypted_name },
quote! { Secret<#provided_ty> },
quote! { Secret<#provided_ty> },
)
}
StructType::Encrypted => {
let decrypted_name = format_ident!("Decrypted{}", struct_name);
(
quote! { #decrypted_name },
quote! { Secret<#provided_ty> },
quote! { Encryption },
)
}
StructType::Updated => {
let decrypted_update_name = format_ident!("DecryptedUpdate{}", struct_name);
(
quote! { #decrypted_update_name },
quote! { Secret<#provided_ty> },
quote! { Secret<#provided_ty> },
)
}
//Unreachable statement
_ => (quote! {}, quote! {}, quote! {}),
};
struct_type.generate_impls(gen1, gen2, gen3, quote! { #name }, &fields)
} else {
quote! {}
};
Ok(quote! {
#impl_block
})
})
.collect::<syn::Result<Vec<_>>>()?;
Ok(quote! {
#(#structs)*
#(#impls)*
})
}
pub fn derive_to_encryption(
input: syn::DeriveInput,
) -> Result<proc_macro2::TokenStream, syn::Error> {
let struct_name = input.ident;
let fields = get_encryptable_fields(get_struct_fields(input.data)?);
generate_to_encryptable(struct_name, fields)
}
| {
"crate": "router_derive",
"file": "crates/router_derive/src/macros/to_encryptable.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_euclid_8956762860232696812 | clm | file | // Repository: hyperswitch
// Crate: euclid
// File: crates/euclid/src/enums.rs
// Contains: 0 structs, 6 enums
pub use common_enums::{
AuthenticationType, CaptureMethod, CardNetwork, Country, CountryAlpha2, Currency,
FutureUsage as SetupFutureUsage, PaymentMethod, PaymentMethodType, RoutableConnectors,
};
use strum::VariantNames;
pub trait CollectVariants {
fn variants<T: FromIterator<String>>() -> T;
}
macro_rules! collect_variants {
($the_enum:ident) => {
impl $crate::enums::CollectVariants for $the_enum {
fn variants<T>() -> T
where
T: FromIterator<String>,
{
Self::VARIANTS.iter().map(|s| String::from(*s)).collect()
}
}
};
}
pub(crate) use collect_variants;
collect_variants!(PaymentMethod);
collect_variants!(RoutableConnectors);
collect_variants!(PaymentType);
collect_variants!(MandateType);
collect_variants!(MandateAcceptanceType);
collect_variants!(PaymentMethodType);
collect_variants!(CardNetwork);
collect_variants!(AuthenticationType);
collect_variants!(CaptureMethod);
collect_variants!(Currency);
collect_variants!(Country);
collect_variants!(SetupFutureUsage);
#[cfg(feature = "payouts")]
collect_variants!(PayoutType);
#[cfg(feature = "payouts")]
collect_variants!(PayoutBankTransferType);
#[cfg(feature = "payouts")]
collect_variants!(PayoutWalletType);
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum MandateAcceptanceType {
Online,
Offline,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PaymentType {
SetupMandate,
NonMandate,
NewMandate,
UpdateMandate,
PptMandate,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum MandateType {
SingleUse,
MultiUse,
}
#[cfg(feature = "payouts")]
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PayoutBankTransferType {
Ach,
Bacs,
SepaBankTransfer,
}
#[cfg(feature = "payouts")]
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PayoutWalletType {
Paypal,
}
#[cfg(feature = "payouts")]
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PayoutType {
Card,
BankTransfer,
Wallet,
BankRedirect,
}
| {
"crate": "euclid",
"file": "crates/euclid/src/enums.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 6,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_euclid_7555801554616867701 | clm | file | // Repository: hyperswitch
// Crate: euclid
// File: crates/euclid/src/frontend/dir/enums.rs
// Contains: 0 structs, 18 enums
use strum::VariantNames;
use utoipa::ToSchema;
use crate::enums::collect_variants;
pub use crate::enums::{
AuthenticationType, CaptureMethod, CardNetwork, Country, Country as BusinessCountry,
Country as BillingCountry, Country as IssuerCountry, Country as AcquirerCountry, CountryAlpha2,
Currency as PaymentCurrency, MandateAcceptanceType, MandateType, PaymentMethod, PaymentType,
RoutableConnectors, SetupFutureUsage,
};
#[cfg(feature = "payouts")]
pub use crate::enums::{PayoutBankTransferType, PayoutType, PayoutWalletType};
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CardType {
Credit,
Debit,
#[cfg(feature = "v2")]
Card,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PayLaterType {
Affirm,
AfterpayClearpay,
Alma,
Klarna,
PayBright,
Walley,
Flexiti,
Atome,
Breadpay,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum WalletType {
Bluecode,
GooglePay,
AmazonPay,
Skrill,
Paysera,
ApplePay,
Paypal,
AliPay,
AliPayHk,
MbWay,
MobilePay,
WeChatPay,
SamsungPay,
GoPay,
KakaoPay,
Twint,
Gcash,
Vipps,
Momo,
Dana,
TouchNGo,
Swish,
Cashapp,
Venmo,
Mifinity,
Paze,
RevolutPay,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum VoucherType {
Boleto,
Efecty,
PagoEfectivo,
RedCompra,
RedPagos,
Alfamart,
Indomaret,
SevenEleven,
Lawson,
MiniStop,
FamilyMart,
Seicomart,
PayEasy,
Oxxo,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum BankRedirectType {
Bizum,
Giropay,
Ideal,
Sofort,
Eft,
Eps,
BancontactCard,
Blik,
Interac,
LocalBankRedirect,
OnlineBankingCzechRepublic,
OnlineBankingFinland,
OnlineBankingPoland,
OnlineBankingSlovakia,
OnlineBankingFpx,
OnlineBankingThailand,
OpenBankingUk,
Przelewy24,
Trustly,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum OpenBankingType {
OpenBankingPIS,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum BankTransferType {
Multibanco,
Ach,
SepaBankTransfer,
Bacs,
BcaBankTransfer,
BniVa,
BriVa,
CimbVa,
DanamonVa,
MandiriVa,
PermataBankTransfer,
Pix,
Pse,
LocalBankTransfer,
InstantBankTransfer,
InstantBankTransferFinland,
InstantBankTransferPoland,
IndonesianBankTransfer,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum GiftCardType {
PaySafeCard,
Givex,
BhnCardNetwork,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CardRedirectType {
Benefit,
Knet,
MomoAtm,
CardRedirect,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum MobilePaymentType {
DirectCarrierBilling,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CryptoType {
CryptoCurrency,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RealTimePaymentType {
Fps,
DuitNow,
PromptPay,
VietQr,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum UpiType {
UpiCollect,
UpiIntent,
UpiQr,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum BankDebitType {
Ach,
Sepa,
SepaGuarenteedDebit,
Bacs,
Becs,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RewardType {
ClassicReward,
Evoucher,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CustomerDevicePlatform {
Web,
Android,
Ios,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CustomerDeviceType {
Mobile,
Tablet,
Desktop,
GamingConsole,
}
// Common display sizes for different device types
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CustomerDeviceDisplaySize {
// Mobile sizes
Size320x568, // iPhone SE
Size375x667, // iPhone 8
Size390x844, // iPhone 12/13
Size414x896, // iPhone XR/11
Size428x926, // iPhone 12/13 Pro Max
// Tablet sizes
Size768x1024, // iPad
Size834x1112, // iPad Pro 10.5
Size834x1194, // iPad Pro 11
Size1024x1366, // iPad Pro 12.9
// Desktop sizes
Size1280x720, // HD
Size1366x768, // Common laptop
Size1440x900, // MacBook Air
Size1920x1080, // Full HD
Size2560x1440, // QHD
Size3840x2160, // 4K
// Custom sizes
Size500x600,
Size600x400,
// Other common sizes
Size360x640, // Common Android
Size412x915, // Pixel 6
Size800x1280, // Common Android tablet
}
collect_variants!(CardType);
collect_variants!(PayLaterType);
collect_variants!(WalletType);
collect_variants!(BankRedirectType);
collect_variants!(BankDebitType);
collect_variants!(CryptoType);
collect_variants!(RewardType);
collect_variants!(RealTimePaymentType);
collect_variants!(UpiType);
collect_variants!(VoucherType);
collect_variants!(GiftCardType);
collect_variants!(BankTransferType);
collect_variants!(CardRedirectType);
collect_variants!(OpenBankingType);
collect_variants!(MobilePaymentType);
collect_variants!(CustomerDeviceType);
collect_variants!(CustomerDevicePlatform);
collect_variants!(CustomerDeviceDisplaySize);
| {
"crate": "euclid",
"file": "crates/euclid/src/frontend/dir/enums.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 18,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_euclid_6709686572329007545 | clm | file | // Repository: hyperswitch
// Crate: euclid
// File: crates/euclid/src/backend/vir_interpreter/types.rs
// Contains: 0 structs, 1 enums
use rustc_hash::{FxHashMap, FxHashSet};
use crate::{
backend::inputs::BackendInput,
dssa,
types::{self, EuclidKey, EuclidValue, MetadataValue, NumValueRefinement, StrValue},
};
#[derive(Debug, Clone, serde::Serialize, thiserror::Error)]
pub enum VirInterpreterError {
#[error("Error when lowering the program: {0:?}")]
LoweringError(dssa::types::AnalysisError),
}
pub struct Context {
atomic_values: FxHashSet<EuclidValue>,
numeric_values: FxHashMap<EuclidKey, EuclidValue>,
}
impl Context {
pub fn check_presence(&self, value: &EuclidValue) -> bool {
let key = value.get_key();
match key.key_type() {
types::DataType::MetadataValue => self.atomic_values.contains(value),
types::DataType::StrValue => self.atomic_values.contains(value),
types::DataType::EnumVariant => self.atomic_values.contains(value),
types::DataType::Number => {
let ctx_num_value = self
.numeric_values
.get(&key)
.and_then(|value| value.get_num_value());
value.get_num_value().zip(ctx_num_value).is_some_and(
|(program_value, ctx_value)| {
let program_num = program_value.number;
let ctx_num = ctx_value.number;
match &program_value.refinement {
None => program_num == ctx_num,
Some(NumValueRefinement::NotEqual) => ctx_num != program_num,
Some(NumValueRefinement::GreaterThan) => ctx_num > program_num,
Some(NumValueRefinement::GreaterThanEqual) => ctx_num >= program_num,
Some(NumValueRefinement::LessThanEqual) => ctx_num <= program_num,
Some(NumValueRefinement::LessThan) => ctx_num < program_num,
}
},
)
}
}
}
pub fn from_input(input: BackendInput) -> Self {
let payment = input.payment;
let payment_method = input.payment_method;
let meta_data = input.metadata;
let acquirer_data = input.acquirer_data;
let customer_device_data = input.customer_device_data;
let issuer_data = input.issuer_data;
let payment_mandate = input.mandate;
let mut enum_values: FxHashSet<EuclidValue> =
FxHashSet::from_iter([EuclidValue::PaymentCurrency(payment.currency)]);
if let Some(pm) = payment_method.payment_method {
enum_values.insert(EuclidValue::PaymentMethod(pm));
}
if let Some(pmt) = payment_method.payment_method_type {
enum_values.insert(EuclidValue::PaymentMethodType(pmt));
}
if let Some(met) = meta_data {
for (key, value) in met.into_iter() {
enum_values.insert(EuclidValue::Metadata(MetadataValue { key, value }));
}
}
if let Some(card_network) = payment_method.card_network {
enum_values.insert(EuclidValue::CardNetwork(card_network));
}
if let Some(at) = payment.authentication_type {
enum_values.insert(EuclidValue::AuthenticationType(at));
}
if let Some(capture_method) = payment.capture_method {
enum_values.insert(EuclidValue::CaptureMethod(capture_method));
}
if let Some(country) = payment.business_country {
enum_values.insert(EuclidValue::BusinessCountry(country));
}
if let Some(country) = payment.billing_country {
enum_values.insert(EuclidValue::BillingCountry(country));
}
if let Some(card_bin) = payment.card_bin {
enum_values.insert(EuclidValue::CardBin(StrValue { value: card_bin }));
}
if let Some(business_label) = payment.business_label {
enum_values.insert(EuclidValue::BusinessLabel(StrValue {
value: business_label,
}));
}
if let Some(setup_future_usage) = payment.setup_future_usage {
enum_values.insert(EuclidValue::SetupFutureUsage(setup_future_usage));
}
if let Some(payment_type) = payment_mandate.payment_type {
enum_values.insert(EuclidValue::PaymentType(payment_type));
}
if let Some(mandate_type) = payment_mandate.mandate_type {
enum_values.insert(EuclidValue::MandateType(mandate_type));
}
if let Some(mandate_acceptance_type) = payment_mandate.mandate_acceptance_type {
enum_values.insert(EuclidValue::MandateAcceptanceType(mandate_acceptance_type));
}
if let Some(acquirer_country) = acquirer_data.clone().and_then(|data| data.country) {
enum_values.insert(EuclidValue::AcquirerCountry(acquirer_country));
}
// Handle customer device data
if let Some(device_data) = customer_device_data {
if let Some(platform) = device_data.platform {
enum_values.insert(EuclidValue::CustomerDevicePlatform(platform));
}
if let Some(device_type) = device_data.device_type {
enum_values.insert(EuclidValue::CustomerDeviceType(device_type));
}
if let Some(display_size) = device_data.display_size {
enum_values.insert(EuclidValue::CustomerDeviceDisplaySize(display_size));
}
}
// Handle issuer data
if let Some(issuer) = issuer_data {
if let Some(name) = issuer.name {
enum_values.insert(EuclidValue::IssuerName(StrValue { value: name }));
}
if let Some(country) = issuer.country {
enum_values.insert(EuclidValue::IssuerCountry(country));
}
}
let numeric_values: FxHashMap<EuclidKey, EuclidValue> = FxHashMap::from_iter([(
EuclidKey::PaymentAmount,
EuclidValue::PaymentAmount(types::NumValue {
number: payment.amount,
refinement: None,
}),
)]);
Self {
atomic_values: enum_values,
numeric_values,
}
}
}
| {
"crate": "euclid",
"file": "crates/euclid/src/backend/vir_interpreter/types.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_env_6966696243055166451 | clm | file | // Repository: hyperswitch
// Crate: router_env
// File: crates/router_env/src/env.rs
// Contains: 0 structs, 1 enums
//! Information about the current environment.
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
/// Environment variables accessed by the application. This module aims to be the source of truth
/// containing all environment variable that the application accesses.
pub mod vars {
/// Parent directory where `Cargo.toml` is stored.
pub const CARGO_MANIFEST_DIR: &str = "CARGO_MANIFEST_DIR";
/// Environment variable that sets development/sandbox/production environment.
pub const RUN_ENV: &str = "RUN_ENV";
/// Directory of config TOML files. Default is `config`.
pub const CONFIG_DIR: &str = "CONFIG_DIR";
}
/// Current environment.
#[derive(
Debug, Default, Deserialize, Serialize, Clone, Copy, strum::Display, strum::EnumString,
)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum Env {
/// Development environment.
#[default]
Development,
/// Sandbox environment.
Sandbox,
/// Production environment.
Production,
}
/// Name of current environment. Either "development", "sandbox" or "production".
pub fn which() -> Env {
#[cfg(debug_assertions)]
let default_env = Env::Development;
#[cfg(not(debug_assertions))]
let default_env = Env::Production;
std::env::var(vars::RUN_ENV).map_or_else(|_| default_env, |v| v.parse().unwrap_or(default_env))
}
/// Three letter (lowercase) prefix corresponding to the current environment.
/// Either `dev`, `snd` or `prd`.
pub fn prefix_for_env() -> &'static str {
match which() {
Env::Development => "dev",
Env::Sandbox => "snd",
Env::Production => "prd",
}
}
/// Path to the root directory of the cargo workspace.
/// It is recommended that this be used by the application as the base path to build other paths
/// such as configuration and logs directories.
pub fn workspace_path() -> PathBuf {
if let Ok(manifest_dir) = std::env::var(vars::CARGO_MANIFEST_DIR) {
let mut path = PathBuf::from(manifest_dir);
path.pop();
path.pop();
path
} else {
PathBuf::from(".")
}
}
/// Version of the crate containing the following information:
///
/// - The latest git tag. If tags are not present in the repository, the short commit hash is used
/// instead.
/// - Short hash of the latest git commit.
/// - Timestamp of the latest git commit.
///
/// Example: `0.1.0-abcd012-2038-01-19T03:14:08Z`.
#[cfg(feature = "vergen")]
#[macro_export]
macro_rules! version {
() => {
concat!(
env!("VERGEN_GIT_DESCRIBE"),
"-",
env!("VERGEN_GIT_SHA"),
"-",
env!("VERGEN_GIT_COMMIT_TIMESTAMP"),
)
};
}
/// A string uniquely identifying the application build.
///
/// Consists of a combination of:
/// - Version defined in the crate file
/// - Timestamp of commit
/// - Hash of the commit
/// - Version of rust compiler
/// - Target triple
///
/// Example: `0.1.0-f5f383e-2022-09-04T11:39:37Z-1.63.0-x86_64-unknown-linux-gnu`
#[cfg(feature = "vergen")]
#[macro_export]
macro_rules! build {
() => {
concat!(
env!("CARGO_PKG_VERSION"),
"-",
env!("VERGEN_GIT_SHA"),
"-",
env!("VERGEN_GIT_COMMIT_TIMESTAMP"),
"-",
env!("VERGEN_RUSTC_SEMVER"),
"-",
$crate::profile!(),
"-",
env!("VERGEN_CARGO_TARGET_TRIPLE"),
)
};
}
/// Short hash of the current commit.
///
/// Example: `f5f383e`.
#[cfg(feature = "vergen")]
#[macro_export]
macro_rules! commit {
() => {
env!("VERGEN_GIT_SHA")
};
}
// /// Information about the platform on which service was built, including:
// /// - Information about OS
// /// - Information about CPU
// ///
// /// Example: ``.
// #[macro_export]
// macro_rules! platform {
// (
// ) => {
// concat!(
// env!("VERGEN_SYSINFO_OS_VERSION"),
// " - ",
// env!("VERGEN_SYSINFO_CPU_BRAND"),
// )
// };
// }
/// Service name deduced from name of the binary.
/// This macro must be called within binaries only.
///
/// Example: `router`.
#[macro_export]
macro_rules! service_name {
() => {
env!("CARGO_BIN_NAME")
};
}
/// Build profile, either debug or release.
///
/// Example: `release`.
#[macro_export]
macro_rules! profile {
() => {
env!("CARGO_PROFILE")
};
}
/// The latest git tag. If tags are not present in the repository, the short commit hash is used
/// instead. Refer to the [`git describe`](https://git-scm.com/docs/git-describe) documentation for
/// more details.
#[macro_export]
macro_rules! git_tag {
() => {
env!("VERGEN_GIT_DESCRIBE")
};
}
| {
"crate": "router_env",
"file": "crates/router_env/src/env.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_router_env_4865093687674430726 | clm | file | // Repository: hyperswitch
// Crate: router_env
// File: crates/router_env/src/logger/types.rs
// Contains: 0 structs, 3 enums
//! Types.
use serde::Deserialize;
use strum::{Display, EnumString};
pub use tracing::{
field::{Field, Visit},
Level, Value,
};
/// Category and tag of log event.
///
/// Don't hesitate to add your variant if it is missing here.
#[derive(Debug, Default, Deserialize, Clone, Display, EnumString)]
pub enum Tag {
/// General.
#[default]
General,
/// Redis: get.
RedisGet,
/// Redis: set.
RedisSet,
/// API: incoming web request.
ApiIncomingRequest,
/// API: outgoing web request.
ApiOutgoingRequest,
/// Data base: create.
DbCreate,
/// Data base: read.
DbRead,
/// Data base: updare.
DbUpdate,
/// Data base: delete.
DbDelete,
/// Begin Request
BeginRequest,
/// End Request
EndRequest,
/// Call initiated to connector.
InitiatedToConnector,
/// Event: general.
Event,
/// Compatibility Layer Request
CompatibilityLayerRequest,
}
/// API Flow
#[derive(Debug, Display, Clone, PartialEq, Eq)]
pub enum Flow {
/// Health check
HealthCheck,
/// Deep health Check
DeepHealthCheck,
/// Organization create flow
OrganizationCreate,
/// Organization retrieve flow
OrganizationRetrieve,
/// Organization update flow
OrganizationUpdate,
/// Merchants account create flow.
MerchantsAccountCreate,
/// Merchants account retrieve flow.
MerchantsAccountRetrieve,
/// Merchants account update flow.
MerchantsAccountUpdate,
/// Merchants account delete flow.
MerchantsAccountDelete,
/// Merchant Connectors create flow.
MerchantConnectorsCreate,
/// Merchant Connectors retrieve flow.
MerchantConnectorsRetrieve,
/// Merchant account list
MerchantAccountList,
/// Merchant Connectors update flow.
MerchantConnectorsUpdate,
/// Merchant Connectors delete flow.
MerchantConnectorsDelete,
/// Merchant Connectors list flow.
MerchantConnectorsList,
/// Merchant Transfer Keys
MerchantTransferKey,
/// ConfigKey create flow.
ConfigKeyCreate,
/// ConfigKey fetch flow.
ConfigKeyFetch,
/// Enable platform account flow.
EnablePlatformAccount,
/// ConfigKey Update flow.
ConfigKeyUpdate,
/// ConfigKey Delete flow.
ConfigKeyDelete,
/// Customers create flow.
CustomersCreate,
/// Customers retrieve flow.
CustomersRetrieve,
/// Customers update flow.
CustomersUpdate,
/// Customers delete flow.
CustomersDelete,
/// Customers get mandates flow.
CustomersGetMandates,
/// Create an Ephemeral Key.
EphemeralKeyCreate,
/// Delete an Ephemeral Key.
EphemeralKeyDelete,
/// Mandates retrieve flow.
MandatesRetrieve,
/// Mandates revoke flow.
MandatesRevoke,
/// Mandates list flow.
MandatesList,
/// Payment methods create flow.
PaymentMethodsCreate,
/// Payment methods migrate flow.
PaymentMethodsMigrate,
/// Payment methods batch update flow.
PaymentMethodsBatchUpdate,
/// Payment methods list flow.
PaymentMethodsList,
/// Payment method save flow
PaymentMethodSave,
/// Customer payment methods list flow.
CustomerPaymentMethodsList,
/// Payment methods token data get flow.
GetPaymentMethodTokenData,
/// List Customers for a merchant
CustomersList,
///List Customers for a merchant with constraints.
CustomersListWithConstraints,
/// Retrieve countries and currencies for connector and payment method
ListCountriesCurrencies,
/// Payment method create collect link flow.
PaymentMethodCollectLink,
/// Payment methods retrieve flow.
PaymentMethodsRetrieve,
/// Payment methods update flow.
PaymentMethodsUpdate,
/// Payment methods delete flow.
PaymentMethodsDelete,
/// Network token status check flow.
NetworkTokenStatusCheck,
/// Default Payment method flow.
DefaultPaymentMethodsSet,
/// Payments create flow.
PaymentsCreate,
/// Payments Retrieve flow.
PaymentsRetrieve,
/// Payments Retrieve force sync flow.
PaymentsRetrieveForceSync,
/// Payments Retrieve using merchant reference id
PaymentsRetrieveUsingMerchantReferenceId,
/// Payments update flow.
PaymentsUpdate,
/// Payments confirm flow.
PaymentsConfirm,
/// Payments capture flow.
PaymentsCapture,
/// Payments cancel flow.
PaymentsCancel,
/// Payments cancel post capture flow.
PaymentsCancelPostCapture,
/// Payments approve flow.
PaymentsApprove,
/// Payments reject flow.
PaymentsReject,
/// Payments Session Token flow
PaymentsSessionToken,
/// Payments start flow.
PaymentsStart,
/// Payments list flow.
PaymentsList,
/// Payments filters flow
PaymentsFilters,
/// Payments aggregates flow
PaymentsAggregate,
/// Payments Create Intent flow
PaymentsCreateIntent,
/// Payments Get Intent flow
PaymentsGetIntent,
/// Payments Update Intent flow
PaymentsUpdateIntent,
/// Payments confirm intent flow
PaymentsConfirmIntent,
/// Payments create and confirm intent flow
PaymentsCreateAndConfirmIntent,
/// Payment attempt list flow
PaymentAttemptsList,
#[cfg(feature = "payouts")]
/// Payouts create flow
PayoutsCreate,
#[cfg(feature = "payouts")]
/// Payouts retrieve flow.
PayoutsRetrieve,
#[cfg(feature = "payouts")]
/// Payouts update flow.
PayoutsUpdate,
/// Payouts confirm flow.
PayoutsConfirm,
#[cfg(feature = "payouts")]
/// Payouts cancel flow.
PayoutsCancel,
#[cfg(feature = "payouts")]
/// Payouts fulfill flow.
PayoutsFulfill,
#[cfg(feature = "payouts")]
/// Payouts list flow.
PayoutsList,
#[cfg(feature = "payouts")]
/// Payouts filter flow.
PayoutsFilter,
/// Payouts accounts flow.
PayoutsAccounts,
/// Payout link initiate flow
PayoutLinkInitiate,
/// Payments Redirect flow
PaymentsRedirect,
/// Payemnts Complete Authorize Flow
PaymentsCompleteAuthorize,
/// Refunds create flow.
RefundsCreate,
/// Refunds retrieve flow.
RefundsRetrieve,
/// Refunds retrieve force sync flow.
RefundsRetrieveForceSync,
/// Refunds update flow.
RefundsUpdate,
/// Refunds list flow.
RefundsList,
/// Refunds filters flow
RefundsFilters,
/// Refunds aggregates flow
RefundsAggregate,
// Retrieve forex flow.
RetrieveForexFlow,
/// Toggles recon service for a merchant.
ReconMerchantUpdate,
/// Recon token request flow.
ReconTokenRequest,
/// Initial request for recon service.
ReconServiceRequest,
/// Recon token verification flow
ReconVerifyToken,
/// Routing create flow,
RoutingCreateConfig,
/// Routing link config
RoutingLinkConfig,
/// Routing link config
RoutingUnlinkConfig,
/// Routing retrieve config
RoutingRetrieveConfig,
/// Routing retrieve active config
RoutingRetrieveActiveConfig,
/// Routing retrieve default config
RoutingRetrieveDefaultConfig,
/// Routing retrieve dictionary
RoutingRetrieveDictionary,
/// Rule migration for decision-engine
DecisionEngineRuleMigration,
/// Routing update config
RoutingUpdateConfig,
/// Routing update default config
RoutingUpdateDefaultConfig,
/// Routing delete config
RoutingDeleteConfig,
/// Subscription create flow,
CreateSubscription,
/// Subscription get plans flow,
GetPlansForSubscription,
/// Subscription confirm flow,
ConfirmSubscription,
/// Subscription create and confirm flow,
CreateAndConfirmSubscription,
/// Get Subscription flow
GetSubscription,
/// Update Subscription flow
UpdateSubscription,
/// Get Subscription estimate flow
GetSubscriptionEstimate,
/// Create dynamic routing
CreateDynamicRoutingConfig,
/// Toggle dynamic routing
ToggleDynamicRouting,
/// Update dynamic routing config
UpdateDynamicRoutingConfigs,
/// Add record to blocklist
AddToBlocklist,
/// Delete record from blocklist
DeleteFromBlocklist,
/// List entries from blocklist
ListBlocklist,
/// Toggle blocklist for merchant
ToggleBlocklistGuard,
/// Incoming Webhook Receive
IncomingWebhookReceive,
/// Recovery incoming webhook receive
RecoveryIncomingWebhookReceive,
/// Validate payment method flow
ValidatePaymentMethod,
/// API Key create flow
ApiKeyCreate,
/// API Key retrieve flow
ApiKeyRetrieve,
/// API Key update flow
ApiKeyUpdate,
/// API Key revoke flow
ApiKeyRevoke,
/// API Key list flow
ApiKeyList,
/// Dispute Retrieve flow
DisputesRetrieve,
/// Dispute List flow
DisputesList,
/// Dispute Filters flow
DisputesFilters,
/// Cards Info flow
CardsInfo,
/// Create File flow
CreateFile,
/// Delete File flow
DeleteFile,
/// Retrieve File flow
RetrieveFile,
/// Dispute Evidence submission flow
DisputesEvidenceSubmit,
/// Create Config Key flow
CreateConfigKey,
/// Attach Dispute Evidence flow
AttachDisputeEvidence,
/// Delete Dispute Evidence flow
DeleteDisputeEvidence,
/// Disputes aggregate flow
DisputesAggregate,
/// Retrieve Dispute Evidence flow
RetrieveDisputeEvidence,
/// Invalidate cache flow
CacheInvalidate,
/// Payment Link Retrieve flow
PaymentLinkRetrieve,
/// payment Link Initiate flow
PaymentLinkInitiate,
/// payment Link Initiate flow
PaymentSecureLinkInitiate,
/// Payment Link List flow
PaymentLinkList,
/// Payment Link Status
PaymentLinkStatus,
/// Create a profile
ProfileCreate,
/// Update a profile
ProfileUpdate,
/// Retrieve a profile
ProfileRetrieve,
/// Delete a profile
ProfileDelete,
/// List all the profiles for a merchant
ProfileList,
/// Different verification flows
Verification,
/// Rust locker migration
RustLockerMigration,
/// Gsm Rule Creation flow
GsmRuleCreate,
/// Gsm Rule Retrieve flow
GsmRuleRetrieve,
/// Gsm Rule Update flow
GsmRuleUpdate,
/// Apple pay certificates migration
ApplePayCertificatesMigration,
/// Gsm Rule Delete flow
GsmRuleDelete,
/// Get data from embedded flow
GetDataFromHyperswitchAiFlow,
// List all chat interactions
ListAllChatInteractions,
/// User Sign Up
UserSignUp,
/// User Sign Up
UserSignUpWithMerchantId,
/// User Sign In
UserSignIn,
/// User transfer key
UserTransferKey,
/// User connect account
UserConnectAccount,
/// Upsert Decision Manager Config
DecisionManagerUpsertConfig,
/// Delete Decision Manager Config
DecisionManagerDeleteConfig,
/// Retrieve Decision Manager Config
DecisionManagerRetrieveConfig,
/// Manual payment fulfillment acknowledgement
FrmFulfillment,
/// Get connectors feature matrix
FeatureMatrix,
/// Change password flow
ChangePassword,
/// Signout flow
Signout,
/// Set Dashboard Metadata flow
SetDashboardMetadata,
/// Get Multiple Dashboard Metadata flow
GetMultipleDashboardMetadata,
/// Payment Connector Verify
VerifyPaymentConnector,
/// Internal user signup
InternalUserSignup,
/// Create tenant level user
TenantUserCreate,
/// Switch org
SwitchOrg,
/// Switch merchant v2
SwitchMerchantV2,
/// Switch profile
SwitchProfile,
/// Get permission info
GetAuthorizationInfo,
/// Get Roles info
GetRolesInfo,
/// Get Parent Group Info
GetParentGroupInfo,
/// List roles v2
ListRolesV2,
/// List invitable roles at entity level
ListInvitableRolesAtEntityLevel,
/// List updatable roles at entity level
ListUpdatableRolesAtEntityLevel,
/// Get role
GetRole,
/// Get parent info for role
GetRoleV2,
/// Get role from token
GetRoleFromToken,
/// Get resources and groups for role from token
GetRoleFromTokenV2,
/// Get parent groups info for role from token
GetParentGroupsInfoForRoleFromToken,
/// Update user role
UpdateUserRole,
/// Create merchant account for user in a org
UserMerchantAccountCreate,
/// Create Platform
CreatePlatformAccount,
/// Create Org in a given tenancy
UserOrgMerchantCreate,
/// Generate Sample Data
GenerateSampleData,
/// Delete Sample Data
DeleteSampleData,
/// Get details of a user
GetUserDetails,
/// Get details of a user role in a merchant account
GetUserRoleDetails,
/// PaymentMethodAuth Link token create
PmAuthLinkTokenCreate,
/// PaymentMethodAuth Exchange token create
PmAuthExchangeToken,
/// Get reset password link
ForgotPassword,
/// Reset password using link
ResetPassword,
/// Force set or force change password
RotatePassword,
/// Invite multiple users
InviteMultipleUser,
/// Reinvite user
ReInviteUser,
/// Accept invite from email
AcceptInviteFromEmail,
/// Delete user role
DeleteUserRole,
/// Incremental Authorization flow
PaymentsIncrementalAuthorization,
/// Extend Authorization flow
PaymentsExtendAuthorization,
/// Get action URL for connector onboarding
GetActionUrl,
/// Sync connector onboarding status
SyncOnboardingStatus,
/// Reset tracking id
ResetTrackingId,
/// Verify email Token
VerifyEmail,
/// Send verify email
VerifyEmailRequest,
/// Update user account details
UpdateUserAccountDetails,
/// Accept user invitation using entities
AcceptInvitationsV2,
/// Accept user invitation using entities before user login
AcceptInvitationsPreAuth,
/// Initiate external authentication for a payment
PaymentsExternalAuthentication,
/// Authorize the payment after external 3ds authentication
PaymentsAuthorize,
/// Create Role
CreateRole,
/// Create Role V2
CreateRoleV2,
/// Update Role
UpdateRole,
/// User email flow start
UserFromEmail,
/// Begin TOTP
TotpBegin,
/// Reset TOTP
TotpReset,
/// Verify TOTP
TotpVerify,
/// Update TOTP secret
TotpUpdate,
/// Verify Access Code
RecoveryCodeVerify,
/// Generate or Regenerate recovery codes
RecoveryCodesGenerate,
/// Terminate two factor authentication
TerminateTwoFactorAuth,
/// Check 2FA status
TwoFactorAuthStatus,
/// Create user authentication method
CreateUserAuthenticationMethod,
/// Update user authentication method
UpdateUserAuthenticationMethod,
/// List user authentication methods
ListUserAuthenticationMethods,
/// Get sso auth url
GetSsoAuthUrl,
/// Signin with SSO
SignInWithSso,
/// Auth Select
AuthSelect,
/// List Orgs for user
ListOrgForUser,
/// List Merchants for user in org
ListMerchantsForUserInOrg,
/// List Profile for user in org and merchant
ListProfileForUserInOrgAndMerchant,
/// List Users in Org
ListUsersInLineage,
/// List invitations for user
ListInvitationsForUser,
/// Get theme using lineage
GetThemeUsingLineage,
/// Get theme using theme id
GetThemeUsingThemeId,
/// Upload file to theme storage
UploadFileToThemeStorage,
/// Create theme
CreateTheme,
/// Update theme
UpdateTheme,
/// Delete theme
DeleteTheme,
/// Create user theme
CreateUserTheme,
/// Update user theme
UpdateUserTheme,
/// Delete user theme
DeleteUserTheme,
/// Upload file to user theme storage
UploadFileToUserThemeStorage,
/// Get user theme using theme id
GetUserThemeUsingThemeId,
///List All Themes In Lineage
ListAllThemesInLineage,
/// Get user theme using lineage
GetUserThemeUsingLineage,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
WebhookEventDeliveryAttemptList,
/// Manually retry the delivery for a webhook event
WebhookEventDeliveryRetry,
/// Retrieve status of the Poll
RetrievePollStatus,
/// Toggles the extended card info feature in profile level
ToggleExtendedCardInfo,
/// Toggles the extended card info feature in profile level
ToggleConnectorAgnosticMit,
/// Get the extended card info associated to a payment_id
GetExtendedCardInfo,
/// Manually update the refund details like status, error code, error message etc.
RefundsManualUpdate,
/// Manually update the payment details like status, error code, error message etc.
PaymentsManualUpdate,
/// Dynamic Tax Calcultion
SessionUpdateTaxCalculation,
ProxyConfirmIntent,
/// Payments post session tokens flow
PaymentsPostSessionTokens,
/// Payments Update Metadata
PaymentsUpdateMetadata,
/// Payments start redirection flow
PaymentStartRedirection,
/// Volume split on the routing type
VolumeSplitOnRoutingType,
/// Routing evaluate rule flow
RoutingEvaluateRule,
/// Relay flow
Relay,
/// Relay retrieve flow
RelayRetrieve,
/// Card tokenization flow
TokenizeCard,
/// Card tokenization using payment method flow
TokenizeCardUsingPaymentMethodId,
/// Cards batch tokenization flow
TokenizeCardBatch,
/// Incoming Relay Webhook Receive
IncomingRelayWebhookReceive,
/// Generate Hypersense Token
HypersenseTokenRequest,
/// Verify Hypersense Token
HypersenseVerifyToken,
/// Signout Hypersense Token
HypersenseSignoutToken,
/// Payment Method Session Create
PaymentMethodSessionCreate,
/// Payment Method Session Retrieve
PaymentMethodSessionRetrieve,
// Payment Method Session Update
PaymentMethodSessionUpdate,
/// Update a saved payment method using the payment methods session
PaymentMethodSessionUpdateSavedPaymentMethod,
/// Delete a saved payment method using the payment methods session
PaymentMethodSessionDeleteSavedPaymentMethod,
/// Confirm a payment method session with payment method data
PaymentMethodSessionConfirm,
/// Create Cards Info flow
CardsInfoCreate,
/// Update Cards Info flow
CardsInfoUpdate,
/// Cards Info migrate flow
CardsInfoMigrate,
///Total payment method count for merchant
TotalPaymentMethodCount,
/// Process Tracker Revenue Recovery Workflow Retrieve
RevenueRecoveryRetrieve,
/// Process Tracker Revenue Recovery Workflow Resume
RevenueRecoveryResume,
/// Tokenization flow
TokenizationCreate,
/// Tokenization retrieve flow
TokenizationRetrieve,
/// Clone Connector flow
CloneConnector,
/// Authentication Create flow
AuthenticationCreate,
/// Authentication Eligibility flow
AuthenticationEligibility,
/// Authentication Sync flow
AuthenticationSync,
/// Authentication Sync Post Update flow
AuthenticationSyncPostUpdate,
/// Authentication Authenticate flow
AuthenticationAuthenticate,
///Proxy Flow
Proxy,
/// Profile Acquirer Create flow
ProfileAcquirerCreate,
/// Profile Acquirer Update flow
ProfileAcquirerUpdate,
/// ThreeDs Decision Rule Execute flow
ThreeDsDecisionRuleExecute,
/// Incoming Network Token Webhook Receive
IncomingNetworkTokenWebhookReceive,
/// Decision Engine Decide Gateway Call
DecisionEngineDecideGatewayCall,
/// Decision Engine Gateway Feedback Call
DecisionEngineGatewayFeedbackCall,
/// Recovery payments create flow.
RecoveryPaymentsCreate,
/// Tokenization delete flow
TokenizationDelete,
/// Payment method data backfill flow
RecoveryDataBackfill,
/// Revenue recovery Redis operations flow
RevenueRecoveryRedis,
/// Gift card balance check flow
GiftCardBalanceCheck,
/// Payments Submit Eligibility flow
PaymentsSubmitEligibility,
}
/// Trait for providing generic behaviour to flow metric
pub trait FlowMetric: ToString + std::fmt::Debug + Clone {}
impl FlowMetric for Flow {}
/// Category of log event.
#[derive(Debug)]
pub enum Category {
/// Redis: general.
Redis,
/// API: general.
Api,
/// Database: general.
Store,
/// Event: general.
Event,
/// General: general.
General,
}
| {
"crate": "router_env",
"file": "crates/router_env/src/logger/types.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 3,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_redis_interface_1537769422286889839 | clm | file | // Repository: hyperswitch
// Crate: redis_interface
// File: crates/redis_interface/src/errors.rs
// Contains: 0 structs, 1 enums
//! Errors specific to this custom redis interface
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum RedisError {
#[error("Invalid Redis configuration: {0}")]
InvalidConfiguration(String),
#[error("Failed to set key value in Redis")]
SetFailed,
#[error("Failed to set key value in Redis. Duplicate value")]
SetNxFailed,
#[error("Failed to set key value with expiry in Redis")]
SetExFailed,
#[error("Failed to set expiry for key value in Redis")]
SetExpiryFailed,
#[error("Failed to get key value in Redis")]
GetFailed,
#[error("Failed to delete key value in Redis")]
DeleteFailed,
#[error("Failed to append entry to Redis stream")]
StreamAppendFailed,
#[error("Failed to read entries from Redis stream")]
StreamReadFailed,
#[error("Failed to get stream length")]
GetLengthFailed,
#[error("Failed to delete entries from Redis stream")]
StreamDeleteFailed,
#[error("Failed to trim entries from Redis stream")]
StreamTrimFailed,
#[error("Failed to acknowledge Redis stream entry")]
StreamAcknowledgeFailed,
#[error("Stream is either empty or not available")]
StreamEmptyOrNotAvailable,
#[error("Failed to create Redis consumer group")]
ConsumerGroupCreateFailed,
#[error("Failed to destroy Redis consumer group")]
ConsumerGroupDestroyFailed,
#[error("Failed to delete consumer from consumer group")]
ConsumerGroupRemoveConsumerFailed,
#[error("Failed to set last ID on consumer group")]
ConsumerGroupSetIdFailed,
#[error("Failed to set Redis stream message owner")]
ConsumerGroupClaimFailed,
#[error("Failed to serialize application type to JSON")]
JsonSerializationFailed,
#[error("Failed to deserialize application type from JSON")]
JsonDeserializationFailed,
#[error("Failed to set hash in Redis")]
SetHashFailed,
#[error("Failed to set hash field in Redis")]
SetHashFieldFailed,
#[error("Failed to add members to set in Redis")]
SetAddMembersFailed,
#[error("Failed to get hash field in Redis")]
GetHashFieldFailed,
#[error("The requested value was not found in Redis")]
NotFound,
#[error("Invalid RedisEntryId provided")]
InvalidRedisEntryId,
#[error("Failed to establish Redis connection")]
RedisConnectionError,
#[error("Failed to subscribe to a channel")]
SubscribeError,
#[error("Failed to publish to a channel")]
PublishError,
#[error("Failed while receiving message from publisher")]
OnMessageError,
#[error("Got an unknown result from redis")]
UnknownResult,
#[error("Failed to append elements to list in Redis")]
AppendElementsToListFailed,
#[error("Failed to get list elements in Redis")]
GetListElementsFailed,
#[error("Failed to get length of list")]
GetListLengthFailed,
#[error("Failed to pop list elements in Redis")]
PopListElementsFailed,
#[error("Failed to increment hash field in Redis")]
IncrementHashFieldFailed,
}
| {
"crate": "redis_interface",
"file": "crates/redis_interface/src/errors.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_payment_methods_-5157968592690778550 | clm | file | // Repository: hyperswitch
// Crate: payment_methods
// File: crates/payment_methods/src/core/errors.rs
// Contains: 0 structs, 1 enums
pub use common_utils::errors::{CustomResult, ParsingError, ValidationError};
pub use hyperswitch_domain_models::{
api,
errors::api_error_response::{self, *},
};
pub type PmResult<T> = CustomResult<T, ApiErrorResponse>;
pub type PmResponse<T> = CustomResult<api::ApplicationResponse<T>, ApiErrorResponse>;
pub type VaultResult<T> = CustomResult<T, VaultError>;
#[derive(Debug, thiserror::Error)]
pub enum VaultError {
#[error("Failed to save card in card vault")]
SaveCardFailed,
#[error("Failed to fetch card details from card vault")]
FetchCardFailed,
#[error("Failed to delete card in card vault")]
DeleteCardFailed,
#[error("Failed to encode card vault request")]
RequestEncodingFailed,
#[error("Failed to deserialize card vault response")]
ResponseDeserializationFailed,
#[error("Failed to create payment method")]
PaymentMethodCreationFailed,
#[error("The given payment method is currently not supported in vault")]
PaymentMethodNotSupported,
#[error("The given payout method is currently not supported in vault")]
PayoutMethodNotSupported,
#[error("Missing required field: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error("The card vault returned an unexpected response: {0:?}")]
UnexpectedResponseError(bytes::Bytes),
#[error("Failed to update in PMD table")]
UpdateInPaymentMethodDataTableFailed,
#[error("Failed to fetch payment method in vault")]
FetchPaymentMethodFailed,
#[error("Failed to save payment method in vault")]
SavePaymentMethodFailed,
#[error("Failed to generate fingerprint")]
GenerateFingerprintFailed,
#[error("Failed to encrypt vault request")]
RequestEncryptionFailed,
#[error("Failed to decrypt vault response")]
ResponseDecryptionFailed,
#[error("Failed to call vault")]
VaultAPIError,
#[error("Failed while calling locker API")]
ApiError,
}
| {
"crate": "payment_methods",
"file": "crates/payment_methods/src/core/errors.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_pm_auth_-5917181730451843756 | clm | file | // Repository: hyperswitch
// Crate: pm_auth
// File: crates/pm_auth/src/core/errors.rs
// Contains: 0 structs, 2 enums
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum ConnectorError {
#[error("Failed to obtain authentication type")]
FailedToObtainAuthType,
#[error("Missing required field: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error("Failed to execute a processing step: {0:?}")]
ProcessingStepFailed(Option<bytes::Bytes>),
#[error("Failed to deserialize connector response")]
ResponseDeserializationFailed,
#[error("Failed to encode connector request")]
RequestEncodingFailed,
#[error("Invalid connector configuration: {config}")]
InvalidConnectorConfig { config: &'static str },
}
pub type CustomResult<T, E> = error_stack::Result<T, E>;
#[derive(Debug, thiserror::Error)]
pub enum ParsingError {
#[error("Failed to parse enum: {0}")]
EnumParseFailure(&'static str),
#[error("Failed to parse struct: {0}")]
StructParseFailure(&'static str),
#[error("Failed to serialize to {0} format")]
EncodeError(&'static str),
#[error("Unknown error while parsing")]
UnknownError,
}
| {
"crate": "pm_auth",
"file": "crates/pm_auth/src/core/errors.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_kgraph_utils_-2972020284898935167 | clm | file | // Repository: hyperswitch
// Crate: kgraph_utils
// File: crates/kgraph_utils/src/error.rs
// Contains: 0 structs, 1 enums
#[cfg(feature = "v2")]
use common_enums::connector_enums;
use euclid::{dssa::types::AnalysisErrorType, frontend::dir};
#[derive(Debug, thiserror::Error, serde::Serialize)]
#[serde(tag = "type", content = "info", rename_all = "snake_case")]
pub enum KgraphError {
#[error("Invalid connector name encountered: '{0}'")]
InvalidConnectorName(
#[cfg(feature = "v1")] String,
#[cfg(feature = "v2")] connector_enums::Connector,
),
#[error("Error in domain creation")]
DomainCreationError,
#[error("There was an error constructing the graph: {0}")]
GraphConstructionError(hyperswitch_constraint_graph::GraphError<dir::DirValue>),
#[error("There was an error constructing the context")]
ContextConstructionError(Box<AnalysisErrorType>),
#[error("there was an unprecedented indexing error")]
IndexingError,
}
| {
"crate": "kgraph_utils",
"file": "crates/kgraph_utils/src/error.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_external_services_-3544737670145141757 | clm | file | // Repository: hyperswitch
// Crate: external_services
// File: crates/external_services/src/lib.rs
// Contains: 0 structs, 1 enums
//! Interactions with external systems.
#![warn(missing_docs, missing_debug_implementations)]
#[cfg(feature = "aws_kms")]
pub mod aws_kms;
/// crm module
pub mod crm;
#[cfg(feature = "email")]
pub mod email;
pub mod file_storage;
/// Building grpc clients to communicate with the server
pub mod grpc_client;
#[cfg(feature = "hashicorp-vault")]
pub mod hashicorp_vault;
/// http_client module
pub mod http_client;
/// hubspot_proxy module
pub mod hubspot_proxy;
pub mod managers;
pub mod no_encryption;
#[cfg(feature = "superposition")]
pub mod superposition;
/// deserializers module_path
pub mod utils;
#[cfg(feature = "revenue_recovery")]
/// date_time module
pub mod date_time {
use error_stack::ResultExt;
/// Errors in time conversion
#[derive(Debug, thiserror::Error)]
pub enum DateTimeConversionError {
#[error("Invalid timestamp value from prost Timestamp: out of representable range")]
/// Error for out of range
TimestampOutOfRange,
}
/// Converts a `time::PrimitiveDateTime` to a `prost_types::Timestamp`.
pub fn convert_to_prost_timestamp(dt: time::PrimitiveDateTime) -> prost_types::Timestamp {
let odt = dt.assume_utc();
prost_types::Timestamp {
seconds: odt.unix_timestamp(),
// This conversion is safe as nanoseconds (0..999_999_999) always fit within an i32.
#[allow(clippy::as_conversions)]
nanos: odt.nanosecond() as i32,
}
}
/// Converts a `prost_types::Timestamp` to an `time::PrimitiveDateTime`.
pub fn convert_from_prost_timestamp(
ts: &prost_types::Timestamp,
) -> error_stack::Result<time::PrimitiveDateTime, DateTimeConversionError> {
let timestamp_nanos = i128::from(ts.seconds) * 1_000_000_000 + i128::from(ts.nanos);
time::OffsetDateTime::from_unix_timestamp_nanos(timestamp_nanos)
.map(|offset_dt| time::PrimitiveDateTime::new(offset_dt.date(), offset_dt.time()))
.change_context(DateTimeConversionError::TimestampOutOfRange)
}
}
/// Crate specific constants
pub mod consts {
/// General purpose base64 engine
#[cfg(feature = "aws_kms")]
pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose =
base64::engine::general_purpose::STANDARD;
/// Header key used to specify the connector name in UCS requests.
pub(crate) const UCS_HEADER_CONNECTOR: &str = "x-connector";
/// Header key used to indicate the authentication type being used.
pub(crate) const UCS_HEADER_AUTH_TYPE: &str = "x-auth";
/// Header key for sending the API key used for authentication.
pub(crate) const UCS_HEADER_API_KEY: &str = "x-api-key";
/// Header key for sending an additional secret key used in some auth types.
pub(crate) const UCS_HEADER_KEY1: &str = "x-key1";
/// Header key for sending the API secret in signature-based authentication.
pub(crate) const UCS_HEADER_API_SECRET: &str = "x-api-secret";
/// Header key for sending the AUTH KEY MAP in currency-based authentication.
pub(crate) const UCS_HEADER_AUTH_KEY_MAP: &str = "x-auth-key-map";
/// Header key for sending the EXTERNAL VAULT METADATA in proxy payments
pub(crate) const UCS_HEADER_EXTERNAL_VAULT_METADATA: &str = "x-external-vault-metadata";
/// Header key for sending the list of lineage ids
pub(crate) const UCS_LINEAGE_IDS: &str = "x-lineage-ids";
/// Header key for sending the merchant reference id to UCS
pub(crate) const UCS_HEADER_REFERENCE_ID: &str = "x-reference-id";
}
/// Metrics for interactions with external systems.
#[cfg(feature = "aws_kms")]
pub mod metrics {
use router_env::{counter_metric, global_meter, histogram_metric_f64};
global_meter!(GLOBAL_METER, "EXTERNAL_SERVICES");
#[cfg(feature = "aws_kms")]
counter_metric!(AWS_KMS_DECRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Decryption failures
#[cfg(feature = "aws_kms")]
counter_metric!(AWS_KMS_ENCRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Encryption failures
#[cfg(feature = "aws_kms")]
histogram_metric_f64!(AWS_KMS_DECRYPT_TIME, GLOBAL_METER); // Histogram for AWS KMS decryption time (in sec)
#[cfg(feature = "aws_kms")]
histogram_metric_f64!(AWS_KMS_ENCRYPT_TIME, GLOBAL_METER); // Histogram for AWS KMS encryption time (in sec)
}
| {
"crate": "external_services",
"file": "crates/external_services/src/lib.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_external_services_6130979771713542870 | clm | file | // Repository: hyperswitch
// Crate: external_services
// File: crates/external_services/src/managers/secrets_management.rs
// Contains: 0 structs, 1 enums
//! Secrets management util module
use common_utils::errors::CustomResult;
#[cfg(feature = "hashicorp-vault")]
use error_stack::ResultExt;
use hyperswitch_interfaces::secrets_interface::{
SecretManagementInterface, SecretsManagementError,
};
#[cfg(feature = "aws_kms")]
use crate::aws_kms;
#[cfg(feature = "hashicorp-vault")]
use crate::hashicorp_vault;
use crate::no_encryption::core::NoEncryption;
/// Enum representing configuration options for secrets management.
#[derive(Debug, Clone, Default, serde::Deserialize)]
#[serde(tag = "secrets_manager")]
#[serde(rename_all = "snake_case")]
pub enum SecretsManagementConfig {
/// AWS KMS configuration
#[cfg(feature = "aws_kms")]
AwsKms {
/// AWS KMS config
aws_kms: aws_kms::core::AwsKmsConfig,
},
/// HashiCorp-Vault configuration
#[cfg(feature = "hashicorp-vault")]
HashiCorpVault {
/// HC-Vault config
hc_vault: hashicorp_vault::core::HashiCorpVaultConfig,
},
/// Variant representing no encryption
#[default]
NoEncryption,
}
impl SecretsManagementConfig {
/// Verifies that the client configuration is usable
pub fn validate(&self) -> Result<(), &'static str> {
match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => aws_kms.validate(),
#[cfg(feature = "hashicorp-vault")]
Self::HashiCorpVault { hc_vault } => hc_vault.validate(),
Self::NoEncryption => Ok(()),
}
}
/// Retrieves the appropriate secret management client based on the configuration.
pub async fn get_secret_management_client(
&self,
) -> CustomResult<Box<dyn SecretManagementInterface>, SecretsManagementError> {
match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => {
Ok(Box::new(aws_kms::core::AwsKmsClient::new(aws_kms).await))
}
#[cfg(feature = "hashicorp-vault")]
Self::HashiCorpVault { hc_vault } => {
hashicorp_vault::core::HashiCorpVault::new(hc_vault)
.change_context(SecretsManagementError::ClientCreationFailed)
.map(|inner| -> Box<dyn SecretManagementInterface> { Box::new(inner) })
}
Self::NoEncryption => Ok(Box::new(NoEncryption)),
}
}
}
| {
"crate": "external_services",
"file": "crates/external_services/src/managers/secrets_management.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_external_services_-3562053240510728745 | clm | file | // Repository: hyperswitch
// Crate: external_services
// File: crates/external_services/src/managers/encryption_management.rs
// Contains: 0 structs, 1 enums
//! Encryption management util module
use std::sync::Arc;
use common_utils::errors::CustomResult;
use hyperswitch_interfaces::encryption_interface::{
EncryptionError, EncryptionManagementInterface,
};
#[cfg(feature = "aws_kms")]
use crate::aws_kms;
use crate::no_encryption::core::NoEncryption;
/// Enum representing configuration options for encryption management.
#[derive(Debug, Clone, Default, serde::Deserialize)]
#[serde(tag = "encryption_manager")]
#[serde(rename_all = "snake_case")]
pub enum EncryptionManagementConfig {
/// AWS KMS configuration
#[cfg(feature = "aws_kms")]
AwsKms {
/// AWS KMS config
aws_kms: aws_kms::core::AwsKmsConfig,
},
/// Variant representing no encryption
#[default]
NoEncryption,
}
impl EncryptionManagementConfig {
/// Verifies that the client configuration is usable
pub fn validate(&self) -> Result<(), &'static str> {
match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => aws_kms.validate(),
Self::NoEncryption => Ok(()),
}
}
/// Retrieves the appropriate encryption client based on the configuration.
pub async fn get_encryption_management_client(
&self,
) -> CustomResult<Arc<dyn EncryptionManagementInterface>, EncryptionError> {
Ok(match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => Arc::new(aws_kms::core::AwsKmsClient::new(aws_kms).await),
Self::NoEncryption => Arc::new(NoEncryption),
})
}
}
| {
"crate": "external_services",
"file": "crates/external_services/src/managers/encryption_management.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_masking_1366576461212108391 | clm | file | // Repository: hyperswitch
// Crate: masking
// File: crates/masking/src/strategy.rs
// Contains: 0 structs, 1 enums
use core::fmt;
/// Debugging trait which is specialized for handling secret values
pub trait Strategy<T> {
/// Format information about the secret's type.
fn fmt(value: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result;
}
/// Debug with type
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum WithType {}
impl<T> Strategy<T> for WithType {
fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("*** ")?;
fmt.write_str(std::any::type_name::<T>())?;
fmt.write_str(" ***")
}
}
/// Debug without type
pub enum WithoutType {}
impl<T> Strategy<T> for WithoutType {
fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("*** ***")
}
}
| {
"crate": "masking",
"file": "crates/masking/src/strategy.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_masking_-1920129030197225409 | clm | file | // Repository: hyperswitch
// Crate: masking
// File: crates/masking/src/maskable.rs
// Contains: 0 structs, 1 enums
//! This module contains Masking objects and traits
use crate::{ExposeInterface, Secret};
/// An Enum that allows us to optionally mask data, based on which enum variant that data is stored
/// in.
#[derive(Clone, Eq, PartialEq)]
pub enum Maskable<T: Eq + PartialEq + Clone> {
/// Variant which masks the data by wrapping in a Secret
Masked(Secret<T>),
/// Varant which doesn't mask the data
Normal(T),
}
impl<T: std::fmt::Debug + Clone + Eq + PartialEq> std::fmt::Debug for Maskable<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Masked(secret_value) => std::fmt::Debug::fmt(secret_value, f),
Self::Normal(value) => std::fmt::Debug::fmt(value, f),
}
}
}
impl<T: Eq + PartialEq + Clone + std::hash::Hash> std::hash::Hash for Maskable<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
match self {
Self::Masked(value) => crate::PeekInterface::peek(value).hash(state),
Self::Normal(value) => value.hash(state),
}
}
}
impl<T: Eq + PartialEq + Clone> Maskable<T> {
/// Get the inner data while consuming self
pub fn into_inner(self) -> T {
match self {
Self::Masked(inner_secret) => inner_secret.expose(),
Self::Normal(inner) => inner,
}
}
/// Create a new Masked data
pub fn new_masked(item: Secret<T>) -> Self {
Self::Masked(item)
}
/// Create a new non-masked data
pub fn new_normal(item: T) -> Self {
Self::Normal(item)
}
/// Checks whether the data is masked.
/// Returns `true` if the data is wrapped in the `Masked` variant,
/// returns `false` otherwise.
pub fn is_masked(&self) -> bool {
matches!(self, Self::Masked(_))
}
/// Checks whether the data is normal (not masked).
/// Returns `true` if the data is wrapped in the `Normal` variant,
/// returns `false` otherwise.
pub fn is_normal(&self) -> bool {
matches!(self, Self::Normal(_))
}
}
/// Trait for providing a method on custom types for constructing `Maskable`
pub trait Mask {
/// The type returned by the `into_masked()` method. Must implement `PartialEq`, `Eq` and `Clone`
type Output: Eq + Clone + PartialEq;
/// Construct a `Maskable` instance that wraps `Self::Output` by consuming `self`
fn into_masked(self) -> Maskable<Self::Output>;
}
impl Mask for String {
type Output = Self;
fn into_masked(self) -> Maskable<Self::Output> {
Maskable::new_masked(self.into())
}
}
impl Mask for Secret<String> {
type Output = String;
fn into_masked(self) -> Maskable<Self::Output> {
Maskable::new_masked(self)
}
}
impl<T: Eq + PartialEq + Clone> From<T> for Maskable<T> {
fn from(value: T) -> Self {
Self::new_normal(value)
}
}
impl From<&str> for Maskable<String> {
fn from(value: &str) -> Self {
Self::new_normal(value.to_string())
}
}
| {
"crate": "masking",
"file": "crates/masking/src/maskable.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_analytics_8494627543555301107 | clm | file | // Repository: hyperswitch
// Crate: analytics
// File: crates/analytics/src/errors.rs
// Contains: 0 structs, 1 enums
use api_models::errors::types::{ApiError, ApiErrorResponse};
use common_utils::errors::{CustomResult, ErrorSwitch};
pub type AnalyticsResult<T> = CustomResult<T, AnalyticsError>;
#[derive(Debug, Clone, serde::Serialize, thiserror::Error)]
pub enum AnalyticsError {
#[allow(dead_code)]
#[error("Not implemented: {0}")]
NotImplemented(&'static str),
#[error("Unknown Analytics Error")]
UnknownError,
#[error("Access Forbidden Analytics Error")]
AccessForbiddenError,
#[error("Failed to fetch currency exchange rate")]
ForexFetchFailed,
}
impl ErrorSwitch<ApiErrorResponse> for AnalyticsError {
fn switch(&self) -> ApiErrorResponse {
match self {
Self::NotImplemented(feature) => ApiErrorResponse::NotImplemented(ApiError::new(
"IR",
0,
format!("{feature} is not implemented."),
None,
)),
Self::UnknownError => ApiErrorResponse::InternalServerError(ApiError::new(
"HE",
0,
"Something went wrong",
None,
)),
Self::AccessForbiddenError => {
ApiErrorResponse::Unauthorized(ApiError::new("IR", 0, "Access Forbidden", None))
}
Self::ForexFetchFailed => ApiErrorResponse::InternalServerError(ApiError::new(
"HE",
0,
"Failed to fetch currency exchange rate",
None,
)),
}
}
}
| {
"crate": "analytics",
"file": "crates/analytics/src/errors.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_analytics_-4544856990948596957 | clm | file | // Repository: hyperswitch
// Crate: analytics
// File: crates/analytics/src/payments/core.rs
// Contains: 0 structs, 1 enums
#![allow(dead_code)]
use std::collections::{HashMap, HashSet};
use api_models::analytics::{
payments::{
MetricsBucketResponse, PaymentDimensions, PaymentDistributions, PaymentMetrics,
PaymentMetricsBucketIdentifier,
},
FilterValue, GetPaymentFiltersRequest, GetPaymentMetricRequest, PaymentFiltersResponse,
PaymentsAnalyticsMetadata, PaymentsMetricsResponse,
};
use bigdecimal::ToPrimitive;
use common_enums::Currency;
use common_utils::errors::CustomResult;
use currency_conversion::{conversion::convert, types::ExchangeRates};
use error_stack::ResultExt;
use router_env::{
instrument, logger,
tracing::{self, Instrument},
};
use super::{
distribution::PaymentDistributionRow,
filters::{get_payment_filter_for_dimension, PaymentFilterRow},
metrics::PaymentMetricRow,
PaymentMetricsAccumulator,
};
use crate::{
enums::AuthInfo,
errors::{AnalyticsError, AnalyticsResult},
metrics,
payments::{PaymentDistributionAccumulator, PaymentMetricAccumulator},
AnalyticsProvider,
};
#[derive(Debug)]
pub enum TaskType {
MetricTask(
PaymentMetrics,
CustomResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, AnalyticsError>,
),
DistributionTask(
PaymentDistributions,
CustomResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>, AnalyticsError>,
),
}
#[instrument(skip_all)]
pub async fn get_metrics(
pool: &AnalyticsProvider,
ex_rates: &Option<ExchangeRates>,
auth: &AuthInfo,
req: GetPaymentMetricRequest,
) -> AnalyticsResult<PaymentsMetricsResponse<MetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<
PaymentMetricsBucketIdentifier,
PaymentMetricsAccumulator,
> = HashMap::new();
let mut set = tokio::task::JoinSet::new();
for metric_type in req.metrics.iter().cloned() {
let req = req.clone();
let pool = pool.clone();
let task_span = tracing::debug_span!(
"analytics_payments_metrics_query",
payment_metric = metric_type.as_ref()
);
// TODO: lifetime issues with joinset,
// can be optimized away if joinset lifetime requirements are relaxed
let auth_scoped = auth.to_owned();
set.spawn(
async move {
let data = pool
.get_payment_metrics(
&metric_type,
&req.group_by_names.clone(),
&auth_scoped,
&req.filters,
req.time_series.map(|t| t.granularity),
&req.time_range,
)
.await
.change_context(AnalyticsError::UnknownError);
TaskType::MetricTask(metric_type, data)
}
.instrument(task_span),
);
}
if let Some(distribution) = req.clone().distribution {
let req = req.clone();
let pool = pool.clone();
let task_span = tracing::debug_span!(
"analytics_payments_distribution_query",
payment_distribution = distribution.distribution_for.as_ref()
);
let auth_scoped = auth.to_owned();
set.spawn(
async move {
let data = pool
.get_payment_distribution(
&distribution,
&req.group_by_names.clone(),
&auth_scoped,
&req.filters,
req.time_series.map(|t| t.granularity),
&req.time_range,
)
.await
.change_context(AnalyticsError::UnknownError);
TaskType::DistributionTask(distribution.distribution_for, data)
}
.instrument(task_span),
);
}
while let Some(task_type) = set
.join_next()
.await
.transpose()
.change_context(AnalyticsError::UnknownError)?
{
match task_type {
TaskType::MetricTask(metric, data) => {
let data = data?;
let attributes = router_env::metric_attributes!(
("metric_type", metric.to_string()),
("source", pool.to_string()),
);
let value = u64::try_from(data.len());
if let Ok(val) = value {
metrics::BUCKETS_FETCHED.record(val, attributes);
logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val);
}
for (id, value) in data {
logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}");
let metrics_builder = metrics_accumulator.entry(id).or_default();
match metric {
PaymentMetrics::PaymentSuccessRate
| PaymentMetrics::SessionizedPaymentSuccessRate => metrics_builder
.payment_success_rate
.add_metrics_bucket(&value),
PaymentMetrics::PaymentCount | PaymentMetrics::SessionizedPaymentCount => {
metrics_builder.payment_count.add_metrics_bucket(&value)
}
PaymentMetrics::PaymentSuccessCount
| PaymentMetrics::SessionizedPaymentSuccessCount => {
metrics_builder.payment_success.add_metrics_bucket(&value)
}
PaymentMetrics::PaymentProcessedAmount
| PaymentMetrics::SessionizedPaymentProcessedAmount => {
metrics_builder.processed_amount.add_metrics_bucket(&value)
}
PaymentMetrics::AvgTicketSize
| PaymentMetrics::SessionizedAvgTicketSize => {
metrics_builder.avg_ticket_size.add_metrics_bucket(&value)
}
PaymentMetrics::RetriesCount | PaymentMetrics::SessionizedRetriesCount => {
metrics_builder.retries_count.add_metrics_bucket(&value);
metrics_builder
.retries_amount_processed
.add_metrics_bucket(&value)
}
PaymentMetrics::ConnectorSuccessRate
| PaymentMetrics::SessionizedConnectorSuccessRate => {
metrics_builder
.connector_success_rate
.add_metrics_bucket(&value);
}
PaymentMetrics::DebitRouting | PaymentMetrics::SessionizedDebitRouting => {
metrics_builder.debit_routing.add_metrics_bucket(&value);
}
PaymentMetrics::PaymentsDistribution => {
metrics_builder
.payments_distribution
.add_metrics_bucket(&value);
}
PaymentMetrics::FailureReasons => {
metrics_builder
.failure_reasons_distribution
.add_metrics_bucket(&value);
}
}
}
logger::debug!(
"Analytics Accumulated Results: metric: {}, results: {:#?}",
metric,
metrics_accumulator
);
}
TaskType::DistributionTask(distribution, data) => {
let data = data?;
let attributes = router_env::metric_attributes!(
("distribution_type", distribution.to_string()),
("source", pool.to_string()),
);
let value = u64::try_from(data.len());
if let Ok(val) = value {
metrics::BUCKETS_FETCHED.record(val, attributes);
logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val);
}
for (id, value) in data {
logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for distribution {distribution}");
let metrics_accumulator = metrics_accumulator.entry(id).or_default();
match distribution {
PaymentDistributions::PaymentErrorMessage => metrics_accumulator
.payment_error_message
.add_distribution_bucket(&value),
}
}
logger::debug!(
"Analytics Accumulated Results: distribution: {}, results: {:#?}",
distribution,
metrics_accumulator
);
}
}
}
let mut total_payment_processed_amount = 0;
let mut total_payment_processed_count = 0;
let mut total_payment_processed_amount_without_smart_retries = 0;
let mut total_payment_processed_count_without_smart_retries = 0;
let mut total_failure_reasons_count = 0;
let mut total_failure_reasons_count_without_smart_retries = 0;
let mut total_payment_processed_amount_in_usd = 0;
let mut total_payment_processed_amount_without_smart_retries_usd = 0;
let query_data: Vec<MetricsBucketResponse> = metrics_accumulator
.into_iter()
.map(|(id, val)| {
let mut collected_values = val.collect();
if let Some(amount) = collected_values.payment_processed_amount {
let amount_in_usd = if let Some(ex_rates) = ex_rates {
id.currency
.and_then(|currency| {
i64::try_from(amount)
.inspect_err(|e| logger::error!("Amount conversion error: {:?}", e))
.ok()
.and_then(|amount_i64| {
convert(ex_rates, currency, Currency::USD, amount_i64)
.inspect_err(|e| {
logger::error!("Currency conversion error: {:?}", e)
})
.ok()
})
})
.map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
.unwrap_or_default()
} else {
None
};
collected_values.payment_processed_amount_in_usd = amount_in_usd;
total_payment_processed_amount += amount;
total_payment_processed_amount_in_usd += amount_in_usd.unwrap_or(0);
}
if let Some(count) = collected_values.payment_processed_count {
total_payment_processed_count += count;
}
if let Some(amount) = collected_values.payment_processed_amount_without_smart_retries {
let amount_in_usd = if let Some(ex_rates) = ex_rates {
id.currency
.and_then(|currency| {
i64::try_from(amount)
.inspect_err(|e| logger::error!("Amount conversion error: {:?}", e))
.ok()
.and_then(|amount_i64| {
convert(ex_rates, currency, Currency::USD, amount_i64)
.inspect_err(|e| {
logger::error!("Currency conversion error: {:?}", e)
})
.ok()
})
})
.map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
.unwrap_or_default()
} else {
None
};
collected_values.payment_processed_amount_without_smart_retries_usd = amount_in_usd;
total_payment_processed_amount_without_smart_retries += amount;
total_payment_processed_amount_without_smart_retries_usd +=
amount_in_usd.unwrap_or(0);
}
if let Some(count) = collected_values.payment_processed_count_without_smart_retries {
total_payment_processed_count_without_smart_retries += count;
}
if let Some(count) = collected_values.failure_reason_count {
total_failure_reasons_count += count;
}
if let Some(count) = collected_values.failure_reason_count_without_smart_retries {
total_failure_reasons_count_without_smart_retries += count;
}
if let Some(savings) = collected_values.debit_routing_savings {
let savings_in_usd = if let Some(ex_rates) = ex_rates {
id.currency
.and_then(|currency| {
i64::try_from(savings)
.inspect_err(|e| {
logger::error!(
"Debit Routing savings conversion error: {:?}",
e
)
})
.ok()
.and_then(|savings_i64| {
convert(ex_rates, currency, Currency::USD, savings_i64)
.inspect_err(|e| {
logger::error!("Currency conversion error: {:?}", e)
})
.ok()
})
})
.map(|savings| (savings * rust_decimal::Decimal::new(100, 0)).to_u64())
.unwrap_or_default()
} else {
None
};
collected_values.debit_routing_savings_in_usd = savings_in_usd;
}
MetricsBucketResponse {
values: collected_values,
dimensions: id,
}
})
.collect();
Ok(PaymentsMetricsResponse {
query_data,
meta_data: [PaymentsAnalyticsMetadata {
total_payment_processed_amount: Some(total_payment_processed_amount),
total_payment_processed_amount_in_usd: if ex_rates.is_some() {
Some(total_payment_processed_amount_in_usd)
} else {
None
},
total_payment_processed_amount_without_smart_retries: Some(
total_payment_processed_amount_without_smart_retries,
),
total_payment_processed_amount_without_smart_retries_usd: if ex_rates.is_some() {
Some(total_payment_processed_amount_without_smart_retries_usd)
} else {
None
},
total_payment_processed_count: Some(total_payment_processed_count),
total_payment_processed_count_without_smart_retries: Some(
total_payment_processed_count_without_smart_retries,
),
total_failure_reasons_count: Some(total_failure_reasons_count),
total_failure_reasons_count_without_smart_retries: Some(
total_failure_reasons_count_without_smart_retries,
),
}],
})
}
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetPaymentFiltersRequest,
auth: &AuthInfo,
) -> AnalyticsResult<PaymentFiltersResponse> {
let mut res = PaymentFiltersResponse::default();
for dim in req.group_by_names {
let values = match pool {
AnalyticsProvider::Sqlx(pool) => {
get_payment_filter_for_dimension(dim, auth, &req.time_range, pool)
.await
}
AnalyticsProvider::Clickhouse(pool) => {
get_payment_filter_for_dimension(dim, auth, &req.time_range, pool)
.await
}
AnalyticsProvider::CombinedCkh(sqlx_poll, ckh_pool) => {
let ckh_result = get_payment_filter_for_dimension(
dim,
auth,
&req.time_range,
ckh_pool,
)
.await;
let sqlx_result = get_payment_filter_for_dimension(
dim,
auth,
&req.time_range,
sqlx_poll,
)
.await;
match (&sqlx_result, &ckh_result) {
(Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics filters")
},
_ => {}
};
ckh_result
}
AnalyticsProvider::CombinedSqlx(sqlx_poll, ckh_pool) => {
let ckh_result = get_payment_filter_for_dimension(
dim,
auth,
&req.time_range,
ckh_pool,
)
.await;
let sqlx_result = get_payment_filter_for_dimension(
dim,
auth,
&req.time_range,
sqlx_poll,
)
.await;
match (&sqlx_result, &ckh_result) {
(Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics filters")
},
_ => {}
};
sqlx_result
}
}
.change_context(AnalyticsError::UnknownError)?
.into_iter()
.filter_map(|fil: PaymentFilterRow| match dim {
PaymentDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()),
PaymentDimensions::PaymentStatus => fil.status.map(|i| i.as_ref().to_string()),
PaymentDimensions::Connector => fil.connector,
PaymentDimensions::AuthType => fil.authentication_type.map(|i| i.as_ref().to_string()),
PaymentDimensions::PaymentMethod => fil.payment_method,
PaymentDimensions::PaymentMethodType => fil.payment_method_type,
PaymentDimensions::ClientSource => fil.client_source,
PaymentDimensions::ClientVersion => fil.client_version,
PaymentDimensions::ProfileId => fil.profile_id,
PaymentDimensions::CardNetwork => fil.card_network,
PaymentDimensions::MerchantId => fil.merchant_id,
PaymentDimensions::CardLast4 => fil.card_last_4,
PaymentDimensions::CardIssuer => fil.card_issuer,
PaymentDimensions::ErrorReason => fil.error_reason,
PaymentDimensions::RoutingApproach => fil.routing_approach.map(|i| i.as_ref().to_string()),
PaymentDimensions::SignatureNetwork => fil.signature_network,
PaymentDimensions::IsIssuerRegulated => fil.is_issuer_regulated.map(|b| b.to_string()),
PaymentDimensions::IsDebitRouted => fil.is_debit_routed.map(|b| b.to_string())
})
.collect::<Vec<String>>();
res.query_data.push(FilterValue {
dimension: dim,
values,
})
}
Ok(res)
}
| {
"crate": "analytics",
"file": "crates/analytics/src/payments/core.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
file_analytics_1314261587866528033 | clm | file | // Repository: hyperswitch
// Crate: analytics
// File: crates/analytics/src/payment_intents/core.rs
// Contains: 0 structs, 1 enums
#![allow(dead_code)]
use std::collections::{HashMap, HashSet};
use api_models::analytics::{
payment_intents::{
MetricsBucketResponse, PaymentIntentDimensions, PaymentIntentMetrics,
PaymentIntentMetricsBucketIdentifier,
},
GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, PaymentIntentFilterValue,
PaymentIntentFiltersResponse, PaymentIntentsAnalyticsMetadata, PaymentIntentsMetricsResponse,
};
use bigdecimal::ToPrimitive;
use common_enums::Currency;
use common_utils::{errors::CustomResult, types::TimeRange};
use currency_conversion::{conversion::convert, types::ExchangeRates};
use error_stack::ResultExt;
use router_env::{
instrument, logger,
tracing::{self, Instrument},
};
use super::{
filters::{get_payment_intent_filter_for_dimension, PaymentIntentFilterRow},
metrics::PaymentIntentMetricRow,
sankey::{get_sankey_data, SankeyRow},
PaymentIntentMetricsAccumulator,
};
use crate::{
enums::AuthInfo,
errors::{AnalyticsError, AnalyticsResult},
metrics,
payment_intents::PaymentIntentMetricAccumulator,
AnalyticsProvider,
};
#[derive(Debug)]
pub enum TaskType {
MetricTask(
PaymentIntentMetrics,
CustomResult<
HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>,
AnalyticsError,
>,
),
}
#[instrument(skip_all)]
pub async fn get_sankey(
pool: &AnalyticsProvider,
auth: &AuthInfo,
req: TimeRange,
) -> AnalyticsResult<Vec<SankeyRow>> {
match pool {
AnalyticsProvider::Sqlx(_) => Err(AnalyticsError::NotImplemented(
"Sankey not implemented for sqlx",
))?,
AnalyticsProvider::Clickhouse(ckh_pool)
| AnalyticsProvider::CombinedCkh(_, ckh_pool)
| AnalyticsProvider::CombinedSqlx(_, ckh_pool) => {
let sankey_rows = get_sankey_data(ckh_pool, auth, &req)
.await
.change_context(AnalyticsError::UnknownError)?;
Ok(sankey_rows)
}
}
}
#[instrument(skip_all)]
pub async fn get_metrics(
pool: &AnalyticsProvider,
ex_rates: &Option<ExchangeRates>,
auth: &AuthInfo,
req: GetPaymentIntentMetricRequest,
) -> AnalyticsResult<PaymentIntentsMetricsResponse<MetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<
PaymentIntentMetricsBucketIdentifier,
PaymentIntentMetricsAccumulator,
> = HashMap::new();
let mut set = tokio::task::JoinSet::new();
for metric_type in req.metrics.iter().cloned() {
let req = req.clone();
let pool = pool.clone();
let task_span = tracing::debug_span!(
"analytics_payment_intents_metrics_query",
payment_metric = metric_type.as_ref()
);
// TODO: lifetime issues with joinset,
// can be optimized away if joinset lifetime requirements are relaxed
let auth_scoped = auth.to_owned();
set.spawn(
async move {
let data = pool
.get_payment_intent_metrics(
&metric_type,
&req.group_by_names.clone(),
&auth_scoped,
&req.filters,
req.time_series.map(|t| t.granularity),
&req.time_range,
)
.await
.change_context(AnalyticsError::UnknownError);
TaskType::MetricTask(metric_type, data)
}
.instrument(task_span),
);
}
while let Some(task_type) = set
.join_next()
.await
.transpose()
.change_context(AnalyticsError::UnknownError)?
{
match task_type {
TaskType::MetricTask(metric, data) => {
let data = data?;
let attributes = router_env::metric_attributes!(
("metric_type", metric.to_string()),
("source", pool.to_string()),
);
let value = u64::try_from(data.len());
if let Ok(val) = value {
metrics::BUCKETS_FETCHED.record(val, attributes);
logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val);
}
for (id, value) in data {
logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}");
let metrics_builder = metrics_accumulator.entry(id).or_default();
match metric {
PaymentIntentMetrics::SuccessfulSmartRetries
| PaymentIntentMetrics::SessionizedSuccessfulSmartRetries => {
metrics_builder
.successful_smart_retries
.add_metrics_bucket(&value)
}
PaymentIntentMetrics::TotalSmartRetries
| PaymentIntentMetrics::SessionizedTotalSmartRetries => metrics_builder
.total_smart_retries
.add_metrics_bucket(&value),
PaymentIntentMetrics::SmartRetriedAmount
| PaymentIntentMetrics::SessionizedSmartRetriedAmount => metrics_builder
.smart_retried_amount
.add_metrics_bucket(&value),
PaymentIntentMetrics::PaymentIntentCount
| PaymentIntentMetrics::SessionizedPaymentIntentCount => metrics_builder
.payment_intent_count
.add_metrics_bucket(&value),
PaymentIntentMetrics::PaymentsSuccessRate
| PaymentIntentMetrics::SessionizedPaymentsSuccessRate => metrics_builder
.payments_success_rate
.add_metrics_bucket(&value),
PaymentIntentMetrics::SessionizedPaymentProcessedAmount
| PaymentIntentMetrics::PaymentProcessedAmount => metrics_builder
.payment_processed_amount
.add_metrics_bucket(&value),
PaymentIntentMetrics::SessionizedPaymentsDistribution => metrics_builder
.payments_distribution
.add_metrics_bucket(&value),
}
}
logger::debug!(
"Analytics Accumulated Results: metric: {}, results: {:#?}",
metric,
metrics_accumulator
);
}
}
}
let mut success = 0;
let mut success_without_smart_retries = 0;
let mut total_smart_retried_amount = 0;
let mut total_smart_retried_amount_in_usd = 0;
let mut total_smart_retried_amount_without_smart_retries = 0;
let mut total_smart_retried_amount_without_smart_retries_in_usd = 0;
let mut total = 0;
let mut total_payment_processed_amount = 0;
let mut total_payment_processed_amount_in_usd = 0;
let mut total_payment_processed_count = 0;
let mut total_payment_processed_amount_without_smart_retries = 0;
let mut total_payment_processed_amount_without_smart_retries_in_usd = 0;
let mut total_payment_processed_count_without_smart_retries = 0;
let query_data: Vec<MetricsBucketResponse> = metrics_accumulator
.into_iter()
.map(|(id, val)| {
let mut collected_values = val.collect();
if let Some(success_count) = collected_values.successful_payments {
success += success_count;
}
if let Some(success_count) = collected_values.successful_payments_without_smart_retries
{
success_without_smart_retries += success_count;
}
if let Some(total_count) = collected_values.total_payments {
total += total_count;
}
if let Some(retried_amount) = collected_values.smart_retried_amount {
let amount_in_usd = if let Some(ex_rates) = ex_rates {
id.currency
.and_then(|currency| {
i64::try_from(retried_amount)
.inspect_err(|e| logger::error!("Amount conversion error: {:?}", e))
.ok()
.and_then(|amount_i64| {
convert(ex_rates, currency, Currency::USD, amount_i64)
.inspect_err(|e| {
logger::error!("Currency conversion error: {:?}", e)
})
.ok()
})
})
.map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
.unwrap_or_default()
} else {
None
};
collected_values.smart_retried_amount_in_usd = amount_in_usd;
total_smart_retried_amount += retried_amount;
total_smart_retried_amount_in_usd += amount_in_usd.unwrap_or(0);
}
if let Some(retried_amount) =
collected_values.smart_retried_amount_without_smart_retries
{
let amount_in_usd = if let Some(ex_rates) = ex_rates {
id.currency
.and_then(|currency| {
i64::try_from(retried_amount)
.inspect_err(|e| logger::error!("Amount conversion error: {:?}", e))
.ok()
.and_then(|amount_i64| {
convert(ex_rates, currency, Currency::USD, amount_i64)
.inspect_err(|e| {
logger::error!("Currency conversion error: {:?}", e)
})
.ok()
})
})
.map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
.unwrap_or_default()
} else {
None
};
collected_values.smart_retried_amount_without_smart_retries_in_usd = amount_in_usd;
total_smart_retried_amount_without_smart_retries += retried_amount;
total_smart_retried_amount_without_smart_retries_in_usd +=
amount_in_usd.unwrap_or(0);
}
if let Some(amount) = collected_values.payment_processed_amount {
let amount_in_usd = if let Some(ex_rates) = ex_rates {
id.currency
.and_then(|currency| {
i64::try_from(amount)
.inspect_err(|e| logger::error!("Amount conversion error: {:?}", e))
.ok()
.and_then(|amount_i64| {
convert(ex_rates, currency, Currency::USD, amount_i64)
.inspect_err(|e| {
logger::error!("Currency conversion error: {:?}", e)
})
.ok()
})
})
.map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
.unwrap_or_default()
} else {
None
};
collected_values.payment_processed_amount_in_usd = amount_in_usd;
total_payment_processed_amount_in_usd += amount_in_usd.unwrap_or(0);
total_payment_processed_amount += amount;
}
if let Some(count) = collected_values.payment_processed_count {
total_payment_processed_count += count;
}
if let Some(amount) = collected_values.payment_processed_amount_without_smart_retries {
let amount_in_usd = if let Some(ex_rates) = ex_rates {
id.currency
.and_then(|currency| {
i64::try_from(amount)
.inspect_err(|e| logger::error!("Amount conversion error: {:?}", e))
.ok()
.and_then(|amount_i64| {
convert(ex_rates, currency, Currency::USD, amount_i64)
.inspect_err(|e| {
logger::error!("Currency conversion error: {:?}", e)
})
.ok()
})
})
.map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
.unwrap_or_default()
} else {
None
};
collected_values.payment_processed_amount_without_smart_retries_in_usd =
amount_in_usd;
total_payment_processed_amount_without_smart_retries_in_usd +=
amount_in_usd.unwrap_or(0);
total_payment_processed_amount_without_smart_retries += amount;
}
if let Some(count) = collected_values.payment_processed_count_without_smart_retries {
total_payment_processed_count_without_smart_retries += count;
}
MetricsBucketResponse {
values: collected_values,
dimensions: id,
}
})
.collect();
let total_success_rate = match (success, total) {
(s, t) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
_ => None,
};
let total_success_rate_without_smart_retries = match (success_without_smart_retries, total) {
(s, t) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
_ => None,
};
Ok(PaymentIntentsMetricsResponse {
query_data,
meta_data: [PaymentIntentsAnalyticsMetadata {
total_success_rate,
total_success_rate_without_smart_retries,
total_smart_retried_amount: Some(total_smart_retried_amount),
total_smart_retried_amount_without_smart_retries: Some(
total_smart_retried_amount_without_smart_retries,
),
total_payment_processed_amount: Some(total_payment_processed_amount),
total_payment_processed_amount_without_smart_retries: Some(
total_payment_processed_amount_without_smart_retries,
),
total_smart_retried_amount_in_usd: if ex_rates.is_some() {
Some(total_smart_retried_amount_in_usd)
} else {
None
},
total_smart_retried_amount_without_smart_retries_in_usd: if ex_rates.is_some() {
Some(total_smart_retried_amount_without_smart_retries_in_usd)
} else {
None
},
total_payment_processed_amount_in_usd: if ex_rates.is_some() {
Some(total_payment_processed_amount_in_usd)
} else {
None
},
total_payment_processed_amount_without_smart_retries_in_usd: if ex_rates.is_some() {
Some(total_payment_processed_amount_without_smart_retries_in_usd)
} else {
None
},
total_payment_processed_count: Some(total_payment_processed_count),
total_payment_processed_count_without_smart_retries: Some(
total_payment_processed_count_without_smart_retries,
),
}],
})
}
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetPaymentIntentFiltersRequest,
merchant_id: &common_utils::id_type::MerchantId,
) -> AnalyticsResult<PaymentIntentFiltersResponse> {
let mut res = PaymentIntentFiltersResponse::default();
for dim in req.group_by_names {
let values = match pool {
AnalyticsProvider::Sqlx(pool) => {
get_payment_intent_filter_for_dimension(dim, merchant_id, &req.time_range, pool)
.await
}
AnalyticsProvider::Clickhouse(pool) => {
get_payment_intent_filter_for_dimension(dim, merchant_id, &req.time_range, pool)
.await
}
AnalyticsProvider::CombinedCkh(sqlx_poll, ckh_pool) => {
let ckh_result = get_payment_intent_filter_for_dimension(
dim,
merchant_id,
&req.time_range,
ckh_pool,
)
.await;
let sqlx_result = get_payment_intent_filter_for_dimension(
dim,
merchant_id,
&req.time_range,
sqlx_poll,
)
.await;
match (&sqlx_result, &ckh_result) {
(Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payment intents analytics filters")
},
_ => {}
};
ckh_result
}
AnalyticsProvider::CombinedSqlx(sqlx_poll, ckh_pool) => {
let ckh_result = get_payment_intent_filter_for_dimension(
dim,
merchant_id,
&req.time_range,
ckh_pool,
)
.await;
let sqlx_result = get_payment_intent_filter_for_dimension(
dim,
merchant_id,
&req.time_range,
sqlx_poll,
)
.await;
match (&sqlx_result, &ckh_result) {
(Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payment intents analytics filters")
},
_ => {}
};
sqlx_result
}
}
.change_context(AnalyticsError::UnknownError)?
.into_iter()
.filter_map(|fil: PaymentIntentFilterRow| match dim {
PaymentIntentDimensions::PaymentIntentStatus => fil.status.map(|i| i.as_ref().to_string()),
PaymentIntentDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()),
PaymentIntentDimensions::ProfileId => fil.profile_id,
PaymentIntentDimensions::Connector => fil.connector,
PaymentIntentDimensions::AuthType => fil.authentication_type.map(|i| i.as_ref().to_string()),
PaymentIntentDimensions::PaymentMethod => fil.payment_method,
PaymentIntentDimensions::PaymentMethodType => fil.payment_method_type,
PaymentIntentDimensions::CardNetwork => fil.card_network,
PaymentIntentDimensions::MerchantId => fil.merchant_id,
PaymentIntentDimensions::CardLast4 => fil.card_last_4,
PaymentIntentDimensions::CardIssuer => fil.card_issuer,
PaymentIntentDimensions::ErrorReason => fil.error_reason,
})
.collect::<Vec<String>>();
res.query_data.push(PaymentIntentFilterValue {
dimension: dim,
values,
})
}
Ok(res)
}
| {
"crate": "analytics",
"file": "crates/analytics/src/payment_intents/core.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 0,
"num_tables": null,
"score": null,
"total_crates": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.