repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/subscriptions/src/types/storage.rs | crates/subscriptions/src/types/storage.rs | pub mod invoice_sync;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/subscriptions/src/types/storage/invoice_sync.rs | crates/subscriptions/src/types/storage/invoice_sync.rs | use api_models::enums as api_enums;
use common_utils::id_type;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct InvoiceSyncTrackingData {
pub subscription_id: id_type::SubscriptionId,
pub invoice_id: id_type::InvoiceId,
pub merchant_id: id_type::MerchantId,
pub profile_id: id_type::ProfileId,
pub customer_id: id_type::CustomerId,
// connector_invoice_id is optional because in some cases (Trial/Future), the invoice might not have been created in the connector yet.
pub connector_invoice_id: Option<id_type::InvoiceId>,
pub connector_name: api_enums::Connector, // The connector to which the invoice belongs
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct InvoiceSyncRequest {
pub subscription_id: id_type::SubscriptionId,
pub invoice_id: id_type::InvoiceId,
pub merchant_id: id_type::MerchantId,
pub profile_id: id_type::ProfileId,
pub customer_id: id_type::CustomerId,
pub connector_invoice_id: Option<id_type::InvoiceId>,
pub connector_name: api_enums::Connector,
}
impl From<InvoiceSyncRequest> for InvoiceSyncTrackingData {
fn from(item: InvoiceSyncRequest) -> Self {
Self {
subscription_id: item.subscription_id,
invoice_id: item.invoice_id,
merchant_id: item.merchant_id,
profile_id: item.profile_id,
customer_id: item.customer_id,
connector_invoice_id: item.connector_invoice_id,
connector_name: item.connector_name,
}
}
}
impl InvoiceSyncRequest {
#[allow(clippy::too_many_arguments)]
pub fn new(
subscription_id: id_type::SubscriptionId,
invoice_id: id_type::InvoiceId,
merchant_id: id_type::MerchantId,
profile_id: id_type::ProfileId,
customer_id: id_type::CustomerId,
connector_invoice_id: Option<id_type::InvoiceId>,
connector_name: api_enums::Connector,
) -> Self {
Self {
subscription_id,
invoice_id,
merchant_id,
profile_id,
customer_id,
connector_invoice_id,
connector_name,
}
}
}
impl InvoiceSyncTrackingData {
#[allow(clippy::too_many_arguments)]
pub fn new(
subscription_id: id_type::SubscriptionId,
invoice_id: id_type::InvoiceId,
merchant_id: id_type::MerchantId,
profile_id: id_type::ProfileId,
customer_id: id_type::CustomerId,
connector_invoice_id: Option<id_type::InvoiceId>,
connector_name: api_enums::Connector,
) -> Self {
Self {
subscription_id,
invoice_id,
merchant_id,
profile_id,
customer_id,
connector_invoice_id,
connector_name,
}
}
}
#[derive(Debug, Clone)]
pub enum InvoiceSyncPaymentStatus {
PaymentSucceeded,
PaymentProcessing,
PaymentFailed,
}
impl From<common_enums::IntentStatus> for InvoiceSyncPaymentStatus {
fn from(value: common_enums::IntentStatus) -> Self {
match value {
common_enums::IntentStatus::Succeeded => Self::PaymentSucceeded,
common_enums::IntentStatus::Processing
| common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::RequiresPaymentMethod => Self::PaymentProcessing,
_ => Self::PaymentFailed,
}
}
}
impl From<InvoiceSyncPaymentStatus> for common_enums::connector_enums::InvoiceStatus {
fn from(value: InvoiceSyncPaymentStatus) -> Self {
match value {
InvoiceSyncPaymentStatus::PaymentSucceeded => Self::InvoicePaid,
InvoiceSyncPaymentStatus::PaymentProcessing => Self::PaymentPending,
InvoiceSyncPaymentStatus::PaymentFailed => Self::PaymentFailed,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/subscriptions/src/core/errors.rs | crates/subscriptions/src/core/errors.rs | pub use common_utils::errors::{CustomResult, ParsingError, ValidationError};
pub use hyperswitch_domain_models::{
api,
errors::api_error_response::{self, *},
};
pub type SubscriptionResult<T> = CustomResult<T, ApiErrorResponse>;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/subscriptions/src/core/subscription_handler.rs | crates/subscriptions/src/core/subscription_handler.rs | use std::str::FromStr;
use api_models::{
enums as api_enums,
subscription::{self as subscription_types, SubscriptionResponse},
};
use common_enums::connector_enums;
use common_utils::{consts, ext_traits::OptionExt};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
customer, merchant_connector_account,
platform::Platform,
router_response_types::{self, subscriptions as subscription_response_types},
subscription::{Subscription, SubscriptionStatus},
};
use masking::Secret;
use super::errors;
use crate::{
core::invoice_handler::InvoiceHandler,
errors::CustomResult,
helpers::{ForeignTryFrom, StorageErrorExt},
state::SubscriptionState as SessionState,
};
pub struct SubscriptionHandler<'a> {
pub state: &'a SessionState,
pub platform: &'a Platform,
}
impl<'a> SubscriptionHandler<'a> {
pub fn new(state: &'a SessionState, platform: &'a Platform) -> Self {
Self { state, platform }
}
#[allow(clippy::too_many_arguments)]
/// Helper function to create a subscription entry in the database.
pub async fn create_subscription_entry(
&self,
subscription_id: common_utils::id_type::SubscriptionId,
customer_id: &common_utils::id_type::CustomerId,
billing_processor: connector_enums::Connector,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
merchant_reference_id: Option<String>,
profile: &hyperswitch_domain_models::business_profile::Profile,
plan_id: Option<String>,
item_price_id: Option<String>,
) -> errors::SubscriptionResult<SubscriptionWithHandler<'_>> {
let store = self.state.store.clone();
let db = store.as_ref();
let mut subscription = Subscription {
id: subscription_id,
status: SubscriptionStatus::Created.to_string(),
billing_processor: Some(billing_processor.to_string()),
payment_method_id: None,
merchant_connector_id: Some(merchant_connector_id),
client_secret: None,
connector_subscription_id: None,
merchant_id: self.platform.get_processor().get_account().get_id().clone(),
customer_id: customer_id.clone(),
metadata: None,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
profile_id: profile.get_id().clone(),
merchant_reference_id,
plan_id,
item_price_id,
};
subscription.generate_and_set_client_secret();
let merchant_key_store = self.platform.get_processor().get_key_store();
let new_subscription = db
.insert_subscription_entry(merchant_key_store, subscription)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("subscriptions: unable to insert subscription entry to database")?;
Ok(SubscriptionWithHandler {
handler: self,
subscription: new_subscription,
merchant_account: self.platform.get_processor().get_account().clone(),
})
}
/// Helper function to find and validate customer.
pub async fn find_customer(
state: &SessionState,
platform: &Platform,
customer_id: &common_utils::id_type::CustomerId,
) -> errors::SubscriptionResult<customer::Customer> {
let merchant_key_store = platform.get_processor().get_key_store();
let merchant_id = platform.get_processor().get_account().get_id();
state
.store
.find_customer_by_customer_id_merchant_id(
customer_id,
merchant_id,
merchant_key_store,
platform.get_processor().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("subscriptions: unable to fetch customer from database")
}
pub async fn update_connector_customer_id_in_customer(
state: &SessionState,
platform: &Platform,
merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
customer: &customer::Customer,
customer_create_response: Option<router_response_types::ConnectorCustomerResponseData>,
) -> errors::SubscriptionResult<customer::Customer> {
match customer_create_response {
Some(customer_response) => {
match customer::update_connector_customer_in_customers(
merchant_connector_id.get_string_repr(),
Some(customer),
Some(customer_response.connector_customer_id),
)
.await
{
Some(customer_update) => {
Self::update_customer(state, platform, customer.clone(), customer_update)
.await
.attach_printable(
"Failed to update customer with connector customer ID",
)
}
None => Ok(customer.clone()),
}
}
None => Ok(customer.clone()),
}
}
pub async fn update_customer(
state: &SessionState,
platform: &Platform,
customer: customer::Customer,
customer_update: customer::CustomerUpdate,
) -> errors::SubscriptionResult<customer::Customer> {
let merchant_key_store = platform.get_processor().get_key_store();
let merchant_id = platform.get_processor().get_account().get_id();
let db = state.store.as_ref();
let updated_customer = db
.update_customer_by_customer_id_merchant_id(
customer.customer_id.clone(),
merchant_id.clone(),
customer,
customer_update,
merchant_key_store,
platform.get_processor().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("subscriptions: unable to update customer entry in database")?;
Ok(updated_customer)
}
/// Helper function to find business profile.
pub async fn find_business_profile(
state: &SessionState,
platform: &Platform,
profile_id: &common_utils::id_type::ProfileId,
) -> errors::SubscriptionResult<hyperswitch_domain_models::business_profile::Profile> {
let merchant_key_store = platform.get_processor().get_key_store();
state
.store
.find_business_profile_by_profile_id(merchant_key_store, profile_id)
.await
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_string(),
})
}
pub async fn find_and_validate_subscription(
&self,
client_secret: &hyperswitch_domain_models::subscription::ClientSecret,
) -> errors::SubscriptionResult<()> {
let subscription_id = client_secret.get_subscription_id()?;
let key_store = self.platform.get_processor().get_key_store();
let subscription = self
.state
.store
.find_by_merchant_id_subscription_id(
key_store,
self.platform.get_processor().get_account().get_id(),
subscription_id.to_string(),
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: format!("Subscription not found for id: {subscription_id}"),
})
.attach_printable("Unable to find subscription")?;
self.validate_client_secret(client_secret, &subscription)?;
Ok(())
}
pub fn validate_client_secret(
&self,
client_secret: &hyperswitch_domain_models::subscription::ClientSecret,
subscription: &Subscription,
) -> errors::SubscriptionResult<()> {
let stored_client_secret = subscription
.client_secret
.clone()
.get_required_value("client_secret")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "client_secret",
})
.attach_printable("client secret not found in db")?;
if client_secret.to_string() != stored_client_secret {
Err(errors::ApiErrorResponse::ClientSecretInvalid.into())
} else {
let current_timestamp = common_utils::date_time::now();
let session_expiry = subscription
.created_at
.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));
if current_timestamp > session_expiry {
Err(errors::ApiErrorResponse::ClientSecretExpired.into())
} else {
Ok(())
}
}
}
pub async fn find_subscription(
&self,
subscription_id: common_utils::id_type::SubscriptionId,
) -> errors::SubscriptionResult<SubscriptionWithHandler<'_>> {
let subscription = self
.state
.store
.find_by_merchant_id_subscription_id(
self.platform.get_processor().get_key_store(),
self.platform.get_processor().get_account().get_id(),
subscription_id.get_string_repr().to_string().clone(),
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: format!(
"subscription not found for id: {}",
subscription_id.get_string_repr()
),
})?;
Ok(SubscriptionWithHandler {
handler: self,
subscription,
merchant_account: self.platform.get_processor().get_account().clone(),
})
}
pub async fn list_subscriptions_by_profile_id(
&self,
profile_id: &common_utils::id_type::ProfileId,
limit: Option<i64>,
offset: Option<i64>,
) -> errors::SubscriptionResult<Vec<Subscription>> {
let subscriptions = self
.state
.store
.list_by_merchant_id_profile_id(
self.platform.get_processor().get_key_store(),
self.platform.get_processor().get_account().get_id(),
profile_id,
limit,
offset,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("subscriptions: unable to fetch subscriptions from database")?;
Ok(subscriptions)
}
}
pub struct SubscriptionWithHandler<'a> {
pub handler: &'a SubscriptionHandler<'a>,
pub subscription: Subscription,
pub merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount,
}
impl SubscriptionWithHandler<'_> {
pub fn generate_response(
&self,
invoice: &hyperswitch_domain_models::invoice::Invoice,
payment_response: &subscription_types::PaymentResponseData,
status: subscription_response_types::SubscriptionStatus,
) -> errors::SubscriptionResult<subscription_types::ConfirmSubscriptionResponse> {
Ok(subscription_types::ConfirmSubscriptionResponse {
id: self.subscription.id.clone(),
merchant_reference_id: self.subscription.merchant_reference_id.clone(),
status: common_enums::SubscriptionStatus::from(status),
plan_id: self.subscription.plan_id.clone(),
profile_id: self.subscription.profile_id.to_owned(),
payment: Some(payment_response.clone()),
customer_id: Some(self.subscription.customer_id.clone()),
item_price_id: self.subscription.item_price_id.clone(),
coupon: None,
billing_processor_subscription_id: self.subscription.connector_subscription_id.clone(),
invoice: Some(subscription_types::Invoice::foreign_try_from(invoice)?),
})
}
pub fn to_subscription_response(
subscription: &Subscription,
payment: Option<subscription_types::PaymentResponseData>,
invoice: Option<&hyperswitch_domain_models::invoice::Invoice>,
) -> errors::SubscriptionResult<SubscriptionResponse> {
Ok(SubscriptionResponse::new(
subscription.id.clone(),
subscription.merchant_reference_id.clone(),
common_enums::SubscriptionStatus::from_str(&subscription.status)
.unwrap_or(common_enums::SubscriptionStatus::Created),
subscription.plan_id.clone(),
subscription.item_price_id.clone(),
subscription.profile_id.to_owned(),
subscription.merchant_id.to_owned(),
subscription.client_secret.clone().map(Secret::new),
subscription.customer_id.clone(),
payment,
invoice
.map(
|invoice| -> errors::SubscriptionResult<subscription_types::Invoice> {
subscription_types::Invoice::foreign_try_from(invoice)
},
)
.transpose()?,
))
}
pub async fn update_subscription(
&mut self,
subscription_update: hyperswitch_domain_models::subscription::SubscriptionUpdate,
) -> errors::SubscriptionResult<()> {
let db = self.handler.state.store.as_ref();
let updated_subscription = db
.update_subscription_entry(
self.handler.platform.get_processor().get_key_store(),
self.handler.platform.get_processor().get_account().get_id(),
self.subscription.id.get_string_repr().to_string(),
subscription_update,
)
.await
.change_context(errors::ApiErrorResponse::SubscriptionError {
operation: "Subscription Update".to_string(),
})
.attach_printable("subscriptions: unable to update subscription entry in database")?;
self.subscription = updated_subscription;
Ok(())
}
pub fn get_invoice_handler(
&self,
profile: hyperswitch_domain_models::business_profile::Profile,
) -> InvoiceHandler {
InvoiceHandler {
subscription: self.subscription.clone(),
merchant_account: self.merchant_account.clone(),
profile,
merchant_key_store: self
.handler
.platform
.get_processor()
.get_key_store()
.clone(),
}
}
pub async fn get_mca(
&mut self,
connector_name: &str,
) -> CustomResult<merchant_connector_account::MerchantConnectorAccount, errors::ApiErrorResponse>
{
let db = self.handler.state.store.as_ref();
match &self.subscription.merchant_connector_id {
Some(merchant_connector_id) => {
#[cfg(feature = "v1")]
{
db.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
self.handler.platform.get_processor().get_account().get_id(),
merchant_connector_id,
self.handler.platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)
}
}
None => {
// Fallback to profile-based lookup when merchant_connector_id is not set
#[cfg(feature = "v1")]
{
db.find_merchant_connector_account_by_profile_id_connector_name(
&self.subscription.profile_id,
connector_name,
self.handler.platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: format!(
"profile_id {} and connector_name {connector_name}",
self.subscription.profile_id.get_string_repr()
),
},
)
}
}
}
}
}
impl ForeignTryFrom<&hyperswitch_domain_models::invoice::Invoice> for subscription_types::Invoice {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(
invoice: &hyperswitch_domain_models::invoice::Invoice,
) -> Result<Self, Self::Error> {
Ok(Self {
id: invoice.id.clone(),
subscription_id: invoice.subscription_id.clone(),
merchant_id: invoice.merchant_id.clone(),
profile_id: invoice.profile_id.clone(),
merchant_connector_id: invoice.merchant_connector_id.clone(),
payment_intent_id: invoice.payment_intent_id.clone(),
payment_method_id: invoice.payment_method_id.clone(),
customer_id: invoice.customer_id.clone(),
amount: invoice.amount,
currency: api_enums::Currency::from_str(invoice.currency.as_str())
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "currency",
})
.attach_printable(format!(
"unable to parse currency name {currency:?}",
currency = invoice.currency
))?,
status: invoice.status.clone(),
billing_processor_invoice_id: invoice
.connector_invoice_id
.as_ref()
.map(|id| id.get_string_repr().to_string()),
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/subscriptions/src/core/payments_api_client.rs | crates/subscriptions/src/core/payments_api_client.rs | use api_models::subscription as subscription_types;
use common_utils::{ext_traits::BytesExt, request as services};
use error_stack::ResultExt;
use hyperswitch_interfaces::api_client as api;
use crate::{core::errors, helpers, state::SubscriptionState as SessionState};
pub struct PaymentsApiClient;
#[derive(Debug, serde::Deserialize)]
pub struct ErrorResponse {
error: ErrorResponseDetails,
}
#[derive(Debug, serde::Deserialize)]
pub struct ErrorResponseDetails {
#[serde(rename = "type")]
error_type: Option<String>,
code: String,
message: String,
}
impl PaymentsApiClient {
fn get_internal_auth_headers(
state: &SessionState,
merchant_id: &str,
profile_id: &str,
) -> Vec<(String, masking::Maskable<String>)> {
vec![
(
helpers::X_INTERNAL_API_KEY.to_string(),
masking::Maskable::Masked(
state
.conf
.internal_merchant_id_profile_id_auth
.internal_api_key
.clone(),
),
),
(
helpers::X_TENANT_ID.to_string(),
masking::Maskable::Normal(state.tenant.tenant_id.get_string_repr().to_string()),
),
(
helpers::X_MERCHANT_ID.to_string(),
masking::Maskable::Normal(merchant_id.to_string()),
),
(
helpers::X_PROFILE_ID.to_string(),
masking::Maskable::Normal(profile_id.to_string()),
),
]
}
/// Generic method to handle payment API calls with different HTTP methods and URL patterns
async fn make_payment_api_call(
state: &SessionState,
method: services::Method,
url: String,
request_body: Option<common_utils::request::RequestContent>,
operation_name: &str,
merchant_id: &str,
profile_id: &str,
) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let subscription_error = errors::ApiErrorResponse::SubscriptionError {
operation: operation_name.to_string(),
};
let headers = Self::get_internal_auth_headers(state, merchant_id, profile_id);
let mut request_builder = services::RequestBuilder::new()
.method(method)
.url(&url)
.headers(headers);
// Add request body only if provided (for POST requests)
if let Some(body) = request_body {
request_builder = request_builder.set_body(body);
}
let request = request_builder.build();
let response = api::call_connector_api(state, request, "Subscription Payments")
.await
.change_context(subscription_error.clone())?;
match response {
Ok(res) => {
let api_response: subscription_types::PaymentResponseData = res
.response
.parse_struct(std::any::type_name::<subscription_types::PaymentResponseData>())
.change_context(subscription_error)?;
Ok(api_response)
}
Err(err) => {
let error_response: ErrorResponse = err
.response
.parse_struct(std::any::type_name::<ErrorResponse>())
.change_context(subscription_error)?;
Err(errors::ApiErrorResponse::ExternalConnectorError {
code: error_response.error.code,
message: error_response.error.message,
connector: "payments_microservice".to_string(),
status_code: err.status_code,
reason: error_response.error.error_type,
}
.into())
}
}
}
pub async fn create_cit_payment(
state: &SessionState,
request: subscription_types::CreatePaymentsRequestData,
merchant_id: &str,
profile_id: &str,
) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let base_url = &state.conf.internal_services.payments_base_url;
let url = format!("{}/payments", base_url);
Self::make_payment_api_call(
state,
services::Method::Post,
url,
Some(common_utils::request::RequestContent::Json(Box::new(
request,
))),
"Create Payment",
merchant_id,
profile_id,
)
.await
}
pub async fn create_and_confirm_payment(
state: &SessionState,
request: subscription_types::CreateAndConfirmPaymentsRequestData,
merchant_id: &str,
profile_id: &str,
) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let base_url = &state.conf.internal_services.payments_base_url;
let url = format!("{}/payments", base_url);
Self::make_payment_api_call(
state,
services::Method::Post,
url,
Some(common_utils::request::RequestContent::Json(Box::new(
request,
))),
"Create And Confirm Payment",
merchant_id,
profile_id,
)
.await
}
pub async fn confirm_payment(
state: &SessionState,
request: subscription_types::ConfirmPaymentsRequestData,
payment_id: String,
merchant_id: &str,
profile_id: &str,
) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let base_url = &state.conf.internal_services.payments_base_url;
let url = format!("{}/payments/{}/confirm", base_url, payment_id);
Self::make_payment_api_call(
state,
services::Method::Post,
url,
Some(common_utils::request::RequestContent::Json(Box::new(
request,
))),
"Confirm Payment",
merchant_id,
profile_id,
)
.await
}
pub async fn sync_payment(
state: &SessionState,
payment_id: String,
merchant_id: &str,
profile_id: &str,
) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let base_url = &state.conf.internal_services.payments_base_url;
let url = format!("{}/payments/{}", base_url, payment_id);
Self::make_payment_api_call(
state,
services::Method::Get,
url,
None,
"Sync Payment",
merchant_id,
profile_id,
)
.await
}
pub async fn create_mit_payment(
state: &SessionState,
request: subscription_types::CreateMitPaymentRequestData,
merchant_id: &str,
profile_id: &str,
) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let base_url = &state.conf.internal_services.payments_base_url;
let url = format!("{}/payments", base_url);
Self::make_payment_api_call(
state,
services::Method::Post,
url,
Some(common_utils::request::RequestContent::Json(Box::new(
request,
))),
"Create MIT Payment",
merchant_id,
profile_id,
)
.await
}
pub async fn update_payment(
state: &SessionState,
request: subscription_types::CreatePaymentsRequestData,
payment_id: String,
merchant_id: &str,
profile_id: &str,
) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let base_url = &state.conf.internal_services.payments_base_url;
let url = format!("{}/payments/{}", base_url, payment_id);
Self::make_payment_api_call(
state,
services::Method::Post,
url,
Some(common_utils::request::RequestContent::Json(Box::new(
request,
))),
"Update Payment",
merchant_id,
profile_id,
)
.await
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/subscriptions/src/core/invoice_handler.rs | crates/subscriptions/src/core/invoice_handler.rs | use api_models::{
enums as api_enums,
mandates::RecurringDetails,
subscription::{self as subscription_types},
};
use common_enums::connector_enums;
use common_utils::{pii, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::router_response_types::subscriptions as subscription_response_types;
use masking::PeekInterface;
use super::errors;
use crate::{
core::payments_api_client, state::SubscriptionState as SessionState,
types::storage as storage_types, workflows::invoice_sync as invoice_sync_workflow,
};
pub struct InvoiceHandler {
pub subscription: hyperswitch_domain_models::subscription::Subscription,
pub merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount,
pub profile: hyperswitch_domain_models::business_profile::Profile,
pub merchant_key_store: hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
}
#[allow(clippy::todo)]
impl InvoiceHandler {
pub fn new(
subscription: hyperswitch_domain_models::subscription::Subscription,
merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount,
profile: hyperswitch_domain_models::business_profile::Profile,
merchant_key_store: hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
) -> Self {
Self {
subscription,
merchant_account,
profile,
merchant_key_store,
}
}
#[allow(clippy::too_many_arguments)]
pub async fn create_invoice_entry(
&self,
state: &SessionState,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
payment_intent_id: Option<common_utils::id_type::PaymentId>,
amount: MinorUnit,
currency: common_enums::Currency,
status: connector_enums::InvoiceStatus,
provider_name: connector_enums::Connector,
metadata: Option<pii::SecretSerdeValue>,
connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
) -> errors::SubscriptionResult<hyperswitch_domain_models::invoice::Invoice> {
let invoice_new = hyperswitch_domain_models::invoice::Invoice::to_invoice(
self.subscription.id.to_owned(),
self.subscription.merchant_id.to_owned(),
self.subscription.profile_id.to_owned(),
merchant_connector_id,
payment_intent_id,
self.subscription.payment_method_id.clone(),
self.subscription.customer_id.to_owned(),
amount,
currency.to_string(),
status,
provider_name,
metadata,
connector_invoice_id,
);
let invoice = state
.store
.insert_invoice_entry(&self.merchant_key_store, invoice_new)
.await
.change_context(errors::ApiErrorResponse::SubscriptionError {
operation: "Create Invoice".to_string(),
})
.attach_printable("invoices: unable to insert invoice entry to database")?;
Ok(invoice)
}
pub async fn update_invoice(
&self,
state: &SessionState,
invoice_id: common_utils::id_type::InvoiceId,
update_request: hyperswitch_domain_models::invoice::InvoiceUpdateRequest,
) -> errors::SubscriptionResult<hyperswitch_domain_models::invoice::Invoice> {
let update_invoice: hyperswitch_domain_models::invoice::InvoiceUpdate =
update_request.into();
state
.store
.update_invoice_entry(
&self.merchant_key_store,
invoice_id.get_string_repr().to_string(),
update_invoice,
)
.await
.change_context(errors::ApiErrorResponse::SubscriptionError {
operation: "Invoice Update".to_string(),
})
.attach_printable("invoices: unable to update invoice entry in database")
}
pub fn get_amount_and_currency(
request: (Option<MinorUnit>, Option<api_enums::Currency>),
invoice_details: Option<subscription_response_types::SubscriptionInvoiceData>,
) -> (MinorUnit, api_enums::Currency) {
// Use request amount and currency if provided, else fallback to invoice details from connector response
request.0.zip(request.1).unwrap_or(
invoice_details
.clone()
.map(|invoice| (invoice.total, invoice.currency_code))
.unwrap_or((MinorUnit::new(0), api_enums::Currency::default())),
) // Default to 0 and a default currency if not provided
}
pub async fn create_payment_with_confirm_false(
&self,
state: &SessionState,
request: &subscription_types::CreateSubscriptionRequest,
amount: MinorUnit,
currency: api_enums::Currency,
) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let payment_details = &request.payment_details;
let payment_request = subscription_types::CreatePaymentsRequestData {
amount,
currency,
customer_id: Some(self.subscription.customer_id.clone()),
billing: request.billing.clone(),
shipping: request.shipping.clone(),
profile_id: Some(self.profile.get_id().clone()),
setup_future_usage: payment_details.setup_future_usage,
return_url: Some(payment_details.return_url.clone()),
capture_method: payment_details.capture_method,
authentication_type: payment_details.authentication_type,
};
payments_api_client::PaymentsApiClient::create_cit_payment(
state,
payment_request,
self.merchant_account.get_id().get_string_repr(),
self.profile.get_id().get_string_repr(),
)
.await
}
pub async fn get_payment_details(
&self,
state: &SessionState,
payment_id: common_utils::id_type::PaymentId,
) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
payments_api_client::PaymentsApiClient::sync_payment(
state,
payment_id.get_string_repr().to_string(),
self.merchant_account.get_id().get_string_repr(),
self.profile.get_id().get_string_repr(),
)
.await
}
pub async fn create_and_confirm_payment(
&self,
state: &SessionState,
request: &subscription_types::CreateAndConfirmSubscriptionRequest,
amount: MinorUnit,
currency: common_enums::Currency,
) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let payment_details = &request.payment_details;
let payment_request = subscription_types::CreateAndConfirmPaymentsRequestData {
amount,
currency,
confirm: true,
customer_id: Some(self.subscription.customer_id.clone()),
billing: request.get_billing_address(),
shipping: request.shipping.clone(),
profile_id: Some(self.profile.get_id().clone()),
setup_future_usage: payment_details
.payment_method_id
.is_none()
.then_some(payment_details.setup_future_usage)
.flatten(),
return_url: payment_details.return_url.clone(),
capture_method: payment_details.capture_method,
authentication_type: payment_details.authentication_type,
payment_method: payment_details.payment_method,
payment_method_type: payment_details.payment_method_type,
payment_method_data: payment_details.payment_method_data.clone(),
customer_acceptance: payment_details.customer_acceptance.clone(),
payment_type: payment_details.payment_type,
recurring_details: payment_details
.payment_method_id
.as_ref()
.map(|id| RecurringDetails::PaymentMethodId(id.peek().clone())),
off_session: Some(payment_details.payment_method_id.is_some()),
};
payments_api_client::PaymentsApiClient::create_and_confirm_payment(
state,
payment_request,
self.merchant_account.get_id().get_string_repr(),
self.profile.get_id().get_string_repr(),
)
.await
}
pub async fn confirm_payment(
&self,
state: &SessionState,
payment_id: common_utils::id_type::PaymentId,
request: &subscription_types::ConfirmSubscriptionRequest,
) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let payment_details = &request.payment_details;
let cit_payment_request = subscription_types::ConfirmPaymentsRequestData {
billing: request.get_billing_address(),
shipping: request.payment_details.shipping.clone(),
profile_id: Some(self.profile.get_id().clone()),
payment_method: payment_details.payment_method,
payment_method_type: payment_details.payment_method_type,
payment_method_data: payment_details.payment_method_data.clone(),
customer_acceptance: payment_details.customer_acceptance.clone(),
payment_type: payment_details.payment_type,
payment_token: payment_details.payment_token.clone(),
};
payments_api_client::PaymentsApiClient::confirm_payment(
state,
cit_payment_request,
payment_id.get_string_repr().to_string(),
self.merchant_account.get_id().get_string_repr(),
self.profile.get_id().get_string_repr(),
)
.await
}
pub async fn get_latest_invoice(
&self,
state: &SessionState,
) -> errors::SubscriptionResult<hyperswitch_domain_models::invoice::Invoice> {
state
.store
.get_latest_invoice_for_subscription(
&self.merchant_key_store,
self.subscription.id.get_string_repr().to_string(),
)
.await
.change_context(errors::ApiErrorResponse::SubscriptionError {
operation: "Get Latest Invoice".to_string(),
})
.attach_printable("invoices: unable to get latest invoice from database")
}
pub async fn get_invoice_by_id(
&self,
state: &SessionState,
invoice_id: common_utils::id_type::InvoiceId,
) -> errors::SubscriptionResult<hyperswitch_domain_models::invoice::Invoice> {
state
.store
.find_invoice_by_invoice_id(
&self.merchant_key_store,
invoice_id.get_string_repr().to_string(),
)
.await
.change_context(errors::ApiErrorResponse::SubscriptionError {
operation: "Get Invoice by ID".to_string(),
})
.attach_printable("invoices: unable to get invoice by id from database")
}
pub async fn find_invoice_by_subscription_id_connector_invoice_id(
&self,
state: &SessionState,
subscription_id: common_utils::id_type::SubscriptionId,
connector_invoice_id: common_utils::id_type::InvoiceId,
) -> errors::SubscriptionResult<Option<hyperswitch_domain_models::invoice::Invoice>> {
state
.store
.find_invoice_by_subscription_id_connector_invoice_id(
&self.merchant_key_store,
subscription_id.get_string_repr().to_string(),
connector_invoice_id,
)
.await
.change_context(errors::ApiErrorResponse::SubscriptionError {
operation: "Get Invoice by Subscription ID and Connector Invoice ID".to_string(),
})
.attach_printable("invoices: unable to get invoice by subscription id and connector invoice id from database")
}
pub async fn create_invoice_sync_job(
&self,
state: &SessionState,
invoice: &hyperswitch_domain_models::invoice::Invoice,
connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
connector_name: connector_enums::Connector,
) -> errors::SubscriptionResult<()> {
let request = storage_types::invoice_sync::InvoiceSyncRequest::new(
self.subscription.id.to_owned(),
invoice.id.to_owned(),
self.subscription.merchant_id.to_owned(),
self.subscription.profile_id.to_owned(),
self.subscription.customer_id.to_owned(),
connector_invoice_id,
connector_name,
);
invoice_sync_workflow::create_invoice_sync_job(state, request)
.await
.attach_printable("invoices: unable to create invoice sync job in database")?;
Ok(())
}
pub async fn create_mit_payment(
&self,
state: &SessionState,
amount: MinorUnit,
currency: common_enums::Currency,
payment_method_id: &str,
) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let mit_payment_request = subscription_types::CreateMitPaymentRequestData {
amount,
currency,
confirm: true,
customer_id: Some(self.subscription.customer_id.clone()),
recurring_details: Some(RecurringDetails::PaymentMethodId(
payment_method_id.to_owned(),
)),
off_session: Some(true),
profile_id: Some(self.profile.get_id().clone()),
};
payments_api_client::PaymentsApiClient::create_mit_payment(
state,
mit_payment_request,
self.merchant_account.get_id().get_string_repr(),
self.profile.get_id().get_string_repr(),
)
.await
}
pub async fn update_payment(
&self,
state: &SessionState,
amount: MinorUnit,
currency: common_enums::Currency,
payment_id: common_utils::id_type::PaymentId,
) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let payment_update_request = subscription_types::CreatePaymentsRequestData {
amount,
currency,
customer_id: None,
billing: None,
shipping: None,
profile_id: None,
setup_future_usage: None,
return_url: None,
capture_method: None,
authentication_type: None,
};
payments_api_client::PaymentsApiClient::update_payment(
state,
payment_update_request,
payment_id.get_string_repr().to_string(),
self.merchant_account.get_id().get_string_repr(),
self.profile.get_id().get_string_repr(),
)
.await
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/subscriptions/src/core/billing_processor_handler.rs | crates/subscriptions/src/core/billing_processor_handler.rs | use std::str::FromStr;
use api_models::subscription as subscription_types;
use common_enums::{connector_enums, CallConnectorAction};
use common_utils::{ext_traits::ValueExt, pii};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
errors::api_error_response as errors,
router_data_v2::flow_common_types::{
GetSubscriptionEstimateData, GetSubscriptionItemPricesData, GetSubscriptionItemsData,
InvoiceRecordBackData, SubscriptionCancelData, SubscriptionCreateData,
SubscriptionCustomerData, SubscriptionPauseData, SubscriptionResumeData,
},
router_request_types::{
revenue_recovery::InvoiceRecordBackRequest, subscriptions as subscription_request_types,
ConnectorCustomerData,
},
router_response_types::{
revenue_recovery::InvoiceRecordBackResponse, subscriptions as subscription_response_types,
ConnectorCustomerResponseData, PaymentsResponseData,
},
};
use hyperswitch_interfaces::{
api_client, configs::MerchantConnectorAccountType, connector_integration_interface,
};
use crate::{errors::SubscriptionResult, state::SubscriptionState as SessionState};
pub struct BillingHandler {
pub auth_type: hyperswitch_domain_models::router_data::ConnectorAuthType,
pub connector_name: connector_enums::Connector,
pub connector_enum: connector_integration_interface::ConnectorEnum,
pub connector_params: hyperswitch_domain_models::connector_endpoints::ConnectorParams,
pub connector_metadata: Option<pii::SecretSerdeValue>,
pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
}
#[allow(clippy::todo)]
impl BillingHandler {
pub async fn create(
state: &SessionState,
merchant_account: &hyperswitch_domain_models::merchant_account::MerchantAccount,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
profile: hyperswitch_domain_models::business_profile::Profile,
) -> SubscriptionResult<Self> {
let merchant_connector_id = profile.get_billing_processor_id()?;
let billing_processor_mca = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
merchant_account.get_id(),
&merchant_connector_id,
key_store,
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
})?;
let connector_name = billing_processor_mca.connector_name.clone();
let auth_type: hyperswitch_domain_models::router_data::ConnectorAuthType =
MerchantConnectorAccountType::DbVal(Box::new(billing_processor_mca.clone()))
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_account_details".to_string(),
expected_format: "auth_type and api_key".to_string(),
})?;
let connector_enum = state
.connector_converter
.get_connector_enum_by_name(&connector_name)
.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
.attach_printable(
"invalid connector name received in billing merchant connector account",
)?;
let connector_data = connector_enums::Connector::from_str(connector_name.as_str())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!("unable to parse connector name {connector_name:?}"))?;
let connector_params =
hyperswitch_domain_models::connector_endpoints::Connectors::get_connector_params(
&state.conf.connectors,
connector_data,
)
.change_context(errors::ApiErrorResponse::ConfigNotFound)
.attach_printable(format!(
"cannot find connector params for this connector {connector_name} in this flow",
))?;
Ok(Self {
auth_type,
connector_enum,
connector_name: connector_data,
connector_params,
connector_metadata: billing_processor_mca.metadata.clone(),
merchant_connector_id,
})
}
pub async fn create_customer_on_connector(
&self,
state: &SessionState,
customer: hyperswitch_domain_models::customer::Customer,
customer_id: common_utils::id_type::CustomerId,
billing_address: Option<api_models::payments::Address>,
payment_method_data: Option<api_models::payments::PaymentMethodData>,
) -> SubscriptionResult<Option<ConnectorCustomerResponseData>> {
let connector_customer_map = customer.get_connector_customer_map();
if connector_customer_map.contains_key(&self.merchant_connector_id) {
// Customer already exists on the connector, no need to create again
return Ok(None);
}
let customer_req = ConnectorCustomerData {
email: customer.email.clone().map(pii::Email::from),
payment_method_data: payment_method_data.clone().map(|pmd| pmd.into()),
description: None,
phone: None,
name: None,
preprocessing_id: None,
split_payments: None,
setup_future_usage: None,
customer_acceptance: None,
customer_id: Some(customer_id.clone()),
billing_address: billing_address
.as_ref()
.and_then(|add| add.address.clone())
.and_then(|addr| addr.into()),
};
let router_data = self.build_router_data(
state,
customer_req,
SubscriptionCustomerData {
connector_meta_data: self.connector_metadata.clone(),
},
)?;
let connector_integration = self.connector_enum.get_connector_integration();
let response = Box::pin(self.call_connector(
state,
router_data,
"create customer on connector",
connector_integration,
))
.await?;
match response {
Ok(response_data) => match response_data {
PaymentsResponseData::ConnectorCustomerResponse(customer_response) => {
Ok(Some(customer_response))
}
_ => Err(errors::ApiErrorResponse::SubscriptionError {
operation: "Subscription Customer Create".to_string(),
}
.into()),
},
Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: self.connector_name.to_string(),
status_code: err.status_code,
reason: err.reason,
}
.into()),
}
}
pub async fn create_subscription_on_connector(
&self,
state: &SessionState,
subscription: hyperswitch_domain_models::subscription::Subscription,
item_price_id: Option<String>,
billing_address: Option<api_models::payments::Address>,
) -> SubscriptionResult<subscription_response_types::SubscriptionCreateResponse> {
let subscription_item = subscription_request_types::SubscriptionItem {
item_price_id: item_price_id.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "item_price_id",
})?,
quantity: Some(1),
};
let subscription_req = subscription_request_types::SubscriptionCreateRequest {
subscription_id: subscription.id.to_owned(),
customer_id: subscription.customer_id.to_owned(),
subscription_items: vec![subscription_item],
billing_address: billing_address.ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "billing",
},
)?,
auto_collection: subscription_request_types::SubscriptionAutoCollection::Off,
connector_params: self.connector_params.clone(),
};
let router_data = self.build_router_data(
state,
subscription_req,
SubscriptionCreateData {
connector_meta_data: self.connector_metadata.clone(),
},
)?;
let connector_integration = self.connector_enum.get_connector_integration();
let response = self
.call_connector(
state,
router_data,
"create subscription on connector",
connector_integration,
)
.await?;
self.handle_connector_response(response)
}
#[allow(clippy::too_many_arguments)]
pub async fn record_back_to_billing_processor(
&self,
state: &SessionState,
invoice_id: common_utils::id_type::InvoiceId,
payment_id: common_utils::id_type::PaymentId,
payment_status: common_enums::AttemptStatus,
amount: common_utils::types::MinorUnit,
currency: common_enums::Currency,
payment_method_type: Option<common_enums::PaymentMethodType>,
) -> SubscriptionResult<InvoiceRecordBackResponse> {
let invoice_record_back_req = InvoiceRecordBackRequest {
amount,
currency,
payment_method_type,
attempt_status: payment_status,
merchant_reference_id: common_utils::id_type::PaymentReferenceId::from_str(
invoice_id.get_string_repr(),
)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "invoice_id",
})?,
connector_params: self.connector_params.clone(),
connector_transaction_id: Some(common_utils::types::ConnectorTransactionId::TxnId(
payment_id.get_string_repr().to_string(),
)),
};
let router_data = self.build_router_data(
state,
invoice_record_back_req,
InvoiceRecordBackData {
connector_meta_data: self.connector_metadata.clone(),
},
)?;
let connector_integration = self.connector_enum.get_connector_integration();
let response = self
.call_connector(
state,
router_data,
"invoice record back",
connector_integration,
)
.await?;
self.handle_connector_response(response)
}
pub async fn get_subscription_estimate(
&self,
state: &SessionState,
estimate_request: subscription_types::EstimateSubscriptionQuery,
) -> SubscriptionResult<subscription_response_types::GetSubscriptionEstimateResponse> {
let estimate_req = subscription_request_types::GetSubscriptionEstimateRequest {
price_id: estimate_request.item_price_id.clone(),
};
let router_data = self.build_router_data(
state,
estimate_req,
GetSubscriptionEstimateData {
connector_meta_data: self.connector_metadata.clone(),
},
)?;
let connector_integration = self.connector_enum.get_connector_integration();
let response = self
.call_connector(
state,
router_data,
"get subscription estimate from connector",
connector_integration,
)
.await?;
self.handle_connector_response(response)
}
pub async fn get_subscription_items(
&self,
state: &SessionState,
limit: Option<u32>,
offset: Option<u32>,
item_type: subscription_types::SubscriptionItemType,
) -> SubscriptionResult<subscription_response_types::GetSubscriptionItemsResponse> {
let get_items_request =
subscription_request_types::GetSubscriptionItemsRequest::new(limit, offset, item_type);
let router_data = self.build_router_data(
state,
get_items_request,
GetSubscriptionItemsData {
connector_meta_data: self.connector_metadata.clone(),
},
)?;
let connector_integration = self.connector_enum.get_connector_integration();
let response = self
.call_connector(
state,
router_data,
"get subscription items",
connector_integration,
)
.await?;
self.handle_connector_response(response)
}
pub async fn get_subscription_item_prices(
&self,
state: &SessionState,
item_price_id: String,
) -> SubscriptionResult<subscription_response_types::GetSubscriptionItemPricesResponse> {
let get_item_prices_request =
subscription_request_types::GetSubscriptionItemPricesRequest { item_price_id };
let router_data = self.build_router_data(
state,
get_item_prices_request,
GetSubscriptionItemPricesData {
connector_meta_data: self.connector_metadata.clone(),
},
)?;
let connector_integration = self.connector_enum.get_connector_integration();
let response = self
.call_connector(
state,
router_data,
"get subscription item prices",
connector_integration,
)
.await?;
self.handle_connector_response(response)
}
pub async fn pause_subscription_on_connector(
&self,
state: &SessionState,
subscription: &hyperswitch_domain_models::subscription::Subscription,
request: &subscription_types::PauseSubscriptionRequest,
) -> SubscriptionResult<subscription_response_types::SubscriptionPauseResponse> {
let pause_subscription_request = subscription_request_types::SubscriptionPauseRequest {
subscription_id: subscription.id.clone(),
pause_option: request.pause_option.clone(),
pause_date: request.pause_at,
};
let router_data = self.build_router_data(
state,
pause_subscription_request,
SubscriptionPauseData {
connector_meta_data: self.connector_metadata.clone(),
},
)?;
let connector_integration = self.connector_enum.get_connector_integration();
let response = self
.call_connector(
state,
router_data,
"pause subscription",
connector_integration,
)
.await?;
self.handle_connector_response(response)
}
pub async fn resume_subscription_on_connector(
&self,
state: &SessionState,
subscription: &hyperswitch_domain_models::subscription::Subscription,
request: &subscription_types::ResumeSubscriptionRequest,
) -> SubscriptionResult<subscription_response_types::SubscriptionResumeResponse> {
let resume_subscription_request = subscription_request_types::SubscriptionResumeRequest {
subscription_id: subscription.id.clone(),
resume_date: request.resume_date,
charges_handling: request.charges_handling.clone(),
resume_option: request.resume_option.clone(),
unpaid_invoices_handling: request.unpaid_invoices_handling.clone(),
};
let router_data = self.build_router_data(
state,
resume_subscription_request,
SubscriptionResumeData {
connector_meta_data: self.connector_metadata.clone(),
},
)?;
let connector_integration = self.connector_enum.get_connector_integration();
let response = self
.call_connector(
state,
router_data,
"resume subscription",
connector_integration,
)
.await?;
self.handle_connector_response(response)
}
pub async fn cancel_subscription_on_connector(
&self,
state: &SessionState,
subscription: &hyperswitch_domain_models::subscription::Subscription,
request: &subscription_types::CancelSubscriptionRequest,
) -> SubscriptionResult<subscription_response_types::SubscriptionCancelResponse> {
let cancel_subscription_request = subscription_request_types::SubscriptionCancelRequest {
subscription_id: subscription.id.clone(),
cancel_date: request.cancel_at,
account_receivables_handling: request.account_receivables_handling.clone(),
cancel_option: request.cancel_option.clone(),
cancel_reason_code: request.cancel_reason_code.clone(),
credit_option_for_current_term_charges: request
.credit_option_for_current_term_charges
.clone(),
refundable_credits_handling: request.refundable_credits_handling.clone(),
unbilled_charges_option: request.unbilled_charges_option.clone(),
};
let router_data = self.build_router_data(
state,
cancel_subscription_request,
SubscriptionCancelData {
connector_meta_data: self.connector_metadata.clone(),
},
)?;
let connector_integration = self.connector_enum.get_connector_integration();
let response = self
.call_connector(
state,
router_data,
"cancel subscription",
connector_integration,
)
.await?;
self.handle_connector_response(response)
}
async fn call_connector<F, ResourceCommonData, Req, Resp>(
&self,
state: &SessionState,
router_data: hyperswitch_domain_models::router_data_v2::RouterDataV2<
F,
ResourceCommonData,
Req,
Resp,
>,
operation_name: &str,
connector_integration: connector_integration_interface::BoxedConnectorIntegrationInterface<
F,
ResourceCommonData,
Req,
Resp,
>,
) -> SubscriptionResult<Result<Resp, hyperswitch_domain_models::router_data::ErrorResponse>>
where
F: Clone + std::fmt::Debug + 'static,
Req: Clone + std::fmt::Debug + 'static,
Resp: Clone + std::fmt::Debug + 'static,
ResourceCommonData:
connector_integration_interface::RouterDataConversion<F, Req, Resp> + Clone + 'static,
{
let old_router_data = ResourceCommonData::to_old_router_data(router_data).change_context(
errors::ApiErrorResponse::SubscriptionError {
operation: { operation_name.to_string() },
},
)?;
let router_resp = api_client::execute_connector_processing_step(
state,
connector_integration,
&old_router_data,
CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::SubscriptionError {
operation: operation_name.to_string(),
})
.attach_printable(format!(
"Failed while in subscription operation: {operation_name}"
))?;
Ok(router_resp.response)
}
fn build_router_data<F, ResourceCommonData, Req, Resp>(
&self,
state: &SessionState,
req: Req,
resource_common_data: ResourceCommonData,
) -> SubscriptionResult<
hyperswitch_domain_models::router_data_v2::RouterDataV2<F, ResourceCommonData, Req, Resp>,
> {
Ok(hyperswitch_domain_models::router_data_v2::RouterDataV2 {
flow: std::marker::PhantomData,
connector_auth_type: self.auth_type.clone(),
resource_common_data,
tenant_id: state.tenant.tenant_id.clone(),
request: req,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
})
}
fn handle_connector_response<T>(
&self,
response: Result<T, hyperswitch_domain_models::router_data::ErrorResponse>,
) -> SubscriptionResult<T> {
match response {
Ok(resp) => Ok(resp),
Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: self.connector_name.to_string(),
status_code: err.status_code,
reason: err.reason,
}
.into()),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_types/src/consts.rs | crates/common_types/src/consts.rs | //! Constants that are used in the domain level.
/// API version
#[cfg(feature = "v1")]
pub const API_VERSION: common_enums::ApiVersion = common_enums::ApiVersion::V1;
/// API version
#[cfg(feature = "v2")]
pub const API_VERSION: common_enums::ApiVersion = common_enums::ApiVersion::V2;
/// Maximum Dispute Polling Interval In Hours
pub const MAX_DISPUTE_POLLING_INTERVAL_IN_HOURS: i32 = 24;
///Default Dispute Polling Interval In Hours
pub const DEFAULT_DISPUTE_POLLING_INTERVAL_IN_HOURS: i32 = 24;
/// Customer List Lower Limit
pub const CUSTOMER_LIST_LOWER_LIMIT: u16 = 1;
/// Customer List Upper Limit
pub const CUSTOMER_LIST_UPPER_LIMIT: u16 = 100;
/// Customer List Default Limit
pub const CUSTOMER_LIST_DEFAULT_LIMIT: u16 = 20;
/// Default payment intent statuses that trigger a webhook
pub const DEFAULT_PAYMENT_WEBHOOK_TRIGGER_STATUSES: &[common_enums::IntentStatus] = &[
common_enums::IntentStatus::Succeeded,
common_enums::IntentStatus::Failed,
common_enums::IntentStatus::PartiallyCaptured,
common_enums::IntentStatus::RequiresMerchantAction,
common_enums::IntentStatus::RequiresCapture,
];
/// Default refund statuses that trigger a webhook
pub const DEFAULT_REFUND_WEBHOOK_TRIGGER_STATUSES: &[common_enums::RefundStatus] = &[
common_enums::RefundStatus::Success,
common_enums::RefundStatus::Failure,
common_enums::RefundStatus::TransactionFailure,
];
/// Default payout statuses that trigger a webhook
pub const DEFAULT_PAYOUT_WEBHOOK_TRIGGER_STATUSES: &[common_enums::PayoutStatus] = &[
common_enums::PayoutStatus::Success,
common_enums::PayoutStatus::Failed,
common_enums::PayoutStatus::Initiated,
common_enums::PayoutStatus::Pending,
];
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_types/src/callback_mapper.rs | crates/common_types/src/callback_mapper.rs | use common_utils::id_type;
use diesel::{AsExpression, FromSqlRow};
#[derive(
Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, AsExpression, FromSqlRow,
)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
/// Represents the data associated with a callback mapper.
pub enum CallbackMapperData {
/// data variant used while processing the network token webhook
NetworkTokenWebhook {
/// Merchant id associated with the network token requestor reference id
merchant_id: id_type::MerchantId,
/// Payment Method id associated with the network token requestor reference id
payment_method_id: String,
/// Customer id associated with the network token requestor reference id
customer_id: id_type::CustomerId,
},
}
impl CallbackMapperData {
/// Retrieves the details of the network token webhook type from callback mapper data.
pub fn get_network_token_webhook_details(
&self,
) -> (id_type::MerchantId, String, id_type::CustomerId) {
match self {
Self::NetworkTokenWebhook {
merchant_id,
payment_method_id,
customer_id,
} => (
merchant_id.clone(),
payment_method_id.clone(),
customer_id.clone(),
),
}
}
}
common_utils::impl_to_sql_from_sql_json!(CallbackMapperData);
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_types/src/lib.rs | crates/common_types/src/lib.rs | //! Types shared across the request/response types and database types
#![warn(missing_docs, missing_debug_implementations)]
pub mod consts;
pub mod customers;
pub mod domain;
pub mod payment_methods;
pub mod payments;
/// types that are wrappers around primitive types
pub mod primitive_wrappers;
pub mod refunds;
/// types for three ds decision rule engine
pub mod three_ds_decision_rule_engine;
///types for callback mapper
pub mod callback_mapper;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_types/src/refunds.rs | crates/common_types/src/refunds.rs | //! Refund related types
use common_utils::impl_to_sql_from_sql_json;
use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow};
use serde::{Deserialize, Serialize};
use smithy::SmithyModel;
use utoipa::ToSchema;
use crate::domain::{AdyenSplitData, XenditSplitSubMerchantData};
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// Charge specific fields for controlling the revert of funds from either platform or connected account. Check sub-fields for more details.
pub enum SplitRefund {
/// StripeSplitRefundRequest
#[smithy(value_type = "StripeSplitRefundRequest")]
StripeSplitRefund(StripeSplitRefundRequest),
/// AdyenSplitRefundRequest
#[smithy(value_type = "AdyenSplitData")]
AdyenSplitRefund(AdyenSplitData),
/// XenditSplitRefundRequest
#[smithy(value_type = "XenditSplitSubMerchantData")]
XenditSplitRefund(XenditSplitSubMerchantData),
}
impl_to_sql_from_sql_json!(SplitRefund);
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// Charge specific fields for controlling the revert of funds from either platform or connected account for Stripe. Check sub-fields for more details.
pub struct StripeSplitRefundRequest {
/// Toggle for reverting the application fee that was collected for the payment.
/// If set to false, the funds are pulled from the destination account.
#[smithy(value_type = "Option<bool>")]
pub revert_platform_fee: Option<bool>,
/// Toggle for reverting the transfer that was made during the charge.
/// If set to false, the funds are pulled from the main platform's account.
#[smithy(value_type = "Option<bool>")]
pub revert_transfer: Option<bool>,
}
impl_to_sql_from_sql_json!(StripeSplitRefundRequest);
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_types/src/primitive_wrappers.rs | crates/common_types/src/primitive_wrappers.rs | pub use bool_wrappers::*;
pub use safe_string::*;
pub use u16_wrappers::*;
pub use u32_wrappers::*;
mod bool_wrappers {
use std::ops::Deref;
use serde::{Deserialize, Serialize};
/// Bool that represents if Extended Authorization is Applied or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct ExtendedAuthorizationAppliedBool(bool);
impl Deref for ExtendedAuthorizationAppliedBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<bool> for ExtendedAuthorizationAppliedBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for ExtendedAuthorizationAppliedBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for ExtendedAuthorizationAppliedBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Extended Authorization is Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct RequestExtendedAuthorizationBool(bool);
impl Deref for RequestExtendedAuthorizationBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<bool> for RequestExtendedAuthorizationBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl RequestExtendedAuthorizationBool {
/// returns the inner bool value
pub fn is_true(&self) -> bool {
self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for RequestExtendedAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for RequestExtendedAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Enable Partial Authorization is Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct EnablePartialAuthorizationBool(bool);
impl Deref for EnablePartialAuthorizationBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<bool> for EnablePartialAuthorizationBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl EnablePartialAuthorizationBool {
/// returns the inner bool value
pub fn is_true(&self) -> bool {
self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for EnablePartialAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for EnablePartialAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Extended Authorization is always Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct AlwaysRequestExtendedAuthorization(bool);
impl Deref for AlwaysRequestExtendedAuthorization {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB>
for AlwaysRequestExtendedAuthorization
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for AlwaysRequestExtendedAuthorization
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Cvv should be collected during payment or not. Default is true
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct ShouldCollectCvvDuringPayment(bool);
impl Deref for ShouldCollectCvvDuringPayment {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for ShouldCollectCvvDuringPayment
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for ShouldCollectCvvDuringPayment
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
impl Default for ShouldCollectCvvDuringPayment {
/// Default for `ShouldCollectCvvDuringPayment` is `true`
fn default() -> Self {
Self(true)
}
}
/// Bool that represents if overcapture should always be requested
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct AlwaysEnableOvercaptureBool(bool);
impl AlwaysEnableOvercaptureBool {
/// returns the inner bool value
pub fn is_true(&self) -> bool {
self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for AlwaysEnableOvercaptureBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for AlwaysEnableOvercaptureBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
impl Default for AlwaysEnableOvercaptureBool {
/// Default for `AlwaysEnableOvercaptureBool` is `false`
fn default() -> Self {
Self(false)
}
}
/// Bool that represents if overcapture is requested for this payment
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct EnableOvercaptureBool(bool);
impl From<bool> for EnableOvercaptureBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl From<AlwaysEnableOvercaptureBool> for EnableOvercaptureBool {
fn from(item: AlwaysEnableOvercaptureBool) -> Self {
Self(item.is_true())
}
}
impl Deref for EnableOvercaptureBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for EnableOvercaptureBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for EnableOvercaptureBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
impl Default for EnableOvercaptureBool {
/// Default for `EnableOvercaptureBool` is `false`
fn default() -> Self {
Self(false)
}
}
/// Bool that represents if overcapture is applied for a payment by the connector
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct OvercaptureEnabledBool(bool);
impl OvercaptureEnabledBool {
/// Creates a new instance of `OvercaptureEnabledBool`
pub fn new(value: bool) -> Self {
Self(value)
}
}
impl Default for OvercaptureEnabledBool {
/// Default for `OvercaptureEnabledBool` is `false`
fn default() -> Self {
Self(false)
}
}
impl Deref for OvercaptureEnabledBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for OvercaptureEnabledBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for OvercaptureEnabledBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
}
mod u32_wrappers {
use std::ops::Deref;
use serde::{de::Error, Deserialize, Serialize};
use crate::consts::{
DEFAULT_DISPUTE_POLLING_INTERVAL_IN_HOURS, MAX_DISPUTE_POLLING_INTERVAL_IN_HOURS,
};
/// Time interval in hours for polling disputes
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, diesel::expression::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Integer)]
pub struct DisputePollingIntervalInHours(i32);
impl Deref for DisputePollingIntervalInHours {
type Target = i32;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'de> Deserialize<'de> for DisputePollingIntervalInHours {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let val = i32::deserialize(deserializer)?;
if val < 0 {
Err(D::Error::custom(
"DisputePollingIntervalInHours cannot be negative",
))
} else if val > MAX_DISPUTE_POLLING_INTERVAL_IN_HOURS {
Err(D::Error::custom(
"DisputePollingIntervalInHours exceeds the maximum allowed value of 24",
))
} else {
Ok(Self(val))
}
}
}
impl diesel::deserialize::FromSql<diesel::sql_types::Integer, diesel::pg::Pg>
for DisputePollingIntervalInHours
{
fn from_sql(value: diesel::pg::PgValue<'_>) -> diesel::deserialize::Result<Self> {
i32::from_sql(value).map(Self)
}
}
impl diesel::serialize::ToSql<diesel::sql_types::Integer, diesel::pg::Pg>
for DisputePollingIntervalInHours
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>,
) -> diesel::serialize::Result {
<i32 as diesel::serialize::ToSql<diesel::sql_types::Integer, diesel::pg::Pg>>::to_sql(
&self.0, out,
)
}
}
impl Default for DisputePollingIntervalInHours {
/// Default for `DisputePollingIntervalInHours` is `24`
fn default() -> Self {
Self(DEFAULT_DISPUTE_POLLING_INTERVAL_IN_HOURS)
}
}
}
mod u16_wrappers {
use std::ops::Deref;
use serde::{de::Error, Deserialize, Serialize};
use crate::consts::{
CUSTOMER_LIST_DEFAULT_LIMIT, CUSTOMER_LIST_LOWER_LIMIT, CUSTOMER_LIST_UPPER_LIMIT,
};
/// Customer list limit wrapper with automatic validation
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
pub struct CustomerListLimit(u16);
impl Deref for CustomerListLimit {
type Target = u16;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'de> Deserialize<'de> for CustomerListLimit {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let val = u16::deserialize(deserializer)?;
Self::new(val).map_err(D::Error::custom)
}
}
impl Default for CustomerListLimit {
/// Default for `CustomerListLimit` is `20`
fn default() -> Self {
Self(CUSTOMER_LIST_DEFAULT_LIMIT)
}
}
impl CustomerListLimit {
/// Creates a new CustomerListLimit with validation
pub fn new(value: u16) -> Result<Self, String> {
if value < CUSTOMER_LIST_LOWER_LIMIT {
Err(format!(
"CustomerListLimit cannot be less than {}",
CUSTOMER_LIST_LOWER_LIMIT
))
} else if value > CUSTOMER_LIST_UPPER_LIMIT {
Err(format!(
"CustomerListLimit exceeds the maximum allowed value of {}",
CUSTOMER_LIST_UPPER_LIMIT
))
} else {
Ok(Self(value))
}
}
}
}
/// Safe string wrapper that validates input against XSS attacks
mod safe_string {
use std::ops::Deref;
use common_utils::validation::contains_potential_xss_or_sqli;
use masking::SerializableSecret;
use serde::{de::Error, Deserialize, Serialize};
/// String wrapper that prevents XSS and SQLi attacks
#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct SafeString(String);
impl SafeString {
/// Creates a new SafeString after XSS and SQL injection validation
pub fn new(value: String) -> Result<Self, String> {
if contains_potential_xss_or_sqli(&value) {
return Err("Input contains potentially malicious content".into());
}
Ok(Self(value))
}
/// Creates a SafeString from a string slice
pub fn from_string_slice(value: &str) -> Result<Self, String> {
Self::new(value.to_string())
}
/// Returns the inner string as a string slice
pub fn as_str(&self) -> &str {
&self.0
}
/// Consumes self and returns the inner String
pub fn into_inner(self) -> String {
self.0
}
/// Returns true if the string is empty
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Returns the length of the string
pub fn len(&self) -> usize {
self.0.len()
}
}
impl Deref for SafeString {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0
}
}
// Custom serialization and deserialization
impl Serialize for SafeString {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for SafeString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Self::new(value).map_err(D::Error::custom)
}
}
// Implement SerializableSecret for SafeString to work with Secret<SafeString>
impl SerializableSecret for SafeString {}
// Diesel implementations for database operations
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for SafeString
where
DB: diesel::backend::Backend,
String: diesel::serialize::ToSql<diesel::sql_types::Text, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Text, DB> for SafeString
where
DB: diesel::backend::Backend,
String: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
String::from_sql(value).map(Self)
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_types/src/customers.rs | crates/common_types/src/customers.rs | //! Customer related types
/// HashMap containing MerchantConnectorAccountId and corresponding customer id
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
#[serde(transparent)]
pub struct ConnectorCustomerMap(
std::collections::HashMap<common_utils::id_type::MerchantConnectorAccountId, String>,
);
#[cfg(feature = "v2")]
impl ConnectorCustomerMap {
/// Creates a new `ConnectorCustomerMap` from a HashMap
pub fn new(
map: std::collections::HashMap<common_utils::id_type::MerchantConnectorAccountId, String>,
) -> Self {
Self(map)
}
}
#[cfg(feature = "v2")]
common_utils::impl_to_sql_from_sql_json!(ConnectorCustomerMap);
#[cfg(feature = "v2")]
impl std::ops::Deref for ConnectorCustomerMap {
type Target =
std::collections::HashMap<common_utils::id_type::MerchantConnectorAccountId, String>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "v2")]
impl std::ops::DerefMut for ConnectorCustomerMap {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_types/src/payment_methods.rs | crates/common_types/src/payment_methods.rs | //! Common types to be used in payment methods
use diesel::{
backend::Backend,
deserialize,
deserialize::FromSql,
serialize::ToSql,
sql_types::{Json, Jsonb},
AsExpression, Queryable,
};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
/// Details of all the payment methods enabled for the connector for the given merchant account
// sql_type for this can be json instead of jsonb. This is because validation at database is not required since it will always be written by the application.
// This is a performance optimization to avoid json validation at database level.
// jsonb enables faster querying on json columns, but it doesn't justify here since we are not querying on this column.
// https://docs.rs/diesel/latest/diesel/sql_types/struct.Jsonb.html
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, AsExpression)]
#[serde(deny_unknown_fields)]
#[diesel(sql_type = Json)]
pub struct PaymentMethodsEnabled {
/// Type of payment method.
#[schema(value_type = PaymentMethod,example = "card")]
pub payment_method_type: common_enums::PaymentMethod,
/// Payment method configuration, this includes all the filters associated with the payment method
pub payment_method_subtypes: Option<Vec<RequestPaymentMethodTypes>>,
}
// Custom FromSql implementation to handle deserialization of v1 data format
impl FromSql<Json, diesel::pg::Pg> for PaymentMethodsEnabled {
fn from_sql(bytes: <diesel::pg::Pg as Backend>::RawValue<'_>) -> deserialize::Result<Self> {
let helper: PaymentMethodsEnabledHelper = serde_json::from_slice(bytes.as_bytes())
.map_err(|e| Box::new(diesel::result::Error::DeserializationError(Box::new(e))))?;
Ok(helper.into())
}
}
// In this ToSql implementation, we are directly serializing the PaymentMethodsEnabled struct to JSON
impl ToSql<Json, diesel::pg::Pg> for PaymentMethodsEnabled {
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>,
) -> diesel::serialize::Result {
let value = serde_json::to_value(self)?;
// the function `reborrow` only works in case of `Pg` backend. But, in case of other backends
// please refer to the diesel migration blog:
// https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations
<serde_json::Value as ToSql<Json, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow())
}
}
// Intermediate type to handle deserialization of v1 data format of PaymentMethodsEnabled
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum PaymentMethodsEnabledHelper {
V2 {
payment_method_type: common_enums::PaymentMethod,
payment_method_subtypes: Option<Vec<RequestPaymentMethodTypes>>,
},
V1 {
payment_method: common_enums::PaymentMethod,
payment_method_types: Option<Vec<RequestPaymentMethodTypesV1>>,
},
}
impl From<PaymentMethodsEnabledHelper> for PaymentMethodsEnabled {
fn from(helper: PaymentMethodsEnabledHelper) -> Self {
match helper {
PaymentMethodsEnabledHelper::V2 {
payment_method_type,
payment_method_subtypes,
} => Self {
payment_method_type,
payment_method_subtypes,
},
PaymentMethodsEnabledHelper::V1 {
payment_method,
payment_method_types,
} => Self {
payment_method_type: payment_method,
payment_method_subtypes: payment_method_types.map(|subtypes| {
subtypes
.into_iter()
.map(RequestPaymentMethodTypes::from)
.collect()
}),
},
}
}
}
impl PaymentMethodsEnabled {
/// Get payment_method_type
#[cfg(feature = "v2")]
pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> {
Some(self.payment_method_type)
}
/// Get payment_method_subtypes
#[cfg(feature = "v2")]
pub fn get_payment_method_type(&self) -> Option<&Vec<RequestPaymentMethodTypes>> {
self.payment_method_subtypes.as_ref()
}
}
/// Details of a specific payment method subtype enabled for the connector for the given merchant account
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, Hash)]
pub struct RequestPaymentMethodTypes {
/// The payment method subtype
#[schema(value_type = PaymentMethodType)]
pub payment_method_subtype: common_enums::PaymentMethodType,
/// The payment experience for the payment method
#[schema(value_type = Option<PaymentExperience>)]
pub payment_experience: Option<common_enums::PaymentExperience>,
/// List of cards networks that are enabled for this payment method, applicable for credit and debit payment method subtypes only
#[schema(value_type = Option<Vec<CardNetwork>>)]
pub card_networks: Option<Vec<common_enums::CardNetwork>>,
/// List of currencies accepted or has the processing capabilities of the processor
#[schema(example = json!(
{
"type": "enable_only",
"list": ["USD", "INR"]
}
), value_type = Option<AcceptedCurrencies>)]
pub accepted_currencies: Option<AcceptedCurrencies>,
/// List of Countries accepted or has the processing capabilities of the processor
#[schema(example = json!(
{
"type": "enable_only",
"list": ["UK", "AU"]
}
), value_type = Option<AcceptedCountries>)]
pub accepted_countries: Option<AcceptedCountries>,
/// Minimum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents)
#[schema(example = 1)]
pub minimum_amount: Option<common_utils::types::MinorUnit>,
/// Maximum amount supported by the processor. To be represented in the lowest denomination of
/// the target currency (For example, for USD it should be in cents)
#[schema(example = 1313)]
pub maximum_amount: Option<common_utils::types::MinorUnit>,
/// Indicates whether the payment method supports recurring payments. Optional.
#[schema(example = true)]
pub recurring_enabled: Option<bool>,
/// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional.
#[schema(example = true)]
pub installment_payment_enabled: Option<bool>,
}
impl From<RequestPaymentMethodTypesV1> for RequestPaymentMethodTypes {
fn from(value: RequestPaymentMethodTypesV1) -> Self {
Self {
payment_method_subtype: value.payment_method_type,
payment_experience: value.payment_experience,
card_networks: value.card_networks,
accepted_currencies: value.accepted_currencies,
accepted_countries: value.accepted_countries,
minimum_amount: value.minimum_amount,
maximum_amount: value.maximum_amount,
recurring_enabled: value.recurring_enabled,
installment_payment_enabled: value.installment_payment_enabled,
}
}
}
#[derive(serde::Deserialize)]
struct RequestPaymentMethodTypesV1 {
pub payment_method_type: common_enums::PaymentMethodType,
pub payment_experience: Option<common_enums::PaymentExperience>,
pub card_networks: Option<Vec<common_enums::CardNetwork>>,
pub accepted_currencies: Option<AcceptedCurrencies>,
pub accepted_countries: Option<AcceptedCountries>,
pub minimum_amount: Option<common_utils::types::MinorUnit>,
pub maximum_amount: Option<common_utils::types::MinorUnit>,
pub recurring_enabled: Option<bool>,
pub installment_payment_enabled: Option<bool>,
}
impl RequestPaymentMethodTypes {
///Get payment_method_subtype
pub fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethodType> {
Some(self.payment_method_subtype)
}
}
#[derive(PartialEq, Eq, Hash, Debug, Clone, serde::Serialize, Deserialize, ToSchema)]
#[serde(
deny_unknown_fields,
tag = "type",
content = "list",
rename_all = "snake_case"
)]
/// Object to filter the countries for which the payment method subtype is enabled
pub enum AcceptedCountries {
/// Only enable the payment method subtype for specific countries
#[schema(value_type = Vec<CountryAlpha2>)]
EnableOnly(Vec<common_enums::CountryAlpha2>),
/// Only disable the payment method subtype for specific countries
#[schema(value_type = Vec<CountryAlpha2>)]
DisableOnly(Vec<common_enums::CountryAlpha2>),
/// Enable the payment method subtype for all countries, in which the processor has the processing capabilities
AllAccepted,
}
#[derive(PartialEq, Eq, Hash, Debug, Clone, serde::Serialize, Deserialize, ToSchema)]
#[serde(
deny_unknown_fields,
tag = "type",
content = "list",
rename_all = "snake_case"
)]
/// Object to filter the countries for which the payment method subtype is enabled
pub enum AcceptedCurrencies {
/// Only enable the payment method subtype for specific currencies
#[schema(value_type = Vec<Currency>)]
EnableOnly(Vec<common_enums::Currency>),
/// Only disable the payment method subtype for specific currencies
#[schema(value_type = Vec<Currency>)]
DisableOnly(Vec<common_enums::Currency>),
/// Enable the payment method subtype for all currencies, in which the processor has the processing capabilities
AllAccepted,
}
impl<DB> Queryable<Jsonb, DB> for PaymentMethodsEnabled
where
DB: Backend,
Self: FromSql<Jsonb, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
/// The network tokenization configuration for creating the payment method session
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct NetworkTokenization {
/// Enable the network tokenization for payment methods that are created using the payment method session
#[schema(value_type = NetworkTokenizationToggle)]
pub enable: common_enums::NetworkTokenizationToggle,
}
/// The Payment Service Provider Configuration for payment methods that are created using the payment method session
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PspTokenization {
/// The tokenization type to be applied for the payment method
#[schema(value_type = TokenizationType)]
pub tokenization_type: common_enums::TokenizationType,
/// The merchant connector id to be used for tokenization
#[schema(value_type = String)]
pub connector_id: common_utils::id_type::MerchantConnectorAccountId,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_types/src/three_ds_decision_rule_engine.rs | crates/common_types/src/three_ds_decision_rule_engine.rs | use common_utils::impl_to_sql_from_sql_json;
use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow};
use euclid::frontend::dir::{DirKeyKind, EuclidDirFilter};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
/// Enum representing the possible outcomes of the 3DS Decision Rule Engine.
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
Copy,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
Default,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
pub enum ThreeDSDecision {
/// No 3DS authentication required
#[default]
NoThreeDs,
/// Mandate 3DS Challenge
ChallengeRequested,
/// Prefer 3DS Challenge
ChallengePreferred,
/// Request 3DS Exemption, Type: Transaction Risk Analysis (TRA)
ThreeDsExemptionRequestedTra,
/// Request 3DS Exemption, Type: Low Value Transaction
ThreeDsExemptionRequestedLowValue,
/// No challenge requested by merchant (e.g., delegated authentication)
IssuerThreeDsExemptionRequested,
}
impl_to_sql_from_sql_json!(ThreeDSDecision);
impl ThreeDSDecision {
/// Checks if the decision is to mandate a 3DS challenge
pub fn should_force_3ds_challenge(self) -> bool {
matches!(self, Self::ChallengeRequested)
}
}
/// Struct representing the output configuration for the 3DS Decision Rule Engine.
#[derive(
Serialize, Default, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct ThreeDSDecisionRule {
/// The decided 3DS action based on the rules
pub decision: ThreeDSDecision,
}
impl ThreeDSDecisionRule {
/// Returns the decision
pub fn get_decision(&self) -> ThreeDSDecision {
self.decision
}
}
impl_to_sql_from_sql_json!(ThreeDSDecisionRule);
impl EuclidDirFilter for ThreeDSDecisionRule {
const ALLOWED: &'static [DirKeyKind] = &[
DirKeyKind::CardNetwork,
DirKeyKind::PaymentAmount,
DirKeyKind::PaymentCurrency,
DirKeyKind::IssuerName,
DirKeyKind::IssuerCountry,
DirKeyKind::CustomerDevicePlatform,
DirKeyKind::CustomerDeviceType,
DirKeyKind::CustomerDeviceDisplaySize,
DirKeyKind::AcquirerCountry,
DirKeyKind::AcquirerFraudRate,
];
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_types/src/domain.rs | crates/common_types/src/domain.rs | //! Common types
use std::collections::HashMap;
use common_enums::enums;
use common_utils::{impl_to_sql_from_sql_json, types::MinorUnit};
use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow};
#[cfg(feature = "v2")]
use masking::Secret;
use serde::{Deserialize, Serialize};
use smithy::SmithyModel;
use utoipa::ToSchema;
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// Fee information for Split Payments to be charged on the payment being collected for Adyen
pub struct AdyenSplitData {
/// The store identifier
#[smithy(value_type = "Option<String>")]
pub store: Option<String>,
/// Data for the split items
#[smithy(value_type = "Vec<AdyenSplitItem>")]
pub split_items: Vec<AdyenSplitItem>,
}
impl_to_sql_from_sql_json!(AdyenSplitData);
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// Data for the split items
pub struct AdyenSplitItem {
/// The amount of the split item
#[schema(value_type = i64, example = 6540)]
#[smithy(value_type = "Option<i64>")]
pub amount: Option<MinorUnit>,
/// Defines type of split item
#[schema(value_type = AdyenSplitType, example = "BalanceAccount")]
#[smithy(value_type = "AdyenSplitType")]
pub split_type: enums::AdyenSplitType,
/// The unique identifier of the account to which the split amount is allocated.
#[smithy(value_type = "Option<String>")]
pub account: Option<String>,
/// Unique Identifier for the split item
#[smithy(value_type = "String")]
pub reference: String,
/// Description for the part of the payment that will be allocated to the specified account.
#[smithy(value_type = "Option<String>")]
pub description: Option<String>,
}
impl_to_sql_from_sql_json!(AdyenSplitItem);
/// Fee information to be charged on the payment being collected for sub-merchant via xendit
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct XenditSplitSubMerchantData {
/// The sub-account user-id that you want to make this transaction for.
#[smithy(value_type = "String")]
pub for_user_id: String,
}
impl_to_sql_from_sql_json!(XenditSplitSubMerchantData);
/// Acquirer configuration
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize, PartialEq)]
pub struct AcquirerConfig {
/// The merchant id assigned by the acquirer
#[schema(value_type= String,example = "M123456789")]
pub acquirer_assigned_merchant_id: String,
/// merchant name
#[schema(value_type= String,example = "NewAge Retailer")]
pub merchant_name: String,
/// Network provider
#[schema(value_type= String,example = "VISA")]
pub network: common_enums::CardNetwork,
/// Acquirer bin
#[schema(value_type= String,example = "456789")]
pub acquirer_bin: String,
/// Acquirer ica provided by acquirer
#[schema(value_type= Option<String>,example = "401288")]
pub acquirer_ica: Option<String>,
/// Fraud rate for the particular acquirer configuration
#[schema(value_type= String,example = "0.01")]
pub acquirer_fraud_rate: f64,
}
#[derive(Serialize, Deserialize, Debug, Clone, FromSqlRow, AsExpression, ToSchema)]
#[diesel(sql_type = Jsonb)]
/// Acquirer configs
pub struct AcquirerConfigMap(pub HashMap<common_utils::id_type::ProfileAcquirerId, AcquirerConfig>);
impl_to_sql_from_sql_json!(AcquirerConfigMap);
/// Merchant connector details
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[cfg(feature = "v2")]
pub struct MerchantConnectorAuthDetails {
/// The connector used for the payment
#[schema(value_type = Connector)]
pub connector_name: common_enums::connector_enums::Connector,
/// The merchant connector credentials used for the payment
#[schema(value_type = Object, example = r#"{
"merchant_connector_creds": {
"auth_type": "HeaderKey",
"api_key":"sk_test_xxxxxexamplexxxxxx12345"
},
}"#)]
pub merchant_connector_creds: common_utils::pii::SecretSerdeValue,
}
/// Connector Response Data that are required to be populated in response, but not persisted in DB.
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct ConnectorResponseData {
/// Stringified connector raw response body
pub raw_connector_response: Option<Secret<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, AsExpression, ToSchema)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
/// Contains the data relevant to the specified GSM feature, if applicable.
/// For example, if the `feature` is `Retry`, this will include configuration
/// details specific to the retry behavior.
pub enum GsmFeatureData {
/// Represents the data associated with a retry feature in GSM.
Retry(RetryFeatureData),
}
/// Represents the data associated with a retry feature in GSM.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, AsExpression, ToSchema)]
#[diesel(sql_type = Jsonb)]
pub struct RetryFeatureData {
/// indicates if step_up retry is possible
pub step_up_possible: bool,
/// indicates if retry with pan is possible
pub clear_pan_possible: bool,
/// indicates if retry with alternate network possible
pub alternate_network_possible: bool,
/// decision to be taken for auto retries flow
#[schema(value_type = GsmDecision)]
pub decision: common_enums::GsmDecision,
}
impl_to_sql_from_sql_json!(GsmFeatureData);
impl_to_sql_from_sql_json!(RetryFeatureData);
impl GsmFeatureData {
/// Retrieves the retry feature data if it exists.
pub fn get_retry_feature_data(&self) -> Option<RetryFeatureData> {
match self {
Self::Retry(data) => Some(data.clone()),
}
}
/// Retrieves the decision from the retry feature data.
pub fn get_decision(&self) -> common_enums::GsmDecision {
match self {
Self::Retry(data) => data.decision,
}
}
}
/// Implementation of methods for `RetryFeatureData`
impl RetryFeatureData {
/// Checks if step-up retry is possible.
pub fn is_step_up_possible(&self) -> bool {
self.step_up_possible
}
/// Checks if retry with PAN is possible.
pub fn is_clear_pan_possible(&self) -> bool {
self.clear_pan_possible
}
/// Checks if retry with alternate network is possible.
pub fn is_alternate_network_possible(&self) -> bool {
self.alternate_network_possible
}
/// Retrieves the decision to be taken for auto retries flow.
pub fn get_decision(&self) -> common_enums::GsmDecision {
self.decision
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/common_types/src/payments.rs | crates/common_types/src/payments.rs | //! Payment related types
use std::collections::HashMap;
use common_enums::enums;
use common_utils::{
date_time, errors, events, ext_traits::OptionExt, impl_to_sql_from_sql_json, pii,
types::MinorUnit,
};
use diesel::{
sql_types::{Jsonb, Text},
AsExpression, FromSqlRow,
};
use error_stack::{Report, Result, ResultExt};
use euclid::frontend::{
ast::Program,
dir::{DirKeyKind, EuclidDirFilter},
};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use smithy::SmithyModel;
use time::PrimitiveDateTime;
use utoipa::ToSchema;
use crate::domain::{AdyenSplitData, XenditSplitSubMerchantData};
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// Fee information for Split Payments to be charged on the payment being collected
pub enum SplitPaymentsRequest {
/// StripeSplitPayment
#[smithy(value_type = "StripeSplitPaymentRequest")]
StripeSplitPayment(StripeSplitPaymentRequest),
/// AdyenSplitPayment
#[smithy(value_type = "AdyenSplitData")]
AdyenSplitPayment(AdyenSplitData),
/// XenditSplitPayment
#[smithy(value_type = "XenditSplitRequest")]
XenditSplitPayment(XenditSplitRequest),
}
impl_to_sql_from_sql_json!(SplitPaymentsRequest);
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// Fee information for Split Payments to be charged on the payment being collected for Stripe
pub struct StripeSplitPaymentRequest {
/// Stripe's charge type
#[schema(value_type = PaymentChargeType, example = "direct")]
#[smithy(value_type = "PaymentChargeType")]
pub charge_type: enums::PaymentChargeType,
/// Platform fees to be collected on the payment
#[schema(value_type = i64, example = 6540)]
#[smithy(value_type = "Option<i64>")]
pub application_fees: Option<MinorUnit>,
/// Identifier for the reseller's account where the funds were transferred
#[smithy(value_type = "String")]
pub transfer_account_id: String,
}
impl_to_sql_from_sql_json!(StripeSplitPaymentRequest);
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
/// Hashmap to store mca_id's with product names
pub struct AuthenticationConnectorAccountMap(
HashMap<enums::AuthenticationProduct, common_utils::id_type::MerchantConnectorAccountId>,
);
impl_to_sql_from_sql_json!(AuthenticationConnectorAccountMap);
impl AuthenticationConnectorAccountMap {
/// fn to get click to pay connector_account_id
pub fn get_click_to_pay_connector_account_id(
&self,
) -> Result<common_utils::id_type::MerchantConnectorAccountId, errors::ValidationError> {
self.0
.get(&enums::AuthenticationProduct::ClickToPay)
.ok_or(errors::ValidationError::MissingRequiredField {
field_name: "authentication_product_id.click_to_pay".to_string(),
})
.map_err(Report::from)
.cloned()
}
}
/// A wrapper type for merchant country codes that provides validation and conversion functionality.
///
/// This type stores a country code as a string and provides methods to validate it
/// and convert it to a `Country` enum variant.
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Text)]
#[serde(deny_unknown_fields)]
pub struct MerchantCountryCode(String);
impl MerchantCountryCode {
/// Returns the country code as a string.
pub fn get_country_code(&self) -> String {
self.0.clone()
}
/// Validates the country code and returns a `Country` enum variant.
///
/// This method attempts to parse the country code as a u32 and convert it to a `Country` enum variant.
/// If the country code is invalid, it returns a `ValidationError` with the appropriate error message.
pub fn validate_and_get_country_from_merchant_country_code(
&self,
) -> errors::CustomResult<common_enums::Country, errors::ValidationError> {
let country_code = self.get_country_code();
let code = country_code
.parse::<u32>()
.map_err(Report::from)
.change_context(errors::ValidationError::IncorrectValueProvided {
field_name: "merchant_country_code",
})
.attach_printable_lazy(|| {
format!("Country code {country_code} is negative or too large")
})?;
common_enums::Country::from_numeric(code)
.map_err(|_| errors::ValidationError::IncorrectValueProvided {
field_name: "merchant_country_code",
})
.attach_printable_lazy(|| format!("Invalid country code {code}"))
}
/// Creates a new `MerchantCountryCode` instance from a string.
pub fn new(country_code: String) -> Self {
Self(country_code)
}
}
impl diesel::serialize::ToSql<Text, diesel::pg::Pg> for MerchantCountryCode {
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>,
) -> diesel::serialize::Result {
<String as diesel::serialize::ToSql<Text, diesel::pg::Pg>>::to_sql(&self.0, out)
}
}
impl diesel::deserialize::FromSql<Text, diesel::pg::Pg> for MerchantCountryCode {
fn from_sql(bytes: diesel::pg::PgValue<'_>) -> diesel::deserialize::Result<Self> {
let s = <String as diesel::deserialize::FromSql<Text, diesel::pg::Pg>>::from_sql(bytes)?;
Ok(Self(s))
}
}
#[derive(
Serialize, Default, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
/// ConditionalConfigs
pub struct ConditionalConfigs {
/// Override 3DS
pub override_3ds: Option<common_enums::AuthenticationType>,
}
impl EuclidDirFilter for ConditionalConfigs {
const ALLOWED: &'static [DirKeyKind] = &[
DirKeyKind::PaymentMethod,
DirKeyKind::CardType,
DirKeyKind::CardNetwork,
DirKeyKind::MetaData,
DirKeyKind::PaymentAmount,
DirKeyKind::PaymentCurrency,
DirKeyKind::CaptureMethod,
DirKeyKind::BillingCountry,
DirKeyKind::BusinessCountry,
DirKeyKind::NetworkTokenType,
];
}
impl_to_sql_from_sql_json!(ConditionalConfigs);
/// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client.
#[derive(
Default,
Eq,
PartialEq,
Debug,
serde::Deserialize,
serde::Serialize,
Clone,
AsExpression,
ToSchema,
SmithyModel,
)]
#[serde(deny_unknown_fields)]
#[diesel(sql_type = Jsonb)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct CustomerAcceptance {
/// Type of acceptance provided by the
#[schema(example = "online")]
#[smithy(value_type = "AcceptanceType")]
pub acceptance_type: AcceptanceType,
/// Specifying when the customer acceptance was provided
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
#[smithy(value_type = "Option<PrimitiveDateTime>")]
pub accepted_at: Option<PrimitiveDateTime>,
/// Information required for online mandate generation
#[smithy(value_type = "Option<OnlineMandate>")]
pub online: Option<OnlineMandate>,
}
impl_to_sql_from_sql_json!(CustomerAcceptance);
impl CustomerAcceptance {
/// Get the IP address
pub fn get_ip_address(&self) -> Option<String> {
self.online
.as_ref()
.and_then(|data| data.ip_address.as_ref().map(|ip| ip.peek().to_owned()))
}
/// Get the User Agent
pub fn get_user_agent(&self) -> Option<String> {
self.online.as_ref().map(|data| data.user_agent.clone())
}
/// Get when the customer acceptance was provided
pub fn get_accepted_at(&self) -> PrimitiveDateTime {
self.accepted_at.unwrap_or_else(date_time::now)
}
}
impl masking::SerializableSecret for CustomerAcceptance {}
#[derive(
Default,
Debug,
serde::Deserialize,
serde::Serialize,
PartialEq,
Eq,
Clone,
Copy,
ToSchema,
SmithyModel,
)]
#[serde(rename_all = "lowercase")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// This is used to indicate if the mandate was accepted online or offline
pub enum AcceptanceType {
/// Online
Online,
/// Offline
#[default]
Offline,
}
#[derive(
Default,
Eq,
PartialEq,
Debug,
serde::Deserialize,
serde::Serialize,
AsExpression,
Clone,
ToSchema,
SmithyModel,
)]
#[serde(deny_unknown_fields)]
/// Details of online mandate
#[diesel(sql_type = Jsonb)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct OnlineMandate {
/// Ip address of the customer machine from which the mandate was created
#[schema(value_type = String, example = "123.32.25.123")]
#[smithy(value_type = "String")]
pub ip_address: Option<Secret<String, pii::IpAddress>>,
/// The user-agent of the customer's browser
#[smithy(value_type = "String")]
pub user_agent: String,
}
impl_to_sql_from_sql_json!(OnlineMandate);
#[derive(Serialize, Deserialize, Debug, Clone, FromSqlRow, AsExpression, ToSchema)]
#[diesel(sql_type = Jsonb)]
/// DecisionManagerRecord
pub struct DecisionManagerRecord {
/// Name of the Decision Manager
pub name: String,
/// Program to be executed
pub program: Program<ConditionalConfigs>,
/// Created at timestamp
pub created_at: i64,
}
impl events::ApiEventMetric for DecisionManagerRecord {
fn get_api_event_type(&self) -> Option<events::ApiEventsType> {
Some(events::ApiEventsType::Routing)
}
}
impl_to_sql_from_sql_json!(DecisionManagerRecord);
/// DecisionManagerResponse
pub type DecisionManagerResponse = DecisionManagerRecord;
/// Fee information to be charged on the payment being collected via Stripe
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct StripeChargeResponseData {
/// Identifier for charge created for the payment
#[smithy(value_type = "Option<String>")]
pub charge_id: Option<String>,
/// Type of charge (connector specific)
#[schema(value_type = PaymentChargeType, example = "direct")]
#[smithy(value_type = "PaymentChargeType")]
pub charge_type: enums::PaymentChargeType,
/// Platform fees collected on the payment
#[schema(value_type = i64, example = 6540)]
#[smithy(value_type = "Option<i64>")]
pub application_fees: Option<MinorUnit>,
/// Identifier for the reseller's account where the funds were transferred
#[smithy(value_type = "String")]
pub transfer_account_id: String,
}
impl_to_sql_from_sql_json!(StripeChargeResponseData);
/// Charge Information
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum ConnectorChargeResponseData {
/// StripeChargeResponseData
#[smithy(value_type = "StripeChargeResponseData")]
StripeSplitPayment(StripeChargeResponseData),
/// AdyenChargeResponseData
#[smithy(value_type = "AdyenSplitData")]
AdyenSplitPayment(AdyenSplitData),
/// XenditChargeResponseData
#[smithy(value_type = "XenditChargeResponseData")]
XenditSplitPayment(XenditChargeResponseData),
}
impl_to_sql_from_sql_json!(ConnectorChargeResponseData);
/// Fee information to be charged on the payment being collected via xendit
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct XenditSplitRoute {
/// Amount of payments to be split
#[smithy(value_type = "Option<i64>")]
pub flat_amount: Option<MinorUnit>,
/// Amount of payments to be split, using a percent rate as unit
#[smithy(value_type = "Option<i64>")]
pub percent_amount: Option<i64>,
/// Currency code
#[schema(value_type = Currency, example = "USD")]
#[smithy(value_type = "Currency")]
pub currency: enums::Currency,
/// ID of the destination account where the amount will be routed to
#[smithy(value_type = "String")]
pub destination_account_id: String,
/// Reference ID which acts as an identifier of the route itself
#[smithy(value_type = "String")]
pub reference_id: String,
}
impl_to_sql_from_sql_json!(XenditSplitRoute);
/// Fee information to be charged on the payment being collected via xendit
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct XenditMultipleSplitRequest {
/// Name to identify split rule. Not required to be unique. Typically based on transaction and/or sub-merchant types.
#[smithy(value_type = "String")]
pub name: String,
/// Description to identify fee rule
#[smithy(value_type = "String")]
pub description: String,
/// The sub-account user-id that you want to make this transaction for.
#[smithy(value_type = "Option<String>")]
pub for_user_id: Option<String>,
/// Array of objects that define how the platform wants to route the fees and to which accounts.
#[smithy(value_type = "Vec<XenditSplitRoute>")]
pub routes: Vec<XenditSplitRoute>,
}
impl_to_sql_from_sql_json!(XenditMultipleSplitRequest);
/// Xendit Charge Request
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum XenditSplitRequest {
/// Split Between Multiple Accounts
#[smithy(value_type = "XenditMultipleSplitRequest")]
MultipleSplits(XenditMultipleSplitRequest),
/// Collect Fee for Single Account
#[smithy(value_type = "XenditSplitSubMerchantData")]
SingleSplit(XenditSplitSubMerchantData),
}
impl_to_sql_from_sql_json!(XenditSplitRequest);
/// Charge Information
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub enum XenditChargeResponseData {
/// Split Between Multiple Accounts
#[smithy(value_type = "XenditMultipleSplitResponse")]
MultipleSplits(XenditMultipleSplitResponse),
/// Collect Fee for Single Account
#[smithy(value_type = "XenditSplitSubMerchantData")]
SingleSplit(XenditSplitSubMerchantData),
}
impl_to_sql_from_sql_json!(XenditChargeResponseData);
/// Fee information charged on the payment being collected via xendit
#[derive(
Serialize,
Deserialize,
Debug,
Clone,
PartialEq,
Eq,
FromSqlRow,
AsExpression,
ToSchema,
SmithyModel,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct XenditMultipleSplitResponse {
/// Identifier for split rule created for the payment
#[smithy(value_type = "String")]
pub split_rule_id: String,
/// The sub-account user-id that you want to make this transaction for.
#[smithy(value_type = "Option<String>")]
pub for_user_id: Option<String>,
/// Name to identify split rule. Not required to be unique. Typically based on transaction and/or sub-merchant types.
#[smithy(value_type = "String")]
pub name: String,
/// Description to identify fee rule
#[smithy(value_type = "String")]
pub description: String,
/// Array of objects that define how the platform wants to route the fees and to which accounts.
#[smithy(value_type = "Vec<XenditSplitRoute>")]
pub routes: Vec<XenditSplitRoute>,
}
impl_to_sql_from_sql_json!(XenditMultipleSplitResponse);
#[derive(
Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[serde(untagged)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// This enum is used to represent the Gpay payment data, which can either be encrypted or decrypted.
pub enum GpayTokenizationData {
/// This variant contains the decrypted Gpay payment data as a structured object.
#[smithy(value_type = "GPayPredecryptData")]
Decrypted(GPayPredecryptData),
/// This variant contains the encrypted Gpay payment data as a string.
#[smithy(value_type = "GpayEcryptedTokenizationData")]
Encrypted(GpayEcryptedTokenizationData),
}
#[derive(
Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// This struct represents the encrypted Gpay payment data
pub struct GpayEcryptedTokenizationData {
/// The type of the token
#[serde(rename = "type")]
#[smithy(value_type = "String")]
pub token_type: String,
/// Token generated for the wallet
#[smithy(value_type = "String")]
pub token: String,
}
#[derive(
Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// This struct represents the decrypted Google Pay payment data
pub struct GPayPredecryptData {
/// The card's expiry month
#[schema(value_type = String)]
#[smithy(value_type = "String")]
pub card_exp_month: Secret<String>,
/// The card's expiry year
#[schema(value_type = String)]
#[smithy(value_type = "String")]
pub card_exp_year: Secret<String>,
/// The Primary Account Number (PAN) of the card
#[schema(value_type = String, example = "4242424242424242")]
#[smithy(value_type = "String")]
pub application_primary_account_number: cards::CardNumber,
/// Cryptogram generated by the Network
#[schema(value_type = String, example = "AgAAAAAAAIR8CQrXcIhbQAAAAAA")]
#[smithy(value_type = "Option<String>")]
pub cryptogram: Option<Secret<String>>,
/// Electronic Commerce Indicator
#[schema(value_type = String, example = "07")]
#[smithy(value_type = "Option<String>")]
pub eci_indicator: Option<String>,
}
impl GpayTokenizationData {
/// Get the encrypted Google Pay payment data, returning an error if it does not exist
pub fn get_encrypted_google_pay_payment_data_mandatory(
&self,
) -> Result<&GpayEcryptedTokenizationData, errors::ValidationError> {
match self {
Self::Encrypted(encrypted_data) => Ok(encrypted_data),
Self::Decrypted(_) => Err(errors::ValidationError::InvalidValue {
message: "Encrypted Google Pay payment data is mandatory".to_string(),
}
.into()),
}
}
/// Get the optional decrypted Google Pay payment data
pub fn get_decrypted_google_pay_payment_data_optional(&self) -> Option<&GPayPredecryptData> {
match self {
Self::Decrypted(token) => Some(token),
Self::Encrypted(_) => None,
}
}
/// Get the token from Google Pay tokenization data
/// Returns the token string if encrypted data exists, otherwise returns an error
pub fn get_encrypted_google_pay_token(&self) -> Result<String, errors::ValidationError> {
Ok(self
.get_encrypted_google_pay_payment_data_mandatory()?
.token
.clone())
}
/// Get the token type from Google Pay tokenization data
/// Returns the token_type string if encrypted data exists, otherwise returns an error
pub fn get_encrypted_token_type(&self) -> Result<String, errors::ValidationError> {
Ok(self
.get_encrypted_google_pay_payment_data_mandatory()?
.token_type
.clone())
}
}
impl GPayPredecryptData {
/// Get the four-digit expiration year from the Google Pay pre-decrypt data
pub fn get_four_digit_expiry_year(&self) -> Result<Secret<String>, errors::ValidationError> {
let mut year = self.card_exp_year.peek().clone();
// If it's a 2-digit year, convert to 4-digit
if year.len() == 2 {
year = format!("20{year}");
} else if year.len() != 4 {
return Err(errors::ValidationError::InvalidValue {
message: format!(
"Invalid expiry year length: {}. Must be 2 or 4 digits",
year.len()
),
}
.into());
}
Ok(Secret::new(year))
}
/// Get the 2-digit expiration year from the Google Pay pre-decrypt data
pub fn get_two_digit_expiry_year(&self) -> Result<Secret<String>, errors::ValidationError> {
let binding = self.card_exp_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ValidationError::InvalidValue {
message: "Invalid two-digit year".to_string(),
})?
.to_string(),
))
}
/// Get the expiry date in MMYY format from the Google Pay pre-decrypt data
pub fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ValidationError> {
let year = self.get_two_digit_expiry_year()?.expose();
let month = self.get_expiry_month()?.clone().expose();
Ok(Secret::new(format!("{month}{year}")))
}
/// Get the expiration month from the Google Pay pre-decrypt data
pub fn get_expiry_month(&self) -> Result<Secret<String>, errors::ValidationError> {
let month_str = self.card_exp_month.peek();
let month = month_str
.parse::<u8>()
.map_err(|_| errors::ValidationError::InvalidValue {
message: format!("Failed to parse expiry month: {month_str}"),
})?;
if !(1..=12).contains(&month) {
return Err(errors::ValidationError::InvalidValue {
message: format!("Invalid expiry month: {month}. Must be between 1 and 12"),
}
.into());
}
Ok(self.card_exp_month.clone())
}
}
#[derive(
Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[serde(untagged)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// This enum is used to represent the Apple Pay payment data, which can either be encrypted or decrypted.
pub enum ApplePayPaymentData {
/// This variant contains the decrypted Apple Pay payment data as a structured object.
#[smithy(value_type = "ApplePayPredecryptData")]
Decrypted(ApplePayPredecryptData),
/// This variant contains the encrypted Apple Pay payment data as a string.
#[smithy(value_type = "String")]
Encrypted(String),
}
#[derive(
Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// This struct represents the decrypted Apple Pay payment data
pub struct ApplePayPredecryptData {
/// The primary account number
#[schema(value_type = String, example = "4242424242424242")]
#[smithy(value_type = "String")]
pub application_primary_account_number: cards::CardNumber,
/// The application expiration date (PAN expiry month)
#[schema(value_type = String, example = "12")]
#[smithy(value_type = "String")]
pub application_expiration_month: Secret<String>,
/// The application expiration date (PAN expiry year)
#[schema(value_type = String, example = "24")]
#[smithy(value_type = "String")]
pub application_expiration_year: Secret<String>,
/// The payment data, which contains the cryptogram and ECI indicator
#[schema(value_type = ApplePayCryptogramData)]
#[smithy(value_type = "ApplePayCryptogramData")]
pub payment_data: ApplePayCryptogramData,
}
#[derive(
Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,
)]
#[serde(rename_all = "snake_case")]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// This struct represents the cryptogram data for Apple Pay transactions
pub struct ApplePayCryptogramData {
/// The online payment cryptogram
#[schema(value_type = String, example = "A1B2C3D4E5F6G7H8")]
#[smithy(value_type = "String")]
pub online_payment_cryptogram: Secret<String>,
/// The ECI (Electronic Commerce Indicator) value
#[schema(value_type = String, example = "05")]
#[smithy(value_type = "Option<String>")]
pub eci_indicator: Option<String>,
}
impl ApplePayPaymentData {
/// Get the encrypted Apple Pay payment data if it exists
pub fn get_encrypted_apple_pay_payment_data_optional(&self) -> Option<&String> {
match self {
Self::Encrypted(encrypted_data) => Some(encrypted_data),
Self::Decrypted(_) => None,
}
}
/// Get the decrypted Apple Pay payment data if it exists
pub fn get_decrypted_apple_pay_payment_data_optional(&self) -> Option<&ApplePayPredecryptData> {
match self {
Self::Encrypted(_) => None,
Self::Decrypted(decrypted_data) => Some(decrypted_data),
}
}
/// Get the encrypted Apple Pay payment data, returning an error if it does not exist
pub fn get_encrypted_apple_pay_payment_data_mandatory(
&self,
) -> Result<&String, errors::ValidationError> {
self.get_encrypted_apple_pay_payment_data_optional()
.get_required_value("Encrypted Apple Pay payment data")
.attach_printable("Encrypted Apple Pay payment data is mandatory")
}
/// Get the decrypted Apple Pay payment data, returning an error if it does not exist
pub fn get_decrypted_apple_pay_payment_data_mandatory(
&self,
) -> Result<&ApplePayPredecryptData, errors::ValidationError> {
self.get_decrypted_apple_pay_payment_data_optional()
.get_required_value("Decrypted Apple Pay payment data")
.attach_printable("Decrypted Apple Pay payment data is mandatory")
}
}
impl ApplePayPredecryptData {
/// Get the four-digit expiration year from the Apple Pay pre-decrypt data
pub fn get_two_digit_expiry_year(&self) -> Result<Secret<String>, errors::ValidationError> {
let binding = self.application_expiration_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ValidationError::InvalidValue {
message: "Invalid two-digit year".to_string(),
})?
.to_string(),
))
}
/// Get the four-digit expiration year from the Apple Pay pre-decrypt data
pub fn get_four_digit_expiry_year(&self) -> Secret<String> {
let mut year = self.application_expiration_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
/// Get the expiration month from the Apple Pay pre-decrypt data
pub fn get_expiry_month(&self) -> Result<Secret<String>, errors::ValidationError> {
let month_str = self.application_expiration_month.peek();
let month = month_str
.parse::<u8>()
.map_err(|_| errors::ValidationError::InvalidValue {
message: format!("Failed to parse expiry month: {month_str}"),
})?;
if !(1..=12).contains(&month) {
return Err(errors::ValidationError::InvalidValue {
message: format!("Invalid expiry month: {month}. Must be between 1 and 12"),
}
.into());
}
Ok(self.application_expiration_month.clone())
}
/// Get the two-digit expiration month from the Apple Pay pre-decrypt data
/// Returns the month with zero-padding if it's a single digit (e.g., "1" -> "01")
pub fn get_two_digit_expiry_month(&self) -> Result<Secret<String>, errors::ValidationError> {
let month_str = self.application_expiration_month.peek();
let month = month_str
.parse::<u8>()
.map_err(|_| errors::ValidationError::InvalidValue {
message: format!("Failed to parse expiry month: {month_str}"),
})?;
if !(1..=12).contains(&month) {
return Err(errors::ValidationError::InvalidValue {
message: format!("Invalid expiry month: {month}. Must be between 1 and 12"),
}
.into());
}
Ok(Secret::new(format!("{:02}", month)))
}
/// Get the expiry date in MMYY format from the Apple Pay pre-decrypt data
pub fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ValidationError> {
let year = self.get_two_digit_expiry_year()?.expose();
let month = self.get_expiry_month()?.expose();
Ok(Secret::new(format!("{month}{year}")))
}
/// Get the expiry date in YYMM format from the Apple Pay pre-decrypt data
pub fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ValidationError> {
let year = self.get_two_digit_expiry_year()?.expose();
let month = self.get_expiry_month()?.expose();
Ok(Secret::new(format!("{year}{month}")))
}
}
/// type of action that needs to taken after consuming recovery payload
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RecoveryAction {
/// Stops the process tracker and update the payment intent.
CancelInvoice,
/// Records the external transaction against payment intent.
ScheduleFailedPayment,
/// Records the external payment and stops the internal process tracker.
SuccessPaymentExternal,
/// Pending payments from billing processor.
PendingPayment,
/// No action required.
NoAction,
/// Invalid event has been received.
InvalidAction,
}
/// Billing Descriptor information to be sent to the payment gateway
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, AsExpression, FromSqlRow, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct BillingDescriptor {
/// name to be put in billing description
#[schema(value_type = Option<String>, example = "The Online Retailer")]
pub name: Option<Secret<String>>,
/// city to be put in billing description
#[schema(value_type = Option<String>, example = "San Francisco")]
pub city: Option<Secret<String>>,
/// phone to be put in billing description
#[schema(value_type = Option<String>, example = "9123456789")]
pub phone: Option<Secret<String>>,
/// a short description for the payment
pub statement_descriptor: Option<String>,
/// Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor.
pub statement_descriptor_suffix: Option<String>,
/// A reference to be shown on billing description
pub reference: Option<String>,
}
impl_to_sql_from_sql_json!(BillingDescriptor);
/// Information identifying partner / external platform details
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, AsExpression, FromSqlRow, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct PartnerApplicationDetails {
/// Name of the partner/external platform
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_link/build.rs | crates/payment_link/build.rs | use std::{collections::HashMap, fs, str::FromStr};
use router_env::env::Env;
use serde::Deserialize;
fn main() {
// Manually deserialize ENVIRONMENT variable to Env enum
let environment = std::env::var("ENVIRONMENT")
.ok()
.and_then(|env_str| Env::from_str(&env_str).ok())
.unwrap_or_else(|| {
#[cfg(debug_assertions)]
let default = Env::Development;
#[cfg(not(debug_assertions))]
let default = Env::Production;
default
});
// Use the payment_link specific SDK URL configuration
let sdk_config_path = "config/sdk_urls.toml";
// Tell cargo to rerun if config file changes
println!("cargo:rerun-if-changed={}", sdk_config_path);
println!("cargo:rerun-if-env-changed=ENVIRONMENT");
// Read and parse SDK URLs TOML file
#[allow(clippy::panic)]
let config_content = fs::read_to_string(sdk_config_path).unwrap_or_else(|e| {
panic!(
"Failed to read SDK config file '{}': {}",
sdk_config_path, e
);
});
#[allow(clippy::panic)]
let config: HashMap<Env, EnvConfig> = toml::from_str(&config_content).unwrap_or_else(|e| {
panic!("Failed to parse TOML in '{}': {}", sdk_config_path, e);
});
// Extract SDK URL for the current environment
#[allow(clippy::panic)]
let sdk_url = config
.get(&environment)
.map(|c| c.sdk_url.as_str())
.unwrap_or_else(|| {
panic!(
"Missing [{}] section in config file: {}",
environment, sdk_config_path
)
});
// Set environment variable for compile-time access
println!("cargo:rustc-env=SDK_URL={}", sdk_url);
}
#[derive(Debug, Deserialize)]
struct EnvConfig {
sdk_url: String,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_link/src/meta_tags.rs | crates/payment_link/src/meta_tags.rs | use api_models::payments::PaymentLinkDetails;
pub fn get_meta_tags_html(payment_details: &PaymentLinkDetails) -> String {
format!(
r#"<meta property="og:title" content="Payment request from {0}"/>
<meta property="og:description" content="{1}"/>"#,
payment_details.merchant_name.clone(),
payment_details
.merchant_description
.clone()
.unwrap_or_default()
)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_link/src/lib.rs | crates/payment_link/src/lib.rs | pub mod css_generator;
pub mod js_generator;
pub mod meta_tags;
pub mod template_renderer;
pub mod types;
#[cfg(feature = "wasm")]
pub mod wasm;
pub use css_generator::get_css_script;
pub use js_generator::get_js_script;
pub use meta_tags::get_meta_tags_html;
pub use template_renderer::{
build_payment_link_html, build_secure_payment_link_html, get_payment_link_status,
};
pub use types::{PaymentLinkFormData, PaymentLinkStatusData};
// WASM bindings - thin wrappers around implementation functions in wasm.rs
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;
/// Generate a payment link HTML preview from configuration JSON
///
/// This function is exported to JavaScript when compiled as WASM.
/// It wraps the implementation function in wasm.rs.
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn generate_payment_link_preview(config_json: &str) -> Result<String, JsValue> {
wasm::generate_payment_link_preview_impl(config_json).map_err(|e| JsValue::from_str(&e))
}
/// Validate payment link configuration and return validation results as JSON
///
/// This function is exported to JavaScript when compiled as WASM.
/// It wraps the implementation function in wasm.rs.
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn validate_payment_link_config(config_json: &str) -> Result<String, JsValue> {
wasm::validate_payment_link_config_impl(config_json).map_err(|e| JsValue::from_str(&e))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_link/src/js_generator.rs | crates/payment_link/src/js_generator.rs | use error_stack::Result;
use serde_json::Value;
#[derive(Debug, thiserror::Error)]
pub enum PaymentLinkError {
#[error("Failed to serialize payment link data")]
SerializationFailed,
}
/// Convert snake_case to camelCase
fn camel_case_key(key: &str) -> String {
let mut out = String::new();
let mut uppercase = false;
for c in key.chars() {
if c == '_' {
uppercase = true;
} else if uppercase {
out.push(c.to_ascii_uppercase());
uppercase = false;
} else {
out.push(c);
}
}
out
}
/// Convert JSON keys to camelCase
fn camel_case_json(value: &mut Value) {
match value {
Value::Object(map) => {
let keys: Vec<String> = map.keys().cloned().collect();
for k in keys {
if let Some(mut v) = map.remove(&k) {
camel_case_json(&mut v);
map.insert(camel_case_key(&k), v);
}
}
}
Value::Array(arr) => {
for v in arr {
camel_case_json(v);
}
}
_ => {}
}
}
/// Only convert the `custom_message_for_payment_method_types` field to camelCase
pub fn convert_custom_message_keys_to_camel(value: &mut Value) {
if let Some(custom_msg) = value.get_mut("custom_message_for_payment_method_types") {
camel_case_json(custom_msg);
}
}
pub fn get_js_script(
payment_details: &api_models::payments::PaymentLinkData,
) -> Result<String, PaymentLinkError> {
let mut json =
serde_json::to_value(payment_details).map_err(|_| PaymentLinkError::SerializationFailed)?;
// Apply camelCase only on the custom_message_for_payment_method_types field
convert_custom_message_keys_to_camel(&mut json);
let payment_details_str =
serde_json::to_string(&json).map_err(|_| PaymentLinkError::SerializationFailed)?;
let url_encoded_str = urlencoding::encode(&payment_details_str);
Ok(format!("window.__PAYMENT_DETAILS = '{}';", url_encoded_str))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_link/src/template_renderer.rs | crates/payment_link/src/template_renderer.rs | use error_stack::{Result, ResultExt};
use tera::{Context, Tera};
use crate::types::{PaymentLinkFormData, PaymentLinkStatusData};
#[derive(Debug, thiserror::Error)]
pub enum PaymentLinkError {
#[error("Failed to render template")]
TemplateRenderError,
#[error("Failed to build template")]
TemplateBuildError,
}
pub fn build_payment_link_html(
payment_link_data: PaymentLinkFormData,
) -> Result<String, PaymentLinkError> {
let (tera, mut context) = build_payment_link_template(payment_link_data)
.change_context(PaymentLinkError::TemplateBuildError)
.attach_printable("Failed to build payment link's HTML template")?;
let payment_link_initiator = include_str!(
"../../router/src/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)
.change_context(PaymentLinkError::TemplateRenderError)
.attach_printable("Error while rendering open payment link's HTML template")
}
pub fn build_secure_payment_link_html(
payment_link_data: PaymentLinkFormData,
) -> Result<String, PaymentLinkError> {
let (tera, mut context) = build_payment_link_template(payment_link_data)
.change_context(PaymentLinkError::TemplateBuildError)
.attach_printable("Failed to build payment link's HTML template")?;
let payment_link_initiator = include_str!(
"../../router/src/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)
.change_context(PaymentLinkError::TemplateRenderError)
.attach_printable("Error while rendering secure payment link's HTML template")
}
fn build_payment_link_template(
payment_link_data: PaymentLinkFormData,
) -> Result<(Tera, Context), PaymentLinkError> {
let mut tera = Tera::default();
let css_template =
include_str!("../../router/src/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 = tera
.render("payment_link_css", &context)
.change_context(PaymentLinkError::TemplateRenderError)?;
let js_template =
include_str!("../../router/src/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(PaymentLinkError::TemplateBuildError)
.attach_printable("Host missing for payment link SDK URL")
.and_then(|host| {
if host == "localhost" {
let port = payment_link_data
.sdk_url
.port()
.ok_or(PaymentLinkError::TemplateBuildError)
.attach_printable("Port missing for localhost in SDK URL")?;
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 = tera
.render("payment_link_js", &context)
.change_context(PaymentLinkError::TemplateRenderError)?;
let logging_template =
include_str!("../../router/src/services/redirection/assets/redirect_error_logs_push.js")
.to_string();
let locale_template = include_str!("../../router/src/core/payment_link/locale.js").to_string();
let html_template =
include_str!("../../router/src/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))
}
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,
) -> Result<String, PaymentLinkError> {
let mut tera = Tera::default();
// Add modification to css template with dynamic data
let css_template =
include_str!("../../router/src/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 = tera
.render("payment_link_css", &context)
.change_context(PaymentLinkError::TemplateRenderError)?;
//Locale template
let locale_template = include_str!("../../router/src/core/payment_link/locale.js");
// Logging template
let logging_template =
include_str!("../../router/src/services/redirection/assets/redirect_error_logs_push.js")
.to_string();
// Add modification to js template with dynamic data
let js_template =
include_str!("../../router/src/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 = tera
.render("payment_link_js", &context)
.change_context(PaymentLinkError::TemplateRenderError)?;
// Modify Html template with rendered js and rendered css files
let html_template =
include_str!("../../router/src/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);
tera.render("payment_link_status", &context)
.change_context(PaymentLinkError::TemplateRenderError)
.attach_printable("Error while rendering payment link status page")
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_link/src/types.rs | crates/payment_link/src/types.rs | //! Payment link specific types
use common_utils::{
events::{ApiEventMetric, ApiEventsType},
impl_api_event_type,
};
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentLinkFormData {
pub js_script: String,
pub css_script: String,
pub sdk_url: url::Url,
pub html_meta_tags: String,
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentLinkStatusData {
pub js_script: String,
pub css_script: String,
}
impl_api_event_type!(Miscellaneous, (PaymentLinkFormData, PaymentLinkStatusData));
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_link/src/wasm.rs | crates/payment_link/src/wasm.rs | use api_models::{admin::PaymentLinkConfig, payments::PaymentLinkData};
use crate::{
build_payment_link_html, get_css_script, get_js_script, get_meta_tags_html, PaymentLinkFormData,
};
const SDK_URL: &str = env!("SDK_URL");
/// Implementation function for generating payment link preview
/// Called by the wasm_bindgen wrapper in lib.rs
pub fn generate_payment_link_preview_impl(config_json: &str) -> Result<String, String> {
let payment_link_details: api_models::payments::PaymentLinkDetails =
serde_json::from_str(config_json)
.map_err(|e| format!("Failed to deserialize PaymentLinkDetails: {}", e))?;
let mut payment_link_config = PaymentLinkConfig {
theme: payment_link_details.theme.clone(),
logo: payment_link_details.merchant_logo.clone(),
seller_name: payment_link_details.merchant_name.clone(),
sdk_layout: payment_link_details.sdk_layout.clone(),
display_sdk_only: payment_link_details.display_sdk_only,
hide_card_nickname_field: payment_link_details.hide_card_nickname_field,
show_card_form_by_default: payment_link_details.show_card_form_by_default,
transaction_details: payment_link_details.transaction_details.clone(),
background_image: payment_link_details.background_image.clone(),
details_layout: payment_link_details.details_layout,
branding_visibility: payment_link_details.branding_visibility,
payment_button_text: payment_link_details.payment_button_text.clone(),
custom_message_for_card_terms: payment_link_details.custom_message_for_card_terms.clone(),
payment_button_colour: payment_link_details.payment_button_colour.clone(),
skip_status_screen: payment_link_details.skip_status_screen,
background_colour: payment_link_details.background_colour.clone(),
payment_button_text_colour: payment_link_details.payment_button_text_colour.clone(),
sdk_ui_rules: payment_link_details.sdk_ui_rules.clone(),
enable_button_only_on_form_ready: payment_link_details.enable_button_only_on_form_ready,
payment_form_header_text: payment_link_details.payment_form_header_text.clone(),
payment_form_label_type: payment_link_details.payment_form_label_type,
show_card_terms: payment_link_details.show_card_terms,
is_setup_mandate_flow: payment_link_details.is_setup_mandate_flow,
color_icon_card_cvc_error: payment_link_details.color_icon_card_cvc_error.clone(),
enabled_saved_payment_method: false,
allowed_domains: None,
payment_link_ui_rules: None,
custom_message_for_payment_method_types: payment_link_details
.custom_message_for_payment_method_types
.clone(),
};
if let Ok(config_from_json) = serde_json::from_str::<PaymentLinkConfig>(config_json) {
payment_link_config.enabled_saved_payment_method =
config_from_json.enabled_saved_payment_method;
payment_link_config.allowed_domains = config_from_json.allowed_domains;
payment_link_config.payment_link_ui_rules = config_from_json.payment_link_ui_rules;
}
let sdk_url = url::Url::parse(SDK_URL).map_err(|e| format!("Invalid SDK URL: {}", e))?;
let js_script = get_js_script(&PaymentLinkData::PaymentLinkDetails(Box::new(
payment_link_details.clone(),
)))
.map_err(|e| format!("Failed to generate JS script: {:?}", e))?;
let css_script = get_css_script(&payment_link_config)
.map_err(|e| format!("Failed to generate CSS script: {:?}", e))?;
let html_meta_tags = get_meta_tags_html(&payment_link_details);
let payment_link_form_data = PaymentLinkFormData {
js_script,
sdk_url,
css_script,
html_meta_tags,
};
build_payment_link_html(payment_link_form_data)
.map_err(|e| format!("Failed to build payment link HTML: {:?}", e))
}
/// Implementation function for validating payment link config
/// Called by the wasm_bindgen wrapper in lib.rs
pub fn validate_payment_link_config_impl(config_json: &str) -> Result<String, String> {
let config: api_models::payments::PaymentLinkDetails =
serde_json::from_str(config_json).map_err(|e| format!("Failed to parse config: {}", e))?;
let mut errors = Vec::new();
let mut warnings = Vec::new();
if !config.theme.starts_with('#') || config.theme.len() != 7 {
errors.push("Theme color must be a valid hex color (e.g., #4E6ADD)".to_string());
}
if let Some(bg_color) = &config.background_colour {
if !bg_color.starts_with('#') || bg_color.len() != 7 {
errors.push("Background color must be a valid hex color (e.g., #FFFFFF)".to_string());
}
}
if !config.merchant_logo.is_empty() && !config.merchant_logo.starts_with("http") {
warnings.push("Merchant logo should be a valid HTTP/HTTPS URL".to_string());
}
let valid_layouts = ["accordion", "tabs", "spaced_accordion"];
if !valid_layouts.contains(&config.sdk_layout.as_str()) {
errors.push(format!(
"SDK layout must be one of: {}",
valid_layouts.join(", ")
));
}
if config.merchant_name.is_empty() {
errors.push("Merchant name is required".to_string());
}
if config.client_secret.is_empty() {
errors.push("Client secret is required".to_string());
}
if config.pub_key.is_empty() {
errors.push("Publishable key is required".to_string());
}
let validation_result = serde_json::json!({
"valid": errors.is_empty(),
"errors": errors,
"warnings": warnings
});
Ok(validation_result.to_string())
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/payment_link/src/css_generator.rs | crates/payment_link/src/css_generator.rs | use std::collections::HashMap;
use api_models::admin::PaymentLinkConfig;
use error_stack::{Result, ResultExt};
#[derive(Debug, thiserror::Error)]
pub enum PaymentLinkError {
#[error("Invalid CSS selector: {0}")]
InvalidCssSelector(String),
}
pub fn get_css_script(payment_link_config: &PaymentLinkConfig) -> Result<String, PaymentLinkError> {
let custom_rules_css_option = payment_link_config
.payment_link_ui_rules
.as_ref()
.map(generate_dynamic_css)
.transpose()?;
let color_scheme_css = get_color_scheme_css(payment_link_config);
if let Some(custom_rules_css) = custom_rules_css_option {
Ok(format!("{color_scheme_css}\n{custom_rules_css}"))
} else {
Ok(color_scheme_css)
}
}
fn get_color_scheme_css(payment_link_config: &PaymentLinkConfig) -> String {
let background_primary_color = payment_link_config
.background_colour
.clone()
.unwrap_or(payment_link_config.theme.clone());
format!(
":root {{
--primary-color: {background_primary_color};
}}"
)
}
fn generate_dynamic_css(
rules: &HashMap<String, HashMap<String, String>>,
) -> Result<String, PaymentLinkError> {
if rules.is_empty() {
return Ok(String::new());
}
let mut css_string = String::new();
css_string.push_str("/* Dynamically Injected UI Rules */\n");
for (selector, styles_map) in rules {
if selector.trim().is_empty() {
return Err(PaymentLinkError::InvalidCssSelector(
"CSS selector cannot be empty.".to_string(),
))
.attach_printable("Empty CSS selector found in payment_link_ui_rules")?;
}
css_string.push_str(selector);
css_string.push_str(" {\n");
for (prop_camel_case, css_value) in styles_map {
let css_property = camel_to_kebab(prop_camel_case);
css_string.push_str(" ");
css_string.push_str(&css_property);
css_string.push_str(": ");
css_string.push_str(css_value);
css_string.push_str(";\n");
}
css_string.push_str("}\n");
}
Ok(css_string)
}
fn camel_to_kebab(s: &str) -> String {
let mut result = String::new();
if s.is_empty() {
return result;
}
let chars: Vec<char> = s.chars().collect();
for (i, &ch) in chars.iter().enumerate() {
if ch.is_uppercase() {
let should_add_dash = i > 0
&& (chars.get(i - 1).map(|c| c.is_lowercase()).unwrap_or(false)
|| (i + 1 < chars.len()
&& chars.get(i + 1).map(|c| c.is_lowercase()).unwrap_or(false)
&& chars.get(i - 1).map(|c| c.is_uppercase()).unwrap_or(false)));
if should_add_dash {
result.push('-');
}
result.push(ch.to_ascii_lowercase());
} else {
result.push(ch);
}
}
result
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/lib.rs | crates/euclid/src/lib.rs | #![allow(clippy::result_large_err)]
pub mod backend;
pub mod dssa;
pub mod enums;
pub mod frontend;
pub mod types;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/backend.rs | crates/euclid/src/backend.rs | pub mod inputs;
pub mod interpreter;
#[cfg(feature = "valued_jit")]
pub mod vir_interpreter;
pub use inputs::BackendInput;
pub use interpreter::InterpreterBackend;
#[cfg(feature = "valued_jit")]
pub use vir_interpreter::VirInterpreterBackend;
use crate::frontend::ast;
#[derive(Debug, Clone, serde::Serialize)]
pub struct BackendOutput<O> {
pub rule_name: Option<String>,
pub connector_selection: O,
}
impl<O> BackendOutput<O> {
// get_connector_selection
pub fn get_output(&self) -> &O {
&self.connector_selection
}
}
pub trait EuclidBackend<O>: Sized {
type Error: serde::Serialize;
fn with_program(program: ast::Program<O>) -> Result<Self, Self::Error>;
fn execute(&self, input: BackendInput) -> Result<BackendOutput<O>, Self::Error>;
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/enums.rs | crates/euclid/src/enums.rs | use common_enums::connector_enums::Connector;
pub use common_enums::{
AuthenticationType, CaptureMethod, CardNetwork, Country, CountryAlpha2, Currency,
FutureUsage as SetupFutureUsage, PaymentMethod, PaymentMethodType,
};
use strum::VariantNames;
use utoipa::ToSchema;
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,
}
#[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,
Payjustnow,
Payjustnowinstore,
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,
Zift,
Plaid,
Zsl,
Juspaythreedsserver,
CtpMastercard,
CtpVisa,
Netcetera,
Cardinal,
Threedsecureio,
}
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::Zift => Ok(Self::Zift),
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::Payjustnow => Ok(Self::Payjustnow),
Connector::Payjustnowinstore => Ok(Self::Payjustnowinstore),
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"),
}
}
}
/// 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::Zift => Self::Zift,
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,
RoutableConnectors::Payjustnow => Self::Payjustnow,
RoutableConnectors::Payjustnowinstore => Self::Payjustnowinstore,
RoutableConnectors::Juspaythreedsserver => Self::Juspaythreedsserver,
RoutableConnectors::CtpMastercard => Self::CtpMastercard,
RoutableConnectors::CtpVisa => Self::CtpVisa,
RoutableConnectors::Netcetera => Self::Netcetera,
RoutableConnectors::Cardinal => Self::Cardinal,
RoutableConnectors::Threedsecureio => Self::Threedsecureio,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/types.rs | crates/euclid/src/types.rs | pub mod transformers;
use common_utils::types::MinorUnit;
use euclid_macros::EnumNums;
use serde::{Deserialize, Serialize};
use strum::VariantNames;
use crate::{
dssa::types::EuclidAnalysable,
enums,
frontend::{
ast,
dir::{
enums::{
CustomerDeviceDisplaySize, CustomerDevicePlatform, CustomerDeviceType,
TransactionInitiator,
},
DirKeyKind, DirValue, EuclidDirFilter,
},
},
};
pub type Metadata = std::collections::HashMap<String, serde_json::Value>;
#[derive(
Debug,
Clone,
EnumNums,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumString,
)]
pub enum EuclidKey {
#[strum(serialize = "payment_method")]
PaymentMethod,
#[strum(serialize = "card_bin")]
CardBin,
#[strum(serialize = "extended_card_bin")]
ExtendedCardBin,
#[strum(serialize = "metadata")]
Metadata,
#[strum(serialize = "mandate_type")]
MandateType,
#[strum(serialize = "mandate_acceptance_type")]
MandateAcceptanceType,
#[strum(serialize = "payment_type")]
PaymentType,
#[strum(serialize = "payment_method_type")]
PaymentMethodType,
#[strum(serialize = "card_network")]
CardNetwork,
#[strum(serialize = "authentication_type")]
AuthenticationType,
#[strum(serialize = "capture_method")]
CaptureMethod,
#[strum(serialize = "amount")]
PaymentAmount,
#[strum(serialize = "currency")]
PaymentCurrency,
#[cfg(feature = "payouts")]
#[strum(serialize = "payout_currency")]
PayoutCurrency,
#[strum(serialize = "country", to_string = "business_country")]
BusinessCountry,
#[strum(serialize = "billing_country")]
BillingCountry,
#[strum(serialize = "business_label")]
BusinessLabel,
#[strum(serialize = "setup_future_usage")]
SetupFutureUsage,
#[strum(serialize = "issuer_name")]
IssuerName,
#[strum(serialize = "issuer_country")]
IssuerCountry,
#[strum(serialize = "acquirer_country")]
AcquirerCountry,
#[strum(serialize = "acquirer_fraud_rate")]
AcquirerFraudRate,
#[strum(serialize = "customer_device_type")]
CustomerDeviceType,
#[strum(serialize = "customer_device_display_size")]
CustomerDeviceDisplaySize,
#[strum(serialize = "customer_device_platform")]
CustomerDevicePlatform,
#[strum(serialize = "transaction_initiator")]
TransactionInitiator,
}
impl EuclidDirFilter for DummyOutput {
const ALLOWED: &'static [DirKeyKind] = &[
DirKeyKind::AuthenticationType,
DirKeyKind::PaymentMethod,
DirKeyKind::CardType,
DirKeyKind::PaymentCurrency,
DirKeyKind::CaptureMethod,
DirKeyKind::AuthenticationType,
DirKeyKind::CardBin,
DirKeyKind::ExtendedCardBin,
DirKeyKind::PayLaterType,
DirKeyKind::PaymentAmount,
DirKeyKind::MetaData,
DirKeyKind::MandateAcceptanceType,
DirKeyKind::MandateType,
DirKeyKind::PaymentType,
DirKeyKind::SetupFutureUsage,
DirKeyKind::TransactionInitiator,
];
}
impl EuclidAnalysable for DummyOutput {
fn get_dir_value_for_analysis(&self, rule_name: String) -> Vec<(DirValue, Metadata)> {
self.outputs
.iter()
.map(|dummyc| {
let metadata_key = "MetadataKey".to_string();
let metadata_value = dummyc;
(
DirValue::MetaData(MetadataValue {
key: metadata_key.clone(),
value: metadata_value.clone(),
}),
std::collections::HashMap::from_iter([(
"DUMMY_OUTPUT".to_string(),
serde_json::json!({
"rule_name":rule_name,
"Metadata_Key" :metadata_key,
"Metadata_Value" : metadata_value,
}),
)]),
)
})
.collect()
}
}
#[derive(Debug, Clone, Serialize)]
pub struct DummyOutput {
pub outputs: Vec<String>,
}
#[derive(Debug, Clone, serde::Serialize, strum::Display)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum DataType {
Number,
EnumVariant,
MetadataValue,
StrValue,
}
impl EuclidKey {
pub fn key_type(&self) -> DataType {
match self {
Self::PaymentMethod => DataType::EnumVariant,
Self::CardBin => DataType::StrValue,
Self::ExtendedCardBin => DataType::StrValue,
Self::Metadata => DataType::MetadataValue,
Self::PaymentMethodType => DataType::EnumVariant,
Self::CardNetwork => DataType::EnumVariant,
Self::AuthenticationType => DataType::EnumVariant,
Self::CaptureMethod => DataType::EnumVariant,
Self::PaymentAmount => DataType::Number,
Self::PaymentCurrency => DataType::EnumVariant,
#[cfg(feature = "payouts")]
Self::PayoutCurrency => DataType::EnumVariant,
Self::BusinessCountry => DataType::EnumVariant,
Self::BillingCountry => DataType::EnumVariant,
Self::MandateType => DataType::EnumVariant,
Self::MandateAcceptanceType => DataType::EnumVariant,
Self::PaymentType => DataType::EnumVariant,
Self::BusinessLabel => DataType::StrValue,
Self::SetupFutureUsage => DataType::EnumVariant,
Self::IssuerName => DataType::StrValue,
Self::IssuerCountry => DataType::EnumVariant,
Self::AcquirerCountry => DataType::EnumVariant,
Self::AcquirerFraudRate => DataType::Number,
Self::CustomerDeviceType => DataType::EnumVariant,
Self::CustomerDeviceDisplaySize => DataType::EnumVariant,
Self::CustomerDevicePlatform => DataType::EnumVariant,
Self::TransactionInitiator => DataType::EnumVariant,
}
}
}
enums::collect_variants!(EuclidKey);
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NumValueRefinement {
NotEqual,
GreaterThan,
LessThan,
GreaterThanEqual,
LessThanEqual,
}
impl From<ast::ComparisonType> for Option<NumValueRefinement> {
fn from(comp_type: ast::ComparisonType) -> Self {
match comp_type {
ast::ComparisonType::Equal => None,
ast::ComparisonType::NotEqual => Some(NumValueRefinement::NotEqual),
ast::ComparisonType::GreaterThan => Some(NumValueRefinement::GreaterThan),
ast::ComparisonType::LessThan => Some(NumValueRefinement::LessThan),
ast::ComparisonType::LessThanEqual => Some(NumValueRefinement::LessThanEqual),
ast::ComparisonType::GreaterThanEqual => Some(NumValueRefinement::GreaterThanEqual),
}
}
}
impl From<NumValueRefinement> for ast::ComparisonType {
fn from(value: NumValueRefinement) -> Self {
match value {
NumValueRefinement::NotEqual => Self::NotEqual,
NumValueRefinement::LessThan => Self::LessThan,
NumValueRefinement::GreaterThan => Self::GreaterThan,
NumValueRefinement::GreaterThanEqual => Self::GreaterThanEqual,
NumValueRefinement::LessThanEqual => Self::LessThanEqual,
}
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct StrValue {
pub value: String,
}
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct MetadataValue {
pub key: String,
pub value: String,
}
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct NumValue {
pub number: MinorUnit,
pub refinement: Option<NumValueRefinement>,
}
impl NumValue {
pub fn fits(&self, other: &Self) -> bool {
let this_num = self.number;
let other_num = other.number;
match (&self.refinement, &other.refinement) {
(None, None) => this_num == other_num,
(Some(NumValueRefinement::GreaterThan), None) => other_num > this_num,
(Some(NumValueRefinement::LessThan), None) => other_num < this_num,
(Some(NumValueRefinement::NotEqual), Some(NumValueRefinement::NotEqual)) => {
other_num == this_num
}
(Some(NumValueRefinement::GreaterThan), Some(NumValueRefinement::GreaterThan)) => {
other_num > this_num
}
(Some(NumValueRefinement::LessThan), Some(NumValueRefinement::LessThan)) => {
other_num < this_num
}
(Some(NumValueRefinement::GreaterThanEqual), None) => other_num >= this_num,
(Some(NumValueRefinement::LessThanEqual), None) => other_num <= this_num,
(
Some(NumValueRefinement::GreaterThanEqual),
Some(NumValueRefinement::GreaterThanEqual),
) => other_num >= this_num,
(Some(NumValueRefinement::LessThanEqual), Some(NumValueRefinement::LessThanEqual)) => {
other_num <= this_num
}
_ => false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum EuclidValue {
PaymentMethod(enums::PaymentMethod),
CardBin(StrValue),
ExtendedCardBin(StrValue),
Metadata(MetadataValue),
PaymentMethodType(enums::PaymentMethodType),
CardNetwork(enums::CardNetwork),
AuthenticationType(enums::AuthenticationType),
CaptureMethod(enums::CaptureMethod),
PaymentType(enums::PaymentType),
MandateAcceptanceType(enums::MandateAcceptanceType),
MandateType(enums::MandateType),
PaymentAmount(NumValue),
PaymentCurrency(enums::Currency),
#[cfg(feature = "payouts")]
PayoutCurrency(enums::Currency),
BusinessCountry(enums::Country),
BillingCountry(enums::Country),
BusinessLabel(StrValue),
SetupFutureUsage(enums::SetupFutureUsage),
IssuerName(StrValue),
IssuerCountry(enums::Country),
AcquirerCountry(enums::Country),
AcquirerFraudRate(NumValue),
CustomerDeviceType(CustomerDeviceType),
CustomerDeviceDisplaySize(CustomerDeviceDisplaySize),
CustomerDevicePlatform(CustomerDevicePlatform),
TransactionInitiator(TransactionInitiator),
}
impl EuclidValue {
pub fn get_num_value(&self) -> Option<NumValue> {
match self {
Self::PaymentAmount(val) => Some(val.clone()),
_ => None,
}
}
pub fn get_key(&self) -> EuclidKey {
match self {
Self::PaymentMethod(_) => EuclidKey::PaymentMethod,
Self::CardBin(_) => EuclidKey::CardBin,
Self::ExtendedCardBin(_) => EuclidKey::ExtendedCardBin,
Self::Metadata(_) => EuclidKey::Metadata,
Self::PaymentMethodType(_) => EuclidKey::PaymentMethodType,
Self::MandateType(_) => EuclidKey::MandateType,
Self::PaymentType(_) => EuclidKey::PaymentType,
Self::MandateAcceptanceType(_) => EuclidKey::MandateAcceptanceType,
Self::CardNetwork(_) => EuclidKey::CardNetwork,
Self::AuthenticationType(_) => EuclidKey::AuthenticationType,
Self::CaptureMethod(_) => EuclidKey::CaptureMethod,
Self::PaymentAmount(_) => EuclidKey::PaymentAmount,
Self::PaymentCurrency(_) => EuclidKey::PaymentCurrency,
#[cfg(feature = "payouts")]
Self::PayoutCurrency(_) => EuclidKey::PayoutCurrency,
Self::BusinessCountry(_) => EuclidKey::BusinessCountry,
Self::BillingCountry(_) => EuclidKey::BillingCountry,
Self::BusinessLabel(_) => EuclidKey::BusinessLabel,
Self::SetupFutureUsage(_) => EuclidKey::SetupFutureUsage,
Self::IssuerName(_) => EuclidKey::IssuerName,
Self::IssuerCountry(_) => EuclidKey::IssuerCountry,
Self::AcquirerCountry(_) => EuclidKey::AcquirerCountry,
Self::AcquirerFraudRate(_) => EuclidKey::AcquirerFraudRate,
Self::CustomerDeviceType(_) => EuclidKey::CustomerDeviceType,
Self::CustomerDeviceDisplaySize(_) => EuclidKey::CustomerDeviceDisplaySize,
Self::CustomerDevicePlatform(_) => EuclidKey::CustomerDevicePlatform,
Self::TransactionInitiator(_) => EuclidKey::TransactionInitiator,
}
}
}
#[cfg(test)]
mod global_type_tests {
use super::*;
#[test]
fn test_num_value_fits_greater_than() {
let val1 = NumValue {
number: MinorUnit::new(10),
refinement: Some(NumValueRefinement::GreaterThan),
};
let val2 = NumValue {
number: MinorUnit::new(30),
refinement: Some(NumValueRefinement::GreaterThan),
};
assert!(val1.fits(&val2))
}
#[test]
fn test_num_value_fits_less_than() {
let val1 = NumValue {
number: MinorUnit::new(30),
refinement: Some(NumValueRefinement::LessThan),
};
let val2 = NumValue {
number: MinorUnit::new(10),
refinement: Some(NumValueRefinement::LessThan),
};
assert!(val1.fits(&val2));
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/dssa.rs | crates/euclid/src/dssa.rs | //! Domain Specific Static Analyzer
pub mod analyzer;
pub mod graph;
pub mod state_machine;
pub mod truth;
pub mod types;
pub mod utils;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/frontend.rs | crates/euclid/src/frontend.rs | pub mod ast;
pub mod dir;
pub mod vir;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/dssa/analyzer.rs | crates/euclid/src/dssa/analyzer.rs | //! Static Analysis for the Euclid Rule DSL
//!
//! Exposes certain functions that can be used to perform static analysis over programs
//! in the Euclid Rule DSL. These include standard control flow analyses like testing
//! conflicting assertions, to Domain Specific Analyses making use of the
//! [`Knowledge Graph Framework`](crate::dssa::graph).
use hyperswitch_constraint_graph::{ConstraintGraph, Memoization};
use rustc_hash::{FxHashMap, FxHashSet};
use crate::{
dssa::{
graph::CgraphExt,
state_machine, truth,
types::{self, EuclidAnalysable},
},
frontend::{
ast,
dir::{self, EuclidDirFilter},
vir,
},
types::{DataType, Metadata},
};
/// Analyses conflicting assertions on the same key in a conjunctive context.
///
/// For example,
/// ```notrust
/// payment_method = card && ... && payment_method = bank_debit
/// ```notrust
/// This is a condition that will never evaluate to `true` given a single
/// payment method and needs to be caught in analysis.
pub fn analyze_conflicting_assertions(
keywise_assertions: &FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>>,
assertion_metadata: &FxHashMap<&dir::DirValue, &Metadata>,
) -> Result<(), types::AnalysisError> {
for (key, value_set) in keywise_assertions {
if value_set.len() > 1 {
let err_type = types::AnalysisErrorType::ConflictingAssertions {
key: key.clone(),
values: value_set
.iter()
.map(|val| types::ValueData {
value: (*val).clone(),
metadata: assertion_metadata
.get(val)
.map(|meta| (*meta).clone())
.unwrap_or_default(),
})
.collect(),
};
Err(types::AnalysisError {
error_type: err_type,
metadata: Default::default(),
})?;
}
}
Ok(())
}
/// Analyses exhaustive negations on the same key in a conjunctive context.
///
/// For example,
/// ```notrust
/// authentication_type /= three_ds && ... && authentication_type /= no_three_ds
/// ```notrust
/// This is a condition that will never evaluate to `true` given any authentication_type
/// since all the possible values authentication_type can take have been negated.
pub fn analyze_exhaustive_negations(
keywise_negations: &FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>>,
keywise_negation_metadata: &FxHashMap<dir::DirKey, Vec<&Metadata>>,
) -> Result<(), types::AnalysisError> {
for (key, negation_set) in keywise_negations {
let mut value_set = if let Some(set) = key.kind.get_value_set() {
set
} else {
continue;
};
value_set.retain(|val| !negation_set.contains(val));
if value_set.is_empty() {
let error_type = types::AnalysisErrorType::ExhaustiveNegation {
key: key.clone(),
metadata: keywise_negation_metadata
.get(key)
.cloned()
.unwrap_or_default()
.iter()
.copied()
.cloned()
.collect(),
};
Err(types::AnalysisError {
error_type,
metadata: Default::default(),
})?;
}
}
Ok(())
}
fn analyze_negated_assertions(
keywise_assertions: &FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>>,
assertion_metadata: &FxHashMap<&dir::DirValue, &Metadata>,
keywise_negations: &FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>>,
negation_metadata: &FxHashMap<&dir::DirValue, &Metadata>,
) -> Result<(), types::AnalysisError> {
for (key, negation_set) in keywise_negations {
let assertion_set = if let Some(set) = keywise_assertions.get(key) {
set
} else {
continue;
};
let intersection = negation_set & assertion_set;
intersection.iter().next().map_or(Ok(()), |val| {
let error_type = types::AnalysisErrorType::NegatedAssertion {
value: (*val).clone(),
assertion_metadata: assertion_metadata
.get(*val)
.copied()
.cloned()
.unwrap_or_default(),
negation_metadata: negation_metadata
.get(*val)
.copied()
.cloned()
.unwrap_or_default(),
};
Err(types::AnalysisError {
error_type,
metadata: Default::default(),
})
})?;
}
Ok(())
}
fn perform_condition_analyses(
context: &types::ConjunctiveContext<'_>,
) -> Result<(), types::AnalysisError> {
let mut assertion_metadata: FxHashMap<&dir::DirValue, &Metadata> = FxHashMap::default();
let mut keywise_assertions: FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>> =
FxHashMap::default();
let mut negation_metadata: FxHashMap<&dir::DirValue, &Metadata> = FxHashMap::default();
let mut keywise_negation_metadata: FxHashMap<dir::DirKey, Vec<&Metadata>> =
FxHashMap::default();
let mut keywise_negations: FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>> =
FxHashMap::default();
for ctx_val in context {
let key = if let Some(k) = ctx_val.value.get_key() {
k
} else {
continue;
};
if let dir::DirKeyKind::Connector = key.kind {
continue;
}
if !matches!(key.kind.get_type(), DataType::EnumVariant) {
continue;
}
match ctx_val.value {
types::CtxValueKind::Assertion(val) => {
keywise_assertions
.entry(key.clone())
.or_default()
.insert(val);
assertion_metadata.insert(val, ctx_val.metadata);
}
types::CtxValueKind::Negation(vals) => {
let negation_set = keywise_negations.entry(key.clone()).or_default();
for val in vals {
negation_set.insert(val);
negation_metadata.insert(val, ctx_val.metadata);
}
keywise_negation_metadata
.entry(key.clone())
.or_default()
.push(ctx_val.metadata);
}
}
}
analyze_conflicting_assertions(&keywise_assertions, &assertion_metadata)?;
analyze_exhaustive_negations(&keywise_negations, &keywise_negation_metadata)?;
analyze_negated_assertions(
&keywise_assertions,
&assertion_metadata,
&keywise_negations,
&negation_metadata,
)?;
Ok(())
}
fn perform_context_analyses(
context: &types::ConjunctiveContext<'_>,
knowledge_graph: &ConstraintGraph<dir::DirValue>,
) -> Result<(), types::AnalysisError> {
perform_condition_analyses(context)?;
let mut memo = Memoization::new();
knowledge_graph
.perform_context_analysis(context, &mut memo, None)
.map_err(|err| types::AnalysisError {
error_type: types::AnalysisErrorType::GraphAnalysis(err, memo),
metadata: Default::default(),
})?;
Ok(())
}
pub fn analyze<O: EuclidAnalysable + EuclidDirFilter>(
program: ast::Program<O>,
knowledge_graph: Option<&ConstraintGraph<dir::DirValue>>,
) -> Result<vir::ValuedProgram<O>, types::AnalysisError> {
let dir_program = ast::lowering::lower_program(program)?;
let selection_data = state_machine::make_connector_selection_data(&dir_program);
let mut ctx_manager = state_machine::AnalysisContextManager::new(&dir_program, &selection_data);
while let Some(ctx) = ctx_manager.advance().map_err(|err| types::AnalysisError {
metadata: Default::default(),
error_type: types::AnalysisErrorType::StateMachine(err),
})? {
perform_context_analyses(ctx, knowledge_graph.unwrap_or(&truth::ANALYSIS_GRAPH))?;
}
dir::lowering::lower_program(dir_program)
}
#[cfg(all(test, feature = "ast_parser"))]
mod tests {
use std::{ops::Deref, sync::Weak};
use euclid_macros::knowledge;
use hyperswitch_constraint_graph as cgraph;
use super::*;
#[allow(unused_imports)] // Required by the `knowledge!` macro expansion
use crate::dssa::graph::euclid_graph_prelude;
use crate::{dirval, dssa::graph, types::DummyOutput};
#[test]
fn test_conflicting_assertion_detection() {
let program_str = r#"
default: ["stripe", "adyen"]
stripe_first: ["stripe", "adyen"]
{
payment_method = wallet {
amount > 500 & capture_method = automatic
amount < 500 & payment_method = card
}
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let analysis_result = analyze(program, None);
if let Err(types::AnalysisError {
error_type: types::AnalysisErrorType::ConflictingAssertions { key, values },
..
}) = analysis_result
{
assert!(
matches!(key.kind, dir::DirKeyKind::PaymentMethod),
"Key should be payment_method"
);
let values: Vec<dir::DirValue> = values.into_iter().map(|v| v.value).collect();
assert_eq!(values.len(), 2, "There should be 2 conflicting conditions");
assert!(
values.contains(&dirval!(PaymentMethod = Wallet)),
"Condition should include payment_method = wallet"
);
assert!(
values.contains(&dirval!(PaymentMethod = Card)),
"Condition should include payment_method = card"
);
} else {
panic!("Did not receive conflicting assertions error");
}
}
#[test]
fn test_exhaustive_negation_detection() {
let program_str = r#"
default: ["stripe"]
rule_1: ["adyen"]
{
payment_method /= wallet {
capture_method = manual & payment_method /= card {
authentication_type = three_ds & payment_method /= pay_later {
amount > 1000 & payment_method /= bank_redirect {
payment_method /= crypto
& payment_method /= bank_debit
& payment_method /= bank_transfer
& payment_method /= upi
& payment_method /= reward
& payment_method /= voucher
& payment_method /= gift_card
& payment_method /= card_redirect
& payment_method /= real_time_payment
& payment_method /= open_banking
& payment_method /= mobile_payment
}
}
}
}
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let analysis_result = analyze(program, None);
if let Err(types::AnalysisError {
error_type: types::AnalysisErrorType::ExhaustiveNegation { key, .. },
..
}) = analysis_result
{
assert!(
matches!(key.kind, dir::DirKeyKind::PaymentMethod),
"Expected key to be payment_method"
);
} else {
panic!("Expected exhaustive negation error");
}
}
#[test]
fn test_negated_assertions_detection() {
let program_str = r#"
default: ["stripe"]
rule_1: ["adyen"]
{
payment_method = wallet {
amount > 500 {
capture_method = automatic
}
amount < 501 {
payment_method /= wallet
}
}
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let analysis_result = analyze(program, None);
if let Err(types::AnalysisError {
error_type: types::AnalysisErrorType::NegatedAssertion { value, .. },
..
}) = analysis_result
{
assert_eq!(
value,
dirval!(PaymentMethod = Wallet),
"Expected to catch payment_method = wallet as conflict"
);
} else {
panic!("Expected negated assertion error");
}
}
#[test]
fn test_negation_graph_analysis() {
let graph = knowledge! {
CaptureMethod(Automatic) ->> PaymentMethod(Card);
};
let program_str = r#"
default: ["stripe"]
rule_1: ["adyen"]
{
amount > 500 {
payment_method = pay_later
}
amount < 500 {
payment_method /= wallet & payment_method /= pay_later
}
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Graph");
let analysis_result = analyze(program, Some(&graph));
let error_type = match analysis_result {
Err(types::AnalysisError { error_type, .. }) => error_type,
_ => panic!("Error_type not found"),
};
let a_err = match error_type {
types::AnalysisErrorType::GraphAnalysis(trace, memo) => (trace, memo),
_ => panic!("Graph Analysis not found"),
};
let (trace, metadata) = match a_err.0 {
graph::AnalysisError::NegationTrace { trace, metadata } => (trace, metadata),
_ => panic!("Negation Trace not found"),
};
let predecessor = match Weak::upgrade(&trace)
.expect("Expected Arc not found")
.deref()
.clone()
{
cgraph::AnalysisTrace::Value { predecessors, .. } => {
let _value = cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(
dir::enums::PaymentMethod::Card,
));
let _relation = cgraph::Relation::Positive;
predecessors
}
_ => panic!("Expected Negation Trace for payment method = card"),
};
let pred = match predecessor {
Some(cgraph::error::ValueTracePredecessor::Mandatory(predecessor)) => predecessor,
_ => panic!("No predecessor found"),
};
assert_eq!(
metadata.len(),
2,
"Expected two metadats for wallet and pay_later"
);
assert!(matches!(
*Weak::upgrade(&pred)
.expect("Expected Arc not found")
.deref(),
cgraph::AnalysisTrace::Value {
value: cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(
dir::enums::CaptureMethod::Automatic
)),
relation: cgraph::Relation::Positive,
info: None,
metadata: None,
predecessors: None,
}
));
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/dssa/types.rs | crates/euclid/src/dssa/types.rs | use std::{collections::HashMap, fmt};
use serde::Serialize;
use crate::{
dssa::{self, graph},
frontend::{ast, dir},
types::{DataType, EuclidValue, Metadata},
};
pub trait EuclidAnalysable: Sized {
fn get_dir_value_for_analysis(&self, rule_name: String) -> Vec<(dir::DirValue, Metadata)>;
}
#[derive(Debug, Clone)]
pub enum CtxValueKind<'a> {
Assertion(&'a dir::DirValue),
Negation(&'a [dir::DirValue]),
}
impl CtxValueKind<'_> {
pub fn get_assertion(&self) -> Option<&dir::DirValue> {
if let Self::Assertion(val) = self {
Some(val)
} else {
None
}
}
pub fn get_negation(&self) -> Option<&[dir::DirValue]> {
if let Self::Negation(vals) = self {
Some(vals)
} else {
None
}
}
pub fn get_key(&self) -> Option<dir::DirKey> {
match self {
Self::Assertion(val) => Some(val.get_key()),
Self::Negation(vals) => vals.first().map(|v| (*v).get_key()),
}
}
}
#[derive(Debug, Clone)]
pub struct ContextValue<'a> {
pub value: CtxValueKind<'a>,
pub metadata: &'a Metadata,
}
impl<'a> ContextValue<'a> {
#[inline]
pub fn assertion(value: &'a dir::DirValue, metadata: &'a Metadata) -> Self {
Self {
value: CtxValueKind::Assertion(value),
metadata,
}
}
#[inline]
pub fn negation(values: &'a [dir::DirValue], metadata: &'a Metadata) -> Self {
Self {
value: CtxValueKind::Negation(values),
metadata,
}
}
}
pub type ConjunctiveContext<'a> = Vec<ContextValue<'a>>;
#[derive(Clone, Serialize)]
pub enum AnalyzeResult {
AllOk,
}
#[derive(Debug, Clone, Serialize, thiserror::Error)]
pub struct AnalysisError {
#[serde(flatten)]
pub error_type: AnalysisErrorType,
pub metadata: Metadata,
}
impl fmt::Display for AnalysisError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.error_type.fmt(f)
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ValueData {
pub value: dir::DirValue,
pub metadata: Metadata,
}
#[derive(Debug, Clone, Serialize, thiserror::Error)]
#[serde(tag = "type", content = "info", rename_all = "snake_case")]
pub enum AnalysisErrorType {
#[error("Invalid program key given: '{0}'")]
InvalidKey(String),
#[error("Invalid variant '{got}' received for key '{key}'")]
InvalidVariant {
key: String,
expected: Vec<String>,
got: String,
},
#[error(
"Invalid data type for value '{}' (expected {expected}, got {got})",
key
)]
InvalidType {
key: String,
expected: DataType,
got: DataType,
},
#[error("Invalid comparison '{operator:?}' for value type {value_type}")]
InvalidComparison {
operator: ast::ComparisonType,
value_type: DataType,
},
#[error("Invalid value received for length as '{value}: {:?}'", message)]
InvalidValue {
key: dir::DirKeyKind,
value: String,
message: Option<String>,
},
#[error("Conflicting assertions received for key '{}'", .key.kind)]
ConflictingAssertions {
key: dir::DirKey,
values: Vec<ValueData>,
},
#[error("Key '{}' exhaustively negated", .key.kind)]
ExhaustiveNegation {
key: dir::DirKey,
metadata: Vec<Metadata>,
},
#[error("The condition '{value}' was asserted and negated in the same condition")]
NegatedAssertion {
value: dir::DirValue,
assertion_metadata: Metadata,
negation_metadata: Metadata,
},
#[error("Graph analysis error: {0:#?}")]
GraphAnalysis(
graph::AnalysisError<dir::DirValue>,
hyperswitch_constraint_graph::Memoization<dir::DirValue>,
),
#[error("State machine error")]
StateMachine(dssa::state_machine::StateMachineError),
#[error("Unsupported program key '{0}'")]
UnsupportedProgramKey(dir::DirKeyKind),
#[error("Ran into an unimplemented feature")]
NotImplemented,
#[error("The payment method type is not supported under the payment method")]
NotSupported,
}
#[derive(Debug, Clone)]
pub enum ValueType {
EnumVariants(Vec<EuclidValue>),
Number,
}
impl EuclidAnalysable for common_enums::AuthenticationType {
fn get_dir_value_for_analysis(&self, rule_name: String) -> Vec<(dir::DirValue, Metadata)> {
let auth = self.to_string();
let dir_value = match self {
Self::ThreeDs => dir::DirValue::AuthenticationType(Self::ThreeDs),
Self::NoThreeDs => dir::DirValue::AuthenticationType(Self::NoThreeDs),
};
vec![(
dir_value,
HashMap::from_iter([(
"AUTHENTICATION_TYPE".to_string(),
serde_json::json!({
"rule_name": rule_name,
"Authentication_type": auth,
}),
)]),
)]
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/dssa/utils.rs | crates/euclid/src/dssa/utils.rs | pub struct Unpacker;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/dssa/truth.rs | crates/euclid/src/dssa/truth.rs | use std::sync::LazyLock;
use euclid_macros::knowledge;
#[allow(unused_imports)] // Required by the `knowledge!` macro expansion
use crate::dssa::graph::euclid_graph_prelude;
use crate::frontend::dir;
pub static ANALYSIS_GRAPH: LazyLock<hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue>> =
LazyLock::new(|| {
knowledge! {
// Payment Method should be `Card` for a CardType to be present
PaymentMethod(Card) ->> CardType(any);
// Payment Method should be `PayLater` for a PayLaterType to be present
PaymentMethod(PayLater) ->> PayLaterType(any);
// Payment Method should be `Wallet` for a WalletType to be present
PaymentMethod(Wallet) ->> WalletType(any);
// Payment Method should be `BankRedirect` for a BankRedirectType to
// be present
PaymentMethod(BankRedirect) ->> BankRedirectType(any);
// Payment Method should be `BankTransfer` for a BankTransferType to
// be present
PaymentMethod(BankTransfer) ->> BankTransferType(any);
// Payment Method should be `GiftCard` for a GiftCardType to
// be present
PaymentMethod(GiftCard) ->> GiftCardType(any);
// Payment Method should be `RealTimePayment` for a RealTimePaymentType to
// be present
PaymentMethod(RealTimePayment) ->> RealTimePaymentType(any);
}
});
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/dssa/graph.rs | crates/euclid/src/dssa/graph.rs | use std::{fmt::Debug, sync::Weak};
use hyperswitch_constraint_graph as cgraph;
use rustc_hash::{FxHashMap, FxHashSet};
use crate::{
dssa::types,
frontend::dir,
types::{DataType, Metadata},
};
pub mod euclid_graph_prelude {
pub use hyperswitch_constraint_graph as cgraph;
pub use rustc_hash::{FxHashMap, FxHashSet};
pub use strum::EnumIter;
pub use crate::{
dssa::graph::*,
frontend::dir::{enums::*, DirKey, DirKeyKind, DirValue},
types::*,
};
}
impl cgraph::KeyNode for dir::DirKey {}
impl cgraph::NodeViz for dir::DirKey {
fn viz(&self) -> String {
self.kind.to_string()
}
}
impl cgraph::ValueNode for dir::DirValue {
type Key = dir::DirKey;
fn get_key(&self) -> Self::Key {
Self::get_key(self)
}
}
impl cgraph::NodeViz for dir::DirValue {
fn viz(&self) -> String {
match self {
Self::PaymentMethod(pm) => pm.to_string(),
Self::CardBin(bin) => bin.value.clone(),
Self::ExtendedCardBin(ebin) => ebin.value.clone(),
Self::CardType(ct) => ct.to_string(),
Self::CardNetwork(cn) => cn.to_string(),
Self::PayLaterType(plt) => plt.to_string(),
Self::WalletType(wt) => wt.to_string(),
Self::UpiType(ut) => ut.to_string(),
Self::BankTransferType(btt) => btt.to_string(),
Self::BankRedirectType(brt) => brt.to_string(),
Self::BankDebitType(bdt) => bdt.to_string(),
Self::CryptoType(ct) => ct.to_string(),
Self::RewardType(rt) => rt.to_string(),
Self::PaymentAmount(amt) => amt.number.to_string(),
Self::PaymentCurrency(curr) => curr.to_string(),
Self::AuthenticationType(at) => at.to_string(),
Self::CaptureMethod(cm) => cm.to_string(),
Self::BusinessCountry(bc) => bc.to_string(),
Self::BillingCountry(bc) => bc.to_string(),
Self::Connector(conn) => conn.connector.to_string(),
Self::MetaData(mv) => format!("[{} = {}]", mv.key, mv.value),
Self::MandateAcceptanceType(mat) => mat.to_string(),
Self::MandateType(mt) => mt.to_string(),
Self::PaymentType(pt) => pt.to_string(),
Self::VoucherType(vt) => vt.to_string(),
Self::GiftCardType(gct) => gct.to_string(),
Self::BusinessLabel(bl) => bl.value.to_string(),
Self::SetupFutureUsage(sfu) => sfu.to_string(),
Self::CardRedirectType(crt) => crt.to_string(),
Self::RealTimePaymentType(rtpt) => rtpt.to_string(),
Self::OpenBankingType(ob) => ob.to_string(),
Self::MobilePaymentType(mpt) => mpt.to_string(),
Self::IssuerName(issuer_name) => issuer_name.value.clone(),
Self::IssuerCountry(issuer_country) => issuer_country.to_string(),
Self::CustomerDevicePlatform(customer_device_platform) => {
customer_device_platform.to_string()
}
Self::CustomerDeviceType(customer_device_type) => customer_device_type.to_string(),
Self::CustomerDeviceDisplaySize(customer_device_display_size) => {
customer_device_display_size.to_string()
}
Self::AcquirerCountry(acquirer_country) => acquirer_country.to_string(),
Self::AcquirerFraudRate(acquirer_fraud_rate) => acquirer_fraud_rate.number.to_string(),
Self::TransactionInitiator(transaction_initiator) => transaction_initiator.to_string(),
Self::NetworkTokenType(ntt) => ntt.to_string(),
}
}
}
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "type", content = "details", rename_all = "snake_case")]
pub enum AnalysisError<V: cgraph::ValueNode> {
Graph(cgraph::GraphError<V>),
AssertionTrace {
trace: Weak<cgraph::AnalysisTrace<V>>,
metadata: Metadata,
},
NegationTrace {
trace: Weak<cgraph::AnalysisTrace<V>>,
metadata: Vec<Metadata>,
},
}
impl<V: cgraph::ValueNode> AnalysisError<V> {
fn assertion_from_graph_error(metadata: &Metadata, graph_error: cgraph::GraphError<V>) -> Self {
match graph_error {
cgraph::GraphError::AnalysisError(trace) => Self::AssertionTrace {
trace,
metadata: metadata.clone(),
},
other => Self::Graph(other),
}
}
fn negation_from_graph_error(
metadata: Vec<&Metadata>,
graph_error: cgraph::GraphError<V>,
) -> Self {
match graph_error {
cgraph::GraphError::AnalysisError(trace) => Self::NegationTrace {
trace,
metadata: metadata.iter().map(|m| (*m).clone()).collect(),
},
other => Self::Graph(other),
}
}
}
#[derive(Debug)]
pub struct AnalysisContext {
keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>>,
}
impl AnalysisContext {
pub fn from_dir_values(vals: impl IntoIterator<Item = dir::DirValue>) -> Self {
let mut keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>> =
FxHashMap::default();
for dir_val in vals {
let key = dir_val.get_key();
let set = keywise_values.entry(key).or_default();
set.insert(dir_val);
}
Self { keywise_values }
}
pub fn insert(&mut self, value: dir::DirValue) {
self.keywise_values
.entry(value.get_key())
.or_default()
.insert(value);
}
pub fn remove(&mut self, value: dir::DirValue) {
let set = self.keywise_values.entry(value.get_key()).or_default();
set.remove(&value);
if set.is_empty() {
self.keywise_values.remove(&value.get_key());
}
}
}
impl cgraph::CheckingContext for AnalysisContext {
type Value = dir::DirValue;
fn from_node_values<L>(vals: impl IntoIterator<Item = L>) -> Self
where
L: Into<Self::Value>,
{
let mut keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>> =
FxHashMap::default();
for dir_val in vals.into_iter().map(L::into) {
let key = dir_val.get_key();
let set = keywise_values.entry(key).or_default();
set.insert(dir_val);
}
Self { keywise_values }
}
fn check_presence(
&self,
value: &cgraph::NodeValue<dir::DirValue>,
strength: cgraph::Strength,
) -> bool {
match value {
cgraph::NodeValue::Key(k) => {
self.keywise_values.contains_key(k) || matches!(strength, cgraph::Strength::Weak)
}
cgraph::NodeValue::Value(val) => {
let key = val.get_key();
let value_set = if let Some(set) = self.keywise_values.get(&key) {
set
} else {
return matches!(strength, cgraph::Strength::Weak);
};
match key.kind.get_type() {
DataType::EnumVariant | DataType::StrValue | DataType::MetadataValue => {
value_set.contains(val)
}
DataType::Number => val.get_num_value().is_some_and(|num_val| {
value_set.iter().any(|ctx_val| {
ctx_val
.get_num_value()
.is_some_and(|ctx_num_val| num_val.fits(&ctx_num_val))
})
}),
}
}
}
}
fn get_values_by_key(
&self,
key: &<Self::Value as cgraph::ValueNode>::Key,
) -> Option<Vec<Self::Value>> {
self.keywise_values
.get(key)
.map(|set| set.iter().cloned().collect())
}
}
pub trait CgraphExt {
fn key_analysis(
&self,
key: dir::DirKey,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>>;
fn value_analysis(
&self,
val: dir::DirValue,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>>;
fn check_value_validity(
&self,
val: dir::DirValue,
analysis_ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<bool, cgraph::GraphError<dir::DirValue>>;
fn key_value_analysis(
&self,
val: dir::DirValue,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>>;
fn assertion_analysis(
&self,
positive_ctx: &[(&dir::DirValue, &Metadata)],
analysis_ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>>;
fn negation_analysis(
&self,
negative_ctx: &[(&[dir::DirValue], &Metadata)],
analysis_ctx: &mut AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>>;
fn perform_context_analysis(
&self,
ctx: &types::ConjunctiveContext<'_>,
memo: &mut cgraph::Memoization<dir::DirValue>,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>>;
}
impl CgraphExt for cgraph::ConstraintGraph<dir::DirValue> {
fn key_analysis(
&self,
key: dir::DirKey,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>> {
self.value_map
.get(&cgraph::NodeValue::Key(key))
.map_or(Ok(()), |node_id| {
self.check_node(
ctx,
*node_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
memo,
cycle_map,
domains,
)
})
}
fn value_analysis(
&self,
val: dir::DirValue,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>> {
self.value_map
.get(&cgraph::NodeValue::Value(val))
.map_or(Ok(()), |node_id| {
self.check_node(
ctx,
*node_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
memo,
cycle_map,
domains,
)
})
}
fn check_value_validity(
&self,
val: dir::DirValue,
analysis_ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<bool, cgraph::GraphError<dir::DirValue>> {
let maybe_node_id = self.value_map.get(&cgraph::NodeValue::Value(val));
let node_id = if let Some(nid) = maybe_node_id {
nid
} else {
return Ok(false);
};
let result = self.check_node(
analysis_ctx,
*node_id,
cgraph::Relation::Positive,
cgraph::Strength::Weak,
memo,
cycle_map,
domains,
);
match result {
Ok(_) => Ok(true),
Err(e) => {
e.get_analysis_trace()?;
Ok(false)
}
}
}
fn key_value_analysis(
&self,
val: dir::DirValue,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>> {
self.key_analysis(val.get_key(), ctx, memo, cycle_map, domains)
.and_then(|_| self.value_analysis(val, ctx, memo, cycle_map, domains))
}
fn assertion_analysis(
&self,
positive_ctx: &[(&dir::DirValue, &Metadata)],
analysis_ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>> {
positive_ctx.iter().try_for_each(|(value, metadata)| {
self.key_value_analysis((*value).clone(), analysis_ctx, memo, cycle_map, domains)
.map_err(|e| AnalysisError::assertion_from_graph_error(metadata, e))
})
}
fn negation_analysis(
&self,
negative_ctx: &[(&[dir::DirValue], &Metadata)],
analysis_ctx: &mut AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>> {
let mut keywise_metadata: FxHashMap<dir::DirKey, Vec<&Metadata>> = FxHashMap::default();
let mut keywise_negation: FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>> =
FxHashMap::default();
for (values, metadata) in negative_ctx {
let mut metadata_added = false;
for dir_value in *values {
if !metadata_added {
keywise_metadata
.entry(dir_value.get_key())
.or_default()
.push(metadata);
metadata_added = true;
}
keywise_negation
.entry(dir_value.get_key())
.or_default()
.insert(dir_value);
}
}
for (key, negation_set) in keywise_negation {
let all_metadata = keywise_metadata.remove(&key).unwrap_or_default();
let first_metadata = all_metadata.first().copied().cloned().unwrap_or_default();
self.key_analysis(key.clone(), analysis_ctx, memo, cycle_map, domains)
.map_err(|e| AnalysisError::assertion_from_graph_error(&first_metadata, e))?;
let mut value_set = if let Some(set) = key.kind.get_value_set() {
set
} else {
continue;
};
value_set.retain(|v| !negation_set.contains(v));
for value in value_set {
analysis_ctx.insert(value.clone());
self.value_analysis(value.clone(), analysis_ctx, memo, cycle_map, domains)
.map_err(|e| {
AnalysisError::negation_from_graph_error(all_metadata.clone(), e)
})?;
analysis_ctx.remove(value);
}
}
Ok(())
}
fn perform_context_analysis(
&self,
ctx: &types::ConjunctiveContext<'_>,
memo: &mut cgraph::Memoization<dir::DirValue>,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>> {
let mut analysis_ctx = AnalysisContext::from_dir_values(
ctx.iter()
.filter_map(|ctx_val| ctx_val.value.get_assertion().cloned()),
);
let positive_ctx = ctx
.iter()
.filter_map(|ctx_val| {
ctx_val
.value
.get_assertion()
.map(|val| (val, ctx_val.metadata))
})
.collect::<Vec<_>>();
self.assertion_analysis(
&positive_ctx,
&analysis_ctx,
memo,
&mut cgraph::CycleCheck::new(),
domains,
)?;
let negative_ctx = ctx
.iter()
.filter_map(|ctx_val| {
ctx_val
.value
.get_negation()
.map(|vals| (vals, ctx_val.metadata))
})
.collect::<Vec<_>>();
self.negation_analysis(
&negative_ctx,
&mut analysis_ctx,
memo,
&mut cgraph::CycleCheck::new(),
domains,
)?;
Ok(())
}
}
#[cfg(test)]
mod test {
use std::ops::Deref;
use euclid_macros::knowledge;
use hyperswitch_constraint_graph::CycleCheck;
use super::*;
use crate::{dirval, frontend::dir::enums};
#[test]
fn test_strong_positive_relation_success() {
let graph = knowledge! {
PaymentMethod(Card) ->> CaptureMethod(Automatic);
PaymentMethod(not Wallet)
& PaymentMethod(not PayLater) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Card),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_strong_positive_relation_failure() {
let graph = knowledge! {
PaymentMethod(Card) ->> CaptureMethod(Automatic);
PaymentMethod(not Wallet) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([dirval!(CaptureMethod = Automatic)]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_strong_negative_relation_success() {
let graph = knowledge! {
PaymentMethod(Card) -> CaptureMethod(Automatic);
PaymentMethod(not Wallet) ->> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Card),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_strong_negative_relation_failure() {
let graph = knowledge! {
PaymentMethod(Card) -> CaptureMethod(Automatic);
PaymentMethod(not Wallet) ->> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Wallet),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_normal_one_of_failure() {
let graph = knowledge! {
PaymentMethod(Card) -> CaptureMethod(Automatic);
PaymentMethod(Wallet) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = PayLater),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(matches!(
*Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap())
.expect("Expected Arc"),
cgraph::AnalysisTrace::Value {
predecessors: Some(cgraph::error::ValueTracePredecessor::OneOf(_)),
..
}
));
}
#[test]
fn test_all_aggregator_success() {
let graph = knowledge! {
PaymentMethod(Card) & PaymentMethod(not Wallet) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(PaymentMethod = Card),
dirval!(CaptureMethod = Automatic),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_all_aggregator_failure() {
let graph = knowledge! {
PaymentMethod(Card) & PaymentMethod(not Wallet) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = PayLater),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_all_aggregator_mandatory_failure() {
let graph = knowledge! {
PaymentMethod(Card) & PaymentMethod(not Wallet) ->> CaptureMethod(Automatic);
};
let mut memo = cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = PayLater),
]),
&mut memo,
&mut CycleCheck::new(),
None,
);
assert!(matches!(
*Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap())
.expect("Expected Arc"),
cgraph::AnalysisTrace::Value {
predecessors: Some(cgraph::error::ValueTracePredecessor::Mandatory(_)),
..
}
));
}
#[test]
fn test_in_aggregator_success() {
let graph = knowledge! {
PaymentMethod(in [Card, Wallet]) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Wallet),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_in_aggregator_failure() {
let graph = knowledge! {
PaymentMethod(in [Card, Wallet]) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = PayLater),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_not_in_aggregator_success() {
let graph = knowledge! {
PaymentMethod(not in [Card, Wallet]) ->> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = PayLater),
dirval!(PaymentMethod = BankRedirect),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_not_in_aggregator_failure() {
let graph = knowledge! {
PaymentMethod(not in [Card, Wallet]) ->> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = PayLater),
dirval!(PaymentMethod = BankRedirect),
dirval!(PaymentMethod = Card),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_in_aggregator_failure_trace() {
let graph = knowledge! {
PaymentMethod(in [Card, Wallet]) ->> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = PayLater),
]),
memo,
&mut CycleCheck::new(),
None,
);
if let cgraph::AnalysisTrace::Value {
predecessors: Some(cgraph::error::ValueTracePredecessor::Mandatory(agg_error)),
..
} = Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap())
.expect("Expected arc")
.deref()
{
assert!(matches!(
*Weak::upgrade(agg_error.deref()).expect("Expected Arc"),
cgraph::AnalysisTrace::InAggregation {
found: Some(dir::DirValue::PaymentMethod(enums::PaymentMethod::PayLater)),
..
}
));
} else {
panic!("Failed unwrapping OnlyInAggregation trace from AnalysisTrace");
}
}
#[test]
fn test_memoization_in_kgraph() {
let mut builder = cgraph::ConstraintGraphBuilder::new();
let _node_1 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)),
None,
None::<()>,
);
let _node_2 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::BillingCountry(enums::BillingCountry::India)),
None,
None::<()>,
);
let _node_3 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::BusinessCountry(
enums::BusinessCountry::UnitedStatesOfAmerica,
)),
None,
None::<()>,
);
let mut memo = cgraph::Memoization::new();
let mut cycle_map = CycleCheck::new();
let _edge_1 = builder
.make_edge(
_node_1,
_node_2,
cgraph::Strength::Strong,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_2 = builder
.make_edge(
_node_2,
_node_3,
cgraph::Strength::Strong,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to an edge");
let graph = builder.build();
let _result = graph.key_value_analysis(
dirval!(BusinessCountry = UnitedStatesOfAmerica),
&AnalysisContext::from_dir_values([
dirval!(PaymentMethod = Wallet),
dirval!(BillingCountry = India),
dirval!(BusinessCountry = UnitedStatesOfAmerica),
]),
&mut memo,
&mut cycle_map,
None,
);
let _answer = memo
.get(&(
_node_3,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
))
.expect("Memoization not workng");
matches!(_answer, Ok(()));
}
#[test]
fn test_cycle_resolution_in_graph() {
let mut builder = cgraph::ConstraintGraphBuilder::new();
let _node_1 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)),
None,
None::<()>,
);
let _node_2 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)),
None,
None::<()>,
);
let mut memo = cgraph::Memoization::new();
let mut cycle_map = CycleCheck::new();
let _edge_1 = builder
.make_edge(
_node_1,
_node_2,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_2 = builder
.make_edge(
_node_2,
_node_1,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to an edge");
let graph = builder.build();
let _result = graph.key_value_analysis(
dirval!(PaymentMethod = Wallet),
&AnalysisContext::from_dir_values([
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = Card),
]),
&mut memo,
&mut cycle_map,
None,
);
assert!(_result.is_ok());
}
#[test]
fn test_cycle_resolution_in_graph1() {
let mut builder = cgraph::ConstraintGraphBuilder::new();
let _node_1 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(
enums::CaptureMethod::Automatic,
)),
None,
None::<()>,
);
let _node_2 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)),
None,
None::<()>,
);
let _node_3 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)),
None,
None::<()>,
);
let mut memo = cgraph::Memoization::new();
let mut cycle_map = CycleCheck::new();
let _edge_1 = builder
.make_edge(
_node_1,
_node_2,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_2 = builder
.make_edge(
_node_1,
_node_3,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_3 = builder
.make_edge(
_node_2,
_node_1,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_4 = builder
.make_edge(
_node_3,
_node_1,
cgraph::Strength::Strong,
cgraph::Relation::Positive,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/dssa/state_machine.rs | crates/euclid/src/dssa/state_machine.rs | use super::types::EuclidAnalysable;
use crate::{dssa::types, frontend::dir, types::Metadata};
#[derive(Debug, Clone, serde::Serialize, thiserror::Error)]
#[serde(tag = "type", content = "info", rename_all = "snake_case")]
pub enum StateMachineError {
#[error("Index out of bounds: {0}")]
IndexOutOfBounds(&'static str),
}
#[derive(Debug)]
struct ComparisonStateMachine<'a> {
values: &'a [dir::DirValue],
logic: &'a dir::DirComparisonLogic,
metadata: &'a Metadata,
count: usize,
ctx_idx: usize,
}
impl<'a> ComparisonStateMachine<'a> {
#[inline]
fn is_finished(&self) -> bool {
self.count + 1 >= self.values.len()
|| matches!(self.logic, dir::DirComparisonLogic::NegativeConjunction)
}
#[inline]
fn advance(&mut self) {
if let dir::DirComparisonLogic::PositiveDisjunction = self.logic {
self.count = (self.count + 1) % self.values.len();
}
}
#[inline]
fn reset(&mut self) {
self.count = 0;
}
#[inline]
fn put(&self, context: &mut types::ConjunctiveContext<'a>) -> Result<(), StateMachineError> {
if let dir::DirComparisonLogic::PositiveDisjunction = self.logic {
*context
.get_mut(self.ctx_idx)
.ok_or(StateMachineError::IndexOutOfBounds(
"in ComparisonStateMachine while indexing into context",
))? = types::ContextValue::assertion(
self.values
.get(self.count)
.ok_or(StateMachineError::IndexOutOfBounds(
"in ComparisonStateMachine while indexing into values",
))?,
self.metadata,
);
}
Ok(())
}
#[inline]
fn push(&self, context: &mut types::ConjunctiveContext<'a>) -> Result<(), StateMachineError> {
match self.logic {
dir::DirComparisonLogic::PositiveDisjunction => {
context.push(types::ContextValue::assertion(
self.values
.get(self.count)
.ok_or(StateMachineError::IndexOutOfBounds(
"in ComparisonStateMachine while pushing",
))?,
self.metadata,
));
}
dir::DirComparisonLogic::NegativeConjunction => {
context.push(types::ContextValue::negation(self.values, self.metadata));
}
}
Ok(())
}
}
#[derive(Debug)]
struct ConditionStateMachine<'a> {
state_machines: Vec<ComparisonStateMachine<'a>>,
start_ctx_idx: usize,
}
impl<'a> ConditionStateMachine<'a> {
fn new(condition: &'a [dir::DirComparison], start_idx: usize) -> Self {
let mut machines = Vec::<ComparisonStateMachine<'a>>::with_capacity(condition.len());
let mut machine_idx = start_idx;
for cond in condition {
let machine = ComparisonStateMachine {
values: &cond.values,
logic: &cond.logic,
metadata: &cond.metadata,
count: 0,
ctx_idx: machine_idx,
};
machines.push(machine);
machine_idx += 1;
}
Self {
state_machines: machines,
start_ctx_idx: start_idx,
}
}
fn init(&self, context: &mut types::ConjunctiveContext<'a>) -> Result<(), StateMachineError> {
for machine in &self.state_machines {
machine.push(context)?;
}
Ok(())
}
#[inline]
fn destroy(&self, context: &mut types::ConjunctiveContext<'a>) {
context.truncate(self.start_ctx_idx);
}
#[inline]
fn is_finished(&self) -> bool {
!self
.state_machines
.iter()
.any(|machine| !machine.is_finished())
}
#[inline]
fn get_next_ctx_idx(&self) -> usize {
self.start_ctx_idx + self.state_machines.len()
}
fn advance(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
for machine in self.state_machines.iter_mut().rev() {
if machine.is_finished() {
machine.reset();
machine.put(context)?;
} else {
machine.advance();
machine.put(context)?;
break;
}
}
Ok(())
}
}
#[derive(Debug)]
struct IfStmtStateMachine<'a> {
condition_machine: ConditionStateMachine<'a>,
nested: Vec<&'a dir::DirIfStatement>,
nested_idx: usize,
}
impl<'a> IfStmtStateMachine<'a> {
fn new(stmt: &'a dir::DirIfStatement, ctx_start_idx: usize) -> Self {
let condition_machine = ConditionStateMachine::new(&stmt.condition, ctx_start_idx);
let nested: Vec<&'a dir::DirIfStatement> = match &stmt.nested {
None => Vec::new(),
Some(nested_stmts) => nested_stmts.iter().collect(),
};
Self {
condition_machine,
nested,
nested_idx: 0,
}
}
fn init(
&self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<Option<Self>, StateMachineError> {
self.condition_machine.init(context)?;
Ok(self
.nested
.first()
.map(|nested| Self::new(nested, self.condition_machine.get_next_ctx_idx())))
}
#[inline]
fn is_finished(&self) -> bool {
self.nested_idx + 1 >= self.nested.len()
}
#[inline]
fn is_condition_machine_finished(&self) -> bool {
self.condition_machine.is_finished()
}
#[inline]
fn destroy(&self, context: &mut types::ConjunctiveContext<'a>) {
self.condition_machine.destroy(context);
}
#[inline]
fn advance_condition_machine(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
self.condition_machine.advance(context)?;
Ok(())
}
fn advance(&mut self) -> Result<Option<Self>, StateMachineError> {
if self.nested.is_empty() {
Ok(None)
} else {
self.nested_idx = (self.nested_idx + 1) % self.nested.len();
Ok(Some(Self::new(
self.nested
.get(self.nested_idx)
.ok_or(StateMachineError::IndexOutOfBounds(
"in IfStmtStateMachine while advancing",
))?,
self.condition_machine.get_next_ctx_idx(),
)))
}
}
}
#[derive(Debug)]
struct RuleStateMachine<'a> {
connector_selection_data: &'a [(dir::DirValue, Metadata)],
connectors_added: bool,
if_stmt_machines: Vec<IfStmtStateMachine<'a>>,
running_stack: Vec<IfStmtStateMachine<'a>>,
}
impl<'a> RuleStateMachine<'a> {
fn new<O>(
rule: &'a dir::DirRule<O>,
connector_selection_data: &'a [(dir::DirValue, Metadata)],
) -> Self {
let mut if_stmt_machines: Vec<IfStmtStateMachine<'a>> =
Vec::with_capacity(rule.statements.len());
for stmt in rule.statements.iter().rev() {
if_stmt_machines.push(IfStmtStateMachine::new(
stmt,
connector_selection_data.len(),
));
}
Self {
connector_selection_data,
connectors_added: false,
if_stmt_machines,
running_stack: Vec::new(),
}
}
fn is_finished(&self) -> bool {
self.if_stmt_machines.is_empty() && self.running_stack.is_empty()
}
fn init_next(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
if self.if_stmt_machines.is_empty() || !self.running_stack.is_empty() {
return Ok(());
}
if !self.connectors_added {
for (dir_val, metadata) in self.connector_selection_data {
context.push(types::ContextValue::assertion(dir_val, metadata));
}
self.connectors_added = true;
}
context.truncate(self.connector_selection_data.len());
if let Some(mut next_running) = self.if_stmt_machines.pop() {
while let Some(nested_running) = next_running.init(context)? {
self.running_stack.push(next_running);
next_running = nested_running;
}
self.running_stack.push(next_running);
}
Ok(())
}
fn advance(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
let mut condition_machines_finished = true;
for stmt_machine in self.running_stack.iter_mut().rev() {
if !stmt_machine.is_condition_machine_finished() {
condition_machines_finished = false;
stmt_machine.advance_condition_machine(context)?;
break;
} else {
stmt_machine.advance_condition_machine(context)?;
}
}
if !condition_machines_finished {
return Ok(());
}
let mut maybe_next_running: Option<IfStmtStateMachine<'a>> = None;
while let Some(last) = self.running_stack.last_mut() {
if !last.is_finished() {
maybe_next_running = last.advance()?;
break;
} else {
last.destroy(context);
self.running_stack.pop();
}
}
if let Some(mut next_running) = maybe_next_running {
while let Some(nested_running) = next_running.init(context)? {
self.running_stack.push(next_running);
next_running = nested_running;
}
self.running_stack.push(next_running);
} else {
self.init_next(context)?;
}
Ok(())
}
}
#[derive(Debug)]
pub struct RuleContextManager<'a> {
context: types::ConjunctiveContext<'a>,
machine: RuleStateMachine<'a>,
init: bool,
}
impl<'a> RuleContextManager<'a> {
pub fn new<O>(
rule: &'a dir::DirRule<O>,
connector_selection_data: &'a [(dir::DirValue, Metadata)],
) -> Self {
Self {
context: Vec::new(),
machine: RuleStateMachine::new(rule, connector_selection_data),
init: false,
}
}
pub fn advance(&mut self) -> Result<Option<&types::ConjunctiveContext<'a>>, StateMachineError> {
if !self.init {
self.init = true;
self.machine.init_next(&mut self.context)?;
Ok(Some(&self.context))
} else if self.machine.is_finished() {
Ok(None)
} else {
self.machine.advance(&mut self.context)?;
if self.machine.is_finished() {
Ok(None)
} else {
Ok(Some(&self.context))
}
}
}
pub fn advance_mut(
&mut self,
) -> Result<Option<&mut types::ConjunctiveContext<'a>>, StateMachineError> {
if !self.init {
self.init = true;
self.machine.init_next(&mut self.context)?;
Ok(Some(&mut self.context))
} else if self.machine.is_finished() {
Ok(None)
} else {
self.machine.advance(&mut self.context)?;
if self.machine.is_finished() {
Ok(None)
} else {
Ok(Some(&mut self.context))
}
}
}
}
#[derive(Debug)]
pub struct ProgramStateMachine<'a> {
rule_machines: Vec<RuleStateMachine<'a>>,
current_rule_machine: Option<RuleStateMachine<'a>>,
is_init: bool,
}
impl<'a> ProgramStateMachine<'a> {
pub fn new<O>(
program: &'a dir::DirProgram<O>,
connector_selection_data: &'a [Vec<(dir::DirValue, Metadata)>],
) -> Self {
let mut rule_machines: Vec<RuleStateMachine<'a>> = program
.rules
.iter()
.zip(connector_selection_data.iter())
.rev()
.map(|(rule, connector_selection_data)| {
RuleStateMachine::new(rule, connector_selection_data)
})
.collect();
Self {
current_rule_machine: rule_machines.pop(),
rule_machines,
is_init: false,
}
}
pub fn is_finished(&self) -> bool {
self.current_rule_machine
.as_ref()
.is_none_or(|rsm| rsm.is_finished())
&& self.rule_machines.is_empty()
}
pub fn init(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
if !self.is_init {
if let Some(rsm) = self.current_rule_machine.as_mut() {
rsm.init_next(context)?;
}
self.is_init = true;
}
Ok(())
}
pub fn advance(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
if self
.current_rule_machine
.as_ref()
.is_none_or(|rsm| rsm.is_finished())
{
self.current_rule_machine = self.rule_machines.pop();
context.clear();
if let Some(rsm) = self.current_rule_machine.as_mut() {
rsm.init_next(context)?;
}
} else if let Some(rsm) = self.current_rule_machine.as_mut() {
rsm.advance(context)?;
}
Ok(())
}
}
pub struct AnalysisContextManager<'a> {
context: types::ConjunctiveContext<'a>,
machine: ProgramStateMachine<'a>,
init: bool,
}
impl<'a> AnalysisContextManager<'a> {
pub fn new<O>(
program: &'a dir::DirProgram<O>,
connector_selection_data: &'a [Vec<(dir::DirValue, Metadata)>],
) -> Self {
let machine = ProgramStateMachine::new(program, connector_selection_data);
let context: types::ConjunctiveContext<'a> = Vec::new();
Self {
context,
machine,
init: false,
}
}
pub fn advance(&mut self) -> Result<Option<&types::ConjunctiveContext<'a>>, StateMachineError> {
if !self.init {
self.init = true;
self.machine.init(&mut self.context)?;
Ok(Some(&self.context))
} else if self.machine.is_finished() {
Ok(None)
} else {
self.machine.advance(&mut self.context)?;
if self.machine.is_finished() {
Ok(None)
} else {
Ok(Some(&self.context))
}
}
}
}
pub fn make_connector_selection_data<O: EuclidAnalysable>(
program: &dir::DirProgram<O>,
) -> Vec<Vec<(dir::DirValue, Metadata)>> {
program
.rules
.iter()
.map(|rule| {
rule.connector_selection
.get_dir_value_for_analysis(rule.name.clone())
})
.collect()
}
#[cfg(all(test, feature = "ast_parser"))]
mod tests {
use super::*;
use crate::{dirval, frontend::ast, types::DummyOutput};
#[test]
fn test_correct_contexts() {
let program_str = r#"
default: ["stripe", "adyen"]
stripe_first: ["stripe", "adyen"]
{
payment_method = wallet {
payment_method = (card, bank_redirect) {
currency = USD
currency = GBP
}
payment_method = pay_later {
capture_method = automatic
capture_method = manual
}
}
payment_method = card {
payment_method = (card, bank_redirect) & capture_method = (automatic, manual) {
currency = (USD, GBP)
}
}
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let lowered = ast::lowering::lower_program(program).expect("Lowering");
let selection_data = make_connector_selection_data(&lowered);
let mut state_machine = ProgramStateMachine::new(&lowered, &selection_data);
let mut ctx: types::ConjunctiveContext<'_> = Vec::new();
state_machine.init(&mut ctx).expect("State machine init");
let expected_contexts: Vec<Vec<dir::DirValue>> = vec![
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = Card),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = BankRedirect),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = Card),
dirval!(PaymentCurrency = GBP),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = BankRedirect),
dirval!(PaymentCurrency = GBP),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = PayLater),
dirval!(CaptureMethod = Automatic),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = PayLater),
dirval!(CaptureMethod = Manual),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Card),
dirval!(CaptureMethod = Automatic),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Card),
dirval!(CaptureMethod = Automatic),
dirval!(PaymentCurrency = GBP),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Card),
dirval!(CaptureMethod = Manual),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Card),
dirval!(CaptureMethod = Manual),
dirval!(PaymentCurrency = GBP),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = BankRedirect),
dirval!(CaptureMethod = Automatic),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = BankRedirect),
dirval!(CaptureMethod = Automatic),
dirval!(PaymentCurrency = GBP),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = BankRedirect),
dirval!(CaptureMethod = Manual),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = BankRedirect),
dirval!(CaptureMethod = Manual),
dirval!(PaymentCurrency = GBP),
],
];
let mut expected_idx = 0usize;
while !state_machine.is_finished() {
let values = ctx
.iter()
.flat_map(|c| match c.value {
types::CtxValueKind::Assertion(val) => vec![val],
types::CtxValueKind::Negation(vals) => vals.iter().collect(),
})
.collect::<Vec<&dir::DirValue>>();
assert_eq!(
values,
expected_contexts
.get(expected_idx)
.expect("Error deriving contexts")
.iter()
.collect::<Vec<&dir::DirValue>>()
);
expected_idx += 1;
state_machine
.advance(&mut ctx)
.expect("State Machine advance");
}
assert_eq!(expected_idx, 14);
let mut ctx_manager = AnalysisContextManager::new(&lowered, &selection_data);
expected_idx = 0;
while let Some(ctx) = ctx_manager.advance().expect("Context Manager Context") {
let values = ctx
.iter()
.flat_map(|c| match c.value {
types::CtxValueKind::Assertion(val) => vec![val],
types::CtxValueKind::Negation(vals) => vals.iter().collect(),
})
.collect::<Vec<&dir::DirValue>>();
assert_eq!(
values,
expected_contexts
.get(expected_idx)
.expect("Error deriving contexts")
.iter()
.collect::<Vec<&dir::DirValue>>()
);
expected_idx += 1;
}
assert_eq!(expected_idx, 14);
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/backend/inputs.rs | crates/euclid/src/backend/inputs.rs | use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use crate::{
enums,
frontend::dir::enums::{
CustomerDeviceDisplaySize, CustomerDevicePlatform, CustomerDeviceType, TransactionInitiator,
},
};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MandateData {
pub mandate_acceptance_type: Option<enums::MandateAcceptanceType>,
pub mandate_type: Option<enums::MandateType>,
pub payment_type: Option<enums::PaymentType>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentMethodInput {
pub payment_method: Option<enums::PaymentMethod>,
pub payment_method_type: Option<enums::PaymentMethodType>,
pub card_network: Option<enums::CardNetwork>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentInput {
pub amount: common_utils::types::MinorUnit,
pub currency: enums::Currency,
pub authentication_type: Option<enums::AuthenticationType>,
pub card_bin: Option<String>,
pub extended_card_bin: Option<String>,
pub capture_method: Option<enums::CaptureMethod>,
pub business_country: Option<enums::Country>,
pub billing_country: Option<enums::Country>,
pub business_label: Option<String>,
pub setup_future_usage: Option<enums::SetupFutureUsage>,
pub transaction_initiator: Option<TransactionInitiator>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AcquirerDataInput {
pub country: Option<enums::Country>,
pub fraud_rate: Option<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomerDeviceDataInput {
pub platform: Option<CustomerDevicePlatform>,
pub device_type: Option<CustomerDeviceType>,
pub display_size: Option<CustomerDeviceDisplaySize>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IssuerDataInput {
pub name: Option<String>,
pub country: Option<enums::Country>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackendInput {
pub metadata: Option<FxHashMap<String, String>>,
pub payment: PaymentInput,
pub payment_method: PaymentMethodInput,
pub acquirer_data: Option<AcquirerDataInput>,
pub customer_device_data: Option<CustomerDeviceDataInput>,
pub issuer_data: Option<IssuerDataInput>,
pub mandate: MandateData,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/backend/interpreter.rs | crates/euclid/src/backend/interpreter.rs | pub mod types;
use common_utils::types::MinorUnit;
use crate::{
backend::{self, inputs, EuclidBackend},
frontend::ast,
};
pub struct InterpreterBackend<O> {
program: ast::Program<O>,
}
impl<O> InterpreterBackend<O>
where
O: Clone,
{
fn eval_number_comparison_array(
num: MinorUnit,
array: &[ast::NumberComparison],
) -> Result<bool, types::InterpreterError> {
for comparison in array {
let other = comparison.number;
let res = match comparison.comparison_type {
ast::ComparisonType::GreaterThan => num > other,
ast::ComparisonType::LessThan => num < other,
ast::ComparisonType::LessThanEqual => num <= other,
ast::ComparisonType::GreaterThanEqual => num >= other,
ast::ComparisonType::Equal => num == other,
ast::ComparisonType::NotEqual => num != other,
};
if res {
return Ok(true);
}
}
Ok(false)
}
fn eval_comparison(
comparison: &ast::Comparison,
ctx: &types::Context,
) -> Result<bool, types::InterpreterError> {
use ast::{ComparisonType::*, ValueType::*};
let value = ctx
.get(&comparison.lhs)
.ok_or_else(|| types::InterpreterError {
error_type: types::InterpreterErrorType::InvalidKey(comparison.lhs.clone()),
metadata: comparison.metadata.clone(),
})?;
if let Some(val) = value {
match (val, &comparison.comparison, &comparison.value) {
(EnumVariant(e1), Equal, EnumVariant(e2)) => Ok(e1 == e2),
(EnumVariant(e1), NotEqual, EnumVariant(e2)) => Ok(e1 != e2),
(EnumVariant(e), Equal, EnumVariantArray(evec)) => Ok(evec.iter().any(|v| e == v)),
(EnumVariant(e), NotEqual, EnumVariantArray(evec)) => {
Ok(evec.iter().all(|v| e != v))
}
(Number(n1), Equal, Number(n2)) => Ok(n1 == n2),
(Number(n1), NotEqual, Number(n2)) => Ok(n1 != n2),
(Number(n1), LessThanEqual, Number(n2)) => Ok(n1 <= n2),
(Number(n1), GreaterThanEqual, Number(n2)) => Ok(n1 >= n2),
(Number(n1), LessThan, Number(n2)) => Ok(n1 < n2),
(Number(n1), GreaterThan, Number(n2)) => Ok(n1 > n2),
(Number(n), Equal, NumberArray(nvec)) => Ok(nvec.iter().any(|v| v == n)),
(Number(n), NotEqual, NumberArray(nvec)) => Ok(nvec.iter().all(|v| v != n)),
(Number(n), Equal, NumberComparisonArray(ncvec)) => {
Self::eval_number_comparison_array(*n, ncvec)
}
_ => Err(types::InterpreterError {
error_type: types::InterpreterErrorType::InvalidComparison,
metadata: comparison.metadata.clone(),
}),
}
} else {
Ok(false)
}
}
fn eval_if_condition(
condition: &ast::IfCondition,
ctx: &types::Context,
) -> Result<bool, types::InterpreterError> {
for comparison in condition {
let res = Self::eval_comparison(comparison, ctx)?;
if !res {
return Ok(false);
}
}
Ok(true)
}
fn eval_if_statement(
stmt: &ast::IfStatement,
ctx: &types::Context,
) -> Result<bool, types::InterpreterError> {
let cond_res = Self::eval_if_condition(&stmt.condition, ctx)?;
if !cond_res {
return Ok(false);
}
if let Some(ref nested) = stmt.nested {
for nested_if in nested {
let res = Self::eval_if_statement(nested_if, ctx)?;
if res {
return Ok(true);
}
}
return Ok(false);
}
Ok(true)
}
fn eval_rule_statements(
statements: &[ast::IfStatement],
ctx: &types::Context,
) -> Result<bool, types::InterpreterError> {
for stmt in statements {
let res = Self::eval_if_statement(stmt, ctx)?;
if res {
return Ok(true);
}
}
Ok(false)
}
#[inline]
fn eval_rule(
rule: &ast::Rule<O>,
ctx: &types::Context,
) -> Result<bool, types::InterpreterError> {
Self::eval_rule_statements(&rule.statements, ctx)
}
fn eval_program(
program: &ast::Program<O>,
ctx: &types::Context,
) -> Result<backend::BackendOutput<O>, types::InterpreterError> {
for rule in &program.rules {
let res = Self::eval_rule(rule, ctx)?;
if res {
return Ok(backend::BackendOutput {
connector_selection: rule.connector_selection.clone(),
rule_name: Some(rule.name.clone()),
});
}
}
Ok(backend::BackendOutput {
connector_selection: program.default_selection.clone(),
rule_name: None,
})
}
}
impl<O> EuclidBackend<O> for InterpreterBackend<O>
where
O: Clone,
{
type Error = types::InterpreterError;
fn with_program(program: ast::Program<O>) -> Result<Self, Self::Error> {
Ok(Self { program })
}
fn execute(&self, input: inputs::BackendInput) -> Result<super::BackendOutput<O>, Self::Error> {
let ctx: types::Context = input.into();
Self::eval_program(&self.program, &ctx)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/backend/vir_interpreter.rs | crates/euclid/src/backend/vir_interpreter.rs | pub mod types;
use std::fmt::Debug;
use serde::{Deserialize, Serialize};
use crate::{
backend::{self, inputs, EuclidBackend},
frontend::{
ast,
dir::{self, EuclidDirFilter},
vir,
},
};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct VirInterpreterBackend<O> {
program: vir::ValuedProgram<O>,
}
impl<O> VirInterpreterBackend<O>
where
O: Clone,
{
#[inline]
fn eval_comparison(comp: &vir::ValuedComparison, ctx: &types::Context) -> bool {
match &comp.logic {
vir::ValuedComparisonLogic::PositiveDisjunction => {
comp.values.iter().any(|v| ctx.check_presence(v))
}
vir::ValuedComparisonLogic::NegativeConjunction => {
comp.values.iter().all(|v| !ctx.check_presence(v))
}
}
}
#[inline]
fn eval_condition(cond: &vir::ValuedIfCondition, ctx: &types::Context) -> bool {
cond.iter().all(|comp| Self::eval_comparison(comp, ctx))
}
fn eval_statement(stmt: &vir::ValuedIfStatement, ctx: &types::Context) -> bool {
if Self::eval_condition(&stmt.condition, ctx) {
{
stmt.nested.as_ref().is_none_or(|nested_stmts| {
nested_stmts.iter().any(|s| Self::eval_statement(s, ctx))
})
}
} else {
false
}
}
fn eval_rule(rule: &vir::ValuedRule<O>, ctx: &types::Context) -> bool {
rule.statements
.iter()
.any(|stmt| Self::eval_statement(stmt, ctx))
}
fn eval_program(
program: &vir::ValuedProgram<O>,
ctx: &types::Context,
) -> backend::BackendOutput<O> {
program
.rules
.iter()
.find(|rule| Self::eval_rule(rule, ctx))
.map_or_else(
|| backend::BackendOutput {
connector_selection: program.default_selection.clone(),
rule_name: None,
},
|rule| backend::BackendOutput {
connector_selection: rule.connector_selection.clone(),
rule_name: Some(rule.name.clone()),
},
)
}
}
impl<O> EuclidBackend<O> for VirInterpreterBackend<O>
where
O: Clone + EuclidDirFilter,
{
type Error = types::VirInterpreterError;
fn with_program(program: ast::Program<O>) -> Result<Self, Self::Error> {
let dir_program = ast::lowering::lower_program(program)
.map_err(types::VirInterpreterError::LoweringError)?;
let vir_program = dir::lowering::lower_program(dir_program)
.map_err(types::VirInterpreterError::LoweringError)?;
Ok(Self {
program: vir_program,
})
}
fn execute(
&self,
input: inputs::BackendInput,
) -> Result<backend::BackendOutput<O>, Self::Error> {
let ctx = types::Context::from_input(input);
Ok(Self::eval_program(&self.program, &ctx))
}
}
#[cfg(all(test, feature = "ast_parser"))]
mod test {
use common_utils::types::MinorUnit;
use rustc_hash::FxHashMap;
use super::*;
use crate::{enums, types::DummyOutput};
#[test]
fn test_execution() {
let program_str = r#"
default: [ "stripe", "adyen"]
rule_1: ["stripe"]
{
pay_later = klarna
}
rule_2: ["adyen"]
{
pay_later = affirm
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(32),
transaction_initiator: None,
card_bin: None,
extended_card_bin: None,
currency: enums::Currency::USD,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_2");
}
#[test]
fn test_payment_type() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
payment_type = setup_mandate
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
transaction_initiator: None,
amount: MinorUnit::new(32),
currency: enums::Currency::USD,
card_bin: Some("123456".to_string()),
extended_card_bin: None,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: Some(enums::PaymentType::SetupMandate),
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_ppt_flow() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
payment_type = ppt_mandate
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
transaction_initiator: None,
amount: MinorUnit::new(32),
currency: enums::Currency::USD,
card_bin: Some("123456".to_string()),
extended_card_bin: None,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: Some(enums::PaymentType::PptMandate),
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_mandate_type() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
mandate_type = single_use
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
transaction_initiator: None,
amount: MinorUnit::new(32),
currency: enums::Currency::USD,
card_bin: Some("123456".to_string()),
extended_card_bin: None,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: Some(enums::MandateType::SingleUse),
payment_type: None,
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_mandate_acceptance_type() {
let program_str = r#"
default: ["stripe","adyen"]
rule_1: ["stripe"]
{
mandate_acceptance_type = online
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
transaction_initiator: None,
amount: MinorUnit::new(32),
currency: enums::Currency::USD,
card_bin: Some("123456".to_string()),
extended_card_bin: None,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: Some(enums::MandateAcceptanceType::Online),
mandate_type: None,
payment_type: None,
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_card_bin() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
card_bin="123456"
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
transaction_initiator: None,
amount: MinorUnit::new(32),
currency: enums::Currency::USD,
card_bin: Some("123456".to_string()),
extended_card_bin: None,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_payment_amount() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
amount = 32
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
transaction_initiator: None,
amount: MinorUnit::new(32),
currency: enums::Currency::USD,
card_bin: None,
extended_card_bin: None,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_payment_method() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
payment_method = pay_later
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
transaction_initiator: None,
amount: MinorUnit::new(32),
currency: enums::Currency::USD,
card_bin: None,
extended_card_bin: None,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_future_usage() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
setup_future_usage = off_session
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(32),
transaction_initiator: None,
currency: enums::Currency::USD,
card_bin: None,
extended_card_bin: None,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: Some(enums::SetupFutureUsage::OffSession),
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_metadata_execution() {
let program_str = r#"
default: ["stripe"," adyen"]
rule_1: ["stripe"]
{
"metadata_key" = "arbitrary meta"
}
"#;
let mut meta_map = FxHashMap::default();
meta_map.insert("metadata_key".to_string(), "arbitrary meta".to_string());
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: Some(meta_map),
payment: inputs::PaymentInput {
amount: MinorUnit::new(32),
transaction_initiator: None,
card_bin: None,
extended_card_bin: None,
currency: enums::Currency::USD,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_less_than_operator() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
amount>=123
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp_greater = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(150),
transaction_initiator: None,
card_bin: None,
extended_card_bin: None,
currency: enums::Currency::USD,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
let mut inp_equal = inp_greater.clone();
inp_equal.payment.amount = MinorUnit::new(123);
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result_greater = backend.execute(inp_greater).expect("Execution");
let result_equal = backend.execute(inp_equal).expect("Execution");
assert_eq!(
result_equal.rule_name.expect("Rule Name").as_str(),
"rule_1"
);
assert_eq!(
result_greater.rule_name.expect("Rule Name").as_str(),
"rule_1"
);
}
#[test]
fn test_greater_than_operator() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
amount<=123
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp_lower = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(120),
transaction_initiator: None,
card_bin: None,
extended_card_bin: None,
currency: enums::Currency::USD,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
let mut inp_equal = inp_lower.clone();
inp_equal.payment.amount = MinorUnit::new(123);
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result_equal = backend.execute(inp_equal).expect("Execution");
let result_lower = backend.execute(inp_lower).expect("Execution");
assert_eq!(
result_equal.rule_name.expect("Rule Name").as_str(),
"rule_1"
);
assert_eq!(
result_lower.rule_name.expect("Rule Name").as_str(),
"rule_1"
);
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/backend/vir_interpreter/types.rs | crates/euclid/src/backend/vir_interpreter/types.rs | 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(transaction_initiator) = payment.transaction_initiator {
enum_values.insert(EuclidValue::TransactionInitiator(transaction_initiator));
}
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(extended_card_bin) = payment.extended_card_bin {
enum_values.insert(EuclidValue::ExtendedCardBin(StrValue {
value: extended_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,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/backend/interpreter/types.rs | crates/euclid/src/backend/interpreter/types.rs | use std::{collections::HashMap, fmt, ops::Deref, string::ToString};
use serde::Serialize;
use crate::{backend::inputs, frontend::ast::ValueType, types::EuclidKey};
#[derive(Debug, Clone, Serialize, thiserror::Error)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum InterpreterErrorType {
#[error("Invalid key received '{0}'")]
InvalidKey(String),
#[error("Invalid Comparison")]
InvalidComparison,
}
#[derive(Debug, Clone, Serialize, thiserror::Error)]
pub struct InterpreterError {
pub error_type: InterpreterErrorType,
pub metadata: HashMap<String, serde_json::Value>,
}
impl fmt::Display for InterpreterError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
InterpreterErrorType::fmt(&self.error_type, f)
}
}
pub struct Context(HashMap<String, Option<ValueType>>);
impl Deref for Context {
type Target = HashMap<String, Option<ValueType>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<inputs::BackendInput> for Context {
fn from(input: inputs::BackendInput) -> Self {
let ctx = HashMap::<String, Option<ValueType>>::from_iter([
(
EuclidKey::PaymentMethod.to_string(),
input
.payment_method
.payment_method
.map(|pm| ValueType::EnumVariant(pm.to_string())),
),
(
EuclidKey::PaymentMethodType.to_string(),
input
.payment_method
.payment_method_type
.map(|pt| ValueType::EnumVariant(pt.to_string())),
),
(
EuclidKey::AuthenticationType.to_string(),
input
.payment
.authentication_type
.map(|at| ValueType::EnumVariant(at.to_string())),
),
(
EuclidKey::CaptureMethod.to_string(),
input
.payment
.capture_method
.map(|cm| ValueType::EnumVariant(cm.to_string())),
),
(
EuclidKey::PaymentAmount.to_string(),
Some(ValueType::Number(input.payment.amount)),
),
(
EuclidKey::PaymentCurrency.to_string(),
Some(ValueType::EnumVariant(input.payment.currency.to_string())),
),
]);
Self(ctx)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/types/transformers.rs | crates/euclid/src/types/transformers.rs | rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false | |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/frontend/ast.rs | crates/euclid/src/frontend/ast.rs | pub mod lowering;
#[cfg(feature = "ast_parser")]
pub mod parser;
use common_utils::types::MinorUnit;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::{
enums::RoutableConnectors,
types::{DataType, Metadata},
};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct ConnectorChoice {
pub connector: RoutableConnectors,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct MetadataValue {
pub key: String,
pub value: String,
}
/// Represents a value in the DSL
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum ValueType {
/// Represents a number literal
Number(MinorUnit),
/// Represents an enum variant
EnumVariant(String),
/// Represents a Metadata variant
MetadataVariant(MetadataValue),
/// Represents a arbitrary String value
StrValue(String),
/// Represents an array of numbers. This is basically used for
/// "one of the given numbers" operations
/// eg: payment.method.amount = (1, 2, 3)
NumberArray(Vec<MinorUnit>),
/// Similar to NumberArray but for enum variants
/// eg: payment.method.cardtype = (debit, credit)
EnumVariantArray(Vec<String>),
/// Like a number array but can include comparisons. Useful for
/// conditions like "500 < amount < 1000"
/// eg: payment.amount = (> 500, < 1000)
NumberComparisonArray(Vec<NumberComparison>),
}
impl ValueType {
pub fn get_type(&self) -> DataType {
match self {
Self::Number(_) => DataType::Number,
Self::StrValue(_) => DataType::StrValue,
Self::MetadataVariant(_) => DataType::MetadataValue,
Self::EnumVariant(_) => DataType::EnumVariant,
Self::NumberComparisonArray(_) => DataType::Number,
Self::NumberArray(_) => DataType::Number,
Self::EnumVariantArray(_) => DataType::EnumVariant,
}
}
}
/// Represents a number comparison for "NumberComparisonArrayValue"
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct NumberComparison {
pub comparison_type: ComparisonType,
pub number: MinorUnit,
}
/// Conditional comparison type
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ComparisonType {
Equal,
NotEqual,
LessThan,
LessThanEqual,
GreaterThan,
GreaterThanEqual,
}
/// Represents a single comparison condition.
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
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, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct IfStatement {
#[schema(value_type=Vec<Comparison>)]
pub condition: IfCondition,
pub nested: Option<Vec<Self>>,
}
/// 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, ToSchema)]
#[serde(rename_all = "camelCase")]
#[aliases(RuleConnectorSelection = Rule<ConnectorSelection>)]
pub struct Rule<O> {
pub name: String,
#[serde(alias = "routingOutput")]
pub connector_selection: O,
pub statements: Vec<IfStatement>,
}
/// The program, having a default connector selection and
/// a bunch of rules. Also can hold arbitrary metadata.
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
#[aliases(ProgramConnectorSelection = Program<ConnectorSelection>)]
pub struct Program<O> {
pub default_selection: O,
#[schema(value_type=RuleConnectorSelection)]
pub rules: Vec<Rule<O>>,
#[schema(value_type=HashMap<String, serde_json::Value>)]
pub metadata: Metadata,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct RoutableConnectorChoice {
#[serde(skip)]
pub choice_kind: RoutableChoiceKind,
pub connector: RoutableConnectors,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)]
pub enum RoutableChoiceKind {
OnlyConnector,
#[default]
FullStruct,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ConnectorVolumeSplit {
pub connector: RoutableConnectorChoice,
pub split: u8,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum ConnectorSelection {
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/frontend/vir.rs | crates/euclid/src/frontend/vir.rs | //! Valued Intermediate Representation
use serde::{Deserialize, Serialize};
use crate::types::{EuclidValue, Metadata};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ValuedComparisonLogic {
NegativeConjunction,
PositiveDisjunction,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValuedComparison {
pub values: Vec<EuclidValue>,
pub logic: ValuedComparisonLogic,
pub metadata: Metadata,
}
pub type ValuedIfCondition = Vec<ValuedComparison>;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValuedIfStatement {
pub condition: ValuedIfCondition,
pub nested: Option<Vec<Self>>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValuedRule<O> {
pub name: String,
pub connector_selection: O,
pub statements: Vec<ValuedIfStatement>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValuedProgram<O> {
pub default_selection: O,
pub rules: Vec<ValuedRule<O>>,
pub metadata: Metadata,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/frontend/dir.rs | crates/euclid/src/frontend/dir.rs | //! Domain Intermediate Representation
pub mod enums;
pub mod lowering;
pub mod transformers;
use strum::IntoEnumIterator;
// use common_utils::types::MinorUnit;
use crate::{enums as euclid_enums, frontend::ast, types};
#[macro_export]
macro_rules! dirval {
(Connector = $name:ident) => {
$crate::frontend::dir::DirValue::Connector(Box::new(
$crate::frontend::ast::ConnectorChoice {
connector: $crate::enums::RoutableConnectors::$name,
},
))
};
($key:ident = $val:ident) => {{
pub use $crate::frontend::dir::enums::*;
$crate::frontend::dir::DirValue::$key($key::$val)
}};
($key:ident = $num:literal) => {{
$crate::frontend::dir::DirValue::$key($crate::types::NumValue {
number: common_utils::types::MinorUnit::new($num),
refinement: None,
})
}};
($key:ident s= $str:literal) => {{
$crate::frontend::dir::DirValue::$key($crate::types::StrValue {
value: $str.to_string(),
})
}};
($key:literal = $str:literal) => {{
$crate::frontend::dir::DirValue::MetaData($crate::types::MetadataValue {
key: $key.to_string(),
value: $str.to_string(),
})
}};
}
#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize)]
pub struct DirKey {
pub kind: DirKeyKind,
pub value: Option<String>,
}
impl DirKey {
pub fn new(kind: DirKeyKind, value: Option<String>) -> Self {
Self { kind, value }
}
}
#[derive(
Debug,
Clone,
Hash,
PartialEq,
Eq,
serde::Serialize,
strum::Display,
strum::EnumIter,
strum::VariantNames,
strum::EnumString,
strum::EnumMessage,
strum::EnumProperty,
)]
pub enum DirKeyKind {
#[strum(
serialize = "payment_method",
detailed_message = "Different modes of payment - eg. cards, wallets, banks",
props(Category = "Payment Methods")
)]
#[serde(rename = "payment_method")]
PaymentMethod,
#[strum(
serialize = "card_bin",
detailed_message = "First 4 to 6 digits of a payment card number",
props(Category = "Payment Methods")
)]
#[serde(rename = "card_bin")]
CardBin,
#[strum(
serialize = "extended_card_bin",
detailed_message = "First 8 digits of a payment card number",
props(Category = "Payment Methods")
)]
#[serde(rename = "extended_card_bin")]
ExtendedCardBin,
#[strum(
serialize = "card_type",
detailed_message = "Type of the payment card - eg. credit, debit",
props(Category = "Payment Methods")
)]
#[serde(rename = "card_type")]
CardType,
#[strum(
serialize = "card_network",
detailed_message = "Network that facilitates payment card transactions",
props(Category = "Payment Methods")
)]
#[serde(rename = "card_network")]
CardNetwork,
#[strum(
serialize = "pay_later",
detailed_message = "Supported types of Pay Later payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "pay_later")]
PayLaterType,
#[strum(
serialize = "gift_card",
detailed_message = "Supported types of Gift Card payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "gift_card")]
GiftCardType,
#[strum(
serialize = "mandate_acceptance_type",
detailed_message = "Mode of customer acceptance for mandates - online and offline",
props(Category = "Payments")
)]
#[serde(rename = "mandate_acceptance_type")]
MandateAcceptanceType,
#[strum(
serialize = "mandate_type",
detailed_message = "Type of mandate acceptance - single use and multi use",
props(Category = "Payments")
)]
#[serde(rename = "mandate_type")]
MandateType,
#[strum(
serialize = "payment_type",
detailed_message = "Indicates if a payment is mandate or non-mandate",
props(Category = "Payments")
)]
#[serde(rename = "payment_type")]
PaymentType,
#[strum(
serialize = "wallet",
detailed_message = "Supported types of Wallet payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "wallet")]
WalletType,
#[strum(
serialize = "upi",
detailed_message = "Supported types of UPI payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "upi")]
UpiType,
#[strum(
serialize = "voucher",
detailed_message = "Supported types of Voucher payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "voucher")]
VoucherType,
#[strum(
serialize = "bank_transfer",
detailed_message = "Supported types of Bank Transfer payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "bank_transfer")]
BankTransferType,
#[strum(
serialize = "bank_redirect",
detailed_message = "Supported types of Bank Redirect payment methods",
props(Category = "Payment Method Types")
)]
#[serde(rename = "bank_redirect")]
BankRedirectType,
#[strum(
serialize = "bank_debit",
detailed_message = "Supported types of Bank Debit payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "bank_debit")]
BankDebitType,
#[strum(
serialize = "crypto",
detailed_message = "Supported types of Crypto payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "crypto")]
CryptoType,
#[strum(
serialize = "metadata",
detailed_message = "Aribitrary Key and value pair",
props(Category = "Metadata")
)]
#[serde(rename = "metadata")]
MetaData,
#[strum(
serialize = "reward",
detailed_message = "Supported types of Reward payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "reward")]
RewardType,
#[strum(
serialize = "amount",
detailed_message = "Value of the transaction",
props(Category = "Payments")
)]
#[serde(rename = "amount")]
PaymentAmount,
#[strum(
serialize = "currency",
detailed_message = "Currency used for the payment",
props(Category = "Payments")
)]
#[serde(rename = "currency")]
PaymentCurrency,
#[strum(
serialize = "authentication_type",
detailed_message = "Type of authentication for the payment",
props(Category = "Payments")
)]
#[serde(rename = "authentication_type")]
AuthenticationType,
#[strum(
serialize = "capture_method",
detailed_message = "Modes of capturing a payment",
props(Category = "Payments")
)]
#[serde(rename = "capture_method")]
CaptureMethod,
#[strum(
serialize = "country",
serialize = "business_country",
detailed_message = "Country of the business unit",
props(Category = "Merchant")
)]
#[serde(rename = "business_country", alias = "country")]
BusinessCountry,
#[strum(
serialize = "billing_country",
detailed_message = "Country of the billing address of the customer",
props(Category = "Customer")
)]
#[serde(rename = "billing_country")]
BillingCountry,
#[serde(skip_deserializing, rename = "connector")]
Connector,
#[strum(
serialize = "business_label",
detailed_message = "Identifier for business unit",
props(Category = "Merchant")
)]
#[serde(rename = "business_label")]
BusinessLabel,
#[strum(
serialize = "setup_future_usage",
detailed_message = "Identifier for recurring payments",
props(Category = "Payments")
)]
#[serde(rename = "setup_future_usage")]
SetupFutureUsage,
#[strum(
serialize = "card_redirect",
detailed_message = "Supported types of Card Redirect payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "card_redirect")]
CardRedirectType,
#[serde(rename = "real_time_payment")]
#[strum(
serialize = "real_time_payment",
detailed_message = "Supported types of real time payment method",
props(Category = "Payment Method Types")
)]
RealTimePaymentType,
#[serde(rename = "open_banking")]
#[strum(
serialize = "open_banking",
detailed_message = "Supported types of open banking payment method",
props(Category = "Payment Method Types")
)]
OpenBankingType,
#[serde(rename = "mobile_payment")]
#[strum(
serialize = "mobile_payment",
detailed_message = "Supported types of mobile payment method",
props(Category = "Payment Method Types")
)]
MobilePaymentType,
#[strum(
serialize = "issuer_name",
detailed_message = "Name of the card issuing bank",
props(Category = "3DS Decision")
)]
#[serde(rename = "issuer_name")]
IssuerName,
#[strum(
serialize = "issuer_country",
detailed_message = "Country of the card issuing bank",
props(Category = "3DS Decision")
)]
#[serde(rename = "issuer_country")]
IssuerCountry,
#[strum(
serialize = "customer_device_platform",
detailed_message = "Platform of the customer's device (Web, Android, iOS)",
props(Category = "3DS Decision")
)]
#[serde(rename = "customer_device_platform")]
CustomerDevicePlatform,
#[strum(
serialize = "customer_device_type",
detailed_message = "Type of the customer's device (Mobile, Tablet, Desktop, Gaming Console)",
props(Category = "3DS Decision")
)]
#[serde(rename = "customer_device_type")]
CustomerDeviceType,
#[strum(
serialize = "customer_device_display_size",
detailed_message = "Display size of the customer's device (e.g., 500x600)",
props(Category = "3DS Decision")
)]
#[serde(rename = "customer_device_display_size")]
CustomerDeviceDisplaySize,
#[strum(
serialize = "acquirer_country",
detailed_message = "Country of the acquiring bank",
props(Category = "3DS Decision")
)]
#[serde(rename = "acquirer_country")]
AcquirerCountry,
#[strum(
serialize = "acquirer_fraud_rate",
detailed_message = "Fraud rate of the acquiring bank",
props(Category = "3DS Decision")
)]
#[serde(rename = "acquirer_fraud_rate")]
AcquirerFraudRate,
#[strum(
serialize = "transaction_initiator",
detailed_message = "Initiator of transaction either Customer or Merchant",
props(Category = "Payments")
)]
#[serde(rename = "transaction_initiator")]
TransactionInitiator,
#[strum(
serialize = "network_token",
detailed_message = "Supported types of network token payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "network_token")]
NetworkTokenType,
}
pub trait EuclidDirFilter: Sized
where
Self: 'static,
{
const ALLOWED: &'static [DirKeyKind];
fn get_allowed_keys() -> &'static [DirKeyKind] {
Self::ALLOWED
}
fn is_key_allowed(key: &DirKeyKind) -> bool {
Self::ALLOWED.contains(key)
}
}
impl DirKeyKind {
pub fn get_type(&self) -> types::DataType {
match self {
Self::PaymentMethod => types::DataType::EnumVariant,
Self::CardBin => types::DataType::StrValue,
Self::ExtendedCardBin => types::DataType::StrValue,
Self::CardType => types::DataType::EnumVariant,
Self::CardNetwork => types::DataType::EnumVariant,
Self::MetaData => types::DataType::MetadataValue,
Self::MandateType => types::DataType::EnumVariant,
Self::PaymentType => types::DataType::EnumVariant,
Self::MandateAcceptanceType => types::DataType::EnumVariant,
Self::PayLaterType => types::DataType::EnumVariant,
Self::WalletType => types::DataType::EnumVariant,
Self::UpiType => types::DataType::EnumVariant,
Self::VoucherType => types::DataType::EnumVariant,
Self::BankTransferType => types::DataType::EnumVariant,
Self::GiftCardType => types::DataType::EnumVariant,
Self::BankRedirectType => types::DataType::EnumVariant,
Self::CryptoType => types::DataType::EnumVariant,
Self::RewardType => types::DataType::EnumVariant,
Self::PaymentAmount => types::DataType::Number,
Self::PaymentCurrency => types::DataType::EnumVariant,
Self::AuthenticationType => types::DataType::EnumVariant,
Self::CaptureMethod => types::DataType::EnumVariant,
Self::BusinessCountry => types::DataType::EnumVariant,
Self::BillingCountry => types::DataType::EnumVariant,
Self::Connector => types::DataType::EnumVariant,
Self::BankDebitType => types::DataType::EnumVariant,
Self::BusinessLabel => types::DataType::StrValue,
Self::SetupFutureUsage => types::DataType::EnumVariant,
Self::CardRedirectType => types::DataType::EnumVariant,
Self::RealTimePaymentType => types::DataType::EnumVariant,
Self::OpenBankingType => types::DataType::EnumVariant,
Self::MobilePaymentType => types::DataType::EnumVariant,
Self::IssuerName => types::DataType::StrValue,
Self::IssuerCountry => types::DataType::EnumVariant,
Self::CustomerDevicePlatform => types::DataType::EnumVariant,
Self::CustomerDeviceType => types::DataType::EnumVariant,
Self::CustomerDeviceDisplaySize => types::DataType::EnumVariant,
Self::AcquirerCountry => types::DataType::EnumVariant,
Self::AcquirerFraudRate => types::DataType::Number,
Self::TransactionInitiator => types::DataType::EnumVariant,
Self::NetworkTokenType => types::DataType::EnumVariant,
}
}
pub fn get_value_set(&self) -> Option<Vec<DirValue>> {
match self {
Self::PaymentMethod => Some(
enums::PaymentMethod::iter()
.map(DirValue::PaymentMethod)
.collect(),
),
Self::CardBin => None,
Self::ExtendedCardBin => None,
Self::CardType => Some(enums::CardType::iter().map(DirValue::CardType).collect()),
Self::MandateAcceptanceType => Some(
euclid_enums::MandateAcceptanceType::iter()
.map(DirValue::MandateAcceptanceType)
.collect(),
),
Self::PaymentType => Some(
euclid_enums::PaymentType::iter()
.map(DirValue::PaymentType)
.collect(),
),
Self::MandateType => Some(
euclid_enums::MandateType::iter()
.map(DirValue::MandateType)
.collect(),
),
Self::CardNetwork => Some(
enums::CardNetwork::iter()
.map(DirValue::CardNetwork)
.collect(),
),
Self::PayLaterType => Some(
enums::PayLaterType::iter()
.map(DirValue::PayLaterType)
.collect(),
),
Self::MetaData => None,
Self::WalletType => Some(
enums::WalletType::iter()
.map(DirValue::WalletType)
.collect(),
),
Self::UpiType => Some(enums::UpiType::iter().map(DirValue::UpiType).collect()),
Self::VoucherType => Some(
enums::VoucherType::iter()
.map(DirValue::VoucherType)
.collect(),
),
Self::BankTransferType => Some(
enums::BankTransferType::iter()
.map(DirValue::BankTransferType)
.collect(),
),
Self::GiftCardType => Some(
enums::GiftCardType::iter()
.map(DirValue::GiftCardType)
.collect(),
),
Self::BankRedirectType => Some(
enums::BankRedirectType::iter()
.map(DirValue::BankRedirectType)
.collect(),
),
Self::CryptoType => Some(
enums::CryptoType::iter()
.map(DirValue::CryptoType)
.collect(),
),
Self::RewardType => Some(
enums::RewardType::iter()
.map(DirValue::RewardType)
.collect(),
),
Self::PaymentAmount => None,
Self::PaymentCurrency => Some(
enums::PaymentCurrency::iter()
.map(DirValue::PaymentCurrency)
.collect(),
),
Self::AuthenticationType => Some(
enums::AuthenticationType::iter()
.map(DirValue::AuthenticationType)
.collect(),
),
Self::CaptureMethod => Some(
enums::CaptureMethod::iter()
.map(DirValue::CaptureMethod)
.collect(),
),
Self::BankDebitType => Some(
enums::BankDebitType::iter()
.map(DirValue::BankDebitType)
.collect(),
),
Self::BusinessCountry => Some(
enums::Country::iter()
.map(DirValue::BusinessCountry)
.collect(),
),
Self::BillingCountry => Some(
enums::Country::iter()
.map(DirValue::BillingCountry)
.collect(),
),
Self::Connector => Some(
crate::enums::RoutableConnectors::iter()
.map(|connector| {
DirValue::Connector(Box::new(ast::ConnectorChoice { connector }))
})
.collect(),
),
Self::BusinessLabel => None,
Self::SetupFutureUsage => Some(
enums::SetupFutureUsage::iter()
.map(DirValue::SetupFutureUsage)
.collect(),
),
Self::CardRedirectType => Some(
enums::CardRedirectType::iter()
.map(DirValue::CardRedirectType)
.collect(),
),
Self::RealTimePaymentType => Some(
enums::RealTimePaymentType::iter()
.map(DirValue::RealTimePaymentType)
.collect(),
),
Self::OpenBankingType => Some(
enums::OpenBankingType::iter()
.map(DirValue::OpenBankingType)
.collect(),
),
Self::MobilePaymentType => Some(
enums::MobilePaymentType::iter()
.map(DirValue::MobilePaymentType)
.collect(),
),
Self::IssuerName => None,
Self::IssuerCountry => Some(
enums::Country::iter()
.map(DirValue::IssuerCountry)
.collect(),
),
Self::CustomerDevicePlatform => Some(
enums::CustomerDevicePlatform::iter()
.map(DirValue::CustomerDevicePlatform)
.collect(),
),
Self::CustomerDeviceType => Some(
enums::CustomerDeviceType::iter()
.map(DirValue::CustomerDeviceType)
.collect(),
),
Self::CustomerDeviceDisplaySize => Some(
enums::CustomerDeviceDisplaySize::iter()
.map(DirValue::CustomerDeviceDisplaySize)
.collect(),
),
Self::AcquirerCountry => Some(
enums::Country::iter()
.map(DirValue::AcquirerCountry)
.collect(),
),
Self::AcquirerFraudRate => None,
Self::TransactionInitiator => Some(
enums::TransactionInitiator::iter()
.map(DirValue::TransactionInitiator)
.collect(),
),
Self::NetworkTokenType => Some(
enums::NetworkTokenType::iter()
.map(DirValue::NetworkTokenType)
.collect(),
),
}
}
}
#[derive(
Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, strum::Display, strum::VariantNames,
)]
#[serde(tag = "key", content = "value")]
pub enum DirValue {
#[serde(rename = "payment_method")]
PaymentMethod(enums::PaymentMethod),
#[serde(rename = "card_bin")]
CardBin(types::StrValue),
#[serde(rename = "extended_card_bin")]
ExtendedCardBin(types::StrValue),
#[serde(rename = "card_type")]
CardType(enums::CardType),
#[serde(rename = "card_network")]
CardNetwork(enums::CardNetwork),
#[serde(rename = "metadata")]
MetaData(types::MetadataValue),
#[serde(rename = "pay_later")]
PayLaterType(enums::PayLaterType),
#[serde(rename = "wallet")]
WalletType(enums::WalletType),
#[serde(rename = "acceptance_type")]
MandateAcceptanceType(euclid_enums::MandateAcceptanceType),
#[serde(rename = "mandate_type")]
MandateType(euclid_enums::MandateType),
#[serde(rename = "payment_type")]
PaymentType(euclid_enums::PaymentType),
#[serde(rename = "upi")]
UpiType(enums::UpiType),
#[serde(rename = "voucher")]
VoucherType(enums::VoucherType),
#[serde(rename = "bank_transfer")]
BankTransferType(enums::BankTransferType),
#[serde(rename = "bank_redirect")]
BankRedirectType(enums::BankRedirectType),
#[serde(rename = "bank_debit")]
BankDebitType(enums::BankDebitType),
#[serde(rename = "crypto")]
CryptoType(enums::CryptoType),
#[serde(rename = "reward")]
RewardType(enums::RewardType),
#[serde(rename = "gift_card")]
GiftCardType(enums::GiftCardType),
#[serde(rename = "amount")]
PaymentAmount(types::NumValue),
#[serde(rename = "currency")]
PaymentCurrency(enums::PaymentCurrency),
#[serde(rename = "authentication_type")]
AuthenticationType(enums::AuthenticationType),
#[serde(rename = "capture_method")]
CaptureMethod(enums::CaptureMethod),
#[serde(rename = "business_country", alias = "country")]
BusinessCountry(enums::Country),
#[serde(rename = "billing_country")]
BillingCountry(enums::Country),
#[serde(skip_deserializing, rename = "connector")]
Connector(Box<ast::ConnectorChoice>),
#[serde(rename = "business_label")]
BusinessLabel(types::StrValue),
#[serde(rename = "setup_future_usage")]
SetupFutureUsage(enums::SetupFutureUsage),
#[serde(rename = "card_redirect")]
CardRedirectType(enums::CardRedirectType),
#[serde(rename = "real_time_payment")]
RealTimePaymentType(enums::RealTimePaymentType),
#[serde(rename = "open_banking")]
OpenBankingType(enums::OpenBankingType),
#[serde(rename = "mobile_payment")]
MobilePaymentType(enums::MobilePaymentType),
#[serde(rename = "issuer_name")]
IssuerName(types::StrValue),
#[serde(rename = "issuer_country")]
IssuerCountry(enums::Country),
#[serde(rename = "customer_device_platform")]
CustomerDevicePlatform(enums::CustomerDevicePlatform),
#[serde(rename = "customer_device_type")]
CustomerDeviceType(enums::CustomerDeviceType),
#[serde(rename = "customer_device_display_size")]
CustomerDeviceDisplaySize(enums::CustomerDeviceDisplaySize),
#[serde(rename = "acquirer_country")]
AcquirerCountry(enums::Country),
#[serde(rename = "acquirer_fraud_rate")]
AcquirerFraudRate(types::NumValue),
#[serde(rename = "transaction_initiator")]
TransactionInitiator(enums::TransactionInitiator),
#[serde(rename = "network_token")]
NetworkTokenType(enums::NetworkTokenType),
}
impl DirValue {
pub fn get_key(&self) -> DirKey {
let (kind, data) = match self {
Self::PaymentMethod(_) => (DirKeyKind::PaymentMethod, None),
Self::CardBin(_) => (DirKeyKind::CardBin, None),
Self::ExtendedCardBin(_) => (DirKeyKind::ExtendedCardBin, None),
Self::RewardType(_) => (DirKeyKind::RewardType, None),
Self::BusinessCountry(_) => (DirKeyKind::BusinessCountry, None),
Self::BillingCountry(_) => (DirKeyKind::BillingCountry, None),
Self::BankTransferType(_) => (DirKeyKind::BankTransferType, None),
Self::UpiType(_) => (DirKeyKind::UpiType, None),
Self::CardType(_) => (DirKeyKind::CardType, None),
Self::CardNetwork(_) => (DirKeyKind::CardNetwork, None),
Self::MetaData(met) => (DirKeyKind::MetaData, Some(met.key.clone())),
Self::PayLaterType(_) => (DirKeyKind::PayLaterType, None),
Self::WalletType(_) => (DirKeyKind::WalletType, None),
Self::BankRedirectType(_) => (DirKeyKind::BankRedirectType, None),
Self::CryptoType(_) => (DirKeyKind::CryptoType, None),
Self::AuthenticationType(_) => (DirKeyKind::AuthenticationType, None),
Self::CaptureMethod(_) => (DirKeyKind::CaptureMethod, None),
Self::PaymentAmount(_) => (DirKeyKind::PaymentAmount, None),
Self::PaymentCurrency(_) => (DirKeyKind::PaymentCurrency, None),
Self::Connector(_) => (DirKeyKind::Connector, None),
Self::BankDebitType(_) => (DirKeyKind::BankDebitType, None),
Self::MandateAcceptanceType(_) => (DirKeyKind::MandateAcceptanceType, None),
Self::MandateType(_) => (DirKeyKind::MandateType, None),
Self::PaymentType(_) => (DirKeyKind::PaymentType, None),
Self::BusinessLabel(_) => (DirKeyKind::BusinessLabel, None),
Self::SetupFutureUsage(_) => (DirKeyKind::SetupFutureUsage, None),
Self::CardRedirectType(_) => (DirKeyKind::CardRedirectType, None),
Self::VoucherType(_) => (DirKeyKind::VoucherType, None),
Self::GiftCardType(_) => (DirKeyKind::GiftCardType, None),
Self::RealTimePaymentType(_) => (DirKeyKind::RealTimePaymentType, None),
Self::OpenBankingType(_) => (DirKeyKind::OpenBankingType, None),
Self::MobilePaymentType(_) => (DirKeyKind::MobilePaymentType, None),
Self::IssuerName(_) => (DirKeyKind::IssuerName, None),
Self::IssuerCountry(_) => (DirKeyKind::IssuerCountry, None),
Self::CustomerDevicePlatform(_) => (DirKeyKind::CustomerDevicePlatform, None),
Self::CustomerDeviceType(_) => (DirKeyKind::CustomerDeviceType, None),
Self::CustomerDeviceDisplaySize(_) => (DirKeyKind::CustomerDeviceDisplaySize, None),
Self::AcquirerCountry(_) => (DirKeyKind::AcquirerCountry, None),
Self::AcquirerFraudRate(_) => (DirKeyKind::AcquirerFraudRate, None),
Self::TransactionInitiator(_) => (DirKeyKind::TransactionInitiator, None),
Self::NetworkTokenType(_) => (DirKeyKind::NetworkTokenType, None),
};
DirKey::new(kind, data)
}
pub fn get_metadata_val(&self) -> Option<types::MetadataValue> {
match self {
Self::MetaData(val) => Some(val.clone()),
Self::PaymentMethod(_) => None,
Self::CardBin(_) => None,
Self::ExtendedCardBin(_) => None,
Self::CardType(_) => None,
Self::CardNetwork(_) => None,
Self::PayLaterType(_) => None,
Self::WalletType(_) => None,
Self::BankRedirectType(_) => None,
Self::CryptoType(_) => None,
Self::AuthenticationType(_) => None,
Self::CaptureMethod(_) => None,
Self::GiftCardType(_) => None,
Self::PaymentAmount(_) => None,
Self::PaymentCurrency(_) => None,
Self::BusinessCountry(_) => None,
Self::BillingCountry(_) => None,
Self::Connector(_) => None,
Self::BankTransferType(_) => None,
Self::UpiType(_) => None,
Self::BankDebitType(_) => None,
Self::RewardType(_) => None,
Self::VoucherType(_) => None,
Self::MandateAcceptanceType(_) => None,
Self::MandateType(_) => None,
Self::PaymentType(_) => None,
Self::BusinessLabel(_) => None,
Self::SetupFutureUsage(_) => None,
Self::CardRedirectType(_) => None,
Self::RealTimePaymentType(_) => None,
Self::OpenBankingType(_) => None,
Self::MobilePaymentType(_) => None,
Self::IssuerName(_) => None,
Self::IssuerCountry(_) => None,
Self::CustomerDevicePlatform(_) => None,
Self::CustomerDeviceType(_) => None,
Self::CustomerDeviceDisplaySize(_) => None,
Self::AcquirerCountry(_) => None,
Self::AcquirerFraudRate(_) => None,
Self::TransactionInitiator(_) => None,
Self::NetworkTokenType(_) => None,
}
}
pub fn get_str_val(&self) -> Option<types::StrValue> {
match self {
Self::CardBin(val) => Some(val.clone()),
Self::ExtendedCardBin(val) => Some(val.clone()),
Self::IssuerName(val) => Some(val.clone()),
_ => None,
}
}
pub fn get_num_value(&self) -> Option<types::NumValue> {
match self {
Self::PaymentAmount(val) => Some(val.clone()),
Self::AcquirerFraudRate(val) => Some(val.clone()),
_ => None,
}
}
pub fn check_equality(v1: &Self, v2: &Self) -> bool {
match (v1, v2) {
(Self::PaymentMethod(pm1), Self::PaymentMethod(pm2)) => pm1 == pm2,
(Self::CardType(ct1), Self::CardType(ct2)) => ct1 == ct2,
(Self::CardNetwork(cn1), Self::CardNetwork(cn2)) => cn1 == cn2,
(Self::MetaData(md1), Self::MetaData(md2)) => md1 == md2,
(Self::PayLaterType(plt1), Self::PayLaterType(plt2)) => plt1 == plt2,
(Self::WalletType(wt1), Self::WalletType(wt2)) => wt1 == wt2,
(Self::BankDebitType(bdt1), Self::BankDebitType(bdt2)) => bdt1 == bdt2,
(Self::BankRedirectType(brt1), Self::BankRedirectType(brt2)) => brt1 == brt2,
(Self::BankTransferType(btt1), Self::BankTransferType(btt2)) => btt1 == btt2,
(Self::GiftCardType(gct1), Self::GiftCardType(gct2)) => gct1 == gct2,
(Self::CryptoType(ct1), Self::CryptoType(ct2)) => ct1 == ct2,
(Self::AuthenticationType(at1), Self::AuthenticationType(at2)) => at1 == at2,
(Self::CaptureMethod(cm1), Self::CaptureMethod(cm2)) => cm1 == cm2,
(Self::PaymentCurrency(pc1), Self::PaymentCurrency(pc2)) => pc1 == pc2,
(Self::BusinessCountry(c1), Self::BusinessCountry(c2)) => c1 == c2,
(Self::BillingCountry(c1), Self::BillingCountry(c2)) => c1 == c2,
(Self::PaymentType(pt1), Self::PaymentType(pt2)) => pt1 == pt2,
(Self::MandateType(mt1), Self::MandateType(mt2)) => mt1 == mt2,
(Self::MandateAcceptanceType(mat1), Self::MandateAcceptanceType(mat2)) => mat1 == mat2,
(Self::RewardType(rt1), Self::RewardType(rt2)) => rt1 == rt2,
(Self::RealTimePaymentType(rtp1), Self::RealTimePaymentType(rtp2)) => rtp1 == rtp2,
(Self::Connector(c1), Self::Connector(c2)) => c1 == c2,
(Self::BusinessLabel(bl1), Self::BusinessLabel(bl2)) => bl1 == bl2,
(Self::SetupFutureUsage(sfu1), Self::SetupFutureUsage(sfu2)) => sfu1 == sfu2,
(Self::UpiType(ut1), Self::UpiType(ut2)) => ut1 == ut2,
(Self::VoucherType(vt1), Self::VoucherType(vt2)) => vt1 == vt2,
(Self::CardRedirectType(crt1), Self::CardRedirectType(crt2)) => crt1 == crt2,
(Self::IssuerName(n1), Self::IssuerName(n2)) => n1 == n2,
(Self::IssuerCountry(c1), Self::IssuerCountry(c2)) => c1 == c2,
(Self::CustomerDevicePlatform(p1), Self::CustomerDevicePlatform(p2)) => p1 == p2,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/frontend/ast/parser.rs | crates/euclid/src/frontend/ast/parser.rs | use common_utils::types::MinorUnit;
use nom::{
branch, bytes::complete, character::complete as pchar, combinator, error, multi, sequence,
};
use crate::{frontend::ast, types::DummyOutput};
pub type ParseResult<T, U> = nom::IResult<T, U, error::VerboseError<T>>;
pub enum EuclidError {
InvalidPercentage(String),
InvalidConnector(String),
InvalidOperator(String),
InvalidNumber(String),
}
pub trait EuclidParsable: Sized {
fn parse_output(input: &str) -> ParseResult<&str, Self>;
}
impl EuclidParsable for DummyOutput {
fn parse_output(input: &str) -> ParseResult<&str, Self> {
let string_w = sequence::delimited(
skip_ws(complete::tag("\"")),
complete::take_while(|c| c != '"'),
skip_ws(complete::tag("\"")),
);
let full_sequence = multi::many0(sequence::preceded(
skip_ws(complete::tag(",")),
sequence::delimited(
skip_ws(complete::tag("\"")),
complete::take_while(|c| c != '"'),
skip_ws(complete::tag("\"")),
),
));
let sequence = sequence::pair(string_w, full_sequence);
error::context(
"dummy_strings",
combinator::map(
sequence::delimited(
skip_ws(complete::tag("[")),
sequence,
skip_ws(complete::tag("]")),
),
|out: (&str, Vec<&str>)| {
let mut first = out.1;
first.insert(0, out.0);
let v = first.iter().map(|s| s.to_string()).collect();
Self { outputs: v }
},
),
)(input)
}
}
pub fn skip_ws<'a, F, O>(inner: F) -> impl FnMut(&'a str) -> ParseResult<&'a str, O>
where
F: FnMut(&'a str) -> ParseResult<&'a str, O> + 'a,
{
sequence::preceded(pchar::multispace0, inner)
}
pub fn num_i64(input: &str) -> ParseResult<&str, i64> {
error::context(
"num_i32",
combinator::map_res(
complete::take_while1(|c: char| c.is_ascii_digit()),
|o: &str| {
o.parse::<i64>()
.map_err(|_| EuclidError::InvalidNumber(o.to_string()))
},
),
)(input)
}
pub fn string_str(input: &str) -> ParseResult<&str, String> {
error::context(
"String",
combinator::map(
sequence::delimited(
complete::tag("\""),
complete::take_while1(|c: char| c != '"'),
complete::tag("\""),
),
|val: &str| val.to_string(),
),
)(input)
}
pub fn identifier(input: &str) -> ParseResult<&str, String> {
error::context(
"identifier",
combinator::map(
sequence::pair(
complete::take_while1(|c: char| c.is_ascii_alphabetic() || c == '_'),
complete::take_while(|c: char| c.is_ascii_alphanumeric() || c == '_'),
),
|out: (&str, &str)| out.0.to_string() + out.1,
),
)(input)
}
pub fn percentage(input: &str) -> ParseResult<&str, u8> {
error::context(
"volume_split_percentage",
combinator::map_res(
sequence::terminated(
complete::take_while_m_n(1, 2, |c: char| c.is_ascii_digit()),
complete::tag("%"),
),
|o: &str| {
o.parse::<u8>()
.map_err(|_| EuclidError::InvalidPercentage(o.to_string()))
},
),
)(input)
}
pub fn number_value(input: &str) -> ParseResult<&str, ast::ValueType> {
error::context(
"number_value",
combinator::map(num_i64, |n| ast::ValueType::Number(MinorUnit::new(n))),
)(input)
}
pub fn str_value(input: &str) -> ParseResult<&str, ast::ValueType> {
error::context(
"str_value",
combinator::map(string_str, ast::ValueType::StrValue),
)(input)
}
pub fn enum_value_string(input: &str) -> ParseResult<&str, String> {
combinator::map(
sequence::pair(
complete::take_while1(|c: char| c.is_ascii_alphabetic() || c == '_'),
complete::take_while(|c: char| c.is_ascii_alphanumeric() || c == '_'),
),
|out: (&str, &str)| out.0.to_string() + out.1,
)(input)
}
pub fn enum_variant_value(input: &str) -> ParseResult<&str, ast::ValueType> {
error::context(
"enum_variant_value",
combinator::map(enum_value_string, ast::ValueType::EnumVariant),
)(input)
}
pub fn number_array_value(input: &str) -> ParseResult<&str, ast::ValueType> {
fn num_minor_unit(input: &str) -> ParseResult<&str, MinorUnit> {
combinator::map(num_i64, MinorUnit::new)(input)
}
let many_with_comma = multi::many0(sequence::preceded(
skip_ws(complete::tag(",")),
skip_ws(num_minor_unit),
));
let full_sequence = sequence::pair(skip_ws(num_minor_unit), many_with_comma);
error::context(
"number_array_value",
combinator::map(
sequence::delimited(
skip_ws(complete::tag("(")),
full_sequence,
skip_ws(complete::tag(")")),
),
|tup: (MinorUnit, Vec<MinorUnit>)| {
let mut rest = tup.1;
rest.insert(0, tup.0);
ast::ValueType::NumberArray(rest)
},
),
)(input)
}
pub fn enum_variant_array_value(input: &str) -> ParseResult<&str, ast::ValueType> {
let many_with_comma = multi::many0(sequence::preceded(
skip_ws(complete::tag(",")),
skip_ws(enum_value_string),
));
let full_sequence = sequence::pair(skip_ws(enum_value_string), many_with_comma);
error::context(
"enum_variant_array_value",
combinator::map(
sequence::delimited(
skip_ws(complete::tag("(")),
full_sequence,
skip_ws(complete::tag(")")),
),
|tup: (String, Vec<String>)| {
let mut rest = tup.1;
rest.insert(0, tup.0);
ast::ValueType::EnumVariantArray(rest)
},
),
)(input)
}
pub fn number_comparison(input: &str) -> ParseResult<&str, ast::NumberComparison> {
let operator = combinator::map_res(
branch::alt((
complete::tag(">="),
complete::tag("<="),
complete::tag(">"),
complete::tag("<"),
)),
|s: &str| match s {
">=" => Ok(ast::ComparisonType::GreaterThanEqual),
"<=" => Ok(ast::ComparisonType::LessThanEqual),
">" => Ok(ast::ComparisonType::GreaterThan),
"<" => Ok(ast::ComparisonType::LessThan),
_ => Err(EuclidError::InvalidOperator(s.to_string())),
},
);
error::context(
"number_comparison",
combinator::map(
sequence::pair(operator, num_i64),
|tup: (ast::ComparisonType, i64)| ast::NumberComparison {
comparison_type: tup.0,
number: MinorUnit::new(tup.1),
},
),
)(input)
}
pub fn number_comparison_array_value(input: &str) -> ParseResult<&str, ast::ValueType> {
let many_with_comma = multi::many0(sequence::preceded(
skip_ws(complete::tag(",")),
skip_ws(number_comparison),
));
let full_sequence = sequence::pair(skip_ws(number_comparison), many_with_comma);
error::context(
"number_comparison_array_value",
combinator::map(
sequence::delimited(
skip_ws(complete::tag("(")),
full_sequence,
skip_ws(complete::tag(")")),
),
|tup: (ast::NumberComparison, Vec<ast::NumberComparison>)| {
let mut rest = tup.1;
rest.insert(0, tup.0);
ast::ValueType::NumberComparisonArray(rest)
},
),
)(input)
}
pub fn value_type(input: &str) -> ParseResult<&str, ast::ValueType> {
error::context(
"value_type",
branch::alt((
number_value,
enum_variant_value,
enum_variant_array_value,
number_array_value,
number_comparison_array_value,
str_value,
)),
)(input)
}
pub fn comparison_type(input: &str) -> ParseResult<&str, ast::ComparisonType> {
error::context(
"comparison_operator",
combinator::map_res(
branch::alt((
complete::tag("/="),
complete::tag(">="),
complete::tag("<="),
complete::tag("="),
complete::tag(">"),
complete::tag("<"),
)),
|s: &str| match s {
"/=" => Ok(ast::ComparisonType::NotEqual),
">=" => Ok(ast::ComparisonType::GreaterThanEqual),
"<=" => Ok(ast::ComparisonType::LessThanEqual),
"=" => Ok(ast::ComparisonType::Equal),
">" => Ok(ast::ComparisonType::GreaterThan),
"<" => Ok(ast::ComparisonType::LessThan),
_ => Err(EuclidError::InvalidOperator(s.to_string())),
},
),
)(input)
}
pub fn comparison(input: &str) -> ParseResult<&str, ast::Comparison> {
error::context(
"condition",
combinator::map(
sequence::tuple((
skip_ws(complete::take_while1(|c: char| {
c.is_ascii_alphabetic() || c == '.' || c == '_'
})),
skip_ws(comparison_type),
skip_ws(value_type),
)),
|tup: (&str, ast::ComparisonType, ast::ValueType)| ast::Comparison {
lhs: tup.0.to_string(),
comparison: tup.1,
value: tup.2,
metadata: std::collections::HashMap::new(),
},
),
)(input)
}
pub fn arbitrary_comparison(input: &str) -> ParseResult<&str, ast::Comparison> {
error::context(
"condition",
combinator::map(
sequence::tuple((
skip_ws(string_str),
skip_ws(comparison_type),
skip_ws(string_str),
)),
|tup: (String, ast::ComparisonType, String)| ast::Comparison {
lhs: "metadata".to_string(),
comparison: tup.1,
value: ast::ValueType::MetadataVariant(ast::MetadataValue {
key: tup.0,
value: tup.2,
}),
metadata: std::collections::HashMap::new(),
},
),
)(input)
}
pub fn comparison_array(input: &str) -> ParseResult<&str, Vec<ast::Comparison>> {
let many_with_ampersand = error::context(
"many_with_amp",
multi::many0(sequence::preceded(skip_ws(complete::tag("&")), comparison)),
);
let full_sequence = sequence::pair(
skip_ws(branch::alt((comparison, arbitrary_comparison))),
many_with_ampersand,
);
error::context(
"comparison_array",
combinator::map(
full_sequence,
|tup: (ast::Comparison, Vec<ast::Comparison>)| {
let mut rest = tup.1;
rest.insert(0, tup.0);
rest
},
),
)(input)
}
pub fn if_statement(input: &str) -> ParseResult<&str, ast::IfStatement> {
let nested_block = sequence::delimited(
skip_ws(complete::tag("{")),
multi::many0(if_statement),
skip_ws(complete::tag("}")),
);
error::context(
"if_statement",
combinator::map(
sequence::pair(comparison_array, combinator::opt(nested_block)),
|tup: (ast::IfCondition, Option<Vec<ast::IfStatement>>)| ast::IfStatement {
condition: tup.0,
nested: tup.1,
},
),
)(input)
}
pub fn rule_conditions_array(input: &str) -> ParseResult<&str, Vec<ast::IfStatement>> {
error::context(
"rules_array",
sequence::delimited(
skip_ws(complete::tag("{")),
multi::many1(if_statement),
skip_ws(complete::tag("}")),
),
)(input)
}
pub fn rule<O: EuclidParsable>(input: &str) -> ParseResult<&str, ast::Rule<O>> {
let rule_name = error::context(
"rule_name",
combinator::map(
skip_ws(sequence::pair(
complete::take_while1(|c: char| c.is_ascii_alphabetic() || c == '_'),
complete::take_while(|c: char| c.is_ascii_alphanumeric() || c == '_'),
)),
|out: (&str, &str)| out.0.to_string() + out.1,
),
);
let connector_selection = error::context(
"parse_output",
sequence::preceded(skip_ws(complete::tag(":")), output),
);
error::context(
"rule",
combinator::map(
sequence::tuple((rule_name, connector_selection, rule_conditions_array)),
|tup: (String, O, Vec<ast::IfStatement>)| ast::Rule {
name: tup.0,
connector_selection: tup.1,
statements: tup.2,
},
),
)(input)
}
pub fn output<O: EuclidParsable>(input: &str) -> ParseResult<&str, O> {
O::parse_output(input)
}
pub fn default_output<O: EuclidParsable + 'static>(input: &str) -> ParseResult<&str, O> {
error::context(
"default_output",
sequence::preceded(
sequence::pair(skip_ws(complete::tag("default")), skip_ws(pchar::char(':'))),
skip_ws(output),
),
)(input)
}
pub fn program<O: EuclidParsable + 'static>(input: &str) -> ParseResult<&str, ast::Program<O>> {
error::context(
"program",
combinator::map(
sequence::pair(default_output, multi::many1(skip_ws(rule::<O>))),
|tup: (O, Vec<ast::Rule<O>>)| ast::Program {
default_selection: tup.0,
rules: tup.1,
metadata: std::collections::HashMap::new(),
},
),
)(input)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/frontend/ast/lowering.rs | crates/euclid/src/frontend/ast/lowering.rs | //! Analysis for the Lowering logic in ast
//!
//!Certain functions that can be used to perform the complete lowering of ast to dir.
//!This includes lowering of enums, numbers, strings as well as Comparison logics.
use std::str::FromStr;
use crate::{
dssa::types::{AnalysisError, AnalysisErrorType},
enums::CollectVariants,
frontend::{
ast,
dir::{self, enums as dir_enums, EuclidDirFilter},
},
types::{self, DataType},
};
/// lowers the provided key (enum variant) & value to the respective DirValue
///
/// For example
/// ```notrust
/// CardType = Visa
/// ```notrust
///
/// This serves for the purpose were we have the DirKey as an explicit Enum type and value as one
/// of the member of the same Enum.
/// So particularly it lowers a predefined Enum from DirKey to an Enum of DirValue.
macro_rules! lower_enum {
($key:ident, $value:ident) => {
match $value {
ast::ValueType::EnumVariant(ev) => Ok(vec![dir::DirValue::$key(
dir_enums::$key::from_str(&ev).map_err(|_| AnalysisErrorType::InvalidVariant {
key: dir::DirKeyKind::$key.to_string(),
got: ev,
expected: dir_enums::$key::variants(),
})?,
)]),
ast::ValueType::EnumVariantArray(eva) => eva
.into_iter()
.map(|ev| {
Ok(dir::DirValue::$key(
dir_enums::$key::from_str(&ev).map_err(|_| {
AnalysisErrorType::InvalidVariant {
key: dir::DirKeyKind::$key.to_string(),
got: ev,
expected: dir_enums::$key::variants(),
}
})?,
))
})
.collect(),
_ => Err(AnalysisErrorType::InvalidType {
key: dir::DirKeyKind::$key.to_string(),
expected: DataType::EnumVariant,
got: $value.get_type(),
}),
}
};
}
/// lowers the provided key for a numerical value
///
/// For example
/// ```notrust
/// payment_amount = 17052001
/// ```notrust
/// This is for the cases in which there are numerical values involved and they are lowered
/// accordingly on basis of the supplied key, currently payment_amount is the only key having this
/// use case
macro_rules! lower_number {
($key:ident, $value:ident, $comp:ident) => {
match $value {
ast::ValueType::Number(num) => Ok(vec![dir::DirValue::$key(types::NumValue {
number: num,
refinement: $comp.into(),
})]),
ast::ValueType::NumberArray(na) => na
.into_iter()
.map(|num| {
Ok(dir::DirValue::$key(types::NumValue {
number: num,
refinement: $comp.clone().into(),
}))
})
.collect(),
ast::ValueType::NumberComparisonArray(nca) => nca
.into_iter()
.map(|nc| {
Ok(dir::DirValue::$key(types::NumValue {
number: nc.number,
refinement: nc.comparison_type.into(),
}))
})
.collect(),
_ => Err(AnalysisErrorType::InvalidType {
key: dir::DirKeyKind::$key.to_string(),
expected: DataType::Number,
got: $value.get_type(),
}),
}
};
}
/// lowers the provided key & value to the respective DirValue
///
/// For example
/// ```notrust
/// card_bin = "123456"
/// ```notrust
///
/// This serves for the purpose were we have the DirKey as Card_bin and value as an arbitrary string
/// So particularly it lowers an arbitrary value to a predefined key.
macro_rules! lower_str {
($key:ident, $value:ident $(, $validation_closure:expr)?) => {
match $value {
ast::ValueType::StrValue(st) => {
$($validation_closure(&st)?;)?
Ok(vec![dir::DirValue::$key(types::StrValue { value: st })])
}
_ => Err(AnalysisErrorType::InvalidType {
key: dir::DirKeyKind::$key.to_string(),
expected: DataType::StrValue,
got: $value.get_type(),
}),
}
};
}
macro_rules! lower_metadata {
($key:ident, $value:ident) => {
match $value {
ast::ValueType::MetadataVariant(md) => {
Ok(vec![dir::DirValue::$key(types::MetadataValue {
key: md.key,
value: md.value,
})])
}
_ => Err(AnalysisErrorType::InvalidType {
key: dir::DirKeyKind::$key.to_string(),
expected: DataType::MetadataValue,
got: $value.get_type(),
}),
}
};
}
/// lowers the comparison operators for different subtle value types present
/// by throwing required errors for comparisons that can't be performed for a certain value type
/// for example
/// can't have greater/less than operations on enum types
fn lower_comparison_inner<O: EuclidDirFilter>(
comp: ast::Comparison,
) -> Result<Vec<dir::DirValue>, AnalysisErrorType> {
let key_enum = dir::DirKeyKind::from_str(comp.lhs.as_str())
.map_err(|_| AnalysisErrorType::InvalidKey(comp.lhs.clone()))?;
if !O::is_key_allowed(&key_enum) {
return Err(AnalysisErrorType::InvalidKey(key_enum.to_string()));
}
match (&comp.comparison, &comp.value) {
(
ast::ComparisonType::LessThan
| ast::ComparisonType::GreaterThan
| ast::ComparisonType::GreaterThanEqual
| ast::ComparisonType::LessThanEqual,
ast::ValueType::EnumVariant(_),
) => {
Err(AnalysisErrorType::InvalidComparison {
operator: comp.comparison.clone(),
value_type: DataType::EnumVariant,
})?;
}
(
ast::ComparisonType::LessThan
| ast::ComparisonType::GreaterThan
| ast::ComparisonType::GreaterThanEqual
| ast::ComparisonType::LessThanEqual,
ast::ValueType::NumberArray(_),
) => {
Err(AnalysisErrorType::InvalidComparison {
operator: comp.comparison.clone(),
value_type: DataType::Number,
})?;
}
(
ast::ComparisonType::LessThan
| ast::ComparisonType::GreaterThan
| ast::ComparisonType::GreaterThanEqual
| ast::ComparisonType::LessThanEqual,
ast::ValueType::EnumVariantArray(_),
) => {
Err(AnalysisErrorType::InvalidComparison {
operator: comp.comparison.clone(),
value_type: DataType::EnumVariant,
})?;
}
(
ast::ComparisonType::LessThan
| ast::ComparisonType::GreaterThan
| ast::ComparisonType::GreaterThanEqual
| ast::ComparisonType::LessThanEqual,
ast::ValueType::NumberComparisonArray(_),
) => {
Err(AnalysisErrorType::InvalidComparison {
operator: comp.comparison.clone(),
value_type: DataType::Number,
})?;
}
_ => {}
}
let value = comp.value;
let comparison = comp.comparison;
match key_enum {
dir::DirKeyKind::PaymentMethod => lower_enum!(PaymentMethod, value),
dir::DirKeyKind::CardType => lower_enum!(CardType, value),
dir::DirKeyKind::CardNetwork => lower_enum!(CardNetwork, value),
dir::DirKeyKind::PayLaterType => lower_enum!(PayLaterType, value),
dir::DirKeyKind::WalletType => lower_enum!(WalletType, value),
dir::DirKeyKind::BankDebitType => lower_enum!(BankDebitType, value),
dir::DirKeyKind::BankRedirectType => lower_enum!(BankRedirectType, value),
dir::DirKeyKind::CryptoType => lower_enum!(CryptoType, value),
dir::DirKeyKind::PaymentType => lower_enum!(PaymentType, value),
dir::DirKeyKind::MandateType => lower_enum!(MandateType, value),
dir::DirKeyKind::MandateAcceptanceType => lower_enum!(MandateAcceptanceType, value),
dir::DirKeyKind::RewardType => lower_enum!(RewardType, value),
dir::DirKeyKind::PaymentCurrency => lower_enum!(PaymentCurrency, value),
dir::DirKeyKind::AuthenticationType => lower_enum!(AuthenticationType, value),
dir::DirKeyKind::CaptureMethod => lower_enum!(CaptureMethod, value),
dir::DirKeyKind::BusinessCountry => lower_enum!(BusinessCountry, value),
dir::DirKeyKind::BillingCountry => lower_enum!(BillingCountry, value),
dir::DirKeyKind::SetupFutureUsage => lower_enum!(SetupFutureUsage, value),
dir::DirKeyKind::UpiType => lower_enum!(UpiType, value),
dir::DirKeyKind::OpenBankingType => lower_enum!(OpenBankingType, value),
dir::DirKeyKind::VoucherType => lower_enum!(VoucherType, value),
dir::DirKeyKind::GiftCardType => lower_enum!(GiftCardType, value),
dir::DirKeyKind::BankTransferType => lower_enum!(BankTransferType, value),
dir::DirKeyKind::CardRedirectType => lower_enum!(CardRedirectType, value),
dir::DirKeyKind::MobilePaymentType => lower_enum!(MobilePaymentType, value),
dir::DirKeyKind::RealTimePaymentType => lower_enum!(RealTimePaymentType, value),
dir::DirKeyKind::CardBin => {
let validation_closure = |st: &String| -> Result<(), AnalysisErrorType> {
if st.len() == 6 && st.chars().all(|x| x.is_ascii_digit()) {
Ok(())
} else {
Err(AnalysisErrorType::InvalidValue {
key: dir::DirKeyKind::CardBin,
value: st.clone(),
message: Some("Expected 6 digits".to_string()),
})
}
};
lower_str!(CardBin, value, validation_closure)
}
dir::DirKeyKind::ExtendedCardBin => {
let validation_closure = |st: &String| -> Result<(), AnalysisErrorType> {
if st.len() == 8 && st.chars().all(|x| x.is_ascii_digit()) {
Ok(())
} else {
Err(AnalysisErrorType::InvalidValue {
key: dir::DirKeyKind::ExtendedCardBin,
value: st.clone(),
message: Some("Expected 8 digits".to_string()),
})
}
};
lower_str!(ExtendedCardBin, value, validation_closure)
}
dir::DirKeyKind::BusinessLabel => lower_str!(BusinessLabel, value),
dir::DirKeyKind::MetaData => lower_metadata!(MetaData, value),
dir::DirKeyKind::PaymentAmount => lower_number!(PaymentAmount, value, comparison),
dir::DirKeyKind::Connector => Err(AnalysisErrorType::InvalidKey(
dir::DirKeyKind::Connector.to_string(),
)),
dir::DirKeyKind::IssuerName => lower_str!(IssuerName, value),
dir::DirKeyKind::IssuerCountry => lower_enum!(IssuerCountry, value),
dir::DirKeyKind::CustomerDevicePlatform => lower_enum!(CustomerDevicePlatform, value),
dir::DirKeyKind::CustomerDeviceType => lower_enum!(CustomerDeviceType, value),
dir::DirKeyKind::CustomerDeviceDisplaySize => lower_enum!(CustomerDeviceDisplaySize, value),
dir::DirKeyKind::AcquirerCountry => lower_enum!(AcquirerCountry, value),
dir::DirKeyKind::AcquirerFraudRate => lower_number!(AcquirerFraudRate, value, comparison),
dir::DirKeyKind::TransactionInitiator => lower_enum!(TransactionInitiator, value),
dir::DirKeyKind::NetworkTokenType => lower_enum!(NetworkTokenType, value),
}
}
/// returns all the comparison values by matching them appropriately to ComparisonTypes and in turn
/// calls the lower_comparison_inner function
fn lower_comparison<O: EuclidDirFilter>(
comp: ast::Comparison,
) -> Result<dir::DirComparison, AnalysisError> {
let metadata = comp.metadata.clone();
let logic = match &comp.comparison {
ast::ComparisonType::Equal => dir::DirComparisonLogic::PositiveDisjunction,
ast::ComparisonType::NotEqual => dir::DirComparisonLogic::NegativeConjunction,
ast::ComparisonType::LessThan => dir::DirComparisonLogic::PositiveDisjunction,
ast::ComparisonType::LessThanEqual => dir::DirComparisonLogic::PositiveDisjunction,
ast::ComparisonType::GreaterThanEqual => dir::DirComparisonLogic::PositiveDisjunction,
ast::ComparisonType::GreaterThan => dir::DirComparisonLogic::PositiveDisjunction,
};
let values = lower_comparison_inner::<O>(comp).map_err(|etype| AnalysisError {
error_type: etype,
metadata: metadata.clone(),
})?;
Ok(dir::DirComparison {
values,
logic,
metadata,
})
}
/// lowers the if statement accordingly with a condition and following nested if statements (if
/// present)
fn lower_if_statement<O: EuclidDirFilter>(
stmt: ast::IfStatement,
) -> Result<dir::DirIfStatement, AnalysisError> {
Ok(dir::DirIfStatement {
condition: stmt
.condition
.into_iter()
.map(lower_comparison::<O>)
.collect::<Result<_, _>>()?,
nested: stmt
.nested
.map(|n| n.into_iter().map(lower_if_statement::<O>).collect())
.transpose()?,
})
}
/// lowers the rules supplied accordingly to DirRule struct by specifying the rule_name,
/// connector_selection and statements that are a bunch of if statements
pub fn lower_rule<O: EuclidDirFilter>(
rule: ast::Rule<O>,
) -> Result<dir::DirRule<O>, AnalysisError> {
Ok(dir::DirRule {
name: rule.name,
connector_selection: rule.connector_selection,
statements: rule
.statements
.into_iter()
.map(lower_if_statement::<O>)
.collect::<Result<_, _>>()?,
})
}
/// uses the above rules and lowers the whole ast Program into DirProgram by specifying
/// default_selection that is ast ConnectorSelection, a vector of DirRules and clones the metadata
/// whatever comes in the ast_program
pub fn lower_program<O: EuclidDirFilter>(
program: ast::Program<O>,
) -> Result<dir::DirProgram<O>, AnalysisError> {
Ok(dir::DirProgram {
default_selection: program.default_selection,
rules: program
.rules
.into_iter()
.map(lower_rule)
.collect::<Result<_, _>>()?,
metadata: program.metadata,
})
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/frontend/dir/enums.rs | crates/euclid/src/frontend/dir/enums.rs | 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,
Payjustnow,
}
#[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,
OpenBanking,
}
#[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 NetworkTokenType {
NetworkToken,
}
#[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 TransactionInitiator {
Customer,
Merchant,
}
#[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!(NetworkTokenType);
collect_variants!(CustomerDeviceType);
collect_variants!(CustomerDevicePlatform);
collect_variants!(CustomerDeviceDisplaySize);
collect_variants!(TransactionInitiator);
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/frontend/dir/lowering.rs | crates/euclid/src/frontend/dir/lowering.rs | //! Analysis of the lowering logic for the DIR
//!
//! Consists of certain functions that supports the lowering logic from DIR to VIR.
//! These includes the lowering of the DIR program and vector of rules , and the lowering of ifstatements
//! ,and comparisonsLogic and also the lowering of the enums of value variants from DIR to VIR.
use super::enums;
use crate::{
dssa::types::{AnalysisError, AnalysisErrorType},
enums as global_enums,
frontend::{dir, vir},
types::EuclidValue,
};
impl From<enums::CardType> for global_enums::PaymentMethodType {
fn from(value: enums::CardType) -> Self {
match value {
enums::CardType::Credit => Self::Credit,
enums::CardType::Debit => Self::Debit,
#[cfg(feature = "v2")]
enums::CardType::Card => Self::Card,
}
}
}
impl From<enums::PayLaterType> for global_enums::PaymentMethodType {
fn from(value: enums::PayLaterType) -> Self {
match value {
enums::PayLaterType::Affirm => Self::Affirm,
enums::PayLaterType::AfterpayClearpay => Self::AfterpayClearpay,
enums::PayLaterType::Alma => Self::Alma,
enums::PayLaterType::Flexiti => Self::Flexiti,
enums::PayLaterType::Klarna => Self::Klarna,
enums::PayLaterType::PayBright => Self::PayBright,
enums::PayLaterType::Walley => Self::Walley,
enums::PayLaterType::Atome => Self::Atome,
enums::PayLaterType::Breadpay => Self::Breadpay,
enums::PayLaterType::Payjustnow => Self::Payjustnow,
}
}
}
impl From<enums::WalletType> for global_enums::PaymentMethodType {
fn from(value: enums::WalletType) -> Self {
match value {
enums::WalletType::Bluecode => Self::Bluecode,
enums::WalletType::GooglePay => Self::GooglePay,
enums::WalletType::AmazonPay => Self::AmazonPay,
enums::WalletType::Skrill => Self::Skrill,
enums::WalletType::Paysera => Self::Paysera,
enums::WalletType::ApplePay => Self::ApplePay,
enums::WalletType::Paypal => Self::Paypal,
enums::WalletType::AliPay => Self::AliPay,
enums::WalletType::AliPayHk => Self::AliPayHk,
enums::WalletType::MbWay => Self::MbWay,
enums::WalletType::MobilePay => Self::MobilePay,
enums::WalletType::WeChatPay => Self::WeChatPay,
enums::WalletType::SamsungPay => Self::SamsungPay,
enums::WalletType::GoPay => Self::GoPay,
enums::WalletType::KakaoPay => Self::KakaoPay,
enums::WalletType::Twint => Self::Twint,
enums::WalletType::Gcash => Self::Gcash,
enums::WalletType::Vipps => Self::Vipps,
enums::WalletType::Momo => Self::Momo,
enums::WalletType::Dana => Self::Dana,
enums::WalletType::TouchNGo => Self::TouchNGo,
enums::WalletType::Swish => Self::Swish,
enums::WalletType::Cashapp => Self::Cashapp,
enums::WalletType::Venmo => Self::Venmo,
enums::WalletType::Mifinity => Self::Mifinity,
enums::WalletType::Paze => Self::Paze,
enums::WalletType::RevolutPay => Self::RevolutPay,
}
}
}
impl From<enums::BankDebitType> for global_enums::PaymentMethodType {
fn from(value: enums::BankDebitType) -> Self {
match value {
enums::BankDebitType::Ach => Self::Ach,
enums::BankDebitType::Sepa => Self::Sepa,
enums::BankDebitType::SepaGuarenteedDebit => Self::SepaGuarenteedDebit,
enums::BankDebitType::Bacs => Self::Bacs,
enums::BankDebitType::Becs => Self::Becs,
}
}
}
impl From<enums::UpiType> for global_enums::PaymentMethodType {
fn from(value: enums::UpiType) -> Self {
match value {
enums::UpiType::UpiCollect => Self::UpiCollect,
enums::UpiType::UpiIntent => Self::UpiIntent,
enums::UpiType::UpiQr => Self::UpiQr,
}
}
}
impl From<enums::VoucherType> for global_enums::PaymentMethodType {
fn from(value: enums::VoucherType) -> Self {
match value {
enums::VoucherType::Boleto => Self::Boleto,
enums::VoucherType::Efecty => Self::Efecty,
enums::VoucherType::PagoEfectivo => Self::PagoEfectivo,
enums::VoucherType::RedCompra => Self::RedCompra,
enums::VoucherType::RedPagos => Self::RedPagos,
enums::VoucherType::Alfamart => Self::Alfamart,
enums::VoucherType::Indomaret => Self::Indomaret,
enums::VoucherType::SevenEleven => Self::SevenEleven,
enums::VoucherType::Lawson => Self::Lawson,
enums::VoucherType::MiniStop => Self::MiniStop,
enums::VoucherType::FamilyMart => Self::FamilyMart,
enums::VoucherType::Seicomart => Self::Seicomart,
enums::VoucherType::PayEasy => Self::PayEasy,
enums::VoucherType::Oxxo => Self::Oxxo,
}
}
}
impl From<enums::BankTransferType> for global_enums::PaymentMethodType {
fn from(value: enums::BankTransferType) -> Self {
match value {
enums::BankTransferType::Multibanco => Self::Multibanco,
enums::BankTransferType::Pix => Self::Pix,
enums::BankTransferType::Pse => Self::Pse,
enums::BankTransferType::Ach => Self::Ach,
enums::BankTransferType::SepaBankTransfer => Self::Sepa,
enums::BankTransferType::Bacs => Self::Bacs,
enums::BankTransferType::BcaBankTransfer => Self::BcaBankTransfer,
enums::BankTransferType::BniVa => Self::BniVa,
enums::BankTransferType::BriVa => Self::BriVa,
enums::BankTransferType::CimbVa => Self::CimbVa,
enums::BankTransferType::DanamonVa => Self::DanamonVa,
enums::BankTransferType::MandiriVa => Self::MandiriVa,
enums::BankTransferType::PermataBankTransfer => Self::PermataBankTransfer,
enums::BankTransferType::LocalBankTransfer => Self::LocalBankTransfer,
enums::BankTransferType::InstantBankTransfer => Self::InstantBankTransfer,
enums::BankTransferType::InstantBankTransferFinland => Self::InstantBankTransferFinland,
enums::BankTransferType::InstantBankTransferPoland => Self::InstantBankTransferPoland,
enums::BankTransferType::IndonesianBankTransfer => Self::IndonesianBankTransfer,
}
}
}
impl From<enums::GiftCardType> for global_enums::PaymentMethodType {
fn from(value: enums::GiftCardType) -> Self {
match value {
enums::GiftCardType::PaySafeCard => Self::PaySafeCard,
enums::GiftCardType::Givex => Self::Givex,
enums::GiftCardType::BhnCardNetwork => Self::BhnCardNetwork,
}
}
}
impl From<enums::CardRedirectType> for global_enums::PaymentMethodType {
fn from(value: enums::CardRedirectType) -> Self {
match value {
enums::CardRedirectType::Benefit => Self::Benefit,
enums::CardRedirectType::Knet => Self::Knet,
enums::CardRedirectType::MomoAtm => Self::MomoAtm,
enums::CardRedirectType::CardRedirect => Self::CardRedirect,
}
}
}
impl From<enums::MobilePaymentType> for global_enums::PaymentMethodType {
fn from(value: enums::MobilePaymentType) -> Self {
match value {
enums::MobilePaymentType::DirectCarrierBilling => Self::DirectCarrierBilling,
}
}
}
impl From<enums::NetworkTokenType> for global_enums::PaymentMethodType {
fn from(value: enums::NetworkTokenType) -> Self {
match value {
enums::NetworkTokenType::NetworkToken => Self::NetworkToken,
}
}
}
impl From<enums::BankRedirectType> for global_enums::PaymentMethodType {
fn from(value: enums::BankRedirectType) -> Self {
match value {
enums::BankRedirectType::Bizum => Self::Bizum,
enums::BankRedirectType::Giropay => Self::Giropay,
enums::BankRedirectType::Ideal => Self::Ideal,
enums::BankRedirectType::Sofort => Self::Sofort,
enums::BankRedirectType::Eft => Self::Eft,
enums::BankRedirectType::Eps => Self::Eps,
enums::BankRedirectType::BancontactCard => Self::BancontactCard,
enums::BankRedirectType::Blik => Self::Blik,
enums::BankRedirectType::Interac => Self::Interac,
enums::BankRedirectType::LocalBankRedirect => Self::LocalBankRedirect,
enums::BankRedirectType::OnlineBankingCzechRepublic => Self::OnlineBankingCzechRepublic,
enums::BankRedirectType::OnlineBankingFinland => Self::OnlineBankingFinland,
enums::BankRedirectType::OnlineBankingPoland => Self::OnlineBankingPoland,
enums::BankRedirectType::OnlineBankingSlovakia => Self::OnlineBankingSlovakia,
enums::BankRedirectType::OnlineBankingFpx => Self::OnlineBankingFpx,
enums::BankRedirectType::OnlineBankingThailand => Self::OnlineBankingThailand,
enums::BankRedirectType::OpenBankingUk => Self::OpenBankingUk,
enums::BankRedirectType::Przelewy24 => Self::Przelewy24,
enums::BankRedirectType::Trustly => Self::Trustly,
enums::BankRedirectType::OpenBanking => Self::OpenBanking,
}
}
}
impl From<enums::OpenBankingType> for global_enums::PaymentMethodType {
fn from(value: enums::OpenBankingType) -> Self {
match value {
enums::OpenBankingType::OpenBankingPIS => Self::OpenBankingPIS,
}
}
}
impl From<enums::CryptoType> for global_enums::PaymentMethodType {
fn from(value: enums::CryptoType) -> Self {
match value {
enums::CryptoType::CryptoCurrency => Self::CryptoCurrency,
}
}
}
impl From<enums::RewardType> for global_enums::PaymentMethodType {
fn from(value: enums::RewardType) -> Self {
match value {
enums::RewardType::ClassicReward => Self::ClassicReward,
enums::RewardType::Evoucher => Self::Evoucher,
}
}
}
impl From<enums::RealTimePaymentType> for global_enums::PaymentMethodType {
fn from(value: enums::RealTimePaymentType) -> Self {
match value {
enums::RealTimePaymentType::Fps => Self::Fps,
enums::RealTimePaymentType::DuitNow => Self::DuitNow,
enums::RealTimePaymentType::PromptPay => Self::PromptPay,
enums::RealTimePaymentType::VietQr => Self::VietQr,
}
}
}
/// Analyses of the lowering of the DirValues to EuclidValues .
///
/// For example,
/// ```notrust
/// DirValue::PaymentMethod::Cards -> EuclidValue::PaymentMethod::Cards
/// ```notrust
/// This is a function that lowers the Values of the DIR variants into the Value of the VIR variants.
/// The function for each DirValue variant creates a corresponding EuclidValue variants and if there
/// lacks any direct mapping, it return an Error.
fn lower_value(dir_value: dir::DirValue) -> Result<EuclidValue, AnalysisErrorType> {
Ok(match dir_value {
dir::DirValue::PaymentMethod(pm) => EuclidValue::PaymentMethod(pm),
dir::DirValue::CardBin(ci) => EuclidValue::CardBin(ci),
dir::DirValue::ExtendedCardBin(ecb) => EuclidValue::ExtendedCardBin(ecb),
dir::DirValue::CardType(ct) => EuclidValue::PaymentMethodType(ct.into()),
dir::DirValue::CardNetwork(cn) => EuclidValue::CardNetwork(cn),
dir::DirValue::MetaData(md) => EuclidValue::Metadata(md),
dir::DirValue::PayLaterType(plt) => EuclidValue::PaymentMethodType(plt.into()),
dir::DirValue::WalletType(wt) => EuclidValue::PaymentMethodType(wt.into()),
dir::DirValue::UpiType(ut) => EuclidValue::PaymentMethodType(ut.into()),
dir::DirValue::VoucherType(vt) => EuclidValue::PaymentMethodType(vt.into()),
dir::DirValue::BankTransferType(btt) => EuclidValue::PaymentMethodType(btt.into()),
dir::DirValue::GiftCardType(gct) => EuclidValue::PaymentMethodType(gct.into()),
dir::DirValue::CardRedirectType(crt) => EuclidValue::PaymentMethodType(crt.into()),
dir::DirValue::BankRedirectType(brt) => EuclidValue::PaymentMethodType(brt.into()),
dir::DirValue::CryptoType(ct) => EuclidValue::PaymentMethodType(ct.into()),
dir::DirValue::RealTimePaymentType(rtpt) => EuclidValue::PaymentMethodType(rtpt.into()),
dir::DirValue::AuthenticationType(at) => EuclidValue::AuthenticationType(at),
dir::DirValue::CaptureMethod(cm) => EuclidValue::CaptureMethod(cm),
dir::DirValue::PaymentAmount(pa) => EuclidValue::PaymentAmount(pa),
dir::DirValue::PaymentCurrency(pc) => EuclidValue::PaymentCurrency(pc),
dir::DirValue::BusinessCountry(buc) => EuclidValue::BusinessCountry(buc),
dir::DirValue::BillingCountry(bic) => EuclidValue::BillingCountry(bic),
dir::DirValue::MandateAcceptanceType(mat) => EuclidValue::MandateAcceptanceType(mat),
dir::DirValue::MandateType(mt) => EuclidValue::MandateType(mt),
dir::DirValue::PaymentType(pt) => EuclidValue::PaymentType(pt),
dir::DirValue::Connector(_) => Err(AnalysisErrorType::UnsupportedProgramKey(
dir::DirKeyKind::Connector,
))?,
dir::DirValue::BankDebitType(bdt) => EuclidValue::PaymentMethodType(bdt.into()),
dir::DirValue::RewardType(rt) => EuclidValue::PaymentMethodType(rt.into()),
dir::DirValue::BusinessLabel(bl) => EuclidValue::BusinessLabel(bl),
dir::DirValue::SetupFutureUsage(sfu) => EuclidValue::SetupFutureUsage(sfu),
dir::DirValue::OpenBankingType(ob) => EuclidValue::PaymentMethodType(ob.into()),
dir::DirValue::MobilePaymentType(mp) => EuclidValue::PaymentMethodType(mp.into()),
dir::DirValue::IssuerName(str_value) => EuclidValue::IssuerName(str_value),
dir::DirValue::IssuerCountry(country) => EuclidValue::IssuerCountry(country),
dir::DirValue::CustomerDevicePlatform(customer_device_platform) => {
EuclidValue::CustomerDevicePlatform(customer_device_platform)
}
dir::DirValue::CustomerDeviceType(customer_device_type) => {
EuclidValue::CustomerDeviceType(customer_device_type)
}
dir::DirValue::CustomerDeviceDisplaySize(customer_device_display_size) => {
EuclidValue::CustomerDeviceDisplaySize(customer_device_display_size)
}
dir::DirValue::AcquirerCountry(country) => EuclidValue::AcquirerCountry(country),
dir::DirValue::AcquirerFraudRate(num_value) => EuclidValue::AcquirerFraudRate(num_value),
dir::DirValue::TransactionInitiator(ti) => EuclidValue::TransactionInitiator(ti),
dir::DirValue::NetworkTokenType(nt) => EuclidValue::PaymentMethodType(nt.into()),
})
}
fn lower_comparison(
dir_comparison: dir::DirComparison,
) -> Result<vir::ValuedComparison, AnalysisErrorType> {
Ok(vir::ValuedComparison {
values: dir_comparison
.values
.into_iter()
.map(lower_value)
.collect::<Result<_, _>>()?,
logic: match dir_comparison.logic {
dir::DirComparisonLogic::NegativeConjunction => {
vir::ValuedComparisonLogic::NegativeConjunction
}
dir::DirComparisonLogic::PositiveDisjunction => {
vir::ValuedComparisonLogic::PositiveDisjunction
}
},
metadata: dir_comparison.metadata,
})
}
fn lower_if_statement(
dir_if_statement: dir::DirIfStatement,
) -> Result<vir::ValuedIfStatement, AnalysisErrorType> {
Ok(vir::ValuedIfStatement {
condition: dir_if_statement
.condition
.into_iter()
.map(lower_comparison)
.collect::<Result<_, _>>()?,
nested: dir_if_statement
.nested
.map(|v| {
v.into_iter()
.map(lower_if_statement)
.collect::<Result<_, _>>()
})
.transpose()?,
})
}
fn lower_rule<O>(dir_rule: dir::DirRule<O>) -> Result<vir::ValuedRule<O>, AnalysisErrorType> {
Ok(vir::ValuedRule {
name: dir_rule.name,
connector_selection: dir_rule.connector_selection,
statements: dir_rule
.statements
.into_iter()
.map(lower_if_statement)
.collect::<Result<_, _>>()?,
})
}
pub fn lower_program<O>(
dir_program: dir::DirProgram<O>,
) -> Result<vir::ValuedProgram<O>, AnalysisError> {
Ok(vir::ValuedProgram {
default_selection: dir_program.default_selection,
rules: dir_program
.rules
.into_iter()
.map(lower_rule)
.collect::<Result<_, _>>()
.map_err(|e| AnalysisError {
error_type: e,
metadata: Default::default(),
})?,
metadata: dir_program.metadata,
})
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/src/frontend/dir/transformers.rs | crates/euclid/src/frontend/dir/transformers.rs | use crate::{dirval, dssa::types::AnalysisErrorType, enums as global_enums, frontend::dir};
pub trait IntoDirValue {
fn into_dir_value(self) -> Result<dir::DirValue, AnalysisErrorType>;
}
impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMethod) {
fn into_dir_value(self) -> Result<dir::DirValue, AnalysisErrorType> {
match self.0 {
global_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)),
global_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)),
#[cfg(feature = "v2")]
global_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)),
global_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)),
global_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)),
global_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)),
global_enums::PaymentMethodType::DuitNow => Ok(dirval!(RealTimePaymentType = DuitNow)),
global_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)),
global_enums::PaymentMethodType::Fps => Ok(dirval!(RealTimePaymentType = Fps)),
global_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)),
global_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)),
global_enums::PaymentMethodType::Payjustnow => Ok(dirval!(PayLaterType = Payjustnow)),
global_enums::PaymentMethodType::AfterpayClearpay => {
Ok(dirval!(PayLaterType = AfterpayClearpay))
}
global_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)),
global_enums::PaymentMethodType::Skrill => Ok(dirval!(WalletType = Skrill)),
global_enums::PaymentMethodType::Paysera => Ok(dirval!(WalletType = Paysera)),
global_enums::PaymentMethodType::GooglePay => Ok(dirval!(WalletType = GooglePay)),
global_enums::PaymentMethodType::Bluecode => Ok(dirval!(WalletType = Bluecode)),
global_enums::PaymentMethodType::ApplePay => Ok(dirval!(WalletType = ApplePay)),
global_enums::PaymentMethodType::Paypal => Ok(dirval!(WalletType = Paypal)),
global_enums::PaymentMethodType::RevolutPay => Ok(dirval!(WalletType = RevolutPay)),
global_enums::PaymentMethodType::CryptoCurrency => {
Ok(dirval!(CryptoType = CryptoCurrency))
}
global_enums::PaymentMethodType::Ach => match self.1 {
global_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Ach)),
global_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Ach)),
global_enums::PaymentMethod::PayLater
| global_enums::PaymentMethod::Card
| global_enums::PaymentMethod::CardRedirect
| global_enums::PaymentMethod::Wallet
| global_enums::PaymentMethod::BankRedirect
| global_enums::PaymentMethod::Crypto
| global_enums::PaymentMethod::Reward
| global_enums::PaymentMethod::RealTimePayment
| global_enums::PaymentMethod::Upi
| global_enums::PaymentMethod::Voucher
| global_enums::PaymentMethod::OpenBanking
| global_enums::PaymentMethod::MobilePayment
| global_enums::PaymentMethod::GiftCard
| global_enums::PaymentMethod::NetworkToken => Err(AnalysisErrorType::NotSupported),
},
global_enums::PaymentMethodType::Bacs => match self.1 {
global_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Bacs)),
global_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Bacs)),
global_enums::PaymentMethod::PayLater
| global_enums::PaymentMethod::Card
| global_enums::PaymentMethod::CardRedirect
| global_enums::PaymentMethod::Wallet
| global_enums::PaymentMethod::BankRedirect
| global_enums::PaymentMethod::Crypto
| global_enums::PaymentMethod::Reward
| global_enums::PaymentMethod::RealTimePayment
| global_enums::PaymentMethod::Upi
| global_enums::PaymentMethod::Voucher
| global_enums::PaymentMethod::OpenBanking
| global_enums::PaymentMethod::MobilePayment
| global_enums::PaymentMethod::GiftCard
| global_enums::PaymentMethod::NetworkToken => Err(AnalysisErrorType::NotSupported),
},
global_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)),
global_enums::PaymentMethodType::Sepa => Ok(dirval!(BankDebitType = Sepa)),
global_enums::PaymentMethodType::SepaGuarenteedDebit => {
Ok(dirval!(BankDebitType = SepaGuarenteedDebit))
}
global_enums::PaymentMethodType::SepaBankTransfer => {
Ok(dirval!(BankTransferType = SepaBankTransfer))
}
global_enums::PaymentMethodType::AliPay => Ok(dirval!(WalletType = AliPay)),
global_enums::PaymentMethodType::AliPayHk => Ok(dirval!(WalletType = AliPayHk)),
global_enums::PaymentMethodType::BancontactCard => {
Ok(dirval!(BankRedirectType = BancontactCard))
}
global_enums::PaymentMethodType::Blik => Ok(dirval!(BankRedirectType = Blik)),
global_enums::PaymentMethodType::MbWay => Ok(dirval!(WalletType = MbWay)),
global_enums::PaymentMethodType::MobilePay => Ok(dirval!(WalletType = MobilePay)),
global_enums::PaymentMethodType::Cashapp => Ok(dirval!(WalletType = Cashapp)),
global_enums::PaymentMethodType::Multibanco => {
Ok(dirval!(BankTransferType = Multibanco))
}
global_enums::PaymentMethodType::Pix => Ok(dirval!(BankTransferType = Pix)),
global_enums::PaymentMethodType::Pse => Ok(dirval!(BankTransferType = Pse)),
global_enums::PaymentMethodType::Interac => Ok(dirval!(BankRedirectType = Interac)),
global_enums::PaymentMethodType::OnlineBankingCzechRepublic => {
Ok(dirval!(BankRedirectType = OnlineBankingCzechRepublic))
}
global_enums::PaymentMethodType::OnlineBankingFinland => {
Ok(dirval!(BankRedirectType = OnlineBankingFinland))
}
global_enums::PaymentMethodType::OnlineBankingPoland => {
Ok(dirval!(BankRedirectType = OnlineBankingPoland))
}
global_enums::PaymentMethodType::OnlineBankingSlovakia => {
Ok(dirval!(BankRedirectType = OnlineBankingSlovakia))
}
global_enums::PaymentMethodType::Swish => Ok(dirval!(WalletType = Swish)),
global_enums::PaymentMethodType::Trustly => Ok(dirval!(BankRedirectType = Trustly)),
global_enums::PaymentMethodType::Bizum => Ok(dirval!(BankRedirectType = Bizum)),
global_enums::PaymentMethodType::PayBright => Ok(dirval!(PayLaterType = PayBright)),
global_enums::PaymentMethodType::Flexiti => Ok(dirval!(PayLaterType = Flexiti)),
global_enums::PaymentMethodType::Walley => Ok(dirval!(PayLaterType = Walley)),
global_enums::PaymentMethodType::Breadpay => Ok(dirval!(PayLaterType = Breadpay)),
global_enums::PaymentMethodType::Przelewy24 => {
Ok(dirval!(BankRedirectType = Przelewy24))
}
global_enums::PaymentMethodType::PromptPay => {
Ok(dirval!(RealTimePaymentType = PromptPay))
}
global_enums::PaymentMethodType::WeChatPay => Ok(dirval!(WalletType = WeChatPay)),
global_enums::PaymentMethodType::ClassicReward => {
Ok(dirval!(RewardType = ClassicReward))
}
global_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)),
global_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)),
global_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)),
global_enums::PaymentMethodType::UpiQr => Ok(dirval!(UpiType = UpiQr)),
global_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)),
global_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)),
global_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)),
global_enums::PaymentMethodType::Twint => Ok(dirval!(WalletType = Twint)),
global_enums::PaymentMethodType::Gcash => Ok(dirval!(WalletType = Gcash)),
global_enums::PaymentMethodType::Vipps => Ok(dirval!(WalletType = Vipps)),
global_enums::PaymentMethodType::VietQr => Ok(dirval!(RealTimePaymentType = VietQr)),
global_enums::PaymentMethodType::Momo => Ok(dirval!(WalletType = Momo)),
global_enums::PaymentMethodType::Alma => Ok(dirval!(PayLaterType = Alma)),
global_enums::PaymentMethodType::Dana => Ok(dirval!(WalletType = Dana)),
global_enums::PaymentMethodType::OnlineBankingFpx => {
Ok(dirval!(BankRedirectType = OnlineBankingFpx))
}
global_enums::PaymentMethodType::LocalBankRedirect => {
Ok(dirval!(BankRedirectType = LocalBankRedirect))
}
global_enums::PaymentMethodType::OnlineBankingThailand => {
Ok(dirval!(BankRedirectType = OnlineBankingThailand))
}
global_enums::PaymentMethodType::TouchNGo => Ok(dirval!(WalletType = TouchNGo)),
global_enums::PaymentMethodType::Atome => Ok(dirval!(PayLaterType = Atome)),
global_enums::PaymentMethodType::Boleto => Ok(dirval!(VoucherType = Boleto)),
global_enums::PaymentMethodType::Efecty => Ok(dirval!(VoucherType = Efecty)),
global_enums::PaymentMethodType::PagoEfectivo => {
Ok(dirval!(VoucherType = PagoEfectivo))
}
global_enums::PaymentMethodType::RedCompra => Ok(dirval!(VoucherType = RedCompra)),
global_enums::PaymentMethodType::RedPagos => Ok(dirval!(VoucherType = RedPagos)),
global_enums::PaymentMethodType::Alfamart => Ok(dirval!(VoucherType = Alfamart)),
global_enums::PaymentMethodType::BcaBankTransfer => {
Ok(dirval!(BankTransferType = BcaBankTransfer))
}
global_enums::PaymentMethodType::BniVa => Ok(dirval!(BankTransferType = BniVa)),
global_enums::PaymentMethodType::BriVa => Ok(dirval!(BankTransferType = BriVa)),
global_enums::PaymentMethodType::CimbVa => Ok(dirval!(BankTransferType = CimbVa)),
global_enums::PaymentMethodType::DanamonVa => Ok(dirval!(BankTransferType = DanamonVa)),
global_enums::PaymentMethodType::Indomaret => Ok(dirval!(VoucherType = Indomaret)),
global_enums::PaymentMethodType::MandiriVa => Ok(dirval!(BankTransferType = MandiriVa)),
global_enums::PaymentMethodType::LocalBankTransfer => {
Ok(dirval!(BankTransferType = LocalBankTransfer))
}
global_enums::PaymentMethodType::InstantBankTransfer => {
Ok(dirval!(BankTransferType = InstantBankTransfer))
}
global_enums::PaymentMethodType::InstantBankTransferFinland => {
Ok(dirval!(BankTransferType = InstantBankTransferFinland))
}
global_enums::PaymentMethodType::InstantBankTransferPoland => {
Ok(dirval!(BankTransferType = InstantBankTransferPoland))
}
global_enums::PaymentMethodType::PermataBankTransfer => {
Ok(dirval!(BankTransferType = PermataBankTransfer))
}
global_enums::PaymentMethodType::PaySafeCard => Ok(dirval!(GiftCardType = PaySafeCard)),
global_enums::PaymentMethodType::SevenEleven => Ok(dirval!(VoucherType = SevenEleven)),
global_enums::PaymentMethodType::Lawson => Ok(dirval!(VoucherType = Lawson)),
global_enums::PaymentMethodType::MiniStop => Ok(dirval!(VoucherType = MiniStop)),
global_enums::PaymentMethodType::FamilyMart => Ok(dirval!(VoucherType = FamilyMart)),
global_enums::PaymentMethodType::Seicomart => Ok(dirval!(VoucherType = Seicomart)),
global_enums::PaymentMethodType::PayEasy => Ok(dirval!(VoucherType = PayEasy)),
global_enums::PaymentMethodType::Givex => Ok(dirval!(GiftCardType = Givex)),
global_enums::PaymentMethodType::Benefit => Ok(dirval!(CardRedirectType = Benefit)),
global_enums::PaymentMethodType::Knet => Ok(dirval!(CardRedirectType = Knet)),
global_enums::PaymentMethodType::OpenBankingUk => {
Ok(dirval!(BankRedirectType = OpenBankingUk))
}
global_enums::PaymentMethodType::MomoAtm => Ok(dirval!(CardRedirectType = MomoAtm)),
global_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)),
global_enums::PaymentMethodType::CardRedirect => {
Ok(dirval!(CardRedirectType = CardRedirect))
}
global_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)),
global_enums::PaymentMethodType::Mifinity => Ok(dirval!(WalletType = Mifinity)),
global_enums::PaymentMethodType::OpenBankingPIS => {
Ok(dirval!(OpenBankingType = OpenBankingPIS))
}
global_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)),
global_enums::PaymentMethodType::DirectCarrierBilling => {
Ok(dirval!(MobilePaymentType = DirectCarrierBilling))
}
global_enums::PaymentMethodType::Eft => Ok(dirval!(BankRedirectType = Eft)),
global_enums::PaymentMethodType::IndonesianBankTransfer => {
Ok(dirval!(BankTransferType = IndonesianBankTransfer))
}
global_enums::PaymentMethodType::BhnCardNetwork => {
Ok(dirval!(GiftCardType = BhnCardNetwork))
}
global_enums::PaymentMethodType::OpenBanking => {
Ok(dirval!(BankRedirectType = OpenBanking))
}
global_enums::PaymentMethodType::NetworkToken => {
Ok(dirval!(NetworkTokenType = NetworkToken))
}
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid/benches/backends.rs | crates/euclid/benches/backends.rs | #![allow(unused, clippy::expect_used)]
use common_utils::types::MinorUnit;
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use euclid::{
backend::{inputs, EuclidBackend, InterpreterBackend, VirInterpreterBackend},
enums,
frontend::ast::{self, parser},
types::DummyOutput,
};
fn get_program_data() -> (ast::Program<DummyOutput>, inputs::BackendInput) {
let code1 = r#"
default: ["stripe", "adyen", "checkout"]
stripe_first: ["stripe", "aci"]
{
payment_method = card & amount = 40 {
payment_method = (card, bank_redirect)
amount = (40, 50)
}
}
adyen_first: ["adyen", "checkout"]
{
payment_method = bank_redirect & amount > 60 {
payment_method = (card, bank_redirect)
amount = (40, 50)
}
}
auth_first: ["authorizedotnet", "adyen"]
{
payment_method = wallet
}
"#;
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(32),
transaction_initiator: None,
card_bin: None,
extended_card_bin: None,
currency: enums::Currency::USD,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Sofort),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
issuer_data: None,
acquirer_data: None,
customer_device_data: None,
};
let (_, program) = parser::program(code1).expect("Parser");
(program, inp)
}
fn interpreter_vs_jit_vs_vir_interpreter(c: &mut Criterion) {
let (program, binputs) = get_program_data();
let interp_b = InterpreterBackend::with_program(program.clone()).expect("Interpreter backend");
let vir_interp_b =
VirInterpreterBackend::with_program(program).expect("Vir Interpreter Backend");
c.bench_function("Raw Interpreter Backend", |b| {
b.iter(|| {
interp_b
.execute(binputs.clone())
.expect("Interpreter EXECUTION");
});
});
c.bench_function("Valued Interpreter Backend", |b| {
b.iter(|| {
vir_interp_b
.execute(binputs.clone())
.expect("Vir Interpreter execution");
})
});
}
criterion_group!(benches, interpreter_vs_jit_vs_vir_interpreter);
criterion_main!(benches);
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hsdev/src/main.rs | crates/hsdev/src/main.rs | #![allow(clippy::print_stdout, clippy::print_stderr)]
use clap::{Parser, ValueHint};
use diesel::{pg::PgConnection, Connection};
use diesel_migrations::{FileBasedMigrations, HarnessWithOutput, MigrationHarness};
use toml::Value;
mod input_file;
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
#[arg(short, long, value_hint = ValueHint::FilePath)]
toml_file: std::path::PathBuf,
#[arg(long, default_value_t = String::from(""))]
toml_table: String,
}
fn main() {
let args = Args::parse();
let toml_file = &args.toml_file;
let table_name = &args.toml_table;
let toml_contents = match std::fs::read_to_string(toml_file) {
Ok(contents) => contents,
Err(e) => {
eprintln!("Error reading TOML file: {e}");
return;
}
};
let toml_data: Value = match toml_contents.parse() {
Ok(data) => data,
Err(e) => {
eprintln!("Error parsing TOML file: {e}");
return;
}
};
let table = get_toml_table(table_name, &toml_data);
let input = match input_file::InputData::read(table) {
Ok(data) => data,
Err(e) => {
eprintln!("Error loading TOML file: {e}");
return;
}
};
let db_url = input.postgres_url();
println!("Attempting to connect to {db_url}");
let mut conn = match PgConnection::establish(&db_url) {
Ok(value) => value,
Err(_) => {
eprintln!("Unable to establish database connection");
return;
}
};
let migrations = match FileBasedMigrations::find_migrations_directory() {
Ok(value) => value,
Err(_) => {
eprintln!("Could not find migrations directory");
return;
}
};
let mut harness = HarnessWithOutput::write_to_stdout(&mut conn);
match harness.run_pending_migrations(migrations) {
Ok(_) => println!("Successfully ran migrations"),
Err(_) => eprintln!("Couldn't run migrations"),
};
}
pub fn get_toml_table<'a>(table_name: &'a str, toml_data: &'a Value) -> &'a Value {
if !table_name.is_empty() {
match toml_data.get(table_name) {
Some(value) => value,
None => {
eprintln!("Unable to find toml table: \"{}\"", &table_name);
std::process::abort()
}
}
} else {
toml_data
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use toml::Value;
use crate::{get_toml_table, input_file::InputData};
#[test]
fn test_input_file() {
let toml_str = r#"username = "db_user"
password = "db_pass"
dbname = "db_name"
host = "localhost"
port = 5432"#;
let toml_value = Value::from_str(toml_str);
assert!(toml_value.is_ok());
let toml_value = toml_value.unwrap();
let toml_table = InputData::read(&toml_value);
assert!(toml_table.is_ok());
let toml_table = toml_table.unwrap();
let db_url = toml_table.postgres_url();
assert_eq!("postgres://db_user:db_pass@localhost:5432/db_name", db_url);
}
#[test]
fn test_given_toml() {
let toml_str_table = r#"[database]
username = "db_user"
password = "db_pass"
dbname = "db_name"
host = "localhost"
port = 5432"#;
let table_name = "database";
let toml_value = Value::from_str(toml_str_table).unwrap();
let table = get_toml_table(table_name, &toml_value);
assert!(table.is_table());
let table_name = "";
let table = get_toml_table(table_name, &toml_value);
assert!(table.is_table());
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hsdev/src/input_file.rs | crates/hsdev/src/input_file.rs | use std::string::String;
use serde::Deserialize;
use toml::Value;
#[derive(Deserialize)]
pub struct InputData {
username: String,
password: String,
dbname: String,
host: String,
port: u16,
}
impl InputData {
pub fn read(db_table: &Value) -> Result<Self, toml::de::Error> {
db_table.clone().try_into()
}
pub fn postgres_url(&self) -> String {
format!(
"postgres://{}:{}@{}:{}/{}",
self.username, self.password, self.host, self.port, self.dbname
)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/errors.rs | crates/hyperswitch_domain_models/src/errors.rs | pub mod api_error_response;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/consts.rs | crates/hyperswitch_domain_models/src/consts.rs | //! Constants that are used in the domain models.
use std::{collections::HashSet, sync::LazyLock};
pub static ROUTING_ENABLED_PAYMENT_METHODS: LazyLock<HashSet<common_enums::PaymentMethod>> =
LazyLock::new(|| {
let mut set = HashSet::new();
set.insert(common_enums::PaymentMethod::BankTransfer);
set.insert(common_enums::PaymentMethod::BankDebit);
set.insert(common_enums::PaymentMethod::BankRedirect);
set
});
pub static ROUTING_ENABLED_PAYMENT_METHOD_TYPES: LazyLock<
HashSet<common_enums::PaymentMethodType>,
> = LazyLock::new(|| {
let mut set = HashSet::new();
set.insert(common_enums::PaymentMethodType::GooglePay);
set.insert(common_enums::PaymentMethodType::ApplePay);
set.insert(common_enums::PaymentMethodType::Klarna);
set.insert(common_enums::PaymentMethodType::Paypal);
set.insert(common_enums::PaymentMethodType::SamsungPay);
set
});
/// Length of the unique reference ID generated for connector mandate requests
pub const CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH: usize = 18;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/mandates.rs | crates/hyperswitch_domain_models/src/mandates.rs | use std::collections::HashMap;
use api_models::payments::{
MandateAmountData as ApiMandateAmountData, MandateData as ApiMandateData, MandateType,
};
use common_enums::Currency;
use common_types::payments as common_payments_types;
use common_utils::{
date_time,
errors::{CustomResult, ParsingError},
pii,
types::MinorUnit,
};
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use crate::router_data::RecurringMandatePaymentData;
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct MandateDetails {
pub update_mandate_id: Option<String>,
}
impl From<MandateDetails> for diesel_models::enums::MandateDetails {
fn from(value: MandateDetails) -> Self {
Self {
update_mandate_id: value.update_mandate_id,
}
}
}
impl From<diesel_models::enums::MandateDetails> for MandateDetails {
fn from(value: diesel_models::enums::MandateDetails) -> Self {
Self {
update_mandate_id: value.update_mandate_id,
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MandateDataType {
SingleUse(MandateAmountData),
MultiUse(Option<MandateAmountData>),
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct MandateAmountData {
pub amount: MinorUnit,
pub currency: Currency,
pub start_date: Option<PrimitiveDateTime>,
pub end_date: Option<PrimitiveDateTime>,
pub metadata: Option<pii::SecretSerdeValue>,
}
// The fields on this struct are optional, as we want to allow the merchant to provide partial
// information about creating mandates
#[derive(Default, Eq, PartialEq, Debug, Clone, serde::Serialize)]
pub struct MandateData {
/// A way to update the mandate's payment method details
pub update_mandate_id: Option<String>,
/// A consent from the customer to store the payment method
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
/// A way to select the type of mandate used
pub mandate_type: Option<MandateDataType>,
}
impl From<MandateType> for MandateDataType {
fn from(mandate_type: MandateType) -> Self {
match mandate_type {
MandateType::SingleUse(mandate_amount_data) => {
Self::SingleUse(mandate_amount_data.into())
}
MandateType::MultiUse(mandate_amount_data) => {
Self::MultiUse(mandate_amount_data.map(|d| d.into()))
}
}
}
}
impl From<MandateDataType> for diesel_models::enums::MandateDataType {
fn from(value: MandateDataType) -> Self {
match value {
MandateDataType::SingleUse(data) => Self::SingleUse(data.into()),
MandateDataType::MultiUse(None) => Self::MultiUse(None),
MandateDataType::MultiUse(Some(data)) => Self::MultiUse(Some(data.into())),
}
}
}
impl From<diesel_models::enums::MandateDataType> for MandateDataType {
fn from(value: diesel_models::enums::MandateDataType) -> Self {
use diesel_models::enums::MandateDataType as DieselMandateDataType;
match value {
DieselMandateDataType::SingleUse(data) => Self::SingleUse(data.into()),
DieselMandateDataType::MultiUse(None) => Self::MultiUse(None),
DieselMandateDataType::MultiUse(Some(data)) => Self::MultiUse(Some(data.into())),
}
}
}
impl From<ApiMandateAmountData> for MandateAmountData {
fn from(value: ApiMandateAmountData) -> Self {
Self {
amount: value.amount,
currency: value.currency,
start_date: value.start_date,
end_date: value.end_date,
metadata: value.metadata,
}
}
}
impl From<MandateAmountData> for diesel_models::enums::MandateAmountData {
fn from(value: MandateAmountData) -> Self {
Self {
amount: value.amount,
currency: value.currency,
start_date: value.start_date,
end_date: value.end_date,
metadata: value.metadata,
}
}
}
impl From<diesel_models::enums::MandateAmountData> for MandateAmountData {
fn from(value: diesel_models::enums::MandateAmountData) -> Self {
Self {
amount: value.amount,
currency: value.currency,
start_date: value.start_date,
end_date: value.end_date,
metadata: value.metadata,
}
}
}
impl From<ApiMandateData> for MandateData {
fn from(value: ApiMandateData) -> Self {
Self {
customer_acceptance: value.customer_acceptance,
mandate_type: value.mandate_type.map(|d| d.into()),
update_mandate_id: value.update_mandate_id,
}
}
}
impl MandateAmountData {
pub fn get_end_date(
&self,
format: date_time::DateFormat,
) -> error_stack::Result<Option<String>, ParsingError> {
self.end_date
.map(|date| {
date_time::format_date(date, format)
.change_context(ParsingError::DateTimeParsingError)
})
.transpose()
}
pub fn get_metadata(&self) -> Option<pii::SecretSerdeValue> {
self.metadata.clone()
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentsMandateReferenceRecord {
pub connector_mandate_id: String,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub original_payment_authorized_amount: Option<i64>,
pub original_payment_authorized_currency: Option<Currency>,
pub mandate_metadata: Option<pii::SecretSerdeValue>,
pub connector_mandate_status: Option<common_enums::ConnectorMandateStatus>,
pub connector_mandate_request_reference_id: Option<String>,
pub connector_customer_id: Option<String>,
}
#[cfg(feature = "v1")]
impl From<&PaymentsMandateReferenceRecord> for RecurringMandatePaymentData {
fn from(mandate_reference_record: &PaymentsMandateReferenceRecord) -> Self {
Self {
payment_method_type: mandate_reference_record.payment_method_type,
original_payment_authorized_amount: mandate_reference_record
.original_payment_authorized_amount,
original_payment_authorized_currency: mandate_reference_record
.original_payment_authorized_currency,
mandate_metadata: mandate_reference_record.mandate_metadata.clone(),
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConnectorTokenReferenceRecord {
pub connector_token: String,
pub payment_method_subtype: Option<common_enums::PaymentMethodType>,
pub original_payment_authorized_amount: Option<MinorUnit>,
pub original_payment_authorized_currency: Option<Currency>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_token_status: common_enums::ConnectorTokenStatus,
pub connector_token_request_reference_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PayoutsMandateReferenceRecord {
pub transfer_method_id: Option<String>,
pub connector_customer_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PayoutsMandateReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>,
);
impl std::ops::Deref for PayoutsMandateReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for PayoutsMandateReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentsTokenReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>,
);
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentsMandateReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>,
);
#[cfg(feature = "v1")]
impl PaymentsMandateReference {
pub fn is_active_connector_mandate_available(&self) -> bool {
self.clone().0.into_iter().any(|detail| {
detail
.1
.connector_mandate_status
.map(|connector_mandate_status| connector_mandate_status.is_active())
.unwrap_or(false)
})
}
}
#[cfg(feature = "v1")]
impl std::ops::Deref for PaymentsMandateReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "v1")]
impl std::ops::DerefMut for PaymentsMandateReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v2")]
impl std::ops::Deref for PaymentsTokenReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "v2")]
impl std::ops::DerefMut for PaymentsTokenReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CommonMandateReference {
pub payments: Option<PaymentsMandateReference>,
pub payouts: Option<PayoutsMandateReference>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CommonMandateReference {
pub payments: Option<PaymentsTokenReference>,
pub payouts: Option<PayoutsMandateReference>,
}
impl CommonMandateReference {
pub fn get_mandate_details_value(&self) -> CustomResult<serde_json::Value, ParsingError> {
let mut payments = self
.payments
.as_ref()
.map_or_else(|| Ok(serde_json::json!({})), serde_json::to_value)
.change_context(ParsingError::StructParseFailure("payment mandate details"))?;
self.payouts
.as_ref()
.map(|payouts_mandate| {
serde_json::to_value(payouts_mandate).map(|payouts_mandate_value| {
payments.as_object_mut().map(|payments_object| {
payments_object.insert("payouts".to_string(), payouts_mandate_value);
})
})
})
.transpose()
.change_context(ParsingError::StructParseFailure("payout mandate details"))?;
Ok(payments)
}
#[cfg(feature = "v2")]
/// Insert a new payment token reference for the given connector_id
pub fn insert_payment_token_reference_record(
&mut self,
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
record: ConnectorTokenReferenceRecord,
) {
match self.payments {
Some(ref mut payments_reference) => {
payments_reference.insert(connector_id.clone(), record);
}
None => {
let mut payments_reference = HashMap::new();
payments_reference.insert(connector_id.clone(), record);
self.payments = Some(PaymentsTokenReference(payments_reference));
}
}
}
}
impl From<diesel_models::CommonMandateReference> for CommonMandateReference {
fn from(value: diesel_models::CommonMandateReference) -> Self {
Self {
payments: value.payments.map(|payments| payments.into()),
payouts: value.payouts.map(|payouts| payouts.into()),
}
}
}
impl From<CommonMandateReference> for diesel_models::CommonMandateReference {
fn from(value: CommonMandateReference) -> Self {
Self {
payments: value.payments.map(|payments| payments.into()),
payouts: value.payouts.map(|payouts| payouts.into()),
}
}
}
impl From<diesel_models::PayoutsMandateReference> for PayoutsMandateReference {
fn from(value: diesel_models::PayoutsMandateReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
impl From<PayoutsMandateReference> for diesel_models::PayoutsMandateReference {
fn from(value: PayoutsMandateReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
#[cfg(feature = "v1")]
impl From<diesel_models::PaymentsMandateReference> for PaymentsMandateReference {
fn from(value: diesel_models::PaymentsMandateReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
#[cfg(feature = "v1")]
impl From<PaymentsMandateReference> for diesel_models::PaymentsMandateReference {
fn from(value: PaymentsMandateReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
#[cfg(feature = "v2")]
impl From<diesel_models::PaymentsTokenReference> for PaymentsTokenReference {
fn from(value: diesel_models::PaymentsTokenReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
#[cfg(feature = "v2")]
impl From<PaymentsTokenReference> for diesel_models::PaymentsTokenReference {
fn from(value: PaymentsTokenReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
impl From<diesel_models::PayoutsMandateReferenceRecord> for PayoutsMandateReferenceRecord {
fn from(value: diesel_models::PayoutsMandateReferenceRecord) -> Self {
Self {
transfer_method_id: value.transfer_method_id,
connector_customer_id: value.connector_customer_id,
}
}
}
impl From<PayoutsMandateReferenceRecord> for diesel_models::PayoutsMandateReferenceRecord {
fn from(value: PayoutsMandateReferenceRecord) -> Self {
Self {
transfer_method_id: value.transfer_method_id,
connector_customer_id: value.connector_customer_id,
}
}
}
#[cfg(feature = "v2")]
impl From<diesel_models::ConnectorTokenReferenceRecord> for ConnectorTokenReferenceRecord {
fn from(value: diesel_models::ConnectorTokenReferenceRecord) -> Self {
let diesel_models::ConnectorTokenReferenceRecord {
connector_token,
payment_method_subtype,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
connector_token_status,
connector_token_request_reference_id,
} = value;
Self {
connector_token,
payment_method_subtype,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
connector_token_status,
connector_token_request_reference_id,
}
}
}
#[cfg(feature = "v1")]
impl From<diesel_models::PaymentsMandateReferenceRecord> for PaymentsMandateReferenceRecord {
fn from(value: diesel_models::PaymentsMandateReferenceRecord) -> Self {
Self {
connector_mandate_id: value.connector_mandate_id,
payment_method_type: value.payment_method_type,
original_payment_authorized_amount: value.original_payment_authorized_amount,
original_payment_authorized_currency: value.original_payment_authorized_currency,
mandate_metadata: value.mandate_metadata,
connector_mandate_status: value.connector_mandate_status,
connector_mandate_request_reference_id: value.connector_mandate_request_reference_id,
connector_customer_id: value.connector_customer_id,
}
}
}
#[cfg(feature = "v2")]
impl From<ConnectorTokenReferenceRecord> for diesel_models::ConnectorTokenReferenceRecord {
fn from(value: ConnectorTokenReferenceRecord) -> Self {
let ConnectorTokenReferenceRecord {
connector_token,
payment_method_subtype,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
connector_token_status,
connector_token_request_reference_id,
} = value;
Self {
connector_token,
payment_method_subtype,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
connector_token_status,
connector_token_request_reference_id,
}
}
}
#[cfg(feature = "v1")]
impl From<PaymentsMandateReferenceRecord> for diesel_models::PaymentsMandateReferenceRecord {
fn from(value: PaymentsMandateReferenceRecord) -> Self {
Self {
connector_mandate_id: value.connector_mandate_id,
payment_method_type: value.payment_method_type,
original_payment_authorized_amount: value.original_payment_authorized_amount,
original_payment_authorized_currency: value.original_payment_authorized_currency,
mandate_metadata: value.mandate_metadata,
connector_mandate_status: value.connector_mandate_status,
connector_mandate_request_reference_id: value.connector_mandate_request_reference_id,
connector_customer_id: value.connector_customer_id,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/vault.rs | crates/hyperswitch_domain_models/src/vault.rs | use api_models::payment_methods;
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),
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),
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()),
),
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,
#[cfg(feature = "v1")]
issuer_country_code: 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,
},
),
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub enum PaymentMethodCustomVaultingData {
CardData(CardCustomData),
NetworkTokenData(NetworkTokenCustomData),
}
impl Default for PaymentMethodCustomVaultingData {
fn default() -> Self {
Self::CardData(CardCustomData::default())
}
}
#[derive(Debug, Default, Deserialize, Serialize, Clone)]
pub struct CardCustomData {
pub card_number: Option<cards::CardNumber>,
pub card_exp_month: Option<masking::Secret<String>>,
pub card_exp_year: Option<masking::Secret<String>>,
pub card_cvc: Option<masking::Secret<String>>,
}
#[derive(Debug, Default, Deserialize, Serialize, Clone)]
pub struct NetworkTokenCustomData {
pub network_token: Option<cards::NetworkToken>,
pub network_token_exp_month: Option<masking::Secret<String>>,
pub network_token_exp_year: Option<masking::Secret<String>>,
pub cryptogram: Option<masking::Secret<String>>,
}
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(),
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(),
),
}
}
}
impl From<PaymentMethodVaultingData> for PaymentMethodCustomVaultingData {
fn from(item: PaymentMethodVaultingData) -> Self {
match item {
PaymentMethodVaultingData::Card(card_data) => Self::CardData(CardCustomData {
card_number: Some(card_data.card_number),
card_exp_month: Some(card_data.card_exp_month),
card_exp_year: Some(card_data.card_exp_year),
card_cvc: card_data.card_cvc,
}),
PaymentMethodVaultingData::NetworkToken(network_token_data) => {
Self::NetworkTokenData(NetworkTokenCustomData {
network_token: Some(network_token_data.network_token),
network_token_exp_month: Some(network_token_data.network_token_exp_month),
network_token_exp_year: Some(network_token_data.network_token_exp_year),
cryptogram: network_token_data.cryptogram,
})
}
PaymentMethodVaultingData::CardNumber(card_number_data) => {
Self::CardData(CardCustomData {
card_number: Some(card_number_data),
card_exp_month: None,
card_exp_year: None,
card_cvc: None,
})
}
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/payment_address.rs | crates/hyperswitch_domain_models/src/payment_address.rs | use crate::address::Address;
#[derive(Clone, Default, Debug, serde::Serialize)]
pub struct PaymentAddress {
shipping: Option<Address>,
billing: Option<Address>,
unified_payment_method_billing: Option<Address>,
payment_method_billing: Option<Address>,
}
impl PaymentAddress {
pub fn new(
shipping: Option<Address>,
billing: Option<Address>,
payment_method_billing: Option<Address>,
should_unify_address: Option<bool>,
) -> Self {
// billing -> .billing, this is the billing details passed in the root of payments request
// payment_method_billing -> .payment_method_data.billing
let unified_payment_method_billing = if should_unify_address.unwrap_or(true) {
// Merge the billing details field from both `payment.billing` and `payment.payment_method_data.billing`
// The unified payment_method_billing will be used as billing address and passed to the connector module
// This unification is required in order to provide backwards compatibility
// so that if `payment.billing` is passed it should be sent to the connector module
// Unify the billing details with `payment_method_data.billing`
payment_method_billing
.as_ref()
.map(|payment_method_billing| {
payment_method_billing
.clone()
.unify_address(billing.as_ref())
})
.or(billing.clone())
} else {
payment_method_billing.clone()
};
Self {
shipping,
billing,
unified_payment_method_billing,
payment_method_billing,
}
}
pub fn get_shipping(&self) -> Option<&Address> {
self.shipping.as_ref()
}
pub fn get_payment_method_billing(&self) -> Option<&Address> {
self.unified_payment_method_billing.as_ref()
}
/// Unify the billing details from `payment_method_data.[payment_method_data].billing details`.
/// Here the fields passed in payment_method_data_billing takes precedence
pub fn unify_with_payment_method_data_billing(
self,
payment_method_data_billing: Option<Address>,
) -> Self {
// Unify the billing details with `payment_method_data.billing_details`
let unified_payment_method_billing = payment_method_data_billing
.map(|payment_method_data_billing| {
payment_method_data_billing.unify_address(self.get_payment_method_billing())
})
.or(self.get_payment_method_billing().cloned());
Self {
shipping: self.shipping,
billing: self.billing,
unified_payment_method_billing,
payment_method_billing: self.payment_method_billing,
}
}
/// Unify the billing details from `payment_method_data.[payment_method_data].billing details`.
/// Here the `self` takes precedence
pub fn unify_with_payment_data_billing(
self,
other_payment_method_billing: Option<Address>,
) -> Self {
let unified_payment_method_billing = self
.get_payment_method_billing()
.map(|payment_method_billing| {
payment_method_billing
.clone()
.unify_address(other_payment_method_billing.as_ref())
})
.or(other_payment_method_billing);
Self {
shipping: self.shipping,
billing: self.billing,
unified_payment_method_billing,
payment_method_billing: self.payment_method_billing,
}
}
pub fn get_request_payment_method_billing(&self) -> Option<&Address> {
self.payment_method_billing.as_ref()
}
pub fn get_payment_billing(&self) -> Option<&Address> {
self.billing.as_ref()
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/master_key.rs | crates/hyperswitch_domain_models/src/master_key.rs | pub trait MasterKeyInterface {
fn get_master_key(&self) -> &[u8];
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/callback_mapper.rs | crates/hyperswitch_domain_models/src/callback_mapper.rs | use common_enums::enums as common_enums;
use common_types::callback_mapper::CallbackMapperData;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CallbackMapper {
pub id: String,
pub callback_mapper_id_type: common_enums::CallbackMapperIdType,
pub data: CallbackMapperData,
pub created_at: time::PrimitiveDateTime,
pub last_modified_at: time::PrimitiveDateTime,
}
impl CallbackMapper {
pub fn new(
id: String,
callback_mapper_id_type: common_enums::CallbackMapperIdType,
data: CallbackMapperData,
created_at: time::PrimitiveDateTime,
last_modified_at: time::PrimitiveDateTime,
) -> Self {
Self {
id,
callback_mapper_id_type,
data,
created_at,
last_modified_at,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/lib.rs | crates/hyperswitch_domain_models/src/lib.rs | 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_key_store;
pub mod payment_address;
pub mod payment_method_data;
pub mod payment_methods;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payouts;
pub mod platform;
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,
custom_message_for_payment_method_types: item.custom_message_for_payment_method_types,
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,
custom_message_for_payment_method_types,
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,
custom_message_for_payment_method_types,
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,
amount_captured: amount.amount_captured,
}
}
}
#[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,
amount_captured: amount.amount_captured,
}
}
}
#[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(),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/connector_endpoints.rs | crates/hyperswitch_domain_models/src/connector_endpoints.rs | //! Configs interface
use common_enums::{connector_enums, ApplicationError};
use common_utils::errors::CustomResult;
use masking::Secret;
use serde::Deserialize;
use crate::errors::api_error_response;
// struct Connectors
#[allow(missing_docs, missing_debug_implementations)]
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct Connectors {
pub aci: ConnectorParams,
pub authipay: ConnectorParams,
pub adyen: AdyenParamsWithThreeBaseUrls,
pub adyenplatform: ConnectorParams,
pub affirm: ConnectorParams,
pub airwallex: ConnectorParams,
pub amazonpay: ConnectorParams,
pub applepay: ConnectorParams,
pub archipel: ConnectorParams,
pub authorizedotnet: ConnectorParams,
pub bambora: ConnectorParams,
pub bamboraapac: ConnectorParams,
pub bankofamerica: ConnectorParams,
pub barclaycard: ConnectorParams,
pub billwerk: ConnectorParams,
pub bitpay: ConnectorParams,
pub blackhawknetwork: ConnectorParams,
pub calida: ConnectorParams,
pub bluesnap: ConnectorParamsWithSecondaryBaseUrl,
pub boku: ConnectorParams,
pub braintree: ConnectorParams,
pub breadpay: ConnectorParams,
pub cashtocode: ConnectorParams,
pub celero: ConnectorParams,
pub chargebee: ConnectorParams,
pub checkbook: ConnectorParams,
pub checkout: ConnectorParams,
pub coinbase: ConnectorParams,
pub coingate: ConnectorParams,
pub cryptopay: ConnectorParams,
pub ctp_mastercard: NoParams,
pub ctp_visa: NoParams,
pub custombilling: NoParams,
pub cybersource: ConnectorParams,
pub datatrans: ConnectorParamsWithSecondaryBaseUrl,
pub deutschebank: ConnectorParams,
pub digitalvirgo: ConnectorParams,
pub dlocal: ConnectorParams,
#[cfg(feature = "dummy_connector")]
pub dummyconnector: ConnectorParams,
pub dwolla: ConnectorParams,
pub ebanx: ConnectorParams,
pub elavon: ConnectorParams,
pub envoy: ConnectorParams,
pub facilitapay: ConnectorParams,
pub finix: ConnectorParams,
pub fiserv: ConnectorParams,
pub fiservemea: ConnectorParams,
pub fiuu: ConnectorParamsWithThreeUrls,
pub flexiti: ConnectorParams,
pub forte: ConnectorParams,
pub getnet: ConnectorParams,
pub gigadat: ConnectorParams,
pub globalpay: ConnectorParams,
pub globepay: ConnectorParams,
pub gocardless: ConnectorParams,
pub gpayments: ConnectorParams,
pub helcim: ConnectorParams,
pub hipay: ConnectorParamsWithThreeUrls,
pub hyperswitch_vault: ConnectorParams,
pub hyperwallet: ConnectorParams,
pub iatapay: ConnectorParams,
pub inespay: ConnectorParams,
pub itaubank: ConnectorParams,
pub jpmorgan: ConnectorParams,
pub juspaythreedsserver: ConnectorParams,
pub cardinal: NoParams,
pub katapult: ConnectorParams,
pub klarna: ConnectorParams,
pub loonio: ConnectorParams,
pub mifinity: ConnectorParams,
pub mollie: ConnectorParams,
pub moneris: ConnectorParams,
pub mpgs: ConnectorParams,
pub multisafepay: ConnectorParams,
pub netcetera: ConnectorParams,
pub nexinets: ConnectorParams,
pub nexixpay: ConnectorParams,
pub nmi: ConnectorParams,
pub nomupay: ConnectorParams,
pub noon: ConnectorParamsWithModeType,
pub nordea: ConnectorParams,
pub novalnet: ConnectorParams,
pub nuvei: ConnectorParams,
pub opayo: ConnectorParams,
pub opennode: ConnectorParams,
pub paybox: ConnectorParamsWithSecondaryBaseUrl,
pub payeezy: ConnectorParams,
pub payjustnow: ConnectorParams,
pub payjustnowinstore: ConnectorParams,
pub payload: ConnectorParams,
pub payme: ConnectorParams,
pub payone: ConnectorParams,
pub paypal: ConnectorParams,
pub paysafe: ConnectorParams,
pub paystack: ConnectorParams,
pub paytm: ConnectorParams,
pub payu: ConnectorParams,
pub peachpayments: ConnectorParams,
pub phonepe: ConnectorParams,
pub placetopay: ConnectorParams,
pub plaid: ConnectorParams,
pub powertranz: ConnectorParams,
pub prophetpay: ConnectorParams,
pub rapyd: ConnectorParams,
pub razorpay: ConnectorParamsWithKeys,
pub recurly: ConnectorParams,
pub redsys: ConnectorParams,
pub riskified: ConnectorParams,
pub santander: ConnectorParams,
pub shift4: ConnectorParams,
pub sift: ConnectorParams,
pub silverflow: ConnectorParams,
pub signifyd: ConnectorParams,
pub square: ConnectorParams,
pub stax: ConnectorParams,
pub stripe: ConnectorParamsWithFileUploadUrl,
pub stripebilling: ConnectorParams,
pub taxjar: ConnectorParams,
pub tesouro: ConnectorParams,
pub threedsecureio: ConnectorParams,
pub thunes: ConnectorParams,
pub tokenex: ConnectorParams,
pub tokenio: ConnectorParams,
pub trustpay: ConnectorParamsWithMoreUrls,
pub trustpayments: ConnectorParams,
pub tsys: ConnectorParams,
pub unified_authentication_service: ConnectorParams,
pub vgs: ConnectorParams,
pub volt: ConnectorParamsWithSecondaryBaseUrl,
pub wellsfargo: ConnectorParams,
pub wellsfargopayout: ConnectorParams,
pub wise: ConnectorParams,
pub worldline: ConnectorParams,
pub worldpay: ConnectorParams,
pub worldpayvantiv: ConnectorParamsWithThreeUrls,
pub worldpayxml: ConnectorParamsWithSecondaryBaseUrl,
pub xendit: ConnectorParams,
pub zift: ConnectorParams,
pub zen: ConnectorParams,
pub zsl: ConnectorParams,
}
impl Connectors {
pub fn get_connector_params(
&self,
connector: connector_enums::Connector,
) -> CustomResult<ConnectorParams, api_error_response::ApiErrorResponse> {
match connector {
connector_enums::Connector::Recurly => Ok(self.recurly.clone()),
connector_enums::Connector::Stripebilling => Ok(self.stripebilling.clone()),
connector_enums::Connector::Chargebee => Ok(self.chargebee.clone()),
_ => Err(api_error_response::ApiErrorResponse::IncorrectConnectorNameGiven.into()),
}
}
}
/// struct ConnectorParams
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct ConnectorParams {
/// base url
pub base_url: String,
/// secondary base url
pub secondary_base_url: Option<String>,
}
///struct No Param for connectors with no params
#[derive(Debug, Deserialize, Clone, Default)]
pub struct NoParams;
impl NoParams {
/// function to satisfy connector param validation macro
pub fn validate(&self, _parent_field: &str) -> Result<(), ApplicationError> {
Ok(())
}
}
/// struct ConnectorParamsWithKeys
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct ConnectorParamsWithKeys {
/// base url
pub base_url: String,
/// api key
pub api_key: Secret<String>,
/// merchant ID
pub merchant_id: Secret<String>,
}
/// struct ConnectorParamsWithModeType
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct ConnectorParamsWithModeType {
/// base url
pub base_url: String,
/// secondary base url
pub secondary_base_url: Option<String>,
/// Can take values like Test or Live for Noon
pub key_mode: String,
}
/// struct ConnectorParamsWithMoreUrls
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct ConnectorParamsWithMoreUrls {
/// base url
pub base_url: String,
/// base url for bank redirects
pub base_url_bank_redirects: String,
}
/// struct ConnectorParamsWithFileUploadUrl
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct ConnectorParamsWithFileUploadUrl {
/// base url
pub base_url: String,
/// base url for file upload
pub base_url_file_upload: String,
}
/// struct ConnectorParamsWithThreeBaseUrls
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct AdyenParamsWithThreeBaseUrls {
/// base url
pub base_url: String,
/// secondary base url
#[cfg(feature = "payouts")]
pub payout_base_url: String,
/// third base url
pub dispute_base_url: String,
}
/// struct ConnectorParamsWithSecondaryBaseUrl
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct ConnectorParamsWithSecondaryBaseUrl {
/// base url
pub base_url: String,
/// secondary base url
pub secondary_base_url: String,
}
/// struct ConnectorParamsWithThreeUrls
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct ConnectorParamsWithThreeUrls {
/// base url
pub base_url: String,
/// secondary base url
pub secondary_base_url: String,
/// third base url
pub third_base_url: String,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_response_types.rs | crates/hyperswitch_domain_models/src/router_response_types.rs | pub mod disputes;
pub mod fraud_check;
pub mod revenue_recovery;
pub mod subscriptions;
use std::collections::HashMap;
use api_models::payments::AddressDetails;
use common_utils::{pii, request::Method, types::MinorUnit};
pub use disputes::{
AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse,
SubmitEvidenceResponse,
};
use error_stack::ResultExt;
use serde::{Deserialize, Serialize};
use crate::{
errors::api_error_response::ApiErrorResponse,
router_request_types::{authentication::AuthNFlowType, ResponseId},
vault::PaymentMethodVaultingData,
};
#[derive(Debug, Clone, serde::Serialize)]
pub struct RefundsResponseData {
pub connector_refund_id: String,
pub refund_status: common_enums::RefundStatus,
// pub amount_received: Option<i32>, // Calculation for amount received not in place yet
}
#[derive(Debug, Clone, Serialize)]
pub struct ConnectorCustomerResponseData {
pub connector_customer_id: String,
pub name: Option<String>,
pub email: Option<String>,
pub billing_address: Option<AddressDetails>,
}
impl ConnectorCustomerResponseData {
pub fn new_with_customer_id(connector_customer_id: String) -> Self {
Self::new(connector_customer_id, None, None, None)
}
pub fn new(
connector_customer_id: String,
name: Option<String>,
email: Option<String>,
billing_address: Option<AddressDetails>,
) -> Self {
Self {
connector_customer_id,
name,
email,
billing_address,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub enum PaymentsResponseData {
TransactionResponse {
resource_id: ResponseId,
redirection_data: Box<Option<RedirectForm>>,
mandate_reference: Box<Option<MandateReference>>,
connector_metadata: Option<serde_json::Value>,
network_txn_id: Option<String>,
connector_response_reference_id: Option<String>,
incremental_authorization_allowed: Option<bool>,
charges: Option<common_types::payments::ConnectorChargeResponseData>,
},
MultipleCaptureResponse {
// pending_capture_id_list: Vec<String>,
capture_sync_response_list: HashMap<String, CaptureSyncResponse>,
},
SessionResponse {
session_token: api_models::payments::SessionToken,
},
SessionTokenResponse {
session_token: String,
},
TransactionUnresolvedResponse {
resource_id: ResponseId,
//to add more info on cypto response, like `unresolved` reason(overpaid, underpaid, delayed)
reason: Option<api_models::enums::UnresolvedResponseReason>,
connector_response_reference_id: Option<String>,
},
TokenizationResponse {
token: String,
},
ConnectorCustomerResponse(ConnectorCustomerResponseData),
ThreeDSEnrollmentResponse {
enrolled_v2: bool,
related_transaction_id: Option<String>,
},
PreProcessingResponse {
pre_processing_id: PreprocessingResponseId,
connector_metadata: Option<serde_json::Value>,
session_token: Option<api_models::payments::SessionToken>,
connector_response_reference_id: Option<String>,
},
IncrementalAuthorizationResponse {
status: common_enums::AuthorizationStatus,
connector_authorization_id: Option<String>,
error_code: Option<String>,
error_message: Option<String>,
},
PostProcessingResponse {
session_token: Option<api_models::payments::OpenBankingSessionToken>,
},
PaymentResourceUpdateResponse {
status: common_enums::PaymentResourceUpdateStatus,
},
PaymentsCreateOrderResponse {
order_id: String,
},
}
#[derive(Debug, Clone)]
pub struct GiftCardBalanceCheckResponseData {
pub balance: MinorUnit,
pub currency: common_enums::Currency,
}
#[derive(Debug, Clone)]
pub struct TaxCalculationResponseData {
pub order_tax_amount: MinorUnit,
}
#[derive(Serialize, Debug, Clone, serde::Deserialize)]
pub struct MandateReference {
pub connector_mandate_id: Option<String>,
pub payment_method_id: Option<String>,
pub mandate_metadata: Option<pii::SecretSerdeValue>,
pub connector_mandate_request_reference_id: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub enum CaptureSyncResponse {
Success {
resource_id: ResponseId,
status: common_enums::AttemptStatus,
connector_response_reference_id: Option<String>,
amount: Option<MinorUnit>,
},
Error {
code: String,
message: String,
reason: Option<String>,
status_code: u16,
amount: Option<MinorUnit>,
},
}
impl CaptureSyncResponse {
pub fn get_amount_captured(&self) -> Option<MinorUnit> {
match self {
Self::Success { amount, .. } | Self::Error { amount, .. } => *amount,
}
}
pub fn get_connector_response_reference_id(&self) -> Option<String> {
match self {
Self::Success {
connector_response_reference_id,
..
} => connector_response_reference_id.clone(),
Self::Error { .. } => None,
}
}
}
impl PaymentsResponseData {
pub fn get_connector_metadata(&self) -> Option<masking::Secret<serde_json::Value>> {
match self {
Self::TransactionResponse {
connector_metadata, ..
}
| Self::PreProcessingResponse {
connector_metadata, ..
} => connector_metadata.clone().map(masking::Secret::new),
_ => None,
}
}
pub fn get_network_transaction_id(&self) -> Option<String> {
match self {
Self::TransactionResponse { network_txn_id, .. } => network_txn_id.clone(),
_ => None,
}
}
pub fn get_connector_transaction_id(
&self,
) -> Result<String, error_stack::Report<ApiErrorResponse>> {
match self {
Self::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(txn_id),
..
} => Ok(txn_id.to_string()),
_ => Err(ApiErrorResponse::MissingRequiredField {
field_name: "ConnectorTransactionId",
}
.into()),
}
}
pub fn merge_transaction_responses(
auth_response: &Self,
capture_response: &Self,
) -> Result<Self, error_stack::Report<ApiErrorResponse>> {
match (auth_response, capture_response) {
(
Self::TransactionResponse {
resource_id: _,
redirection_data: auth_redirection_data,
mandate_reference: auth_mandate_reference,
connector_metadata: auth_connector_metadata,
network_txn_id: auth_network_txn_id,
connector_response_reference_id: auth_connector_response_reference_id,
incremental_authorization_allowed: auth_incremental_auth_allowed,
charges: auth_charges,
},
Self::TransactionResponse {
resource_id: capture_resource_id,
redirection_data: capture_redirection_data,
mandate_reference: capture_mandate_reference,
connector_metadata: capture_connector_metadata,
network_txn_id: capture_network_txn_id,
connector_response_reference_id: capture_connector_response_reference_id,
incremental_authorization_allowed: capture_incremental_auth_allowed,
charges: capture_charges,
},
) => Ok(Self::TransactionResponse {
resource_id: capture_resource_id.clone(),
redirection_data: Box::new(
capture_redirection_data
.clone()
.or_else(|| *auth_redirection_data.clone()),
),
mandate_reference: Box::new(
auth_mandate_reference
.clone()
.or_else(|| *capture_mandate_reference.clone()),
),
connector_metadata: capture_connector_metadata
.clone()
.or(auth_connector_metadata.clone()),
network_txn_id: capture_network_txn_id
.clone()
.or(auth_network_txn_id.clone()),
connector_response_reference_id: capture_connector_response_reference_id
.clone()
.or(auth_connector_response_reference_id.clone()),
incremental_authorization_allowed: (*capture_incremental_auth_allowed)
.or(*auth_incremental_auth_allowed),
charges: auth_charges.clone().or(capture_charges.clone()),
}),
_ => Err(ApiErrorResponse::NotSupported {
message: "Invalid Flow ".to_owned(),
}
.into()),
}
}
#[cfg(feature = "v2")]
pub fn get_updated_connector_token_details(
&self,
original_connector_mandate_request_reference_id: Option<String>,
) -> Option<diesel_models::ConnectorTokenDetails> {
if let Self::TransactionResponse {
mandate_reference, ..
} = self
{
mandate_reference.clone().map(|mandate_ref| {
let connector_mandate_id = mandate_ref.connector_mandate_id;
let connector_mandate_request_reference_id = mandate_ref
.connector_mandate_request_reference_id
.or(original_connector_mandate_request_reference_id);
diesel_models::ConnectorTokenDetails {
connector_mandate_id,
connector_token_request_reference_id: connector_mandate_request_reference_id,
}
})
} else {
None
}
}
pub fn get_mandate_reference(&self) -> Option<MandateReference> {
if let Self::TransactionResponse {
mandate_reference, ..
} = self
{
mandate_reference.as_ref().clone()
} else {
None
}
}
}
#[derive(Debug, Clone, Serialize)]
pub enum PreprocessingResponseId {
PreProcessingId(String),
ConnectorTransactionId(String),
}
impl PreprocessingResponseId {
pub fn get_string_repr(&self) -> &String {
match self {
Self::PreProcessingId(value) => value,
Self::ConnectorTransactionId(value) => value,
}
}
}
#[derive(Debug, Eq, PartialEq, Clone, Serialize, serde::Deserialize)]
pub enum RedirectForm {
Form {
endpoint: String,
method: Method,
form_fields: HashMap<String, String>,
},
Html {
html_data: String,
},
BarclaycardAuthSetup {
access_token: String,
ddc_url: String,
reference_id: String,
},
BarclaycardConsumerAuth {
access_token: String,
step_up_url: String,
},
BlueSnap {
payment_fields_token: String, // payment-field-token
},
CybersourceAuthSetup {
access_token: String,
ddc_url: String,
reference_id: String,
},
CybersourceConsumerAuth {
access_token: String,
step_up_url: String,
},
DeutschebankThreeDSChallengeFlow {
acs_url: String,
creq: String,
},
Payme,
Braintree {
client_token: String,
card_token: String,
bin: String,
acs_url: String,
},
Nmi {
amount: String,
currency: common_enums::Currency,
public_key: masking::Secret<String>,
customer_vault_id: String,
order_id: String,
},
Mifinity {
initialization_token: String,
},
WorldpayDDCForm {
endpoint: url::Url,
method: Method,
form_fields: HashMap<String, String>,
collection_id: Option<String>,
},
WorldpayxmlRedirectForm {
jwt: String,
},
}
impl From<(url::Url, Method)> for RedirectForm {
fn from((mut redirect_url, method): (url::Url, Method)) -> Self {
let form_fields = HashMap::from_iter(
redirect_url
.query_pairs()
.map(|(key, value)| (key.to_string(), value.to_string())),
);
// Do not include query params in the endpoint
redirect_url.set_query(None);
Self::Form {
endpoint: redirect_url.to_string(),
method,
form_fields,
}
}
}
impl From<RedirectForm> for diesel_models::payment_attempt::RedirectForm {
fn from(redirect_form: RedirectForm) -> Self {
match redirect_form {
RedirectForm::Form {
endpoint,
method,
form_fields,
} => Self::Form {
endpoint,
method,
form_fields,
},
RedirectForm::Html { html_data } => Self::Html { html_data },
RedirectForm::BarclaycardAuthSetup {
access_token,
ddc_url,
reference_id,
} => Self::BarclaycardAuthSetup {
access_token,
ddc_url,
reference_id,
},
RedirectForm::BarclaycardConsumerAuth {
access_token,
step_up_url,
} => Self::BarclaycardConsumerAuth {
access_token,
step_up_url,
},
RedirectForm::BlueSnap {
payment_fields_token,
} => Self::BlueSnap {
payment_fields_token,
},
RedirectForm::CybersourceAuthSetup {
access_token,
ddc_url,
reference_id,
} => Self::CybersourceAuthSetup {
access_token,
ddc_url,
reference_id,
},
RedirectForm::CybersourceConsumerAuth {
access_token,
step_up_url,
} => Self::CybersourceConsumerAuth {
access_token,
step_up_url,
},
RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url, creq } => {
Self::DeutschebankThreeDSChallengeFlow { acs_url, creq }
}
RedirectForm::Payme => Self::Payme,
RedirectForm::Braintree {
client_token,
card_token,
bin,
acs_url,
} => Self::Braintree {
client_token,
card_token,
bin,
acs_url,
},
RedirectForm::Nmi {
amount,
currency,
public_key,
customer_vault_id,
order_id,
} => Self::Nmi {
amount,
currency,
public_key,
customer_vault_id,
order_id,
},
RedirectForm::Mifinity {
initialization_token,
} => Self::Mifinity {
initialization_token,
},
RedirectForm::WorldpayDDCForm {
endpoint,
method,
form_fields,
collection_id,
} => Self::WorldpayDDCForm {
endpoint: common_utils::types::Url::wrap(endpoint),
method,
form_fields,
collection_id,
},
RedirectForm::WorldpayxmlRedirectForm { jwt } => Self::WorldpayxmlRedirectForm { jwt },
}
}
}
impl From<diesel_models::payment_attempt::RedirectForm> for RedirectForm {
fn from(redirect_form: diesel_models::payment_attempt::RedirectForm) -> Self {
match redirect_form {
diesel_models::payment_attempt::RedirectForm::Form {
endpoint,
method,
form_fields,
} => Self::Form {
endpoint,
method,
form_fields,
},
diesel_models::payment_attempt::RedirectForm::Html { html_data } => {
Self::Html { html_data }
}
diesel_models::payment_attempt::RedirectForm::BarclaycardAuthSetup {
access_token,
ddc_url,
reference_id,
} => Self::BarclaycardAuthSetup {
access_token,
ddc_url,
reference_id,
},
diesel_models::payment_attempt::RedirectForm::BarclaycardConsumerAuth {
access_token,
step_up_url,
} => Self::BarclaycardConsumerAuth {
access_token,
step_up_url,
},
diesel_models::payment_attempt::RedirectForm::BlueSnap {
payment_fields_token,
} => Self::BlueSnap {
payment_fields_token,
},
diesel_models::payment_attempt::RedirectForm::CybersourceAuthSetup {
access_token,
ddc_url,
reference_id,
} => Self::CybersourceAuthSetup {
access_token,
ddc_url,
reference_id,
},
diesel_models::payment_attempt::RedirectForm::CybersourceConsumerAuth {
access_token,
step_up_url,
} => Self::CybersourceConsumerAuth {
access_token,
step_up_url,
},
diesel_models::RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url, creq } => {
Self::DeutschebankThreeDSChallengeFlow { acs_url, creq }
}
diesel_models::payment_attempt::RedirectForm::Payme => Self::Payme,
diesel_models::payment_attempt::RedirectForm::Braintree {
client_token,
card_token,
bin,
acs_url,
} => Self::Braintree {
client_token,
card_token,
bin,
acs_url,
},
diesel_models::payment_attempt::RedirectForm::Nmi {
amount,
currency,
public_key,
customer_vault_id,
order_id,
} => Self::Nmi {
amount,
currency,
public_key,
customer_vault_id,
order_id,
},
diesel_models::payment_attempt::RedirectForm::Mifinity {
initialization_token,
} => Self::Mifinity {
initialization_token,
},
diesel_models::payment_attempt::RedirectForm::WorldpayDDCForm {
endpoint,
method,
form_fields,
collection_id,
} => Self::WorldpayDDCForm {
endpoint: endpoint.into_inner(),
method,
form_fields,
collection_id,
},
diesel_models::payment_attempt::RedirectForm::WorldpayxmlRedirectForm { jwt } => {
Self::WorldpayxmlRedirectForm { jwt }
}
}
}
}
#[derive(Default, Clone, Debug)]
pub struct UploadFileResponse {
pub provider_file_id: String,
}
#[derive(Clone, Debug)]
pub struct RetrieveFileResponse {
pub file_data: Vec<u8>,
}
#[cfg(feature = "payouts")]
#[derive(Clone, Debug, Default)]
pub struct PayoutsResponseData {
pub status: Option<common_enums::PayoutStatus>,
pub connector_payout_id: Option<String>,
pub payout_eligible: Option<bool>,
pub should_add_next_step_to_process_tracker: bool,
pub error_code: Option<String>,
pub error_message: Option<String>,
pub payout_connector_metadata: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Clone)]
pub struct VerifyWebhookSourceResponseData {
pub verify_webhook_status: VerifyWebhookStatus,
}
#[derive(Debug, Clone)]
pub enum VerifyWebhookStatus {
SourceVerified,
SourceNotVerified,
}
#[derive(Debug, Clone)]
pub struct MandateRevokeResponseData {
pub mandate_status: common_enums::MandateStatus,
}
#[derive(Debug, Clone)]
pub enum AuthenticationResponseData {
PreAuthVersionCallResponse {
maximum_supported_3ds_version: common_utils::types::SemanticVersion,
},
PreAuthThreeDsMethodCallResponse {
threeds_server_transaction_id: String,
three_ds_method_data: Option<String>,
three_ds_method_url: Option<String>,
connector_metadata: Option<serde_json::Value>,
},
PreAuthNResponse {
threeds_server_transaction_id: String,
maximum_supported_3ds_version: common_utils::types::SemanticVersion,
connector_authentication_id: String,
three_ds_method_data: Option<String>,
three_ds_method_url: Option<String>,
message_version: common_utils::types::SemanticVersion,
connector_metadata: Option<serde_json::Value>,
directory_server_id: Option<String>,
scheme_id: Option<String>,
},
AuthNResponse {
authn_flow_type: AuthNFlowType,
authentication_value: Option<masking::Secret<String>>,
trans_status: common_enums::TransactionStatus,
connector_metadata: Option<serde_json::Value>,
ds_trans_id: Option<String>,
eci: Option<String>,
challenge_code: Option<String>,
challenge_cancel: Option<String>,
challenge_code_reason: Option<String>,
message_extension: Option<pii::SecretSerdeValue>,
},
PostAuthNResponse {
trans_status: common_enums::TransactionStatus,
authentication_value: Option<masking::Secret<String>>,
eci: Option<String>,
challenge_cancel: Option<String>,
challenge_code_reason: Option<String>,
},
}
/// Represents details of a payment method.
#[derive(Debug, Clone)]
pub struct PaymentMethodDetails {
/// Indicates whether mandates are supported by this payment method.
pub mandates: common_enums::FeatureStatus,
/// Indicates whether refund is supported by this payment method.
pub refunds: common_enums::FeatureStatus,
/// List of supported capture methods
pub supported_capture_methods: Vec<common_enums::CaptureMethod>,
/// Payment method specific features
pub specific_features: Option<api_models::feature_matrix::PaymentMethodSpecificFeatures>,
}
/// list of payment method types and metadata related to them
pub type PaymentMethodTypeMetadata = HashMap<common_enums::PaymentMethodType, PaymentMethodDetails>;
/// list of payment methods, payment method types and metadata related to them
pub type SupportedPaymentMethods = HashMap<common_enums::PaymentMethod, PaymentMethodTypeMetadata>;
#[derive(Debug, Clone)]
pub struct ConnectorInfo {
/// Display name of the Connector
pub display_name: &'static str,
/// Description of the connector.
pub description: &'static str,
/// Connector Type
pub connector_type: common_enums::HyperswitchConnectorCategory,
/// Integration status of the connector
pub integration_status: common_enums::ConnectorIntegrationStatus,
}
pub trait SupportedPaymentMethodsExt {
fn add(
&mut self,
payment_method: common_enums::PaymentMethod,
payment_method_type: common_enums::PaymentMethodType,
payment_method_details: PaymentMethodDetails,
);
}
impl SupportedPaymentMethodsExt for SupportedPaymentMethods {
fn add(
&mut self,
payment_method: common_enums::PaymentMethod,
payment_method_type: common_enums::PaymentMethodType,
payment_method_details: PaymentMethodDetails,
) {
if let Some(payment_method_data) = self.get_mut(&payment_method) {
payment_method_data.insert(payment_method_type, payment_method_details);
} else {
let mut payment_method_type_metadata = PaymentMethodTypeMetadata::new();
payment_method_type_metadata.insert(payment_method_type, payment_method_details);
self.insert(payment_method, payment_method_type_metadata);
}
}
}
#[derive(Debug, Clone)]
pub enum VaultResponseData {
ExternalVaultCreateResponse {
session_id: masking::Secret<String>,
client_secret: masking::Secret<String>,
},
ExternalVaultInsertResponse {
connector_vault_id: VaultIdType,
fingerprint_id: String,
},
ExternalVaultRetrieveResponse {
vault_data: PaymentMethodVaultingData,
},
ExternalVaultDeleteResponse {
connector_vault_id: String,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum VaultIdType {
SingleVaultId(String),
MultiVauldIds(MultiVaultIdType),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MultiVaultIdType {
Card {
tokenized_card_number: Option<masking::Secret<String>>,
tokenized_card_expiry_year: Option<masking::Secret<String>>,
tokenized_card_expiry_month: Option<masking::Secret<String>>,
tokenized_card_cvc: Option<masking::Secret<String>>,
},
NetworkToken {
tokenized_network_token: Option<masking::Secret<String>>,
tokenized_network_token_exp_year: Option<masking::Secret<String>>,
tokenized_network_token_exp_month: Option<masking::Secret<String>>,
tokenized_cryptogram: Option<masking::Secret<String>>,
},
}
impl VaultIdType {
pub fn get_single_vault_id(&self) -> Result<String, error_stack::Report<ApiErrorResponse>> {
match self {
Self::SingleVaultId(vault_id) => Ok(vault_id.to_string()),
Self::MultiVauldIds(_) => Err(ApiErrorResponse::MissingRequiredField {
field_name: "SingleVaultId",
}
.into()),
}
}
#[cfg(feature = "v1")]
pub fn get_auth_vault_token_data(
&self,
) -> Result<
api_models::authentication::AuthenticationVaultTokenData,
error_stack::Report<ApiErrorResponse>,
> {
match self.clone() {
Self::MultiVauldIds(multi_vault_data) => match multi_vault_data {
MultiVaultIdType::Card {
tokenized_card_number,
tokenized_card_expiry_year,
tokenized_card_expiry_month,
tokenized_card_cvc,
} => Ok(
api_models::authentication::AuthenticationVaultTokenData::CardData {
tokenized_card_number,
tokenized_card_expiry_month,
tokenized_card_expiry_year,
tokenized_card_cvc,
},
),
MultiVaultIdType::NetworkToken {
tokenized_network_token,
tokenized_network_token_exp_month,
tokenized_network_token_exp_year,
tokenized_cryptogram,
} => Ok(
api_models::authentication::AuthenticationVaultTokenData::NetworkTokenData {
tokenized_network_token,
tokenized_expiry_month: tokenized_network_token_exp_month,
tokenized_expiry_year: tokenized_network_token_exp_year,
tokenized_cryptogram,
},
),
},
Self::SingleVaultId(_) => Err(ApiErrorResponse::InternalServerError)
.attach_printable("Unexpected Behaviour, Multi Token Data is missing"),
}
}
}
impl Default for VaultResponseData {
fn default() -> Self {
Self::ExternalVaultInsertResponse {
connector_vault_id: VaultIdType::SingleVaultId(String::new()),
fingerprint_id: String::new(),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/address.rs | crates/hyperswitch_domain_models/src/address.rs | use masking::{PeekInterface, Secret};
#[derive(Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct Address {
pub address: Option<AddressDetails>,
pub phone: Option<PhoneDetails>,
pub email: Option<common_utils::pii::Email>,
}
impl masking::SerializableSecret for Address {}
impl Address {
/// Unify the address, giving priority to `self` when details are present in both
pub fn unify_address(&self, other: Option<&Self>) -> Self {
let other_address_details = other.and_then(|address| address.address.as_ref());
Self {
address: self
.address
.as_ref()
.map(|address| address.unify_address_details(other_address_details))
.or(other_address_details.cloned()),
email: self
.email
.clone()
.or(other.and_then(|other| other.email.clone())),
phone: {
self.phone
.clone()
.and_then(|phone_details| {
if phone_details.number.is_some() {
Some(phone_details)
} else {
None
}
})
.or_else(|| other.and_then(|other| other.phone.clone()))
},
}
}
}
#[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq)]
pub struct AddressDetails {
pub city: Option<String>,
pub country: Option<common_enums::CountryAlpha2>,
pub line1: Option<Secret<String>>,
pub line2: Option<Secret<String>>,
pub line3: Option<Secret<String>>,
pub zip: Option<Secret<String>>,
pub state: Option<Secret<String>>,
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub origin_zip: Option<Secret<String>>,
}
impl AddressDetails {
pub fn get_optional_full_name(&self) -> Option<Secret<String>> {
match (self.first_name.as_ref(), self.last_name.as_ref()) {
(Some(first_name), Some(last_name)) => Some(Secret::new(format!(
"{} {}",
first_name.peek(),
last_name.peek()
))),
(Some(name), None) | (None, Some(name)) => Some(name.to_owned()),
_ => None,
}
}
/// Unify the address details, giving priority to `self` when details are present in both
pub fn unify_address_details(&self, other: Option<&Self>) -> Self {
if let Some(other) = other {
let (first_name, last_name) = if self
.first_name
.as_ref()
.is_some_and(|first_name| !first_name.peek().trim().is_empty())
{
(self.first_name.clone(), self.last_name.clone())
} else {
(other.first_name.clone(), other.last_name.clone())
};
Self {
first_name,
last_name,
city: self.city.clone().or(other.city.clone()),
country: self.country.or(other.country),
line1: self.line1.clone().or(other.line1.clone()),
line2: self.line2.clone().or(other.line2.clone()),
line3: self.line3.clone().or(other.line3.clone()),
zip: self.zip.clone().or(other.zip.clone()),
state: self.state.clone().or(other.state.clone()),
origin_zip: self.origin_zip.clone().or(other.origin_zip.clone()),
}
} else {
self.clone()
}
}
}
#[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct PhoneDetails {
pub number: Option<Secret<String>>,
pub country_code: Option<String>,
}
impl From<api_models::payments::Address> for Address {
fn from(address: api_models::payments::Address) -> Self {
Self {
address: address.address.map(AddressDetails::from),
phone: address.phone.map(PhoneDetails::from),
email: address.email,
}
}
}
impl From<api_models::payments::AddressDetails> for AddressDetails {
fn from(address: api_models::payments::AddressDetails) -> Self {
Self {
city: address.city,
country: address.country,
line1: address.line1,
line2: address.line2,
line3: address.line3,
zip: address.zip,
state: address.state,
first_name: address.first_name,
last_name: address.last_name,
origin_zip: address.origin_zip,
}
}
}
impl From<api_models::payments::PhoneDetails> for PhoneDetails {
fn from(phone: api_models::payments::PhoneDetails) -> Self {
Self {
number: phone.number,
country_code: phone.country_code,
}
}
}
impl From<Address> for api_models::payments::Address {
fn from(address: Address) -> Self {
Self {
address: address
.address
.map(api_models::payments::AddressDetails::from),
phone: address.phone.map(api_models::payments::PhoneDetails::from),
email: address.email,
}
}
}
impl From<AddressDetails> for api_models::payments::AddressDetails {
fn from(address: AddressDetails) -> Self {
Self {
city: address.city,
country: address.country,
line1: address.line1,
line2: address.line2,
line3: address.line3,
zip: address.zip,
state: address.state,
first_name: address.first_name,
last_name: address.last_name,
origin_zip: address.origin_zip,
}
}
}
impl From<PhoneDetails> for api_models::payments::PhoneDetails {
fn from(phone: PhoneDetails) -> Self {
Self {
number: phone.number,
country_code: phone.country_code,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/refunds.rs | crates/hyperswitch_domain_models/src/refunds.rs | #[cfg(feature = "v2")]
use crate::business_profile::Profile;
#[cfg(feature = "v1")]
use crate::errors;
#[cfg(feature = "v1")]
pub struct RefundListConstraints {
pub payment_id: Option<common_utils::id_type::PaymentId>,
pub refund_id: Option<String>,
pub profile_id: Option<Vec<common_utils::id_type::ProfileId>>,
pub limit: Option<i64>,
pub offset: Option<i64>,
pub time_range: Option<common_utils::types::TimeRange>,
pub amount_filter: Option<api_models::payments::AmountFilter>,
pub connector: Option<Vec<String>>,
pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
pub currency: Option<Vec<common_enums::Currency>>,
pub refund_status: Option<Vec<common_enums::RefundStatus>>,
}
#[cfg(feature = "v2")]
pub struct RefundListConstraints {
pub payment_id: Option<common_utils::id_type::GlobalPaymentId>,
pub refund_id: Option<common_utils::id_type::GlobalRefundId>,
pub profile_id: common_utils::id_type::ProfileId,
pub limit: Option<i64>,
pub offset: Option<i64>,
pub time_range: Option<common_utils::types::TimeRange>,
pub amount_filter: Option<api_models::payments::AmountFilter>,
pub connector: Option<Vec<String>>,
pub connector_id_list: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
pub currency: Option<Vec<common_enums::Currency>>,
pub refund_status: Option<Vec<common_enums::RefundStatus>>,
}
#[cfg(feature = "v1")]
impl
TryFrom<(
api_models::refunds::RefundListRequest,
Option<Vec<common_utils::id_type::ProfileId>>,
)> for RefundListConstraints
{
type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>;
fn try_from(
(value, auth_profile_id_list): (
api_models::refunds::RefundListRequest,
Option<Vec<common_utils::id_type::ProfileId>>,
),
) -> Result<Self, Self::Error> {
let api_models::refunds::RefundListRequest {
connector,
currency,
refund_status,
payment_id,
refund_id,
profile_id,
limit,
offset,
time_range,
amount_filter,
merchant_connector_id,
} = value;
let profile_id_from_request_body = profile_id;
let profile_id_list = match (profile_id_from_request_body, auth_profile_id_list) {
(None, None) => None,
(None, Some(auth_profile_id_list)) => Some(auth_profile_id_list),
(Some(profile_id_from_request_body), None) => Some(vec![profile_id_from_request_body]),
(Some(profile_id_from_request_body), Some(auth_profile_id_list)) => {
let profile_id_from_request_body_is_available_in_auth_profile_id_list =
auth_profile_id_list.contains(&profile_id_from_request_body);
if profile_id_from_request_body_is_available_in_auth_profile_id_list {
Some(vec![profile_id_from_request_body])
} else {
// This scenario is very unlikely to happen
return Err(error_stack::Report::new(
errors::api_error_response::ApiErrorResponse::PreconditionFailed {
message: format!(
"Access not available for the given profile_id {profile_id_from_request_body:?}",
),
},
));
}
}
};
Ok(Self {
payment_id,
refund_id,
profile_id: profile_id_list,
limit,
offset,
time_range,
amount_filter,
connector,
merchant_connector_id,
currency,
refund_status,
})
}
}
#[cfg(feature = "v2")]
impl From<(api_models::refunds::RefundListRequest, Profile)> for RefundListConstraints {
fn from((value, profile): (api_models::refunds::RefundListRequest, Profile)) -> Self {
let api_models::refunds::RefundListRequest {
payment_id,
refund_id,
connector,
currency,
refund_status,
limit,
offset,
time_range,
amount_filter,
connector_id_list,
} = value;
Self {
payment_id,
refund_id,
profile_id: profile.get_id().to_owned(),
limit,
offset,
time_range,
amount_filter,
connector,
connector_id_list,
currency,
refund_status,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/behaviour.rs | crates/hyperswitch_domain_models/src/behaviour.rs | use common_utils::{
errors::{CustomResult, ValidationError},
types::keymanager::{Identifier, KeyManagerState},
};
use masking::Secret;
/// Trait for converting domain types to storage models
#[async_trait::async_trait]
pub trait Conversion {
type DstType;
type NewDstType;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError>;
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized;
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError>;
}
#[async_trait::async_trait]
pub trait ReverseConversion<SrcType: Conversion> {
async fn convert(
self,
state: &KeyManagerState,
key: &Secret<Vec<u8>>,
key_manager_identifier: Identifier,
) -> CustomResult<SrcType, ValidationError>;
}
#[async_trait::async_trait]
impl<T: Send, U: Conversion<DstType = T>> ReverseConversion<U> for T {
async fn convert(
self,
state: &KeyManagerState,
key: &Secret<Vec<u8>>,
key_manager_identifier: Identifier,
) -> CustomResult<U, ValidationError> {
U::convert_back(state, self, key, key_manager_identifier).await
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/routing.rs | crates/hyperswitch_domain_models/src/routing.rs | use std::collections::HashMap;
use api_models::{enums as api_enums, routing};
use common_utils::id_type;
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingData {
pub routed_through: Option<String>,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub routing_info: PaymentRoutingInfo,
pub algorithm: Option<routing::StraightThroughAlgorithm>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingData {
// TODO: change this to RoutableConnectors enum
pub routed_through: Option<String>,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub pre_routing_connector_choice: Option<PreRoutingConnectorChoice>,
pub algorithm_requested: Option<id_type::RoutingId>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
#[serde(from = "PaymentRoutingInfoSerde", into = "PaymentRoutingInfoSerde")]
pub struct PaymentRoutingInfo {
pub algorithm: Option<routing::StraightThroughAlgorithm>,
pub pre_routing_results:
Option<HashMap<api_enums::PaymentMethodType, PreRoutingConnectorChoice>>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
#[serde(untagged)]
pub enum PreRoutingConnectorChoice {
Single(routing::RoutableConnectorChoice),
Multiple(Vec<routing::RoutableConnectorChoice>),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentRoutingInfoInner {
pub algorithm: Option<routing::StraightThroughAlgorithm>,
pub pre_routing_results:
Option<HashMap<api_enums::PaymentMethodType, PreRoutingConnectorChoice>>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum PaymentRoutingInfoSerde {
OnlyAlgorithm(Box<routing::StraightThroughAlgorithm>),
WithDetails(Box<PaymentRoutingInfoInner>),
}
impl From<PaymentRoutingInfoSerde> for PaymentRoutingInfo {
fn from(value: PaymentRoutingInfoSerde) -> Self {
match value {
PaymentRoutingInfoSerde::OnlyAlgorithm(algo) => Self {
algorithm: Some(*algo),
pre_routing_results: None,
},
PaymentRoutingInfoSerde::WithDetails(details) => Self {
algorithm: details.algorithm,
pre_routing_results: details.pre_routing_results,
},
}
}
}
impl From<PaymentRoutingInfo> for PaymentRoutingInfoSerde {
fn from(value: PaymentRoutingInfo) -> Self {
Self::WithDetails(Box::new(PaymentRoutingInfoInner {
algorithm: value.algorithm,
pre_routing_results: value.pre_routing_results,
}))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/ext_traits.rs | crates/hyperswitch_domain_models/src/ext_traits.rs | use common_utils::{
errors::{self, CustomResult},
ext_traits::ValueExt,
fp_utils::when,
};
use error_stack::ResultExt;
use crate::errors::api_error_response;
pub type DomainResult<T> = CustomResult<T, api_error_response::ApiErrorResponse>;
pub trait OptionExt<T> {
fn check_value_present(&self, field_name: &'static str) -> DomainResult<()>;
fn get_required_value(self, field_name: &'static str) -> DomainResult<T>;
fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError>
where
T: AsRef<str>,
E: std::str::FromStr,
// Requirement for converting the `Err` variant of `FromStr` to `Report<Err>`
<E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static;
fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError>
where
T: ValueExt,
U: serde::de::DeserializeOwned;
fn update_value(&mut self, value: Option<T>);
}
impl<T> OptionExt<T> for Option<T> {
fn check_value_present(&self, field_name: &'static str) -> DomainResult<()> {
when(self.is_none(), || {
Err(error_stack::Report::new(
api_error_response::ApiErrorResponse::MissingRequiredField { field_name },
)
.attach_printable(format!("Missing required field {field_name}")))
})
}
// This will allow the error message that was generated in this function to point to the call site
#[track_caller]
fn get_required_value(self, field_name: &'static str) -> DomainResult<T> {
match self {
Some(v) => Ok(v),
None => Err(error_stack::Report::new(
api_error_response::ApiErrorResponse::MissingRequiredField { field_name },
)
.attach_printable(format!("Missing required field {field_name}"))),
}
}
fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError>
where
T: AsRef<str>,
E: std::str::FromStr,
<E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static,
{
let value = self
.get_required_value(enum_name)
.change_context(errors::ParsingError::UnknownError)?;
E::from_str(value.as_ref())
.change_context(errors::ParsingError::UnknownError)
.attach_printable_lazy(|| format!("Invalid {{ {enum_name} }} "))
}
fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError>
where
T: ValueExt,
U: serde::de::DeserializeOwned,
{
let value = self
.get_required_value(type_name)
.change_context(errors::ParsingError::UnknownError)?;
value.parse_value(type_name)
}
fn update_value(&mut self, value: Self) {
if let Some(a) = value {
*self = Some(a)
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/disputes.rs | crates/hyperswitch_domain_models/src/disputes.rs | use crate::errors;
pub struct DisputeListConstraints {
pub dispute_id: Option<String>,
pub payment_id: Option<common_utils::id_type::PaymentId>,
pub limit: Option<u32>,
pub offset: Option<u32>,
pub profile_id: Option<Vec<common_utils::id_type::ProfileId>>,
pub dispute_status: Option<Vec<common_enums::DisputeStatus>>,
pub dispute_stage: Option<Vec<common_enums::DisputeStage>>,
pub reason: Option<String>,
pub connector: Option<Vec<String>>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub currency: Option<Vec<common_enums::Currency>>,
pub time_range: Option<common_utils::types::TimeRange>,
}
impl
TryFrom<(
api_models::disputes::DisputeListGetConstraints,
Option<Vec<common_utils::id_type::ProfileId>>,
)> for DisputeListConstraints
{
type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>;
fn try_from(
(value, auth_profile_id_list): (
api_models::disputes::DisputeListGetConstraints,
Option<Vec<common_utils::id_type::ProfileId>>,
),
) -> Result<Self, Self::Error> {
let api_models::disputes::DisputeListGetConstraints {
dispute_id,
payment_id,
limit,
offset,
profile_id,
dispute_status,
dispute_stage,
reason,
connector,
merchant_connector_id,
currency,
time_range,
} = value;
let profile_id_from_request_body = profile_id;
// Match both the profile ID from the request body and the list of authenticated profile IDs coming from auth layer
let profile_id_list = match (profile_id_from_request_body, auth_profile_id_list) {
(None, None) => None,
// Case when the request body profile ID is None, but authenticated profile IDs are available, return the auth list
(None, Some(auth_profile_id_list)) => Some(auth_profile_id_list),
// Case when the request body profile ID is provided, but the auth list is None, create a vector with the request body profile ID
(Some(profile_id_from_request_body), None) => Some(vec![profile_id_from_request_body]),
(Some(profile_id_from_request_body), Some(auth_profile_id_list)) => {
// Check if the profile ID from the request body is present in the authenticated profile ID list
let profile_id_from_request_body_is_available_in_auth_profile_id_list =
auth_profile_id_list.contains(&profile_id_from_request_body);
if profile_id_from_request_body_is_available_in_auth_profile_id_list {
Some(vec![profile_id_from_request_body])
} else {
// If the profile ID is not valid, return an error indicating access is not available
return Err(error_stack::Report::new(
errors::api_error_response::ApiErrorResponse::PreconditionFailed {
message: format!(
"Access not available for the given profile_id {profile_id_from_request_body:?}",
),
},
));
}
}
};
Ok(Self {
dispute_id,
payment_id,
limit,
offset,
profile_id: profile_id_list,
dispute_status,
dispute_stage,
reason,
connector,
merchant_connector_id,
currency,
time_range,
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_data_v2.rs | crates/hyperswitch_domain_models/src/router_data_v2.rs | pub mod flow_common_types;
use std::{marker::PhantomData, ops::Deref};
use common_utils::id_type;
#[cfg(feature = "frm")]
pub use flow_common_types::FrmFlowData;
#[cfg(feature = "payouts")]
pub use flow_common_types::PayoutFlowData;
pub use flow_common_types::{
AccessTokenFlowData, AuthenticationTokenFlowData, DisputesFlowData,
ExternalAuthenticationFlowData, ExternalVaultProxyFlowData, FilesFlowData,
MandateRevokeFlowData, PaymentFlowData, RefundFlowData, UasFlowData, VaultConnectorFlowData,
WebhookSourceVerifyData,
};
use crate::router_data::{ConnectorAuthType, ErrorResponse};
#[derive(Debug, Clone)]
pub struct RouterDataV2<Flow, ResourceCommonData, FlowSpecificRequest, FlowSpecificResponse> {
pub flow: PhantomData<Flow>,
pub tenant_id: id_type::TenantId,
pub resource_common_data: ResourceCommonData,
pub connector_auth_type: ConnectorAuthType,
/// Contains flow-specific data required to construct a request and send it to the connector.
pub request: FlowSpecificRequest,
/// Contains flow-specific data that the connector responds with.
pub response: Result<FlowSpecificResponse, ErrorResponse>,
}
impl<Flow, ResourceCommonData, FlowSpecificRequest, FlowSpecificResponse> Deref
for RouterDataV2<Flow, ResourceCommonData, FlowSpecificRequest, FlowSpecificResponse>
{
type Target = ResourceCommonData;
fn deref(&self) -> &Self::Target {
&self.resource_common_data
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_flow_types.rs | crates/hyperswitch_domain_models/src/router_flow_types.rs | pub mod access_token_auth;
pub mod authentication;
pub mod dispute;
pub mod files;
pub mod fraud_check;
pub mod mandate_revoke;
pub mod payments;
pub mod payouts;
pub mod refunds;
pub mod revenue_recovery;
pub mod subscriptions;
pub mod unified_authentication_service;
pub mod vault;
pub mod webhooks;
pub use access_token_auth::*;
pub use dispute::*;
pub use files::*;
pub use fraud_check::*;
pub use payments::*;
pub use payouts::*;
pub use refunds::*;
pub use revenue_recovery::*;
pub use subscriptions::*;
pub use unified_authentication_service::*;
pub use vault::*;
pub use webhooks::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/revenue_recovery.rs | crates/hyperswitch_domain_models/src/revenue_recovery.rs | use api_models::{payments as api_payments, webhooks};
use common_enums::enums as common_enums;
use common_types::primitive_wrappers;
use common_utils::{id_type, pii, types as util_types};
use time::PrimitiveDateTime;
use crate::{
payments,
router_response_types::revenue_recovery::{
BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse,
},
ApiModelToDieselModelConvertor,
};
/// Recovery payload is unified struct constructed from billing connectors
#[derive(Debug)]
pub struct RevenueRecoveryAttemptData {
/// transaction amount against invoice, accepted in minor unit.
pub amount: util_types::MinorUnit,
/// currency of the transaction
pub currency: common_enums::Currency,
/// merchant reference id at billing connector. ex: invoice_id
pub merchant_reference_id: id_type::PaymentReferenceId,
/// transaction id reference at payment connector
pub connector_transaction_id: Option<util_types::ConnectorTransactionId>,
/// error code sent by billing connector.
pub error_code: Option<String>,
/// error message sent by billing connector.
pub error_message: Option<String>,
/// mandate token at payment processor end.
pub processor_payment_method_token: String,
/// customer id at payment connector for which mandate is attached.
pub connector_customer_id: String,
/// Payment gateway identifier id at billing processor.
pub connector_account_reference_id: String,
/// timestamp at which transaction has been created at billing connector
pub transaction_created_at: Option<PrimitiveDateTime>,
/// transaction status at billing connector equivalent to payment attempt status.
pub status: common_enums::AttemptStatus,
/// payment method of payment attempt.
pub payment_method_type: common_enums::PaymentMethod,
/// payment method sub type of the payment attempt.
pub payment_method_sub_type: common_enums::PaymentMethodType,
/// This field can be returned for both approved and refused Mastercard payments.
/// This code provides additional information about the type of transaction or the reason why the payment failed.
/// If the payment failed, the network advice code gives guidance on if and when you can retry the payment.
pub network_advice_code: Option<String>,
/// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed.
pub network_decline_code: Option<String>,
/// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better.
pub network_error_message: Option<String>,
/// Number of attempts made for an invoice
pub retry_count: Option<u16>,
/// Time when next invoice will be generated which will be equal to the end time of the current invoice
pub invoice_next_billing_time: Option<PrimitiveDateTime>,
/// Time at which the invoice created
pub invoice_billing_started_at_time: Option<PrimitiveDateTime>,
/// stripe specific id used to validate duplicate attempts in revenue recovery flow
pub charge_id: Option<String>,
/// Additional card details
pub card_info: api_payments::AdditionalCardInfo,
}
/// This is unified struct for Revenue Recovery Invoice Data and it is constructed from billing connectors
#[derive(Debug, Clone)]
pub struct RevenueRecoveryInvoiceData {
/// invoice amount at billing connector
pub amount: util_types::MinorUnit,
/// currency of the amount.
pub currency: common_enums::Currency,
/// merchant reference id at billing connector. ex: invoice_id
pub merchant_reference_id: id_type::PaymentReferenceId,
/// billing address id of the invoice
pub billing_address: Option<api_payments::Address>,
/// Retry count of the invoice
pub retry_count: Option<u16>,
/// Ending date of the invoice or the Next billing time of the Subscription
pub next_billing_at: Option<PrimitiveDateTime>,
/// Invoice Starting Time
pub billing_started_at: Option<PrimitiveDateTime>,
/// metadata of the merchant
pub metadata: Option<pii::SecretSerdeValue>,
/// Allow partial authorization for this payment
pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,
}
#[derive(Clone, Debug)]
pub struct RecoveryPaymentIntent {
pub payment_id: id_type::GlobalPaymentId,
pub status: common_enums::IntentStatus,
pub feature_metadata: Option<api_payments::FeatureMetadata>,
pub merchant_id: id_type::MerchantId,
pub merchant_reference_id: Option<id_type::PaymentReferenceId>,
pub invoice_amount: util_types::MinorUnit,
pub invoice_currency: common_enums::Currency,
pub created_at: Option<PrimitiveDateTime>,
pub billing_address: Option<api_payments::Address>,
}
#[derive(Clone, Debug)]
pub struct RecoveryPaymentAttempt {
pub attempt_id: id_type::GlobalAttemptId,
pub attempt_status: common_enums::AttemptStatus,
pub feature_metadata: Option<api_payments::PaymentAttemptFeatureMetadata>,
pub amount: util_types::MinorUnit,
pub network_advice_code: Option<String>,
pub network_decline_code: Option<String>,
pub error_code: Option<String>,
pub created_at: PrimitiveDateTime,
}
impl RecoveryPaymentAttempt {
pub fn get_attempt_triggered_by(&self) -> Option<common_enums::TriggeredBy> {
self.feature_metadata.as_ref().and_then(|metadata| {
metadata
.revenue_recovery
.as_ref()
.map(|recovery| recovery.attempt_triggered_by)
})
}
}
impl From<&RevenueRecoveryInvoiceData> for api_payments::AmountDetails {
fn from(data: &RevenueRecoveryInvoiceData) -> Self {
let amount = api_payments::AmountDetailsSetter {
order_amount: data.amount.into(),
currency: data.currency,
shipping_cost: None,
order_tax_amount: None,
skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip,
skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip,
surcharge_amount: None,
tax_on_surcharge: None,
};
Self::new(amount)
}
}
impl From<&RevenueRecoveryInvoiceData> for api_payments::PaymentsCreateIntentRequest {
fn from(data: &RevenueRecoveryInvoiceData) -> Self {
let amount_details = api_payments::AmountDetails::from(data);
Self {
amount_details,
merchant_reference_id: Some(data.merchant_reference_id.clone()),
routing_algorithm_id: None,
// Payments in the revenue recovery flow are always recurring transactions,
// so capture method will be always automatic.
capture_method: Some(common_enums::CaptureMethod::Automatic),
authentication_type: Some(common_enums::AuthenticationType::NoThreeDs),
billing: data.billing_address.clone(),
shipping: None,
customer_id: None,
customer_present: Some(common_enums::PresenceOfCustomerDuringPayment::Absent),
description: None,
return_url: None,
setup_future_usage: Some(common_enums::FutureUsage::OffSession),
apply_mit_exemption: None,
statement_descriptor: None,
order_details: None,
allowed_payment_method_types: None,
metadata: data.metadata.clone(),
connector_metadata: None,
feature_metadata: None,
payment_link_enabled: None,
payment_link_config: None,
request_incremental_authorization: None,
session_expiry: None,
frm_metadata: None,
request_external_three_ds_authentication: None,
force_3ds_challenge: None,
merchant_connector_details: None,
enable_partial_authorization: data.enable_partial_authorization,
}
}
}
impl From<&BillingConnectorInvoiceSyncResponse> for RevenueRecoveryInvoiceData {
fn from(data: &BillingConnectorInvoiceSyncResponse) -> Self {
Self {
amount: data.amount,
currency: data.currency,
merchant_reference_id: data.merchant_reference_id.clone(),
billing_address: data.billing_address.clone(),
retry_count: data.retry_count,
next_billing_at: data.ends_at,
billing_started_at: data.created_at,
metadata: None,
enable_partial_authorization: None,
}
}
}
impl
From<(
&BillingConnectorPaymentsSyncResponse,
&RevenueRecoveryInvoiceData,
)> for RevenueRecoveryAttemptData
{
fn from(
data: (
&BillingConnectorPaymentsSyncResponse,
&RevenueRecoveryInvoiceData,
),
) -> Self {
let billing_connector_payment_details = data.0;
let invoice_details = data.1;
Self {
amount: billing_connector_payment_details.amount,
currency: billing_connector_payment_details.currency,
merchant_reference_id: billing_connector_payment_details
.merchant_reference_id
.clone(),
connector_transaction_id: billing_connector_payment_details
.connector_transaction_id
.clone(),
error_code: billing_connector_payment_details.error_code.clone(),
error_message: billing_connector_payment_details.error_message.clone(),
processor_payment_method_token: billing_connector_payment_details
.processor_payment_method_token
.clone(),
connector_customer_id: billing_connector_payment_details
.connector_customer_id
.clone(),
connector_account_reference_id: billing_connector_payment_details
.connector_account_reference_id
.clone(),
transaction_created_at: billing_connector_payment_details.transaction_created_at,
status: billing_connector_payment_details.status,
payment_method_type: billing_connector_payment_details.payment_method_type,
payment_method_sub_type: billing_connector_payment_details.payment_method_sub_type,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
retry_count: invoice_details.retry_count,
invoice_next_billing_time: invoice_details.next_billing_at,
charge_id: billing_connector_payment_details.charge_id.clone(),
invoice_billing_started_at_time: invoice_details.billing_started_at,
card_info: billing_connector_payment_details.card_info.clone(),
}
}
}
impl From<&RevenueRecoveryAttemptData> for api_payments::PaymentAttemptAmountDetails {
fn from(data: &RevenueRecoveryAttemptData) -> Self {
Self {
net_amount: data.amount,
amount_to_capture: None,
surcharge_amount: None,
tax_on_surcharge: None,
amount_capturable: data.amount,
shipping_cost: None,
order_tax_amount: None,
amount_captured: None,
}
}
}
impl From<&RevenueRecoveryAttemptData> for Option<api_payments::RecordAttemptErrorDetails> {
fn from(data: &RevenueRecoveryAttemptData) -> Self {
data.error_code
.as_ref()
.zip(data.error_message.clone())
.map(|(code, message)| api_payments::RecordAttemptErrorDetails {
code: code.to_string(),
message: message.to_string(),
network_advice_code: data.network_advice_code.clone(),
network_decline_code: data.network_decline_code.clone(),
network_error_message: data.network_error_message.clone(),
})
}
}
impl From<&payments::PaymentIntent> for RecoveryPaymentIntent {
fn from(payment_intent: &payments::PaymentIntent) -> Self {
Self {
payment_id: payment_intent.id.clone(),
status: payment_intent.status,
feature_metadata: payment_intent
.feature_metadata
.clone()
.map(|feature_metadata| feature_metadata.convert_back()),
merchant_reference_id: payment_intent.merchant_reference_id.clone(),
invoice_amount: payment_intent.amount_details.order_amount,
invoice_currency: payment_intent.amount_details.currency,
billing_address: payment_intent
.billing_address
.clone()
.map(|address| api_payments::Address::from(address.into_inner())),
merchant_id: payment_intent.merchant_id.clone(),
created_at: Some(payment_intent.created_at),
}
}
}
impl From<&payments::payment_attempt::PaymentAttempt> for RecoveryPaymentAttempt {
fn from(payment_attempt: &payments::payment_attempt::PaymentAttempt) -> Self {
Self {
attempt_id: payment_attempt.id.clone(),
attempt_status: payment_attempt.status,
feature_metadata: payment_attempt
.feature_metadata
.clone()
.map(
|feature_metadata| api_payments::PaymentAttemptFeatureMetadata {
revenue_recovery: feature_metadata.revenue_recovery.map(|recovery| {
api_payments::PaymentAttemptRevenueRecoveryData {
attempt_triggered_by: recovery.attempt_triggered_by,
charge_id: recovery.charge_id,
}
}),
},
),
amount: payment_attempt.amount_details.get_net_amount(),
network_advice_code: payment_attempt
.error
.clone()
.and_then(|error| error.network_advice_code),
network_decline_code: payment_attempt
.error
.clone()
.and_then(|error| error.network_decline_code),
error_code: payment_attempt
.error
.as_ref()
.map(|error| error.code.clone()),
created_at: payment_attempt.created_at,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/platform.rs | crates/hyperswitch_domain_models/src/platform.rs | pub use crate::{merchant_account::MerchantAccount, merchant_key_store::MerchantKeyStore};
/// Provider = The business owner or the governing entity in the hierarchy.
/// In a platform-connected setup this is represented by the platform merchant.
/// For a standard merchant, both provider and processor are represented by the same entity.
#[derive(Clone, Debug)]
pub struct Provider {
account: MerchantAccount,
key_store: MerchantKeyStore,
}
impl Provider {
fn new(account: MerchantAccount, key_store: MerchantKeyStore) -> Self {
Self { account, key_store }
}
/// Returns a reference to the merchant account of the provider.
pub fn get_account(&self) -> &MerchantAccount {
&self.account
}
/// Returns a reference to the key store associated with the provider.
pub fn get_key_store(&self) -> &MerchantKeyStore {
&self.key_store
}
}
/// Processor = The merchant account whose processor credentials are used
/// to execute the operation.
#[derive(Clone, Debug)]
pub struct Processor {
account: MerchantAccount,
key_store: MerchantKeyStore,
}
impl Processor {
fn new(account: MerchantAccount, key_store: MerchantKeyStore) -> Self {
Self { account, key_store }
}
/// Returns a reference to the merchant account of the processor.
pub fn get_account(&self) -> &MerchantAccount {
&self.account
}
/// Returns a reference to the key store associated with the processor.
pub fn get_key_store(&self) -> &MerchantKeyStore {
&self.key_store
}
}
/// Initiator = The entity that initiated the operation.
#[derive(Clone, Debug)]
pub enum Initiator {
Api {
merchant_id: common_utils::id_type::MerchantId,
merchant_account_type: common_enums::MerchantAccountType,
},
Jwt {
user_id: String,
},
Admin,
}
/// Platform holds both Provider and Processor together.
/// This struct makes it possible to distinguish the business owner for the org versus whose processor credentials are used for execution.
/// For a standard merchant flow, provider == processor.
#[derive(Clone, Debug)]
pub struct Platform {
provider: Box<Provider>,
processor: Box<Processor>,
initiator: Option<Initiator>,
}
impl Platform {
/// Creates a Platform pairing from two merchant identities:
/// one acting as provider and one as processor
/// Standard merchants can pass the same account/key_store for both provider and processor
pub fn new(
provider_account: MerchantAccount,
provider_key_store: MerchantKeyStore,
processor_account: MerchantAccount,
processor_key_store: MerchantKeyStore,
initiator: Option<Initiator>,
) -> Self {
let provider = Provider::new(provider_account, provider_key_store);
let processor = Processor::new(processor_account, processor_key_store);
Self {
provider: Box::new(provider),
processor: Box::new(processor),
initiator,
}
}
/// Returns a reference to the provider.
pub fn get_provider(&self) -> &Provider {
&self.provider
}
/// Returns a reference to the processor.
pub fn get_processor(&self) -> &Processor {
&self.processor
}
/// Returns a reference to the initiator.
/// Returns None if the initiator is not known or not applicable.
pub fn get_initiator(&self) -> Option<&Initiator> {
self.initiator.as_ref()
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/cards_info.rs | crates/hyperswitch_domain_models/src/cards_info.rs | use common_utils::errors;
use diesel_models::cards_info;
#[async_trait::async_trait]
pub trait CardsInfoInterface {
type Error;
async fn get_card_info(
&self,
_card_iin: &str,
) -> errors::CustomResult<Option<cards_info::CardInfo>, Self::Error>;
async fn add_card_info(
&self,
data: cards_info::CardInfo,
) -> errors::CustomResult<cards_info::CardInfo, Self::Error>;
async fn update_card_info(
&self,
card_iin: String,
data: cards_info::UpdateCardInfo,
) -> errors::CustomResult<cards_info::CardInfo, Self::Error>;
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/merchant_account.rs | crates/hyperswitch_domain_models/src/merchant_account.rs | use common_utils::{
crypto::{OptionalEncryptableName, OptionalEncryptableValue},
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
ext_traits::ValueExt,
pii, type_name,
types::keymanager::{self},
};
use diesel_models::{
enums::MerchantStorageScheme, merchant_account::MerchantAccountUpdateInternal,
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use router_env::logger;
use crate::{
behaviour::Conversion,
merchant_key_store,
type_encryption::{crypto_operation, AsyncLift, CryptoOperation},
};
#[cfg(feature = "v1")]
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantAccount {
merchant_id: common_utils::id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub merchant_name: OptionalEncryptableName,
pub merchant_details: OptionalEncryptableValue,
pub webhook_details: Option<diesel_models::business_profile::WebhookDetails>,
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub publishable_key: String,
pub storage_scheme: MerchantStorageScheme,
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub primary_business_details: serde_json::Value,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub intent_fulfillment_time: Option<i64>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub is_recon_enabled: bool,
pub default_profile: Option<common_utils::id_type::ProfileId>,
pub recon_status: diesel_models::enums::ReconStatus,
pub payment_link_config: Option<serde_json::Value>,
pub pm_collect_link_config: Option<serde_json::Value>,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
#[cfg(feature = "v1")]
#[derive(Clone)]
/// Set the private fields of merchant account
pub struct MerchantAccountSetter {
pub merchant_id: common_utils::id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub merchant_name: OptionalEncryptableName,
pub merchant_details: OptionalEncryptableValue,
pub webhook_details: Option<diesel_models::business_profile::WebhookDetails>,
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub publishable_key: String,
pub storage_scheme: MerchantStorageScheme,
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub primary_business_details: serde_json::Value,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub intent_fulfillment_time: Option<i64>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub is_recon_enabled: bool,
pub default_profile: Option<common_utils::id_type::ProfileId>,
pub recon_status: diesel_models::enums::ReconStatus,
pub payment_link_config: Option<serde_json::Value>,
pub pm_collect_link_config: Option<serde_json::Value>,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
#[cfg(feature = "v1")]
impl From<MerchantAccountSetter> for MerchantAccount {
fn from(item: MerchantAccountSetter) -> Self {
Self {
merchant_id: item.merchant_id,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
payment_response_hash_key: item.payment_response_hash_key,
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
merchant_name: item.merchant_name,
merchant_details: item.merchant_details,
webhook_details: item.webhook_details,
sub_merchants_enabled: item.sub_merchants_enabled,
parent_merchant_id: item.parent_merchant_id,
publishable_key: item.publishable_key,
storage_scheme: item.storage_scheme,
locker_id: item.locker_id,
metadata: item.metadata,
routing_algorithm: item.routing_algorithm,
primary_business_details: item.primary_business_details,
frm_routing_algorithm: item.frm_routing_algorithm,
created_at: item.created_at,
modified_at: item.modified_at,
intent_fulfillment_time: item.intent_fulfillment_time,
payout_routing_algorithm: item.payout_routing_algorithm,
organization_id: item.organization_id,
is_recon_enabled: item.is_recon_enabled,
default_profile: item.default_profile,
recon_status: item.recon_status,
payment_link_config: item.payment_link_config,
pm_collect_link_config: item.pm_collect_link_config,
version: item.version,
is_platform_account: item.is_platform_account,
product_type: item.product_type,
merchant_account_type: item.merchant_account_type,
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone)]
/// Set the private fields of merchant account
pub struct MerchantAccountSetter {
pub id: common_utils::id_type::MerchantId,
pub merchant_name: OptionalEncryptableName,
pub merchant_details: OptionalEncryptableValue,
pub publishable_key: String,
pub storage_scheme: MerchantStorageScheme,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub organization_id: common_utils::id_type::OrganizationId,
pub recon_status: diesel_models::enums::ReconStatus,
pub is_platform_account: bool,
pub version: common_enums::ApiVersion,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
#[cfg(feature = "v2")]
impl From<MerchantAccountSetter> for MerchantAccount {
fn from(item: MerchantAccountSetter) -> Self {
let MerchantAccountSetter {
id,
merchant_name,
merchant_details,
publishable_key,
storage_scheme,
metadata,
created_at,
modified_at,
organization_id,
recon_status,
is_platform_account,
version,
product_type,
merchant_account_type,
} = item;
Self {
id,
merchant_name,
merchant_details,
publishable_key,
storage_scheme,
metadata,
created_at,
modified_at,
organization_id,
recon_status,
is_platform_account,
version,
product_type,
merchant_account_type,
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantAccount {
id: common_utils::id_type::MerchantId,
pub merchant_name: OptionalEncryptableName,
pub merchant_details: OptionalEncryptableValue,
pub publishable_key: String,
pub storage_scheme: MerchantStorageScheme,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub organization_id: common_utils::id_type::OrganizationId,
pub recon_status: diesel_models::enums::ReconStatus,
pub is_platform_account: bool,
pub version: common_enums::ApiVersion,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
impl MerchantAccount {
#[cfg(feature = "v1")]
/// Get the unique identifier of MerchantAccount
pub fn get_id(&self) -> &common_utils::id_type::MerchantId {
&self.merchant_id
}
#[cfg(feature = "v2")]
/// Get the unique identifier of MerchantAccount
pub fn get_id(&self) -> &common_utils::id_type::MerchantId {
&self.id
}
/// Get the organization_id from MerchantAccount
pub fn get_org_id(&self) -> &common_utils::id_type::OrganizationId {
&self.organization_id
}
/// Get the merchant_details from MerchantAccount
pub fn get_merchant_details(&self) -> &OptionalEncryptableValue {
&self.merchant_details
}
/// Extract merchant_tax_registration_id from merchant_details
pub fn get_merchant_tax_registration_id(&self) -> Option<Secret<String>> {
self.merchant_details.as_ref().and_then(|details| {
details
.get_inner()
.peek()
.get("merchant_tax_registration_id")
.and_then(|id| id.as_str().map(|s| Secret::new(s.to_string())))
})
}
/// Check whether the merchant account is a platform account
pub fn is_platform_account(&self) -> bool {
matches!(
self.merchant_account_type,
common_enums::MerchantAccountType::Platform
)
}
}
#[cfg(feature = "v1")]
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum MerchantAccountUpdate {
Update {
merchant_name: OptionalEncryptableName,
merchant_details: OptionalEncryptableValue,
return_url: Option<String>,
webhook_details: Option<diesel_models::business_profile::WebhookDetails>,
sub_merchants_enabled: Option<bool>,
parent_merchant_id: Option<common_utils::id_type::MerchantId>,
enable_payment_response_hash: Option<bool>,
payment_response_hash_key: Option<String>,
redirect_to_merchant_with_http_post: Option<bool>,
publishable_key: Option<String>,
locker_id: Option<String>,
metadata: Option<pii::SecretSerdeValue>,
routing_algorithm: Option<serde_json::Value>,
primary_business_details: Option<serde_json::Value>,
intent_fulfillment_time: Option<i64>,
frm_routing_algorithm: Option<serde_json::Value>,
payout_routing_algorithm: Option<serde_json::Value>,
default_profile: Option<Option<common_utils::id_type::ProfileId>>,
payment_link_config: Option<serde_json::Value>,
pm_collect_link_config: Option<serde_json::Value>,
},
StorageSchemeUpdate {
storage_scheme: MerchantStorageScheme,
},
ReconUpdate {
recon_status: diesel_models::enums::ReconStatus,
},
UnsetDefaultProfile,
ModifiedAtUpdate,
ToPlatformAccount,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone)]
pub enum MerchantAccountUpdate {
Update {
merchant_name: OptionalEncryptableName,
merchant_details: OptionalEncryptableValue,
publishable_key: Option<String>,
metadata: Option<Box<pii::SecretSerdeValue>>,
},
StorageSchemeUpdate {
storage_scheme: MerchantStorageScheme,
},
ReconUpdate {
recon_status: diesel_models::enums::ReconStatus,
},
ModifiedAtUpdate,
ToPlatformAccount,
}
#[cfg(feature = "v1")]
impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
fn from(merchant_account_update: MerchantAccountUpdate) -> Self {
let now = date_time::now();
match merchant_account_update {
MerchantAccountUpdate::Update {
merchant_name,
merchant_details,
webhook_details,
return_url,
routing_algorithm,
sub_merchants_enabled,
parent_merchant_id,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
publishable_key,
locker_id,
metadata,
primary_business_details,
intent_fulfillment_time,
frm_routing_algorithm,
payout_routing_algorithm,
default_profile,
payment_link_config,
pm_collect_link_config,
} => Self {
merchant_name: merchant_name.map(Encryption::from),
merchant_details: merchant_details.map(Encryption::from),
frm_routing_algorithm,
webhook_details,
routing_algorithm,
sub_merchants_enabled,
parent_merchant_id,
return_url,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
publishable_key,
locker_id,
metadata,
primary_business_details,
modified_at: now,
intent_fulfillment_time,
payout_routing_algorithm,
default_profile,
payment_link_config,
pm_collect_link_config,
storage_scheme: None,
organization_id: None,
is_recon_enabled: None,
recon_status: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self {
storage_scheme: Some(storage_scheme),
modified_at: now,
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: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
default_profile: None,
recon_status: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ReconUpdate { recon_status } => Self {
recon_status: Some(recon_status),
modified_at: now,
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,
storage_scheme: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
default_profile: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::UnsetDefaultProfile => Self {
default_profile: Some(None),
modified_at: now,
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,
storage_scheme: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
recon_status: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ModifiedAtUpdate => Self {
modified_at: now,
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,
storage_scheme: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
default_profile: None,
recon_status: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ToPlatformAccount => Self {
modified_at: now,
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,
storage_scheme: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
default_profile: None,
recon_status: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: Some(true),
product_type: None,
},
}
}
}
#[cfg(feature = "v2")]
impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
fn from(merchant_account_update: MerchantAccountUpdate) -> Self {
let now = date_time::now();
match merchant_account_update {
MerchantAccountUpdate::Update {
merchant_name,
merchant_details,
publishable_key,
metadata,
} => Self {
merchant_name: merchant_name.map(Encryption::from),
merchant_details: merchant_details.map(Encryption::from),
publishable_key,
metadata: metadata.map(|metadata| *metadata),
modified_at: now,
storage_scheme: None,
organization_id: None,
recon_status: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self {
storage_scheme: Some(storage_scheme),
modified_at: now,
merchant_name: None,
merchant_details: None,
publishable_key: None,
metadata: None,
organization_id: None,
recon_status: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ReconUpdate { recon_status } => Self {
recon_status: Some(recon_status),
modified_at: now,
merchant_name: None,
merchant_details: None,
publishable_key: None,
storage_scheme: None,
metadata: None,
organization_id: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ModifiedAtUpdate => Self {
modified_at: now,
merchant_name: None,
merchant_details: None,
publishable_key: None,
storage_scheme: None,
metadata: None,
organization_id: None,
recon_status: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ToPlatformAccount => Self {
modified_at: now,
merchant_name: None,
merchant_details: None,
publishable_key: None,
storage_scheme: None,
metadata: None,
organization_id: None,
recon_status: None,
is_platform_account: Some(true),
product_type: None,
},
}
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl Conversion for MerchantAccount {
type DstType = diesel_models::merchant_account::MerchantAccount;
type NewDstType = diesel_models::merchant_account::MerchantAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let id = self.get_id().to_owned();
let setter = diesel_models::merchant_account::MerchantAccountSetter {
id,
merchant_name: self.merchant_name.map(|name| name.into()),
merchant_details: self.merchant_details.map(|details| details.into()),
publishable_key: Some(self.publishable_key),
storage_scheme: self.storage_scheme,
metadata: self.metadata,
created_at: self.created_at,
modified_at: self.modified_at,
organization_id: self.organization_id,
recon_status: self.recon_status,
version: common_types::consts::API_VERSION,
is_platform_account: self.is_platform_account,
product_type: self.product_type,
merchant_account_type: self.merchant_account_type,
};
Ok(diesel_models::MerchantAccount::from(setter))
}
async fn convert_back(
state: &keymanager::KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let id = item.get_id().to_owned();
let publishable_key =
item.publishable_key
.ok_or(ValidationError::MissingRequiredField {
field_name: "publishable_key".to_string(),
})?;
async {
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
id,
merchant_name: item
.merchant_name
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
merchant_details: item
.merchant_details
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
publishable_key,
storage_scheme: item.storage_scheme,
metadata: item.metadata,
created_at: item.created_at,
modified_at: item.modified_at,
organization_id: item.organization_id,
recon_status: item.recon_status,
is_platform_account: item.is_platform_account,
version: item.version,
product_type: item.product_type,
merchant_account_type: item.merchant_account_type.unwrap_or_default(),
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting merchant data".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(diesel_models::merchant_account::MerchantAccountNew {
id: self.id,
merchant_name: self.merchant_name.map(Encryption::from),
merchant_details: self.merchant_details.map(Encryption::from),
publishable_key: Some(self.publishable_key),
metadata: self.metadata,
created_at: now,
modified_at: now,
organization_id: self.organization_id,
recon_status: self.recon_status,
version: common_types::consts::API_VERSION,
is_platform_account: self.is_platform_account,
product_type: self
.product_type
.or(Some(common_enums::MerchantProductType::Orchestration)),
merchant_account_type: self.merchant_account_type,
})
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl Conversion for MerchantAccount {
type DstType = diesel_models::merchant_account::MerchantAccount;
type NewDstType = diesel_models::merchant_account::MerchantAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let setter = diesel_models::merchant_account::MerchantAccountSetter {
merchant_id: self.merchant_id,
return_url: self.return_url,
enable_payment_response_hash: self.enable_payment_response_hash,
payment_response_hash_key: self.payment_response_hash_key,
redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post,
merchant_name: self.merchant_name.map(|name| name.into()),
merchant_details: self.merchant_details.map(|details| details.into()),
webhook_details: self.webhook_details,
sub_merchants_enabled: self.sub_merchants_enabled,
parent_merchant_id: self.parent_merchant_id,
publishable_key: Some(self.publishable_key),
storage_scheme: self.storage_scheme,
locker_id: self.locker_id,
metadata: self.metadata,
routing_algorithm: self.routing_algorithm,
primary_business_details: self.primary_business_details,
created_at: self.created_at,
modified_at: self.modified_at,
intent_fulfillment_time: self.intent_fulfillment_time,
frm_routing_algorithm: self.frm_routing_algorithm,
payout_routing_algorithm: self.payout_routing_algorithm,
organization_id: self.organization_id,
is_recon_enabled: self.is_recon_enabled,
default_profile: self.default_profile,
recon_status: self.recon_status,
payment_link_config: self.payment_link_config,
pm_collect_link_config: self.pm_collect_link_config,
version: self.version,
is_platform_account: self.is_platform_account,
product_type: self.product_type,
merchant_account_type: self.merchant_account_type,
};
Ok(diesel_models::MerchantAccount::from(setter))
}
async fn convert_back(
state: &keymanager::KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let merchant_id = item.get_id().to_owned();
let publishable_key =
item.publishable_key
.ok_or(ValidationError::MissingRequiredField {
field_name: "publishable_key".to_string(),
})?;
async {
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
merchant_id,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
payment_response_hash_key: item.payment_response_hash_key,
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
merchant_name: item
.merchant_name
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
merchant_details: item
.merchant_details
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
webhook_details: item.webhook_details,
sub_merchants_enabled: item.sub_merchants_enabled,
parent_merchant_id: item.parent_merchant_id,
publishable_key,
storage_scheme: item.storage_scheme,
locker_id: item.locker_id,
metadata: item.metadata,
routing_algorithm: item.routing_algorithm,
frm_routing_algorithm: item.frm_routing_algorithm,
primary_business_details: item.primary_business_details,
created_at: item.created_at,
modified_at: item.modified_at,
intent_fulfillment_time: item.intent_fulfillment_time,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/subscription.rs | crates/hyperswitch_domain_models/src/subscription.rs | use common_utils::{
errors::{CustomResult, ValidationError},
events::ApiEventMetric,
generate_id_with_default_len,
pii::SecretSerdeValue,
types::keymanager::{self, KeyManagerState},
};
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret};
use time::PrimitiveDateTime;
use crate::{errors::api_error_response::ApiErrorResponse, merchant_key_store::MerchantKeyStore};
const SECRET_SPLIT: &str = "_secret";
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ClientSecret(String);
impl ClientSecret {
pub fn new(secret: String) -> Self {
Self(secret)
}
pub fn get_subscription_id(&self) -> error_stack::Result<String, ApiErrorResponse> {
let sub_id = self
.0
.split(SECRET_SPLIT)
.next()
.ok_or(ApiErrorResponse::MissingRequiredField {
field_name: "client_secret",
})
.attach_printable("Failed to extract subscription_id from client_secret")?;
Ok(sub_id.to_string())
}
}
impl std::fmt::Display for ClientSecret {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl ApiEventMetric for ClientSecret {}
impl From<api_models::subscription::ClientSecret> for ClientSecret {
fn from(api_secret: api_models::subscription::ClientSecret) -> Self {
Self::new(api_secret.as_str().to_string())
}
}
impl From<ClientSecret> for api_models::subscription::ClientSecret {
fn from(domain_secret: ClientSecret) -> Self {
Self::new(domain_secret.to_string())
}
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct Subscription {
pub id: common_utils::id_type::SubscriptionId,
pub status: String,
pub billing_processor: Option<String>,
pub payment_method_id: Option<String>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub client_secret: Option<String>,
pub connector_subscription_id: Option<String>,
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: common_utils::id_type::CustomerId,
pub metadata: Option<SecretSerdeValue>,
pub created_at: PrimitiveDateTime,
pub modified_at: PrimitiveDateTime,
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_reference_id: Option<String>,
pub plan_id: Option<String>,
pub item_price_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub enum SubscriptionStatus {
Active,
Created,
InActive,
Pending,
Trial,
Paused,
Unpaid,
Onetime,
Cancelled,
Failed,
}
impl std::fmt::Display for SubscriptionStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Active => write!(f, "Active"),
Self::Created => write!(f, "Created"),
Self::InActive => write!(f, "InActive"),
Self::Pending => write!(f, "Pending"),
Self::Trial => write!(f, "Trial"),
Self::Paused => write!(f, "Paused"),
Self::Unpaid => write!(f, "Unpaid"),
Self::Onetime => write!(f, "Onetime"),
Self::Cancelled => write!(f, "Cancelled"),
Self::Failed => write!(f, "Failed"),
}
}
}
impl Subscription {
pub fn generate_and_set_client_secret(&mut self) -> Secret<String> {
let client_secret =
generate_id_with_default_len(&format!("{}_secret", self.id.get_string_repr()));
self.client_secret = Some(client_secret.clone());
Secret::new(client_secret)
}
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for Subscription {
type DstType = diesel_models::subscription::Subscription;
type NewDstType = diesel_models::subscription::SubscriptionNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let now = common_utils::date_time::now();
Ok(diesel_models::subscription::Subscription {
id: self.id,
status: self.status,
billing_processor: self.billing_processor,
payment_method_id: self.payment_method_id,
merchant_connector_id: self.merchant_connector_id,
client_secret: self.client_secret,
connector_subscription_id: self.connector_subscription_id,
merchant_id: self.merchant_id,
customer_id: self.customer_id,
metadata: self.metadata.map(|m| m.expose()),
created_at: now,
modified_at: now,
profile_id: self.profile_id,
merchant_reference_id: self.merchant_reference_id,
plan_id: self.plan_id,
item_price_id: self.item_price_id,
})
}
async fn convert_back(
_state: &KeyManagerState,
item: Self::DstType,
_key: &Secret<Vec<u8>>,
_key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
Ok(Self {
id: item.id,
status: item.status,
billing_processor: item.billing_processor,
payment_method_id: item.payment_method_id,
merchant_connector_id: item.merchant_connector_id,
client_secret: item.client_secret,
connector_subscription_id: item.connector_subscription_id,
merchant_id: item.merchant_id,
customer_id: item.customer_id,
metadata: item.metadata.map(SecretSerdeValue::new),
created_at: item.created_at,
modified_at: item.modified_at,
profile_id: item.profile_id,
merchant_reference_id: item.merchant_reference_id,
plan_id: item.plan_id,
item_price_id: item.item_price_id,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::subscription::SubscriptionNew::new(
self.id,
self.status,
self.billing_processor,
self.payment_method_id,
self.merchant_connector_id,
self.client_secret,
self.connector_subscription_id,
self.merchant_id,
self.customer_id,
self.metadata,
self.profile_id,
self.merchant_reference_id,
self.plan_id,
self.item_price_id,
))
}
}
#[async_trait::async_trait]
pub trait SubscriptionInterface {
type Error;
async fn insert_subscription_entry(
&self,
key_store: &MerchantKeyStore,
subscription_new: Subscription,
) -> CustomResult<Subscription, Self::Error>;
async fn find_by_merchant_id_subscription_id(
&self,
key_store: &MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
subscription_id: String,
) -> CustomResult<Subscription, Self::Error>;
async fn update_subscription_entry(
&self,
key_store: &MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
subscription_id: String,
data: SubscriptionUpdate,
) -> CustomResult<Subscription, Self::Error>;
async fn list_by_merchant_id_profile_id(
&self,
key_store: &MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
limit: Option<i64>,
offset: Option<i64>,
) -> CustomResult<Vec<Subscription>, Self::Error>;
}
pub struct SubscriptionUpdate {
pub connector_subscription_id: Option<String>,
pub payment_method_id: Option<String>,
pub status: Option<String>,
pub modified_at: PrimitiveDateTime,
pub plan_id: Option<String>,
pub item_price_id: Option<String>,
}
impl SubscriptionUpdate {
pub fn new(
connector_subscription_id: Option<String>,
payment_method_id: Option<Secret<String>>,
status: Option<String>,
plan_id: Option<String>,
item_price_id: Option<String>,
) -> Self {
Self {
connector_subscription_id,
payment_method_id: payment_method_id.map(|pmid| pmid.peek().clone()),
status,
modified_at: common_utils::date_time::now(),
plan_id,
item_price_id,
}
}
pub fn update_status(status: String) -> Self {
Self::new(None, None, Some(status), None, None)
}
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for SubscriptionUpdate {
type DstType = diesel_models::subscription::SubscriptionUpdate;
type NewDstType = diesel_models::subscription::SubscriptionUpdate;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::subscription::SubscriptionUpdate {
connector_subscription_id: self.connector_subscription_id,
payment_method_id: self.payment_method_id,
status: self.status,
modified_at: self.modified_at,
plan_id: self.plan_id,
item_price_id: self.item_price_id,
})
}
async fn convert_back(
_state: &KeyManagerState,
item: Self::DstType,
_key: &Secret<Vec<u8>>,
_key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
Ok(Self {
connector_subscription_id: item.connector_subscription_id,
payment_method_id: item.payment_method_id,
status: item.status,
modified_at: item.modified_at,
plan_id: item.plan_id,
item_price_id: item.item_price_id,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::subscription::SubscriptionUpdate {
connector_subscription_id: self.connector_subscription_id,
payment_method_id: self.payment_method_id,
status: self.status,
modified_at: self.modified_at,
plan_id: self.plan_id,
item_price_id: self.item_price_id,
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/card_testing_guard_data.rs | crates/hyperswitch_domain_models/src/card_testing_guard_data.rs | use serde::{self, Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct CardTestingGuardData {
pub is_card_ip_blocking_enabled: bool,
pub card_ip_blocking_cache_key: String,
pub is_guest_user_card_blocking_enabled: bool,
pub guest_user_card_blocking_cache_key: String,
pub is_customer_id_blocking_enabled: bool,
pub customer_id_blocking_cache_key: String,
pub card_testing_guard_expiry: i32,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/payment_method_data.rs | crates/hyperswitch_domain_models/src/payment_method_data.rs | #[cfg(feature = "v2")]
use std::str::FromStr;
use api_models::{
mandates,
payment_methods::{self},
payments::{
additional_info as payment_additional_types, AdditionalNetworkTokenInfo, ExtendedCardInfo,
},
};
use common_enums::{enums as api_enums, GooglePayCardFundingSource};
use common_utils::{
errors::CustomResult,
ext_traits::{OptionExt, StringExt},
id_type,
new_type::{
MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode, MaskedUpiVpaId,
},
payout_method_utils,
pii::{self, Email},
};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use time::Date;
use crate::{errors::api_error_response::ApiErrorResponse, router_data::PaymentMethodToken};
// We need to derive Serialize and Deserialize because some parts of payment method data are being
// stored in the database as serde_json::Value
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
pub enum PaymentMethodData {
Card(Card),
CardDetailsForNetworkTransactionId(CardDetailsForNetworkTransactionId),
NetworkTokenDetailsForNetworkTransactionId(NetworkTokenDetailsForNetworkTransactionId),
CardRedirect(CardRedirectData),
Wallet(WalletData),
PayLater(PayLaterData),
BankRedirect(BankRedirectData),
BankDebit(BankDebitData),
BankTransfer(Box<BankTransferData>),
Crypto(CryptoData),
MandatePayment,
Reward,
RealTimePayment(Box<RealTimePaymentData>),
Upi(UpiData),
Voucher(VoucherData),
GiftCard(Box<GiftCardData>),
CardToken(CardToken),
OpenBanking(OpenBankingData),
NetworkToken(NetworkTokenData),
MobilePayment(MobilePaymentData),
}
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
pub enum ExternalVaultPaymentMethodData {
Card(Box<ExternalVaultCard>),
VaultToken(VaultToken),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum RecurringDetails {
MandateId(String),
PaymentMethodId(String),
ProcessorPaymentToken(ProcessorPaymentToken),
/// Network transaction ID and Card Details for MIT payments when payment_method_data
/// is not stored in the application
NetworkTransactionIdAndCardDetails(Box<NetworkTransactionIdAndCardDetails>),
/// Network transaction ID and Network Token Details for MIT payments when payment_method_data
/// is not stored in the application
NetworkTransactionIdAndNetworkTokenDetails(Box<NetworkTransactionIdAndNetworkTokenDetails>),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct ProcessorPaymentToken {
pub processor_payment_token: String,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct NetworkTransactionIdAndCardDetails {
/// The card number
pub card_number: cards::CardNumber,
/// The card's expiry month
pub card_exp_month: Secret<String>,
/// The card's expiry year
pub card_exp_year: Secret<String>,
/// The card holder's name
pub card_holder_name: Option<Secret<String>>,
/// The name of the issuer of card
pub card_issuer: Option<String>,
/// The card network for the card
pub card_network: Option<api_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub card_issuing_country_code: Option<String>,
pub bank_code: Option<String>,
/// The card holder's nick name
pub nick_name: Option<Secret<String>>,
/// The network transaction ID provided by the card network during a CIT (Customer Initiated Transaction),
/// when `setup_future_usage` is set to `off_session`.
pub network_transaction_id: Secret<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct NetworkTransactionIdAndNetworkTokenDetails {
/// The Network Token
pub network_token: cards::NetworkToken,
/// The token's expiry month
pub token_exp_month: Secret<String>,
/// The token's expiry year
pub token_exp_year: Secret<String>,
/// The card network for the card
pub card_network: Option<api_enums::CardNetwork>,
/// The type of the card such as Credit, Debit
pub card_type: Option<String>,
/// The country in which the card was issued
pub card_issuing_country: Option<String>,
/// The bank code of the bank that issued the card
pub bank_code: Option<String>,
/// The card holder's name
pub card_holder_name: Option<Secret<String>>,
/// The name of the issuer of card
pub card_issuer: Option<String>,
/// The card holder's nick name
pub nick_name: Option<Secret<String>>,
/// The ECI(Electronic Commerce Indicator) value for this authentication.
pub eci: Option<String>,
/// The network transaction ID provided by the card network during a Customer Initiated Transaction (CIT)
/// when `setup_future_usage` is set to `off_session`.
pub network_transaction_id: Secret<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub enum ApplePayFlow {
Simplified(api_models::payments::PaymentProcessingDetails),
Manual,
}
impl PaymentMethodData {
pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> {
match self {
Self::Card(_)
| Self::NetworkToken(_)
| Self::CardDetailsForNetworkTransactionId(_)
| Self::NetworkTokenDetailsForNetworkTransactionId(_) => {
Some(common_enums::PaymentMethod::Card)
}
Self::CardRedirect(_) => Some(common_enums::PaymentMethod::CardRedirect),
Self::Wallet(_) => Some(common_enums::PaymentMethod::Wallet),
Self::PayLater(_) => Some(common_enums::PaymentMethod::PayLater),
Self::BankRedirect(_) => Some(common_enums::PaymentMethod::BankRedirect),
Self::BankDebit(_) => Some(common_enums::PaymentMethod::BankDebit),
Self::BankTransfer(_) => Some(common_enums::PaymentMethod::BankTransfer),
Self::Crypto(_) => Some(common_enums::PaymentMethod::Crypto),
Self::Reward => Some(common_enums::PaymentMethod::Reward),
Self::RealTimePayment(_) => Some(common_enums::PaymentMethod::RealTimePayment),
Self::Upi(_) => Some(common_enums::PaymentMethod::Upi),
Self::Voucher(_) => Some(common_enums::PaymentMethod::Voucher),
Self::GiftCard(_) => Some(common_enums::PaymentMethod::GiftCard),
Self::OpenBanking(_) => Some(common_enums::PaymentMethod::OpenBanking),
Self::MobilePayment(_) => Some(common_enums::PaymentMethod::MobilePayment),
Self::CardToken(_) | Self::MandatePayment => None,
}
}
pub fn get_wallet_data(&self) -> Option<&WalletData> {
if let Self::Wallet(wallet_data) = self {
Some(wallet_data)
} else {
None
}
}
pub fn is_network_token_payment_method_data(&self) -> bool {
matches!(self, Self::NetworkToken(_))
}
pub fn get_co_badged_card_data(&self) -> Option<&payment_methods::CoBadgedCardData> {
if let Self::Card(card) = self {
card.co_badged_card_data.as_ref()
} else {
None
}
}
pub fn get_card_data(&self) -> Option<&Card> {
if let Self::Card(card) = self {
Some(card)
} else {
None
}
}
pub fn extract_debit_routing_saving_percentage(
&self,
network: &common_enums::CardNetwork,
) -> Option<f64> {
self.get_co_badged_card_data()?
.co_badged_card_networks_info
.0
.iter()
.find(|info| &info.network == network)
.and_then(|info| info.saving_percentage)
}
}
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct Card {
pub card_number: cards::CardNumber,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub card_cvc: Secret<String>,
pub card_issuer: Option<String>,
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub card_issuing_country_code: Option<String>,
pub bank_code: Option<String>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>,
}
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct ExternalVaultCard {
pub card_number: Secret<String>,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub card_cvc: Secret<String>,
pub bin_number: Option<String>,
pub last_four: Option<String>,
pub card_issuer: Option<String>,
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code: Option<String>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>,
}
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct VaultToken {
pub card_cvc: Secret<String>,
pub card_holder_name: Option<Secret<String>>,
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct CardDetailsForNetworkTransactionId {
pub card_number: cards::CardNumber,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub card_issuer: Option<String>,
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub card_issuing_country_code: Option<String>,
pub bank_code: Option<String>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct NetworkTokenDetailsForNetworkTransactionId {
pub network_token: cards::NetworkToken,
pub token_exp_month: Secret<String>,
pub token_exp_year: Secret<String>,
pub card_issuer: Option<String>,
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code: Option<String>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
pub eci: Option<String>,
}
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct CardDetail {
pub card_number: cards::CardNumber,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub card_issuer: Option<String>,
pub card_network: Option<api_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub card_issuing_country_code: Option<String>,
pub bank_code: Option<String>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>,
}
impl CardDetailsForNetworkTransactionId {
pub fn get_nti_and_card_details_for_mit_flow(
recurring_details: RecurringDetails,
) -> Option<(api_models::payments::MandateReferenceId, Self)> {
let network_transaction_id_and_card_details = match recurring_details {
RecurringDetails::NetworkTransactionIdAndCardDetails(
network_transaction_id_and_card_details,
) => Some(network_transaction_id_and_card_details),
RecurringDetails::MandateId(_)
| RecurringDetails::PaymentMethodId(_)
| RecurringDetails::ProcessorPaymentToken(_)
| RecurringDetails::NetworkTransactionIdAndNetworkTokenDetails(_) => None,
}?;
let mandate_reference_id = api_models::payments::MandateReferenceId::NetworkMandateId(
network_transaction_id_and_card_details
.network_transaction_id
.peek()
.to_string(),
);
Some((
mandate_reference_id,
(*network_transaction_id_and_card_details.clone()).into(),
))
}
}
impl NetworkTokenDetailsForNetworkTransactionId {
pub fn get_nti_and_network_token_details_for_mit_flow(
recurring_details: RecurringDetails,
) -> Option<(api_models::payments::MandateReferenceId, Self)> {
let network_transaction_id_and_network_token_details = match recurring_details {
RecurringDetails::NetworkTransactionIdAndNetworkTokenDetails(
network_transaction_id_and_card_details,
) => Some(network_transaction_id_and_card_details),
RecurringDetails::MandateId(_)
| RecurringDetails::PaymentMethodId(_)
| RecurringDetails::ProcessorPaymentToken(_)
| RecurringDetails::NetworkTransactionIdAndCardDetails(_) => None,
}?;
let mandate_reference_id = api_models::payments::MandateReferenceId::NetworkMandateId(
network_transaction_id_and_network_token_details
.network_transaction_id
.peek()
.to_string(),
);
Some((
mandate_reference_id,
(*network_transaction_id_and_network_token_details.clone()).into(),
))
}
}
impl From<&Card> for CardDetail {
fn from(item: &Card) -> Self {
Self {
card_number: item.card_number.to_owned(),
card_exp_month: item.card_exp_month.to_owned(),
card_exp_year: item.card_exp_year.to_owned(),
card_issuer: item.card_issuer.to_owned(),
card_network: item.card_network.to_owned(),
card_type: item.card_type.to_owned(),
card_issuing_country: item.card_issuing_country.to_owned(),
card_issuing_country_code: item.card_issuing_country_code.to_owned(),
bank_code: item.bank_code.to_owned(),
nick_name: item.nick_name.to_owned(),
card_holder_name: item.card_holder_name.to_owned(),
co_badged_card_data: item.co_badged_card_data.to_owned(),
}
}
}
impl From<NetworkTransactionIdAndCardDetails> for CardDetailsForNetworkTransactionId {
fn from(card_details_for_nti: NetworkTransactionIdAndCardDetails) -> Self {
Self {
card_number: card_details_for_nti.card_number,
card_exp_month: card_details_for_nti.card_exp_month,
card_exp_year: card_details_for_nti.card_exp_year,
card_issuer: card_details_for_nti.card_issuer,
card_network: card_details_for_nti.card_network,
card_type: card_details_for_nti.card_type,
card_issuing_country: card_details_for_nti.card_issuing_country,
card_issuing_country_code: card_details_for_nti.card_issuing_country_code,
bank_code: card_details_for_nti.bank_code,
nick_name: card_details_for_nti.nick_name,
card_holder_name: card_details_for_nti.card_holder_name,
}
}
}
impl From<NetworkTransactionIdAndNetworkTokenDetails>
for NetworkTokenDetailsForNetworkTransactionId
{
fn from(network_token_details_for_nti: NetworkTransactionIdAndNetworkTokenDetails) -> Self {
Self {
network_token: network_token_details_for_nti.network_token,
token_exp_month: network_token_details_for_nti.token_exp_month,
token_exp_year: network_token_details_for_nti.token_exp_year,
card_network: network_token_details_for_nti.card_network,
card_issuer: network_token_details_for_nti.card_issuer,
card_type: network_token_details_for_nti.card_type,
card_issuing_country: network_token_details_for_nti.card_issuing_country,
bank_code: network_token_details_for_nti.bank_code,
nick_name: network_token_details_for_nti.nick_name,
card_holder_name: network_token_details_for_nti.card_holder_name,
eci: network_token_details_for_nti.eci,
}
}
}
#[cfg(feature = "v1")]
impl From<NetworkTokenDetailsForNetworkTransactionId> for NetworkTokenData {
fn from(network_token_details_for_nti: NetworkTokenDetailsForNetworkTransactionId) -> Self {
Self {
token_number: network_token_details_for_nti.network_token,
token_exp_month: network_token_details_for_nti.token_exp_month,
token_exp_year: network_token_details_for_nti.token_exp_year,
token_cryptogram: None,
card_issuer: network_token_details_for_nti.card_issuer,
card_network: network_token_details_for_nti.card_network,
card_type: network_token_details_for_nti.card_type,
card_issuing_country: network_token_details_for_nti.card_issuing_country,
bank_code: network_token_details_for_nti.bank_code,
nick_name: network_token_details_for_nti.nick_name,
eci: network_token_details_for_nti.eci,
}
}
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
pub enum CardRedirectData {
Knet {},
Benefit {},
MomoAtm {},
CardRedirect {},
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub enum PayLaterData {
KlarnaRedirect {},
KlarnaSdk { token: String },
AffirmRedirect {},
AfterpayClearpayRedirect {},
PayBrightRedirect {},
WalleyRedirect {},
FlexitiRedirect {},
AlmaRedirect {},
AtomeRedirect {},
BreadpayRedirect {},
PayjustnowRedirect {},
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub enum WalletData {
AliPayQr(Box<AliPayQr>),
AliPayRedirect(AliPayRedirection),
AliPayHkRedirect(AliPayHkRedirection),
AmazonPay(AmazonPayWalletData),
AmazonPayRedirect(Box<AmazonPayRedirect>),
BluecodeRedirect {},
Paysera(Box<PayseraData>),
Skrill(Box<SkrillData>),
MomoRedirect(MomoRedirection),
KakaoPayRedirect(KakaoPayRedirection),
GoPayRedirect(GoPayRedirection),
GcashRedirect(GcashRedirection),
ApplePay(ApplePayWalletData),
ApplePayRedirect(Box<ApplePayRedirectData>),
ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>),
DanaRedirect {},
GooglePay(GooglePayWalletData),
GooglePayRedirect(Box<GooglePayRedirectData>),
GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>),
MbWayRedirect(Box<MbWayRedirection>),
MobilePayRedirect(Box<MobilePayRedirection>),
PaypalRedirect(PaypalRedirection),
PaypalSdk(PayPalWalletData),
Paze(PazeWalletData),
SamsungPay(Box<SamsungPayWalletData>),
TwintRedirect {},
VippsRedirect {},
TouchNGoRedirect(Box<TouchNGoRedirection>),
WeChatPayRedirect(Box<WeChatPayRedirection>),
WeChatPayQr(Box<WeChatPayQr>),
CashappQr(Box<CashappQr>),
SwishQr(SwishQrData),
Mifinity(MifinityData),
RevolutPay(RevolutPayData),
}
impl WalletData {
pub fn get_paze_wallet_data(&self) -> Option<&PazeWalletData> {
if let Self::Paze(paze_wallet_data) = self {
Some(paze_wallet_data)
} else {
None
}
}
pub fn get_apple_pay_wallet_data(&self) -> Option<&ApplePayWalletData> {
if let Self::ApplePay(apple_pay_wallet_data) = self {
Some(apple_pay_wallet_data)
} else {
None
}
}
pub fn get_google_pay_wallet_data(&self) -> Option<&GooglePayWalletData> {
if let Self::GooglePay(google_pay_wallet_data) = self {
Some(google_pay_wallet_data)
} else {
None
}
}
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MifinityData {
pub date_of_birth: Secret<Date>,
pub language_preference: Option<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct PazeWalletData {
pub complete_response: Secret<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct SamsungPayWalletData {
pub payment_credential: SamsungPayWalletCredentials,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct SamsungPayWalletCredentials {
pub method: Option<String>,
pub recurring_payment: Option<bool>,
pub card_brand: common_enums::SamsungPayCardBrand,
pub dpan_last_four_digits: Option<String>,
#[serde(rename = "card_last4digits")]
pub card_last_four_digits: String,
#[serde(rename = "3_d_s")]
pub token_data: SamsungPayTokenData,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct SamsungPayTokenData {
#[serde(rename = "type")]
pub three_ds_type: Option<String>,
pub version: String,
pub data: Secret<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GooglePayWalletData {
/// The type of payment method
pub pm_type: String,
/// User-facing message to describe the payment method that funds this transaction.
pub description: String,
/// The information of the payment method
pub info: GooglePayPaymentMethodInfo,
/// The tokenization data of Google pay
pub tokenization_data: common_types::payments::GpayTokenizationData,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ApplePayRedirectData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RevolutPayData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GooglePayRedirectData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GooglePayThirdPartySdkData {
pub token: Option<Secret<String>>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ApplePayThirdPartySdkData {
pub token: Option<Secret<String>>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct WeChatPayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct WeChatPay {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct WeChatPayQr {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct CashappQr {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct PaypalRedirection {
/// paypal's email address
pub email: Option<Email>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct AliPayQr {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct AliPayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct AliPayHkRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct AmazonPayRedirect {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct BluecodeQrRedirect {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct PayseraData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct SkrillData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MomoRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct KakaoPayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GoPayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GcashRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MobilePayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MbWayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GooglePayPaymentMethodInfo {
/// The name of the card network
pub card_network: String,
/// The details of the card
pub card_details: String,
/// assurance_details of the card
pub assurance_details: Option<GooglePayAssuranceDetails>,
/// Card funding source for the selected payment method
pub card_funding_source: Option<GooglePayCardFundingSource>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct GooglePayAssuranceDetails {
///indicates that Cardholder possession validation has been performed
pub card_holder_authenticated: bool,
/// indicates that identification and verifications (ID&V) was performed
pub account_verified: bool,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct PayPalWalletData {
/// Token generated for the Apple pay
pub token: String,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct TouchNGoRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct SwishQrData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ApplePayWalletData {
/// The payment data of Apple pay
pub payment_data: common_types::payments::ApplePayPaymentData,
/// The payment method of Apple pay
pub payment_method: ApplepayPaymentMethod,
/// The unique identifier for the transaction
pub transaction_identifier: String,
}
impl ApplePayWalletData {
pub fn get_payment_method_type(&self) -> Option<api_enums::PaymentMethodType> {
self.payment_method
.pm_type
.clone()
.parse_enum("ApplePayPaymentMethodType")
.ok()
.and_then(|payment_type| match payment_type {
common_enums::ApplePayPaymentMethodType::Debit => {
Some(api_enums::PaymentMethodType::Debit)
}
common_enums::ApplePayPaymentMethodType::Credit => {
Some(api_enums::PaymentMethodType::Credit)
}
common_enums::ApplePayPaymentMethodType::Prepaid
| common_enums::ApplePayPaymentMethodType::Store => None,
})
}
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ApplepayPaymentMethod {
pub display_name: String,
pub network: String,
pub pm_type: String,
}
#[derive(Eq, PartialEq, Clone, Default, Debug, serde::Deserialize, serde::Serialize)]
pub struct AmazonPayWalletData {
pub checkout_session_id: String,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum RealTimePaymentData {
DuitNow {},
Fps {},
PromptPay {},
VietQr {},
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum BankRedirectData {
BancontactCard {
card_number: Option<cards::CardNumber>,
card_exp_month: Option<Secret<String>>,
card_exp_year: Option<Secret<String>>,
card_holder_name: Option<Secret<String>>,
},
Bizum {},
Blik {
blik_code: Option<String>,
},
Eps {
bank_name: Option<common_enums::BankNames>,
country: Option<api_enums::CountryAlpha2>,
},
Giropay {
bank_account_bic: Option<Secret<String>>,
bank_account_iban: Option<Secret<String>>,
country: Option<api_enums::CountryAlpha2>,
},
Ideal {
bank_name: Option<common_enums::BankNames>,
},
Interac {
country: Option<api_enums::CountryAlpha2>,
email: Option<Email>,
},
OnlineBankingCzechRepublic {
issuer: common_enums::BankNames,
},
OnlineBankingFinland {
email: Option<Email>,
},
OnlineBankingPoland {
issuer: common_enums::BankNames,
},
OnlineBankingSlovakia {
issuer: common_enums::BankNames,
},
OpenBankingUk {
issuer: Option<common_enums::BankNames>,
country: Option<api_enums::CountryAlpha2>,
},
Przelewy24 {
bank_name: Option<common_enums::BankNames>,
},
Sofort {
country: Option<api_enums::CountryAlpha2>,
preferred_language: Option<String>,
},
Trustly {
country: Option<api_enums::CountryAlpha2>,
},
OnlineBankingFpx {
issuer: common_enums::BankNames,
},
OnlineBankingThailand {
issuer: common_enums::BankNames,
},
LocalBankRedirect {},
Eft {
provider: String,
},
OpenBanking {},
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum OpenBankingData {
OpenBankingPIS {},
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct CryptoData {
pub pay_currency: Option<String>,
pub network: Option<String>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UpiData {
UpiCollect(UpiCollectData),
UpiIntent(UpiIntentData),
UpiQr(UpiQrData),
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct UpiCollectData {
pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct UpiIntentData {}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct UpiQrData {}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VoucherData {
Boleto(Box<BoletoVoucherData>),
Efecty,
PagoEfectivo,
RedCompra,
RedPagos,
Alfamart(Box<AlfamartVoucherData>),
Indomaret(Box<IndomaretVoucherData>),
Oxxo,
SevenEleven(Box<JCSVoucherData>),
Lawson(Box<JCSVoucherData>),
MiniStop(Box<JCSVoucherData>),
FamilyMart(Box<JCSVoucherData>),
Seicomart(Box<JCSVoucherData>),
PayEasy(Box<JCSVoucherData>),
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct BoletoVoucherData {
/// The shopper's social security number
pub social_security_number: Option<Secret<String>>,
/// The bank number associated with the boleto
pub bank_number: Option<Secret<String>>,
/// The type of document (e.g., CPF, CNPJ)
pub document_type: Option<common_enums::DocumentKind>,
/// The percentage of fine applied for late payment
pub fine_percentage: Option<String>,
/// The number of days after due date when fine is applied
pub fine_quantity_days: Option<String>,
/// The percentage of interest applied for late payment
pub interest_percentage: Option<String>,
/// Number of days after which the boleto can be written off
pub write_off_quantity_days: Option<String>,
/// Additional messages to display to the shopper
pub messages: Option<Vec<String>>,
/// The date upon which the boleto is due and is of format: "YYYY-MM-DD"
pub due_date: Option<String>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct AlfamartVoucherData {}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct IndomaretVoucherData {}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct JCSVoucherData {}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum GiftCardData {
Givex(GiftCardDetails),
PaySafeCard {},
BhnCardNetwork(BHNGiftCardDetails),
}
impl GiftCardData {
/// Returns a key that uniquely identifies the gift card. Used in
/// Payment Method Balance Check Flow for storing the balance
/// data in Redis.
///
pub fn get_payment_method_key(
&self,
) -> Result<Secret<String>, error_stack::Report<common_utils::errors::ValidationError>> {
match self {
Self::Givex(givex) => Ok(givex.number.clone()),
Self::PaySafeCard {} =>
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/invoice.rs | crates/hyperswitch_domain_models/src/invoice.rs | use common_utils::{
errors::{CustomResult, ValidationError},
id_type::GenerateId,
pii::SecretSerdeValue,
types::{
keymanager::{Identifier, KeyManagerState},
MinorUnit,
},
};
use masking::{PeekInterface, Secret};
use utoipa::ToSchema;
use crate::merchant_key_store::MerchantKeyStore;
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct Invoice {
pub id: common_utils::id_type::InvoiceId,
pub subscription_id: common_utils::id_type::SubscriptionId,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
pub payment_intent_id: Option<common_utils::id_type::PaymentId>,
pub payment_method_id: Option<String>,
pub customer_id: common_utils::id_type::CustomerId,
pub amount: MinorUnit,
pub currency: String,
pub status: common_enums::connector_enums::InvoiceStatus,
pub provider_name: common_enums::connector_enums::Connector,
pub metadata: Option<SecretSerdeValue>,
pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for Invoice {
type DstType = diesel_models::invoice::Invoice;
type NewDstType = diesel_models::invoice::InvoiceNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let now = common_utils::date_time::now();
Ok(diesel_models::invoice::Invoice {
id: self.id,
subscription_id: self.subscription_id,
merchant_id: self.merchant_id,
profile_id: self.profile_id,
merchant_connector_id: self.merchant_connector_id,
payment_intent_id: self.payment_intent_id,
payment_method_id: self.payment_method_id,
customer_id: self.customer_id,
amount: self.amount,
currency: self.currency.to_string(),
status: self.status,
provider_name: self.provider_name,
metadata: None,
created_at: now,
modified_at: now,
connector_invoice_id: self.connector_invoice_id,
})
}
async fn convert_back(
_state: &KeyManagerState,
item: Self::DstType,
_key: &Secret<Vec<u8>>,
_key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
Ok(Self {
id: item.id,
subscription_id: item.subscription_id,
merchant_id: item.merchant_id,
profile_id: item.profile_id,
merchant_connector_id: item.merchant_connector_id,
payment_intent_id: item.payment_intent_id,
payment_method_id: item.payment_method_id,
customer_id: item.customer_id,
amount: item.amount,
currency: item.currency,
status: item.status,
provider_name: item.provider_name,
metadata: item.metadata,
connector_invoice_id: item.connector_invoice_id,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::invoice::InvoiceNew::new(
self.subscription_id,
self.merchant_id,
self.profile_id,
self.merchant_connector_id,
self.payment_intent_id,
self.payment_method_id,
self.customer_id,
self.amount,
self.currency.to_string(),
self.status,
self.provider_name,
None,
self.connector_invoice_id,
))
}
}
impl Invoice {
#[allow(clippy::too_many_arguments)]
pub fn to_invoice(
subscription_id: common_utils::id_type::SubscriptionId,
merchant_id: common_utils::id_type::MerchantId,
profile_id: common_utils::id_type::ProfileId,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
payment_intent_id: Option<common_utils::id_type::PaymentId>,
payment_method_id: Option<String>,
customer_id: common_utils::id_type::CustomerId,
amount: MinorUnit,
currency: String,
status: common_enums::connector_enums::InvoiceStatus,
provider_name: common_enums::connector_enums::Connector,
metadata: Option<SecretSerdeValue>,
connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
) -> Self {
Self {
id: common_utils::id_type::InvoiceId::generate(),
subscription_id,
merchant_id,
profile_id,
merchant_connector_id,
payment_intent_id,
payment_method_id,
customer_id,
amount,
currency: currency.to_string(),
status,
provider_name,
metadata,
connector_invoice_id,
}
}
}
#[async_trait::async_trait]
pub trait InvoiceInterface {
type Error;
async fn insert_invoice_entry(
&self,
key_store: &MerchantKeyStore,
invoice_new: Invoice,
) -> CustomResult<Invoice, Self::Error>;
async fn find_invoice_by_invoice_id(
&self,
key_store: &MerchantKeyStore,
invoice_id: String,
) -> CustomResult<Invoice, Self::Error>;
async fn update_invoice_entry(
&self,
key_store: &MerchantKeyStore,
invoice_id: String,
data: InvoiceUpdate,
) -> CustomResult<Invoice, Self::Error>;
async fn get_latest_invoice_for_subscription(
&self,
key_store: &MerchantKeyStore,
subscription_id: String,
) -> CustomResult<Invoice, Self::Error>;
async fn find_invoice_by_subscription_id_connector_invoice_id(
&self,
key_store: &MerchantKeyStore,
subscription_id: String,
connector_invoice_id: common_utils::id_type::InvoiceId,
) -> CustomResult<Option<Invoice>, Self::Error>;
}
pub struct InvoiceUpdate {
pub status: Option<common_enums::connector_enums::InvoiceStatus>,
pub payment_method_id: Option<String>,
pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
pub modified_at: time::PrimitiveDateTime,
pub payment_intent_id: Option<common_utils::id_type::PaymentId>,
pub amount: Option<MinorUnit>,
pub currency: Option<String>,
}
#[derive(Debug, Clone)]
pub struct AmountAndCurrencyUpdate {
pub amount: MinorUnit,
pub currency: String,
}
#[derive(Debug, Clone)]
pub struct ConnectorAndStatusUpdate {
pub connector_invoice_id: common_utils::id_type::InvoiceId,
pub status: common_enums::connector_enums::InvoiceStatus,
}
#[derive(Debug, Clone)]
pub struct PaymentAndStatusUpdate {
pub payment_method_id: Option<Secret<String>>,
pub payment_intent_id: Option<common_utils::id_type::PaymentId>,
pub status: common_enums::connector_enums::InvoiceStatus,
pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
}
/// Enum-based invoice update request for different scenarios
#[derive(Debug, Clone)]
pub enum InvoiceUpdateRequest {
/// Update amount and currency
Amount(AmountAndCurrencyUpdate),
/// Update connector invoice ID and status
Connector(ConnectorAndStatusUpdate),
/// Update payment details along with status
PaymentStatus(PaymentAndStatusUpdate),
}
impl InvoiceUpdateRequest {
/// Create an amount and currency update request
pub fn update_amount_and_currency(amount: MinorUnit, currency: String) -> Self {
Self::Amount(AmountAndCurrencyUpdate { amount, currency })
}
/// Create a connector invoice ID and status update request
pub fn update_connector_and_status(
connector_invoice_id: common_utils::id_type::InvoiceId,
status: common_enums::connector_enums::InvoiceStatus,
) -> Self {
Self::Connector(ConnectorAndStatusUpdate {
connector_invoice_id,
status,
})
}
/// Create a combined payment and status update request
pub fn update_payment_and_status(
payment_method_id: Option<Secret<String>>,
payment_intent_id: Option<common_utils::id_type::PaymentId>,
status: common_enums::connector_enums::InvoiceStatus,
connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
) -> Self {
Self::PaymentStatus(PaymentAndStatusUpdate {
payment_method_id,
payment_intent_id,
status,
connector_invoice_id,
})
}
}
impl From<InvoiceUpdateRequest> for InvoiceUpdate {
fn from(request: InvoiceUpdateRequest) -> Self {
let now = common_utils::date_time::now();
match request {
InvoiceUpdateRequest::Amount(update) => Self {
status: None,
payment_method_id: None,
connector_invoice_id: None,
modified_at: now,
payment_intent_id: None,
amount: Some(update.amount),
currency: Some(update.currency),
},
InvoiceUpdateRequest::Connector(update) => Self {
status: Some(update.status),
payment_method_id: None,
connector_invoice_id: Some(update.connector_invoice_id),
modified_at: now,
payment_intent_id: None,
amount: None,
currency: None,
},
InvoiceUpdateRequest::PaymentStatus(update) => Self {
status: Some(update.status),
payment_method_id: update
.payment_method_id
.as_ref()
.map(|id| id.peek())
.cloned(),
connector_invoice_id: update.connector_invoice_id,
modified_at: now,
payment_intent_id: update.payment_intent_id,
amount: None,
currency: None,
},
}
}
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for InvoiceUpdate {
type DstType = diesel_models::invoice::InvoiceUpdate;
type NewDstType = diesel_models::invoice::InvoiceUpdate;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::invoice::InvoiceUpdate {
status: self.status,
payment_method_id: self.payment_method_id,
connector_invoice_id: self.connector_invoice_id,
modified_at: self.modified_at,
payment_intent_id: self.payment_intent_id,
amount: self.amount,
currency: self.currency,
})
}
async fn convert_back(
_state: &KeyManagerState,
item: Self::DstType,
_key: &Secret<Vec<u8>>,
_key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
Ok(Self {
status: item.status,
payment_method_id: item.payment_method_id,
connector_invoice_id: item.connector_invoice_id,
modified_at: item.modified_at,
payment_intent_id: item.payment_intent_id,
amount: item.amount,
currency: item.currency,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::invoice::InvoiceUpdate {
status: self.status,
payment_method_id: self.payment_method_id,
connector_invoice_id: self.connector_invoice_id,
modified_at: self.modified_at,
payment_intent_id: self.payment_intent_id,
amount: self.amount,
currency: self.currency,
})
}
}
impl InvoiceUpdate {
pub fn new(
payment_method_id: Option<String>,
status: Option<common_enums::connector_enums::InvoiceStatus>,
connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
payment_intent_id: Option<common_utils::id_type::PaymentId>,
amount: Option<MinorUnit>,
currency: Option<String>,
) -> Self {
Self {
status,
payment_method_id,
connector_invoice_id,
modified_at: common_utils::date_time::now(),
payment_intent_id,
amount,
currency,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/relay.rs | crates/hyperswitch_domain_models/src/relay.rs | use common_enums::enums;
use common_utils::{
self,
errors::{CustomResult, ValidationError},
id_type::{self, GenerateId},
pii,
types::{keymanager, MinorUnit},
};
use diesel_models::relay::RelayUpdateInternal;
use error_stack::ResultExt;
use masking::{ExposeInterface, Secret};
use serde::{self, Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{router_data::ErrorResponse, router_response_types};
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Relay {
pub id: id_type::RelayId,
pub connector_resource_id: String,
pub connector_id: id_type::MerchantConnectorAccountId,
pub profile_id: id_type::ProfileId,
pub merchant_id: id_type::MerchantId,
pub relay_type: enums::RelayType,
pub request_data: Option<RelayData>,
pub status: enums::RelayStatus,
pub connector_reference_id: Option<String>,
pub error_code: Option<String>,
pub error_message: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub response_data: Option<pii::SecretSerdeValue>,
}
impl Relay {
pub fn new(
relay_request: &api_models::relay::RelayRequest,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
) -> Self {
let relay_id = id_type::RelayId::generate();
Self {
id: relay_id.clone(),
connector_resource_id: relay_request.connector_resource_id.clone(),
connector_id: relay_request.connector_id.clone(),
profile_id: profile_id.clone(),
merchant_id: merchant_id.clone(),
relay_type: common_enums::RelayType::Refund,
request_data: relay_request.data.clone().map(From::from),
status: common_enums::RelayStatus::Created,
connector_reference_id: None,
error_code: None,
error_message: None,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
response_data: None,
}
}
}
impl From<api_models::relay::RelayData> for RelayData {
fn from(relay: api_models::relay::RelayData) -> Self {
match relay {
api_models::relay::RelayData::Refund(relay_refund_request) => {
Self::Refund(RelayRefundData {
amount: relay_refund_request.amount,
currency: relay_refund_request.currency,
reason: relay_refund_request.reason,
})
}
}
}
}
impl From<api_models::relay::RelayRefundRequestData> for RelayRefundData {
fn from(relay: api_models::relay::RelayRefundRequestData) -> Self {
Self {
amount: relay.amount,
currency: relay.currency,
reason: relay.reason,
}
}
}
impl RelayUpdate {
pub fn from(
response: Result<router_response_types::RefundsResponseData, ErrorResponse>,
) -> Self {
match response {
Err(error) => Self::ErrorUpdate {
error_code: error.code,
error_message: error.reason.unwrap_or(error.message),
status: common_enums::RelayStatus::Failure,
},
Ok(response) => Self::StatusUpdate {
connector_reference_id: Some(response.connector_refund_id),
status: common_enums::RelayStatus::from(response.refund_status),
},
}
}
}
impl From<RelayData> for api_models::relay::RelayData {
fn from(relay: RelayData) -> Self {
match relay {
RelayData::Refund(relay_refund_request) => {
Self::Refund(api_models::relay::RelayRefundRequestData {
amount: relay_refund_request.amount,
currency: relay_refund_request.currency,
reason: relay_refund_request.reason,
})
}
}
}
}
impl From<Relay> for api_models::relay::RelayResponse {
fn from(value: Relay) -> Self {
let error = value
.error_code
.zip(value.error_message)
.map(
|(error_code, error_message)| api_models::relay::RelayError {
code: error_code,
message: error_message,
},
);
let data = value.request_data.map(|relay_data| match relay_data {
RelayData::Refund(relay_refund_request) => {
api_models::relay::RelayData::Refund(api_models::relay::RelayRefundRequestData {
amount: relay_refund_request.amount,
currency: relay_refund_request.currency,
reason: relay_refund_request.reason,
})
}
});
Self {
id: value.id,
status: value.status,
error,
connector_resource_id: value.connector_resource_id,
connector_id: value.connector_id,
profile_id: value.profile_id,
relay_type: value.relay_type,
data,
connector_reference_id: value.connector_reference_id,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "snake_case", untagged)]
pub enum RelayData {
Refund(RelayRefundData),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RelayRefundData {
pub amount: MinorUnit,
pub currency: enums::Currency,
pub reason: Option<String>,
}
#[derive(Debug)]
pub enum RelayUpdate {
ErrorUpdate {
error_code: String,
error_message: String,
status: enums::RelayStatus,
},
StatusUpdate {
connector_reference_id: Option<String>,
status: common_enums::RelayStatus,
},
}
impl From<RelayUpdate> for RelayUpdateInternal {
fn from(value: RelayUpdate) -> Self {
match value {
RelayUpdate::ErrorUpdate {
error_code,
error_message,
status,
} => Self {
error_code: Some(error_code),
error_message: Some(error_message),
connector_reference_id: None,
status: Some(status),
modified_at: common_utils::date_time::now(),
},
RelayUpdate::StatusUpdate {
connector_reference_id,
status,
} => Self {
connector_reference_id,
status: Some(status),
error_code: None,
error_message: None,
modified_at: common_utils::date_time::now(),
},
}
}
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for Relay {
type DstType = diesel_models::relay::Relay;
type NewDstType = diesel_models::relay::RelayNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::relay::Relay {
id: self.id,
connector_resource_id: self.connector_resource_id,
connector_id: self.connector_id,
profile_id: self.profile_id,
merchant_id: self.merchant_id,
relay_type: self.relay_type,
request_data: self
.request_data
.map(|data| {
serde_json::to_value(data).change_context(ValidationError::InvalidValue {
message: "Failed while decrypting business profile data".to_string(),
})
})
.transpose()?
.map(Secret::new),
status: self.status,
connector_reference_id: self.connector_reference_id,
error_code: self.error_code,
error_message: self.error_message,
created_at: self.created_at,
modified_at: self.modified_at,
response_data: self.response_data,
})
}
async fn convert_back(
_state: &keymanager::KeyManagerState,
item: Self::DstType,
_key: &Secret<Vec<u8>>,
_key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError> {
Ok(Self {
id: item.id,
connector_resource_id: item.connector_resource_id,
connector_id: item.connector_id,
profile_id: item.profile_id,
merchant_id: item.merchant_id,
relay_type: enums::RelayType::Refund,
request_data: item
.request_data
.map(|data| {
serde_json::from_value(data.expose()).change_context(
ValidationError::InvalidValue {
message: "Failed while decrypting business profile data".to_string(),
},
)
})
.transpose()?,
status: item.status,
connector_reference_id: item.connector_reference_id,
error_code: item.error_code,
error_message: item.error_message,
created_at: item.created_at,
modified_at: item.modified_at,
response_data: item.response_data,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::relay::RelayNew {
id: self.id,
connector_resource_id: self.connector_resource_id,
connector_id: self.connector_id,
profile_id: self.profile_id,
merchant_id: self.merchant_id,
relay_type: self.relay_type,
request_data: self
.request_data
.map(|data| {
serde_json::to_value(data).change_context(ValidationError::InvalidValue {
message: "Failed while decrypting business profile data".to_string(),
})
})
.transpose()?
.map(Secret::new),
status: self.status,
connector_reference_id: self.connector_reference_id,
error_code: self.error_code,
error_message: self.error_message,
created_at: self.created_at,
modified_at: self.modified_at,
response_data: self.response_data,
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/api.rs | crates/hyperswitch_domain_models/src/api.rs | use std::{collections::HashSet, fmt::Display};
use common_utils::{
events::{ApiEventMetric, ApiEventsType},
impl_api_event_type,
};
use super::payment_method_data::PaymentMethodData;
#[derive(Debug, PartialEq)]
pub enum ApplicationResponse<R> {
Json(R),
StatusOk,
TextPlain(String),
JsonForRedirection(api_models::payments::RedirectionResponse),
Form(Box<RedirectionFormData>),
PaymentLinkForm(Box<PaymentLinkAction>),
FileData((Vec<u8>, mime::Mime)),
JsonWithHeaders((R, Vec<(String, masking::Maskable<String>)>)),
GenericLinkForm(Box<GenericLinks>),
}
impl<R> ApplicationResponse<R> {
/// Get the json response from response
#[inline]
pub fn get_json_body(
self,
) -> common_utils::errors::CustomResult<R, common_utils::errors::ValidationError> {
match self {
Self::Json(body) | Self::JsonWithHeaders((body, _)) => Ok(body),
Self::TextPlain(_)
| Self::JsonForRedirection(_)
| Self::Form(_)
| Self::PaymentLinkForm(_)
| Self::FileData(_)
| Self::GenericLinkForm(_)
| Self::StatusOk => Err(common_utils::errors::ValidationError::InvalidValue {
message: "expected either Json or JsonWithHeaders Response".to_string(),
}
.into()),
}
}
}
impl<T: ApiEventMetric> ApiEventMetric for ApplicationResponse<T> {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
match self {
Self::Json(r) => r.get_api_event_type(),
Self::JsonWithHeaders((r, _)) => r.get_api_event_type(),
_ => None,
}
}
}
impl_api_event_type!(Miscellaneous, (GenericLinkFormData));
#[derive(Debug, PartialEq)]
pub struct RedirectionFormData {
pub redirect_form: crate::router_response_types::RedirectForm,
pub payment_method_data: Option<PaymentMethodData>,
pub amount: String,
pub currency: String,
}
#[derive(Debug, Eq, PartialEq)]
pub enum PaymentLinkAction {
PaymentLinkFormData(payment_link::PaymentLinkFormData),
PaymentLinkStatus(payment_link::PaymentLinkStatusData),
}
#[derive(Debug, Eq, PartialEq)]
pub struct GenericLinks {
pub allowed_domains: HashSet<String>,
pub data: GenericLinksData,
pub locale: String,
}
#[derive(Debug, Eq, PartialEq)]
pub enum GenericLinksData {
ExpiredLink(GenericExpiredLinkData),
PaymentMethodCollect(GenericLinkFormData),
PayoutLink(GenericLinkFormData),
PayoutLinkStatus(GenericLinkStatusData),
PaymentMethodCollectStatus(GenericLinkStatusData),
SecurePaymentLink(payment_link::PaymentLinkFormData),
}
impl Display for GenericLinksData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match *self {
Self::ExpiredLink(_) => "ExpiredLink",
Self::PaymentMethodCollect(_) => "PaymentMethodCollect",
Self::PayoutLink(_) => "PayoutLink",
Self::PayoutLinkStatus(_) => "PayoutLinkStatus",
Self::PaymentMethodCollectStatus(_) => "PaymentMethodCollectStatus",
Self::SecurePaymentLink(_) => "SecurePaymentLink",
}
)
}
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericExpiredLinkData {
pub title: String,
pub message: String,
pub theme: String,
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericLinkFormData {
pub js_data: String,
pub css_data: String,
pub sdk_url: url::Url,
pub html_meta_tags: String,
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericLinkStatusData {
pub js_data: String,
pub css_data: String,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/types.rs | crates/hyperswitch_domain_models/src/types.rs | pub use diesel_models::types::OrderDetailsWithAmount;
use crate::{
router_data::{AccessToken, AccessTokenAuthenticationResponse, RouterData},
router_data_v2::{self, RouterDataV2},
router_flow_types::{
mandate_revoke::MandateRevoke,
revenue_recovery::InvoiceRecordBack,
subscriptions::{
GetSubscriptionEstimate, GetSubscriptionItemPrices, GetSubscriptionItems,
SubscriptionCancel, SubscriptionCreate, SubscriptionPause, SubscriptionResume,
},
AccessTokenAuth, AccessTokenAuthentication, Authenticate, AuthenticationConfirmation,
Authorize, AuthorizeSessionToken, BillingConnectorInvoiceSync,
BillingConnectorPaymentsSync, CalculateTax, Capture, CompleteAuthorize,
CreateConnectorCustomer, CreateOrder, Execute, ExtendAuthorization, ExternalVaultProxy,
GiftCardBalanceCheck, IncrementalAuthorization, PSync, PaymentMethodToken,
PostAuthenticate, PostCaptureVoid, PostSessionTokens, PreAuthenticate, PreProcessing,
RSync, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, VerifyWebhookSource, Void,
},
router_request_types::{
revenue_recovery::{
BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest,
InvoiceRecordBackRequest,
},
subscriptions::{
GetSubscriptionEstimateRequest, GetSubscriptionItemPricesRequest,
GetSubscriptionItemsRequest, SubscriptionCancelRequest, SubscriptionCreateRequest,
SubscriptionPauseRequest, SubscriptionResumeRequest,
},
unified_authentication_service::{
UasAuthenticationRequestData, UasAuthenticationResponseData,
UasConfirmationRequestData, UasPostAuthenticationRequestData,
UasPreAuthenticationRequestData,
},
AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData,
CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData,
ExternalVaultProxyPaymentsData, GiftCardBalanceCheckRequestData, MandateRevokeRequestData,
PaymentMethodTokenizationData, PaymentsAuthenticateData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData,
PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData,
PaymentsPostAuthenticateData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData,
PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData,
PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData,
SdkPaymentsSessionUpdateData, SetupMandateRequestData, VaultRequestData,
VerifyWebhookSourceRequestData,
},
router_response_types::{
revenue_recovery::{
BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse,
InvoiceRecordBackResponse,
},
subscriptions::{
GetSubscriptionEstimateResponse, GetSubscriptionItemPricesResponse,
GetSubscriptionItemsResponse, SubscriptionCancelResponse, SubscriptionCreateResponse,
SubscriptionPauseResponse, SubscriptionResumeResponse,
},
GiftCardBalanceCheckResponseData, MandateRevokeResponseData, PaymentsResponseData,
RefundsResponseData, TaxCalculationResponseData, VaultResponseData,
VerifyWebhookSourceResponseData,
},
};
#[cfg(feature = "payouts")]
pub use crate::{router_request_types::PayoutsData, router_response_types::PayoutsResponseData};
pub type PaymentsAuthorizeRouterData =
RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>;
pub type ExternalVaultProxyPaymentsRouterData =
RouterData<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>;
pub type PaymentsAuthorizeSessionTokenRouterData =
RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>;
pub type PaymentsPreProcessingRouterData =
RouterData<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>;
pub type PaymentsPreAuthenticateRouterData =
RouterData<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>;
pub type PaymentsAuthenticateRouterData =
RouterData<Authenticate, PaymentsAuthenticateData, PaymentsResponseData>;
pub type PaymentsPostAuthenticateRouterData =
RouterData<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData>;
pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>;
pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>;
pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>;
pub type PaymentsCancelPostCaptureRouterData =
RouterData<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>;
pub type SetupMandateRouterData =
RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>;
pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>;
pub type RefundExecuteRouterData = RouterData<Execute, RefundsData, RefundsResponseData>;
pub type RefundSyncRouterData = RouterData<RSync, RefundsData, RefundsResponseData>;
pub type TokenizationRouterData =
RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>;
pub type ConnectorCustomerRouterData =
RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>;
pub type PaymentsCompleteAuthorizeRouterData =
RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>;
pub type PaymentsTaxCalculationRouterData =
RouterData<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>;
pub type AccessTokenAuthenticationRouterData = RouterData<
AccessTokenAuthentication,
AccessTokenAuthenticationRequestData,
AccessTokenAuthenticationResponse,
>;
pub type PaymentsGiftCardBalanceCheckRouterData = RouterData<
GiftCardBalanceCheck,
GiftCardBalanceCheckRequestData,
GiftCardBalanceCheckResponseData,
>;
pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>;
pub type PaymentsPostSessionTokensRouterData =
RouterData<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>;
pub type PaymentsSessionRouterData = RouterData<Session, PaymentsSessionData, PaymentsResponseData>;
pub type PaymentsUpdateMetadataRouterData =
RouterData<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>;
pub type CreateOrderRouterData =
RouterData<CreateOrder, CreateOrderRequestData, PaymentsResponseData>;
pub type UasPostAuthenticationRouterData =
RouterData<PostAuthenticate, UasPostAuthenticationRequestData, UasAuthenticationResponseData>;
pub type UasPreAuthenticationRouterData =
RouterData<PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData>;
pub type UasAuthenticationConfirmationRouterData = RouterData<
AuthenticationConfirmation,
UasConfirmationRequestData,
UasAuthenticationResponseData,
>;
pub type MandateRevokeRouterData =
RouterData<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>;
pub type PaymentsIncrementalAuthorizationRouterData = RouterData<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>;
pub type PaymentsExtendAuthorizationRouterData =
RouterData<ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData>;
pub type SdkSessionUpdateRouterData =
RouterData<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>;
pub type VerifyWebhookSourceRouterData = RouterData<
VerifyWebhookSource,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
>;
#[cfg(feature = "payouts")]
pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>;
pub type InvoiceRecordBackRouterData =
RouterData<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse>;
pub type GetSubscriptionItemsRouterData =
RouterData<GetSubscriptionItems, GetSubscriptionItemsRequest, GetSubscriptionItemsResponse>;
pub type GetSubscriptionEstimateRouterData = RouterData<
GetSubscriptionEstimate,
GetSubscriptionEstimateRequest,
GetSubscriptionEstimateResponse,
>;
pub type SubscriptionPauseRouterData =
RouterData<SubscriptionPause, SubscriptionPauseRequest, SubscriptionPauseResponse>;
pub type SubscriptionResumeRouterData =
RouterData<SubscriptionResume, SubscriptionResumeRequest, SubscriptionResumeResponse>;
pub type SubscriptionCancelRouterData =
RouterData<SubscriptionCancel, SubscriptionCancelRequest, SubscriptionCancelResponse>;
pub type UasAuthenticationRouterData =
RouterData<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData>;
pub type BillingConnectorPaymentsSyncRouterData = RouterData<
BillingConnectorPaymentsSync,
BillingConnectorPaymentsSyncRequest,
BillingConnectorPaymentsSyncResponse,
>;
pub type BillingConnectorInvoiceSyncRouterData = RouterData<
BillingConnectorInvoiceSync,
BillingConnectorInvoiceSyncRequest,
BillingConnectorInvoiceSyncResponse,
>;
pub type BillingConnectorInvoiceSyncRouterDataV2 = RouterDataV2<
BillingConnectorInvoiceSync,
router_data_v2::flow_common_types::BillingConnectorInvoiceSyncFlowData,
BillingConnectorInvoiceSyncRequest,
BillingConnectorInvoiceSyncResponse,
>;
pub type BillingConnectorPaymentsSyncRouterDataV2 = RouterDataV2<
BillingConnectorPaymentsSync,
router_data_v2::flow_common_types::BillingConnectorPaymentsSyncFlowData,
BillingConnectorPaymentsSyncRequest,
BillingConnectorPaymentsSyncResponse,
>;
pub type InvoiceRecordBackRouterDataV2 = RouterDataV2<
InvoiceRecordBack,
router_data_v2::flow_common_types::InvoiceRecordBackData,
InvoiceRecordBackRequest,
InvoiceRecordBackResponse,
>;
pub type GetSubscriptionPlanPricesRouterData = RouterData<
GetSubscriptionItemPrices,
GetSubscriptionItemPricesRequest,
GetSubscriptionItemPricesResponse,
>;
pub type VaultRouterData<F> = RouterData<F, VaultRequestData, VaultResponseData>;
pub type VaultRouterDataV2<F> = RouterDataV2<
F,
router_data_v2::flow_common_types::VaultConnectorFlowData,
VaultRequestData,
VaultResponseData,
>;
pub type ExternalVaultProxyPaymentsRouterDataV2 = RouterDataV2<
ExternalVaultProxy,
router_data_v2::flow_common_types::ExternalVaultProxyFlowData,
ExternalVaultProxyPaymentsData,
PaymentsResponseData,
>;
pub type SubscriptionCreateRouterData =
RouterData<SubscriptionCreate, SubscriptionCreateRequest, SubscriptionCreateResponse>;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/merchant_connector_account.rs | crates/hyperswitch_domain_models/src/merchant_connector_account.rs | #[cfg(feature = "v2")]
use std::collections::HashMap;
use common_utils::{
crypto::Encryptable,
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
ext_traits::{StringExt, ValueExt},
id_type, pii, type_name,
types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
};
#[cfg(feature = "v2")]
use diesel_models::merchant_connector_account::{
BillingAccountReference as DieselBillingAccountReference,
MerchantConnectorAccountFeatureMetadata as DieselMerchantConnectorAccountFeatureMetadata,
RevenueRecoveryMetadata as DieselRevenueRecoveryMetadata,
};
use diesel_models::{
enums,
merchant_connector_account::{self as storage, MerchantConnectorAccountUpdateInternal},
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use rustc_hash::FxHashMap;
use serde_json::Value;
use super::behaviour;
#[cfg(feature = "v2")]
use crate::errors::api_error_response;
use crate::{
mandates::CommonMandateReference,
merchant_key_store::MerchantKeyStore,
router_data,
type_encryption::{crypto_operation, CryptoOperation},
};
#[cfg(feature = "v1")]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct MerchantConnectorAccount {
pub merchant_id: id_type::MerchantId,
pub connector_name: String,
#[encrypt]
pub connector_account_details: Encryptable<Secret<Value>>,
pub test_mode: Option<bool>,
pub disabled: Option<bool>,
pub merchant_connector_id: id_type::MerchantConnectorAccountId,
pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>,
pub connector_type: enums::ConnectorType,
pub metadata: Option<pii::SecretSerdeValue>,
pub frm_configs: Option<Vec<pii::SecretSerdeValue>>,
pub connector_label: Option<String>,
pub business_country: Option<enums::CountryAlpha2>,
pub business_label: Option<String>,
pub business_sub_label: Option<String>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub connector_webhook_details: Option<pii::SecretSerdeValue>,
pub profile_id: id_type::ProfileId,
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: enums::ConnectorStatus,
#[encrypt]
pub connector_wallets_details: Option<Encryptable<Secret<Value>>>,
#[encrypt]
pub additional_merchant_data: Option<Encryptable<Secret<Value>>>,
pub version: common_enums::ApiVersion,
}
#[cfg(feature = "v1")]
impl MerchantConnectorAccount {
pub fn get_id(&self) -> id_type::MerchantConnectorAccountId {
self.merchant_connector_id.clone()
}
pub fn get_connector_account_details(
&self,
) -> error_stack::Result<router_data::ConnectorAuthType, common_utils::errors::ParsingError>
{
self.connector_account_details
.get_inner()
.clone()
.parse_value("ConnectorAuthType")
}
pub fn get_connector_wallets_details(&self) -> Option<Secret<Value>> {
self.connector_wallets_details.as_deref().cloned()
}
pub fn get_connector_test_mode(&self) -> Option<bool> {
self.test_mode
}
pub fn get_connector_name_as_string(&self) -> String {
self.connector_name.clone()
}
pub fn get_metadata(&self) -> Option<Secret<Value>> {
self.metadata.clone()
}
pub fn get_ctp_service_provider(
&self,
) -> error_stack::Result<
Option<common_enums::CtpServiceProvider>,
common_utils::errors::ParsingError,
> {
let provider = self
.connector_name
.clone()
.parse_enum("CtpServiceProvider")
.attach_printable_lazy(|| {
format!(
"Failed to parse ctp service provider from connector_name: {}",
self.connector_name
)
})?;
Ok(Some(provider))
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub enum MerchantConnectorAccountTypeDetails {
MerchantConnectorAccount(Box<MerchantConnectorAccount>),
MerchantConnectorDetails(common_types::domain::MerchantConnectorAuthDetails),
}
#[cfg(feature = "v2")]
impl MerchantConnectorAccountTypeDetails {
pub fn get_connector_account_details(
&self,
) -> error_stack::Result<router_data::ConnectorAuthType, common_utils::errors::ParsingError>
{
match self {
Self::MerchantConnectorAccount(merchant_connector_account) => {
merchant_connector_account
.connector_account_details
.peek()
.clone()
.parse_value("ConnectorAuthType")
}
Self::MerchantConnectorDetails(merchant_connector_details) => {
merchant_connector_details
.merchant_connector_creds
.peek()
.clone()
.parse_value("ConnectorAuthType")
}
}
}
pub fn is_disabled(&self) -> bool {
match self {
Self::MerchantConnectorAccount(merchant_connector_account) => {
merchant_connector_account.disabled.unwrap_or(false)
}
Self::MerchantConnectorDetails(_) => false,
}
}
pub fn get_metadata(&self) -> Option<Secret<Value>> {
match self {
Self::MerchantConnectorAccount(merchant_connector_account) => {
merchant_connector_account.metadata.to_owned()
}
Self::MerchantConnectorDetails(_) => None,
}
}
pub fn get_id(&self) -> Option<id_type::MerchantConnectorAccountId> {
match self {
Self::MerchantConnectorAccount(merchant_connector_account) => {
Some(merchant_connector_account.id.clone())
}
Self::MerchantConnectorDetails(_) => None,
}
}
pub fn get_mca_id(&self) -> Option<id_type::MerchantConnectorAccountId> {
match self {
Self::MerchantConnectorAccount(merchant_connector_account) => {
Some(merchant_connector_account.get_id())
}
Self::MerchantConnectorDetails(_) => None,
}
}
pub fn get_connector_name(&self) -> Option<common_enums::connector_enums::Connector> {
match self {
Self::MerchantConnectorAccount(merchant_connector_account) => {
Some(merchant_connector_account.connector_name)
}
Self::MerchantConnectorDetails(merchant_connector_details) => {
Some(merchant_connector_details.connector_name)
}
}
}
pub fn get_connector_name_as_string(&self) -> String {
match self {
Self::MerchantConnectorAccount(merchant_connector_account) => {
merchant_connector_account.connector_name.to_string()
}
Self::MerchantConnectorDetails(merchant_connector_details) => {
merchant_connector_details.connector_name.to_string()
}
}
}
pub fn get_inner_db_merchant_connector_account(&self) -> Option<&MerchantConnectorAccount> {
match self {
Self::MerchantConnectorAccount(merchant_connector_account) => {
Some(merchant_connector_account)
}
Self::MerchantConnectorDetails(_) => None,
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct MerchantConnectorAccount {
pub id: id_type::MerchantConnectorAccountId,
pub merchant_id: id_type::MerchantId,
pub connector_name: common_enums::connector_enums::Connector,
#[encrypt]
pub connector_account_details: Encryptable<Secret<Value>>,
pub disabled: Option<bool>,
pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>,
pub connector_type: enums::ConnectorType,
pub metadata: Option<pii::SecretSerdeValue>,
pub frm_configs: Option<Vec<pii::SecretSerdeValue>>,
pub connector_label: Option<String>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub connector_webhook_details: Option<pii::SecretSerdeValue>,
pub profile_id: id_type::ProfileId,
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: enums::ConnectorStatus,
#[encrypt]
pub connector_wallets_details: Option<Encryptable<Secret<Value>>>,
#[encrypt]
pub additional_merchant_data: Option<Encryptable<Secret<Value>>>,
pub version: common_enums::ApiVersion,
pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>,
}
#[cfg(feature = "v2")]
impl MerchantConnectorAccount {
pub fn get_retry_threshold(&self) -> Option<u16> {
self.feature_metadata
.as_ref()
.and_then(|metadata| metadata.revenue_recovery.as_ref())
.map(|recovery| recovery.billing_connector_retry_threshold)
}
pub fn get_id(&self) -> id_type::MerchantConnectorAccountId {
self.id.clone()
}
pub fn get_metadata(&self) -> Option<pii::SecretSerdeValue> {
self.metadata.clone()
}
pub fn is_disabled(&self) -> bool {
self.disabled.unwrap_or(false)
}
pub fn get_connector_account_details(
&self,
) -> error_stack::Result<router_data::ConnectorAuthType, common_utils::errors::ParsingError>
{
use common_utils::ext_traits::ValueExt;
self.connector_account_details
.get_inner()
.clone()
.parse_value("ConnectorAuthType")
}
pub fn get_connector_wallets_details(&self) -> Option<Secret<Value>> {
self.connector_wallets_details.as_deref().cloned()
}
pub fn get_connector_test_mode(&self) -> Option<bool> {
todo!()
}
pub fn get_connector_name_as_string(&self) -> String {
self.connector_name.clone().to_string()
}
#[cfg(feature = "v2")]
pub fn get_connector_name(&self) -> common_enums::connector_enums::Connector {
self.connector_name
}
pub fn get_payment_merchant_connector_account_id_using_account_reference_id(
&self,
account_reference_id: String,
) -> Option<id_type::MerchantConnectorAccountId> {
self.feature_metadata.as_ref().and_then(|metadata| {
metadata.revenue_recovery.as_ref().and_then(|recovery| {
recovery
.mca_reference
.billing_to_recovery
.get(&account_reference_id)
.cloned()
})
})
}
pub fn get_account_reference_id_using_payment_merchant_connector_account_id(
&self,
payment_merchant_connector_account_id: id_type::MerchantConnectorAccountId,
) -> Option<String> {
self.feature_metadata.as_ref().and_then(|metadata| {
metadata.revenue_recovery.as_ref().and_then(|recovery| {
recovery
.mca_reference
.recovery_to_billing
.get(&payment_merchant_connector_account_id)
.cloned()
})
})
}
}
#[cfg(feature = "v2")]
/// Holds the payment methods enabled for a connector along with the connector name
/// This struct is a flattened representation of the payment methods enabled for a connector
#[derive(Debug)]
pub struct PaymentMethodsEnabledForConnector {
pub payment_methods_enabled: common_types::payment_methods::RequestPaymentMethodTypes,
pub payment_method: common_enums::PaymentMethod,
pub connector: common_enums::connector_enums::Connector,
pub merchant_connector_id: id_type::MerchantConnectorAccountId,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone)]
pub struct MerchantConnectorAccountFeatureMetadata {
pub revenue_recovery: Option<RevenueRecoveryMetadata>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone)]
pub struct RevenueRecoveryMetadata {
pub max_retry_count: u16,
pub billing_connector_retry_threshold: u16,
pub mca_reference: AccountReferenceMap,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Deserialize)]
pub struct ExternalVaultConnectorMetadata {
pub proxy_url: common_utils::types::Url,
pub certificate: Secret<String>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone)]
pub struct AccountReferenceMap {
pub recovery_to_billing: HashMap<id_type::MerchantConnectorAccountId, String>,
pub billing_to_recovery: HashMap<String, id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v2")]
impl AccountReferenceMap {
pub fn new(
hash_map: HashMap<id_type::MerchantConnectorAccountId, String>,
) -> Result<Self, api_error_response::ApiErrorResponse> {
Self::validate(&hash_map)?;
let recovery_to_billing = hash_map.clone();
let mut billing_to_recovery = HashMap::new();
for (key, value) in &hash_map {
billing_to_recovery.insert(value.clone(), key.clone());
}
Ok(Self {
recovery_to_billing,
billing_to_recovery,
})
}
fn validate(
hash_map: &HashMap<id_type::MerchantConnectorAccountId, String>,
) -> Result<(), api_error_response::ApiErrorResponse> {
let mut seen_values = std::collections::HashSet::new(); // To check uniqueness of values
for value in hash_map.values() {
if !seen_values.insert(value.clone()) {
return Err(api_error_response::ApiErrorResponse::InvalidRequestData {
message: "Duplicate account reference IDs found in Recovery feature metadata. Each account reference ID must be unique.".to_string(),
});
}
}
Ok(())
}
}
#[cfg(feature = "v2")]
/// Holds the payment methods enabled for a connector
pub struct FlattenedPaymentMethodsEnabled {
pub payment_methods_enabled: Vec<PaymentMethodsEnabledForConnector>,
}
#[cfg(feature = "v2")]
impl FlattenedPaymentMethodsEnabled {
/// This functions flattens the payment methods enabled from the connector accounts
/// Retains the connector name and payment method in every flattened element
pub fn from_payment_connectors_list(payment_connectors: Vec<MerchantConnectorAccount>) -> Self {
let payment_methods_enabled_flattened_with_connector = payment_connectors
.into_iter()
.map(|connector| {
(
connector
.payment_methods_enabled
.clone()
.unwrap_or_default(),
connector.connector_name,
connector.get_id(),
)
})
.flat_map(
|(payment_method_enabled, connector, merchant_connector_id)| {
payment_method_enabled
.into_iter()
.flat_map(move |payment_method| {
let request_payment_methods_enabled =
payment_method.payment_method_subtypes.unwrap_or_default();
let length = request_payment_methods_enabled.len();
request_payment_methods_enabled
.into_iter()
.zip(std::iter::repeat_n(
(
connector,
merchant_connector_id.clone(),
payment_method.payment_method_type,
),
length,
))
})
},
)
.map(
|(request_payment_methods, (connector, merchant_connector_id, payment_method))| {
PaymentMethodsEnabledForConnector {
payment_methods_enabled: request_payment_methods,
connector,
payment_method,
merchant_connector_id,
}
},
)
.collect();
Self {
payment_methods_enabled: payment_methods_enabled_flattened_with_connector,
}
}
}
#[cfg(feature = "v1")]
#[derive(Debug)]
pub enum MerchantConnectorAccountUpdate {
Update {
connector_type: Option<enums::ConnectorType>,
connector_name: Option<String>,
connector_account_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
test_mode: Option<bool>,
disabled: Option<bool>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>,
metadata: Option<pii::SecretSerdeValue>,
frm_configs: Option<Vec<pii::SecretSerdeValue>>,
connector_webhook_details: Box<Option<pii::SecretSerdeValue>>,
applepay_verified_domains: Option<Vec<String>>,
pm_auth_config: Box<Option<pii::SecretSerdeValue>>,
connector_label: Option<String>,
status: Option<enums::ConnectorStatus>,
connector_wallets_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
additional_merchant_data: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
},
ConnectorWalletDetailsUpdate {
connector_wallets_details: Encryptable<pii::SecretSerdeValue>,
},
}
#[cfg(feature = "v2")]
#[derive(Debug)]
pub enum MerchantConnectorAccountUpdate {
Update {
connector_type: Option<enums::ConnectorType>,
connector_account_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
disabled: Option<bool>,
payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>,
metadata: Option<pii::SecretSerdeValue>,
frm_configs: Option<Vec<pii::SecretSerdeValue>>,
connector_webhook_details: Box<Option<pii::SecretSerdeValue>>,
applepay_verified_domains: Option<Vec<String>>,
pm_auth_config: Box<Option<pii::SecretSerdeValue>>,
connector_label: Option<String>,
status: Option<enums::ConnectorStatus>,
connector_wallets_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
additional_merchant_data: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
feature_metadata: Box<Option<MerchantConnectorAccountFeatureMetadata>>,
},
ConnectorWalletDetailsUpdate {
connector_wallets_details: Encryptable<pii::SecretSerdeValue>,
},
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl behaviour::Conversion for MerchantConnectorAccount {
type DstType = storage::MerchantConnectorAccount;
type NewDstType = storage::MerchantConnectorAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(storage::MerchantConnectorAccount {
merchant_id: self.merchant_id,
connector_name: self.connector_name,
connector_account_details: self.connector_account_details.into(),
test_mode: self.test_mode,
disabled: self.disabled,
merchant_connector_id: self.merchant_connector_id.clone(),
id: Some(self.merchant_connector_id),
payment_methods_enabled: self.payment_methods_enabled,
connector_type: self.connector_type,
metadata: self.metadata,
frm_configs: None,
frm_config: self.frm_configs,
business_country: self.business_country,
business_label: self.business_label,
connector_label: self.connector_label,
business_sub_label: self.business_sub_label,
created_at: self.created_at,
modified_at: self.modified_at,
connector_webhook_details: self.connector_webhook_details,
profile_id: Some(self.profile_id),
applepay_verified_domains: self.applepay_verified_domains,
pm_auth_config: self.pm_auth_config,
status: self.status,
connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),
version: self.version,
})
}
async fn convert_back(
state: &KeyManagerState,
other: Self::DstType,
key: &Secret<Vec<u8>>,
_key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let identifier = Identifier::Merchant(other.merchant_id.clone());
let decrypted_data = crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::BatchDecrypt(EncryptedMerchantConnectorAccount::to_encryptable(
EncryptedMerchantConnectorAccount {
connector_account_details: other.connector_account_details,
additional_merchant_data: other.additional_merchant_data,
connector_wallets_details: other.connector_wallets_details,
},
)),
identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting connector account details".to_string(),
})?;
let decrypted_data = EncryptedMerchantConnectorAccount::from_encryptable(decrypted_data)
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting connector account details".to_string(),
})?;
Ok(Self {
merchant_id: other.merchant_id,
connector_name: other.connector_name,
connector_account_details: decrypted_data.connector_account_details,
test_mode: other.test_mode,
disabled: other.disabled,
merchant_connector_id: other.merchant_connector_id,
payment_methods_enabled: other.payment_methods_enabled,
connector_type: other.connector_type,
metadata: other.metadata,
frm_configs: other.frm_config,
business_country: other.business_country,
business_label: other.business_label,
connector_label: other.connector_label,
business_sub_label: other.business_sub_label,
created_at: other.created_at,
modified_at: other.modified_at,
connector_webhook_details: other.connector_webhook_details,
profile_id: other
.profile_id
.ok_or(ValidationError::MissingRequiredField {
field_name: "profile_id".to_string(),
})?,
applepay_verified_domains: other.applepay_verified_domains,
pm_auth_config: other.pm_auth_config,
status: other.status,
connector_wallets_details: decrypted_data.connector_wallets_details,
additional_merchant_data: decrypted_data.additional_merchant_data,
version: other.version,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(Self::NewDstType {
merchant_id: Some(self.merchant_id),
connector_name: Some(self.connector_name),
connector_account_details: Some(self.connector_account_details.into()),
test_mode: self.test_mode,
disabled: self.disabled,
merchant_connector_id: self.merchant_connector_id.clone(),
id: Some(self.merchant_connector_id),
payment_methods_enabled: self.payment_methods_enabled,
connector_type: Some(self.connector_type),
metadata: self.metadata,
frm_configs: None,
frm_config: self.frm_configs,
business_country: self.business_country,
business_label: self.business_label,
connector_label: self.connector_label,
business_sub_label: self.business_sub_label,
created_at: now,
modified_at: now,
connector_webhook_details: self.connector_webhook_details,
profile_id: Some(self.profile_id),
applepay_verified_domains: self.applepay_verified_domains,
pm_auth_config: self.pm_auth_config,
status: self.status,
connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),
version: self.version,
})
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl behaviour::Conversion for MerchantConnectorAccount {
type DstType = storage::MerchantConnectorAccount;
type NewDstType = storage::MerchantConnectorAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(storage::MerchantConnectorAccount {
id: self.id,
merchant_id: self.merchant_id,
connector_name: self.connector_name,
connector_account_details: self.connector_account_details.into(),
disabled: self.disabled,
payment_methods_enabled: self.payment_methods_enabled,
connector_type: self.connector_type,
metadata: self.metadata,
frm_config: self.frm_configs,
connector_label: self.connector_label,
created_at: self.created_at,
modified_at: self.modified_at,
connector_webhook_details: self.connector_webhook_details,
profile_id: self.profile_id,
applepay_verified_domains: self.applepay_verified_domains,
pm_auth_config: self.pm_auth_config,
status: self.status,
connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),
version: self.version,
feature_metadata: self.feature_metadata.map(From::from),
})
}
async fn convert_back(
state: &KeyManagerState,
other: Self::DstType,
key: &Secret<Vec<u8>>,
_key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let identifier = Identifier::Merchant(other.merchant_id.clone());
let decrypted_data = crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::BatchDecrypt(EncryptedMerchantConnectorAccount::to_encryptable(
EncryptedMerchantConnectorAccount {
connector_account_details: other.connector_account_details,
additional_merchant_data: other.additional_merchant_data,
connector_wallets_details: other.connector_wallets_details,
},
)),
identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting connector account details".to_string(),
})?;
let decrypted_data = EncryptedMerchantConnectorAccount::from_encryptable(decrypted_data)
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting connector account details".to_string(),
})?;
Ok(Self {
id: other.id,
merchant_id: other.merchant_id,
connector_name: other.connector_name,
connector_account_details: decrypted_data.connector_account_details,
disabled: other.disabled,
payment_methods_enabled: other.payment_methods_enabled,
connector_type: other.connector_type,
metadata: other.metadata,
frm_configs: other.frm_config,
connector_label: other.connector_label,
created_at: other.created_at,
modified_at: other.modified_at,
connector_webhook_details: other.connector_webhook_details,
profile_id: other.profile_id,
applepay_verified_domains: other.applepay_verified_domains,
pm_auth_config: other.pm_auth_config,
status: other.status,
connector_wallets_details: decrypted_data.connector_wallets_details,
additional_merchant_data: decrypted_data.additional_merchant_data,
version: other.version,
feature_metadata: other.feature_metadata.map(From::from),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(Self::NewDstType {
id: self.id,
merchant_id: Some(self.merchant_id),
connector_name: Some(self.connector_name),
connector_account_details: Some(self.connector_account_details.into()),
disabled: self.disabled,
payment_methods_enabled: self.payment_methods_enabled,
connector_type: Some(self.connector_type),
metadata: self.metadata,
frm_config: self.frm_configs,
connector_label: self.connector_label,
created_at: now,
modified_at: now,
connector_webhook_details: self.connector_webhook_details,
profile_id: self.profile_id,
applepay_verified_domains: self.applepay_verified_domains,
pm_auth_config: self.pm_auth_config,
status: self.status,
connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),
version: self.version,
feature_metadata: self.feature_metadata.map(From::from),
})
}
}
#[cfg(feature = "v1")]
impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInternal {
fn from(merchant_connector_account_update: MerchantConnectorAccountUpdate) -> Self {
match merchant_connector_account_update {
MerchantConnectorAccountUpdate::Update {
connector_type,
connector_name,
connector_account_details,
test_mode,
disabled,
merchant_connector_id,
payment_methods_enabled,
metadata,
frm_configs,
connector_webhook_details,
applepay_verified_domains,
pm_auth_config,
connector_label,
status,
connector_wallets_details,
additional_merchant_data,
} => Self {
connector_type,
connector_name,
connector_account_details: connector_account_details.map(Encryption::from),
test_mode,
disabled,
merchant_connector_id,
payment_methods_enabled,
metadata,
frm_configs: None,
frm_config: frm_configs,
modified_at: Some(date_time::now()),
connector_webhook_details: *connector_webhook_details,
applepay_verified_domains,
pm_auth_config: *pm_auth_config,
connector_label,
status,
connector_wallets_details: connector_wallets_details.map(Encryption::from),
additional_merchant_data: additional_merchant_data.map(Encryption::from),
},
MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate {
connector_wallets_details,
} => Self {
connector_wallets_details: Some(Encryption::from(connector_wallets_details)),
connector_type: None,
connector_name: None,
connector_account_details: None,
connector_label: None,
test_mode: None,
disabled: None,
merchant_connector_id: None,
payment_methods_enabled: None,
frm_configs: None,
metadata: None,
modified_at: None,
connector_webhook_details: None,
frm_config: None,
applepay_verified_domains: None,
pm_auth_config: None,
status: None,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/bulk_tokenization.rs | crates/hyperswitch_domain_models/src/bulk_tokenization.rs | use api_models::{payment_methods as payment_methods_api, payments as payments_api};
use cards::CardNumber;
use common_enums as enums;
use common_utils::{
errors,
ext_traits::OptionExt,
id_type, pii,
transformers::{ForeignFrom, ForeignTryFrom},
};
use error_stack::report;
use crate::{
address::{Address, AddressDetails, PhoneDetails},
router_request_types::CustomerDetails,
};
#[derive(Debug)]
pub struct CardNetworkTokenizeRequest {
pub data: TokenizeDataRequest,
pub customer: CustomerDetails,
pub billing: Option<Address>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_issuer: Option<String>,
}
#[derive(Debug)]
pub enum TokenizeDataRequest {
Card(TokenizeCardRequest),
ExistingPaymentMethod(TokenizePaymentMethodRequest),
}
#[derive(Clone, Debug)]
pub struct TokenizeCardRequest {
pub raw_card_number: CardNumber,
pub card_expiry_month: masking::Secret<String>,
pub card_expiry_year: masking::Secret<String>,
pub card_cvc: Option<masking::Secret<String>>,
pub card_holder_name: Option<masking::Secret<String>>,
pub nick_name: Option<masking::Secret<String>>,
pub card_issuing_country: Option<String>,
pub card_issuing_country_code: Option<String>,
pub card_network: Option<enums::CardNetwork>,
pub card_issuer: Option<String>,
pub card_type: Option<payment_methods_api::CardType>,
}
#[derive(Clone, Debug)]
pub struct TokenizePaymentMethodRequest {
pub payment_method_id: String,
pub card_cvc: Option<masking::Secret<String>>,
}
#[derive(Default, Debug, serde::Deserialize, serde::Serialize)]
pub struct CardNetworkTokenizeRecord {
// Card details
pub raw_card_number: Option<CardNumber>,
pub card_expiry_month: Option<masking::Secret<String>>,
pub card_expiry_year: Option<masking::Secret<String>>,
pub card_cvc: Option<masking::Secret<String>>,
pub card_holder_name: Option<masking::Secret<String>>,
pub nick_name: Option<masking::Secret<String>>,
pub card_issuing_country: Option<String>,
pub card_issuing_country_code: Option<String>,
pub card_network: Option<enums::CardNetwork>,
pub card_issuer: Option<String>,
pub card_type: Option<payment_methods_api::CardType>,
// Payment method details
pub payment_method_id: Option<String>,
pub payment_method_type: Option<payment_methods_api::CardType>,
pub payment_method_issuer: Option<String>,
// Customer details
pub customer_id: id_type::CustomerId,
#[serde(rename = "name")]
pub customer_name: Option<masking::Secret<String>>,
#[serde(rename = "email")]
pub customer_email: Option<pii::Email>,
#[serde(rename = "phone")]
pub customer_phone: Option<masking::Secret<String>>,
#[serde(rename = "phone_country_code")]
pub customer_phone_country_code: Option<String>,
#[serde(rename = "tax_registration_id")]
pub customer_tax_registration_id: Option<masking::Secret<String>>,
// Billing details
pub billing_address_city: Option<String>,
pub billing_address_country: Option<enums::CountryAlpha2>,
pub billing_address_line1: Option<masking::Secret<String>>,
pub billing_address_line2: Option<masking::Secret<String>>,
pub billing_address_line3: Option<masking::Secret<String>>,
pub billing_address_zip: Option<masking::Secret<String>>,
pub billing_address_state: Option<masking::Secret<String>>,
pub billing_address_first_name: Option<masking::Secret<String>>,
pub billing_address_last_name: Option<masking::Secret<String>>,
pub billing_phone_number: Option<masking::Secret<String>>,
pub billing_phone_country_code: Option<String>,
pub billing_email: Option<pii::Email>,
// Other details
pub line_number: Option<u64>,
pub merchant_id: Option<id_type::MerchantId>,
}
impl ForeignFrom<&CardNetworkTokenizeRecord> for payments_api::CustomerDetails {
fn foreign_from(record: &CardNetworkTokenizeRecord) -> Self {
Self {
id: record.customer_id.clone(),
name: record.customer_name.clone(),
email: record.customer_email.clone(),
phone: record.customer_phone.clone(),
phone_country_code: record.customer_phone_country_code.clone(),
tax_registration_id: record.customer_tax_registration_id.clone(),
}
}
}
impl ForeignFrom<&CardNetworkTokenizeRecord> for payments_api::Address {
fn foreign_from(record: &CardNetworkTokenizeRecord) -> Self {
Self {
address: Some(payments_api::AddressDetails {
first_name: record.billing_address_first_name.clone(),
last_name: record.billing_address_last_name.clone(),
line1: record.billing_address_line1.clone(),
line2: record.billing_address_line2.clone(),
line3: record.billing_address_line3.clone(),
city: record.billing_address_city.clone(),
zip: record.billing_address_zip.clone(),
state: record.billing_address_state.clone(),
country: record.billing_address_country,
origin_zip: None,
}),
phone: Some(payments_api::PhoneDetails {
number: record.billing_phone_number.clone(),
country_code: record.billing_phone_country_code.clone(),
}),
email: record.billing_email.clone(),
}
}
}
impl ForeignTryFrom<CardNetworkTokenizeRecord> for payment_methods_api::CardNetworkTokenizeRequest {
type Error = error_stack::Report<errors::ValidationError>;
fn foreign_try_from(record: CardNetworkTokenizeRecord) -> Result<Self, Self::Error> {
let billing = Some(payments_api::Address::foreign_from(&record));
let customer = payments_api::CustomerDetails::foreign_from(&record);
let merchant_id = record.merchant_id.get_required_value("merchant_id")?;
match (
record.raw_card_number,
record.card_expiry_month,
record.card_expiry_year,
record.payment_method_id,
) {
(Some(raw_card_number), Some(card_expiry_month), Some(card_expiry_year), None) => {
Ok(Self {
merchant_id,
data: payment_methods_api::TokenizeDataRequest::Card(
payment_methods_api::TokenizeCardRequest {
raw_card_number,
card_expiry_month,
card_expiry_year,
card_cvc: record.card_cvc,
card_holder_name: record.card_holder_name,
nick_name: record.nick_name,
card_issuing_country: record.card_issuing_country,
card_issuing_country_code: record.card_issuing_country_code,
card_network: record.card_network,
card_issuer: record.card_issuer,
card_type: record.card_type.clone(),
},
),
billing,
customer,
metadata: None,
payment_method_issuer: record.payment_method_issuer,
})
}
(None, None, None, Some(payment_method_id)) => Ok(Self {
merchant_id,
data: payment_methods_api::TokenizeDataRequest::ExistingPaymentMethod(
payment_methods_api::TokenizePaymentMethodRequest {
payment_method_id,
card_cvc: record.card_cvc,
},
),
billing,
customer,
metadata: None,
payment_method_issuer: record.payment_method_issuer,
}),
_ => Err(report!(errors::ValidationError::InvalidValue {
message: "Invalid record in bulk tokenization - expected one of card details or payment method details".to_string()
})),
}
}
}
impl ForeignFrom<&TokenizeCardRequest> for payment_methods_api::MigrateCardDetail {
fn foreign_from(card: &TokenizeCardRequest) -> Self {
Self {
card_number: masking::Secret::new(card.raw_card_number.get_card_no()),
card_exp_month: card.card_expiry_month.clone(),
card_exp_year: card.card_expiry_year.clone(),
card_holder_name: card.card_holder_name.clone(),
nick_name: card.nick_name.clone(),
card_issuing_country: card.card_issuing_country.clone(),
card_issuing_country_code: card.card_issuing_country_code.clone(),
card_network: card.card_network.clone(),
card_issuer: card.card_issuer.clone(),
card_type: card
.card_type
.as_ref()
.map(|card_type| card_type.to_string()),
}
}
}
impl ForeignTryFrom<CustomerDetails> for payments_api::CustomerDetails {
type Error = error_stack::Report<errors::ValidationError>;
fn foreign_try_from(customer: CustomerDetails) -> Result<Self, Self::Error> {
Ok(Self {
id: customer.customer_id.get_required_value("customer_id")?,
name: customer.name,
email: customer.email,
phone: customer.phone,
phone_country_code: customer.phone_country_code,
tax_registration_id: customer.tax_registration_id,
})
}
}
impl ForeignFrom<payment_methods_api::CardNetworkTokenizeRequest> for CardNetworkTokenizeRequest {
fn foreign_from(req: payment_methods_api::CardNetworkTokenizeRequest) -> Self {
Self {
data: TokenizeDataRequest::foreign_from(req.data),
customer: CustomerDetails::foreign_from(req.customer),
billing: req.billing.map(ForeignFrom::foreign_from),
metadata: req.metadata,
payment_method_issuer: req.payment_method_issuer,
}
}
}
impl ForeignFrom<payment_methods_api::TokenizeDataRequest> for TokenizeDataRequest {
fn foreign_from(req: payment_methods_api::TokenizeDataRequest) -> Self {
match req {
payment_methods_api::TokenizeDataRequest::Card(card) => {
Self::Card(TokenizeCardRequest {
raw_card_number: card.raw_card_number,
card_expiry_month: card.card_expiry_month,
card_expiry_year: card.card_expiry_year,
card_cvc: card.card_cvc,
card_holder_name: card.card_holder_name,
nick_name: card.nick_name,
card_issuing_country: card.card_issuing_country,
card_issuing_country_code: card.card_issuing_country_code,
card_network: card.card_network,
card_issuer: card.card_issuer,
card_type: card.card_type,
})
}
payment_methods_api::TokenizeDataRequest::ExistingPaymentMethod(pm) => {
Self::ExistingPaymentMethod(TokenizePaymentMethodRequest {
payment_method_id: pm.payment_method_id,
card_cvc: pm.card_cvc,
})
}
}
}
}
impl ForeignFrom<payments_api::CustomerDetails> for CustomerDetails {
fn foreign_from(req: payments_api::CustomerDetails) -> Self {
Self {
customer_id: Some(req.id),
name: req.name,
email: req.email,
phone: req.phone,
phone_country_code: req.phone_country_code,
tax_registration_id: req.tax_registration_id,
}
}
}
impl ForeignFrom<payments_api::Address> for Address {
fn foreign_from(req: payments_api::Address) -> Self {
Self {
address: req.address.map(ForeignFrom::foreign_from),
phone: req.phone.map(ForeignFrom::foreign_from),
email: req.email,
}
}
}
impl ForeignFrom<payments_api::AddressDetails> for AddressDetails {
fn foreign_from(req: payments_api::AddressDetails) -> Self {
Self {
city: req.city,
country: req.country,
line1: req.line1,
line2: req.line2,
line3: req.line3,
zip: req.zip,
state: req.state,
first_name: req.first_name,
last_name: req.last_name,
origin_zip: req.origin_zip,
}
}
}
impl ForeignFrom<payments_api::PhoneDetails> for PhoneDetails {
fn foreign_from(req: payments_api::PhoneDetails) -> Self {
Self {
number: req.number,
country_code: req.country_code,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/payouts.rs | crates/hyperswitch_domain_models/src/payouts.rs | pub mod payout_attempt;
#[allow(clippy::module_inception)]
pub mod payouts;
use common_enums as storage_enums;
use common_utils::{consts, id_type};
use time::PrimitiveDateTime;
pub enum PayoutFetchConstraints {
Single { payout_id: id_type::PayoutId },
List(Box<PayoutListParams>),
}
pub struct PayoutListParams {
pub offset: u32,
pub starting_at: Option<PrimitiveDateTime>,
pub ending_at: Option<PrimitiveDateTime>,
pub connector: Option<Vec<api_models::enums::PayoutConnectors>>,
pub currency: Option<Vec<storage_enums::Currency>>,
pub status: Option<Vec<storage_enums::PayoutStatus>>,
pub payout_method: Option<Vec<common_enums::PayoutType>>,
pub profile_id: Option<id_type::ProfileId>,
pub customer_id: Option<id_type::CustomerId>,
pub starting_after_id: Option<id_type::PayoutId>,
pub ending_before_id: Option<id_type::PayoutId>,
pub entity_type: Option<common_enums::PayoutEntityType>,
pub limit: Option<u32>,
pub merchant_order_reference_id: Option<String>,
}
impl From<api_models::payouts::PayoutListConstraints> for PayoutFetchConstraints {
fn from(value: api_models::payouts::PayoutListConstraints) -> Self {
Self::List(Box::new(PayoutListParams {
offset: 0,
starting_at: value
.time_range
.map_or(value.created, |t| Some(t.start_time)),
ending_at: value.time_range.and_then(|t| t.end_time),
connector: None,
currency: None,
status: None,
payout_method: None,
profile_id: None,
customer_id: value.customer_id,
starting_after_id: value.starting_after,
ending_before_id: value.ending_before,
entity_type: None,
merchant_order_reference_id: None,
limit: Some(std::cmp::min(
value.limit,
consts::PAYOUTS_LIST_MAX_LIMIT_GET,
)),
}))
}
}
impl From<common_utils::types::TimeRange> for PayoutFetchConstraints {
fn from(value: common_utils::types::TimeRange) -> Self {
Self::List(Box::new(PayoutListParams {
offset: 0,
starting_at: Some(value.start_time),
ending_at: value.end_time,
connector: None,
currency: None,
status: None,
payout_method: None,
profile_id: None,
customer_id: None,
starting_after_id: None,
ending_before_id: None,
entity_type: None,
merchant_order_reference_id: None,
limit: None,
}))
}
}
impl From<api_models::payouts::PayoutListFilterConstraints> for PayoutFetchConstraints {
fn from(value: api_models::payouts::PayoutListFilterConstraints) -> Self {
if let Some(payout_id) = value.payout_id {
Self::Single { payout_id }
} else {
Self::List(Box::new(PayoutListParams {
offset: value.offset.unwrap_or_default(),
starting_at: value.time_range.map(|t| t.start_time),
ending_at: value.time_range.and_then(|t| t.end_time),
connector: value.connector,
currency: value.currency,
status: value.status,
payout_method: value.payout_method,
profile_id: value.profile_id,
customer_id: value.customer_id,
starting_after_id: None,
ending_before_id: None,
entity_type: value.entity_type,
merchant_order_reference_id: value.merchant_order_reference_id,
limit: Some(std::cmp::min(
value.limit,
consts::PAYOUTS_LIST_MAX_LIMIT_POST,
)),
}))
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/chat.rs | crates/hyperswitch_domain_models/src/chat.rs | use common_utils::id_type;
use masking::Secret;
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct GetDataMessage {
pub message: Secret<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct HyperswitchAiDataRequest {
pub merchant_id: id_type::MerchantId,
pub profile_id: id_type::ProfileId,
pub org_id: id_type::OrganizationId,
pub query: GetDataMessage,
pub entity_type: common_enums::EntityType,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/gsm.rs | crates/hyperswitch_domain_models/src/gsm.rs | use common_utils::{errors::ValidationError, ext_traits::StringExt};
use serde::{self, Deserialize, Serialize};
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct GatewayStatusMap {
pub connector: String,
pub flow: String,
pub sub_flow: String,
pub code: String,
pub message: String,
pub status: String,
pub router_error: Option<String>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub error_category: Option<common_enums::ErrorCategory>,
pub feature_data: common_types::domain::GsmFeatureData,
pub feature: common_enums::GsmFeature,
pub standardised_code: Option<common_enums::StandardisedCode>,
pub description: Option<String>,
pub user_guidance_message: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GatewayStatusMappingUpdate {
pub status: Option<String>,
pub router_error: Option<Option<String>>,
pub decision: Option<common_enums::GsmDecision>,
pub step_up_possible: Option<bool>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub error_category: Option<common_enums::ErrorCategory>,
pub clear_pan_possible: Option<bool>,
pub feature_data: Option<common_types::domain::GsmFeatureData>,
pub feature: Option<common_enums::GsmFeature>,
pub standardised_code: Option<common_enums::StandardisedCode>,
pub description: Option<String>,
pub user_guidance_message: Option<String>,
}
impl TryFrom<GatewayStatusMap> for diesel_models::gsm::GatewayStatusMappingNew {
type Error = error_stack::Report<ValidationError>;
fn try_from(value: GatewayStatusMap) -> Result<Self, Self::Error> {
Ok(Self {
connector: value.connector.to_string(),
flow: value.flow,
sub_flow: value.sub_flow,
code: value.code,
message: value.message,
status: value.status.clone(),
router_error: value.router_error,
decision: value.feature_data.get_decision().to_string(),
step_up_possible: value
.feature_data
.get_retry_feature_data()
.map(|retry_feature_data| retry_feature_data.is_step_up_possible())
.unwrap_or(false),
unified_code: value.unified_code,
unified_message: value.unified_message,
error_category: value.error_category,
clear_pan_possible: value
.feature_data
.get_retry_feature_data()
.map(|retry_feature_data| retry_feature_data.is_clear_pan_possible())
.unwrap_or(false),
feature_data: Some(value.feature_data),
feature: Some(value.feature),
standardised_code: value.standardised_code,
description: value.description,
user_guidance_message: value.user_guidance_message,
})
}
}
impl TryFrom<GatewayStatusMappingUpdate> for diesel_models::gsm::GatewayStatusMappingUpdate {
type Error = error_stack::Report<ValidationError>;
fn try_from(value: GatewayStatusMappingUpdate) -> Result<Self, Self::Error> {
Ok(Self {
status: value.status,
router_error: value.router_error,
decision: value.decision.map(|gsm_decision| gsm_decision.to_string()),
step_up_possible: value.step_up_possible,
unified_code: value.unified_code,
unified_message: value.unified_message,
error_category: value.error_category,
clear_pan_possible: value.clear_pan_possible,
feature_data: value.feature_data,
feature: value.feature,
standardised_code: value.standardised_code,
description: value.description,
user_guidance_message: value.user_guidance_message,
})
}
}
impl TryFrom<diesel_models::gsm::GatewayStatusMap> for GatewayStatusMap {
type Error = ValidationError;
fn try_from(item: diesel_models::gsm::GatewayStatusMap) -> Result<Self, Self::Error> {
let decision =
StringExt::<common_enums::GsmDecision>::parse_enum(item.decision, "GsmDecision")
.map_err(|_| ValidationError::InvalidValue {
message: "Failed to parse GsmDecision".to_string(),
})?;
let db_feature_data = item.feature_data;
// The only case where `FeatureData` can be null is for legacy records
// (i.e., records created before `FeatureData` and related features were introduced).
// At that time, the only supported feature was `Retry`, so it's safe to default to it.
let feature_data = match db_feature_data {
Some(common_types::domain::GsmFeatureData::Retry(data)) => {
common_types::domain::GsmFeatureData::Retry(data)
}
None => common_types::domain::GsmFeatureData::Retry(
common_types::domain::RetryFeatureData {
step_up_possible: item.step_up_possible,
clear_pan_possible: item.clear_pan_possible,
alternate_network_possible: false,
decision,
},
),
};
let feature = item.feature.unwrap_or(common_enums::GsmFeature::Retry);
Ok(Self {
connector: item.connector,
flow: item.flow,
sub_flow: item.sub_flow,
code: item.code,
message: item.message,
status: item.status,
router_error: item.router_error,
unified_code: item.unified_code,
unified_message: item.unified_message,
error_category: item.error_category,
feature_data,
feature,
standardised_code: item.standardised_code,
description: item.description,
user_guidance_message: item.user_guidance_message,
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/payment_methods.rs | crates/hyperswitch_domain_models/src/payment_methods.rs | #[cfg(feature = "v2")]
use std::collections::HashMap;
#[cfg(feature = "v2")]
use api_models::payment_methods::PaymentMethodsData;
use api_models::{customers, payment_methods, payments};
// specific imports because of using the macro
use common_enums::enums::MerchantStorageScheme;
#[cfg(feature = "v1")]
use common_utils::crypto::OptionalEncryptableValue;
#[cfg(feature = "v2")]
use common_utils::{
crypto::Encryptable, encryption::Encryption, ext_traits::OptionExt,
types::keymanager::ToEncryptable,
};
use common_utils::{
errors::{CustomResult, ParsingError, ValidationError},
id_type, pii, type_name,
types::{keymanager, CreatedBy},
};
pub use diesel_models::{enums as storage_enums, PaymentMethodUpdate};
use error_stack::ResultExt;
#[cfg(feature = "v1")]
use masking::ExposeInterface;
use masking::{PeekInterface, Secret};
#[cfg(feature = "v1")]
use router_env::logger;
#[cfg(feature = "v2")]
use rustc_hash::FxHashMap;
#[cfg(feature = "v2")]
use serde_json::Value;
use time::PrimitiveDateTime;
#[cfg(feature = "v2")]
use crate::address::Address;
#[cfg(feature = "v1")]
use crate::type_encryption::AsyncLift;
use crate::{
mandates::{self, CommonMandateReference},
merchant_key_store::MerchantKeyStore,
payment_method_data as domain_payment_method_data,
transformers::ForeignTryFrom,
type_encryption::{crypto_operation, CryptoOperation},
};
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct VaultId(String);
impl VaultId {
pub fn get_string_repr(&self) -> &String {
&self.0
}
pub fn generate(id: String) -> Self {
Self(id)
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub struct PaymentMethod {
pub customer_id: id_type::CustomerId,
pub merchant_id: id_type::MerchantId,
pub payment_method_id: String,
pub accepted_currency: Option<Vec<storage_enums::Currency>>,
pub scheme: Option<String>,
pub token: Option<String>,
pub cardholder_name: Option<Secret<String>>,
pub issuer_name: Option<String>,
pub issuer_country: Option<String>,
pub payer_country: Option<Vec<String>>,
pub is_stored: Option<bool>,
pub swift_code: Option<String>,
pub direct_debit_token: Option<String>,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_issuer: Option<String>,
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: OptionalEncryptableValue,
pub locker_id: Option<String>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
pub payment_method_billing_address: OptionalEncryptableValue,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
pub network_token_payment_method_data: OptionalEncryptableValue,
pub vault_source_details: PaymentMethodVaultSourceDetails,
pub created_by: Option<CreatedBy>,
pub last_modified_by: Option<CreatedBy>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, router_derive::ToEncryption, serde::Serialize)]
pub struct PaymentMethod {
/// The identifier for the payment method. Using this recurring payments can be made
pub id: id_type::GlobalPaymentMethodId,
/// The customer id against which the payment method is saved
/// It is made optional to support guest checkout tokenization
pub customer_id: Option<id_type::GlobalCustomerId>,
/// The merchant id against which the payment method is saved
pub merchant_id: id_type::MerchantId,
/// The merchant connector account id of the external vault where the payment method is saved
pub external_vault_source: Option<id_type::MerchantConnectorAccountId>,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub payment_method_type: Option<storage_enums::PaymentMethod>,
pub payment_method_subtype: Option<storage_enums::PaymentMethodType>,
#[encrypt(ty = Value)]
pub payment_method_data: Option<Encryptable<PaymentMethodsData>>,
pub locker_id: Option<VaultId>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<CommonMandateReference>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
#[encrypt(ty = Value)]
pub payment_method_billing_address: Option<Encryptable<Address>>,
pub updated_by: Option<String>,
pub locker_fingerprint_id: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
#[encrypt(ty = Value)]
pub network_token_payment_method_data:
Option<Encryptable<domain_payment_method_data::PaymentMethodsData>>,
#[encrypt(ty = Value)]
pub external_vault_token_data:
Option<Encryptable<api_models::payment_methods::ExternalVaultTokenData>>,
pub vault_type: Option<storage_enums::VaultType>,
pub created_by: Option<CreatedBy>,
pub last_modified_by: Option<CreatedBy>,
}
impl PaymentMethod {
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &String {
&self.payment_method_id
}
#[cfg(feature = "v1")]
pub fn get_payment_methods_data(
&self,
) -> Option<domain_payment_method_data::PaymentMethodsData> {
self.payment_method_data
.clone()
.map(|value| value.into_inner().expose())
.and_then(|value| {
serde_json::from_value::<domain_payment_method_data::PaymentMethodsData>(value)
.map_err(|error| {
logger::warn!(
?error,
"Failed to parse payment method data in payment method info"
);
})
.ok()
})
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &id_type::GlobalPaymentMethodId {
&self.id
}
#[cfg(feature = "v1")]
pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethod> {
self.payment_method
}
#[cfg(feature = "v2")]
pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethod> {
self.payment_method_type
}
#[cfg(feature = "v1")]
pub fn get_payment_method_subtype(&self) -> Option<storage_enums::PaymentMethodType> {
self.payment_method_type
}
#[cfg(feature = "v2")]
pub fn get_payment_method_subtype(&self) -> Option<storage_enums::PaymentMethodType> {
self.payment_method_subtype
}
#[cfg(feature = "v1")]
pub fn get_common_mandate_reference(&self) -> Result<CommonMandateReference, ParsingError> {
let payments_data = self
.connector_mandate_details
.clone()
.map(|mut mandate_details| {
mandate_details
.as_object_mut()
.map(|obj| obj.remove("payouts"));
serde_json::from_value::<mandates::PaymentsMandateReference>(mandate_details)
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payments data: {:?}", err);
})
})
.transpose()
.map_err(|err| {
router_env::logger::error!("Failed to parse payments data: {:?}", err);
ParsingError::StructParseFailure("Failed to parse payments data")
})?;
let payouts_data = self
.connector_mandate_details
.clone()
.map(|mandate_details| {
serde_json::from_value::<Option<CommonMandateReference>>(mandate_details)
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payouts data: {:?}", err);
})
.map(|optional_common_mandate_details| {
optional_common_mandate_details
.and_then(|common_mandate_details| common_mandate_details.payouts)
})
})
.transpose()
.map_err(|err| {
router_env::logger::error!("Failed to parse payouts data: {:?}", err);
ParsingError::StructParseFailure("Failed to parse payouts data")
})?
.flatten();
Ok(CommonMandateReference {
payments: payments_data,
payouts: payouts_data,
})
}
#[cfg(feature = "v2")]
pub fn get_common_mandate_reference(&self) -> Result<CommonMandateReference, ParsingError> {
if let Some(value) = &self.connector_mandate_details {
Ok(value.clone())
} else {
Ok(CommonMandateReference {
payments: None,
payouts: None,
})
}
}
#[cfg(feature = "v1")]
pub fn get_payment_connector_customer_id(
&self,
merchant_connector_account_id: id_type::MerchantConnectorAccountId,
) -> Result<Option<String>, ParsingError> {
let common_mandate_reference = self.get_common_mandate_reference()?;
Ok(common_mandate_reference
.payments
.as_ref()
.and_then(|payments| payments.get(&merchant_connector_account_id))
.and_then(|record| record.connector_customer_id.clone()))
}
#[cfg(feature = "v2")]
pub fn get_payment_connector_customer_id(
&self,
merchant_connector_account_id: id_type::MerchantConnectorAccountId,
) -> Result<Option<String>, ParsingError> {
todo!()
}
#[cfg(feature = "v1")]
pub fn get_payout_connector_customer_id(
&self,
merchant_connector_account_id: id_type::MerchantConnectorAccountId,
) -> Result<Option<String>, ParsingError> {
let common_mandate_reference = self.get_common_mandate_reference()?;
Ok(common_mandate_reference
.payouts
.as_ref()
.and_then(|payouts| payouts.get(&merchant_connector_account_id))
.and_then(|record| record.connector_customer_id.clone()))
}
#[cfg(feature = "v1")]
pub fn get_payment_method_metadata(
&self,
optional_metadata: Option<pii::SecretSerdeValue>,
) -> Option<pii::SecretSerdeValue> {
common_utils::merge_json_values(self.metadata.clone(), optional_metadata)
}
#[cfg(feature = "v2")]
pub fn get_payout_connector_customer_id(
&self,
merchant_connector_account_id: id_type::MerchantConnectorAccountId,
) -> Result<Option<String>, ParsingError> {
todo!()
}
#[cfg(feature = "v2")]
pub fn set_payment_method_type(&mut self, payment_method_type: common_enums::PaymentMethod) {
self.payment_method_type = Some(payment_method_type);
}
#[cfg(feature = "v2")]
pub fn set_payment_method_subtype(
&mut self,
payment_method_subtype: common_enums::PaymentMethodType,
) {
self.payment_method_subtype = Some(payment_method_subtype);
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl super::behaviour::Conversion for PaymentMethod {
type DstType = diesel_models::payment_method::PaymentMethod;
type NewDstType = diesel_models::payment_method::PaymentMethodNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let (vault_type, external_vault_source) = self.vault_source_details.into();
Ok(Self::DstType {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
payment_method_id: self.payment_method_id,
accepted_currency: self.accepted_currency,
scheme: self.scheme,
token: self.token,
cardholder_name: self.cardholder_name,
issuer_name: self.issuer_name,
issuer_country: self.issuer_country,
payer_country: self.payer_country,
is_stored: self.is_stored,
swift_code: self.swift_code,
direct_debit_token: self.direct_debit_token,
created_at: self.created_at,
last_modified: self.last_modified,
payment_method: self.payment_method,
payment_method_type: self.payment_method_type,
payment_method_issuer: self.payment_method_issuer,
payment_method_issuer_code: self.payment_method_issuer_code,
metadata: self.metadata,
payment_method_data: self.payment_method_data.map(|val| val.into()),
locker_id: self.locker_id,
last_used_at: self.last_used_at,
connector_mandate_details: self.connector_mandate_details,
customer_acceptance: self.customer_acceptance,
status: self.status,
network_transaction_id: self.network_transaction_id,
client_secret: self.client_secret,
payment_method_billing_address: self
.payment_method_billing_address
.map(|val| val.into()),
updated_by: self.updated_by,
version: self.version,
network_token_requestor_reference_id: self.network_token_requestor_reference_id,
network_token_locker_id: self.network_token_locker_id,
network_token_payment_method_data: self
.network_token_payment_method_data
.map(|val| val.into()),
external_vault_source,
vault_type,
created_by: self.created_by.map(|created_by| created_by.to_string()),
last_modified_by: self
.last_modified_by
.map(|last_modified_by| last_modified_by.to_string()),
})
}
async fn convert_back(
state: &keymanager::KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
// Decrypt encrypted fields first
let (
payment_method_data,
payment_method_billing_address,
network_token_payment_method_data,
) = async {
let payment_method_data = item
.payment_method_data
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?;
let payment_method_billing_address = item
.payment_method_billing_address
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?;
let network_token_payment_method_data = item
.network_token_payment_method_data
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?;
Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>((
payment_method_data,
payment_method_billing_address,
network_token_payment_method_data,
))
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting payment method data".to_string(),
})?;
let vault_source_details = PaymentMethodVaultSourceDetails::try_from((
item.vault_type,
item.external_vault_source,
))?;
// Construct the domain type
Ok(Self {
customer_id: item.customer_id,
merchant_id: item.merchant_id,
payment_method_id: item.payment_method_id,
accepted_currency: item.accepted_currency,
scheme: item.scheme,
token: item.token,
cardholder_name: item.cardholder_name,
issuer_name: item.issuer_name,
issuer_country: item.issuer_country,
payer_country: item.payer_country,
is_stored: item.is_stored,
swift_code: item.swift_code,
direct_debit_token: item.direct_debit_token,
created_at: item.created_at,
last_modified: item.last_modified,
payment_method: item.payment_method,
payment_method_type: item.payment_method_type,
payment_method_issuer: item.payment_method_issuer,
payment_method_issuer_code: item.payment_method_issuer_code,
metadata: item.metadata,
payment_method_data,
locker_id: item.locker_id,
last_used_at: item.last_used_at,
connector_mandate_details: item.connector_mandate_details,
customer_acceptance: item.customer_acceptance,
status: item.status,
network_transaction_id: item.network_transaction_id,
client_secret: item.client_secret,
payment_method_billing_address,
updated_by: item.updated_by,
version: item.version,
network_token_requestor_reference_id: item.network_token_requestor_reference_id,
network_token_locker_id: item.network_token_locker_id,
network_token_payment_method_data,
vault_source_details,
created_by: item
.created_by
.and_then(|created_by| created_by.parse::<CreatedBy>().ok()),
last_modified_by: item
.last_modified_by
.and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let (vault_type, external_vault_source) = self.vault_source_details.into();
Ok(Self::NewDstType {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
payment_method_id: self.payment_method_id,
accepted_currency: self.accepted_currency,
scheme: self.scheme,
token: self.token,
cardholder_name: self.cardholder_name,
issuer_name: self.issuer_name,
issuer_country: self.issuer_country,
payer_country: self.payer_country,
is_stored: self.is_stored,
swift_code: self.swift_code,
direct_debit_token: self.direct_debit_token,
created_at: self.created_at,
last_modified: self.last_modified,
payment_method: self.payment_method,
payment_method_type: self.payment_method_type,
payment_method_issuer: self.payment_method_issuer,
payment_method_issuer_code: self.payment_method_issuer_code,
metadata: self.metadata,
payment_method_data: self.payment_method_data.map(|val| val.into()),
locker_id: self.locker_id,
last_used_at: self.last_used_at,
connector_mandate_details: self.connector_mandate_details,
customer_acceptance: self.customer_acceptance,
status: self.status,
network_transaction_id: self.network_transaction_id,
client_secret: self.client_secret,
payment_method_billing_address: self
.payment_method_billing_address
.map(|val| val.into()),
updated_by: self.updated_by,
version: self.version,
network_token_requestor_reference_id: self.network_token_requestor_reference_id,
network_token_locker_id: self.network_token_locker_id,
network_token_payment_method_data: self
.network_token_payment_method_data
.map(|val| val.into()),
external_vault_source,
vault_type,
created_by: self.created_by.map(|created_by| created_by.to_string()),
last_modified_by: self
.last_modified_by
.map(|last_modified_by| last_modified_by.to_string()),
})
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl super::behaviour::Conversion for PaymentMethod {
type DstType = diesel_models::payment_method::PaymentMethod;
type NewDstType = diesel_models::payment_method::PaymentMethodNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(Self::DstType {
customer_id: self.customer_id.get_required_value("GlobalCustomerId")?,
merchant_id: self.merchant_id,
id: self.id,
created_at: self.created_at,
last_modified: self.last_modified,
payment_method_type_v2: self.payment_method_type,
payment_method_subtype: self.payment_method_subtype,
payment_method_data: self.payment_method_data.map(|val| val.into()),
locker_id: self.locker_id.map(|id| id.get_string_repr().clone()),
last_used_at: self.last_used_at,
connector_mandate_details: self.connector_mandate_details.map(|cmd| cmd.into()),
customer_acceptance: self.customer_acceptance,
status: self.status,
network_transaction_id: self.network_transaction_id,
client_secret: self.client_secret,
payment_method_billing_address: self
.payment_method_billing_address
.map(|val| val.into()),
updated_by: self.updated_by,
locker_fingerprint_id: self.locker_fingerprint_id,
version: self.version,
network_token_requestor_reference_id: self.network_token_requestor_reference_id,
network_token_locker_id: self.network_token_locker_id,
network_token_payment_method_data: self
.network_token_payment_method_data
.map(|val| val.into()),
external_vault_source: self.external_vault_source,
external_vault_token_data: self.external_vault_token_data.map(|val| val.into()),
vault_type: self.vault_type,
created_by: self.created_by.map(|created_by| created_by.to_string()),
last_modified_by: self
.last_modified_by
.map(|last_modified_by| last_modified_by.to_string()),
})
}
async fn convert_back(
state: &keymanager::KeyManagerState,
storage_model: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
use common_utils::ext_traits::ValueExt;
async {
let decrypted_data = crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::BatchDecrypt(EncryptedPaymentMethod::to_encryptable(
EncryptedPaymentMethod {
payment_method_data: storage_model.payment_method_data,
payment_method_billing_address: storage_model
.payment_method_billing_address,
network_token_payment_method_data: storage_model
.network_token_payment_method_data,
external_vault_token_data: storage_model.external_vault_token_data,
},
)),
key_manager_identifier,
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())?;
let data = EncryptedPaymentMethod::from_encryptable(decrypted_data)
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Invalid batch operation data")?;
let payment_method_billing_address = data
.payment_method_billing_address
.map(|billing| {
billing.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing Address")?;
let payment_method_data = data
.payment_method_data
.map(|payment_method_data| {
payment_method_data
.deserialize_inner_value(|value| value.parse_value("Payment Method Data"))
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing Payment Method Data")?;
let network_token_payment_method_data = data
.network_token_payment_method_data
.map(|network_token_payment_method_data| {
network_token_payment_method_data.deserialize_inner_value(|value| {
value.parse_value("Network token Payment Method Data")
})
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing Network token Payment Method Data")?;
let external_vault_token_data = data
.external_vault_token_data
.map(|external_vault_token_data| {
external_vault_token_data.deserialize_inner_value(|value| {
value.parse_value("External Vault Token Data")
})
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing External Vault Token Data")?;
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
customer_id: Some(storage_model.customer_id),
merchant_id: storage_model.merchant_id,
id: storage_model.id,
created_at: storage_model.created_at,
last_modified: storage_model.last_modified,
payment_method_type: storage_model.payment_method_type_v2,
payment_method_subtype: storage_model.payment_method_subtype,
payment_method_data,
locker_id: storage_model.locker_id.map(VaultId::generate),
last_used_at: storage_model.last_used_at,
connector_mandate_details: storage_model.connector_mandate_details.map(From::from),
customer_acceptance: storage_model.customer_acceptance,
status: storage_model.status,
network_transaction_id: storage_model.network_transaction_id,
client_secret: storage_model.client_secret,
payment_method_billing_address,
updated_by: storage_model.updated_by,
locker_fingerprint_id: storage_model.locker_fingerprint_id,
version: storage_model.version,
network_token_requestor_reference_id: storage_model
.network_token_requestor_reference_id,
network_token_locker_id: storage_model.network_token_locker_id,
network_token_payment_method_data,
external_vault_source: storage_model.external_vault_source,
external_vault_token_data,
vault_type: storage_model.vault_type,
created_by: storage_model
.created_by
.and_then(|created_by| created_by.parse::<CreatedBy>().ok()),
last_modified_by: storage_model
.last_modified_by
.and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting payment method data".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(Self::NewDstType {
customer_id: self.customer_id.get_required_value("GlobalCustomerId")?,
merchant_id: self.merchant_id,
id: self.id,
created_at: self.created_at,
last_modified: self.last_modified,
payment_method_type_v2: self.payment_method_type,
payment_method_subtype: self.payment_method_subtype,
payment_method_data: self.payment_method_data.map(|val| val.into()),
locker_id: self.locker_id.map(|id| id.get_string_repr().clone()),
last_used_at: self.last_used_at,
connector_mandate_details: self.connector_mandate_details.map(|cmd| cmd.into()),
customer_acceptance: self.customer_acceptance,
status: self.status,
network_transaction_id: self.network_transaction_id,
client_secret: self.client_secret,
payment_method_billing_address: self
.payment_method_billing_address
.map(|val| val.into()),
updated_by: self.updated_by,
locker_fingerprint_id: self.locker_fingerprint_id,
version: self.version,
network_token_requestor_reference_id: self.network_token_requestor_reference_id,
network_token_locker_id: self.network_token_locker_id,
network_token_payment_method_data: self
.network_token_payment_method_data
.map(|val| val.into()),
external_vault_token_data: self.external_vault_token_data.map(|val| val.into()),
vault_type: self.vault_type,
created_by: self.created_by.map(|created_by| created_by.to_string()),
last_modified_by: self
.last_modified_by
.map(|last_modified_by| last_modified_by.to_string()),
})
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct PaymentMethodSession {
pub id: id_type::GlobalPaymentMethodSessionId,
pub customer_id: Option<id_type::GlobalCustomerId>,
#[encrypt(ty = Value)]
pub billing: Option<Encryptable<Address>>,
pub return_url: Option<common_utils::types::Url>,
pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>,
pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,
pub tokenization_data: Option<pii::SecretSerdeValue>,
pub expires_at: PrimitiveDateTime,
pub associated_payment_methods: Option<Vec<String>>,
pub associated_payment: Option<id_type::GlobalPaymentId>,
pub associated_token_id: Option<id_type::GlobalTokenId>,
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl super::behaviour::Conversion for PaymentMethodSession {
type DstType = diesel_models::payment_methods_session::PaymentMethodSession;
type NewDstType = diesel_models::payment_methods_session::PaymentMethodSession;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(Self::DstType {
id: self.id,
customer_id: self.customer_id,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/transformers.rs | crates/hyperswitch_domain_models/src/transformers.rs | pub trait ForeignFrom<F> {
fn foreign_from(from: F) -> Self;
}
pub trait ForeignTryFrom<F>: Sized {
type Error;
fn foreign_try_from(from: F) -> Result<Self, Self::Error>;
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/authentication.rs | crates/hyperswitch_domain_models/src/authentication.rs | use std::str::FromStr;
use async_trait::async_trait;
use common_enums::MerchantCategoryCode;
use common_utils::{
crypto::Encryptable,
encryption::Encryption,
errors::{CustomResult, ValidationError},
pii,
types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use rustc_hash::FxHashMap;
use serde_json::Value;
use super::behaviour;
use crate::type_encryption::{crypto_operation, AsyncLift, CryptoOperation};
#[derive(Clone, Debug, router_derive::ToEncryption, serde::Serialize)]
pub struct Authentication {
pub authentication_id: common_utils::id_type::AuthenticationId,
pub merchant_id: common_utils::id_type::MerchantId,
pub authentication_connector: Option<String>,
pub connector_authentication_id: Option<String>,
pub authentication_data: Option<Value>,
pub payment_method_id: String,
pub authentication_type: Option<common_enums::DecoupledAuthenticationType>,
pub authentication_status: common_enums::AuthenticationStatus,
pub authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: time::PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: time::PrimitiveDateTime,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub connector_metadata: Option<Value>,
pub maximum_supported_version: Option<common_utils::types::SemanticVersion>,
pub threeds_server_transaction_id: Option<String>,
pub cavv: Option<String>,
pub authentication_flow_type: Option<String>,
pub message_version: Option<common_utils::types::SemanticVersion>,
pub eci: Option<String>,
pub trans_status: Option<common_enums::TransactionStatus>,
pub acquirer_bin: Option<String>,
pub acquirer_merchant_id: Option<String>,
pub three_ds_method_data: Option<String>,
pub three_ds_method_url: Option<String>,
pub acs_url: Option<String>,
pub challenge_request: Option<String>,
pub acs_reference_number: Option<String>,
pub acs_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
pub profile_id: common_utils::id_type::ProfileId,
pub payment_id: Option<common_utils::id_type::PaymentId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub ds_trans_id: Option<String>,
pub directory_server_id: Option<String>,
pub acquirer_country_code: Option<String>,
pub organization_id: common_utils::id_type::OrganizationId,
pub mcc: Option<MerchantCategoryCode>,
pub currency: Option<common_enums::Currency>,
pub billing_country: Option<String>,
pub shipping_country: Option<String>,
pub issuer_country: Option<String>,
pub earliest_supported_version: Option<common_utils::types::SemanticVersion>,
pub latest_supported_version: Option<common_utils::types::SemanticVersion>,
pub platform: Option<api_models::payments::DeviceChannel>,
pub device_type: Option<String>,
pub device_brand: Option<String>,
pub device_os: Option<String>,
pub device_display: Option<String>,
pub browser_name: Option<String>,
pub browser_version: Option<String>,
pub issuer_id: Option<String>,
pub scheme_name: Option<String>,
pub exemption_requested: Option<bool>,
pub exemption_accepted: Option<bool>,
pub service_details: Option<Value>,
pub authentication_client_secret: Option<String>,
pub force_3ds_challenge: Option<bool>,
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
pub return_url: Option<String>,
#[encrypt(ty = Value)]
pub billing_address: Option<Encryptable<Secret<Value>>>,
#[encrypt(ty = Value)]
pub shipping_address: Option<Encryptable<Secret<Value>>>,
pub browser_info: Option<Value>,
pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,
pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,
pub challenge_code: Option<String>,
pub challenge_cancel: Option<String>,
pub challenge_code_reason: Option<String>,
pub message_extension: Option<pii::SecretSerdeValue>,
pub challenge_request_key: Option<String>,
pub customer_details: Option<Encryption>,
pub amount: Option<common_utils::types::MinorUnit>,
pub merchant_country_code: Option<String>,
}
impl Authentication {
pub fn is_separate_authn_required(&self) -> bool {
self.maximum_supported_version
.as_ref()
.is_some_and(|version| version.get_major() == 2)
}
// get authentication_connector from authentication record and check if it is jwt flow
pub fn is_jwt_flow(&self) -> CustomResult<bool, ValidationError> {
Ok(self
.authentication_connector
.clone()
.map(|connector| {
common_enums::AuthenticationConnectors::from_str(&connector)
.change_context(ValidationError::InvalidValue {
message: "failed to parse authentication_connector".to_string(),
})
.map(|connector_enum| connector_enum.is_jwt_flow())
})
.transpose()?
.unwrap_or(false))
}
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct PgRedirectResponseForAuthentication {
pub authentication_id: common_utils::id_type::AuthenticationId,
pub status: common_enums::TransactionStatus,
pub gateway_id: String,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub amount: Option<common_utils::types::MinorUnit>,
}
#[async_trait]
impl behaviour::Conversion for Authentication {
type DstType = diesel_models::authentication::Authentication;
type NewDstType = diesel_models::authentication::AuthenticationNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(Self::DstType {
authentication_id: self.authentication_id,
merchant_id: self.merchant_id,
authentication_connector: self.authentication_connector,
connector_authentication_id: self.connector_authentication_id,
authentication_data: self.authentication_data,
payment_method_id: self.payment_method_id,
authentication_type: self.authentication_type,
authentication_status: self.authentication_status,
authentication_lifecycle_status: self.authentication_lifecycle_status,
created_at: self.created_at,
modified_at: self.modified_at,
error_message: self.error_message,
error_code: self.error_code,
connector_metadata: self.connector_metadata,
maximum_supported_version: self.maximum_supported_version,
threeds_server_transaction_id: self.threeds_server_transaction_id,
cavv: self.cavv,
authentication_flow_type: self.authentication_flow_type,
message_version: self.message_version,
eci: self.eci,
trans_status: self.trans_status,
acquirer_bin: self.acquirer_bin,
acquirer_merchant_id: self.acquirer_merchant_id,
three_ds_method_data: self.three_ds_method_data,
three_ds_method_url: self.three_ds_method_url,
acs_url: self.acs_url,
challenge_request: self.challenge_request,
acs_reference_number: self.acs_reference_number,
acs_trans_id: self.acs_trans_id,
acs_signed_content: self.acs_signed_content,
profile_id: self.profile_id,
payment_id: self.payment_id,
merchant_connector_id: self.merchant_connector_id,
ds_trans_id: self.ds_trans_id,
directory_server_id: self.directory_server_id,
acquirer_country_code: self.acquirer_country_code,
service_details: self.service_details,
organization_id: self.organization_id,
authentication_client_secret: self.authentication_client_secret,
force_3ds_challenge: self.force_3ds_challenge,
psd2_sca_exemption_type: self.psd2_sca_exemption_type,
return_url: self.return_url,
amount: self.amount,
currency: self.currency,
billing_address: self.billing_address.map(Encryption::from),
shipping_address: self.shipping_address.map(Encryption::from),
browser_info: self.browser_info,
email: self.email.map(|email| email.into()),
profile_acquirer_id: self.profile_acquirer_id,
challenge_code: self.challenge_code,
challenge_cancel: self.challenge_cancel,
challenge_code_reason: self.challenge_code_reason,
message_extension: self.message_extension,
challenge_request_key: self.challenge_request_key,
customer_details: self.customer_details,
earliest_supported_version: self.earliest_supported_version,
latest_supported_version: self.latest_supported_version,
mcc: self.mcc,
platform: self.platform.map(|platform| platform.to_string()),
device_type: self.device_type,
device_brand: self.device_brand,
device_os: self.device_os,
device_display: self.device_display,
browser_name: self.browser_name,
browser_version: self.browser_version,
scheme_name: self.scheme_name,
exemption_requested: self.exemption_requested,
exemption_accepted: self.exemption_accepted,
issuer_id: self.issuer_id,
issuer_country: self.issuer_country,
merchant_country_code: self.merchant_country_code,
billing_country: self.billing_country,
shipping_country: self.shipping_country,
})
}
async fn convert_back(
state: &KeyManagerState,
other: Self::DstType,
key: &Secret<Vec<u8>>,
_key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let encrypted_data = crypto_operation(
state,
common_utils::type_name!(Self),
CryptoOperation::BatchDecrypt(EncryptedAuthentication::to_encryptable(
EncryptedAuthentication {
billing_address: other.billing_address,
shipping_address: other.shipping_address,
},
)),
Identifier::Merchant(other.merchant_id.clone()),
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting authentication data".to_string(),
})?;
let decrypted_data = FromRequestEncryptableAuthentication::from_encryptable(encrypted_data)
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting authentication data".to_string(),
})?;
let email_decrypted = other
.email
.clone()
.async_lift(|inner| async {
crypto_operation::<String, pii::EmailStrategy>(
state,
common_utils::type_name!(Self),
CryptoOperation::DecryptOptional(inner),
Identifier::Merchant(other.merchant_id.clone()),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting authentication email".to_string(),
})?;
Ok(Self {
authentication_id: other.authentication_id,
merchant_id: other.merchant_id,
authentication_connector: other.authentication_connector,
connector_authentication_id: other.connector_authentication_id,
authentication_data: other.authentication_data,
payment_method_id: other.payment_method_id,
authentication_type: other.authentication_type,
authentication_status: other.authentication_status,
authentication_lifecycle_status: other.authentication_lifecycle_status,
created_at: other.created_at,
modified_at: other.modified_at,
error_message: other.error_message,
error_code: other.error_code,
connector_metadata: other.connector_metadata,
maximum_supported_version: other.maximum_supported_version,
threeds_server_transaction_id: other.threeds_server_transaction_id,
cavv: other.cavv,
authentication_flow_type: other.authentication_flow_type,
message_version: other.message_version,
eci: other.eci,
trans_status: other.trans_status,
acquirer_bin: other.acquirer_bin,
acquirer_merchant_id: other.acquirer_merchant_id,
three_ds_method_data: other.three_ds_method_data,
three_ds_method_url: other.three_ds_method_url,
acs_url: other.acs_url,
challenge_request: other.challenge_request,
acs_reference_number: other.acs_reference_number,
acs_trans_id: other.acs_trans_id,
acs_signed_content: other.acs_signed_content,
profile_id: other.profile_id,
payment_id: other.payment_id,
merchant_connector_id: other.merchant_connector_id,
ds_trans_id: other.ds_trans_id,
directory_server_id: other.directory_server_id,
acquirer_country_code: other.acquirer_country_code,
organization_id: other.organization_id,
mcc: other.mcc,
amount: other.amount,
currency: other.currency,
issuer_country: other.issuer_country,
earliest_supported_version: other.earliest_supported_version,
latest_supported_version: other.latest_supported_version,
platform: other
.platform
.as_deref()
.map(|s| {
api_models::payments::DeviceChannel::from_str(s).change_context(
ValidationError::InvalidValue {
message: "Invalid device channel".into(),
},
)
})
.transpose()?,
device_type: other.device_type,
device_brand: other.device_brand,
device_os: other.device_os,
device_display: other.device_display,
browser_name: other.browser_name,
browser_version: other.browser_version,
issuer_id: other.issuer_id,
scheme_name: other.scheme_name,
exemption_requested: other.exemption_requested,
exemption_accepted: other.exemption_accepted,
service_details: other.service_details,
authentication_client_secret: other.authentication_client_secret,
force_3ds_challenge: other.force_3ds_challenge,
psd2_sca_exemption_type: other.psd2_sca_exemption_type,
return_url: other.return_url,
billing_address: decrypted_data.billing_address,
shipping_address: decrypted_data.shipping_address,
browser_info: other.browser_info,
email: email_decrypted,
profile_acquirer_id: other.profile_acquirer_id,
challenge_code: other.challenge_code,
challenge_cancel: other.challenge_cancel,
challenge_code_reason: other.challenge_code_reason,
message_extension: other.message_extension,
challenge_request_key: other.challenge_request_key,
customer_details: other.customer_details,
billing_country: other.billing_country,
shipping_country: other.shipping_country,
merchant_country_code: other.merchant_country_code,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(Self::NewDstType {
authentication_id: __self.authentication_id,
merchant_id: __self.merchant_id,
authentication_connector: __self.authentication_connector,
connector_authentication_id: __self.connector_authentication_id,
payment_method_id: __self.payment_method_id,
authentication_type: __self.authentication_type,
authentication_status: __self.authentication_status,
authentication_lifecycle_status: __self.authentication_lifecycle_status,
error_message: __self.error_message,
error_code: __self.error_code,
connector_metadata: __self.connector_metadata,
maximum_supported_version: __self.maximum_supported_version,
threeds_server_transaction_id: __self.threeds_server_transaction_id,
cavv: __self.cavv,
authentication_flow_type: __self.authentication_flow_type,
message_version: __self.message_version,
eci: __self.eci,
trans_status: __self.trans_status,
acquirer_bin: __self.acquirer_bin,
acquirer_merchant_id: __self.acquirer_merchant_id,
three_ds_method_data: __self.three_ds_method_data,
three_ds_method_url: __self.three_ds_method_url,
acs_url: __self.acs_url,
challenge_request: __self.challenge_request,
acs_reference_number: __self.acs_reference_number,
acs_trans_id: __self.acs_trans_id,
acs_signed_content: __self.acs_signed_content,
profile_id: __self.profile_id,
payment_id: __self.payment_id,
merchant_connector_id: __self.merchant_connector_id,
ds_trans_id: __self.ds_trans_id,
directory_server_id: __self.directory_server_id,
acquirer_country_code: __self.acquirer_country_code,
service_details: __self.service_details,
organization_id: __self.organization_id,
authentication_client_secret: __self.authentication_client_secret,
force_3ds_challenge: __self.force_3ds_challenge,
psd2_sca_exemption_type: __self.psd2_sca_exemption_type,
return_url: __self.return_url,
amount: __self.amount,
currency: __self.currency,
billing_address: __self.billing_address.map(Encryption::from),
shipping_address: __self.shipping_address.map(Encryption::from),
browser_info: __self.browser_info,
email: __self.email.map(|email| email.into()),
profile_acquirer_id: __self.profile_acquirer_id,
challenge_code: __self.challenge_code,
challenge_cancel: __self.challenge_cancel,
challenge_code_reason: __self.challenge_code_reason,
message_extension: __self.message_extension,
challenge_request_key: __self.challenge_request_key,
customer_details: __self.customer_details,
earliest_supported_version: __self.earliest_supported_version,
latest_supported_version: __self.latest_supported_version,
mcc: __self.mcc,
platform: __self.platform.map(|platform| platform.to_string()),
device_type: __self.device_type,
device_brand: __self.device_brand,
device_os: __self.device_os,
device_display: __self.device_display,
browser_name: __self.browser_name,
browser_version: __self.browser_version,
scheme_name: __self.scheme_name,
exemption_requested: __self.exemption_requested,
exemption_accepted: __self.exemption_accepted,
issuer_id: __self.issuer_id,
issuer_country: __self.issuer_country,
merchant_country_code: __self.merchant_country_code,
created_at: __self.created_at,
modified_at: __self.modified_at,
authentication_data: __self.authentication_data,
billing_country: __self.billing_country,
shipping_country: __self.shipping_country,
})
}
}
#[derive(Debug)]
pub enum AuthenticationUpdate {
PreAuthenticationVersionCallUpdate {
maximum_supported_3ds_version: common_utils::types::SemanticVersion,
message_version: common_utils::types::SemanticVersion,
},
PreAuthenticationThreeDsMethodCall {
threeds_server_transaction_id: String,
three_ds_method_data: Option<String>,
three_ds_method_url: Option<String>,
acquirer_bin: Option<String>,
acquirer_merchant_id: Option<String>,
connector_metadata: Option<Value>,
},
PreAuthenticationUpdate {
threeds_server_transaction_id: String,
maximum_supported_3ds_version: common_utils::types::SemanticVersion,
connector_authentication_id: String,
three_ds_method_data: Option<String>,
three_ds_method_url: Option<String>,
message_version: common_utils::types::SemanticVersion,
connector_metadata: Option<Value>,
authentication_status: common_enums::AuthenticationStatus,
acquirer_bin: Option<String>,
acquirer_merchant_id: Option<String>,
directory_server_id: Option<String>,
acquirer_country_code: Option<String>,
billing_address: Box<Option<Encryptable<Secret<Value>>>>,
shipping_address: Box<Option<Encryptable<Secret<Value>>>>,
browser_info: Box<Option<Value>>,
email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,
scheme_id: Option<String>,
merchant_category_code: Option<MerchantCategoryCode>,
merchant_country_code: Option<String>,
billing_country: Option<String>,
shipping_country: Option<String>,
earliest_supported_version: Option<common_utils::types::SemanticVersion>,
latest_supported_version: Option<common_utils::types::SemanticVersion>,
},
AuthenticationUpdate {
trans_status: common_enums::TransactionStatus,
authentication_type: common_enums::DecoupledAuthenticationType,
acs_url: Option<String>,
challenge_request: Option<String>,
acs_reference_number: Option<String>,
acs_trans_id: Option<String>,
acs_signed_content: Option<String>,
connector_metadata: Option<Value>,
authentication_status: common_enums::AuthenticationStatus,
ds_trans_id: Option<String>,
eci: Option<String>,
challenge_code: Option<String>,
challenge_cancel: Option<String>,
challenge_code_reason: Option<String>,
message_extension: Option<pii::SecretSerdeValue>,
challenge_request_key: Option<String>,
device_type: Option<String>,
device_brand: Option<String>,
device_os: Option<String>,
device_display: Option<String>,
},
PostAuthenticationUpdate {
trans_status: common_enums::TransactionStatus,
eci: Option<String>,
authentication_status: common_enums::AuthenticationStatus,
challenge_cancel: Option<String>,
challenge_code_reason: Option<String>,
},
ErrorUpdate {
error_message: Option<String>,
error_code: Option<String>,
authentication_status: common_enums::AuthenticationStatus,
connector_authentication_id: Option<String>,
},
PostAuthorizationUpdate {
authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus,
},
AuthenticationStatusUpdate {
trans_status: common_enums::TransactionStatus,
authentication_status: common_enums::AuthenticationStatus,
},
}
impl From<AuthenticationUpdate> for diesel_models::authentication::AuthenticationUpdate {
fn from(authentication_update: AuthenticationUpdate) -> Self {
match authentication_update {
AuthenticationUpdate::PreAuthenticationVersionCallUpdate {
maximum_supported_3ds_version,
message_version,
} => Self::PreAuthenticationVersionCallUpdate {
maximum_supported_3ds_version,
message_version,
},
AuthenticationUpdate::PreAuthenticationThreeDsMethodCall {
threeds_server_transaction_id,
three_ds_method_data,
three_ds_method_url,
acquirer_bin,
acquirer_merchant_id,
connector_metadata,
} => Self::PreAuthenticationThreeDsMethodCall {
threeds_server_transaction_id,
three_ds_method_data,
three_ds_method_url,
acquirer_bin,
acquirer_merchant_id,
connector_metadata,
},
AuthenticationUpdate::PreAuthenticationUpdate {
threeds_server_transaction_id,
maximum_supported_3ds_version,
connector_authentication_id,
three_ds_method_data,
three_ds_method_url,
message_version,
connector_metadata,
authentication_status,
acquirer_bin,
acquirer_merchant_id,
directory_server_id,
acquirer_country_code,
billing_address,
shipping_address,
browser_info,
email,
scheme_id,
merchant_category_code,
merchant_country_code,
billing_country,
shipping_country,
earliest_supported_version,
latest_supported_version,
} => Self::PreAuthenticationUpdate {
threeds_server_transaction_id,
maximum_supported_3ds_version,
connector_authentication_id,
three_ds_method_data,
three_ds_method_url,
message_version,
connector_metadata,
authentication_status,
acquirer_bin,
acquirer_merchant_id,
directory_server_id,
acquirer_country_code,
billing_address: billing_address.map(|billing_address| billing_address.into()),
shipping_address: shipping_address.map(|shipping_address| shipping_address.into()),
browser_info,
email: email.map(|email| email.into()),
scheme_id,
merchant_category_code,
merchant_country_code,
billing_country,
shipping_country,
earliest_supported_version,
latest_supported_version,
},
AuthenticationUpdate::AuthenticationUpdate {
trans_status,
authentication_type,
acs_url,
challenge_request,
acs_reference_number,
acs_trans_id,
acs_signed_content,
connector_metadata,
authentication_status,
ds_trans_id,
eci,
challenge_code,
challenge_cancel,
challenge_code_reason,
message_extension,
challenge_request_key,
device_type,
device_brand,
device_os,
device_display,
} => Self::AuthenticationUpdate {
trans_status,
authentication_type,
acs_url,
challenge_request,
acs_reference_number,
acs_trans_id,
acs_signed_content,
connector_metadata,
authentication_status,
ds_trans_id,
eci,
challenge_code,
challenge_cancel,
challenge_code_reason,
message_extension,
challenge_request_key,
device_type,
device_brand,
device_os,
device_display,
},
AuthenticationUpdate::PostAuthenticationUpdate {
trans_status,
eci,
authentication_status,
challenge_cancel,
challenge_code_reason,
} => Self::PostAuthenticationUpdate {
trans_status,
eci,
authentication_status,
challenge_cancel,
challenge_code_reason,
},
AuthenticationUpdate::ErrorUpdate {
error_message,
error_code,
authentication_status,
connector_authentication_id,
} => Self::ErrorUpdate {
error_message,
error_code,
authentication_status,
connector_authentication_id,
},
AuthenticationUpdate::PostAuthorizationUpdate {
authentication_lifecycle_status,
} => Self::PostAuthorizationUpdate {
authentication_lifecycle_status,
},
AuthenticationUpdate::AuthenticationStatusUpdate {
trans_status,
authentication_status,
} => Self::AuthenticationStatusUpdate {
trans_status,
authentication_status,
},
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/business_profile.rs | crates/hyperswitch_domain_models/src/business_profile.rs | use std::borrow::Cow;
use common_enums::enums as api_enums;
use common_types::{domain::AcquirerConfig, primitive_wrappers};
use common_utils::{
crypto::{OptionalEncryptableName, OptionalEncryptableValue},
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
ext_traits::{OptionExt, ValueExt},
pii, type_name,
types::keymanager,
};
#[cfg(feature = "v2")]
use diesel_models::business_profile::RevenueRecoveryAlgorithmData;
use diesel_models::business_profile::{
self as storage_types, AuthenticationConnectorDetails, BusinessPaymentLinkConfig,
BusinessPayoutLinkConfig, CardTestingGuardConfig, ExternalVaultConnectorDetails,
ProfileUpdateInternal, WebhookDetails,
};
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret};
use router_env::logger;
use crate::{
behaviour::Conversion,
errors::api_error_response,
merchant_key_store::MerchantKeyStore,
type_encryption::{crypto_operation, AsyncLift, CryptoOperation},
};
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub struct Profile {
profile_id: common_utils::id_type::ProfileId,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub intent_fulfillment_time: Option<i64>,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub is_recon_enabled: bool,
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: bool,
pub is_l2_l3_enabled: bool,
pub version: common_enums::ApiVersion,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: bool,
pub max_auto_retries_enabled: Option<i16>,
pub always_request_extended_authorization:
Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>,
pub is_click_to_pay_enabled: bool,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: OptionalEncryptableName,
pub is_clear_pan_retries_enabled: bool,
pub force_3ds_challenge: bool,
pub is_debit_routing_enabled: bool,
pub merchant_business_country: Option<common_enums::CountryAlpha2>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_pre_network_tokenization_enabled: bool,
pub three_ds_decision_rule_algorithm: Option<serde_json::Value>,
pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>,
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
pub is_manual_retry_enabled: Option<bool>,
pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
pub external_vault_details: ExternalVaultDetails,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub enum ExternalVaultDetails {
ExternalVaultEnabled(ExternalVaultConnectorDetails),
Skip,
}
#[cfg(feature = "v1")]
impl ExternalVaultDetails {
pub fn is_external_vault_enabled(&self) -> bool {
match self {
Self::ExternalVaultEnabled(_) => true,
Self::Skip => false,
}
}
}
#[cfg(feature = "v1")]
impl
TryFrom<(
Option<common_enums::ExternalVaultEnabled>,
Option<ExternalVaultConnectorDetails>,
)> for ExternalVaultDetails
{
type Error = error_stack::Report<ValidationError>;
fn try_from(
item: (
Option<common_enums::ExternalVaultEnabled>,
Option<ExternalVaultConnectorDetails>,
),
) -> Result<Self, Self::Error> {
match item {
(is_external_vault_enabled, external_vault_connector_details)
if is_external_vault_enabled
.unwrap_or(common_enums::ExternalVaultEnabled::Skip)
== common_enums::ExternalVaultEnabled::Enable =>
{
Ok(Self::ExternalVaultEnabled(
external_vault_connector_details
.get_required_value("ExternalVaultConnectorDetails")?,
))
}
_ => Ok(Self::Skip),
}
}
}
#[cfg(feature = "v1")]
impl TryFrom<(Option<bool>, Option<ExternalVaultConnectorDetails>)> for ExternalVaultDetails {
type Error = error_stack::Report<ValidationError>;
fn try_from(
item: (Option<bool>, Option<ExternalVaultConnectorDetails>),
) -> Result<Self, Self::Error> {
match item {
(is_external_vault_enabled, external_vault_connector_details)
if is_external_vault_enabled.unwrap_or(false) =>
{
Ok(Self::ExternalVaultEnabled(
external_vault_connector_details
.get_required_value("ExternalVaultConnectorDetails")?,
))
}
_ => Ok(Self::Skip),
}
}
}
#[cfg(feature = "v1")]
impl From<ExternalVaultDetails>
for (
Option<common_enums::ExternalVaultEnabled>,
Option<ExternalVaultConnectorDetails>,
)
{
fn from(external_vault_details: ExternalVaultDetails) -> Self {
match external_vault_details {
ExternalVaultDetails::ExternalVaultEnabled(connector_details) => (
Some(common_enums::ExternalVaultEnabled::Enable),
Some(connector_details),
),
ExternalVaultDetails::Skip => (Some(common_enums::ExternalVaultEnabled::Skip), None),
}
}
}
#[cfg(feature = "v1")]
impl From<ExternalVaultDetails> for (Option<bool>, Option<ExternalVaultConnectorDetails>) {
fn from(external_vault_details: ExternalVaultDetails) -> Self {
match external_vault_details {
ExternalVaultDetails::ExternalVaultEnabled(connector_details) => {
(Some(true), Some(connector_details))
}
ExternalVaultDetails::Skip => (Some(false), None),
}
}
}
#[cfg(feature = "v1")]
pub struct ProfileSetter {
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub intent_fulfillment_time: Option<i64>,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub is_recon_enabled: bool,
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: bool,
pub is_l2_l3_enabled: bool,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: bool,
pub max_auto_retries_enabled: Option<i16>,
pub always_request_extended_authorization:
Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>,
pub is_click_to_pay_enabled: bool,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: OptionalEncryptableName,
pub is_clear_pan_retries_enabled: bool,
pub force_3ds_challenge: bool,
pub is_debit_routing_enabled: bool,
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_pre_network_tokenization_enabled: bool,
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
pub is_manual_retry_enabled: Option<bool>,
pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
pub external_vault_details: ExternalVaultDetails,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v1")]
impl From<ProfileSetter> for Profile {
fn from(value: ProfileSetter) -> Self {
Self {
profile_id: value.profile_id,
merchant_id: value.merchant_id,
profile_name: value.profile_name,
created_at: value.created_at,
modified_at: value.modified_at,
return_url: value.return_url,
enable_payment_response_hash: value.enable_payment_response_hash,
payment_response_hash_key: value.payment_response_hash_key,
redirect_to_merchant_with_http_post: value.redirect_to_merchant_with_http_post,
webhook_details: value.webhook_details,
metadata: value.metadata,
routing_algorithm: value.routing_algorithm,
intent_fulfillment_time: value.intent_fulfillment_time,
frm_routing_algorithm: value.frm_routing_algorithm,
payout_routing_algorithm: value.payout_routing_algorithm,
is_recon_enabled: value.is_recon_enabled,
applepay_verified_domains: value.applepay_verified_domains,
payment_link_config: value.payment_link_config,
session_expiry: value.session_expiry,
authentication_connector_details: value.authentication_connector_details,
payout_link_config: value.payout_link_config,
is_extended_card_info_enabled: value.is_extended_card_info_enabled,
extended_card_info_config: value.extended_card_info_config,
is_connector_agnostic_mit_enabled: value.is_connector_agnostic_mit_enabled,
use_billing_as_payment_method_billing: value.use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector: value
.collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector: value
.collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: value.outgoing_webhook_custom_http_headers,
always_collect_billing_details_from_wallet_connector: value
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: value
.always_collect_shipping_details_from_wallet_connector,
tax_connector_id: value.tax_connector_id,
is_tax_connector_enabled: value.is_tax_connector_enabled,
is_l2_l3_enabled: value.is_l2_l3_enabled,
version: common_types::consts::API_VERSION,
dynamic_routing_algorithm: value.dynamic_routing_algorithm,
is_network_tokenization_enabled: value.is_network_tokenization_enabled,
is_auto_retries_enabled: value.is_auto_retries_enabled,
max_auto_retries_enabled: value.max_auto_retries_enabled,
always_request_extended_authorization: value.always_request_extended_authorization,
is_click_to_pay_enabled: value.is_click_to_pay_enabled,
authentication_product_ids: value.authentication_product_ids,
card_testing_guard_config: value.card_testing_guard_config,
card_testing_secret_key: value.card_testing_secret_key,
is_clear_pan_retries_enabled: value.is_clear_pan_retries_enabled,
force_3ds_challenge: value.force_3ds_challenge,
is_debit_routing_enabled: value.is_debit_routing_enabled,
merchant_business_country: value.merchant_business_country,
is_iframe_redirection_enabled: value.is_iframe_redirection_enabled,
is_pre_network_tokenization_enabled: value.is_pre_network_tokenization_enabled,
three_ds_decision_rule_algorithm: None, // three_ds_decision_rule_algorithm is not yet created during profile creation
acquirer_config_map: None,
merchant_category_code: value.merchant_category_code,
merchant_country_code: value.merchant_country_code,
dispute_polling_interval: value.dispute_polling_interval,
is_manual_retry_enabled: value.is_manual_retry_enabled,
always_enable_overcapture: value.always_enable_overcapture,
external_vault_details: value.external_vault_details,
billing_processor_id: value.billing_processor_id,
}
}
}
impl Profile {
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &common_utils::id_type::ProfileId {
&self.profile_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &common_utils::id_type::ProfileId {
&self.id
}
}
#[cfg(feature = "v1")]
#[derive(Debug)]
pub struct ProfileGeneralUpdate {
pub profile_name: Option<String>,
pub return_url: Option<String>,
pub enable_payment_response_hash: Option<bool>,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: Option<bool>,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub intent_fulfillment_time: Option<i64>,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub always_request_extended_authorization:
Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
pub is_l2_l3_enabled: Option<bool>,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: Option<bool>,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
pub is_click_to_pay_enabled: Option<bool>,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: OptionalEncryptableName,
pub is_clear_pan_retries_enabled: Option<bool>,
pub force_3ds_challenge: Option<bool>,
pub is_debit_routing_enabled: Option<bool>,
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_pre_network_tokenization_enabled: Option<bool>,
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
pub is_manual_retry_enabled: Option<bool>,
pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>,
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v1")]
#[derive(Debug)]
pub enum ProfileUpdate {
Update(Box<ProfileGeneralUpdate>),
RoutingAlgorithmUpdate {
routing_algorithm: Option<serde_json::Value>,
payout_routing_algorithm: Option<serde_json::Value>,
three_ds_decision_rule_algorithm: Option<serde_json::Value>,
},
DynamicRoutingAlgorithmUpdate {
dynamic_routing_algorithm: Option<serde_json::Value>,
},
ExtendedCardInfoUpdate {
is_extended_card_info_enabled: bool,
},
ConnectorAgnosticMitUpdate {
is_connector_agnostic_mit_enabled: bool,
},
NetworkTokenizationUpdate {
is_network_tokenization_enabled: bool,
},
CardTestingSecretKeyUpdate {
card_testing_secret_key: OptionalEncryptableName,
},
AcquirerConfigMapUpdate {
acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>,
},
}
#[cfg(feature = "v1")]
impl From<ProfileUpdate> for ProfileUpdateInternal {
fn from(profile_update: ProfileUpdate) -> Self {
let now = date_time::now();
match profile_update {
ProfileUpdate::Update(update) => {
let ProfileGeneralUpdate {
profile_name,
return_url,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
webhook_details,
metadata,
routing_algorithm,
intent_fulfillment_time,
frm_routing_algorithm,
payout_routing_algorithm,
applepay_verified_domains,
payment_link_config,
session_expiry,
authentication_connector_details,
payout_link_config,
extended_card_info_config,
use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector,
is_connector_agnostic_mit_enabled,
outgoing_webhook_custom_http_headers,
always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector,
tax_connector_id,
is_tax_connector_enabled,
is_l2_l3_enabled,
dynamic_routing_algorithm,
is_network_tokenization_enabled,
is_auto_retries_enabled,
max_auto_retries_enabled,
is_click_to_pay_enabled,
authentication_product_ids,
card_testing_guard_config,
card_testing_secret_key,
is_clear_pan_retries_enabled,
force_3ds_challenge,
is_debit_routing_enabled,
merchant_business_country,
is_iframe_redirection_enabled,
is_pre_network_tokenization_enabled,
merchant_category_code,
merchant_country_code,
dispute_polling_interval,
always_request_extended_authorization,
is_manual_retry_enabled,
always_enable_overcapture,
is_external_vault_enabled,
external_vault_connector_details,
billing_processor_id,
} = *update;
let is_external_vault_enabled = match is_external_vault_enabled {
Some(external_vault_mode) => match external_vault_mode {
common_enums::ExternalVaultEnabled::Enable => Some(true),
common_enums::ExternalVaultEnabled::Skip => Some(false),
},
None => Some(false),
};
Self {
profile_name,
modified_at: now,
return_url,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
webhook_details,
metadata,
routing_algorithm,
intent_fulfillment_time,
frm_routing_algorithm,
payout_routing_algorithm,
is_recon_enabled: None,
applepay_verified_domains,
payment_link_config,
session_expiry,
authentication_connector_details,
payout_link_config,
is_extended_card_info_enabled: None,
extended_card_info_config,
is_connector_agnostic_mit_enabled,
use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers
.map(Encryption::from),
always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector,
tax_connector_id,
is_tax_connector_enabled,
is_l2_l3_enabled,
dynamic_routing_algorithm,
is_network_tokenization_enabled,
is_auto_retries_enabled,
max_auto_retries_enabled,
always_request_extended_authorization,
is_click_to_pay_enabled,
authentication_product_ids,
card_testing_guard_config,
card_testing_secret_key: card_testing_secret_key.map(Encryption::from),
is_clear_pan_retries_enabled,
force_3ds_challenge,
is_debit_routing_enabled,
merchant_business_country,
is_iframe_redirection_enabled,
is_pre_network_tokenization_enabled,
three_ds_decision_rule_algorithm: None,
acquirer_config_map: None,
merchant_category_code,
merchant_country_code,
dispute_polling_interval,
is_manual_retry_enabled,
always_enable_overcapture,
is_external_vault_enabled,
external_vault_connector_details,
billing_processor_id,
}
}
ProfileUpdate::RoutingAlgorithmUpdate {
routing_algorithm,
payout_routing_algorithm,
three_ds_decision_rule_algorithm,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
routing_algorithm,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
always_request_extended_authorization: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
card_testing_guard_config: None,
card_testing_secret_key: None,
is_clear_pan_retries_enabled: None,
force_3ds_challenge: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
is_iframe_redirection_enabled: None,
is_pre_network_tokenization_enabled: None,
three_ds_decision_rule_algorithm,
acquirer_config_map: None,
merchant_category_code: None,
merchant_country_code: None,
dispute_polling_interval: None,
is_manual_retry_enabled: None,
always_enable_overcapture: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
billing_processor_id: None,
is_l2_l3_enabled: None,
},
ProfileUpdate::DynamicRoutingAlgorithmUpdate {
dynamic_routing_algorithm,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
routing_algorithm: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
dynamic_routing_algorithm,
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
always_request_extended_authorization: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
card_testing_guard_config: None,
card_testing_secret_key: None,
is_clear_pan_retries_enabled: None,
force_3ds_challenge: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
is_iframe_redirection_enabled: None,
is_pre_network_tokenization_enabled: None,
three_ds_decision_rule_algorithm: None,
acquirer_config_map: None,
merchant_category_code: None,
merchant_country_code: None,
dispute_polling_interval: None,
is_manual_retry_enabled: None,
always_enable_overcapture: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
billing_processor_id: None,
is_l2_l3_enabled: None,
},
ProfileUpdate::ExtendedCardInfoUpdate {
is_extended_card_info_enabled,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
routing_algorithm: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: Some(is_extended_card_info_enabled),
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/customer.rs | crates/hyperswitch_domain_models/src/customer.rs | use common_enums::enums::MerchantStorageScheme;
#[cfg(feature = "v2")]
use common_enums::DeleteStatus;
use common_utils::{
crypto::{self, Encryptable},
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
ext_traits::ValueExt,
id_type, pii,
types::{
keymanager::{self, KeyManagerState, ToEncryptable},
CreatedBy, Description,
},
};
use diesel_models::{
customers as storage_types, customers::CustomerUpdateInternal, query::customers as query,
};
use error_stack::ResultExt;
use masking::{ExposeOptionInterface, PeekInterface, Secret, SwitchStrategy};
use router_env::{instrument, tracing};
use rustc_hash::FxHashMap;
use time::PrimitiveDateTime;
#[cfg(feature = "v2")]
use crate::merchant_connector_account::MerchantConnectorAccountTypeDetails;
use crate::{behaviour, merchant_key_store::MerchantKeyStore, type_encryption as types};
#[cfg(feature = "v1")]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct Customer {
pub customer_id: id_type::CustomerId,
pub merchant_id: id_type::MerchantId,
#[encrypt]
pub name: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,
#[encrypt]
pub phone: Option<Encryptable<Secret<String>>>,
pub phone_country_code: Option<String>,
pub description: Option<Description>,
pub created_at: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: PrimitiveDateTime,
pub connector_customer: Option<pii::SecretSerdeValue>,
pub address_id: Option<String>,
pub default_payment_method_id: Option<String>,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
#[encrypt]
pub tax_registration_id: Option<Encryptable<Secret<String>>>,
pub created_by: Option<CreatedBy>,
pub last_modified_by: Option<CreatedBy>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct Customer {
pub merchant_id: id_type::MerchantId,
#[encrypt]
pub name: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,
#[encrypt]
pub phone: Option<Encryptable<Secret<String>>>,
pub phone_country_code: Option<String>,
pub description: Option<Description>,
pub created_at: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>,
pub modified_at: PrimitiveDateTime,
pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>,
pub updated_by: Option<String>,
pub merchant_reference_id: Option<id_type::CustomerId>,
pub default_billing_address: Option<Encryption>,
pub default_shipping_address: Option<Encryption>,
pub id: id_type::GlobalCustomerId,
pub version: common_enums::ApiVersion,
pub status: DeleteStatus,
#[encrypt]
pub tax_registration_id: Option<Encryptable<Secret<String>>>,
pub created_by: Option<CreatedBy>,
pub last_modified_by: Option<CreatedBy>,
}
impl Customer {
/// Get the unique identifier of Customer
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &id_type::CustomerId {
&self.customer_id
}
/// Get the global identifier of Customer
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &id_type::GlobalCustomerId {
&self.id
}
/// Get the connector customer ID for the specified connector label, if present
#[cfg(feature = "v1")]
pub fn get_connector_customer_map(
&self,
) -> FxHashMap<id_type::MerchantConnectorAccountId, String> {
use masking::PeekInterface;
if let Some(connector_customer_value) = &self.connector_customer {
connector_customer_value
.peek()
.clone()
.parse_value("ConnectorCustomerMap")
.unwrap_or_default()
} else {
FxHashMap::default()
}
}
/// Get the connector customer ID for the specified connector label, if present
#[cfg(feature = "v1")]
pub fn get_connector_customer_id(&self, connector_label: &str) -> Option<&str> {
use masking::PeekInterface;
self.connector_customer
.as_ref()
.and_then(|connector_customer_value| {
connector_customer_value.peek().get(connector_label)
})
.and_then(|connector_customer| connector_customer.as_str())
}
/// Get the connector customer ID for the specified merchant connector account ID, if present
#[cfg(feature = "v2")]
pub fn get_connector_customer_id(
&self,
merchant_connector_account: &MerchantConnectorAccountTypeDetails,
) -> Option<&str> {
match merchant_connector_account {
MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(account) => {
let connector_account_id = account.get_id();
self.connector_customer
.as_ref()?
.get(&connector_account_id)
.map(|connector_customer_id| connector_customer_id.as_str())
}
MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None,
}
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl behaviour::Conversion for Customer {
type DstType = diesel_models::customers::Customer;
type NewDstType = diesel_models::customers::CustomerNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::customers::Customer {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
name: self.name.map(Encryption::from),
email: self.email.map(Encryption::from),
phone: self.phone.map(Encryption::from),
phone_country_code: self.phone_country_code,
description: self.description,
created_at: self.created_at,
metadata: self.metadata,
modified_at: self.modified_at,
connector_customer: self.connector_customer,
address_id: self.address_id,
default_payment_method_id: self.default_payment_method_id,
updated_by: self.updated_by,
version: self.version,
tax_registration_id: self.tax_registration_id.map(Encryption::from),
created_by: self.created_by.map(|created_by| created_by.to_string()),
last_modified_by: self
.last_modified_by
.map(|last_modified_by| last_modified_by.to_string()),
})
}
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
_key_store_ref_id: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let decrypted = types::crypto_operation(
state,
common_utils::type_name!(Self::DstType),
types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable(
EncryptedCustomer {
name: item.name.clone(),
phone: item.phone.clone(),
email: item.email.clone(),
tax_registration_id: item.tax_registration_id.clone(),
},
)),
keymanager::Identifier::Merchant(item.merchant_id.clone()),
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
})?;
let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context(
ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
},
)?;
Ok(Self {
customer_id: item.customer_id,
merchant_id: item.merchant_id,
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: encryptable_customer.phone,
phone_country_code: item.phone_country_code,
description: item.description,
created_at: item.created_at,
metadata: item.metadata,
modified_at: item.modified_at,
connector_customer: item.connector_customer,
address_id: item.address_id,
default_payment_method_id: item.default_payment_method_id,
updated_by: item.updated_by,
version: item.version,
tax_registration_id: encryptable_customer.tax_registration_id,
created_by: item
.created_by
.and_then(|created_by| created_by.parse::<CreatedBy>().ok()),
last_modified_by: item
.last_modified_by
.and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(diesel_models::customers::CustomerNew {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
name: self.name.map(Encryption::from),
email: self.email.map(Encryption::from),
phone: self.phone.map(Encryption::from),
description: self.description,
phone_country_code: self.phone_country_code,
metadata: self.metadata,
created_at: now,
modified_at: now,
connector_customer: self.connector_customer,
address_id: self.address_id,
updated_by: self.updated_by,
version: self.version,
tax_registration_id: self.tax_registration_id.map(Encryption::from),
created_by: self
.created_by
.as_ref()
.map(|created_by| created_by.to_string()),
last_modified_by: self.created_by.map(|created_by| created_by.to_string()), // Same as created_by on creation
})
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl behaviour::Conversion for Customer {
type DstType = diesel_models::customers::Customer;
type NewDstType = diesel_models::customers::CustomerNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::customers::Customer {
id: self.id,
merchant_reference_id: self.merchant_reference_id,
merchant_id: self.merchant_id,
name: self.name.map(Encryption::from),
email: self.email.map(Encryption::from),
phone: self.phone.map(Encryption::from),
phone_country_code: self.phone_country_code,
description: self.description,
created_at: self.created_at,
metadata: self.metadata,
modified_at: self.modified_at,
connector_customer: self.connector_customer,
default_payment_method_id: self.default_payment_method_id,
updated_by: self.updated_by,
default_billing_address: self.default_billing_address,
default_shipping_address: self.default_shipping_address,
version: self.version,
status: self.status,
tax_registration_id: self.tax_registration_id.map(Encryption::from),
created_by: self.created_by.map(|created_by| created_by.to_string()),
last_modified_by: self
.last_modified_by
.map(|last_modified_by| last_modified_by.to_string()),
})
}
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
_key_store_ref_id: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let decrypted = types::crypto_operation(
state,
common_utils::type_name!(Self::DstType),
types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable(
EncryptedCustomer {
name: item.name.clone(),
phone: item.phone.clone(),
email: item.email.clone(),
tax_registration_id: item.tax_registration_id.clone(),
},
)),
keymanager::Identifier::Merchant(item.merchant_id.clone()),
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
})?;
let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context(
ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
},
)?;
Ok(Self {
id: item.id,
merchant_reference_id: item.merchant_reference_id,
merchant_id: item.merchant_id,
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: encryptable_customer.phone,
phone_country_code: item.phone_country_code,
description: item.description,
created_at: item.created_at,
metadata: item.metadata,
modified_at: item.modified_at,
connector_customer: item.connector_customer,
default_payment_method_id: item.default_payment_method_id,
updated_by: item.updated_by,
default_billing_address: item.default_billing_address,
default_shipping_address: item.default_shipping_address,
version: item.version,
status: item.status,
tax_registration_id: encryptable_customer.tax_registration_id,
created_by: item
.created_by
.and_then(|created_by| created_by.parse::<CreatedBy>().ok()),
last_modified_by: item
.last_modified_by
.and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(diesel_models::customers::CustomerNew {
id: self.id,
merchant_reference_id: self.merchant_reference_id,
merchant_id: self.merchant_id,
name: self.name.map(Encryption::from),
email: self.email.map(Encryption::from),
phone: self.phone.map(Encryption::from),
description: self.description,
phone_country_code: self.phone_country_code,
metadata: self.metadata,
default_payment_method_id: None,
created_at: now,
modified_at: now,
connector_customer: self.connector_customer,
updated_by: self.updated_by,
default_billing_address: self.default_billing_address,
default_shipping_address: self.default_shipping_address,
version: common_types::consts::API_VERSION,
status: self.status,
tax_registration_id: self.tax_registration_id.map(Encryption::from),
created_by: self
.created_by
.as_ref()
.map(|created_by| created_by.to_string()),
last_modified_by: self.created_by.map(|created_by| created_by.to_string()), // Same as created_by on creation
})
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct CustomerGeneralUpdate {
pub name: crypto::OptionalEncryptableName,
pub email: Box<crypto::OptionalEncryptableEmail>,
pub phone: Box<crypto::OptionalEncryptablePhone>,
pub description: Option<Description>,
pub phone_country_code: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_customer: Box<Option<common_types::customers::ConnectorCustomerMap>>,
pub default_billing_address: Option<Encryption>,
pub default_shipping_address: Option<Encryption>,
pub default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>,
pub status: Option<DeleteStatus>,
pub tax_registration_id: crypto::OptionalEncryptableSecretString,
pub last_modified_by: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub enum CustomerUpdate {
Update(Box<CustomerGeneralUpdate>),
ConnectorCustomer {
connector_customer: Option<common_types::customers::ConnectorCustomerMap>,
last_modified_by: Option<String>,
},
UpdateDefaultPaymentMethod {
default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>,
last_modified_by: Option<String>,
},
}
#[cfg(feature = "v2")]
impl From<CustomerUpdate> for CustomerUpdateInternal {
fn from(customer_update: CustomerUpdate) -> Self {
match customer_update {
CustomerUpdate::Update(update) => {
let CustomerGeneralUpdate {
name,
email,
phone,
description,
phone_country_code,
metadata,
connector_customer,
default_billing_address,
default_shipping_address,
default_payment_method_id,
status,
tax_registration_id,
last_modified_by,
} = *update;
Self {
name: name.map(Encryption::from),
email: email.map(Encryption::from),
phone: phone.map(Encryption::from),
description,
phone_country_code,
metadata,
connector_customer: *connector_customer,
modified_at: date_time::now(),
default_billing_address,
default_shipping_address,
default_payment_method_id,
updated_by: None,
status,
tax_registration_id: tax_registration_id.map(Encryption::from),
last_modified_by,
}
}
CustomerUpdate::ConnectorCustomer {
connector_customer,
last_modified_by,
} => Self {
connector_customer,
name: None,
email: None,
phone: None,
description: None,
phone_country_code: None,
metadata: None,
modified_at: date_time::now(),
default_payment_method_id: None,
updated_by: None,
default_billing_address: None,
default_shipping_address: None,
status: None,
tax_registration_id: None,
last_modified_by,
},
CustomerUpdate::UpdateDefaultPaymentMethod {
default_payment_method_id,
last_modified_by,
} => Self {
default_payment_method_id,
modified_at: date_time::now(),
name: None,
email: None,
phone: None,
description: None,
phone_country_code: None,
metadata: None,
connector_customer: None,
updated_by: None,
default_billing_address: None,
default_shipping_address: None,
status: None,
tax_registration_id: None,
last_modified_by,
},
}
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub enum CustomerUpdate {
Update {
name: crypto::OptionalEncryptableName,
email: crypto::OptionalEncryptableEmail,
phone: Box<crypto::OptionalEncryptablePhone>,
description: Option<Description>,
phone_country_code: Option<String>,
metadata: Box<Option<pii::SecretSerdeValue>>,
connector_customer: Box<Option<pii::SecretSerdeValue>>,
address_id: Option<String>,
tax_registration_id: crypto::OptionalEncryptableSecretString,
last_modified_by: Option<String>,
},
ConnectorCustomer {
connector_customer: Option<pii::SecretSerdeValue>,
last_modified_by: Option<String>,
},
UpdateDefaultPaymentMethod {
default_payment_method_id: Option<Option<String>>,
last_modified_by: Option<String>,
},
}
#[cfg(feature = "v1")]
impl From<CustomerUpdate> for CustomerUpdateInternal {
fn from(customer_update: CustomerUpdate) -> Self {
match customer_update {
CustomerUpdate::Update {
name,
email,
phone,
description,
phone_country_code,
metadata,
connector_customer,
address_id,
tax_registration_id,
last_modified_by,
} => Self {
name: name.map(Encryption::from),
email: email.map(Encryption::from),
phone: phone.map(Encryption::from),
description,
phone_country_code,
metadata: *metadata,
connector_customer: *connector_customer,
modified_at: date_time::now(),
address_id,
default_payment_method_id: None,
updated_by: None,
tax_registration_id: tax_registration_id.map(Encryption::from),
last_modified_by,
},
CustomerUpdate::ConnectorCustomer {
connector_customer,
last_modified_by,
} => Self {
connector_customer,
modified_at: date_time::now(),
name: None,
email: None,
phone: None,
description: None,
phone_country_code: None,
metadata: None,
default_payment_method_id: None,
updated_by: None,
address_id: None,
tax_registration_id: None,
last_modified_by,
},
CustomerUpdate::UpdateDefaultPaymentMethod {
default_payment_method_id,
last_modified_by,
} => Self {
default_payment_method_id,
modified_at: date_time::now(),
name: None,
email: None,
phone: None,
description: None,
phone_country_code: None,
metadata: None,
connector_customer: None,
updated_by: None,
address_id: None,
tax_registration_id: None,
last_modified_by,
},
}
}
}
pub struct CustomerListConstraints {
pub limit: u16,
pub offset: Option<u32>,
pub customer_id: Option<id_type::CustomerId>,
pub time_range: Option<common_utils::types::TimeRange>,
}
impl From<CustomerListConstraints> for query::CustomerListConstraints {
fn from(value: CustomerListConstraints) -> Self {
Self {
limit: i64::from(value.limit),
offset: value.offset.map(i64::from),
customer_id: value.customer_id,
time_range: value.time_range,
}
}
}
#[async_trait::async_trait]
pub trait CustomerInterface
where
Customer: behaviour::Conversion<
DstType = storage_types::Customer,
NewDstType = storage_types::CustomerNew,
>,
{
type Error;
#[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, Self::Error>;
#[cfg(feature = "v1")]
async fn find_customer_optional_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<Customer>, Self::Error>;
#[cfg(feature = "v1")]
async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<Customer>, Self::Error>;
#[cfg(feature = "v2")]
async fn find_optional_by_merchant_id_merchant_reference_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<Customer>, Self::Error>;
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn update_customer_by_customer_id_merchant_id(
&self,
customer_id: id_type::CustomerId,
merchant_id: id_type::MerchantId,
customer: Customer,
customer_update: CustomerUpdate,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
#[cfg(feature = "v1")]
async fn find_customer_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
#[cfg(feature = "v2")]
async fn find_customer_by_merchant_reference_id_merchant_id(
&self,
merchant_reference_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
async fn list_customers_by_merchant_id(
&self,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
constraints: CustomerListConstraints,
) -> CustomResult<Vec<Customer>, Self::Error>;
async fn list_customers_by_merchant_id_with_count(
&self,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
constraints: CustomerListConstraints,
) -> CustomResult<(Vec<Customer>, usize), Self::Error>;
async fn insert_customer(
&self,
customer_data: Customer,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn update_customer_by_global_id(
&self,
id: &id_type::GlobalCustomerId,
customer: Customer,
customer_update: CustomerUpdate,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
#[cfg(feature = "v2")]
async fn find_customer_by_global_id(
&self,
id: &id_type::GlobalCustomerId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
}
#[cfg(feature = "v1")]
#[instrument]
pub async fn update_connector_customer_in_customers(
connector_label: &str,
customer: Option<&Customer>,
connector_customer_id: Option<String>,
) -> Option<CustomerUpdate> {
let mut connector_customer_map = customer
.and_then(|customer| customer.connector_customer.clone().expose_option())
.and_then(|connector_customer| connector_customer.as_object().cloned())
.unwrap_or_default();
let updated_connector_customer_map = connector_customer_id.map(|connector_customer_id| {
let connector_customer_value = serde_json::Value::String(connector_customer_id);
connector_customer_map.insert(connector_label.to_string(), connector_customer_value);
connector_customer_map
});
updated_connector_customer_map
.map(serde_json::Value::Object)
.map(
|connector_customer_value| CustomerUpdate::ConnectorCustomer {
connector_customer: Some(pii::SecretSerdeValue::new(connector_customer_value)),
last_modified_by: None,
},
)
}
#[cfg(feature = "v2")]
#[instrument]
pub async fn update_connector_customer_in_customers(
merchant_connector_account: &MerchantConnectorAccountTypeDetails,
customer: Option<&Customer>,
connector_customer_id: Option<String>,
) -> Option<CustomerUpdate> {
match merchant_connector_account {
MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(account) => {
connector_customer_id.map(|new_conn_cust_id| {
let connector_account_id = account.get_id().clone();
let mut connector_customer_map = customer
.and_then(|customer| customer.connector_customer.clone())
.unwrap_or_default();
connector_customer_map.insert(connector_account_id, new_conn_cust_id);
CustomerUpdate::ConnectorCustomer {
connector_customer: Some(connector_customer_map),
last_modified_by: None,
}
})
}
// TODO: Construct connector_customer for MerchantConnectorDetails if required by connector.
MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => {
todo!("Handle connector_customer construction for MerchantConnectorDetails");
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_request_types.rs | crates/hyperswitch_domain_models/src/router_request_types.rs | pub mod authentication;
pub mod fraud_check;
pub mod revenue_recovery;
pub mod subscriptions;
pub mod unified_authentication_service;
use api_models::payments::{AdditionalPaymentData, AddressDetails, RequestSurchargeDetails};
use common_types::payments as common_payments_types;
use common_utils::{
consts, errors,
ext_traits::OptionExt,
id_type, payout_method_utils, pii,
types::{MinorUnit, SemanticVersion},
};
use diesel_models::{enums as storage_enums, types::OrderDetailsWithAmount};
use error_stack::ResultExt;
use masking::Secret;
use serde::Serialize;
use serde_with::serde_as;
use super::payment_method_data::PaymentMethodData;
use crate::{
address,
errors::api_error_response::{ApiErrorResponse, NotImplementedMessage},
mandates,
payment_method_data::ExternalVaultPaymentMethodData,
payments,
router_data::{self, AccessTokenAuthenticationResponse, RouterData},
router_flow_types as flows, router_response_types as response_types,
vault::PaymentMethodCustomVaultingData,
};
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsAuthorizeData {
pub payment_method_data: PaymentMethodData,
/// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount)
/// If connector supports separate field for surcharge amount, consider using below functions defined on `PaymentsAuthorizeData` to fetch original amount and surcharge amount separately
/// ```text
/// get_original_amount()
/// get_surcharge_amount()
/// get_tax_on_surcharge_amount()
/// get_total_surcharge_amount() // returns surcharge_amount + tax_on_surcharge_amount
/// ```
pub amount: i64,
pub order_tax_amount: Option<MinorUnit>,
pub email: Option<pii::Email>,
pub customer_name: Option<Secret<String>>,
pub currency: storage_enums::Currency,
pub confirm: bool,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub router_return_url: Option<String>,
pub webhook_url: Option<String>,
pub complete_authorize_url: Option<String>,
// Mandates
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub off_session: Option<bool>,
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub browser_info: Option<BrowserInformation>,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub order_category: Option<String>,
pub session_token: Option<String>,
pub enrolled_for_3ds: bool,
pub related_transaction_id: Option<String>,
pub payment_experience: Option<storage_enums::PaymentExperience>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub surcharge_details: Option<SurchargeDetails>,
pub customer_id: Option<id_type::CustomerId>,
pub request_incremental_authorization: bool,
pub metadata: Option<serde_json::Value>,
pub authentication_data: Option<AuthenticationData>,
pub request_extended_authorization:
Option<common_types::primitive_wrappers::RequestExtendedAuthorizationBool>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
// New amount for amount frame work
pub minor_amount: MinorUnit,
/// Merchant's identifier for the payment/invoice. This will be sent to the connector
/// if the connector provides support to accept multiple reference ids.
/// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference.
pub merchant_order_reference_id: Option<String>,
pub integrity_object: Option<AuthoriseIntegrityObject>,
pub shipping_cost: Option<MinorUnit>,
pub additional_payment_method_data: Option<AdditionalPaymentData>,
pub merchant_account_id: Option<Secret<String>>,
pub merchant_config_currency: Option<storage_enums::Currency>,
pub connector_testing_data: Option<pii::SecretSerdeValue>,
pub order_id: Option<String>,
pub locale: Option<String>,
pub payment_channel: Option<common_enums::PaymentChannel>,
pub enable_partial_authorization:
Option<common_types::primitive_wrappers::EnablePartialAuthorizationBool>,
pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>,
pub is_stored_credential: Option<bool>,
pub mit_category: Option<common_enums::MitCategory>,
pub billing_descriptor: Option<common_types::payments::BillingDescriptor>,
pub tokenization: Option<common_enums::Tokenization>,
pub partner_merchant_identifier_details:
Option<common_types::payments::PartnerMerchantIdentifierDetails>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ExternalVaultProxyPaymentsData {
pub payment_method_data: ExternalVaultPaymentMethodData,
/// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount)
/// If connector supports separate field for surcharge amount, consider using below functions defined on `PaymentsAuthorizeData` to fetch original amount and surcharge amount separately
/// ```text
/// get_original_amount()
/// get_surcharge_amount()
/// get_tax_on_surcharge_amount()
/// get_total_surcharge_amount() // returns surcharge_amount + tax_on_surcharge_amount
/// ```
pub amount: i64,
pub order_tax_amount: Option<MinorUnit>,
pub email: Option<pii::Email>,
pub customer_name: Option<Secret<String>>,
pub currency: storage_enums::Currency,
pub confirm: bool,
pub statement_descriptor_suffix: Option<String>,
pub statement_descriptor: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub router_return_url: Option<String>,
pub webhook_url: Option<String>,
pub complete_authorize_url: Option<String>,
// Mandates
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub off_session: Option<bool>,
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub browser_info: Option<BrowserInformation>,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub order_category: Option<String>,
pub session_token: Option<String>,
pub enrolled_for_3ds: bool,
pub related_transaction_id: Option<String>,
pub payment_experience: Option<storage_enums::PaymentExperience>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub surcharge_details: Option<SurchargeDetails>,
pub customer_id: Option<id_type::CustomerId>,
pub request_incremental_authorization: bool,
pub metadata: Option<serde_json::Value>,
pub authentication_data: Option<AuthenticationData>,
pub request_extended_authorization:
Option<common_types::primitive_wrappers::RequestExtendedAuthorizationBool>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
// New amount for amount frame work
pub minor_amount: MinorUnit,
/// Merchant's identifier for the payment/invoice. This will be sent to the connector
/// if the connector provides support to accept multiple reference ids.
/// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference.
pub merchant_order_reference_id: Option<id_type::PaymentReferenceId>,
pub integrity_object: Option<AuthoriseIntegrityObject>,
pub shipping_cost: Option<MinorUnit>,
pub additional_payment_method_data: Option<AdditionalPaymentData>,
pub merchant_account_id: Option<Secret<String>>,
pub merchant_config_currency: Option<storage_enums::Currency>,
pub connector_testing_data: Option<pii::SecretSerdeValue>,
pub order_id: Option<String>,
}
// Note: Integrity traits for ExternalVaultProxyPaymentsData are not implemented
// as they are not mandatory for this flow. The integrity_check field in RouterData
// will use Ok(()) as default, similar to other flows.
// Implement ConnectorCustomerData conversion for ExternalVaultProxy RouterData
impl
TryFrom<
&RouterData<
flows::ExternalVaultProxy,
ExternalVaultProxyPaymentsData,
response_types::PaymentsResponseData,
>,
> for ConnectorCustomerData
{
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(
data: &RouterData<
flows::ExternalVaultProxy,
ExternalVaultProxyPaymentsData,
response_types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
email: data.request.email.clone(),
payment_method_data: None, // External vault proxy doesn't use regular payment method data
description: None,
phone: None,
name: data.request.customer_name.clone(),
preprocessing_id: data.preprocessing_id.clone(),
split_payments: data.request.split_payments.clone(),
setup_future_usage: data.request.setup_future_usage,
customer_acceptance: data.request.customer_acceptance.clone(),
customer_id: None,
billing_address: None,
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsPostSessionTokensData {
// amount here would include amount, surcharge_amount and shipping_cost
pub amount: MinorUnit,
/// original amount sent by the merchant
pub order_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub capture_method: Option<storage_enums::CaptureMethod>,
/// Merchant's identifier for the payment/invoice. This will be sent to the connector
/// if the connector provides support to accept multiple reference ids.
/// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference.
pub merchant_order_reference_id: Option<String>,
pub shipping_cost: Option<MinorUnit>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub router_return_url: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsUpdateMetadataData {
pub metadata: pii::SecretSerdeValue,
pub connector_transaction_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct AuthoriseIntegrityObject {
/// Authorise amount
pub amount: MinorUnit,
/// Authorise currency
pub currency: storage_enums::Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SyncIntegrityObject {
/// Sync amount
pub amount: Option<MinorUnit>,
/// Sync currency
pub currency: Option<storage_enums::Currency>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct PaymentsCaptureData {
pub amount_to_capture: i64,
pub currency: storage_enums::Currency,
pub connector_transaction_id: String,
pub payment_amount: i64,
pub multiple_capture_data: Option<MultipleCaptureRequestData>,
pub connector_meta: Option<serde_json::Value>,
pub browser_info: Option<BrowserInformation>,
pub metadata: Option<serde_json::Value>,
// This metadata is used to store the metadata shared during the payment intent request.
pub capture_method: Option<storage_enums::CaptureMethod>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
// New amount for amount frame work
pub minor_payment_amount: MinorUnit,
pub minor_amount_to_capture: MinorUnit,
pub integrity_object: Option<CaptureIntegrityObject>,
pub webhook_url: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct CaptureIntegrityObject {
/// capture amount
pub capture_amount: Option<MinorUnit>,
/// capture currency
pub currency: storage_enums::Currency,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct PaymentsIncrementalAuthorizationData {
pub total_amount: i64,
pub additional_amount: i64,
pub currency: storage_enums::Currency,
pub reason: Option<String>,
pub connector_transaction_id: String,
pub connector_meta: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct MultipleCaptureRequestData {
pub capture_sequence: i16,
pub capture_reference: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct AuthorizeSessionTokenData {
pub amount_to_capture: Option<i64>,
pub currency: storage_enums::Currency,
pub connector_transaction_id: String,
pub amount: Option<i64>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ConnectorCustomerData {
pub description: Option<String>,
pub email: Option<pii::Email>,
pub phone: Option<Secret<String>>,
pub name: Option<Secret<String>>,
pub preprocessing_id: Option<String>,
pub payment_method_data: Option<PaymentMethodData>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
// Mandates
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
pub customer_id: Option<id_type::CustomerId>,
pub billing_address: Option<AddressDetails>,
}
impl TryFrom<SetupMandateRequestData> for ConnectorCustomerData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: SetupMandateRequestData) -> Result<Self, Self::Error> {
Ok(Self {
email: data.email,
payment_method_data: Some(data.payment_method_data),
description: None,
phone: None,
name: data.customer_name.clone(),
preprocessing_id: None,
split_payments: data.split_payments,
setup_future_usage: data.setup_future_usage,
customer_acceptance: data.customer_acceptance,
customer_id: None,
billing_address: None,
})
}
}
impl TryFrom<SetupMandateRequestData> for PaymentsPreProcessingData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: SetupMandateRequestData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: Some(data.payment_method_data),
amount: data.amount,
minor_amount: data.minor_amount,
email: data.email,
currency: Some(data.currency),
payment_method_type: data.payment_method_type,
setup_mandate_details: data.setup_mandate_details,
capture_method: data.capture_method,
order_details: None,
router_return_url: data.router_return_url,
webhook_url: data.webhook_url,
complete_authorize_url: data.complete_authorize_url,
browser_info: data.browser_info,
surcharge_details: None,
connector_transaction_id: None,
mandate_id: data.mandate_id,
related_transaction_id: None,
redirect_response: None,
enrolled_for_3ds: false,
split_payments: None,
metadata: data.metadata,
customer_acceptance: data.customer_acceptance,
setup_future_usage: data.setup_future_usage,
is_stored_credential: data.is_stored_credential,
})
}
}
impl
TryFrom<
&RouterData<flows::Authorize, PaymentsAuthorizeData, response_types::PaymentsResponseData>,
> for ConnectorCustomerData
{
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(
data: &RouterData<
flows::Authorize,
PaymentsAuthorizeData,
response_types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
email: data.request.email.clone(),
payment_method_data: Some(data.request.payment_method_data.clone()),
description: None,
phone: None,
name: data.request.customer_name.clone(),
preprocessing_id: data.preprocessing_id.clone(),
split_payments: data.request.split_payments.clone(),
setup_future_usage: data.request.setup_future_usage,
customer_acceptance: data.request.customer_acceptance.clone(),
customer_id: None,
billing_address: None,
})
}
}
impl TryFrom<&RouterData<flows::Session, PaymentsSessionData, response_types::PaymentsResponseData>>
for ConnectorCustomerData
{
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(
data: &RouterData<
flows::Session,
PaymentsSessionData,
response_types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
email: data.request.email.clone(),
payment_method_data: None,
description: None,
phone: None,
name: data.request.customer_name.clone(),
preprocessing_id: data.preprocessing_id.clone(),
split_payments: None,
setup_future_usage: None,
customer_acceptance: None,
customer_id: None,
billing_address: None,
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentMethodTokenizationData {
pub payment_method_data: PaymentMethodData,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub browser_info: Option<BrowserInformation>,
pub currency: storage_enums::Currency,
pub amount: Option<i64>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub router_return_url: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
}
impl TryFrom<SetupMandateRequestData> for PaymentMethodTokenizationData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: SetupMandateRequestData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: data.payment_method_data,
browser_info: data.browser_info,
currency: data.currency,
amount: data.amount,
split_payments: data.split_payments,
customer_acceptance: data.customer_acceptance,
setup_future_usage: data.setup_future_usage,
setup_mandate_details: data.setup_mandate_details,
mandate_id: data.mandate_id,
payment_method_type: data.payment_method_type,
router_return_url: data.router_return_url,
capture_method: data.capture_method,
})
}
}
impl<F> From<&RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>>
for PaymentMethodTokenizationData
{
fn from(
data: &RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>,
) -> Self {
Self {
payment_method_data: data.request.payment_method_data.clone(),
browser_info: None,
currency: data.request.currency,
amount: Some(data.request.amount),
split_payments: data.request.split_payments.clone(),
customer_acceptance: data.request.customer_acceptance.clone(),
setup_future_usage: data.request.setup_future_usage,
setup_mandate_details: data.request.setup_mandate_details.clone(),
mandate_id: data.request.mandate_id.clone(),
payment_method_type: data.payment_method_type,
router_return_url: None,
capture_method: None,
}
}
}
impl TryFrom<PaymentsAuthorizeData> for PaymentMethodTokenizationData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: data.payment_method_data,
browser_info: data.browser_info,
currency: data.currency,
amount: Some(data.amount),
split_payments: data.split_payments.clone(),
customer_acceptance: data.customer_acceptance,
setup_future_usage: data.setup_future_usage,
setup_mandate_details: data.setup_mandate_details,
mandate_id: data.mandate_id,
payment_method_type: data.payment_method_type,
router_return_url: data.router_return_url,
capture_method: data.capture_method,
})
}
}
impl TryFrom<CompleteAuthorizeData> for PaymentMethodTokenizationData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: CompleteAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: data
.payment_method_data
.get_required_value("payment_method_data")
.change_context(ApiErrorResponse::MissingRequiredField {
field_name: "payment_method_data",
})?,
browser_info: data.browser_info,
currency: data.currency,
amount: Some(data.amount),
split_payments: None,
customer_acceptance: data.customer_acceptance,
setup_future_usage: data.setup_future_usage,
setup_mandate_details: data.setup_mandate_details,
mandate_id: data.mandate_id,
payment_method_type: data.payment_method_type,
router_return_url: data.router_return_url,
capture_method: data.capture_method,
})
}
}
impl TryFrom<ExternalVaultProxyPaymentsData> for PaymentMethodTokenizationData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(_data: ExternalVaultProxyPaymentsData) -> Result<Self, Self::Error> {
// TODO: External vault proxy payments should not use regular payment method tokenization
// This needs to be implemented separately for external vault flows
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason(
"External vault proxy tokenization not implemented".to_string(),
),
}
.into())
}
}
#[derive(Debug, Clone, Serialize)]
pub struct CreateOrderRequestData {
pub minor_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub payment_method_data: Option<PaymentMethodData>,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub webhook_url: Option<String>,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub router_return_url: Option<String>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub capture_method: Option<storage_enums::CaptureMethod>,
}
impl CreateOrderRequestData {
pub fn is_auto_capture(&self) -> bool {
match self.capture_method {
Some(storage_enums::CaptureMethod::Automatic)
| Some(storage_enums::CaptureMethod::SequentialAutomatic)
| None => true,
Some(storage_enums::CaptureMethod::Manual)
| Some(storage_enums::CaptureMethod::ManualMultiple)
| Some(storage_enums::CaptureMethod::Scheduled) => false,
}
}
}
impl TryFrom<PaymentsAuthorizeData> for CreateOrderRequestData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_type: data.payment_method_type,
minor_amount: data.minor_amount,
currency: data.currency,
payment_method_data: Some(data.payment_method_data),
order_details: data.order_details,
webhook_url: data.webhook_url,
router_return_url: data.router_return_url,
setup_mandate_details: data.setup_mandate_details,
capture_method: data.capture_method,
})
}
}
impl TryFrom<ExternalVaultProxyPaymentsData> for CreateOrderRequestData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: ExternalVaultProxyPaymentsData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_type: data.payment_method_type,
minor_amount: data.minor_amount,
currency: data.currency,
payment_method_data: None,
order_details: data.order_details,
webhook_url: data.webhook_url,
router_return_url: data.router_return_url,
setup_mandate_details: data.setup_mandate_details,
capture_method: data.capture_method,
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsPreProcessingData {
pub payment_method_data: Option<PaymentMethodData>,
pub amount: Option<i64>,
pub email: Option<pii::Email>,
pub currency: Option<storage_enums::Currency>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub router_return_url: Option<String>,
pub webhook_url: Option<String>,
pub complete_authorize_url: Option<String>,
pub surcharge_details: Option<SurchargeDetails>,
pub browser_info: Option<BrowserInformation>,
pub connector_transaction_id: Option<String>,
pub enrolled_for_3ds: bool,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub related_transaction_id: Option<String>,
pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
pub metadata: Option<Secret<serde_json::Value>>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
// New amount for amount frame work
pub minor_amount: Option<MinorUnit>,
pub is_stored_credential: Option<bool>,
}
#[derive(Debug, Clone, Serialize)]
pub struct GiftCardBalanceCheckRequestData {
pub payment_method_data: PaymentMethodData,
pub currency: Option<storage_enums::Currency>,
pub minor_amount: Option<MinorUnit>,
}
impl TryFrom<PaymentsAuthorizeData> for PaymentsPreProcessingData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: Some(data.payment_method_data),
amount: Some(data.amount),
minor_amount: Some(data.minor_amount),
email: data.email,
currency: Some(data.currency),
payment_method_type: data.payment_method_type,
setup_mandate_details: data.setup_mandate_details,
capture_method: data.capture_method,
order_details: data.order_details,
router_return_url: data.router_return_url,
webhook_url: data.webhook_url,
complete_authorize_url: data.complete_authorize_url,
browser_info: data.browser_info,
surcharge_details: data.surcharge_details,
connector_transaction_id: None,
mandate_id: data.mandate_id,
related_transaction_id: data.related_transaction_id,
redirect_response: None,
enrolled_for_3ds: data.enrolled_for_3ds,
split_payments: data.split_payments,
metadata: data.metadata.map(Secret::new),
customer_acceptance: data.customer_acceptance,
setup_future_usage: data.setup_future_usage,
is_stored_credential: data.is_stored_credential,
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsPreAuthenticateData {
pub payment_method_data: PaymentMethodData,
pub amount: i64,
pub email: Option<pii::Email>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub currency: Option<storage_enums::Currency>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub router_return_url: Option<String>,
pub complete_authorize_url: Option<String>,
pub browser_info: Option<BrowserInformation>,
pub enrolled_for_3ds: bool,
pub customer_name: Option<Secret<String>>,
pub metadata: Option<pii::SecretSerdeValue>,
// New amount for amount frame work
pub minor_amount: MinorUnit,
pub webhook_url: Option<String>,
}
impl TryFrom<PaymentsAuthorizeData> for PaymentsPreAuthenticateData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: data.payment_method_data,
customer_name: data.customer_name,
metadata: data.metadata.map(Secret::new),
amount: data.amount,
minor_amount: data.minor_amount,
email: data.email,
capture_method: data.capture_method,
currency: Some(data.currency),
payment_method_type: data.payment_method_type,
router_return_url: data.router_return_url,
complete_authorize_url: data.complete_authorize_url,
browser_info: data.browser_info,
enrolled_for_3ds: data.enrolled_for_3ds,
webhook_url: data.webhook_url,
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsAuthenticateData {
pub payment_method_data: Option<PaymentMethodData>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub amount: Option<i64>,
pub email: Option<pii::Email>,
pub currency: Option<storage_enums::Currency>,
pub complete_authorize_url: Option<String>,
pub browser_info: Option<BrowserInformation>,
pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
pub minor_amount: Option<MinorUnit>,
}
impl TryFrom<CompleteAuthorizeData> for PaymentsAuthenticateData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: CompleteAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: data.payment_method_data,
payment_method_type: data.payment_method_type,
amount: Some(data.amount),
minor_amount: Some(data.minor_amount),
email: data.email,
currency: Some(data.currency),
complete_authorize_url: data.complete_authorize_url,
browser_info: data.browser_info,
redirect_response: data.redirect_response,
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsPostAuthenticateData {
pub payment_method_data: Option<PaymentMethodData>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub amount: Option<i64>,
pub email: Option<pii::Email>,
pub currency: Option<storage_enums::Currency>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub browser_info: Option<BrowserInformation>,
pub connector_transaction_id: Option<String>,
pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
// New amount for amount frame work
pub minor_amount: Option<MinorUnit>,
pub metadata: Option<pii::SecretSerdeValue>,
}
impl TryFrom<CompleteAuthorizeData> for PaymentsPostAuthenticateData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: CompleteAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_type: data.payment_method_type,
payment_method_data: data.payment_method_data,
amount: Some(data.amount),
minor_amount: Some(data.minor_amount),
email: data.email,
currency: Some(data.currency),
capture_method: data.capture_method,
browser_info: data.browser_info,
connector_transaction_id: data.connector_transaction_id,
redirect_response: data.redirect_response,
metadata: data.connector_meta.map(Secret::new),
})
}
}
impl TryFrom<CompleteAuthorizeData> for PaymentsPreProcessingData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: CompleteAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: data.payment_method_data,
amount: Some(data.amount),
minor_amount: Some(data.minor_amount),
email: data.email,
currency: Some(data.currency),
payment_method_type: None,
setup_mandate_details: data.setup_mandate_details,
capture_method: data.capture_method,
order_details: None,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/configs.rs | crates/hyperswitch_domain_models/src/configs.rs | use common_utils::errors::CustomResult;
use diesel_models::configs as storage;
#[async_trait::async_trait]
pub trait ConfigInterface {
type Error;
async fn insert_config(
&self,
config: storage::ConfigNew,
) -> CustomResult<storage::Config, Self::Error>;
async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error>;
async fn find_config_by_key_unwrap_or(
&self,
key: &str,
// If the config is not found it will be created with the default value.
default_config: Option<String>,
) -> CustomResult<storage::Config, Self::Error>;
async fn find_config_by_key_from_db(
&self,
key: &str,
) -> CustomResult<storage::Config, Self::Error>;
async fn update_config_by_key(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, Self::Error>;
async fn update_config_in_database(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, Self::Error>;
async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error>;
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/router_data.rs | crates/hyperswitch_domain_models/src/router_data.rs | use std::{collections::HashMap, marker::PhantomData};
use cards::NetworkToken;
use common_types::{payments as common_payment_types, primitive_wrappers};
use common_utils::{
errors::IntegrityCheckError,
ext_traits::{OptionExt, ValueExt},
id_type::{self},
types::MinorUnit,
};
use error_stack::ResultExt;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
address::AddressDetails, payment_address::PaymentAddress, payment_method_data, payments,
router_response_types,
};
#[cfg(feature = "v2")]
use crate::{
payments::{
payment_attempt::{ErrorDetails, PaymentAttemptUpdate},
payment_intent::PaymentIntentUpdate,
},
router_flow_types, router_request_types,
};
#[derive(Debug, Clone, Serialize)]
pub struct RouterData<Flow, Request, Response> {
pub flow: PhantomData<Flow>,
pub merchant_id: id_type::MerchantId,
pub customer_id: Option<id_type::CustomerId>,
pub connector_customer: Option<String>,
pub connector: String,
// TODO: This should be a PaymentId type.
// Make this change after all the connector dependency has been removed from connectors
pub payment_id: String,
pub attempt_id: String,
pub tenant_id: id_type::TenantId,
pub status: common_enums::enums::AttemptStatus,
pub payment_method: common_enums::enums::PaymentMethod,
pub payment_method_type: Option<common_enums::enums::PaymentMethodType>,
pub connector_auth_type: ConnectorAuthType,
pub description: Option<String>,
pub address: PaymentAddress,
pub auth_type: common_enums::enums::AuthenticationType,
pub connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
pub connector_wallets_details: Option<common_utils::pii::SecretSerdeValue>,
pub amount_captured: Option<i64>,
pub access_token: Option<AccessToken>,
pub session_token: Option<String>,
pub reference_id: Option<String>,
pub payment_method_token: Option<PaymentMethodToken>,
pub recurring_mandate_payment_data: Option<RecurringMandatePaymentData>,
pub preprocessing_id: Option<String>,
/// This is the balance amount for gift cards or voucher
pub payment_method_balance: Option<PaymentMethodBalance>,
///for switching between two different versions of the same connector
pub connector_api_version: Option<String>,
/// Contains flow-specific data required to construct a request and send it to the connector.
pub request: Request,
/// Contains flow-specific data that the connector responds with.
pub response: Result<Response, ErrorResponse>,
/// Contains a reference ID that should be sent in the connector request
pub connector_request_reference_id: String,
#[cfg(feature = "payouts")]
/// Contains payout method data
pub payout_method_data: Option<api_models::payouts::PayoutMethodData>,
#[cfg(feature = "payouts")]
/// Contains payout's quote ID
pub quote_id: Option<String>,
pub test_mode: Option<bool>,
pub connector_http_status_code: Option<u16>,
pub external_latency: Option<u128>,
/// Contains apple pay flow type simplified or manual
pub apple_pay_flow: Option<payment_method_data::ApplePayFlow>,
pub frm_metadata: Option<common_utils::pii::SecretSerdeValue>,
pub dispute_id: Option<String>,
pub refund_id: Option<String>,
pub payout_id: Option<String>,
/// This field is used to store various data regarding the response from connector
pub connector_response: Option<ConnectorResponseData>,
pub payment_method_status: Option<common_enums::PaymentMethodStatus>,
// minor amount for amount framework
pub minor_amount_captured: Option<MinorUnit>,
pub minor_amount_capturable: Option<MinorUnit>,
// stores the authorized amount in case of partial authorization
pub authorized_amount: Option<MinorUnit>,
pub integrity_check: Result<(), IntegrityCheckError>,
pub additional_merchant_data: Option<api_models::admin::AdditionalMerchantData>,
pub header_payload: Option<payments::HeaderPayload>,
pub connector_mandate_request_reference_id: Option<String>,
pub l2_l3_data: Option<Box<L2L3Data>>,
pub authentication_id: Option<id_type::AuthenticationId>,
/// Contains the type of sca exemption required for the transaction
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
/// Contains stringified connector raw response body
pub raw_connector_response: Option<Secret<String>>,
/// Indicates whether the payment ID was provided by the merchant (true),
/// or generated internally by Hyperswitch (false)
pub is_payment_id_from_merchant: Option<bool>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct L2L3Data {
pub order_info: Option<OrderInfo>,
pub tax_info: Option<TaxInfo>,
pub customer_info: Option<CustomerInfo>,
pub shipping_details: Option<AddressDetails>,
pub billing_details: Option<BillingDetails>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderInfo {
pub order_date: Option<time::PrimitiveDateTime>,
pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
pub merchant_order_reference_id: Option<String>,
pub discount_amount: Option<MinorUnit>,
pub shipping_cost: Option<MinorUnit>,
pub duty_amount: Option<MinorUnit>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxInfo {
pub tax_status: Option<common_enums::TaxStatus>,
pub customer_tax_registration_id: Option<Secret<String>>,
pub merchant_tax_registration_id: Option<Secret<String>>,
pub shipping_amount_tax: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomerInfo {
pub customer_id: Option<id_type::CustomerId>,
pub customer_email: Option<common_utils::pii::Email>,
pub customer_name: Option<Secret<String>>,
pub customer_phone_number: Option<Secret<String>>,
pub customer_phone_country_code: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BillingDetails {
pub address_city: Option<String>,
}
impl L2L3Data {
pub fn get_shipping_country(&self) -> Option<common_enums::enums::CountryAlpha2> {
self.shipping_details
.as_ref()
.and_then(|address| address.country)
}
pub fn get_shipping_city(&self) -> Option<String> {
self.shipping_details
.as_ref()
.and_then(|address| address.city.clone())
}
pub fn get_shipping_state(&self) -> Option<Secret<String>> {
self.shipping_details
.as_ref()
.and_then(|address| address.state.clone())
}
pub fn get_shipping_origin_zip(&self) -> Option<Secret<String>> {
self.shipping_details
.as_ref()
.and_then(|address| address.origin_zip.clone())
}
pub fn get_shipping_zip(&self) -> Option<Secret<String>> {
self.shipping_details
.as_ref()
.and_then(|address| address.zip.clone())
}
pub fn get_shipping_address_line1(&self) -> Option<Secret<String>> {
self.shipping_details
.as_ref()
.and_then(|address| address.line1.clone())
}
pub fn get_shipping_address_line2(&self) -> Option<Secret<String>> {
self.shipping_details
.as_ref()
.and_then(|address| address.line2.clone())
}
pub fn get_order_date(&self) -> Option<time::PrimitiveDateTime> {
self.order_info.as_ref().and_then(|order| order.order_date)
}
pub fn get_order_details(&self) -> Option<Vec<api_models::payments::OrderDetailsWithAmount>> {
self.order_info
.as_ref()
.and_then(|order| order.order_details.clone())
}
pub fn get_merchant_order_reference_id(&self) -> Option<String> {
self.order_info
.as_ref()
.and_then(|order| order.merchant_order_reference_id.clone())
}
pub fn get_discount_amount(&self) -> Option<MinorUnit> {
self.order_info
.as_ref()
.and_then(|order| order.discount_amount)
}
pub fn get_shipping_cost(&self) -> Option<MinorUnit> {
self.order_info
.as_ref()
.and_then(|order| order.shipping_cost)
}
pub fn get_duty_amount(&self) -> Option<MinorUnit> {
self.order_info.as_ref().and_then(|order| order.duty_amount)
}
pub fn get_tax_status(&self) -> Option<common_enums::TaxStatus> {
self.tax_info.as_ref().and_then(|tax| tax.tax_status)
}
pub fn get_customer_tax_registration_id(&self) -> Option<Secret<String>> {
self.tax_info
.as_ref()
.and_then(|tax| tax.customer_tax_registration_id.clone())
}
pub fn get_merchant_tax_registration_id(&self) -> Option<Secret<String>> {
self.tax_info
.as_ref()
.and_then(|tax| tax.merchant_tax_registration_id.clone())
}
pub fn get_shipping_amount_tax(&self) -> Option<MinorUnit> {
self.tax_info
.as_ref()
.and_then(|tax| tax.shipping_amount_tax)
}
pub fn get_order_tax_amount(&self) -> Option<MinorUnit> {
self.tax_info.as_ref().and_then(|tax| tax.order_tax_amount)
}
pub fn get_customer_id(&self) -> Option<id_type::CustomerId> {
self.customer_info
.as_ref()
.and_then(|customer| customer.customer_id.clone())
}
pub fn get_customer_email(&self) -> Option<common_utils::pii::Email> {
self.customer_info
.as_ref()
.and_then(|customer| customer.customer_email.clone())
}
pub fn get_customer_name(&self) -> Option<Secret<String>> {
self.customer_info
.as_ref()
.and_then(|customer| customer.customer_name.clone())
}
pub fn get_customer_phone_number(&self) -> Option<Secret<String>> {
self.customer_info
.as_ref()
.and_then(|customer| customer.customer_phone_number.clone())
}
pub fn get_customer_phone_country_code(&self) -> Option<String> {
self.customer_info
.as_ref()
.and_then(|customer| customer.customer_phone_country_code.clone())
}
pub fn get_billing_city(&self) -> Option<String> {
self.billing_details
.as_ref()
.and_then(|billing| billing.address_city.clone())
}
}
// Different patterns of authentication.
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "auth_type")]
pub enum ConnectorAuthType {
TemporaryAuth,
HeaderKey {
api_key: Secret<String>,
},
BodyKey {
api_key: Secret<String>,
key1: Secret<String>,
},
SignatureKey {
api_key: Secret<String>,
key1: Secret<String>,
api_secret: Secret<String>,
},
MultiAuthKey {
api_key: Secret<String>,
key1: Secret<String>,
api_secret: Secret<String>,
key2: Secret<String>,
},
CurrencyAuthKey {
auth_key_map: HashMap<common_enums::enums::Currency, common_utils::pii::SecretSerdeValue>,
},
CertificateAuth {
certificate: Secret<String>,
private_key: Secret<String>,
},
#[default]
NoKey,
}
impl ConnectorAuthType {
pub fn from_option_secret_value(
value: Option<common_utils::pii::SecretSerdeValue>,
) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> {
value
.parse_value::<Self>("ConnectorAuthType")
.change_context(common_utils::errors::ParsingError::StructParseFailure(
"ConnectorAuthType",
))
}
pub fn from_secret_value(
value: common_utils::pii::SecretSerdeValue,
) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> {
value
.parse_value::<Self>("ConnectorAuthType")
.change_context(common_utils::errors::ParsingError::StructParseFailure(
"ConnectorAuthType",
))
}
// show only first and last two digits of the key and mask others with *
// mask the entire key if it's length is less than or equal to 4
fn mask_key(&self, key: String) -> Secret<String> {
let key_len = key.len();
let masked_key = if key_len <= 4 {
"*".repeat(key_len)
} else {
// Show the first two and last two characters, mask the rest with '*'
let mut masked_key = String::new();
let key_len = key.len();
// Iterate through characters by their index
for (index, character) in key.chars().enumerate() {
if index < 2 || index >= key_len - 2 {
masked_key.push(character); // Keep the first two and last two characters
} else {
masked_key.push('*'); // Mask the middle characters
}
}
masked_key
};
Secret::new(masked_key)
}
// Mask the keys in the auth_type
pub fn get_masked_keys(&self) -> Self {
match self {
Self::TemporaryAuth => Self::TemporaryAuth,
Self::NoKey => Self::NoKey,
Self::HeaderKey { api_key } => Self::HeaderKey {
api_key: self.mask_key(api_key.clone().expose()),
},
Self::BodyKey { api_key, key1 } => Self::BodyKey {
api_key: self.mask_key(api_key.clone().expose()),
key1: self.mask_key(key1.clone().expose()),
},
Self::SignatureKey {
api_key,
key1,
api_secret,
} => Self::SignatureKey {
api_key: self.mask_key(api_key.clone().expose()),
key1: self.mask_key(key1.clone().expose()),
api_secret: self.mask_key(api_secret.clone().expose()),
},
Self::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Self::MultiAuthKey {
api_key: self.mask_key(api_key.clone().expose()),
key1: self.mask_key(key1.clone().expose()),
api_secret: self.mask_key(api_secret.clone().expose()),
key2: self.mask_key(key2.clone().expose()),
},
Self::CurrencyAuthKey { auth_key_map } => Self::CurrencyAuthKey {
auth_key_map: auth_key_map.clone(),
},
Self::CertificateAuth {
certificate,
private_key,
} => Self::CertificateAuth {
certificate: self.mask_key(certificate.clone().expose()),
private_key: self.mask_key(private_key.clone().expose()),
},
}
}
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct AccessTokenAuthenticationResponse {
pub code: Secret<String>,
pub expires: i64,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct AccessToken {
pub token: Secret<String>,
pub expires: i64,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum PaymentMethodToken {
Token(Secret<String>),
ApplePayDecrypt(Box<common_payment_types::ApplePayPredecryptData>),
GooglePayDecrypt(Box<common_payment_types::GPayPredecryptData>),
PazeDecrypt(Box<PazeDecryptedData>),
}
impl PaymentMethodToken {
pub fn get_payment_method_token(&self) -> Option<Secret<String>> {
match self {
Self::Token(secret_token) => Some(secret_token.clone()),
_ => None,
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayPredecryptDataInternal {
pub application_primary_account_number: cards::CardNumber,
pub application_expiration_date: String,
pub currency_code: String,
pub transaction_amount: i64,
pub device_manufacturer_identifier: Secret<String>,
pub payment_data_type: Secret<String>,
pub payment_data: ApplePayCryptogramDataInternal,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayCryptogramDataInternal {
pub online_payment_cryptogram: Secret<String>,
pub eci_indicator: Option<String>,
}
impl TryFrom<ApplePayPredecryptDataInternal> for common_payment_types::ApplePayPredecryptData {
type Error = common_utils::errors::ValidationError;
fn try_from(data: ApplePayPredecryptDataInternal) -> Result<Self, Self::Error> {
let application_expiration_month = data.clone().get_expiry_month()?;
let application_expiration_year = data.clone().get_four_digit_expiry_year()?;
Ok(Self {
application_primary_account_number: data.application_primary_account_number.clone(),
application_expiration_month,
application_expiration_year,
payment_data: data.payment_data.into(),
})
}
}
impl From<GooglePayPredecryptDataInternal> for common_payment_types::GPayPredecryptData {
fn from(data: GooglePayPredecryptDataInternal) -> Self {
Self {
card_exp_month: Secret::new(data.payment_method_details.expiration_month.two_digits()),
card_exp_year: Secret::new(data.payment_method_details.expiration_year.four_digits()),
application_primary_account_number: data.payment_method_details.pan.clone(),
cryptogram: data.payment_method_details.cryptogram.clone(),
eci_indicator: data.payment_method_details.eci_indicator.clone(),
}
}
}
impl From<ApplePayCryptogramDataInternal> for common_payment_types::ApplePayCryptogramData {
fn from(payment_data: ApplePayCryptogramDataInternal) -> Self {
Self {
online_payment_cryptogram: payment_data.online_payment_cryptogram,
eci_indicator: payment_data.eci_indicator,
}
}
}
impl ApplePayPredecryptDataInternal {
/// This logic being applied as apple pay provides application_expiration_date in the YYMMDD format
fn get_four_digit_expiry_year(
&self,
) -> Result<Secret<String>, common_utils::errors::ValidationError> {
Ok(Secret::new(format!(
"20{}",
self.application_expiration_date.get(0..2).ok_or(
common_utils::errors::ValidationError::InvalidValue {
message: "Invalid two-digit year".to_string(),
}
)?
)))
}
fn get_expiry_month(&self) -> Result<Secret<String>, common_utils::errors::ValidationError> {
Ok(Secret::new(
self.application_expiration_date
.get(2..4)
.ok_or(common_utils::errors::ValidationError::InvalidValue {
message: "Invalid two-digit month".to_string(),
})?
.to_owned(),
))
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPredecryptDataInternal {
pub message_expiration: String,
pub message_id: String,
#[serde(rename = "paymentMethod")]
pub payment_method_type: String,
pub payment_method_details: GooglePayPaymentMethodDetails,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPaymentMethodDetails {
pub auth_method: common_enums::enums::GooglePayAuthMethod,
pub expiration_month: cards::CardExpirationMonth,
pub expiration_year: cards::CardExpirationYear,
pub pan: cards::CardNumber,
pub cryptogram: Option<Secret<String>>,
pub eci_indicator: Option<String>,
pub card_network: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeDecryptedData {
pub client_id: Secret<String>,
pub profile_id: String,
pub token: PazeToken,
pub payment_card_network: common_enums::enums::CardNetwork,
pub dynamic_data: Vec<PazeDynamicData>,
pub billing_address: PazeAddress,
pub consumer: PazeConsumer,
pub eci: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeToken {
pub payment_token: NetworkToken,
pub token_expiration_month: Secret<String>,
pub token_expiration_year: Secret<String>,
pub payment_account_reference: Secret<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeDynamicData {
pub dynamic_data_value: Option<Secret<String>>,
pub dynamic_data_type: Option<String>,
pub dynamic_data_expiration: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeAddress {
pub name: Option<Secret<String>>,
pub line1: Option<Secret<String>>,
pub line2: Option<Secret<String>>,
pub line3: Option<Secret<String>>,
pub city: Option<Secret<String>>,
pub state: Option<Secret<String>>,
pub zip: Option<Secret<String>>,
pub country_code: Option<common_enums::enums::CountryAlpha2>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeConsumer {
// This is consumer data not customer data.
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub full_name: Secret<String>,
pub email_address: common_utils::pii::Email,
pub mobile_number: Option<PazePhoneNumber>,
pub country_code: Option<common_enums::enums::CountryAlpha2>,
pub language_code: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PazePhoneNumber {
pub country_code: Secret<String>,
pub phone_number: Secret<String>,
}
#[derive(Debug, Default, Clone, Serialize)]
pub struct RecurringMandatePaymentData {
pub payment_method_type: Option<common_enums::enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe
pub original_payment_authorized_amount: Option<i64>,
pub original_payment_authorized_currency: Option<common_enums::enums::Currency>,
pub mandate_metadata: Option<common_utils::pii::SecretSerdeValue>,
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentMethodBalance {
pub amount: MinorUnit,
pub currency: common_enums::enums::Currency,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectorResponseData {
pub additional_payment_method_data: Option<AdditionalPaymentMethodConnectorResponse>,
extended_authorization_response_data: Option<ExtendedAuthorizationResponseData>,
is_overcapture_enabled: Option<primitive_wrappers::OvercaptureEnabledBool>,
pub mandate_reference: Option<router_response_types::MandateReference>,
}
impl ConnectorResponseData {
pub fn with_additional_payment_method_data(
additional_payment_method_data: AdditionalPaymentMethodConnectorResponse,
) -> Self {
Self {
additional_payment_method_data: Some(additional_payment_method_data),
extended_authorization_response_data: None,
is_overcapture_enabled: None,
mandate_reference: None,
}
}
pub fn new(
additional_payment_method_data: Option<AdditionalPaymentMethodConnectorResponse>,
is_overcapture_enabled: Option<primitive_wrappers::OvercaptureEnabledBool>,
extended_authorization_response_data: Option<ExtendedAuthorizationResponseData>,
mandate_reference: Option<router_response_types::MandateReference>,
) -> Self {
Self {
additional_payment_method_data,
extended_authorization_response_data,
is_overcapture_enabled,
mandate_reference,
}
}
pub fn get_extended_authorization_response_data(
&self,
) -> Option<&ExtendedAuthorizationResponseData> {
self.extended_authorization_response_data.as_ref()
}
pub fn is_overcapture_enabled(&self) -> Option<primitive_wrappers::OvercaptureEnabledBool> {
self.is_overcapture_enabled
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AdditionalPaymentMethodConnectorResponse {
Card {
/// Details regarding the authentication details of the connector, if this is a 3ds payment.
authentication_data: Option<serde_json::Value>,
/// Various payment checks that are done for a payment
payment_checks: Option<serde_json::Value>,
/// Card Network returned by the processor
card_network: Option<String>,
/// Domestic(Co-Branded) Card network returned by the processor
domestic_network: Option<String>,
},
PayLater {
klarna_sdk: Option<KlarnaSdkResponse>,
},
BankRedirect {
interac: Option<InteracCustomerInfo>,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtendedAuthorizationResponseData {
pub extended_authentication_applied:
Option<primitive_wrappers::ExtendedAuthorizationAppliedBool>,
pub extended_authorization_last_applied_at: Option<time::PrimitiveDateTime>,
pub capture_before: Option<time::PrimitiveDateTime>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KlarnaSdkResponse {
pub payment_type: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InteracCustomerInfo {
pub customer_info: Option<common_payment_types::InteracCustomerInfoDetails>,
}
#[derive(Clone, Debug, Serialize)]
pub struct ErrorResponse {
pub code: String,
pub message: String,
pub reason: Option<String>,
pub status_code: u16,
pub attempt_status: Option<common_enums::enums::AttemptStatus>,
pub connector_transaction_id: Option<String>,
pub network_decline_code: Option<String>,
pub network_advice_code: Option<String>,
pub network_error_message: Option<String>,
pub connector_metadata: Option<Secret<serde_json::Value>>,
}
impl Default for ErrorResponse {
fn default() -> Self {
Self {
code: "HE_00".to_string(),
message: "Something went wrong".to_string(),
reason: None,
status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}
}
}
impl ErrorResponse {
pub fn get_not_implemented() -> Self {
Self {
code: "IR_00".to_string(),
message: "This API is under development and will be made available soon.".to_string(),
reason: None,
status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}
}
}
/// Get updatable trakcer objects of payment intent and payment attempt
#[cfg(feature = "v2")]
pub trait TrackerPostUpdateObjects<Flow, FlowRequest, D> {
fn get_payment_intent_update(
&self,
payment_data: &D,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentIntentUpdate;
fn get_payment_attempt_update(
&self,
payment_data: &D,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentAttemptUpdate;
/// Get the amount that can be captured for the payment
fn get_amount_capturable(&self, payment_data: &D) -> Option<MinorUnit>;
/// Get the amount that has been captured for the payment
fn get_captured_amount(&self, payment_data: &D) -> Option<MinorUnit>;
/// Get the intent status based on parameters like captured amount and amount capturable
fn get_intent_status_for_db_update(
&self,
payment_data: &D,
) -> common_enums::enums::IntentStatus;
/// Get the intent error response status based on parameters like captured amount and amount capturable
fn get_intent_error_response_status_for_db_update(
&self,
payment_data: &D,
error: ErrorResponse,
) -> common_enums::enums::IntentStatus;
/// Get the attempt status based on parameters like captured amount and amount capturable
fn get_attempt_status_for_db_update(
&self,
payment_data: &D,
) -> common_enums::enums::AttemptStatus;
}
#[cfg(feature = "v2")]
impl
TrackerPostUpdateObjects<
router_flow_types::Authorize,
router_request_types::PaymentsAuthorizeData,
payments::PaymentConfirmData<router_flow_types::Authorize>,
>
for RouterData<
router_flow_types::Authorize,
router_request_types::PaymentsAuthorizeData,
router_response_types::PaymentsResponseData,
>
{
fn get_payment_intent_update(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentIntentUpdate {
let amount_captured = self.get_captured_amount(payment_data);
let intent_amount_captured = payment_data
.payment_intent
.amount_captured
.map(|amount| amount + amount_captured.unwrap_or(MinorUnit::zero()))
.or(amount_captured);
let updated_feature_metadata =
payment_data
.payment_intent
.feature_metadata
.clone()
.map(|mut feature_metadata| {
if let Some(ref mut payment_revenue_recovery_metadata) =
feature_metadata.payment_revenue_recovery_metadata
{
payment_revenue_recovery_metadata.payment_connector_transmission = match &self.response {
Ok(_) => common_enums::enums::PaymentConnectorTransmission::ConnectorCallSucceeded,
Err(error_response) => match &error_response.status_code {
500..=511 => common_enums::enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
_ => common_enums::enums::PaymentConnectorTransmission::ConnectorCallSucceeded,
}
}
}
Box::new(feature_metadata)
});
match self.response {
Ok(ref _response) => {
let status = self.get_intent_status_for_db_update(payment_data);
PaymentIntentUpdate::ConfirmIntentPostUpdate {
status,
amount_captured: intent_amount_captured,
updated_by: storage_scheme.to_string(),
feature_metadata: updated_feature_metadata,
}
}
Err(ref error) => {
let status = self
.get_intent_error_response_status_for_db_update(payment_data, error.clone());
PaymentIntentUpdate::ConfirmIntentPostUpdate {
status,
amount_captured: intent_amount_captured,
updated_by: storage_scheme.to_string(),
feature_metadata: updated_feature_metadata,
}
}
}
}
fn get_payment_attempt_update(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentAttemptUpdate {
let amount_capturable = self.get_amount_capturable(payment_data);
let amount_captured = self.get_captured_amount(payment_data);
match self.response {
Ok(ref response_router_data) => match response_router_data {
router_response_types::PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data,
connector_metadata,
connector_response_reference_id,
..
} => {
let attempt_status = self.get_attempt_status_for_db_update(payment_data);
let connector_payment_id = match resource_id {
router_request_types::ResponseId::NoResponseId => None,
router_request_types::ResponseId::ConnectorTransactionId(id)
| router_request_types::ResponseId::EncodedData(id) => Some(id.to_owned()),
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/merchant_key_store.rs | crates/hyperswitch_domain_models/src/merchant_key_store.rs | use common_utils::{
crypto::Encryptable,
custom_serde, date_time,
errors::{CustomResult, ValidationError},
type_name,
types::keymanager::{self, KeyManagerState},
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use time::PrimitiveDateTime;
use crate::type_encryption::{crypto_operation, CryptoOperation};
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantKeyStore {
pub merchant_id: common_utils::id_type::MerchantId,
pub key: Encryptable<Secret<Vec<u8>>>,
#[serde(with = "custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for MerchantKeyStore {
type DstType = diesel_models::merchant_key_store::MerchantKeyStore;
type NewDstType = diesel_models::merchant_key_store::MerchantKeyStoreNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::merchant_key_store::MerchantKeyStore {
key: self.key.into(),
merchant_id: self.merchant_id,
created_at: self.created_at,
})
}
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
_key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let identifier = keymanager::Identifier::Merchant(item.merchant_id.clone());
Ok(Self {
key: crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptLocally(item.key),
identifier,
key.peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting merchant key store".to_string(),
})?,
merchant_id: item.merchant_id,
created_at: item.created_at,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::merchant_key_store::MerchantKeyStoreNew {
merchant_id: self.merchant_id,
key: self.key.into(),
created_at: date_time::now(),
})
}
}
#[async_trait::async_trait]
pub trait MerchantKeyStoreInterface {
type Error;
async fn insert_merchant_key_store(
&self,
merchant_key_store: MerchantKeyStore,
key: &Secret<Vec<u8>>,
) -> CustomResult<MerchantKeyStore, Self::Error>;
async fn get_merchant_key_store_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
key: &Secret<Vec<u8>>,
) -> CustomResult<MerchantKeyStore, Self::Error>;
async fn delete_merchant_key_store_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, Self::Error>;
#[cfg(feature = "olap")]
async fn list_multiple_key_stores(
&self,
merchant_ids: Vec<common_utils::id_type::MerchantId>,
key: &Secret<Vec<u8>>,
) -> CustomResult<Vec<MerchantKeyStore>, Self::Error>;
async fn get_all_key_stores(
&self,
key: &Secret<Vec<u8>>,
from: u32,
to: u32,
) -> CustomResult<Vec<MerchantKeyStore>, Self::Error>;
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/payments.rs | crates/hyperswitch_domain_models/src/payments.rs | #[cfg(feature = "v2")]
use std::marker::PhantomData;
#[cfg(feature = "v2")]
use api_models::payments::{ConnectorMetadata, SessionToken, VaultSessionDetails};
use common_types::primitive_wrappers;
#[cfg(feature = "v1")]
use common_types::{
payments::BillingDescriptor,
primitive_wrappers::{
AlwaysRequestExtendedAuthorization, EnableOvercaptureBool, RequestExtendedAuthorizationBool,
},
};
#[cfg(feature = "v2")]
use common_utils::fp_utils;
use common_utils::{
self,
crypto::Encryptable,
encryption::Encryption,
errors::CustomResult,
ext_traits::ValueExt,
id_type, pii,
types::{keymanager::ToEncryptable, CreatedBy, MinorUnit},
};
use diesel_models::payment_intent::TaxDetails;
#[cfg(feature = "v2")]
use error_stack::ResultExt;
use masking::Secret;
use router_derive::ToEncryption;
use rustc_hash::FxHashMap;
use serde_json::Value;
use time::PrimitiveDateTime;
pub mod payment_attempt;
pub mod payment_intent;
#[cfg(feature = "v2")]
pub mod split_payments;
use common_enums as storage_enums;
#[cfg(feature = "v2")]
use diesel_models::types::{FeatureMetadata, OrderDetailsWithAmount};
use self::payment_attempt::PaymentAttempt;
#[cfg(feature = "v2")]
use crate::{
address::Address, business_profile, customer, errors, merchant_connector_account,
merchant_connector_account::MerchantConnectorAccountTypeDetails, payment_address,
payment_method_data, payment_methods, platform, revenue_recovery, routing,
ApiModelToDieselModelConvertor,
};
#[cfg(feature = "v1")]
use crate::{payment_method_data, RemoteStorageObject};
#[cfg(feature = "v1")]
#[derive(Clone, Debug, PartialEq, serde::Serialize, ToEncryption)]
pub struct PaymentIntent {
pub payment_id: id_type::PaymentId,
pub merchant_id: id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: MinorUnit,
pub shipping_cost: Option<MinorUnit>,
pub currency: Option<storage_enums::Currency>,
pub amount_captured: Option<MinorUnit>,
pub customer_id: Option<id_type::CustomerId>,
pub description: Option<String>,
pub return_url: Option<String>,
pub metadata: Option<Value>,
pub connector_id: Option<String>,
pub shipping_address_id: Option<String>,
pub billing_address_id: Option<String>,
pub statement_descriptor_name: Option<String>,
pub statement_descriptor_suffix: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub off_session: Option<bool>,
pub client_secret: Option<String>,
pub active_attempt: RemoteStorageObject<PaymentAttempt>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
pub allowed_payment_method_types: Option<Value>,
pub connector_metadata: Option<Value>,
pub feature_metadata: Option<Value>,
pub attempt_count: i16,
pub profile_id: Option<id_type::ProfileId>,
pub payment_link_id: Option<String>,
// Denotes the action(approve or reject) taken by merchant in case of manual review.
// Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment
pub merchant_decision: Option<String>,
pub payment_confirm_source: Option<storage_enums::PaymentSource>,
pub updated_by: String,
pub surcharge_applicable: Option<bool>,
pub request_incremental_authorization: Option<storage_enums::RequestIncrementalAuthorization>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
pub fingerprint_id: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub session_expiry: Option<PrimitiveDateTime>,
pub request_external_three_ds_authentication: Option<bool>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
#[encrypt]
pub customer_details: Option<Encryptable<Secret<Value>>>,
#[encrypt]
pub billing_details: Option<Encryptable<Secret<Value>>>,
pub merchant_order_reference_id: Option<String>,
#[encrypt]
pub shipping_details: Option<Encryptable<Secret<Value>>>,
pub is_payment_processor_token_flow: Option<bool>,
pub organization_id: id_type::OrganizationId,
pub tax_details: Option<TaxDetails>,
pub skip_external_tax_calculation: Option<bool>,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>,
pub processor_merchant_id: id_type::MerchantId,
pub created_by: Option<CreatedBy>,
pub force_3ds_challenge: Option<bool>,
pub force_3ds_challenge_trigger: Option<bool>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_payment_id_from_merchant: Option<bool>,
pub payment_channel: Option<common_enums::PaymentChannel>,
pub tax_status: Option<storage_enums::TaxStatus>,
pub discount_amount: Option<MinorUnit>,
pub order_date: Option<PrimitiveDateTime>,
pub shipping_amount_tax: Option<MinorUnit>,
pub duty_amount: Option<MinorUnit>,
pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,
pub enable_overcapture: Option<EnableOvercaptureBool>,
pub mit_category: Option<common_enums::MitCategory>,
pub billing_descriptor: Option<BillingDescriptor>,
pub tokenization: Option<common_enums::Tokenization>,
pub partner_merchant_identifier_details:
Option<common_types::payments::PartnerMerchantIdentifierDetails>,
}
impl PaymentIntent {
#[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.id
}
#[cfg(feature = "v2")]
/// This is the url to which the customer will be redirected to, to complete the redirection flow
pub fn create_start_redirection_url(
&self,
base_url: &str,
publishable_key: String,
) -> CustomResult<url::Url, errors::api_error_response::ApiErrorResponse> {
let start_redirection_url = &format!(
"{}/v2/payments/{}/start-redirection?publishable_key={}&profile_id={}",
base_url,
self.get_id().get_string_repr(),
publishable_key,
self.profile_id.get_string_repr()
);
url::Url::parse(start_redirection_url)
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Error creating start redirection url")
}
#[cfg(feature = "v1")]
pub fn get_request_extended_authorization_bool_if_connector_supports(
&self,
connector: common_enums::connector_enums::Connector,
always_request_extended_authorization_optional: Option<AlwaysRequestExtendedAuthorization>,
payment_method_optional: Option<common_enums::PaymentMethod>,
payment_method_type_optional: Option<common_enums::PaymentMethodType>,
) -> Option<RequestExtendedAuthorizationBool> {
use router_env::logger;
let is_extended_authorization_supported_by_connector = || {
let supported_pms = connector.get_payment_methods_supporting_extended_authorization();
let supported_pmts =
connector.get_payment_method_types_supporting_extended_authorization();
// check if payment method or payment method type is supported by the connector
logger::info!(
"Extended Authentication Connector:{:?}, Supported payment methods: {:?}, Supported payment method types: {:?}, Payment method Selected: {:?}, Payment method type Selected: {:?}",
connector,
supported_pms,
supported_pmts,
payment_method_optional,
payment_method_type_optional
);
match (payment_method_optional, payment_method_type_optional) {
(Some(payment_method), Some(payment_method_type)) => {
supported_pms.contains(&payment_method)
&& supported_pmts.contains(&payment_method_type)
}
(Some(payment_method), None) => supported_pms.contains(&payment_method),
(None, Some(payment_method_type)) => supported_pmts.contains(&payment_method_type),
(None, None) => false,
}
};
let intent_request_extended_authorization_optional = self.request_extended_authorization;
let is_extended_authorization_requested = intent_request_extended_authorization_optional
.map(|should_request_extended_authorization| *should_request_extended_authorization)
.or(always_request_extended_authorization_optional.map(
|should_always_request_extended_authorization| {
*should_always_request_extended_authorization
},
));
is_extended_authorization_requested
.map(|requested| {
if requested {
is_extended_authorization_supported_by_connector()
} else {
false
}
})
.map(RequestExtendedAuthorizationBool::from)
}
#[cfg(feature = "v1")]
pub fn get_enable_overcapture_bool_if_connector_supports(
&self,
connector: common_enums::connector_enums::Connector,
always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
capture_method: &Option<common_enums::CaptureMethod>,
) -> Option<EnableOvercaptureBool> {
let is_overcapture_supported_by_connector =
connector.is_overcapture_supported_by_connector();
if matches!(capture_method, Some(common_enums::CaptureMethod::Manual))
&& is_overcapture_supported_by_connector
{
self.enable_overcapture
.or_else(|| always_enable_overcapture.map(EnableOvercaptureBool::from))
} else {
None
}
}
#[cfg(feature = "v2")]
/// This is the url to which the customer will be redirected to, after completing the redirection flow
pub fn create_finish_redirection_url(
&self,
base_url: &str,
publishable_key: &str,
) -> CustomResult<url::Url, errors::api_error_response::ApiErrorResponse> {
let finish_redirection_url = format!(
"{base_url}/v2/payments/{}/finish-redirection/{publishable_key}/{}",
self.id.get_string_repr(),
self.profile_id.get_string_repr()
);
url::Url::parse(&finish_redirection_url)
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Error creating finish redirection url")
}
pub fn parse_and_get_metadata<T>(
&self,
type_name: &'static str,
) -> CustomResult<Option<T>, common_utils::errors::ParsingError>
where
T: for<'de> masking::Deserialize<'de>,
{
self.metadata
.clone()
.map(|metadata| metadata.parse_value(type_name))
.transpose()
}
#[cfg(feature = "v1")]
pub fn merge_metadata(
&self,
request_metadata: Value,
) -> Result<Value, common_utils::errors::ParsingError> {
if !request_metadata.is_null() {
match (&self.metadata, &request_metadata) {
(Some(Value::Object(existing_map)), Value::Object(req_map)) => {
let mut merged = existing_map.clone();
merged.extend(req_map.clone());
Ok(Value::Object(merged))
}
(None, Value::Object(_)) => Ok(request_metadata),
_ => {
router_env::logger::error!(
"Expected metadata to be an object, got: {:?}",
request_metadata
);
Err(common_utils::errors::ParsingError::UnknownError)
}
}
} else {
router_env::logger::error!("Metadata does not contain any key");
Err(common_utils::errors::ParsingError::UnknownError)
}
}
#[cfg(feature = "v1")]
pub fn get_billing_descriptor(&self) -> Option<BillingDescriptor> {
self.billing_descriptor
.as_ref()
.map(|descriptor| BillingDescriptor {
name: descriptor.name.clone(),
city: descriptor.city.clone(),
phone: descriptor.phone.clone(),
statement_descriptor: descriptor
.statement_descriptor
.clone()
.or_else(|| self.statement_descriptor_name.clone()),
statement_descriptor_suffix: descriptor
.statement_descriptor_suffix
.clone()
.or_else(|| self.statement_descriptor_suffix.clone()),
reference: descriptor.reference.clone(),
})
.or_else(|| {
// Only build a fallback if at least one descriptor exists
if self.statement_descriptor_name.is_some()
|| self.statement_descriptor_suffix.is_some()
{
Some(BillingDescriptor {
name: None,
city: None,
phone: None,
reference: None,
statement_descriptor: self.statement_descriptor_name.clone(),
statement_descriptor_suffix: self.statement_descriptor_suffix.clone(),
})
} else {
None
}
})
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
pub struct AmountDetails {
/// The amount of the order in the lowest denomination of currency
pub order_amount: MinorUnit,
/// The currency of the order
pub currency: common_enums::Currency,
/// The shipping cost of the order. This has to be collected from the merchant
pub shipping_cost: Option<MinorUnit>,
/// Tax details related to the order. This will be calculated by the external tax provider
pub tax_details: Option<TaxDetails>,
/// The action to whether calculate tax by calling external tax provider or not
pub skip_external_tax_calculation: common_enums::TaxCalculationOverride,
/// The action to whether calculate surcharge or not
pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride,
/// The surcharge amount to be added to the order, collected from the merchant
pub surcharge_amount: Option<MinorUnit>,
/// tax on surcharge amount
pub tax_on_surcharge: Option<MinorUnit>,
/// The total amount captured for the order. This is the sum of all the captured amounts for the order.
/// For automatic captures, this will be the same as net amount for the order
pub amount_captured: Option<MinorUnit>,
}
#[cfg(feature = "v2")]
impl AmountDetails {
/// Get the action to whether calculate surcharge or not as a boolean value
fn get_surcharge_action_as_bool(&self) -> bool {
self.skip_surcharge_calculation.as_bool()
}
/// Get the action to whether calculate external tax or not as a boolean value
pub fn get_external_tax_action_as_bool(&self) -> bool {
self.skip_external_tax_calculation.as_bool()
}
/// Calculate the net amount for the order
pub fn calculate_net_amount(&self) -> MinorUnit {
self.order_amount
+ self.shipping_cost.unwrap_or(MinorUnit::zero())
+ self.surcharge_amount.unwrap_or(MinorUnit::zero())
+ self.tax_on_surcharge.unwrap_or(MinorUnit::zero())
}
pub fn create_attempt_amount_details(
&self,
confirm_intent_request: &api_models::payments::PaymentsConfirmIntentRequest,
) -> payment_attempt::AttemptAmountDetails {
let net_amount = self.calculate_net_amount();
let surcharge_amount = match self.skip_surcharge_calculation {
common_enums::SurchargeCalculationOverride::Skip => self.surcharge_amount,
common_enums::SurchargeCalculationOverride::Calculate => None,
};
let tax_on_surcharge = match self.skip_surcharge_calculation {
common_enums::SurchargeCalculationOverride::Skip => self.tax_on_surcharge,
common_enums::SurchargeCalculationOverride::Calculate => None,
};
let order_tax_amount = match self.skip_external_tax_calculation {
common_enums::TaxCalculationOverride::Skip => {
self.tax_details.as_ref().and_then(|tax_details| {
tax_details.get_tax_amount(Some(confirm_intent_request.payment_method_subtype))
})
}
common_enums::TaxCalculationOverride::Calculate => None,
};
payment_attempt::AttemptAmountDetails::from(payment_attempt::AttemptAmountDetailsSetter {
net_amount,
amount_to_capture: None,
surcharge_amount,
tax_on_surcharge,
// This will be updated when we receive response from the connector
amount_capturable: MinorUnit::zero(),
shipping_cost: self.shipping_cost,
order_tax_amount,
amount_captured: None,
})
}
pub fn get_order_amount_for_recovery_data(
&self,
) -> CustomResult<MinorUnit, errors::api_error_response::ApiErrorResponse> {
// Validate that amount_captured doesn't exceed order_amount
let captured_amount = self.amount_captured.unwrap_or(MinorUnit::zero());
fp_utils::when(captured_amount > self.order_amount, || {
Err(
errors::api_error_response::ApiErrorResponse::InvalidRequestData {
message: "Amount captured cannot exceed the order amount".into(),
},
)
})?;
Ok(self.order_amount - captured_amount)
}
pub fn create_split_attempt_amount_details(
&self,
confirm_intent_request: &api_models::payments::PaymentsConfirmIntentRequest,
split_amount: MinorUnit,
) -> payment_attempt::AttemptAmountDetails {
let net_amount = split_amount;
let surcharge_amount = match self.skip_surcharge_calculation {
common_enums::SurchargeCalculationOverride::Skip => self.surcharge_amount,
common_enums::SurchargeCalculationOverride::Calculate => None,
};
let tax_on_surcharge = match self.skip_surcharge_calculation {
common_enums::SurchargeCalculationOverride::Skip => self.tax_on_surcharge,
common_enums::SurchargeCalculationOverride::Calculate => None,
};
let order_tax_amount = match self.skip_external_tax_calculation {
common_enums::TaxCalculationOverride::Skip => {
self.tax_details.as_ref().and_then(|tax_details| {
tax_details.get_tax_amount(Some(confirm_intent_request.payment_method_subtype))
})
}
common_enums::TaxCalculationOverride::Calculate => None,
};
payment_attempt::AttemptAmountDetails::from(payment_attempt::AttemptAmountDetailsSetter {
net_amount,
amount_to_capture: None,
surcharge_amount,
tax_on_surcharge,
// This will be updated when we receive response from the connector
amount_capturable: MinorUnit::zero(),
shipping_cost: self.shipping_cost,
order_tax_amount,
amount_captured: None,
})
}
pub fn proxy_create_attempt_amount_details(
&self,
_confirm_intent_request: &api_models::payments::ProxyPaymentsRequest,
) -> payment_attempt::AttemptAmountDetails {
let net_amount = self.calculate_net_amount();
let surcharge_amount = match self.skip_surcharge_calculation {
common_enums::SurchargeCalculationOverride::Skip => self.surcharge_amount,
common_enums::SurchargeCalculationOverride::Calculate => None,
};
let tax_on_surcharge = match self.skip_surcharge_calculation {
common_enums::SurchargeCalculationOverride::Skip => self.tax_on_surcharge,
common_enums::SurchargeCalculationOverride::Calculate => None,
};
let order_tax_amount = match self.skip_external_tax_calculation {
common_enums::TaxCalculationOverride::Skip => self
.tax_details
.as_ref()
.and_then(|tax_details| tax_details.get_tax_amount(None)),
common_enums::TaxCalculationOverride::Calculate => None,
};
payment_attempt::AttemptAmountDetails::from(payment_attempt::AttemptAmountDetailsSetter {
net_amount,
amount_to_capture: None,
surcharge_amount,
tax_on_surcharge,
// This will be updated when we receive response from the connector
amount_capturable: MinorUnit::zero(),
shipping_cost: self.shipping_cost,
order_tax_amount,
amount_captured: None,
})
}
pub fn update_from_request(self, req: &api_models::payments::AmountDetailsUpdate) -> Self {
Self {
order_amount: req
.order_amount()
.unwrap_or(self.order_amount.into())
.into(),
currency: req.currency().unwrap_or(self.currency),
shipping_cost: req.shipping_cost().or(self.shipping_cost),
tax_details: req
.order_tax_amount()
.map(|order_tax_amount| TaxDetails {
default: Some(diesel_models::DefaultTax { order_tax_amount }),
payment_method_type: None,
})
.or(self.tax_details),
skip_external_tax_calculation: req
.skip_external_tax_calculation()
.unwrap_or(self.skip_external_tax_calculation),
skip_surcharge_calculation: req
.skip_surcharge_calculation()
.unwrap_or(self.skip_surcharge_calculation),
surcharge_amount: req.surcharge_amount().or(self.surcharge_amount),
tax_on_surcharge: req.tax_on_surcharge().or(self.tax_on_surcharge),
amount_captured: self.amount_captured,
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, PartialEq, serde::Serialize, ToEncryption)]
pub struct PaymentIntent {
/// The global identifier for the payment intent. This is generated by the system.
/// The format of the global id is `{cell_id:5}_pay_{time_ordered_uuid:32}`.
pub id: id_type::GlobalPaymentId,
/// The identifier for the merchant. This is automatically derived from the api key used to create the payment.
pub merchant_id: id_type::MerchantId,
/// The status of payment intent.
pub status: storage_enums::IntentStatus,
/// The amount related details of the payment
pub amount_details: AmountDetails,
/// The total amount captured for the order. This is the sum of all the captured amounts for the order.
pub amount_captured: Option<MinorUnit>,
/// The identifier for the customer. This is the identifier for the customer in the merchant's system.
pub customer_id: Option<id_type::GlobalCustomerId>,
/// The description of the order. This will be passed to connectors which support description.
pub description: Option<common_utils::types::Description>,
/// The return url for the payment. This is the url to which the user will be redirected after the payment is completed.
pub return_url: Option<common_utils::types::Url>,
/// The metadata for the payment intent. This is the metadata that will be passed to the connectors.
pub metadata: Option<pii::SecretSerdeValue>,
/// The statement descriptor for the order, this will be displayed in the user's bank statement.
pub statement_descriptor: Option<common_utils::types::StatementDescriptor>,
/// The time at which the order was created
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
/// The time at which the order was last modified
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub setup_future_usage: storage_enums::FutureUsage,
/// The active attempt for the payment intent. This is the payment attempt that is currently active for the payment intent.
pub active_attempt_id: Option<id_type::GlobalAttemptId>,
/// This field represents whether there are attempt groups for this payment intent. Used in split payments workflow
pub active_attempt_id_type: common_enums::ActiveAttemptIDType,
/// The ID of the active attempt group for the payment intent
pub active_attempts_group_id: Option<id_type::GlobalAttemptGroupId>,
/// The order details for the payment.
pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>,
/// This is the list of payment method types that are allowed for the payment intent.
/// This field allows the merchant to restrict the payment methods that can be used for the payment intent.
pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>,
/// This metadata contains connector-specific details like Apple Pay certificates, Airwallex data, Noon order category, Braintree merchant account ID, and Adyen testing data
pub connector_metadata: Option<ConnectorMetadata>,
pub feature_metadata: Option<FeatureMetadata>,
/// Number of attempts that have been made for the order
pub attempt_count: i16,
/// The profile id for the payment.
pub profile_id: id_type::ProfileId,
/// The payment link id for the payment. This is generated only if `enable_payment_link` is set to true.
pub payment_link_id: Option<String>,
/// This Denotes the action(approve or reject) taken by merchant in case of manual review.
/// Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment
pub frm_merchant_decision: Option<common_enums::MerchantDecision>,
/// Denotes the last instance which updated the payment
pub updated_by: String,
/// Denotes whether merchant requested for incremental authorization to be enabled for this payment.
pub request_incremental_authorization: storage_enums::RequestIncrementalAuthorization,
/// Denotes whether merchant requested for split payments to be enabled for this payment
pub split_txns_enabled: storage_enums::SplitTxnsEnabled,
/// Denotes the number of authorizations that have been made for the payment.
pub authorization_count: Option<i32>,
/// Denotes the client secret expiry for the payment. This is the time at which the client secret will expire.
#[serde(with = "common_utils::custom_serde::iso8601")]
pub session_expiry: PrimitiveDateTime,
/// Denotes whether merchant requested for 3ds authentication to be enabled for this payment.
pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest,
/// Metadata related to fraud and risk management
pub frm_metadata: Option<pii::SecretSerdeValue>,
/// The details of the customer in a denormalized form. Only a subset of fields are stored.
#[encrypt]
pub customer_details: Option<Encryptable<Secret<Value>>>,
/// The reference id for the order in the merchant's system. This value can be passed by the merchant.
pub merchant_reference_id: Option<id_type::PaymentReferenceId>,
/// The billing address for the order in a denormalized form.
#[encrypt(ty = Value)]
pub billing_address: Option<Encryptable<Address>>,
/// The shipping address for the order in a denormalized form.
#[encrypt(ty = Value)]
pub shipping_address: Option<Encryptable<Address>>,
/// Capture method for the payment
pub capture_method: storage_enums::CaptureMethod,
/// Authentication type that is requested by the merchant for this payment.
pub authentication_type: Option<common_enums::AuthenticationType>,
/// This contains the pre routing results that are done when routing is done during listing the payment methods.
pub prerouting_algorithm: Option<routing::PaymentRoutingInfo>,
/// The organization id for the payment. This is derived from the merchant account
pub organization_id: id_type::OrganizationId,
/// Denotes the request by the merchant whether to enable a payment link for this payment.
pub enable_payment_link: common_enums::EnablePaymentLinkRequest,
/// Denotes the request by the merchant whether to apply MIT exemption for this payment
pub apply_mit_exemption: common_enums::MitExemptionRequest,
/// Denotes whether the customer is present during the payment flow. This information may be used for 3ds authentication
pub customer_present: common_enums::PresenceOfCustomerDuringPayment,
/// Denotes the override for payment link configuration
pub payment_link_config: Option<diesel_models::PaymentLinkConfigRequestForPayments>,
/// The straight through routing algorithm id that is used for this payment. This overrides the default routing algorithm that is configured in business profile.
pub routing_algorithm_id: Option<id_type::RoutingId>,
/// Split Payment Data
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
pub force_3ds_challenge: Option<bool>,
pub force_3ds_challenge_trigger: Option<bool>,
/// merchant who owns the credentials of the processor, i.e. processor owner
pub processor_merchant_id: id_type::MerchantId,
/// merchant or user who invoked the resource-based API (identifier) and the source (Api, Jwt(Dashboard))
pub created_by: Option<CreatedBy>,
/// Indicates if the redirection has to open in the iframe
pub is_iframe_redirection_enabled: Option<bool>,
/// Indicates whether the payment_id was provided by the merchant (true),
/// or generated internally by Hyperswitch (false)
pub is_payment_id_from_merchant: Option<bool>,
/// Denotes whether merchant requested for partial authorization to be enabled for this payment.
pub enable_partial_authorization: primitive_wrappers::EnablePartialAuthorizationBool,
}
#[cfg(feature = "v2")]
impl PaymentIntent {
/// Extract customer_id from payment intent feature metadata
pub fn extract_connector_customer_id_from_payment_intent(
&self,
) -> Result<String, common_utils::errors::ValidationError> {
self.feature_metadata
.as_ref()
.and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref())
.map(|recovery| {
recovery
.billing_connector_payment_details
.connector_customer_id
.clone()
})
.ok_or(
common_utils::errors::ValidationError::MissingRequiredField {
field_name: "connector_customer_id".to_string(),
},
)
}
fn get_payment_method_sub_type(&self) -> Option<common_enums::PaymentMethodType> {
self.feature_metadata
.as_ref()
.and_then(|metadata| metadata.get_payment_method_sub_type())
}
fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethod> {
self.feature_metadata
.as_ref()
.and_then(|metadata| metadata.get_payment_method_type())
}
pub fn get_connector_customer_id_from_feature_metadata(&self) -> Option<String> {
self.feature_metadata
.as_ref()
.and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref())
.map(|recovery_metadata| {
recovery_metadata
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/type_encryption.rs | crates/hyperswitch_domain_models/src/type_encryption.rs | use async_trait::async_trait;
use common_utils::{
crypto,
encryption::Encryption,
errors::{CryptoError, CustomResult},
ext_traits::AsyncExt,
metrics::utils::record_operation_time,
types::keymanager::{Identifier, KeyManagerState},
};
use encrypt::TypeEncryption;
use masking::Secret;
use router_env::{instrument, tracing};
use rustc_hash::FxHashMap;
mod encrypt {
use async_trait::async_trait;
use common_utils::{
crypto,
encryption::Encryption,
errors::{self, CustomResult},
ext_traits::ByteSliceExt,
keymanager::call_encryption_service,
transformers::{ForeignFrom, ForeignTryFrom},
types::keymanager::{
BatchDecryptDataResponse, BatchEncryptDataRequest, BatchEncryptDataResponse,
DecryptDataResponse, EncryptDataRequest, EncryptDataResponse, Identifier,
KeyManagerState, TransientBatchDecryptDataRequest, TransientDecryptDataRequest,
},
};
use error_stack::ResultExt;
use http::Method;
use masking::{PeekInterface, Secret};
use router_env::{instrument, logger, tracing};
use rustc_hash::FxHashMap;
use super::{metrics, obtain_data_to_decrypt_locally, EncryptedJsonType};
#[async_trait]
pub trait TypeEncryption<
T,
V: crypto::EncodeMessage + crypto::DecodeMessage,
S: masking::Strategy<T>,
>: Sized
{
async fn encrypt_via_api(
state: &KeyManagerState,
masked_data: Secret<T, S>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError>;
async fn decrypt_via_api(
state: &KeyManagerState,
encrypted_data: Encryption,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError>;
async fn encrypt(
masked_data: Secret<T, S>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError>;
async fn decrypt(
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError>;
async fn batch_encrypt_via_api(
state: &KeyManagerState,
masked_data: FxHashMap<String, Secret<T, S>>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>;
async fn batch_decrypt_via_api(
state: &KeyManagerState,
encrypted_data: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>;
async fn batch_encrypt(
masked_data: FxHashMap<String, Secret<T, S>>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>;
async fn batch_decrypt(
encrypted_data: FxHashMap<String, Encryption>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>;
}
fn is_encryption_service_enabled(_state: &KeyManagerState) -> bool {
#[cfg(feature = "encryption_service")]
{
_state.enabled
}
#[cfg(not(feature = "encryption_service"))]
{
false
}
}
#[async_trait]
impl<
V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static,
S: masking::Strategy<String> + Send + Sync,
> TypeEncryption<String, V, S> for crypto::Encryptable<Secret<String, S>>
{
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt_via_api(
state: &KeyManagerState,
masked_data: Secret<String, S>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::encrypt(masked_data, key, crypt_algo).await
} else {
let result: Result<
EncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/encrypt",
EncryptDataRequest::from((masked_data.clone(), identifier)),
)
.await;
match result {
Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))),
Err(err) => {
logger::error!("Encryption error {:?}", err);
metrics::ENCRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Encryption");
Self::encrypt(masked_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt_via_api(
state: &KeyManagerState,
encrypted_data: Encryption,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::decrypt(encrypted_data, key, crypt_algo).await
} else {
let result: Result<
DecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/decrypt",
TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)),
)
.await;
let decrypted = match result {
Ok(decrypted_data) => {
ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data))
}
Err(err) => {
logger::error!("Decryption error {:?}", err);
Err(err.change_context(errors::CryptoError::DecodingFailed))
}
};
match decrypted {
Ok(de) => Ok(de),
Err(_) => {
metrics::DECRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Decryption");
Self::decrypt(encrypted_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt(
masked_data: Secret<String, S>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]);
let encrypted_data = crypt_algo.encode_message(key, masked_data.peek().as_bytes())?;
Ok(Self::new(masked_data, encrypted_data.into()))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt(
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]);
let encrypted = obtain_data_to_decrypt_locally(encrypted_data.into_inner())?;
let data = crypt_algo.decode_message(key, encrypted.clone())?;
let value: String = std::str::from_utf8(&data)
.change_context(errors::CryptoError::DecodingFailed)?
.to_string();
Ok(Self::new(value.into(), encrypted))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt_via_api(
state: &KeyManagerState,
masked_data: FxHashMap<String, Secret<String, S>>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::batch_encrypt(masked_data, key, crypt_algo).await
} else {
let result: Result<
BatchEncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/encrypt",
BatchEncryptDataRequest::from((masked_data.clone(), identifier)),
)
.await;
match result {
Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))),
Err(err) => {
metrics::ENCRYPTION_API_FAILURES.add(1, &[]);
logger::error!("Encryption error {:?}", err);
logger::info!("Fall back to Application Encryption");
Self::batch_encrypt(masked_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt_via_api(
state: &KeyManagerState,
encrypted_data: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
} else {
let result: Result<
BatchDecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/decrypt",
TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)),
)
.await;
let decrypted = match result {
Ok(decrypted_data) => {
ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data))
}
Err(err) => {
logger::error!("Decryption error {:?}", err);
Err(err.change_context(errors::CryptoError::DecodingFailed))
}
};
match decrypted {
Ok(de) => Ok(de),
Err(_) => {
metrics::DECRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Decryption");
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt(
masked_data: FxHashMap<String, Secret<String, S>>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]);
masked_data
.into_iter()
.map(|(k, v)| {
Ok((
k,
Self::new(
v.clone(),
crypt_algo.encode_message(key, v.peek().as_bytes())?.into(),
),
))
})
.collect()
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt(
encrypted_data: FxHashMap<String, Encryption>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]);
encrypted_data
.into_iter()
.map(|(k, v)| {
let encrypted = obtain_data_to_decrypt_locally(v.clone().into_inner())?;
let data = crypt_algo.decode_message(key, encrypted)?;
let value: String = std::str::from_utf8(&data)
.change_context(errors::CryptoError::DecodingFailed)?
.to_string();
Ok((k, Self::new(value.into(), v.into_inner())))
})
.collect()
}
}
#[async_trait]
impl<
V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static,
S: masking::Strategy<serde_json::Value> + Send + Sync,
> TypeEncryption<serde_json::Value, V, S>
for crypto::Encryptable<Secret<serde_json::Value, S>>
{
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt_via_api(
state: &KeyManagerState,
masked_data: Secret<serde_json::Value, S>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::encrypt(masked_data, key, crypt_algo).await
} else {
let result: Result<
EncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/encrypt",
EncryptDataRequest::from((masked_data.clone(), identifier)),
)
.await;
match result {
Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))),
Err(err) => {
logger::error!("Encryption error {:?}", err);
metrics::ENCRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Encryption");
Self::encrypt(masked_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt_via_api(
state: &KeyManagerState,
encrypted_data: Encryption,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::decrypt(encrypted_data, key, crypt_algo).await
} else {
let result: Result<
DecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/decrypt",
TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)),
)
.await;
let decrypted = match result {
Ok(decrypted_data) => {
ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data))
}
Err(err) => {
logger::error!("Decryption error {:?}", err);
Err(err.change_context(errors::CryptoError::EncodingFailed))
}
};
match decrypted {
Ok(de) => Ok(de),
Err(_) => {
metrics::DECRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Decryption");
Self::decrypt(encrypted_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt(
masked_data: Secret<serde_json::Value, S>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]);
let data = serde_json::to_vec(&masked_data.peek())
.change_context(errors::CryptoError::DecodingFailed)?;
let encrypted_data = crypt_algo.encode_message(key, &data)?;
Ok(Self::new(masked_data, encrypted_data.into()))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt(
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]);
let encrypted = obtain_data_to_decrypt_locally(encrypted_data.into_inner())?;
let data = crypt_algo.decode_message(key, encrypted.clone())?;
let value: serde_json::Value = serde_json::from_slice(&data)
.change_context(errors::CryptoError::DecodingFailed)?;
Ok(Self::new(value.into(), encrypted))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt_via_api(
state: &KeyManagerState,
masked_data: FxHashMap<String, Secret<serde_json::Value, S>>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::batch_encrypt(masked_data, key, crypt_algo).await
} else {
let result: Result<
BatchEncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/encrypt",
BatchEncryptDataRequest::from((masked_data.clone(), identifier)),
)
.await;
match result {
Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))),
Err(err) => {
metrics::ENCRYPTION_API_FAILURES.add(1, &[]);
logger::error!("Encryption error {:?}", err);
logger::info!("Fall back to Application Encryption");
Self::batch_encrypt(masked_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt_via_api(
state: &KeyManagerState,
encrypted_data: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
} else {
let result: Result<
BatchDecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/decrypt",
TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)),
)
.await;
let decrypted = match result {
Ok(decrypted_data) => {
ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data))
}
Err(err) => {
logger::error!("Decryption error {:?}", err);
Err(err.change_context(errors::CryptoError::DecodingFailed))
}
};
match decrypted {
Ok(de) => Ok(de),
Err(_) => {
metrics::DECRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Decryption");
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt(
masked_data: FxHashMap<String, Secret<serde_json::Value, S>>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]);
masked_data
.into_iter()
.map(|(k, v)| {
let data = serde_json::to_vec(v.peek())
.change_context(errors::CryptoError::DecodingFailed)?;
Ok((
k,
Self::new(v, crypt_algo.encode_message(key, &data)?.into()),
))
})
.collect()
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt(
encrypted_data: FxHashMap<String, Encryption>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]);
encrypted_data
.into_iter()
.map(|(k, v)| {
let encrypted = obtain_data_to_decrypt_locally(v.clone().into_inner())?;
let data = crypt_algo.decode_message(key, encrypted)?;
let value: serde_json::Value = serde_json::from_slice(&data)
.change_context(errors::CryptoError::DecodingFailed)?;
Ok((k, Self::new(value.into(), v.into_inner())))
})
.collect()
}
}
impl<T> EncryptedJsonType<T>
where
T: std::fmt::Debug + Clone + serde::Serialize + serde::de::DeserializeOwned,
{
fn serialize_json_bytes(&self) -> CustomResult<Secret<Vec<u8>>, errors::CryptoError> {
common_utils::ext_traits::Encode::encode_to_vec(self.inner())
.change_context(errors::CryptoError::EncodingFailed)
.attach_printable("Failed to JSON serialize data before encryption")
.map(Secret::new)
}
fn deserialize_json_bytes<S>(
bytes: Secret<Vec<u8>>,
) -> CustomResult<Secret<Self, S>, errors::ParsingError>
where
S: masking::Strategy<Self>,
{
bytes
.peek()
.as_slice()
.parse_struct::<T>(std::any::type_name::<T>())
.map(|result| Secret::new(Self::from(result)))
.attach_printable("Failed to JSON deserialize data after decryption")
}
}
#[async_trait]
impl<
T: std::fmt::Debug + Clone + serde::Serialize + serde::de::DeserializeOwned + Send,
V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static,
S: masking::Strategy<EncryptedJsonType<T>> + Send + Sync,
> TypeEncryption<EncryptedJsonType<T>, V, S>
for crypto::Encryptable<Secret<EncryptedJsonType<T>, S>>
{
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt_via_api(
state: &KeyManagerState,
masked_data: Secret<EncryptedJsonType<T>, S>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
let data_bytes = EncryptedJsonType::serialize_json_bytes(masked_data.peek())?;
let result: crypto::Encryptable<Secret<Vec<u8>>> =
TypeEncryption::encrypt_via_api(state, data_bytes, identifier, key, crypt_algo)
.await?;
Ok(Self::new(masked_data, result.into_encrypted()))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt_via_api(
state: &KeyManagerState,
encrypted_data: Encryption,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
let result: crypto::Encryptable<Secret<Vec<u8>>> =
TypeEncryption::decrypt_via_api(state, encrypted_data, identifier, key, crypt_algo)
.await?;
result
.deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes)
.change_context(errors::CryptoError::DecodingFailed)
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt(
masked_data: Secret<EncryptedJsonType<T>, S>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
let data_bytes = EncryptedJsonType::serialize_json_bytes(masked_data.peek())?;
let result: crypto::Encryptable<Secret<Vec<u8>>> =
TypeEncryption::encrypt(data_bytes, key, crypt_algo).await?;
Ok(Self::new(masked_data, result.into_encrypted()))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt(
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
let result: crypto::Encryptable<Secret<Vec<u8>>> =
TypeEncryption::decrypt(encrypted_data, key, crypt_algo).await?;
result
.deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes)
.change_context(errors::CryptoError::DecodingFailed)
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt_via_api(
state: &KeyManagerState,
masked_data: FxHashMap<String, Secret<EncryptedJsonType<T>, S>>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
let hashmap_capacity = masked_data.len();
let data_bytes = masked_data.iter().try_fold(
FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()),
|mut map, (key, value)| {
let value_bytes = EncryptedJsonType::serialize_json_bytes(value.peek())?;
map.insert(key.to_owned(), value_bytes);
Ok::<_, error_stack::Report<errors::CryptoError>>(map)
},
)?;
let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> =
TypeEncryption::batch_encrypt_via_api(
state, data_bytes, identifier, key, crypt_algo,
)
.await?;
let result_hashmap = result.into_iter().try_fold(
FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()),
|mut map, (key, value)| {
let original_value = masked_data
.get(&key)
.ok_or(errors::CryptoError::EncodingFailed)
.attach_printable_lazy(|| {
format!("Failed to find {key} in input hashmap")
})?;
map.insert(
key,
Self::new(original_value.clone(), value.into_encrypted()),
);
Ok::<_, error_stack::Report<errors::CryptoError>>(map)
},
)?;
Ok(result_hashmap)
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt_via_api(
state: &KeyManagerState,
encrypted_data: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> =
TypeEncryption::batch_decrypt_via_api(
state,
encrypted_data,
identifier,
key,
crypt_algo,
)
.await?;
let hashmap_capacity = result.len();
let result_hashmap = result.into_iter().try_fold(
FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()),
|mut map, (key, value)| {
let deserialized_value = value
.deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes)
.change_context(errors::CryptoError::DecodingFailed)?;
map.insert(key, deserialized_value);
Ok::<_, error_stack::Report<errors::CryptoError>>(map)
},
)?;
Ok(result_hashmap)
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt(
masked_data: FxHashMap<String, Secret<EncryptedJsonType<T>, S>>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
let hashmap_capacity = masked_data.len();
let data_bytes = masked_data.iter().try_fold(
FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()),
|mut map, (key, value)| {
let value_bytes = EncryptedJsonType::serialize_json_bytes(value.peek())?;
map.insert(key.to_owned(), value_bytes);
Ok::<_, error_stack::Report<errors::CryptoError>>(map)
},
)?;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/hyperswitch_domain_models/src/tokenization.rs | crates/hyperswitch_domain_models/src/tokenization.rs | use common_utils::{
self, date_time,
errors::{CustomResult, ValidationError},
types::keymanager,
};
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Tokenization {
pub id: common_utils::id_type::GlobalTokenId,
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: common_utils::id_type::GlobalCustomerId,
pub locker_id: String,
pub created_at: PrimitiveDateTime,
pub updated_at: PrimitiveDateTime,
pub flag: common_enums::TokenizationFlag,
pub version: common_enums::ApiVersion,
}
impl Tokenization {
pub fn is_disabled(&self) -> bool {
self.flag == common_enums::TokenizationFlag::Disabled
}
}
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TokenizationNew {
pub id: common_utils::id_type::GlobalTokenId,
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: common_utils::id_type::GlobalCustomerId,
pub locker_id: String,
pub flag: common_enums::TokenizationFlag,
pub version: common_enums::ApiVersion,
}
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TokenizationResponse {
pub token: String,
pub created_at: PrimitiveDateTime,
pub flag: common_enums::TokenizationFlag,
}
impl From<Tokenization> for TokenizationResponse {
fn from(value: Tokenization) -> Self {
Self {
token: value.id.get_string_repr().to_string(),
created_at: value.created_at,
flag: value.flag,
}
}
}
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TokenizationUpdate {
DeleteTokenizationRecordUpdate {
flag: Option<common_enums::enums::TokenizationFlag>,
},
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for Tokenization {
type DstType = diesel_models::tokenization::Tokenization;
type NewDstType = diesel_models::tokenization::Tokenization;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::tokenization::Tokenization {
id: self.id,
merchant_id: self.merchant_id,
customer_id: self.customer_id,
locker_id: self.locker_id,
created_at: self.created_at,
updated_at: self.updated_at,
version: self.version,
flag: self.flag,
})
}
async fn convert_back(
_state: &keymanager::KeyManagerState,
item: Self::DstType,
_key: &Secret<Vec<u8>>,
_key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError> {
Ok(Self {
id: item.id,
merchant_id: item.merchant_id,
customer_id: item.customer_id,
locker_id: item.locker_id,
created_at: item.created_at,
updated_at: item.updated_at,
flag: item.flag,
version: item.version,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::tokenization::Tokenization {
id: self.id,
merchant_id: self.merchant_id,
customer_id: self.customer_id,
locker_id: self.locker_id,
created_at: self.created_at,
updated_at: self.updated_at,
version: self.version,
flag: self.flag,
})
}
}
impl From<TokenizationUpdate> for diesel_models::tokenization::TokenizationUpdateInternal {
fn from(value: TokenizationUpdate) -> Self {
let now = date_time::now();
match value {
TokenizationUpdate::DeleteTokenizationRecordUpdate { flag } => Self {
updated_at: now,
flag,
},
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.