text
stringlengths 81
477k
| file_path
stringlengths 22
92
| module
stringlengths 13
87
| token_count
int64 24
94.8k
| has_source_code
bool 1
class |
|---|---|---|---|---|
// File: crates/router/src/compatibility/stripe/setup_intents/types.rs
// Module: router::src::compatibility::stripe::setup_intents::types
use std::str::FromStr;
use api_models::payments;
use common_utils::{date_time, ext_traits::StringExt, id_type, pii as secret};
use error_stack::ResultExt;
use router_env::logger;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
compatibility::stripe::{
payment_intents::types as payment_intent, refunds::types as stripe_refunds,
},
consts,
core::errors,
pii::{self, PeekInterface},
types::{
api::{self as api_types, admin, enums as api_enums},
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::OptionExt,
};
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
pub struct StripeBillingDetails {
pub address: Option<payments::AddressDetails>,
pub email: Option<pii::Email>,
pub name: Option<String>,
pub phone: Option<pii::Secret<String>>,
}
impl From<StripeBillingDetails> for payments::Address {
fn from(details: StripeBillingDetails) -> Self {
Self {
address: details.address,
phone: Some(payments::PhoneDetails {
number: details.phone,
country_code: None,
}),
email: details.email,
}
}
}
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
pub struct StripeCard {
pub number: cards::CardNumber,
pub exp_month: pii::Secret<String>,
pub exp_year: pii::Secret<String>,
pub cvc: pii::Secret<String>,
}
// ApplePay wallet param is not available in stripe Docs
#[derive(Serialize, PartialEq, Eq, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum StripeWallet {
ApplePay(payments::ApplePayWalletData),
}
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum StripePaymentMethodType {
#[default]
Card,
Wallet,
}
impl From<StripePaymentMethodType> for api_enums::PaymentMethod {
fn from(item: StripePaymentMethodType) -> Self {
match item {
StripePaymentMethodType::Card => Self::Card,
StripePaymentMethodType::Wallet => Self::Wallet,
}
}
}
#[derive(Default, PartialEq, Eq, Deserialize, Clone)]
pub struct StripePaymentMethodData {
#[serde(rename = "type")]
pub stype: StripePaymentMethodType,
pub billing_details: Option<StripeBillingDetails>,
#[serde(flatten)]
pub payment_method_details: Option<StripePaymentMethodDetails>, // enum
pub metadata: Option<Value>,
}
#[derive(PartialEq, Eq, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum StripePaymentMethodDetails {
Card(StripeCard),
Wallet(StripeWallet),
}
impl From<StripeCard> for payments::Card {
fn from(card: StripeCard) -> Self {
Self {
card_number: card.number,
card_exp_month: card.exp_month,
card_exp_year: card.exp_year,
card_holder_name: Some(masking::Secret::new("stripe_cust".to_owned())),
card_cvc: card.cvc,
card_issuer: None,
card_network: None,
bank_code: None,
card_issuing_country: None,
card_type: None,
nick_name: None,
}
}
}
impl From<StripeWallet> for payments::WalletData {
fn from(wallet: StripeWallet) -> Self {
match wallet {
StripeWallet::ApplePay(data) => Self::ApplePay(data),
}
}
}
impl From<StripePaymentMethodDetails> for payments::PaymentMethodData {
fn from(item: StripePaymentMethodDetails) -> Self {
match item {
StripePaymentMethodDetails::Card(card) => Self::Card(payments::Card::from(card)),
StripePaymentMethodDetails::Wallet(wallet) => {
Self::Wallet(payments::WalletData::from(wallet))
}
}
}
}
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
pub struct Shipping {
pub address: Option<payments::AddressDetails>,
pub name: Option<String>,
pub carrier: Option<String>,
pub phone: Option<pii::Secret<String>>,
pub tracking_number: Option<pii::Secret<String>>,
}
impl From<Shipping> for payments::Address {
fn from(details: Shipping) -> Self {
Self {
address: details.address,
phone: Some(payments::PhoneDetails {
number: details.phone,
country_code: None,
}),
email: None,
}
}
}
#[derive(Default, Deserialize, Clone)]
pub struct StripeSetupIntentRequest {
pub confirm: Option<bool>,
pub customer: Option<id_type::CustomerId>,
pub connector: Option<Vec<api_enums::RoutableConnectors>>,
pub description: Option<String>,
pub currency: Option<String>,
pub payment_method_data: Option<StripePaymentMethodData>,
pub receipt_email: Option<pii::Email>,
pub return_url: Option<url::Url>,
pub setup_future_usage: Option<api_enums::FutureUsage>,
pub shipping: Option<Shipping>,
pub billing_details: Option<StripeBillingDetails>,
pub statement_descriptor: Option<String>,
pub statement_descriptor_suffix: Option<String>,
pub metadata: Option<secret::SecretSerdeValue>,
pub client_secret: Option<pii::Secret<String>>,
pub payment_method_options: Option<payment_intent::StripePaymentMethodOptions>,
pub payment_method: Option<String>,
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
pub receipt_ipaddress: Option<String>,
pub user_agent: Option<String>,
pub mandate_data: Option<payment_intent::MandateData>,
pub connector_metadata: Option<payments::ConnectorMetadata>,
}
impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(item: StripeSetupIntentRequest) -> errors::RouterResult<Self> {
let routable_connector: Option<api_enums::RoutableConnectors> =
item.connector.and_then(|v| v.into_iter().next());
let routing = routable_connector
.map(|connector| {
api_models::routing::StaticRoutingAlgorithm::Single(Box::new(
api_models::routing::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector,
merchant_connector_id: None,
},
))
})
.map(|r| {
serde_json::to_value(r)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("converting to routing failed")
})
.transpose()?;
let ip_address = item
.receipt_ipaddress
.map(|ip| std::net::IpAddr::from_str(ip.as_str()))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "receipt_ipaddress".to_string(),
expected_format: "127.0.0.1".to_string(),
})?;
let metadata_object = item
.metadata
.clone()
.parse_value("metadata")
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "metadata mapping failed",
})?;
let request = Ok(Self {
amount: Some(api_types::Amount::Zero),
capture_method: None,
amount_to_capture: None,
confirm: item.confirm,
customer_id: item.customer,
currency: item
.currency
.as_ref()
.map(|c| c.to_uppercase().parse_enum("currency"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "currency",
})?,
email: item.receipt_email,
name: item
.billing_details
.as_ref()
.and_then(|b| b.name.as_ref().map(|x| masking::Secret::new(x.to_owned()))),
phone: item.shipping.as_ref().and_then(|s| s.phone.clone()),
description: item.description,
return_url: item.return_url,
payment_method_data: item.payment_method_data.as_ref().and_then(|pmd| {
pmd.payment_method_details
.as_ref()
.map(|spmd| payments::PaymentMethodDataRequest {
payment_method_data: Some(payments::PaymentMethodData::from(
spmd.to_owned(),
)),
billing: pmd.billing_details.clone().map(payments::Address::from),
})
}),
payment_method: item
.payment_method_data
.as_ref()
.map(|pmd| api_enums::PaymentMethod::from(pmd.stype.to_owned())),
shipping: item
.shipping
.as_ref()
.map(|s| payments::Address::from(s.to_owned())),
billing: item
.billing_details
.as_ref()
.map(|b| payments::Address::from(b.to_owned())),
statement_descriptor_name: item.statement_descriptor,
statement_descriptor_suffix: item.statement_descriptor_suffix,
metadata: metadata_object,
client_secret: item.client_secret.map(|s| s.peek().clone()),
setup_future_usage: item.setup_future_usage,
merchant_connector_details: item.merchant_connector_details,
routing,
authentication_type: match item.payment_method_options {
Some(pmo) => {
let payment_intent::StripePaymentMethodOptions::Card {
request_three_d_secure,
}: payment_intent::StripePaymentMethodOptions = pmo;
Some(api_enums::AuthenticationType::foreign_from(
request_three_d_secure,
))
}
None => None,
},
mandate_data: ForeignTryFrom::foreign_try_from((
item.mandate_data,
item.currency.to_owned(),
))?,
browser_info: Some(
serde_json::to_value(crate::types::BrowserInformation {
ip_address,
user_agent: item.user_agent,
..Default::default()
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("convert to browser info failed")?,
),
connector_metadata: item.connector_metadata,
..Default::default()
});
request
}
}
#[derive(Clone, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StripeSetupStatus {
Succeeded,
Canceled,
#[default]
Processing,
RequiresAction,
RequiresPaymentMethod,
RequiresConfirmation,
}
impl From<api_enums::IntentStatus> for StripeSetupStatus {
fn from(item: api_enums::IntentStatus) -> Self {
match item {
api_enums::IntentStatus::Succeeded | api_enums::IntentStatus::PartiallyCaptured => {
Self::Succeeded
}
api_enums::IntentStatus::Failed | api_enums::IntentStatus::Expired => Self::Canceled,
api_enums::IntentStatus::Processing
| api_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => Self::Processing,
api_enums::IntentStatus::RequiresCustomerAction => Self::RequiresAction,
api_enums::IntentStatus::RequiresMerchantAction
| api_enums::IntentStatus::Conflicted => Self::RequiresAction,
api_enums::IntentStatus::RequiresPaymentMethod => Self::RequiresPaymentMethod,
api_enums::IntentStatus::RequiresConfirmation => Self::RequiresConfirmation,
api_enums::IntentStatus::RequiresCapture
| api_enums::IntentStatus::PartiallyCapturedAndCapturable => {
logger::error!("Invalid status change");
Self::Canceled
}
api_enums::IntentStatus::Cancelled | api_enums::IntentStatus::CancelledPostCapture => {
Self::Canceled
}
}
}
}
#[derive(Debug, Serialize, Deserialize, Copy, Clone, strum::Display)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CancellationReason {
Duplicate,
Fraudulent,
RequestedByCustomer,
Abandoned,
}
#[derive(Debug, Deserialize, Serialize, Copy, Clone)]
pub struct StripePaymentCancelRequest {
cancellation_reason: Option<CancellationReason>,
}
impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest {
fn from(item: StripePaymentCancelRequest) -> Self {
Self {
cancellation_reason: item.cancellation_reason.map(|c| c.to_string()),
..Self::default()
}
}
}
#[derive(Default, Eq, PartialEq, Serialize)]
pub struct RedirectUrl {
pub return_url: Option<String>,
pub url: Option<String>,
}
#[derive(Eq, PartialEq, serde::Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum StripeNextAction {
RedirectToUrl {
redirect_to_url: RedirectUrl,
},
DisplayBankTransferInformation {
bank_transfer_steps_and_charges_details: payments::BankTransferNextStepsData,
},
ThirdPartySdkSessionToken {
session_token: Option<payments::SessionToken>,
},
QrCodeInformation {
image_data_url: Option<url::Url>,
display_to_timestamp: Option<i64>,
qr_code_url: Option<url::Url>,
border_color: Option<String>,
display_text: Option<String>,
},
FetchQrCodeInformation {
qr_code_fetch_url: url::Url,
},
DisplayVoucherInformation {
voucher_details: payments::VoucherNextStepData,
},
WaitScreenInformation {
display_from_timestamp: i128,
display_to_timestamp: Option<i128>,
poll_config: Option<payments::PollConfig>,
},
InvokeSdkClient {
next_action_data: payments::SdkNextActionData,
},
CollectOtp {
consent_data_required: payments::MobilePaymentConsent,
},
InvokeHiddenIframe {
iframe_data: payments::IframeData,
},
SdkUpiIntentInformation {
sdk_uri: url::Url,
},
}
pub(crate) fn into_stripe_next_action(
next_action: Option<payments::NextActionData>,
return_url: Option<String>,
) -> Option<StripeNextAction> {
next_action.map(|next_action_data| match next_action_data {
payments::NextActionData::RedirectToUrl { redirect_to_url } => {
StripeNextAction::RedirectToUrl {
redirect_to_url: RedirectUrl {
return_url,
url: Some(redirect_to_url),
},
}
}
payments::NextActionData::RedirectInsidePopup { popup_url, .. } => {
StripeNextAction::RedirectToUrl {
redirect_to_url: RedirectUrl {
return_url,
url: Some(popup_url),
},
}
}
payments::NextActionData::DisplayBankTransferInformation {
bank_transfer_steps_and_charges_details,
} => StripeNextAction::DisplayBankTransferInformation {
bank_transfer_steps_and_charges_details,
},
payments::NextActionData::ThirdPartySdkSessionToken { session_token } => {
StripeNextAction::ThirdPartySdkSessionToken { session_token }
}
payments::NextActionData::QrCodeInformation {
image_data_url,
display_to_timestamp,
qr_code_url,
display_text,
border_color,
} => StripeNextAction::QrCodeInformation {
image_data_url,
display_to_timestamp,
qr_code_url,
display_text,
border_color,
},
payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url } => {
StripeNextAction::FetchQrCodeInformation { qr_code_fetch_url }
}
payments::NextActionData::DisplayVoucherInformation { voucher_details } => {
StripeNextAction::DisplayVoucherInformation { voucher_details }
}
payments::NextActionData::WaitScreenInformation {
display_from_timestamp,
display_to_timestamp,
poll_config: _,
} => StripeNextAction::WaitScreenInformation {
display_from_timestamp,
display_to_timestamp,
poll_config: None,
},
payments::NextActionData::ThreeDsInvoke { .. } => StripeNextAction::RedirectToUrl {
redirect_to_url: RedirectUrl {
return_url: None,
url: None,
},
},
payments::NextActionData::InvokeSdkClient { next_action_data } => {
StripeNextAction::InvokeSdkClient { next_action_data }
}
payments::NextActionData::CollectOtp {
consent_data_required,
} => StripeNextAction::CollectOtp {
consent_data_required,
},
payments::NextActionData::InvokeHiddenIframe { iframe_data } => {
StripeNextAction::InvokeHiddenIframe { iframe_data }
}
payments::NextActionData::SdkUpiIntentInformation { sdk_uri } => {
StripeNextAction::SdkUpiIntentInformation { sdk_uri }
}
})
}
#[derive(Default, Eq, PartialEq, Serialize)]
pub struct StripeSetupIntentResponse {
pub id: id_type::PaymentId,
pub object: String,
pub status: StripeSetupStatus,
pub client_secret: Option<masking::Secret<String>>,
pub metadata: Option<Value>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub created: Option<time::PrimitiveDateTime>,
pub customer: Option<id_type::CustomerId>,
pub refunds: Option<Vec<stripe_refunds::StripeRefundResponse>>,
pub mandate_id: Option<String>,
pub next_action: Option<StripeNextAction>,
pub last_payment_error: Option<LastPaymentError>,
pub charges: payment_intent::Charges,
pub connector_transaction_id: Option<String>,
}
#[derive(Default, Eq, PartialEq, Serialize)]
pub struct LastPaymentError {
charge: Option<String>,
code: Option<String>,
decline_code: Option<String>,
message: String,
param: Option<String>,
payment_method: StripePaymentMethod,
#[serde(rename = "type")]
error_type: String,
}
#[derive(Default, Eq, PartialEq, Serialize)]
pub struct StripePaymentMethod {
#[serde(rename = "id")]
payment_method_id: String,
object: &'static str,
card: Option<StripeCard>,
created: u64,
#[serde(rename = "type")]
method_type: String,
livemode: bool,
}
impl From<payments::PaymentsResponse> for StripeSetupIntentResponse {
fn from(resp: payments::PaymentsResponse) -> Self {
Self {
object: "setup_intent".to_owned(),
status: StripeSetupStatus::from(resp.status),
client_secret: resp.client_secret,
charges: payment_intent::Charges::new(),
created: resp.created,
customer: resp.customer_id,
metadata: resp.metadata,
id: resp.payment_id,
refunds: resp
.refunds
.map(|a| a.into_iter().map(Into::into).collect()),
mandate_id: resp.mandate_id,
next_action: into_stripe_next_action(resp.next_action, resp.return_url),
last_payment_error: resp.error_code.map(|code| -> LastPaymentError {
LastPaymentError {
charge: None,
code: Some(code.to_owned()),
decline_code: None,
message: resp
.error_message
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
param: None,
payment_method: StripePaymentMethod {
payment_method_id: "place_holder_id".to_string(),
object: "payment_method",
card: None,
created: u64::try_from(date_time::now().assume_utc().unix_timestamp())
.unwrap_or_default(),
method_type: "card".to_string(),
livemode: false,
},
error_type: code,
}
}),
connector_transaction_id: resp.connector_transaction_id,
}
}
}
#[derive(Clone, Debug, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StripePaymentListConstraints {
pub customer: Option<id_type::CustomerId>,
pub starting_after: Option<id_type::PaymentId>,
pub ending_before: Option<id_type::PaymentId>,
#[serde(default = "default_limit")]
pub limit: u32,
pub created: Option<i64>,
#[serde(rename = "created[lt]")]
pub created_lt: Option<i64>,
#[serde(rename = "created[gt]")]
pub created_gt: Option<i64>,
#[serde(rename = "created[lte]")]
pub created_lte: Option<i64>,
#[serde(rename = "created[gte]")]
pub created_gte: Option<i64>,
}
fn default_limit() -> u32 {
10
}
impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(item: StripePaymentListConstraints) -> Result<Self, Self::Error> {
Ok(Self {
customer_id: item.customer,
starting_after: item.starting_after,
ending_before: item.ending_before,
limit: item.limit,
created: from_timestamp_to_datetime(item.created)?,
created_lt: from_timestamp_to_datetime(item.created_lt)?,
created_gt: from_timestamp_to_datetime(item.created_gt)?,
created_lte: from_timestamp_to_datetime(item.created_lte)?,
created_gte: from_timestamp_to_datetime(item.created_gte)?,
})
}
}
#[inline]
fn from_timestamp_to_datetime(
time: Option<i64>,
) -> Result<Option<time::PrimitiveDateTime>, errors::ApiErrorResponse> {
if let Some(time) = time {
let time = time::OffsetDateTime::from_unix_timestamp(time).map_err(|err| {
logger::error!("Error: from_unix_timestamp: {}", err);
errors::ApiErrorResponse::InvalidRequestData {
message: "Error while converting timestamp".to_string(),
}
})?;
Ok(Some(time::PrimitiveDateTime::new(time.date(), time.time())))
} else {
Ok(None)
}
}
|
crates/router/src/compatibility/stripe/setup_intents/types.rs
|
router::src::compatibility::stripe::setup_intents::types
| 4,786
| true
|
// File: crates/router/src/compatibility/stripe/refunds/types.rs
// Module: router::src::compatibility::stripe::refunds::types
use std::{convert::From, default::Default};
use common_utils::pii;
use serde::{Deserialize, Serialize};
use crate::types::api::{admin, refunds};
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)]
pub struct StripeCreateRefundRequest {
pub refund_id: Option<String>,
pub amount: Option<i64>,
pub payment_intent: common_utils::id_type::PaymentId,
pub reason: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct StripeUpdateRefundRequest {
#[serde(skip)]
pub refund_id: String,
pub metadata: Option<pii::SecretSerdeValue>,
}
#[derive(Clone, Serialize, PartialEq, Eq, Debug)]
pub struct StripeRefundResponse {
pub id: String,
pub amount: i64,
pub currency: String,
pub payment_intent: common_utils::id_type::PaymentId,
pub status: StripeRefundStatus,
pub created: Option<i64>,
pub metadata: pii::SecretSerdeValue,
}
#[derive(Clone, Serialize, Deserialize, Eq, PartialEq, Debug)]
#[serde(rename_all = "snake_case")]
pub enum StripeRefundStatus {
Succeeded,
Failed,
Pending,
RequiresAction,
}
impl From<StripeCreateRefundRequest> for refunds::RefundRequest {
fn from(req: StripeCreateRefundRequest) -> Self {
Self {
refund_id: req.refund_id,
amount: req.amount.map(common_utils::types::MinorUnit::new),
payment_id: req.payment_intent,
reason: req.reason,
refund_type: Some(refunds::RefundType::Instant),
metadata: req.metadata,
merchant_connector_details: req.merchant_connector_details,
..Default::default()
}
}
}
impl From<StripeUpdateRefundRequest> for refunds::RefundUpdateRequest {
fn from(req: StripeUpdateRefundRequest) -> Self {
Self {
refund_id: req.refund_id,
metadata: req.metadata,
reason: None,
}
}
}
impl From<refunds::RefundStatus> for StripeRefundStatus {
fn from(status: refunds::RefundStatus) -> Self {
match status {
refunds::RefundStatus::Succeeded => Self::Succeeded,
refunds::RefundStatus::Failed => Self::Failed,
refunds::RefundStatus::Pending => Self::Pending,
refunds::RefundStatus::Review => Self::RequiresAction,
}
}
}
impl From<refunds::RefundResponse> for StripeRefundResponse {
fn from(res: refunds::RefundResponse) -> Self {
Self {
id: res.refund_id,
amount: res.amount.get_amount_as_i64(),
currency: res.currency.to_ascii_lowercase(),
payment_intent: res.payment_id,
status: res.status.into(),
created: res.created_at.map(|t| t.assume_utc().unix_timestamp()),
metadata: res
.metadata
.unwrap_or_else(|| masking::Secret::new(serde_json::json!({}))),
}
}
}
|
crates/router/src/compatibility/stripe/refunds/types.rs
|
router::src::compatibility::stripe::refunds::types
| 729
| true
|
// File: crates/router/src/types/payment_methods.rs
// Module: router::src::types::payment_methods
use std::fmt::Debug;
use api_models::enums as api_enums;
#[cfg(feature = "v1")]
use cards::CardNumber;
#[cfg(feature = "v2")]
use cards::{CardNumber, NetworkToken};
#[cfg(feature = "v2")]
use common_types::primitive_wrappers;
#[cfg(feature = "v2")]
use common_utils::generate_id;
use common_utils::id_type;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payment_method_data::NetworkTokenDetails;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::types::api;
#[cfg(feature = "v2")]
use crate::{
consts,
types::{domain, storage},
};
#[cfg(feature = "v2")]
pub trait VaultingInterface {
fn get_vaulting_request_url() -> &'static str;
fn get_vaulting_flow_name() -> &'static str;
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultFingerprintRequest {
pub data: String,
pub key: String,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultFingerprintResponse {
pub fingerprint_id: String,
}
#[cfg(any(feature = "v2", feature = "tokenization_v2"))]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AddVaultRequest<D> {
pub entity_id: id_type::GlobalCustomerId,
pub vault_id: domain::VaultId,
pub data: D,
pub ttl: i64,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AddVaultResponse {
#[cfg(feature = "v2")]
pub entity_id: Option<id_type::GlobalCustomerId>,
#[cfg(feature = "v1")]
pub entity_id: Option<id_type::CustomerId>,
#[cfg(feature = "v2")]
pub vault_id: domain::VaultId,
#[cfg(feature = "v1")]
pub vault_id: String,
pub fingerprint_id: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AddVault;
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct GetVaultFingerprint;
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultRetrieve;
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultDelete;
#[cfg(feature = "v2")]
impl VaultingInterface for AddVault {
fn get_vaulting_request_url() -> &'static str {
consts::ADD_VAULT_REQUEST_URL
}
fn get_vaulting_flow_name() -> &'static str {
consts::VAULT_ADD_FLOW_TYPE
}
}
#[cfg(feature = "v2")]
impl VaultingInterface for GetVaultFingerprint {
fn get_vaulting_request_url() -> &'static str {
consts::VAULT_FINGERPRINT_REQUEST_URL
}
fn get_vaulting_flow_name() -> &'static str {
consts::VAULT_GET_FINGERPRINT_FLOW_TYPE
}
}
#[cfg(feature = "v2")]
impl VaultingInterface for VaultRetrieve {
fn get_vaulting_request_url() -> &'static str {
consts::VAULT_RETRIEVE_REQUEST_URL
}
fn get_vaulting_flow_name() -> &'static str {
consts::VAULT_RETRIEVE_FLOW_TYPE
}
}
#[cfg(feature = "v2")]
impl VaultingInterface for VaultDelete {
fn get_vaulting_request_url() -> &'static str {
consts::VAULT_DELETE_REQUEST_URL
}
fn get_vaulting_flow_name() -> &'static str {
consts::VAULT_DELETE_FLOW_TYPE
}
}
#[cfg(feature = "v2")]
pub struct SavedPMLPaymentsInfo {
pub payment_intent: storage::PaymentIntent,
pub profile: domain::Profile,
pub collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>,
pub off_session_payment_flag: bool,
pub is_connector_agnostic_mit_enabled: bool,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultRetrieveRequest {
pub entity_id: id_type::GlobalCustomerId,
pub vault_id: domain::VaultId,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultRetrieveResponse {
pub data: domain::PaymentMethodVaultingData,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultDeleteRequest {
pub entity_id: id_type::GlobalCustomerId,
pub vault_id: domain::VaultId,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultDeleteResponse {
pub entity_id: id_type::GlobalCustomerId,
pub vault_id: domain::VaultId,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardData {
pub card_number: CardNumber,
pub exp_month: Secret<String>,
pub exp_year: Secret<String>,
pub card_security_code: Option<Secret<String>>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardData {
pub card_number: CardNumber,
pub exp_month: Secret<String>,
pub exp_year: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card_security_code: Option<Secret<String>>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderData {
pub consent_id: String,
pub customer_id: id_type::CustomerId,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderData {
pub consent_id: String,
pub customer_id: id_type::GlobalCustomerId,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiPayload {
pub service: String,
pub card_data: Secret<String>, //encrypted card data
pub order_data: OrderData,
pub key_id: String,
pub should_send_token: bool,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct CardNetworkTokenResponse {
pub payload: Secret<String>, //encrypted payload
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardNetworkTokenResponsePayload {
pub card_brand: api_enums::CardNetwork,
pub card_fingerprint: Option<Secret<String>>,
pub card_reference: String,
pub correlation_id: String,
pub customer_id: String,
pub par: String,
pub token: CardNumber,
pub token_expiry_month: Secret<String>,
pub token_expiry_year: Secret<String>,
pub token_isin: String,
pub token_last_four: String,
pub token_status: String,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GenerateNetworkTokenResponsePayload {
pub card_brand: api_enums::CardNetwork,
pub card_fingerprint: Option<Secret<String>>,
pub card_reference: String,
pub correlation_id: String,
pub customer_id: String,
pub par: String,
pub token: NetworkToken,
pub token_expiry_month: Secret<String>,
pub token_expiry_year: Secret<String>,
pub token_isin: String,
pub token_last_four: String,
pub token_status: String,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize)]
pub struct GetCardToken {
pub card_reference: String,
pub customer_id: id_type::CustomerId,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize)]
pub struct GetCardToken {
pub card_reference: String,
pub customer_id: id_type::GlobalCustomerId,
}
#[cfg(feature = "v1")]
#[derive(Debug, Deserialize)]
pub struct AuthenticationDetails {
pub cryptogram: Secret<String>,
pub token: CardNumber, //network token
}
#[cfg(feature = "v2")]
#[derive(Debug, Deserialize)]
pub struct AuthenticationDetails {
pub cryptogram: Secret<String>,
pub token: NetworkToken, //network token
}
#[derive(Debug, Serialize, Deserialize)]
pub struct TokenDetails {
pub exp_month: Secret<String>,
pub exp_year: Secret<String>,
}
#[derive(Debug, Deserialize)]
pub struct TokenResponse {
pub authentication_details: AuthenticationDetails,
pub network: api_enums::CardNetwork,
pub token_details: TokenDetails,
pub eci: Option<String>,
pub card_type: Option<String>,
pub issuer: Option<String>,
pub nickname: Option<Secret<String>>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
pub struct DeleteCardToken {
pub card_reference: String, //network token requestor ref id
pub customer_id: id_type::CustomerId,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize, Deserialize)]
pub struct DeleteCardToken {
pub card_reference: String, //network token requestor ref id
pub customer_id: id_type::GlobalCustomerId,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum DeleteNetworkTokenStatus {
Success,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct NetworkTokenErrorInfo {
pub code: String,
pub developer_message: String,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct NetworkTokenErrorResponse {
pub error_message: String,
pub error_info: NetworkTokenErrorInfo,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct DeleteNetworkTokenResponse {
pub status: DeleteNetworkTokenStatus,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckTokenStatus {
pub card_reference: String,
pub customer_id: id_type::CustomerId,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckTokenStatus {
pub card_reference: String,
pub customer_id: id_type::GlobalCustomerId,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum TokenStatus {
Active,
Suspended,
Deactivated,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckTokenStatusResponse {
pub token_status: TokenStatus,
pub token_expiry_month: Secret<String>,
pub token_expiry_year: Secret<String>,
pub card_last_4: String,
pub card_expiry: String,
pub token_last_4: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NetworkTokenRequestorData {
pub card_reference: String,
pub customer_id: String,
pub expiry_year: Secret<String>,
pub expiry_month: Secret<String>,
}
impl NetworkTokenRequestorData {
pub fn is_update_required(
&self,
data_stored_in_vault: api::payment_methods::CardDetailFromLocker,
) -> bool {
//if the expiry year and month in the vault are not the same as the ones in the requestor data,
//then we need to update the vault data with the updated expiry year and month.
!((data_stored_in_vault.expiry_year.unwrap_or_default() == self.expiry_year)
&& (data_stored_in_vault.expiry_month.unwrap_or_default() == self.expiry_month))
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NetworkTokenMetaDataUpdateBody {
pub token: NetworkTokenRequestorData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PanMetadataUpdateBody {
pub card: NetworkTokenRequestorData,
}
|
crates/router/src/types/payment_methods.rs
|
router::src::types::payment_methods
| 2,611
| true
|
// File: crates/router/src/types/fraud_check.rs
// Module: router::src::types::fraud_check
pub use hyperswitch_domain_models::{
router_request_types::fraud_check::{
FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData,
FraudCheckSaleData, FraudCheckTransactionData, RefundMethod,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
use crate::{
services,
types::{api, ErrorResponse, RouterData},
};
pub type FrmSaleRouterData = RouterData<api::Sale, FraudCheckSaleData, FraudCheckResponseData>;
pub type FrmSaleType =
dyn services::ConnectorIntegration<api::Sale, FraudCheckSaleData, FraudCheckResponseData>;
#[derive(Debug, Clone)]
pub struct FrmRouterData {
pub merchant_id: common_utils::id_type::MerchantId,
pub connector: String,
// TODO: change this to PaymentId type
pub payment_id: String,
pub attempt_id: String,
pub request: FrmRequest,
pub response: FrmResponse,
}
#[derive(Debug, Clone)]
pub enum FrmRequest {
Sale(FraudCheckSaleData),
Checkout(Box<FraudCheckCheckoutData>),
Transaction(FraudCheckTransactionData),
Fulfillment(FraudCheckFulfillmentData),
RecordReturn(FraudCheckRecordReturnData),
}
#[derive(Debug, Clone)]
pub enum FrmResponse {
Sale(Result<FraudCheckResponseData, ErrorResponse>),
Checkout(Result<FraudCheckResponseData, ErrorResponse>),
Transaction(Result<FraudCheckResponseData, ErrorResponse>),
Fulfillment(Result<FraudCheckResponseData, ErrorResponse>),
RecordReturn(Result<FraudCheckResponseData, ErrorResponse>),
}
pub type FrmCheckoutRouterData =
RouterData<api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>;
pub type FrmCheckoutType = dyn services::ConnectorIntegration<
api::Checkout,
FraudCheckCheckoutData,
FraudCheckResponseData,
>;
pub type FrmTransactionRouterData =
RouterData<api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>;
pub type FrmTransactionType = dyn services::ConnectorIntegration<
api::Transaction,
FraudCheckTransactionData,
FraudCheckResponseData,
>;
pub type FrmFulfillmentRouterData =
RouterData<api::Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>;
pub type FrmFulfillmentType = dyn services::ConnectorIntegration<
api::Fulfillment,
FraudCheckFulfillmentData,
FraudCheckResponseData,
>;
pub type FrmRecordReturnRouterData =
RouterData<api::RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>;
pub type FrmRecordReturnType = dyn services::ConnectorIntegration<
api::RecordReturn,
FraudCheckRecordReturnData,
FraudCheckResponseData,
>;
|
crates/router/src/types/fraud_check.rs
|
router::src::types::fraud_check
| 605
| true
|
// File: crates/router/src/types/connector_transformers.rs
// Module: router::src::types::connector_transformers
use api_models::enums as api_enums;
use super::ForeignTryFrom;
impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
type Error = error_stack::Report<common_utils::errors::ValidationError>;
fn foreign_try_from(from: api_enums::Connector) -> Result<Self, Self::Error> {
Ok(match from {
api_enums::Connector::Aci => Self::Aci,
api_enums::Connector::Adyen => Self::Adyen,
api_enums::Connector::Affirm => Self::Affirm,
api_enums::Connector::Adyenplatform => Self::Adyenplatform,
api_enums::Connector::Airwallex => Self::Airwallex,
api_enums::Connector::Amazonpay => Self::Amazonpay,
api_enums::Connector::Archipel => Self::Archipel,
api_enums::Connector::Authipay => Self::Authipay,
api_enums::Connector::Authorizedotnet => Self::Authorizedotnet,
api_enums::Connector::Bambora => Self::Bambora,
api_enums::Connector::Bamboraapac => Self::Bamboraapac,
api_enums::Connector::Bankofamerica => Self::Bankofamerica,
api_enums::Connector::Barclaycard => Self::Barclaycard,
api_enums::Connector::Billwerk => Self::Billwerk,
api_enums::Connector::Bitpay => Self::Bitpay,
api_enums::Connector::Bluesnap => Self::Bluesnap,
api_enums::Connector::Blackhawknetwork => Self::Blackhawknetwork,
api_enums::Connector::Calida => Self::Calida,
api_enums::Connector::Boku => Self::Boku,
api_enums::Connector::Braintree => Self::Braintree,
api_enums::Connector::Breadpay => Self::Breadpay,
api_enums::Connector::Cardinal => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "cardinal is not a routable connector".to_string(),
})?
}
api_enums::Connector::Cashtocode => Self::Cashtocode,
api_enums::Connector::Celero => Self::Celero,
api_enums::Connector::Chargebee => Self::Chargebee,
api_enums::Connector::Checkbook => Self::Checkbook,
api_enums::Connector::Checkout => Self::Checkout,
api_enums::Connector::Coinbase => Self::Coinbase,
api_enums::Connector::Coingate => Self::Coingate,
api_enums::Connector::Cryptopay => Self::Cryptopay,
api_enums::Connector::Custombilling => Self::Custombilling,
api_enums::Connector::CtpVisa => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "ctp visa is not a routable connector".to_string(),
})?
}
api_enums::Connector::CtpMastercard => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "ctp mastercard is not a routable connector".to_string(),
})?
}
api_enums::Connector::Cybersource => Self::Cybersource,
api_enums::Connector::Datatrans => Self::Datatrans,
api_enums::Connector::Deutschebank => Self::Deutschebank,
api_enums::Connector::Digitalvirgo => Self::Digitalvirgo,
api_enums::Connector::Dlocal => Self::Dlocal,
api_enums::Connector::Dwolla => Self::Dwolla,
api_enums::Connector::Ebanx => Self::Ebanx,
api_enums::Connector::Elavon => Self::Elavon,
api_enums::Connector::Facilitapay => Self::Facilitapay,
api_enums::Connector::Finix => Self::Finix,
api_enums::Connector::Fiserv => Self::Fiserv,
api_enums::Connector::Fiservemea => Self::Fiservemea,
api_enums::Connector::Fiuu => Self::Fiuu,
api_enums::Connector::Flexiti => Self::Flexiti,
api_enums::Connector::Forte => Self::Forte,
api_enums::Connector::Getnet => Self::Getnet,
api_enums::Connector::Gigadat => Self::Gigadat,
api_enums::Connector::Globalpay => Self::Globalpay,
api_enums::Connector::Globepay => Self::Globepay,
api_enums::Connector::Gocardless => Self::Gocardless,
api_enums::Connector::Gpayments => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "gpayments is not a routable connector".to_string(),
})?
}
api_enums::Connector::Hipay => Self::Hipay,
api_enums::Connector::Helcim => Self::Helcim,
api_enums::Connector::HyperswitchVault => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "Hyperswitch Vault is not a routable connector".to_string(),
})?
}
api_enums::Connector::Iatapay => Self::Iatapay,
api_enums::Connector::Inespay => Self::Inespay,
api_enums::Connector::Itaubank => Self::Itaubank,
api_enums::Connector::Jpmorgan => Self::Jpmorgan,
api_enums::Connector::Juspaythreedsserver => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "juspaythreedsserver is not a routable connector".to_string(),
})?
}
api_enums::Connector::Klarna => Self::Klarna,
api_enums::Connector::Loonio => Self::Loonio,
api_enums::Connector::Mifinity => Self::Mifinity,
api_enums::Connector::Mollie => Self::Mollie,
api_enums::Connector::Moneris => Self::Moneris,
api_enums::Connector::Multisafepay => Self::Multisafepay,
api_enums::Connector::Netcetera => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "netcetera is not a routable connector".to_string(),
})?
}
api_enums::Connector::Nexinets => Self::Nexinets,
api_enums::Connector::Nexixpay => Self::Nexixpay,
api_enums::Connector::Nmi => Self::Nmi,
api_enums::Connector::Nomupay => Self::Nomupay,
api_enums::Connector::Noon => Self::Noon,
api_enums::Connector::Nordea => Self::Nordea,
api_enums::Connector::Novalnet => Self::Novalnet,
api_enums::Connector::Nuvei => Self::Nuvei,
api_enums::Connector::Opennode => Self::Opennode,
api_enums::Connector::Paybox => Self::Paybox,
api_enums::Connector::Payload => Self::Payload,
api_enums::Connector::Payme => Self::Payme,
api_enums::Connector::Payone => Self::Payone,
api_enums::Connector::Paypal => Self::Paypal,
api_enums::Connector::Paysafe => Self::Paysafe,
api_enums::Connector::Paystack => Self::Paystack,
api_enums::Connector::Payu => Self::Payu,
api_enums::Connector::Peachpayments => Self::Peachpayments,
api_models::enums::Connector::Placetopay => Self::Placetopay,
api_enums::Connector::Plaid => Self::Plaid,
api_enums::Connector::Powertranz => Self::Powertranz,
api_enums::Connector::Prophetpay => Self::Prophetpay,
api_enums::Connector::Rapyd => Self::Rapyd,
api_enums::Connector::Razorpay => Self::Razorpay,
api_enums::Connector::Recurly => Self::Recurly,
api_enums::Connector::Redsys => Self::Redsys,
api_enums::Connector::Santander => Self::Santander,
api_enums::Connector::Shift4 => Self::Shift4,
api_enums::Connector::Silverflow => Self::Silverflow,
api_enums::Connector::Signifyd => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "signifyd is not a routable connector".to_string(),
})?
}
api_enums::Connector::Riskified => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "riskified is not a routable connector".to_string(),
})?
}
api_enums::Connector::Square => Self::Square,
api_enums::Connector::Stax => Self::Stax,
api_enums::Connector::Stripe => Self::Stripe,
api_enums::Connector::Stripebilling => Self::Stripebilling,
// api_enums::Connector::Thunes => Self::Thunes,
api_enums::Connector::Tesouro => Self::Tesouro,
api_enums::Connector::Tokenex => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "Tokenex is not a routable connector".to_string(),
})?
}
api_enums::Connector::Tokenio => Self::Tokenio,
api_enums::Connector::Trustpay => Self::Trustpay,
api_enums::Connector::Trustpayments => Self::Trustpayments,
api_enums::Connector::Tsys => Self::Tsys,
// api_enums::Connector::UnifiedAuthenticationService => {
// Self::UnifiedAuthenticationService
// }
api_enums::Connector::Vgs => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "Vgs is not a routable connector".to_string(),
})?
}
api_enums::Connector::Volt => Self::Volt,
api_enums::Connector::Wellsfargo => Self::Wellsfargo,
// api_enums::Connector::Wellsfargopayout => Self::Wellsfargopayout,
api_enums::Connector::Wise => Self::Wise,
api_enums::Connector::Worldline => Self::Worldline,
api_enums::Connector::Worldpay => Self::Worldpay,
api_enums::Connector::Worldpayvantiv => Self::Worldpayvantiv,
api_enums::Connector::Worldpayxml => Self::Worldpayxml,
api_enums::Connector::Xendit => Self::Xendit,
api_enums::Connector::Zen => Self::Zen,
api_enums::Connector::Zsl => Self::Zsl,
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyBillingConnector => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "stripe_billing_test is not a routable connector".to_string(),
})?
}
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyConnector1 => Self::DummyConnector1,
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyConnector2 => Self::DummyConnector2,
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyConnector3 => Self::DummyConnector3,
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyConnector4 => Self::DummyConnector4,
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyConnector5 => Self::DummyConnector5,
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyConnector6 => Self::DummyConnector6,
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyConnector7 => Self::DummyConnector7,
api_enums::Connector::Threedsecureio => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "threedsecureio is not a routable connector".to_string(),
})?
}
api_enums::Connector::Taxjar => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "Taxjar is not a routable connector".to_string(),
})?
}
api_enums::Connector::Phonepe => Self::Phonepe,
api_enums::Connector::Paytm => Self::Paytm,
})
}
}
|
crates/router/src/types/connector_transformers.rs
|
router::src::types::connector_transformers
| 2,835
| true
|
// File: crates/router/src/types/transformers.rs
// Module: router::src::types::transformers
use actix_web::http::header::HeaderMap;
use api_models::{
cards_info as card_info_types, enums as api_enums, gsm as gsm_api_types, payment_methods,
payments, routing::ConnectorSelection,
};
use common_utils::{
consts::X_HS_LATENCY,
crypto::Encryptable,
ext_traits::{Encode, StringExt, ValueExt},
fp_utils::when,
pii,
types::ConnectorTransactionIdTrait,
};
use diesel_models::enums as storage_enums;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::payments::payment_intent::CustomerData;
use masking::{ExposeInterface, PeekInterface, Secret};
use super::domain;
#[cfg(feature = "v2")]
use crate::db::storage::revenue_recovery_redis_operation;
use crate::{
core::errors,
headers::{
ACCEPT_LANGUAGE, BROWSER_NAME, X_APP_ID, X_CLIENT_PLATFORM, X_CLIENT_SOURCE,
X_CLIENT_VERSION, X_MERCHANT_DOMAIN, X_PAYMENT_CONFIRM_SOURCE, X_REDIRECT_URI,
X_REFERENCE_ID,
},
services::authentication::get_header_value_by_key,
types::{
self as router_types,
api::{self as api_types, routing as routing_types},
storage,
},
};
pub trait ForeignInto<T> {
fn foreign_into(self) -> T;
}
pub trait ForeignTryInto<T> {
type Error;
fn foreign_try_into(self) -> Result<T, Self::Error>;
}
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>;
}
impl<F, T> ForeignInto<T> for F
where
T: ForeignFrom<F>,
{
fn foreign_into(self) -> T {
T::foreign_from(self)
}
}
impl<F, T> ForeignTryInto<T> for F
where
T: ForeignTryFrom<F>,
{
type Error = <T as ForeignTryFrom<F>>::Error;
fn foreign_try_into(self) -> Result<T, Self::Error> {
T::foreign_try_from(self)
}
}
impl ForeignFrom<api_models::refunds::RefundType> for storage_enums::RefundType {
fn foreign_from(item: api_models::refunds::RefundType) -> Self {
match item {
api_models::refunds::RefundType::Instant => Self::InstantRefund,
api_models::refunds::RefundType::Scheduled => Self::RegularRefund,
}
}
}
#[cfg(feature = "v1")]
impl
ForeignFrom<(
Option<payment_methods::CardDetailFromLocker>,
domain::PaymentMethod,
)> for payment_methods::PaymentMethodResponse
{
fn foreign_from(
(card_details, item): (
Option<payment_methods::CardDetailFromLocker>,
domain::PaymentMethod,
),
) -> Self {
Self {
merchant_id: item.merchant_id.to_owned(),
customer_id: Some(item.customer_id.to_owned()),
payment_method_id: item.get_id().clone(),
payment_method: item.get_payment_method_type(),
payment_method_type: item.get_payment_method_subtype(),
card: card_details,
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: None,
metadata: item.metadata,
created: Some(item.created_at),
#[cfg(feature = "payouts")]
bank_transfer: None,
last_used_at: None,
client_secret: item.client_secret,
}
}
}
#[cfg(feature = "v2")]
impl
ForeignFrom<(
Option<payment_methods::CardDetailFromLocker>,
domain::PaymentMethod,
)> for payment_methods::PaymentMethodResponse
{
fn foreign_from(
(card_details, item): (
Option<payment_methods::CardDetailFromLocker>,
domain::PaymentMethod,
),
) -> Self {
todo!()
}
}
// TODO: remove this usage in v1 code
impl ForeignFrom<storage_enums::AttemptStatus> for storage_enums::IntentStatus {
fn foreign_from(s: storage_enums::AttemptStatus) -> Self {
Self::from(s)
}
}
impl ForeignTryFrom<storage_enums::AttemptStatus> for storage_enums::CaptureStatus {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(
attempt_status: storage_enums::AttemptStatus,
) -> errors::RouterResult<Self> {
match attempt_status {
storage_enums::AttemptStatus::Charged
| storage_enums::AttemptStatus::PartialCharged | storage_enums::AttemptStatus::IntegrityFailure => Ok(Self::Charged),
storage_enums::AttemptStatus::Pending
| storage_enums::AttemptStatus::CaptureInitiated => Ok(Self::Pending),
storage_enums::AttemptStatus::Failure
| storage_enums::AttemptStatus::CaptureFailed => Ok(Self::Failed),
storage_enums::AttemptStatus::Started
| storage_enums::AttemptStatus::AuthenticationFailed
| storage_enums::AttemptStatus::RouterDeclined
| storage_enums::AttemptStatus::AuthenticationPending
| storage_enums::AttemptStatus::AuthenticationSuccessful
| storage_enums::AttemptStatus::Authorized
| storage_enums::AttemptStatus::AuthorizationFailed
| storage_enums::AttemptStatus::Authorizing
| storage_enums::AttemptStatus::CodInitiated
| storage_enums::AttemptStatus::Voided
| storage_enums::AttemptStatus::VoidedPostCharge
| storage_enums::AttemptStatus::VoidInitiated
| storage_enums::AttemptStatus::VoidFailed
| storage_enums::AttemptStatus::AutoRefunded
| storage_enums::AttemptStatus::Unresolved
| storage_enums::AttemptStatus::PaymentMethodAwaited
| storage_enums::AttemptStatus::ConfirmationAwaited
| storage_enums::AttemptStatus::DeviceDataCollectionPending
| storage_enums::AttemptStatus::PartiallyAuthorized
| storage_enums::AttemptStatus::PartialChargedAndChargeable | storage_enums::AttemptStatus::Expired => {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "AttemptStatus must be one of these for multiple partial captures [Charged, PartialCharged, Pending, CaptureInitiated, Failure, CaptureFailed]".into(),
}.into())
}
}
}
}
impl ForeignFrom<payments::MandateType> for storage_enums::MandateDataType {
fn foreign_from(from: payments::MandateType) -> Self {
match from {
payments::MandateType::SingleUse(inner) => Self::SingleUse(inner.foreign_into()),
payments::MandateType::MultiUse(inner) => {
Self::MultiUse(inner.map(ForeignInto::foreign_into))
}
}
}
}
impl ForeignFrom<storage_enums::MandateDataType> for payments::MandateType {
fn foreign_from(from: storage_enums::MandateDataType) -> Self {
match from {
storage_enums::MandateDataType::SingleUse(inner) => {
Self::SingleUse(inner.foreign_into())
}
storage_enums::MandateDataType::MultiUse(inner) => {
Self::MultiUse(inner.map(ForeignInto::foreign_into))
}
}
}
}
impl ForeignFrom<storage_enums::MandateAmountData> for payments::MandateAmountData {
fn foreign_from(from: storage_enums::MandateAmountData) -> Self {
Self {
amount: from.amount,
currency: from.currency,
start_date: from.start_date,
end_date: from.end_date,
metadata: from.metadata,
}
}
}
// TODO: remove foreign from since this conversion won't be needed in the router crate once data models is treated as a single & primary source of truth for structure information
impl ForeignFrom<payments::MandateData> for hyperswitch_domain_models::mandates::MandateData {
fn foreign_from(d: payments::MandateData) -> Self {
Self {
customer_acceptance: d.customer_acceptance,
mandate_type: d.mandate_type.map(|d| match d {
payments::MandateType::MultiUse(Some(i)) => {
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(
hyperswitch_domain_models::mandates::MandateAmountData {
amount: i.amount,
currency: i.currency,
start_date: i.start_date,
end_date: i.end_date,
metadata: i.metadata,
},
))
}
payments::MandateType::SingleUse(i) => {
hyperswitch_domain_models::mandates::MandateDataType::SingleUse(
hyperswitch_domain_models::mandates::MandateAmountData {
amount: i.amount,
currency: i.currency,
start_date: i.start_date,
end_date: i.end_date,
metadata: i.metadata,
},
)
}
payments::MandateType::MultiUse(None) => {
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None)
}
}),
update_mandate_id: d.update_mandate_id,
}
}
}
impl ForeignFrom<payments::MandateAmountData> for storage_enums::MandateAmountData {
fn foreign_from(from: payments::MandateAmountData) -> Self {
Self {
amount: from.amount,
currency: from.currency,
start_date: from.start_date,
end_date: from.end_date,
metadata: from.metadata,
}
}
}
impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod {
fn foreign_from(payment_method_type: api_enums::PaymentMethodType) -> Self {
match payment_method_type {
api_enums::PaymentMethodType::AmazonPay
| api_enums::PaymentMethodType::Paysera
| api_enums::PaymentMethodType::Skrill
| api_enums::PaymentMethodType::ApplePay
| api_enums::PaymentMethodType::GooglePay
| api_enums::PaymentMethodType::Paypal
| api_enums::PaymentMethodType::AliPay
| api_enums::PaymentMethodType::AliPayHk
| api_enums::PaymentMethodType::Dana
| api_enums::PaymentMethodType::MbWay
| api_enums::PaymentMethodType::MobilePay
| api_enums::PaymentMethodType::Paze
| api_enums::PaymentMethodType::SamsungPay
| api_enums::PaymentMethodType::Twint
| api_enums::PaymentMethodType::Vipps
| api_enums::PaymentMethodType::TouchNGo
| api_enums::PaymentMethodType::Swish
| api_enums::PaymentMethodType::WeChatPay
| api_enums::PaymentMethodType::GoPay
| api_enums::PaymentMethodType::Gcash
| api_enums::PaymentMethodType::Momo
| api_enums::PaymentMethodType::Cashapp
| api_enums::PaymentMethodType::KakaoPay
| api_enums::PaymentMethodType::Venmo
| api_enums::PaymentMethodType::Mifinity
| api_enums::PaymentMethodType::RevolutPay
| api_enums::PaymentMethodType::Bluecode => Self::Wallet,
api_enums::PaymentMethodType::Affirm
| api_enums::PaymentMethodType::Alma
| api_enums::PaymentMethodType::AfterpayClearpay
| api_enums::PaymentMethodType::Klarna
| api_enums::PaymentMethodType::Flexiti
| api_enums::PaymentMethodType::PayBright
| api_enums::PaymentMethodType::Atome
| api_enums::PaymentMethodType::Walley
| api_enums::PaymentMethodType::Breadpay => Self::PayLater,
api_enums::PaymentMethodType::Giropay
| api_enums::PaymentMethodType::Ideal
| api_enums::PaymentMethodType::Sofort
| api_enums::PaymentMethodType::Eft
| api_enums::PaymentMethodType::Eps
| api_enums::PaymentMethodType::BancontactCard
| api_enums::PaymentMethodType::Blik
| api_enums::PaymentMethodType::LocalBankRedirect
| api_enums::PaymentMethodType::OnlineBankingThailand
| api_enums::PaymentMethodType::OnlineBankingCzechRepublic
| api_enums::PaymentMethodType::OnlineBankingFinland
| api_enums::PaymentMethodType::OnlineBankingFpx
| api_enums::PaymentMethodType::OnlineBankingPoland
| api_enums::PaymentMethodType::OnlineBankingSlovakia
| api_enums::PaymentMethodType::OpenBankingUk
| api_enums::PaymentMethodType::OpenBankingPIS
| api_enums::PaymentMethodType::Przelewy24
| api_enums::PaymentMethodType::Trustly
| api_enums::PaymentMethodType::Bizum
| api_enums::PaymentMethodType::Interac => Self::BankRedirect,
api_enums::PaymentMethodType::UpiCollect
| api_enums::PaymentMethodType::UpiIntent
| api_enums::PaymentMethodType::UpiQr => Self::Upi,
api_enums::PaymentMethodType::CryptoCurrency => Self::Crypto,
api_enums::PaymentMethodType::Ach
| api_enums::PaymentMethodType::Sepa
| api_enums::PaymentMethodType::SepaGuarenteedDebit
| api_enums::PaymentMethodType::Bacs
| api_enums::PaymentMethodType::Becs => Self::BankDebit,
api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => {
Self::Card
}
#[cfg(feature = "v2")]
api_enums::PaymentMethodType::Card => Self::Card,
api_enums::PaymentMethodType::Evoucher
| api_enums::PaymentMethodType::ClassicReward => Self::Reward,
api_enums::PaymentMethodType::Boleto
| api_enums::PaymentMethodType::Efecty
| api_enums::PaymentMethodType::PagoEfectivo
| api_enums::PaymentMethodType::RedCompra
| api_enums::PaymentMethodType::Alfamart
| api_enums::PaymentMethodType::Indomaret
| api_enums::PaymentMethodType::Oxxo
| api_enums::PaymentMethodType::SevenEleven
| api_enums::PaymentMethodType::Lawson
| api_enums::PaymentMethodType::MiniStop
| api_enums::PaymentMethodType::FamilyMart
| api_enums::PaymentMethodType::Seicomart
| api_enums::PaymentMethodType::PayEasy
| api_enums::PaymentMethodType::RedPagos => Self::Voucher,
api_enums::PaymentMethodType::Pse
| api_enums::PaymentMethodType::Multibanco
| api_enums::PaymentMethodType::PermataBankTransfer
| api_enums::PaymentMethodType::BcaBankTransfer
| api_enums::PaymentMethodType::BniVa
| api_enums::PaymentMethodType::BriVa
| api_enums::PaymentMethodType::CimbVa
| api_enums::PaymentMethodType::DanamonVa
| api_enums::PaymentMethodType::MandiriVa
| api_enums::PaymentMethodType::LocalBankTransfer
| api_enums::PaymentMethodType::InstantBankTransfer
| api_enums::PaymentMethodType::InstantBankTransferFinland
| api_enums::PaymentMethodType::InstantBankTransferPoland
| api_enums::PaymentMethodType::SepaBankTransfer
| api_enums::PaymentMethodType::IndonesianBankTransfer
| api_enums::PaymentMethodType::Pix => Self::BankTransfer,
api_enums::PaymentMethodType::Givex
| api_enums::PaymentMethodType::PaySafeCard
| api_enums::PaymentMethodType::BhnCardNetwork => Self::GiftCard,
api_enums::PaymentMethodType::Benefit
| api_enums::PaymentMethodType::Knet
| api_enums::PaymentMethodType::MomoAtm
| api_enums::PaymentMethodType::CardRedirect => Self::CardRedirect,
api_enums::PaymentMethodType::Fps
| api_enums::PaymentMethodType::DuitNow
| api_enums::PaymentMethodType::PromptPay
| api_enums::PaymentMethodType::VietQr => Self::RealTimePayment,
api_enums::PaymentMethodType::DirectCarrierBilling => Self::MobilePayment,
}
}
}
impl ForeignTryFrom<payments::PaymentMethodData> for api_enums::PaymentMethod {
type Error = errors::ApiErrorResponse;
fn foreign_try_from(
payment_method_data: payments::PaymentMethodData,
) -> Result<Self, Self::Error> {
match payment_method_data {
payments::PaymentMethodData::Card(..) | payments::PaymentMethodData::CardToken(..) => {
Ok(Self::Card)
}
payments::PaymentMethodData::Wallet(..) => Ok(Self::Wallet),
payments::PaymentMethodData::PayLater(..) => Ok(Self::PayLater),
payments::PaymentMethodData::BankRedirect(..) => Ok(Self::BankRedirect),
payments::PaymentMethodData::BankDebit(..) => Ok(Self::BankDebit),
payments::PaymentMethodData::BankTransfer(..) => Ok(Self::BankTransfer),
payments::PaymentMethodData::Crypto(..) => Ok(Self::Crypto),
payments::PaymentMethodData::Reward => Ok(Self::Reward),
payments::PaymentMethodData::RealTimePayment(..) => Ok(Self::RealTimePayment),
payments::PaymentMethodData::Upi(..) => Ok(Self::Upi),
payments::PaymentMethodData::Voucher(..) => Ok(Self::Voucher),
payments::PaymentMethodData::GiftCard(..) => Ok(Self::GiftCard),
payments::PaymentMethodData::CardRedirect(..) => Ok(Self::CardRedirect),
payments::PaymentMethodData::OpenBanking(..) => Ok(Self::OpenBanking),
payments::PaymentMethodData::MobilePayment(..) => Ok(Self::MobilePayment),
payments::PaymentMethodData::MandatePayment => {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: ("Mandate payments cannot have payment_method_data field".to_string()),
})
}
}
}
}
impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::RefundStatus {
type Error = errors::ValidationError;
fn foreign_try_from(
value: api_models::webhooks::IncomingWebhookEvent,
) -> Result<Self, Self::Error> {
match value {
api_models::webhooks::IncomingWebhookEvent::RefundSuccess => Ok(Self::Success),
api_models::webhooks::IncomingWebhookEvent::RefundFailure => Ok(Self::Failure),
_ => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "incoming_webhook_event_type",
}),
}
}
}
impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for api_enums::RelayStatus {
type Error = errors::ValidationError;
fn foreign_try_from(
value: api_models::webhooks::IncomingWebhookEvent,
) -> Result<Self, Self::Error> {
match value {
api_models::webhooks::IncomingWebhookEvent::RefundSuccess => Ok(Self::Success),
api_models::webhooks::IncomingWebhookEvent::RefundFailure => Ok(Self::Failure),
_ => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "incoming_webhook_event_type",
}),
}
}
}
#[cfg(feature = "payouts")]
impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::PayoutStatus {
type Error = errors::ValidationError;
fn foreign_try_from(
value: api_models::webhooks::IncomingWebhookEvent,
) -> Result<Self, Self::Error> {
match value {
api_models::webhooks::IncomingWebhookEvent::PayoutSuccess => Ok(Self::Success),
api_models::webhooks::IncomingWebhookEvent::PayoutFailure => Ok(Self::Failed),
api_models::webhooks::IncomingWebhookEvent::PayoutCancelled => Ok(Self::Cancelled),
api_models::webhooks::IncomingWebhookEvent::PayoutProcessing => Ok(Self::Pending),
api_models::webhooks::IncomingWebhookEvent::PayoutCreated => Ok(Self::Initiated),
api_models::webhooks::IncomingWebhookEvent::PayoutExpired => Ok(Self::Expired),
api_models::webhooks::IncomingWebhookEvent::PayoutReversed => Ok(Self::Reversed),
_ => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "incoming_webhook_event_type",
}),
}
}
}
impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::MandateStatus {
type Error = errors::ValidationError;
fn foreign_try_from(
value: api_models::webhooks::IncomingWebhookEvent,
) -> Result<Self, Self::Error> {
match value {
api_models::webhooks::IncomingWebhookEvent::MandateActive => Ok(Self::Active),
api_models::webhooks::IncomingWebhookEvent::MandateRevoked => Ok(Self::Revoked),
_ => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "incoming_webhook_event_type",
}),
}
}
}
impl ForeignFrom<storage::Config> for api_types::Config {
fn foreign_from(config: storage::Config) -> Self {
Self {
key: config.key,
value: config.config,
}
}
}
impl ForeignFrom<&api_types::ConfigUpdate> for storage::ConfigUpdate {
fn foreign_from(config: &api_types::ConfigUpdate) -> Self {
Self::Update {
config: Some(config.value.clone()),
}
}
}
impl From<&domain::Address> for hyperswitch_domain_models::address::Address {
fn from(address: &domain::Address) -> Self {
// If all the fields of address are none, then pass the address as None
let address_details = if address.city.is_none()
&& address.line1.is_none()
&& address.line2.is_none()
&& address.line3.is_none()
&& address.state.is_none()
&& address.country.is_none()
&& address.zip.is_none()
&& address.first_name.is_none()
&& address.last_name.is_none()
{
None
} else {
Some(hyperswitch_domain_models::address::AddressDetails {
city: address.city.clone(),
country: address.country,
line1: address.line1.clone().map(Encryptable::into_inner),
line2: address.line2.clone().map(Encryptable::into_inner),
line3: address.line3.clone().map(Encryptable::into_inner),
state: address.state.clone().map(Encryptable::into_inner),
zip: address.zip.clone().map(Encryptable::into_inner),
first_name: address.first_name.clone().map(Encryptable::into_inner),
last_name: address.last_name.clone().map(Encryptable::into_inner),
origin_zip: address.origin_zip.clone().map(Encryptable::into_inner),
})
};
// If all the fields of phone are none, then pass the phone as None
let phone_details = if address.phone_number.is_none() && address.country_code.is_none() {
None
} else {
Some(hyperswitch_domain_models::address::PhoneDetails {
number: address.phone_number.clone().map(Encryptable::into_inner),
country_code: address.country_code.clone(),
})
};
Self {
address: address_details,
phone: phone_details,
email: address.email.clone().map(pii::Email::from),
}
}
}
impl ForeignFrom<domain::Address> for api_types::Address {
fn foreign_from(address: domain::Address) -> Self {
// If all the fields of address are none, then pass the address as None
let address_details = if address.city.is_none()
&& address.line1.is_none()
&& address.line2.is_none()
&& address.line3.is_none()
&& address.state.is_none()
&& address.country.is_none()
&& address.zip.is_none()
&& address.first_name.is_none()
&& address.last_name.is_none()
{
None
} else {
Some(api_types::AddressDetails {
city: address.city.clone(),
country: address.country,
line1: address.line1.clone().map(Encryptable::into_inner),
line2: address.line2.clone().map(Encryptable::into_inner),
line3: address.line3.clone().map(Encryptable::into_inner),
state: address.state.clone().map(Encryptable::into_inner),
zip: address.zip.clone().map(Encryptable::into_inner),
first_name: address.first_name.clone().map(Encryptable::into_inner),
last_name: address.last_name.clone().map(Encryptable::into_inner),
origin_zip: address.origin_zip.clone().map(Encryptable::into_inner),
})
};
// If all the fields of phone are none, then pass the phone as None
let phone_details = if address.phone_number.is_none() && address.country_code.is_none() {
None
} else {
Some(api_types::PhoneDetails {
number: address.phone_number.clone().map(Encryptable::into_inner),
country_code: address.country_code.clone(),
})
};
Self {
address: address_details,
phone: phone_details,
email: address.email.clone().map(pii::Email::from),
}
}
}
impl
ForeignFrom<(
diesel_models::api_keys::ApiKey,
crate::core::api_keys::PlaintextApiKey,
)> for api_models::api_keys::CreateApiKeyResponse
{
fn foreign_from(
item: (
diesel_models::api_keys::ApiKey,
crate::core::api_keys::PlaintextApiKey,
),
) -> Self {
use masking::StrongSecret;
let (api_key, plaintext_api_key) = item;
Self {
key_id: api_key.key_id,
merchant_id: api_key.merchant_id,
name: api_key.name,
description: api_key.description,
api_key: StrongSecret::from(plaintext_api_key.peek().to_owned()),
created: api_key.created_at,
expiration: api_key.expires_at.into(),
}
}
}
impl ForeignFrom<diesel_models::api_keys::ApiKey> for api_models::api_keys::RetrieveApiKeyResponse {
fn foreign_from(api_key: diesel_models::api_keys::ApiKey) -> Self {
Self {
key_id: api_key.key_id,
merchant_id: api_key.merchant_id,
name: api_key.name,
description: api_key.description,
prefix: api_key.prefix.into(),
created: api_key.created_at,
expiration: api_key.expires_at.into(),
}
}
}
impl ForeignFrom<api_models::api_keys::UpdateApiKeyRequest>
for diesel_models::api_keys::ApiKeyUpdate
{
fn foreign_from(api_key: api_models::api_keys::UpdateApiKeyRequest) -> Self {
Self::Update {
name: api_key.name,
description: api_key.description,
expires_at: api_key.expiration.map(Into::into),
last_used: None,
}
}
}
impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::DisputeStatus {
type Error = errors::ValidationError;
fn foreign_try_from(
value: api_models::webhooks::IncomingWebhookEvent,
) -> Result<Self, Self::Error> {
match value {
api_models::webhooks::IncomingWebhookEvent::DisputeOpened => Ok(Self::DisputeOpened),
api_models::webhooks::IncomingWebhookEvent::DisputeExpired => Ok(Self::DisputeExpired),
api_models::webhooks::IncomingWebhookEvent::DisputeAccepted => {
Ok(Self::DisputeAccepted)
}
api_models::webhooks::IncomingWebhookEvent::DisputeCancelled => {
Ok(Self::DisputeCancelled)
}
api_models::webhooks::IncomingWebhookEvent::DisputeChallenged => {
Ok(Self::DisputeChallenged)
}
api_models::webhooks::IncomingWebhookEvent::DisputeWon => Ok(Self::DisputeWon),
api_models::webhooks::IncomingWebhookEvent::DisputeLost => Ok(Self::DisputeLost),
_ => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "incoming_webhook_event",
}),
}
}
}
impl ForeignFrom<storage::Dispute> for api_models::disputes::DisputeResponse {
fn foreign_from(dispute: storage::Dispute) -> Self {
Self {
dispute_id: dispute.dispute_id,
payment_id: dispute.payment_id,
attempt_id: dispute.attempt_id,
amount: dispute.amount,
currency: dispute.dispute_currency.unwrap_or(
dispute
.currency
.to_uppercase()
.parse_enum("Currency")
.unwrap_or_default(),
),
dispute_stage: dispute.dispute_stage,
dispute_status: dispute.dispute_status,
connector: dispute.connector,
connector_status: dispute.connector_status,
connector_dispute_id: dispute.connector_dispute_id,
connector_reason: dispute.connector_reason,
connector_reason_code: dispute.connector_reason_code,
challenge_required_by: dispute.challenge_required_by,
connector_created_at: dispute.connector_created_at,
connector_updated_at: dispute.connector_updated_at,
created_at: dispute.created_at,
profile_id: dispute.profile_id,
merchant_connector_id: dispute.merchant_connector_id,
}
}
}
impl ForeignFrom<storage::Authorization> for payments::IncrementalAuthorizationResponse {
fn foreign_from(authorization: storage::Authorization) -> Self {
Self {
authorization_id: authorization.authorization_id,
amount: authorization.amount,
status: authorization.status,
error_code: authorization.error_code,
error_message: authorization.error_message,
previously_authorized_amount: authorization.previously_authorized_amount,
}
}
}
impl
ForeignFrom<
&hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore,
> for payments::ExternalAuthenticationDetailsResponse
{
fn foreign_from(
authn_store: &hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore,
) -> Self {
let authn_data = &authn_store.authentication;
let version = authn_data
.maximum_supported_version
.as_ref()
.map(|version| version.to_string());
Self {
authentication_flow: authn_data.authentication_type,
electronic_commerce_indicator: authn_data.eci.clone(),
status: authn_data.authentication_status,
ds_transaction_id: authn_data.threeds_server_transaction_id.clone(),
version,
error_code: authn_data.error_code.clone(),
error_message: authn_data.error_message.clone(),
}
}
}
impl ForeignFrom<storage::Dispute> for api_models::disputes::DisputeResponsePaymentsRetrieve {
fn foreign_from(dispute: storage::Dispute) -> Self {
Self {
dispute_id: dispute.dispute_id,
dispute_stage: dispute.dispute_stage,
dispute_status: dispute.dispute_status,
connector_status: dispute.connector_status,
connector_dispute_id: dispute.connector_dispute_id,
connector_reason: dispute.connector_reason,
connector_reason_code: dispute.connector_reason_code,
challenge_required_by: dispute.challenge_required_by,
connector_created_at: dispute.connector_created_at,
connector_updated_at: dispute.connector_updated_at,
created_at: dispute.created_at,
}
}
}
impl ForeignFrom<storage::FileMetadata> for api_models::files::FileMetadataResponse {
fn foreign_from(file_metadata: storage::FileMetadata) -> Self {
Self {
file_id: file_metadata.file_id,
file_name: file_metadata.file_name,
file_size: file_metadata.file_size,
file_type: file_metadata.file_type,
available: file_metadata.available,
}
}
}
impl ForeignFrom<diesel_models::cards_info::CardInfo> for api_models::cards_info::CardInfoResponse {
fn foreign_from(item: diesel_models::cards_info::CardInfo) -> Self {
Self {
card_iin: item.card_iin,
card_type: item.card_type,
card_sub_type: item.card_subtype,
card_network: item.card_network.map(|x| x.to_string()),
card_issuer: item.card_issuer,
card_issuing_country: item.card_issuing_country,
}
}
}
impl ForeignTryFrom<domain::MerchantConnectorAccount>
for api_models::admin::MerchantConnectorListResponse
{
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(item: domain::MerchantConnectorAccount) -> Result<Self, Self::Error> {
#[cfg(feature = "v1")]
let payment_methods_enabled = match item.payment_methods_enabled {
Some(secret_val) => {
let val = secret_val
.into_iter()
.map(|secret| secret.expose())
.collect();
serde_json::Value::Array(val)
.parse_value("PaymentMethods")
.change_context(errors::ApiErrorResponse::InternalServerError)?
}
None => None,
};
let frm_configs = match item.frm_configs {
Some(frm_value) => {
let configs_for_frm : Vec<api_models::admin::FrmConfigs> = frm_value
.iter()
.map(|config| { config
.peek()
.clone()
.parse_value("FrmConfigs")
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "frm_configs".to_string(),
expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","payment_method_types": [{"payment_method_type": "credit","card_networks": ["Visa"],"flow": "pre","action": "cancel_txn"}]}]}]"#.to_string(),
})
})
.collect::<Result<Vec<_>, _>>()?;
Some(configs_for_frm)
}
None => None,
};
#[cfg(feature = "v1")]
let response = Self {
connector_type: item.connector_type,
connector_name: item.connector_name,
connector_label: item.connector_label,
merchant_connector_id: item.merchant_connector_id,
test_mode: item.test_mode,
disabled: item.disabled,
payment_methods_enabled,
business_country: item.business_country,
business_label: item.business_label,
business_sub_label: item.business_sub_label,
frm_configs,
profile_id: item.profile_id,
applepay_verified_domains: item.applepay_verified_domains,
pm_auth_config: item.pm_auth_config,
status: item.status,
};
#[cfg(feature = "v2")]
let response = Self {
id: item.id,
connector_type: item.connector_type,
connector_name: item.connector_name,
connector_label: item.connector_label,
disabled: item.disabled,
payment_methods_enabled: item.payment_methods_enabled,
frm_configs,
profile_id: item.profile_id,
applepay_verified_domains: item.applepay_verified_domains,
pm_auth_config: item.pm_auth_config,
status: item.status,
};
Ok(response)
}
}
#[cfg(feature = "v1")]
impl ForeignTryFrom<domain::MerchantConnectorAccount>
for api_models::admin::MerchantConnectorResponse
{
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(item: domain::MerchantConnectorAccount) -> Result<Self, Self::Error> {
let payment_methods_enabled = match item.payment_methods_enabled.clone() {
Some(secret_val) => {
let val = secret_val
.into_iter()
.map(|secret| secret.expose())
.collect();
serde_json::Value::Array(val)
.parse_value("PaymentMethods")
.change_context(errors::ApiErrorResponse::InternalServerError)?
}
None => None,
};
let frm_configs = match item.frm_configs {
Some(ref frm_value) => {
let configs_for_frm : Vec<api_models::admin::FrmConfigs> = frm_value
.iter()
.map(|config| { config
.peek()
.clone()
.parse_value("FrmConfigs")
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "frm_configs".to_string(),
expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","payment_method_types": [{"payment_method_type": "credit","card_networks": ["Visa"],"flow": "pre","action": "cancel_txn"}]}]}]"#.to_string(),
})
})
.collect::<Result<Vec<_>, _>>()?;
Some(configs_for_frm)
}
None => None,
};
// parse the connector_account_details into ConnectorAuthType
let connector_account_details: hyperswitch_domain_models::router_data::ConnectorAuthType =
item.connector_account_details
.clone()
.into_inner()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
// get the masked keys from the ConnectorAuthType and encode it to secret value
let masked_connector_account_details = Secret::new(
connector_account_details
.get_masked_keys()
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode ConnectorAuthType")?,
);
#[cfg(feature = "v2")]
let response = Self {
id: item.get_id(),
connector_type: item.connector_type,
connector_name: item.connector_name,
connector_label: item.connector_label,
connector_account_details: masked_connector_account_details,
disabled: item.disabled,
payment_methods_enabled,
metadata: item.metadata,
frm_configs,
connector_webhook_details: item
.connector_webhook_details
.map(|webhook_details| {
serde_json::Value::parse_value(
webhook_details.expose(),
"MerchantConnectorWebhookDetails",
)
.attach_printable("Unable to deserialize connector_webhook_details")
.change_context(errors::ApiErrorResponse::InternalServerError)
})
.transpose()?,
profile_id: item.profile_id,
applepay_verified_domains: item.applepay_verified_domains,
pm_auth_config: item.pm_auth_config,
status: item.status,
additional_merchant_data: item
.additional_merchant_data
.map(|data| {
let data = data.into_inner();
serde_json::Value::parse_value::<router_types::AdditionalMerchantData>(
data.expose(),
"AdditionalMerchantData",
)
.attach_printable("Unable to deserialize additional_merchant_data")
.change_context(errors::ApiErrorResponse::InternalServerError)
})
.transpose()?
.map(api_models::admin::AdditionalMerchantData::foreign_from),
connector_wallets_details: item
.connector_wallets_details
.map(|data| {
data.into_inner()
.expose()
.parse_value::<api_models::admin::ConnectorWalletDetails>(
"ConnectorWalletDetails",
)
.attach_printable("Unable to deserialize connector_wallets_details")
.change_context(errors::ApiErrorResponse::InternalServerError)
})
.transpose()?,
};
#[cfg(feature = "v1")]
let response = Self {
connector_type: item.connector_type,
connector_name: item.connector_name,
connector_label: item.connector_label,
merchant_connector_id: item.merchant_connector_id,
connector_account_details: masked_connector_account_details,
test_mode: item.test_mode,
disabled: item.disabled,
payment_methods_enabled,
metadata: item.metadata,
business_country: item.business_country,
business_label: item.business_label,
business_sub_label: item.business_sub_label,
frm_configs,
connector_webhook_details: item
.connector_webhook_details
.map(|webhook_details| {
serde_json::Value::parse_value(
webhook_details.expose(),
"MerchantConnectorWebhookDetails",
)
.attach_printable("Unable to deserialize connector_webhook_details")
.change_context(errors::ApiErrorResponse::InternalServerError)
})
.transpose()?,
profile_id: item.profile_id,
applepay_verified_domains: item.applepay_verified_domains,
pm_auth_config: item.pm_auth_config,
status: item.status,
additional_merchant_data: item
.additional_merchant_data
.map(|data| {
let data = data.into_inner();
serde_json::Value::parse_value::<router_types::AdditionalMerchantData>(
data.expose(),
"AdditionalMerchantData",
)
.attach_printable("Unable to deserialize additional_merchant_data")
.change_context(errors::ApiErrorResponse::InternalServerError)
})
.transpose()?
.map(api_models::admin::AdditionalMerchantData::foreign_from),
connector_wallets_details: item
.connector_wallets_details
.map(|data| {
data.into_inner()
.expose()
.parse_value::<api_models::admin::ConnectorWalletDetails>(
"ConnectorWalletDetails",
)
.attach_printable("Unable to deserialize connector_wallets_details")
.change_context(errors::ApiErrorResponse::InternalServerError)
})
.transpose()?,
};
Ok(response)
}
}
#[cfg(feature = "v2")]
impl ForeignTryFrom<domain::MerchantConnectorAccount>
for api_models::admin::MerchantConnectorResponse
{
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(item: domain::MerchantConnectorAccount) -> Result<Self, Self::Error> {
let frm_configs = match item.frm_configs {
Some(ref frm_value) => {
let configs_for_frm : Vec<api_models::admin::FrmConfigs> = frm_value
.iter()
.map(|config| { config
.peek()
.clone()
.parse_value("FrmConfigs")
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "frm_configs".to_string(),
expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","payment_method_types": [{"payment_method_type": "credit","card_networks": ["Visa"],"flow": "pre","action": "cancel_txn"}]}]}]"#.to_string(),
})
})
.collect::<Result<Vec<_>, _>>()?;
Some(configs_for_frm)
}
None => None,
};
// parse the connector_account_details into ConnectorAuthType
let connector_account_details: hyperswitch_domain_models::router_data::ConnectorAuthType =
item.connector_account_details
.clone()
.into_inner()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
// get the masked keys from the ConnectorAuthType and encode it to secret value
let masked_connector_account_details = Secret::new(
connector_account_details
.get_masked_keys()
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode ConnectorAuthType")?,
);
let feature_metadata = item.feature_metadata.as_ref().map(|metadata| {
api_models::admin::MerchantConnectorAccountFeatureMetadata::foreign_from(metadata)
});
let response = Self {
id: item.get_id(),
connector_type: item.connector_type,
connector_name: item.connector_name,
connector_label: item.connector_label,
connector_account_details: masked_connector_account_details,
disabled: item.disabled,
payment_methods_enabled: item.payment_methods_enabled,
metadata: item.metadata,
frm_configs,
connector_webhook_details: item
.connector_webhook_details
.map(|webhook_details| {
serde_json::Value::parse_value(
webhook_details.expose(),
"MerchantConnectorWebhookDetails",
)
.attach_printable("Unable to deserialize connector_webhook_details")
.change_context(errors::ApiErrorResponse::InternalServerError)
})
.transpose()?,
profile_id: item.profile_id,
applepay_verified_domains: item.applepay_verified_domains,
pm_auth_config: item.pm_auth_config,
status: item.status,
additional_merchant_data: item
.additional_merchant_data
.map(|data| {
let data = data.into_inner();
serde_json::Value::parse_value::<router_types::AdditionalMerchantData>(
data.expose(),
"AdditionalMerchantData",
)
.attach_printable("Unable to deserialize additional_merchant_data")
.change_context(errors::ApiErrorResponse::InternalServerError)
})
.transpose()?
.map(api_models::admin::AdditionalMerchantData::foreign_from),
connector_wallets_details: item
.connector_wallets_details
.map(|data| {
data.into_inner()
.expose()
.parse_value::<api_models::admin::ConnectorWalletDetails>(
"ConnectorWalletDetails",
)
.attach_printable("Unable to deserialize connector_wallets_details")
.change_context(errors::ApiErrorResponse::InternalServerError)
})
.transpose()?,
feature_metadata,
};
Ok(response)
}
}
#[cfg(feature = "v1")]
impl ForeignFrom<storage::PaymentAttempt> for payments::PaymentAttemptResponse {
fn foreign_from(payment_attempt: storage::PaymentAttempt) -> Self {
let connector_transaction_id = payment_attempt
.get_connector_payment_id()
.map(ToString::to_string);
Self {
attempt_id: payment_attempt.attempt_id,
status: payment_attempt.status,
amount: payment_attempt.net_amount.get_order_amount(),
order_tax_amount: payment_attempt.net_amount.get_order_tax_amount(),
currency: payment_attempt.currency,
connector: payment_attempt.connector,
error_message: payment_attempt.error_reason,
payment_method: payment_attempt.payment_method,
connector_transaction_id,
capture_method: payment_attempt.capture_method,
authentication_type: payment_attempt.authentication_type,
created_at: payment_attempt.created_at,
modified_at: payment_attempt.modified_at,
cancellation_reason: payment_attempt.cancellation_reason,
mandate_id: payment_attempt.mandate_id,
error_code: payment_attempt.error_code,
payment_token: payment_attempt.payment_token,
connector_metadata: payment_attempt.connector_metadata,
payment_experience: payment_attempt.payment_experience,
payment_method_type: payment_attempt.payment_method_type,
reference_id: payment_attempt.connector_response_reference_id,
unified_code: payment_attempt.unified_code,
unified_message: payment_attempt.unified_message,
client_source: payment_attempt.client_source,
client_version: payment_attempt.client_version,
}
}
}
impl ForeignFrom<storage::Capture> for payments::CaptureResponse {
fn foreign_from(capture: storage::Capture) -> Self {
let connector_capture_id = capture.get_optional_connector_transaction_id().cloned();
Self {
capture_id: capture.capture_id,
status: capture.status,
amount: capture.amount,
currency: capture.currency,
connector: capture.connector,
authorized_attempt_id: capture.authorized_attempt_id,
connector_capture_id,
capture_sequence: capture.capture_sequence,
error_message: capture.error_message,
error_code: capture.error_code,
error_reason: capture.error_reason,
reference_id: capture.connector_response_reference_id,
}
}
}
#[cfg(feature = "payouts")]
impl ForeignFrom<&api_models::payouts::PayoutMethodData> for api_enums::PaymentMethodType {
fn foreign_from(value: &api_models::payouts::PayoutMethodData) -> Self {
match value {
api_models::payouts::PayoutMethodData::Bank(bank) => Self::foreign_from(bank),
api_models::payouts::PayoutMethodData::Card(_) => Self::Debit,
api_models::payouts::PayoutMethodData::Wallet(wallet) => Self::foreign_from(wallet),
api_models::payouts::PayoutMethodData::BankRedirect(bank_redirect) => {
Self::foreign_from(bank_redirect)
}
}
}
}
#[cfg(feature = "payouts")]
impl ForeignFrom<&api_models::payouts::Bank> for api_enums::PaymentMethodType {
fn foreign_from(value: &api_models::payouts::Bank) -> Self {
match value {
api_models::payouts::Bank::Ach(_) => Self::Ach,
api_models::payouts::Bank::Bacs(_) => Self::Bacs,
api_models::payouts::Bank::Sepa(_) => Self::SepaBankTransfer,
api_models::payouts::Bank::Pix(_) => Self::Pix,
}
}
}
#[cfg(feature = "payouts")]
impl ForeignFrom<&api_models::payouts::Wallet> for api_enums::PaymentMethodType {
fn foreign_from(value: &api_models::payouts::Wallet) -> Self {
match value {
api_models::payouts::Wallet::Paypal(_) => Self::Paypal,
api_models::payouts::Wallet::Venmo(_) => Self::Venmo,
api_models::payouts::Wallet::ApplePayDecrypt(_) => Self::ApplePay,
}
}
}
#[cfg(feature = "payouts")]
impl ForeignFrom<&api_models::payouts::BankRedirect> for api_enums::PaymentMethodType {
fn foreign_from(value: &api_models::payouts::BankRedirect) -> Self {
match value {
api_models::payouts::BankRedirect::Interac(_) => Self::Interac,
}
}
}
#[cfg(feature = "payouts")]
impl ForeignFrom<&api_models::payouts::PayoutMethodData> for api_enums::PaymentMethod {
fn foreign_from(value: &api_models::payouts::PayoutMethodData) -> Self {
match value {
api_models::payouts::PayoutMethodData::Bank(_) => Self::BankTransfer,
api_models::payouts::PayoutMethodData::Card(_) => Self::Card,
api_models::payouts::PayoutMethodData::Wallet(_) => Self::Wallet,
api_models::payouts::PayoutMethodData::BankRedirect(_) => Self::BankRedirect,
}
}
}
#[cfg(feature = "payouts")]
impl ForeignFrom<&api_models::payouts::PayoutMethodData> for api_models::enums::PayoutType {
fn foreign_from(value: &api_models::payouts::PayoutMethodData) -> Self {
match value {
api_models::payouts::PayoutMethodData::Bank(_) => Self::Bank,
api_models::payouts::PayoutMethodData::Card(_) => Self::Card,
api_models::payouts::PayoutMethodData::Wallet(_) => Self::Wallet,
api_models::payouts::PayoutMethodData::BankRedirect(_) => Self::BankRedirect,
}
}
}
#[cfg(feature = "payouts")]
impl ForeignFrom<api_models::enums::PayoutType> for api_enums::PaymentMethod {
fn foreign_from(value: api_models::enums::PayoutType) -> Self {
match value {
api_models::enums::PayoutType::Bank => Self::BankTransfer,
api_models::enums::PayoutType::Card => Self::Card,
api_models::enums::PayoutType::Wallet => Self::Wallet,
api_models::enums::PayoutType::BankRedirect => Self::BankRedirect,
}
}
}
#[cfg(feature = "payouts")]
impl ForeignTryFrom<api_enums::PaymentMethod> for api_models::enums::PayoutType {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(value: api_enums::PaymentMethod) -> Result<Self, Self::Error> {
match value {
api_enums::PaymentMethod::Card => Ok(Self::Card),
api_enums::PaymentMethod::BankTransfer => Ok(Self::Bank),
api_enums::PaymentMethod::Wallet => Ok(Self::Wallet),
_ => Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!("PaymentMethod {value:?} is not supported for payouts"),
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert PaymentMethod to PayoutType"),
}
}
}
#[cfg(feature = "v1")]
impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderPayload {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(headers: &HeaderMap) -> Result<Self, Self::Error> {
let payment_confirm_source: Option<api_enums::PaymentSource> =
get_header_value_by_key(X_PAYMENT_CONFIRM_SOURCE.into(), headers)?
.map(|source| {
source
.to_owned()
.parse_enum("PaymentSource")
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid data received in payment_confirm_source header"
.into(),
})
.attach_printable(
"Failed while paring PaymentConfirmSource header value to enum",
)
})
.transpose()?;
when(
payment_confirm_source.is_some_and(|payment_confirm_source| {
payment_confirm_source.is_for_internal_use_only()
}),
|| {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid data received in payment_confirm_source header".into(),
}))
},
)?;
let locale =
get_header_value_by_key(ACCEPT_LANGUAGE.into(), headers)?.map(|val| val.to_string());
let x_hs_latency = get_header_value_by_key(X_HS_LATENCY.into(), headers)
.map(|value| value == Some("true"))
.unwrap_or(false);
let client_source =
get_header_value_by_key(X_CLIENT_SOURCE.into(), headers)?.map(|val| val.to_string());
let client_version =
get_header_value_by_key(X_CLIENT_VERSION.into(), headers)?.map(|val| val.to_string());
let browser_name_str =
get_header_value_by_key(BROWSER_NAME.into(), headers)?.map(|val| val.to_string());
let browser_name: Option<api_enums::BrowserName> = browser_name_str.map(|browser_name| {
browser_name
.parse_enum("BrowserName")
.unwrap_or(api_enums::BrowserName::Unknown)
});
let x_client_platform_str =
get_header_value_by_key(X_CLIENT_PLATFORM.into(), headers)?.map(|val| val.to_string());
let x_client_platform: Option<api_enums::ClientPlatform> =
x_client_platform_str.map(|x_client_platform| {
x_client_platform
.parse_enum("ClientPlatform")
.unwrap_or(api_enums::ClientPlatform::Unknown)
});
let x_merchant_domain =
get_header_value_by_key(X_MERCHANT_DOMAIN.into(), headers)?.map(|val| val.to_string());
let x_app_id =
get_header_value_by_key(X_APP_ID.into(), headers)?.map(|val| val.to_string());
let x_redirect_uri =
get_header_value_by_key(X_REDIRECT_URI.into(), headers)?.map(|val| val.to_string());
let x_reference_id =
get_header_value_by_key(X_REFERENCE_ID.into(), headers)?.map(|val| val.to_string());
Ok(Self {
payment_confirm_source,
client_source,
client_version,
x_hs_latency: Some(x_hs_latency),
browser_name,
x_client_platform,
x_merchant_domain,
locale,
x_app_id,
x_redirect_uri,
x_reference_id,
})
}
}
#[cfg(feature = "v2")]
impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderPayload {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(headers: &HeaderMap) -> Result<Self, Self::Error> {
use std::str::FromStr;
use crate::headers::X_CLIENT_SECRET;
let payment_confirm_source: Option<api_enums::PaymentSource> =
get_header_value_by_key(X_PAYMENT_CONFIRM_SOURCE.into(), headers)?
.map(|source| {
source
.to_owned()
.parse_enum("PaymentSource")
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid data received in payment_confirm_source header"
.into(),
})
.attach_printable(
"Failed while paring PaymentConfirmSource header value to enum",
)
})
.transpose()?;
when(
payment_confirm_source.is_some_and(|payment_confirm_source| {
payment_confirm_source.is_for_internal_use_only()
}),
|| {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid data received in payment_confirm_source header".into(),
}))
},
)?;
let locale =
get_header_value_by_key(ACCEPT_LANGUAGE.into(), headers)?.map(|val| val.to_string());
let x_hs_latency = get_header_value_by_key(X_HS_LATENCY.into(), headers)
.map(|value| value == Some("true"))
.unwrap_or(false);
let client_source =
get_header_value_by_key(X_CLIENT_SOURCE.into(), headers)?.map(|val| val.to_string());
let client_version =
get_header_value_by_key(X_CLIENT_VERSION.into(), headers)?.map(|val| val.to_string());
let browser_name_str =
get_header_value_by_key(BROWSER_NAME.into(), headers)?.map(|val| val.to_string());
let browser_name: Option<api_enums::BrowserName> = browser_name_str.map(|browser_name| {
browser_name
.parse_enum("BrowserName")
.unwrap_or(api_enums::BrowserName::Unknown)
});
let x_client_platform_str =
get_header_value_by_key(X_CLIENT_PLATFORM.into(), headers)?.map(|val| val.to_string());
let x_client_platform: Option<api_enums::ClientPlatform> =
x_client_platform_str.map(|x_client_platform| {
x_client_platform
.parse_enum("ClientPlatform")
.unwrap_or(api_enums::ClientPlatform::Unknown)
});
let x_merchant_domain =
get_header_value_by_key(X_MERCHANT_DOMAIN.into(), headers)?.map(|val| val.to_string());
let x_app_id =
get_header_value_by_key(X_APP_ID.into(), headers)?.map(|val| val.to_string());
let x_redirect_uri =
get_header_value_by_key(X_REDIRECT_URI.into(), headers)?.map(|val| val.to_string());
let x_reference_id =
get_header_value_by_key(X_REFERENCE_ID.into(), headers)?.map(|val| val.to_string());
Ok(Self {
payment_confirm_source,
// client_source,
// client_version,
x_hs_latency: Some(x_hs_latency),
browser_name,
x_client_platform,
x_merchant_domain,
locale,
x_app_id,
x_redirect_uri,
x_reference_id,
})
}
}
#[cfg(feature = "v1")]
impl
ForeignTryFrom<(
Option<&storage::PaymentAttempt>,
Option<&storage::PaymentIntent>,
Option<&domain::Address>,
Option<&domain::Address>,
Option<&domain::Customer>,
)> for payments::PaymentsRequest
{
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(
value: (
Option<&storage::PaymentAttempt>,
Option<&storage::PaymentIntent>,
Option<&domain::Address>,
Option<&domain::Address>,
Option<&domain::Customer>,
),
) -> Result<Self, Self::Error> {
let (payment_attempt, payment_intent, shipping, billing, customer) = value;
// Populating the dynamic fields directly, for the cases where we have customer details stored in
// Payment Intent
let customer_details_from_pi = payment_intent
.and_then(|payment_intent| payment_intent.customer_details.clone())
.map(|customer_details| {
customer_details
.into_inner()
.peek()
.clone()
.parse_value::<CustomerData>("CustomerData")
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "customer_details",
})
.attach_printable("Failed to parse customer_details")
})
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "customer_details",
})?;
let mut billing_address = billing
.map(hyperswitch_domain_models::address::Address::from)
.map(api_types::Address::from);
// This change is to fix a merchant integration
// If billing.email is not passed by the merchant, and if the customer email is present, then use the `customer.email` as the billing email
if let Some(billing_address) = &mut billing_address {
billing_address.email = billing_address.email.clone().or_else(|| {
customer
.and_then(|cust| {
cust.email
.as_ref()
.map(|email| pii::Email::from(email.clone()))
})
.or(customer_details_from_pi.clone().and_then(|cd| cd.email))
});
} else {
billing_address = Some(payments::Address {
email: customer
.and_then(|cust| {
cust.email
.as_ref()
.map(|email| pii::Email::from(email.clone()))
})
.or(customer_details_from_pi.clone().and_then(|cd| cd.email)),
..Default::default()
});
}
Ok(Self {
currency: payment_attempt.map(|pa| pa.currency.unwrap_or_default()),
shipping: shipping
.map(hyperswitch_domain_models::address::Address::from)
.map(api_types::Address::from),
billing: billing_address,
amount: payment_attempt
.map(|pa| api_types::Amount::from(pa.net_amount.get_order_amount())),
email: customer
.and_then(|cust| cust.email.as_ref().map(|em| pii::Email::from(em.clone())))
.or(customer_details_from_pi.clone().and_then(|cd| cd.email)),
phone: customer
.and_then(|cust| cust.phone.as_ref().map(|p| p.clone().into_inner()))
.or(customer_details_from_pi.clone().and_then(|cd| cd.phone)),
name: customer
.and_then(|cust| cust.name.as_ref().map(|n| n.clone().into_inner()))
.or(customer_details_from_pi.clone().and_then(|cd| cd.name)),
..Self::default()
})
}
}
impl ForeignFrom<(storage::PaymentLink, payments::PaymentLinkStatus)>
for payments::RetrievePaymentLinkResponse
{
fn foreign_from(
(payment_link_config, status): (storage::PaymentLink, payments::PaymentLinkStatus),
) -> Self {
Self {
payment_link_id: payment_link_config.payment_link_id,
merchant_id: payment_link_config.merchant_id,
link_to_pay: payment_link_config.link_to_pay,
amount: payment_link_config.amount,
created_at: payment_link_config.created_at,
expiry: payment_link_config.fulfilment_time,
description: payment_link_config.description,
currency: payment_link_config.currency,
status,
secure_link: payment_link_config.secure_link,
}
}
}
impl From<domain::Address> for payments::AddressDetails {
fn from(addr: domain::Address) -> Self {
Self {
city: addr.city,
country: addr.country,
line1: addr.line1.map(Encryptable::into_inner),
line2: addr.line2.map(Encryptable::into_inner),
line3: addr.line3.map(Encryptable::into_inner),
zip: addr.zip.map(Encryptable::into_inner),
state: addr.state.map(Encryptable::into_inner),
first_name: addr.first_name.map(Encryptable::into_inner),
last_name: addr.last_name.map(Encryptable::into_inner),
origin_zip: addr.origin_zip.map(Encryptable::into_inner),
}
}
}
impl ForeignFrom<ConnectorSelection> for routing_types::StaticRoutingAlgorithm {
fn foreign_from(value: ConnectorSelection) -> Self {
match value {
ConnectorSelection::Priority(connectors) => Self::Priority(connectors),
ConnectorSelection::VolumeSplit(splits) => Self::VolumeSplit(splits),
}
}
}
impl ForeignFrom<api_models::organization::OrganizationNew>
for diesel_models::organization::OrganizationNew
{
fn foreign_from(item: api_models::organization::OrganizationNew) -> Self {
Self::new(item.org_id, item.org_type, item.org_name)
}
}
impl ForeignFrom<api_models::organization::OrganizationCreateRequest>
for diesel_models::organization::OrganizationNew
{
fn foreign_from(item: api_models::organization::OrganizationCreateRequest) -> Self {
// Create a new organization with a standard type by default
let org_new = api_models::organization::OrganizationNew::new(
common_enums::OrganizationType::Standard,
None,
);
let api_models::organization::OrganizationCreateRequest {
organization_name,
organization_details,
metadata,
} = item;
let mut org_new_db = Self::new(org_new.org_id, org_new.org_type, Some(organization_name));
org_new_db.organization_details = organization_details;
org_new_db.metadata = metadata;
org_new_db
}
}
impl ForeignFrom<gsm_api_types::GsmCreateRequest>
for hyperswitch_domain_models::gsm::GatewayStatusMap
{
fn foreign_from(value: gsm_api_types::GsmCreateRequest) -> Self {
let inferred_feature_data = common_types::domain::GsmFeatureData::foreign_from(&value);
Self {
connector: value.connector.to_string(),
flow: value.flow,
sub_flow: value.sub_flow,
code: value.code,
message: value.message,
status: value.status,
router_error: value.router_error,
unified_code: value.unified_code,
unified_message: value.unified_message,
error_category: value.error_category,
feature_data: value.feature_data.unwrap_or(inferred_feature_data),
feature: value.feature.unwrap_or(api_enums::GsmFeature::Retry),
}
}
}
impl ForeignFrom<&gsm_api_types::GsmCreateRequest> for common_types::domain::GsmFeatureData {
fn foreign_from(value: &gsm_api_types::GsmCreateRequest) -> Self {
// Defaulting alternate_network_possible to false as it is provided only in the Retry feature
// If the retry feature is not used, we assume alternate network as false
let alternate_network_possible = false;
match value.feature {
Some(api_enums::GsmFeature::Retry) | None => {
Self::Retry(common_types::domain::RetryFeatureData {
step_up_possible: value.step_up_possible,
clear_pan_possible: value.clear_pan_possible,
alternate_network_possible,
decision: value.decision,
})
}
}
}
}
impl
ForeignFrom<(
&gsm_api_types::GsmUpdateRequest,
hyperswitch_domain_models::gsm::GatewayStatusMap,
)> for (api_enums::GsmFeature, common_types::domain::GsmFeatureData)
{
fn foreign_from(
(gsm_update_request, gsm_db_record): (
&gsm_api_types::GsmUpdateRequest,
hyperswitch_domain_models::gsm::GatewayStatusMap,
),
) -> Self {
let gsm_db_record_inferred_feature = match gsm_db_record.feature_data.get_decision() {
api_enums::GsmDecision::Retry | api_enums::GsmDecision::DoDefault => {
api_enums::GsmFeature::Retry
}
};
let gsm_feature = gsm_update_request
.feature
.unwrap_or(gsm_db_record_inferred_feature);
match gsm_feature {
api_enums::GsmFeature::Retry => {
let gsm_db_record_retry_feature_data =
gsm_db_record.feature_data.get_retry_feature_data();
let retry_feature_data = common_types::domain::GsmFeatureData::Retry(
common_types::domain::RetryFeatureData {
step_up_possible: gsm_update_request
.step_up_possible
.or(gsm_db_record_retry_feature_data
.clone()
.map(|data| data.step_up_possible))
.unwrap_or_default(),
clear_pan_possible: gsm_update_request
.clear_pan_possible
.or(gsm_db_record_retry_feature_data
.clone()
.map(|data| data.clear_pan_possible))
.unwrap_or_default(),
alternate_network_possible: gsm_db_record_retry_feature_data
.map(|data| data.alternate_network_possible)
.unwrap_or_default(),
decision: gsm_update_request
.decision
.or(Some(gsm_db_record.feature_data.get_decision()))
.unwrap_or_default(),
},
);
(api_enums::GsmFeature::Retry, retry_feature_data)
}
}
}
}
impl ForeignFrom<hyperswitch_domain_models::gsm::GatewayStatusMap> for gsm_api_types::GsmResponse {
fn foreign_from(value: hyperswitch_domain_models::gsm::GatewayStatusMap) -> Self {
Self {
connector: value.connector.to_string(),
flow: value.flow,
sub_flow: value.sub_flow,
code: value.code,
message: value.message,
decision: value.feature_data.get_decision(),
status: value.status,
router_error: value.router_error,
step_up_possible: value
.feature_data
.get_retry_feature_data()
.map(|data| 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(|data| data.is_clear_pan_possible())
.unwrap_or(false),
feature_data: Some(value.feature_data),
feature: value.feature,
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<&domain::Customer> for payments::CustomerDetailsResponse {
fn foreign_from(_customer: &domain::Customer) -> Self {
todo!()
}
}
#[cfg(feature = "v1")]
impl ForeignFrom<&domain::Customer> for payments::CustomerDetailsResponse {
fn foreign_from(customer: &domain::Customer) -> Self {
Self {
id: Some(customer.customer_id.clone()),
name: customer
.name
.as_ref()
.map(|name| name.get_inner().to_owned()),
email: customer.email.clone().map(Into::into),
phone: customer
.phone
.as_ref()
.map(|phone| phone.get_inner().to_owned()),
phone_country_code: customer.phone_country_code.clone(),
}
}
}
#[cfg(feature = "olap")]
impl ForeignTryFrom<api_types::webhook_events::EventListConstraints>
for api_types::webhook_events::EventListConstraintsInternal
{
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(
item: api_types::webhook_events::EventListConstraints,
) -> Result<Self, Self::Error> {
if item.object_id.is_some()
&& (item.created_after.is_some()
|| item.created_before.is_some()
|| item.limit.is_some()
|| item.offset.is_some()
|| item.event_classes.is_some()
|| item.event_types.is_some())
{
return Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message:
"Either only `object_id` must be specified, or one or more of \
`created_after`, `created_before`, `limit`, `offset`, `event_classes` and `event_types` must be specified"
.to_string()
}));
}
match item.object_id {
Some(object_id) => Ok(Self::ObjectIdFilter { object_id }),
None => Ok(Self::GenericFilter {
created_after: item.created_after,
created_before: item.created_before,
limit: item.limit.map(i64::from),
offset: item.offset.map(i64::from),
event_classes: item.event_classes,
event_types: item.event_types,
is_delivered: item.is_delivered,
}),
}
}
}
#[cfg(feature = "olap")]
impl TryFrom<domain::Event> for api_models::webhook_events::EventListItemResponse {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(item: domain::Event) -> Result<Self, Self::Error> {
use crate::utils::OptionExt;
// We only allow retrieving events with merchant_id, business_profile_id
// and initial_attempt_id populated.
// We cannot retrieve events with only some of these fields populated.
let merchant_id = item
.merchant_id
.get_required_value("merchant_id")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let profile_id = item
.business_profile_id
.get_required_value("business_profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let initial_attempt_id = item
.initial_attempt_id
.get_required_value("initial_attempt_id")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(Self {
event_id: item.event_id,
merchant_id,
profile_id,
object_id: item.primary_object_id,
event_type: item.event_type,
event_class: item.event_class,
is_delivery_successful: item.is_overall_delivery_successful,
initial_attempt_id,
created: item.created_at,
})
}
}
#[cfg(feature = "olap")]
impl TryFrom<domain::Event> for api_models::webhook_events::EventRetrieveResponse {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(item: domain::Event) -> Result<Self, Self::Error> {
use crate::utils::OptionExt;
// We only allow retrieving events with all required fields in `EventListItemResponse`, and
// `request` and `response` populated.
// We cannot retrieve events with only some of these fields populated.
let event_information =
api_models::webhook_events::EventListItemResponse::try_from(item.clone())?;
let request = item
.request
.get_required_value("request")
.change_context(errors::ApiErrorResponse::InternalServerError)?
.peek()
.parse_struct("OutgoingWebhookRequestContent")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse webhook event request information")?;
let response = item
.response
.get_required_value("response")
.change_context(errors::ApiErrorResponse::InternalServerError)?
.peek()
.parse_struct("OutgoingWebhookResponseContent")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse webhook event response information")?;
Ok(Self {
event_information,
request,
response,
delivery_attempt: item.delivery_attempt,
})
}
}
impl ForeignFrom<api_models::admin::AuthenticationConnectorDetails>
for diesel_models::business_profile::AuthenticationConnectorDetails
{
fn foreign_from(item: api_models::admin::AuthenticationConnectorDetails) -> Self {
Self {
authentication_connectors: item.authentication_connectors,
three_ds_requestor_url: item.three_ds_requestor_url,
three_ds_requestor_app_url: item.three_ds_requestor_app_url,
}
}
}
impl ForeignFrom<diesel_models::business_profile::AuthenticationConnectorDetails>
for api_models::admin::AuthenticationConnectorDetails
{
fn foreign_from(item: diesel_models::business_profile::AuthenticationConnectorDetails) -> Self {
Self {
authentication_connectors: item.authentication_connectors,
three_ds_requestor_url: item.three_ds_requestor_url,
three_ds_requestor_app_url: item.three_ds_requestor_app_url,
}
}
}
impl ForeignFrom<api_models::admin::ExternalVaultConnectorDetails>
for diesel_models::business_profile::ExternalVaultConnectorDetails
{
fn foreign_from(item: api_models::admin::ExternalVaultConnectorDetails) -> Self {
Self {
vault_connector_id: item.vault_connector_id,
vault_sdk: item.vault_sdk,
}
}
}
impl ForeignFrom<diesel_models::business_profile::ExternalVaultConnectorDetails>
for api_models::admin::ExternalVaultConnectorDetails
{
fn foreign_from(item: diesel_models::business_profile::ExternalVaultConnectorDetails) -> Self {
Self {
vault_connector_id: item.vault_connector_id,
vault_sdk: item.vault_sdk,
}
}
}
impl ForeignFrom<api_models::admin::CardTestingGuardConfig>
for diesel_models::business_profile::CardTestingGuardConfig
{
fn foreign_from(item: api_models::admin::CardTestingGuardConfig) -> Self {
Self {
is_card_ip_blocking_enabled: match item.card_ip_blocking_status {
api_models::admin::CardTestingGuardStatus::Enabled => true,
api_models::admin::CardTestingGuardStatus::Disabled => false,
},
card_ip_blocking_threshold: item.card_ip_blocking_threshold,
is_guest_user_card_blocking_enabled: match item.guest_user_card_blocking_status {
api_models::admin::CardTestingGuardStatus::Enabled => true,
api_models::admin::CardTestingGuardStatus::Disabled => false,
},
guest_user_card_blocking_threshold: item.guest_user_card_blocking_threshold,
is_customer_id_blocking_enabled: match item.customer_id_blocking_status {
api_models::admin::CardTestingGuardStatus::Enabled => true,
api_models::admin::CardTestingGuardStatus::Disabled => false,
},
customer_id_blocking_threshold: item.customer_id_blocking_threshold,
card_testing_guard_expiry: item.card_testing_guard_expiry,
}
}
}
impl ForeignFrom<diesel_models::business_profile::CardTestingGuardConfig>
for api_models::admin::CardTestingGuardConfig
{
fn foreign_from(item: diesel_models::business_profile::CardTestingGuardConfig) -> Self {
Self {
card_ip_blocking_status: match item.is_card_ip_blocking_enabled {
true => api_models::admin::CardTestingGuardStatus::Enabled,
false => api_models::admin::CardTestingGuardStatus::Disabled,
},
card_ip_blocking_threshold: item.card_ip_blocking_threshold,
guest_user_card_blocking_status: match item.is_guest_user_card_blocking_enabled {
true => api_models::admin::CardTestingGuardStatus::Enabled,
false => api_models::admin::CardTestingGuardStatus::Disabled,
},
guest_user_card_blocking_threshold: item.guest_user_card_blocking_threshold,
customer_id_blocking_status: match item.is_customer_id_blocking_enabled {
true => api_models::admin::CardTestingGuardStatus::Enabled,
false => api_models::admin::CardTestingGuardStatus::Disabled,
},
customer_id_blocking_threshold: item.customer_id_blocking_threshold,
card_testing_guard_expiry: item.card_testing_guard_expiry,
}
}
}
impl ForeignFrom<api_models::admin::WebhookDetails>
for diesel_models::business_profile::WebhookDetails
{
fn foreign_from(item: api_models::admin::WebhookDetails) -> Self {
Self {
webhook_version: item.webhook_version,
webhook_username: item.webhook_username,
webhook_password: item.webhook_password,
webhook_url: item.webhook_url,
payment_created_enabled: item.payment_created_enabled,
payment_failed_enabled: item.payment_failed_enabled,
payment_succeeded_enabled: item.payment_succeeded_enabled,
payment_statuses_enabled: item.payment_statuses_enabled,
refund_statuses_enabled: item.refund_statuses_enabled,
payout_statuses_enabled: item.payout_statuses_enabled,
multiple_webhooks_list: None,
}
}
}
impl ForeignFrom<diesel_models::business_profile::WebhookDetails>
for api_models::admin::WebhookDetails
{
fn foreign_from(item: diesel_models::business_profile::WebhookDetails) -> Self {
Self {
webhook_version: item.webhook_version,
webhook_username: item.webhook_username,
webhook_password: item.webhook_password,
webhook_url: item.webhook_url,
payment_created_enabled: item.payment_created_enabled,
payment_failed_enabled: item.payment_failed_enabled,
payment_succeeded_enabled: item.payment_succeeded_enabled,
payment_statuses_enabled: item.payment_statuses_enabled,
refund_statuses_enabled: item.refund_statuses_enabled,
payout_statuses_enabled: item.payout_statuses_enabled,
}
}
}
impl ForeignFrom<api_models::admin::BusinessPaymentLinkConfig>
for diesel_models::business_profile::BusinessPaymentLinkConfig
{
fn foreign_from(item: api_models::admin::BusinessPaymentLinkConfig) -> Self {
Self {
domain_name: item.domain_name,
default_config: item.default_config.map(ForeignInto::foreign_into),
business_specific_configs: item.business_specific_configs.map(|map| {
map.into_iter()
.map(|(k, v)| (k, v.foreign_into()))
.collect()
}),
allowed_domains: item.allowed_domains,
branding_visibility: item.branding_visibility,
}
}
}
impl ForeignFrom<diesel_models::business_profile::BusinessPaymentLinkConfig>
for api_models::admin::BusinessPaymentLinkConfig
{
fn foreign_from(item: diesel_models::business_profile::BusinessPaymentLinkConfig) -> Self {
Self {
domain_name: item.domain_name,
default_config: item.default_config.map(ForeignInto::foreign_into),
business_specific_configs: item.business_specific_configs.map(|map| {
map.into_iter()
.map(|(k, v)| (k, v.foreign_into()))
.collect()
}),
allowed_domains: item.allowed_domains,
branding_visibility: item.branding_visibility,
}
}
}
impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest>
for diesel_models::business_profile::PaymentLinkConfigRequest
{
fn foreign_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,
background_image: item
.background_image
.map(|background_image| background_image.foreign_into()),
payment_button_text: item.payment_button_text,
skip_status_screen: item.skip_status_screen,
custom_message_for_card_terms: item.custom_message_for_card_terms,
payment_button_colour: item.payment_button_colour,
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,
}
}
}
impl ForeignFrom<diesel_models::business_profile::PaymentLinkConfigRequest>
for api_models::admin::PaymentLinkConfigRequest
{
fn foreign_from(item: diesel_models::business_profile::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,
transaction_details: None,
details_layout: item.details_layout,
background_image: item
.background_image
.map(|background_image| background_image.foreign_into()),
payment_button_text: item.payment_button_text,
skip_status_screen: item.skip_status_screen,
custom_message_for_card_terms: item.custom_message_for_card_terms,
payment_button_colour: item.payment_button_colour,
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,
}
}
}
impl ForeignFrom<diesel_models::business_profile::PaymentLinkBackgroundImageConfig>
for api_models::admin::PaymentLinkBackgroundImageConfig
{
fn foreign_from(
item: diesel_models::business_profile::PaymentLinkBackgroundImageConfig,
) -> Self {
Self {
url: item.url,
position: item.position,
size: item.size,
}
}
}
impl ForeignFrom<api_models::admin::PaymentLinkBackgroundImageConfig>
for diesel_models::business_profile::PaymentLinkBackgroundImageConfig
{
fn foreign_from(item: api_models::admin::PaymentLinkBackgroundImageConfig) -> Self {
Self {
url: item.url,
position: item.position,
size: item.size,
}
}
}
impl ForeignFrom<api_models::admin::BusinessPayoutLinkConfig>
for diesel_models::business_profile::BusinessPayoutLinkConfig
{
fn foreign_from(item: api_models::admin::BusinessPayoutLinkConfig) -> Self {
Self {
config: item.config.foreign_into(),
form_layout: item.form_layout,
payout_test_mode: item.payout_test_mode,
}
}
}
impl ForeignFrom<diesel_models::business_profile::BusinessPayoutLinkConfig>
for api_models::admin::BusinessPayoutLinkConfig
{
fn foreign_from(item: diesel_models::business_profile::BusinessPayoutLinkConfig) -> Self {
Self {
config: item.config.foreign_into(),
form_layout: item.form_layout,
payout_test_mode: item.payout_test_mode,
}
}
}
impl ForeignFrom<api_models::admin::BusinessGenericLinkConfig>
for diesel_models::business_profile::BusinessGenericLinkConfig
{
fn foreign_from(item: api_models::admin::BusinessGenericLinkConfig) -> Self {
Self {
domain_name: item.domain_name,
allowed_domains: item.allowed_domains,
ui_config: item.ui_config,
}
}
}
impl ForeignFrom<diesel_models::business_profile::BusinessGenericLinkConfig>
for api_models::admin::BusinessGenericLinkConfig
{
fn foreign_from(item: diesel_models::business_profile::BusinessGenericLinkConfig) -> Self {
Self {
domain_name: item.domain_name,
allowed_domains: item.allowed_domains,
ui_config: item.ui_config,
}
}
}
impl ForeignFrom<card_info_types::CardInfoCreateRequest> for storage::CardInfo {
fn foreign_from(value: card_info_types::CardInfoCreateRequest) -> Self {
Self {
card_iin: value.card_iin,
card_issuer: value.card_issuer,
card_network: value.card_network,
card_type: value.card_type,
card_subtype: value.card_subtype,
card_issuing_country: value.card_issuing_country,
bank_code_id: value.bank_code_id,
bank_code: value.bank_code,
country_code: value.country_code,
date_created: common_utils::date_time::now(),
last_updated: Some(common_utils::date_time::now()),
last_updated_provider: value.last_updated_provider,
}
}
}
impl ForeignFrom<card_info_types::CardInfoUpdateRequest> for storage::CardInfo {
fn foreign_from(value: card_info_types::CardInfoUpdateRequest) -> Self {
Self {
card_iin: value.card_iin,
card_issuer: value.card_issuer,
card_network: value.card_network,
card_type: value.card_type,
card_subtype: value.card_subtype,
card_issuing_country: value.card_issuing_country,
bank_code_id: value.bank_code_id,
bank_code: value.bank_code,
country_code: value.country_code,
date_created: common_utils::date_time::now(),
last_updated: Some(common_utils::date_time::now()),
last_updated_provider: value.last_updated_provider,
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<&revenue_recovery_redis_operation::PaymentProcessorTokenStatus>
for payments::AdditionalCardInfo
{
fn foreign_from(value: &revenue_recovery_redis_operation::PaymentProcessorTokenStatus) -> Self {
let card_info = &value.payment_processor_token_details;
// TODO! All other card info fields needs to be populated in redis.
Self {
card_issuer: card_info.card_issuer.to_owned(),
card_network: card_info.card_network.to_owned(),
card_type: card_info.card_type.to_owned(),
card_issuing_country: None,
bank_code: None,
last4: card_info.last_four_digits.to_owned(),
card_isin: None,
card_extended_bin: None,
card_exp_month: card_info.expiry_month.to_owned(),
card_exp_year: card_info.expiry_year.to_owned(),
card_holder_name: None,
payment_checks: None,
authentication_data: None,
is_regulated: None,
signature_network: None,
}
}
}
|
crates/router/src/types/transformers.rs
|
router::src::types::transformers
| 19,614
| true
|
// File: crates/router/src/types/domain.rs
// Module: router::src::types::domain
pub mod behaviour {
pub use hyperswitch_domain_models::behaviour::{Conversion, ReverseConversion};
}
mod payment_attempt {
pub use hyperswitch_domain_models::payments::payment_attempt::*;
}
mod merchant_account {
pub use hyperswitch_domain_models::merchant_account::*;
}
#[cfg(feature = "v2")]
mod business_profile {
pub use hyperswitch_domain_models::business_profile::{
Profile, ProfileGeneralUpdate, ProfileSetter, ProfileUpdate,
};
}
#[cfg(feature = "v1")]
mod business_profile {
pub use hyperswitch_domain_models::business_profile::{
ExternalVaultDetails, Profile, ProfileGeneralUpdate, ProfileSetter, ProfileUpdate,
};
}
pub mod merchant_context {
pub use hyperswitch_domain_models::merchant_context::{Context, MerchantContext};
}
mod customers {
pub use hyperswitch_domain_models::customer::*;
}
pub mod callback_mapper {
pub use hyperswitch_domain_models::callback_mapper::CallbackMapper;
}
mod network_tokenization {
pub use hyperswitch_domain_models::network_tokenization::*;
}
pub use customers::*;
pub use merchant_account::*;
mod address;
mod event;
mod merchant_connector_account;
mod merchant_key_store {
pub use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;
}
pub use hyperswitch_domain_models::bulk_tokenization::*;
pub mod payment_methods {
pub use hyperswitch_domain_models::payment_methods::*;
}
pub mod consts {
pub use hyperswitch_domain_models::consts::*;
}
pub mod payment_method_data {
pub use hyperswitch_domain_models::payment_method_data::*;
}
pub mod authentication {
pub use hyperswitch_domain_models::router_request_types::authentication::*;
}
#[cfg(feature = "v2")]
pub mod vault {
pub use hyperswitch_domain_models::vault::*;
}
#[cfg(feature = "v2")]
pub mod tokenization {
pub use hyperswitch_domain_models::tokenization::*;
}
mod routing {
pub use hyperswitch_domain_models::routing::*;
}
pub mod payments;
pub mod types;
#[cfg(feature = "olap")]
pub mod user;
pub mod user_key_store;
pub use address::*;
pub use business_profile::*;
pub use callback_mapper::*;
pub use consts::*;
pub use event::*;
pub use merchant_connector_account::*;
pub use merchant_context::*;
pub use merchant_key_store::*;
pub use network_tokenization::*;
pub use payment_attempt::*;
pub use payment_method_data::*;
pub use payment_methods::*;
pub use routing::*;
#[cfg(feature = "v2")]
pub use tokenization::*;
#[cfg(feature = "olap")]
pub use user::*;
pub use user_key_store::*;
#[cfg(feature = "v2")]
pub use vault::*;
|
crates/router/src/types/domain.rs
|
router::src::types::domain
| 551
| true
|
// File: crates/router/src/types/authentication.rs
// Module: router::src::types::authentication
pub use hyperswitch_domain_models::{
router_request_types::authentication::{
AcquirerDetails, AuthNFlowType, ChallengeParams, ConnectorAuthenticationRequestData,
ConnectorPostAuthenticationRequestData, PreAuthNRequestData, PreAuthenticationData,
},
router_response_types::AuthenticationResponseData,
};
use super::{api, RouterData};
use crate::services;
pub type PreAuthNRouterData =
RouterData<api::PreAuthentication, PreAuthNRequestData, AuthenticationResponseData>;
pub type PreAuthNVersionCallRouterData =
RouterData<api::PreAuthenticationVersionCall, PreAuthNRequestData, AuthenticationResponseData>;
pub type ConnectorAuthenticationRouterData =
RouterData<api::Authentication, ConnectorAuthenticationRequestData, AuthenticationResponseData>;
pub type ConnectorPostAuthenticationRouterData = RouterData<
api::PostAuthentication,
ConnectorPostAuthenticationRequestData,
AuthenticationResponseData,
>;
pub type ConnectorAuthenticationType = dyn services::ConnectorIntegration<
api::Authentication,
ConnectorAuthenticationRequestData,
AuthenticationResponseData,
>;
pub type ConnectorPostAuthenticationType = dyn services::ConnectorIntegration<
api::PostAuthentication,
ConnectorPostAuthenticationRequestData,
AuthenticationResponseData,
>;
pub type ConnectorPreAuthenticationType = dyn services::ConnectorIntegration<
api::PreAuthentication,
PreAuthNRequestData,
AuthenticationResponseData,
>;
pub type ConnectorPreAuthenticationVersionCallType = dyn services::ConnectorIntegration<
api::PreAuthenticationVersionCall,
PreAuthNRequestData,
AuthenticationResponseData,
>;
|
crates/router/src/types/authentication.rs
|
router::src::types::authentication
| 336
| true
|
// File: crates/router/src/types/storage.rs
// Module: router::src::types::storage
pub mod address;
pub mod api_keys;
pub mod authentication;
pub mod authorization;
pub mod blocklist;
pub mod blocklist_fingerprint;
pub mod blocklist_lookup;
pub mod business_profile;
pub mod callback_mapper;
pub mod capture;
pub mod cards_info;
pub mod configs;
pub mod customers;
pub mod dashboard_metadata;
pub mod dispute;
pub mod dynamic_routing_stats;
pub mod enums;
pub mod ephemeral_key;
pub mod events;
pub mod file;
pub mod fraud_check;
pub mod generic_link;
pub mod gsm;
pub mod hyperswitch_ai_interaction;
#[cfg(feature = "kv_store")]
pub mod kv;
pub mod locker_mock_up;
pub mod mandate;
pub mod merchant_account;
pub mod merchant_connector_account;
pub mod merchant_key_store;
pub mod payment_attempt;
pub mod payment_link;
pub mod payment_method;
pub mod payout_attempt;
pub mod payouts;
pub mod refund;
#[cfg(feature = "v2")]
pub mod revenue_recovery;
#[cfg(feature = "v2")]
pub mod revenue_recovery_redis_operation;
pub mod reverse_lookup;
pub mod role;
pub mod routing_algorithm;
pub mod unified_translations;
pub mod user;
pub mod user_authentication_method;
pub mod user_role;
pub use diesel_models::{
process_tracker::business_status, ProcessTracker, ProcessTrackerNew, ProcessTrackerRunner,
ProcessTrackerUpdate,
};
#[cfg(feature = "v1")]
pub use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew;
#[cfg(feature = "payouts")]
pub use hyperswitch_domain_models::payouts::{
payout_attempt::{PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate},
payouts::{Payouts, PayoutsNew, PayoutsUpdate},
};
pub use hyperswitch_domain_models::{
payments::{
payment_attempt::{PaymentAttempt, PaymentAttemptUpdate},
payment_intent::{PaymentIntentUpdate, PaymentIntentUpdateFields},
PaymentIntent,
},
routing::{
PaymentRoutingInfo, PaymentRoutingInfoInner, PreRoutingConnectorChoice, RoutingData,
},
};
pub use scheduler::db::process_tracker;
pub use self::{
address::*, api_keys::*, authentication::*, authorization::*, blocklist::*,
blocklist_fingerprint::*, blocklist_lookup::*, business_profile::*, callback_mapper::*,
capture::*, cards_info::*, configs::*, customers::*, dashboard_metadata::*, dispute::*,
dynamic_routing_stats::*, ephemeral_key::*, events::*, file::*, fraud_check::*,
generic_link::*, gsm::*, hyperswitch_ai_interaction::*, locker_mock_up::*, mandate::*,
merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*,
payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*,
routing_algorithm::*, unified_translations::*, user::*, user_authentication_method::*,
user_role::*,
};
|
crates/router/src/types/storage.rs
|
router::src::types::storage
| 619
| true
|
// File: crates/router/src/types/api.rs
// Module: router::src::types::api
pub mod admin;
pub mod api_keys;
pub mod authentication;
pub mod configs;
#[cfg(feature = "olap")]
pub mod connector_onboarding;
pub mod customers;
pub mod disputes;
pub mod enums;
pub mod ephemeral_key;
pub mod files;
#[cfg(feature = "frm")]
pub mod fraud_check;
pub mod mandates;
pub mod payment_link;
pub mod payment_methods;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payouts;
pub mod poll;
pub mod refunds;
pub mod routing;
#[cfg(feature = "olap")]
pub mod verify_connector;
#[cfg(feature = "olap")]
pub mod webhook_events;
pub mod webhooks;
pub mod authentication_v2;
pub mod connector_mapping;
pub mod disputes_v2;
pub mod feature_matrix;
pub mod files_v2;
#[cfg(feature = "frm")]
pub mod fraud_check_v2;
pub mod payments_v2;
#[cfg(feature = "payouts")]
pub mod payouts_v2;
pub mod refunds_v2;
use std::{fmt::Debug, str::FromStr};
use api_models::routing::{self as api_routing, RoutableConnectorChoice};
use common_enums::RoutableConnectors;
use error_stack::ResultExt;
pub use hyperswitch_domain_models::router_flow_types::{
access_token_auth::{AccessTokenAuth, AccessTokenAuthentication},
mandate_revoke::MandateRevoke,
webhooks::VerifyWebhookSource,
};
pub use hyperswitch_interfaces::{
api::{
authentication::{
ConnectorAuthentication, ConnectorPostAuthentication, ConnectorPreAuthentication,
ConnectorPreAuthenticationVersionCall, ExternalAuthentication,
},
authentication_v2::{
ConnectorAuthenticationV2, ConnectorPostAuthenticationV2, ConnectorPreAuthenticationV2,
ConnectorPreAuthenticationVersionCallV2, ExternalAuthenticationV2,
},
fraud_check::FraudCheck,
revenue_recovery::{
BillingConnectorInvoiceSyncIntegration, BillingConnectorPaymentsSyncIntegration,
RevenueRecovery, RevenueRecoveryRecordBack,
},
revenue_recovery_v2::RevenueRecoveryV2,
BoxedConnector, Connector, ConnectorAccessToken, ConnectorAccessTokenV2,
ConnectorAuthenticationToken, ConnectorAuthenticationTokenV2, ConnectorCommon,
ConnectorCommonExt, ConnectorMandateRevoke, ConnectorMandateRevokeV2,
ConnectorTransactionId, ConnectorVerifyWebhookSource, ConnectorVerifyWebhookSourceV2,
CurrencyUnit,
},
connector_integration_v2::{BoxedConnectorV2, ConnectorV2},
};
use rustc_hash::FxHashMap;
#[cfg(feature = "frm")]
pub use self::fraud_check::*;
#[cfg(feature = "payouts")]
pub use self::payouts::*;
pub use self::{
admin::*, api_keys::*, authentication::*, configs::*, connector_mapping::*, customers::*,
disputes::*, files::*, payment_link::*, payment_methods::*, payments::*, poll::*, refunds::*,
refunds_v2::*, webhooks::*,
};
use super::transformers::ForeignTryFrom;
use crate::{
connector, consts,
core::{
errors::{self, CustomResult},
payments::types as payments_types,
},
services::connector_integration_interface::ConnectorEnum,
types::{self, api::enums as api_enums},
};
#[derive(Clone)]
pub enum ConnectorCallType {
PreDetermined(ConnectorRoutingData),
Retryable(Vec<ConnectorRoutingData>),
SessionMultiple(SessionConnectorDatas),
#[cfg(feature = "v2")]
Skip,
}
impl From<ConnectorData> for ConnectorRoutingData {
fn from(connector_data: ConnectorData) -> Self {
Self {
connector_data,
network: None,
action_type: None,
}
}
}
#[derive(Clone, Debug)]
pub struct SessionConnectorData {
pub payment_method_sub_type: api_enums::PaymentMethodType,
pub payment_method_type: api_enums::PaymentMethod,
pub connector: ConnectorData,
pub business_sub_label: Option<String>,
}
impl SessionConnectorData {
pub fn new(
payment_method_sub_type: api_enums::PaymentMethodType,
connector: ConnectorData,
business_sub_label: Option<String>,
payment_method_type: api_enums::PaymentMethod,
) -> Self {
Self {
payment_method_sub_type,
connector,
business_sub_label,
payment_method_type,
}
}
}
common_utils::create_list_wrapper!(
SessionConnectorDatas,
SessionConnectorData,
impl_functions: {
pub fn apply_filter_for_session_routing(&self) -> Self {
let routing_enabled_pmts = &consts::ROUTING_ENABLED_PAYMENT_METHOD_TYPES;
let routing_enabled_pms = &consts::ROUTING_ENABLED_PAYMENT_METHODS;
self
.iter()
.filter(|connector_data| {
routing_enabled_pmts.contains(&connector_data.payment_method_sub_type)
|| routing_enabled_pms.contains(&connector_data.payment_method_type)
})
.cloned()
.collect()
}
pub fn filter_and_validate_for_session_flow(self, routing_results: &FxHashMap<api_enums::PaymentMethodType, Vec<routing::SessionRoutingChoice>>) -> Result<Self, errors::ApiErrorResponse> {
let mut final_list = Self::new(Vec::new());
let routing_enabled_pmts = &consts::ROUTING_ENABLED_PAYMENT_METHOD_TYPES;
for connector_data in self {
if !routing_enabled_pmts.contains(&connector_data.payment_method_sub_type) {
final_list.push(connector_data);
} else if let Some(choice) = routing_results.get(&connector_data.payment_method_sub_type) {
let routing_choice = choice
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)?;
if connector_data.connector.connector_name == routing_choice.connector.connector_name
&& connector_data.connector.merchant_connector_id
== routing_choice.connector.merchant_connector_id
{
final_list.push(connector_data);
}
}
}
Ok(final_list)
}
}
);
pub fn convert_connector_data_to_routable_connectors(
connectors: &[ConnectorRoutingData],
) -> CustomResult<Vec<RoutableConnectorChoice>, common_utils::errors::ValidationError> {
connectors
.iter()
.map(|connectors_routing_data| {
RoutableConnectorChoice::foreign_try_from(
connectors_routing_data.connector_data.clone(),
)
})
.collect()
}
impl ForeignTryFrom<ConnectorData> for RoutableConnectorChoice {
type Error = error_stack::Report<common_utils::errors::ValidationError>;
fn foreign_try_from(from: ConnectorData) -> Result<Self, Self::Error> {
match RoutableConnectors::foreign_try_from(from.connector_name) {
Ok(connector) => Ok(Self {
choice_kind: api_routing::RoutableChoiceKind::FullStruct,
connector,
merchant_connector_id: from.merchant_connector_id,
}),
Err(e) => Err(common_utils::errors::ValidationError::InvalidValue {
message: format!("This is not a routable connector: {e:?}"),
})?,
}
}
}
/// Session Surcharge type
pub enum SessionSurchargeDetails {
/// Surcharge is calculated by hyperswitch
Calculated(payments_types::SurchargeMetadata),
/// Surcharge is sent by merchant
PreDetermined(payments_types::SurchargeDetails),
}
impl SessionSurchargeDetails {
pub fn fetch_surcharge_details(
&self,
payment_method: enums::PaymentMethod,
payment_method_type: enums::PaymentMethodType,
card_network: Option<&enums::CardNetwork>,
) -> Option<payments_types::SurchargeDetails> {
match self {
Self::Calculated(surcharge_metadata) => surcharge_metadata
.get_surcharge_details(payments_types::SurchargeKey::PaymentMethodData(
payment_method,
payment_method_type,
card_network.cloned(),
))
.cloned(),
Self::PreDetermined(surcharge_details) => Some(surcharge_details.clone()),
}
}
}
pub enum ConnectorChoice {
SessionMultiple(SessionConnectorDatas),
StraightThrough(serde_json::Value),
Decide,
}
#[cfg(test)]
mod test {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn test_convert_connector_parsing_success() {
let result = enums::Connector::from_str("aci");
assert!(result.is_ok());
assert_eq!(result.unwrap(), enums::Connector::Aci);
let result = enums::Connector::from_str("shift4");
assert!(result.is_ok());
assert_eq!(result.unwrap(), enums::Connector::Shift4);
let result = enums::Connector::from_str("authorizedotnet");
assert!(result.is_ok());
assert_eq!(result.unwrap(), enums::Connector::Authorizedotnet);
}
#[test]
fn test_convert_connector_parsing_fail_for_unknown_type() {
let result = enums::Connector::from_str("unknowntype");
assert!(result.is_err());
let result = enums::Connector::from_str("randomstring");
assert!(result.is_err());
}
#[test]
fn test_convert_connector_parsing_fail_for_camel_case() {
let result = enums::Connector::from_str("Paypal");
assert!(result.is_err());
let result = enums::Connector::from_str("Authorizedotnet");
assert!(result.is_err());
let result = enums::Connector::from_str("Opennode");
assert!(result.is_err());
}
}
#[derive(Clone)]
pub struct TaxCalculateConnectorData {
pub connector: ConnectorEnum,
pub connector_name: enums::TaxConnectors,
}
impl TaxCalculateConnectorData {
pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> {
let connector_name = enums::TaxConnectors::from_str(name)
.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
.attach_printable_lazy(|| format!("unable to parse connector: {name}"))?;
let connector = Self::convert_connector(connector_name)?;
Ok(Self {
connector,
connector_name,
})
}
fn convert_connector(
connector_name: enums::TaxConnectors,
) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> {
match connector_name {
enums::TaxConnectors::Taxjar => {
Ok(ConnectorEnum::Old(Box::new(connector::Taxjar::new())))
}
}
}
}
|
crates/router/src/types/api.rs
|
router::src::types::api
| 2,225
| true
|
// File: crates/router/src/types/pm_auth.rs
// Module: router::src::types::pm_auth
use std::str::FromStr;
use error_stack::ResultExt;
use pm_auth::{
connector::plaid,
types::{
self as pm_auth_types,
api::{BoxedPaymentAuthConnector, PaymentAuthConnectorData},
},
};
use crate::core::{
errors::{self, ApiErrorResponse},
pm_auth::helpers::PaymentAuthConnectorDataExt,
};
impl PaymentAuthConnectorDataExt for PaymentAuthConnectorData {
fn get_connector_by_name(name: &str) -> errors::CustomResult<Self, ApiErrorResponse> {
let connector_name = pm_auth_types::PaymentMethodAuthConnectors::from_str(name)
.change_context(ApiErrorResponse::IncorrectConnectorNameGiven)
.attach_printable_lazy(|| {
format!("unable to parse connector: {:?}", name.to_string())
})?;
let connector = Self::convert_connector(connector_name.clone())?;
Ok(Self {
connector,
connector_name,
})
}
fn convert_connector(
connector_name: pm_auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<BoxedPaymentAuthConnector, ApiErrorResponse> {
match connector_name {
pm_auth_types::PaymentMethodAuthConnectors::Plaid => Ok(Box::new(&plaid::Plaid)),
}
}
}
|
crates/router/src/types/pm_auth.rs
|
router::src::types::pm_auth
| 290
| true
|
// File: crates/router/src/types/storage/dynamic_routing_stats.rs
// Module: router::src::types::storage::dynamic_routing_stats
pub use diesel_models::dynamic_routing_stats::{
DynamicRoutingStats, DynamicRoutingStatsNew, DynamicRoutingStatsUpdate,
};
|
crates/router/src/types/storage/dynamic_routing_stats.rs
|
router::src::types::storage::dynamic_routing_stats
| 54
| true
|
// File: crates/router/src/types/storage/dispute.rs
// Module: router::src::types::storage::dispute
use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::errors::CustomResult;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl};
pub use diesel_models::dispute::{Dispute, DisputeNew, DisputeUpdate};
use diesel_models::{errors, query::generics::db_metrics, schema::dispute::dsl};
use error_stack::ResultExt;
use hyperswitch_domain_models::disputes;
use crate::{connection::PgPooledConn, logger};
#[async_trait::async_trait]
pub trait DisputeDbExt: Sized {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
dispute_list_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
async fn get_dispute_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::DatabaseError>;
}
#[async_trait::async_trait]
impl DisputeDbExt for Dispute {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
dispute_list_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.order(dsl::modified_at.desc())
.into_boxed();
let mut search_by_payment_or_dispute_id = false;
if let (Some(payment_id), Some(dispute_id)) = (
&dispute_list_constraints.payment_id,
&dispute_list_constraints.dispute_id,
) {
search_by_payment_or_dispute_id = true;
filter = filter.filter(
dsl::payment_id
.eq(payment_id.to_owned())
.or(dsl::dispute_id.eq(dispute_id.to_owned())),
);
};
if !search_by_payment_or_dispute_id {
if let Some(payment_id) = &dispute_list_constraints.payment_id {
filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));
};
}
if !search_by_payment_or_dispute_id {
if let Some(dispute_id) = &dispute_list_constraints.dispute_id {
filter = filter.filter(dsl::dispute_id.eq(dispute_id.clone()));
};
}
if let Some(time_range) = dispute_list_constraints.time_range {
filter = filter.filter(dsl::created_at.ge(time_range.start_time));
if let Some(end_time) = time_range.end_time {
filter = filter.filter(dsl::created_at.le(end_time));
}
}
if let Some(profile_id) = &dispute_list_constraints.profile_id {
filter = filter.filter(dsl::profile_id.eq_any(profile_id.clone()));
}
if let Some(connector_list) = &dispute_list_constraints.connector {
filter = filter.filter(dsl::connector.eq_any(connector_list.clone()));
}
if let Some(reason) = &dispute_list_constraints.reason {
filter = filter.filter(dsl::connector_reason.eq(reason.clone()));
}
if let Some(dispute_stage) = &dispute_list_constraints.dispute_stage {
filter = filter.filter(dsl::dispute_stage.eq_any(dispute_stage.clone()));
}
if let Some(dispute_status) = &dispute_list_constraints.dispute_status {
filter = filter.filter(dsl::dispute_status.eq_any(dispute_status.clone()));
}
if let Some(currency_list) = &dispute_list_constraints.currency {
filter = filter.filter(dsl::dispute_currency.eq_any(currency_list.clone()));
}
if let Some(merchant_connector_id) = &dispute_list_constraints.merchant_connector_id {
filter = filter.filter(dsl::merchant_connector_id.eq(merchant_connector_id.clone()))
}
if let Some(limit) = dispute_list_constraints.limit {
filter = filter.limit(limit.into());
}
if let Some(offset) = dispute_list_constraints.offset {
filter = filter.offset(offset.into());
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
filter.get_results_async(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering records by predicate")
}
async fn get_dispute_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::DatabaseError> {
let mut query = <Self as HasTable>::table()
.group_by(dsl::dispute_status)
.select((dsl::dispute_status, diesel::dsl::count_star()))
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.into_boxed();
if let Some(profile_id) = profile_id_list {
query = query.filter(dsl::profile_id.eq_any(profile_id));
}
query = query.filter(dsl::created_at.ge(time_range.start_time));
query = match time_range.end_time {
Some(ending_at) => query.filter(dsl::created_at.le(ending_at)),
None => query,
};
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
query.get_results_async::<(common_enums::DisputeStatus, i64)>(conn),
db_metrics::DatabaseOperation::Count,
)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering records by predicate")
}
}
|
crates/router/src/types/storage/dispute.rs
|
router::src::types::storage::dispute
| 1,411
| true
|
// File: crates/router/src/types/storage/kv.rs
// Module: router::src::types::storage::kv
pub use diesel_models::kv::{
AddressUpdateMems, DBOperation, Insertable, PaymentAttemptUpdateMems, PaymentIntentUpdateMems,
RefundUpdateMems, TypedSql, Updateable,
};
|
crates/router/src/types/storage/kv.rs
|
router::src::types::storage::kv
| 71
| true
|
// File: crates/router/src/types/storage/callback_mapper.rs
// Module: router::src::types::storage::callback_mapper
pub use diesel_models::callback_mapper::CallbackMapper;
|
crates/router/src/types/storage/callback_mapper.rs
|
router::src::types::storage::callback_mapper
| 37
| true
|
// File: crates/router/src/types/storage/role.rs
// Module: router::src::types::storage::role
pub use diesel_models::role::*;
|
crates/router/src/types/storage/role.rs
|
router::src::types::storage::role
| 32
| true
|
// File: crates/router/src/types/storage/payment_attempt.rs
// Module: router::src::types::storage::payment_attempt
use common_utils::types::MinorUnit;
use diesel_models::{capture::CaptureNew, enums};
use error_stack::ResultExt;
pub use hyperswitch_domain_models::payments::payment_attempt::{
PaymentAttempt, PaymentAttemptUpdate,
};
use crate::{
core::errors, errors::RouterResult, types::transformers::ForeignFrom, utils::OptionExt,
};
pub trait PaymentAttemptExt {
fn make_new_capture(
&self,
capture_amount: MinorUnit,
capture_status: enums::CaptureStatus,
) -> RouterResult<CaptureNew>;
fn get_next_capture_id(&self) -> String;
fn get_total_amount(&self) -> MinorUnit;
fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails>;
}
impl PaymentAttemptExt for PaymentAttempt {
#[cfg(feature = "v2")]
fn make_new_capture(
&self,
capture_amount: MinorUnit,
capture_status: enums::CaptureStatus,
) -> RouterResult<CaptureNew> {
todo!()
}
#[cfg(feature = "v1")]
fn make_new_capture(
&self,
capture_amount: MinorUnit,
capture_status: enums::CaptureStatus,
) -> RouterResult<CaptureNew> {
let capture_sequence = self.multiple_capture_count.unwrap_or_default() + 1;
let now = common_utils::date_time::now();
Ok(CaptureNew {
payment_id: self.payment_id.clone(),
merchant_id: self.merchant_id.clone(),
capture_id: self.get_next_capture_id(),
status: capture_status,
amount: capture_amount,
currency: self.currency,
connector: self
.connector
.clone()
.get_required_value("connector")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"connector field is required in payment_attempt to create a capture",
)?,
error_message: None,
tax_amount: None,
created_at: now,
modified_at: now,
error_code: None,
error_reason: None,
authorized_attempt_id: self.attempt_id.clone(),
capture_sequence,
connector_capture_id: None,
connector_response_reference_id: None,
processor_capture_data: None,
// Below fields are deprecated. Please add any new fields above this line.
connector_capture_data: None,
})
}
#[cfg(feature = "v1")]
fn get_next_capture_id(&self) -> String {
let next_sequence_number = self.multiple_capture_count.unwrap_or_default() + 1;
format!("{}_{}", self.attempt_id.clone(), next_sequence_number)
}
#[cfg(feature = "v2")]
fn get_next_capture_id(&self) -> String {
todo!()
}
#[cfg(feature = "v1")]
fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails> {
self.net_amount
.get_surcharge_amount()
.map(
|surcharge_amount| api_models::payments::RequestSurchargeDetails {
surcharge_amount,
tax_amount: self.net_amount.get_tax_on_surcharge(),
},
)
}
#[cfg(feature = "v2")]
fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails> {
todo!()
}
#[cfg(feature = "v1")]
fn get_total_amount(&self) -> MinorUnit {
self.net_amount.get_total_amount()
}
#[cfg(feature = "v2")]
fn get_total_amount(&self) -> MinorUnit {
todo!()
}
}
pub trait AttemptStatusExt {
fn maps_to_intent_status(self, intent_status: enums::IntentStatus) -> bool;
}
impl AttemptStatusExt for enums::AttemptStatus {
fn maps_to_intent_status(self, intent_status: enums::IntentStatus) -> bool {
enums::IntentStatus::foreign_from(self) == intent_status
}
}
#[cfg(test)]
#[cfg(all(
feature = "v1", // Ignoring tests for v2 since they aren't actively running
feature = "dummy_connector"
))]
mod tests {
#![allow(clippy::expect_used, clippy::unwrap_used, clippy::print_stderr)]
use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew;
use tokio::sync::oneshot;
use uuid::Uuid;
use crate::{
configs::settings::Settings,
db::StorageImpl,
routes, services,
types::{self, storage::enums},
};
async fn create_single_connection_test_transaction_pool() -> routes::AppState {
// Set pool size to 1 and minimum idle connection size to 0
std::env::set_var("ROUTER__MASTER_DATABASE__POOL_SIZE", "1");
std::env::set_var("ROUTER__MASTER_DATABASE__MIN_IDLE", "0");
std::env::set_var("ROUTER__REPLICA_DATABASE__POOL_SIZE", "1");
std::env::set_var("ROUTER__REPLICA_DATABASE__MIN_IDLE", "0");
let conf = Settings::new().expect("invalid settings");
let tx: oneshot::Sender<()> = oneshot::channel().0;
let api_client = Box::new(services::MockApiClient);
Box::pin(routes::AppState::with_storage(
conf,
StorageImpl::PostgresqlTest,
tx,
api_client,
))
.await
}
#[tokio::test]
async fn test_payment_attempt_insert() {
let state = create_single_connection_test_transaction_pool().await;
let payment_id =
common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();
let current_time = common_utils::date_time::now();
let connector = types::Connector::DummyConnector1.to_string();
let payment_attempt = PaymentAttemptNew {
payment_id: payment_id.clone(),
connector: Some(connector),
created_at: current_time.into(),
modified_at: current_time.into(),
merchant_id: Default::default(),
attempt_id: Default::default(),
status: Default::default(),
net_amount: Default::default(),
currency: Default::default(),
save_to_locker: Default::default(),
error_message: Default::default(),
offer_amount: Default::default(),
payment_method_id: Default::default(),
payment_method: Default::default(),
capture_method: Default::default(),
capture_on: Default::default(),
confirm: Default::default(),
authentication_type: Default::default(),
last_synced: Default::default(),
cancellation_reason: Default::default(),
amount_to_capture: Default::default(),
mandate_id: Default::default(),
browser_info: Default::default(),
payment_token: Default::default(),
error_code: Default::default(),
connector_metadata: Default::default(),
payment_experience: Default::default(),
payment_method_type: Default::default(),
payment_method_data: Default::default(),
business_sub_label: Default::default(),
straight_through_algorithm: Default::default(),
preprocessing_step_id: Default::default(),
mandate_details: Default::default(),
error_reason: Default::default(),
connector_response_reference_id: Default::default(),
multiple_capture_count: Default::default(),
amount_capturable: Default::default(),
updated_by: Default::default(),
authentication_data: Default::default(),
encoded_data: Default::default(),
merchant_connector_id: Default::default(),
unified_code: Default::default(),
unified_message: Default::default(),
external_three_ds_authentication_attempted: Default::default(),
authentication_connector: Default::default(),
authentication_id: Default::default(),
mandate_data: Default::default(),
payment_method_billing_address_id: Default::default(),
fingerprint_id: Default::default(),
client_source: Default::default(),
client_version: Default::default(),
customer_acceptance: Default::default(),
profile_id: common_utils::generate_profile_id_of_default_length(),
organization_id: Default::default(),
connector_mandate_detail: Default::default(),
request_extended_authorization: Default::default(),
extended_authorization_applied: Default::default(),
capture_before: Default::default(),
card_discovery: Default::default(),
processor_merchant_id: Default::default(),
created_by: None,
setup_future_usage_applied: Default::default(),
routing_approach: Default::default(),
connector_request_reference_id: Default::default(),
network_transaction_id: Default::default(),
network_details: Default::default(),
is_stored_credential: None,
authorized_amount: Default::default(),
};
let store = state
.stores
.get(state.conf.multitenancy.get_tenant_ids().first().unwrap())
.unwrap();
let response = store
.insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly)
.await
.unwrap();
eprintln!("{response:?}");
assert_eq!(response.payment_id, payment_id.clone());
}
#[tokio::test]
/// Example of unit test
/// Kind of test: state-based testing
async fn test_find_payment_attempt() {
let state = create_single_connection_test_transaction_pool().await;
let current_time = common_utils::date_time::now();
let payment_id =
common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();
let attempt_id = Uuid::new_v4().to_string();
let merchant_id = common_utils::id_type::MerchantId::new_from_unix_timestamp();
let connector = types::Connector::DummyConnector1.to_string();
let payment_attempt = PaymentAttemptNew {
payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
connector: Some(connector),
created_at: current_time.into(),
modified_at: current_time.into(),
attempt_id: attempt_id.clone(),
status: Default::default(),
net_amount: Default::default(),
currency: Default::default(),
save_to_locker: Default::default(),
error_message: Default::default(),
offer_amount: Default::default(),
payment_method_id: Default::default(),
payment_method: Default::default(),
capture_method: Default::default(),
capture_on: Default::default(),
confirm: Default::default(),
authentication_type: Default::default(),
last_synced: Default::default(),
cancellation_reason: Default::default(),
amount_to_capture: Default::default(),
mandate_id: Default::default(),
browser_info: Default::default(),
payment_token: Default::default(),
error_code: Default::default(),
connector_metadata: Default::default(),
payment_experience: Default::default(),
payment_method_type: Default::default(),
payment_method_data: Default::default(),
business_sub_label: Default::default(),
straight_through_algorithm: Default::default(),
preprocessing_step_id: Default::default(),
mandate_details: Default::default(),
error_reason: Default::default(),
connector_response_reference_id: Default::default(),
multiple_capture_count: Default::default(),
amount_capturable: Default::default(),
updated_by: Default::default(),
authentication_data: Default::default(),
encoded_data: Default::default(),
merchant_connector_id: Default::default(),
unified_code: Default::default(),
unified_message: Default::default(),
external_three_ds_authentication_attempted: Default::default(),
authentication_connector: Default::default(),
authentication_id: Default::default(),
mandate_data: Default::default(),
payment_method_billing_address_id: Default::default(),
fingerprint_id: Default::default(),
client_source: Default::default(),
client_version: Default::default(),
customer_acceptance: Default::default(),
profile_id: common_utils::generate_profile_id_of_default_length(),
organization_id: Default::default(),
connector_mandate_detail: Default::default(),
request_extended_authorization: Default::default(),
extended_authorization_applied: Default::default(),
capture_before: Default::default(),
card_discovery: Default::default(),
processor_merchant_id: Default::default(),
created_by: None,
setup_future_usage_applied: Default::default(),
routing_approach: Default::default(),
connector_request_reference_id: Default::default(),
network_transaction_id: Default::default(),
network_details: Default::default(),
is_stored_credential: Default::default(),
authorized_amount: Default::default(),
};
let store = state
.stores
.get(state.conf.multitenancy.get_tenant_ids().first().unwrap())
.unwrap();
store
.insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly)
.await
.unwrap();
let response = store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_id,
&merchant_id,
&attempt_id,
enums::MerchantStorageScheme::PostgresOnly,
)
.await
.unwrap();
eprintln!("{response:?}");
assert_eq!(response.payment_id, payment_id);
}
#[tokio::test]
/// Example of unit test
/// Kind of test: state-based testing
async fn test_payment_attempt_mandate_field() {
let state = create_single_connection_test_transaction_pool().await;
let uuid = Uuid::new_v4().to_string();
let merchant_id =
common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant1"))
.unwrap();
let payment_id =
common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();
let current_time = common_utils::date_time::now();
let connector = types::Connector::DummyConnector1.to_string();
let payment_attempt = PaymentAttemptNew {
payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
connector: Some(connector),
created_at: current_time.into(),
modified_at: current_time.into(),
mandate_id: Some("man_121212".to_string()),
attempt_id: uuid.clone(),
status: Default::default(),
net_amount: Default::default(),
currency: Default::default(),
save_to_locker: Default::default(),
error_message: Default::default(),
offer_amount: Default::default(),
payment_method_id: Default::default(),
payment_method: Default::default(),
capture_method: Default::default(),
capture_on: Default::default(),
confirm: Default::default(),
authentication_type: Default::default(),
last_synced: Default::default(),
cancellation_reason: Default::default(),
amount_to_capture: Default::default(),
browser_info: Default::default(),
payment_token: Default::default(),
error_code: Default::default(),
connector_metadata: Default::default(),
payment_experience: Default::default(),
payment_method_type: Default::default(),
payment_method_data: Default::default(),
business_sub_label: Default::default(),
straight_through_algorithm: Default::default(),
preprocessing_step_id: Default::default(),
mandate_details: Default::default(),
error_reason: Default::default(),
connector_response_reference_id: Default::default(),
multiple_capture_count: Default::default(),
amount_capturable: Default::default(),
updated_by: Default::default(),
authentication_data: Default::default(),
encoded_data: Default::default(),
merchant_connector_id: Default::default(),
unified_code: Default::default(),
unified_message: Default::default(),
external_three_ds_authentication_attempted: Default::default(),
authentication_connector: Default::default(),
authentication_id: Default::default(),
mandate_data: Default::default(),
payment_method_billing_address_id: Default::default(),
fingerprint_id: Default::default(),
client_source: Default::default(),
client_version: Default::default(),
customer_acceptance: Default::default(),
profile_id: common_utils::generate_profile_id_of_default_length(),
organization_id: Default::default(),
connector_mandate_detail: Default::default(),
request_extended_authorization: Default::default(),
extended_authorization_applied: Default::default(),
capture_before: Default::default(),
card_discovery: Default::default(),
processor_merchant_id: Default::default(),
created_by: None,
setup_future_usage_applied: Default::default(),
routing_approach: Default::default(),
connector_request_reference_id: Default::default(),
network_transaction_id: Default::default(),
network_details: Default::default(),
is_stored_credential: Default::default(),
authorized_amount: Default::default(),
};
let store = state
.stores
.get(state.conf.multitenancy.get_tenant_ids().first().unwrap())
.unwrap();
store
.insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly)
.await
.unwrap();
let response = store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_id,
&merchant_id,
&uuid,
enums::MerchantStorageScheme::PostgresOnly,
)
.await
.unwrap();
// checking it after fetch
assert_eq!(response.mandate_id, Some("man_121212".to_string()));
}
}
|
crates/router/src/types/storage/payment_attempt.rs
|
router::src::types::storage::payment_attempt
| 3,728
| true
|
// File: crates/router/src/types/storage/events.rs
// Module: router::src::types::storage::events
pub use diesel_models::events::{Event, EventMetadata, EventNew};
|
crates/router/src/types/storage/events.rs
|
router::src::types::storage::events
| 39
| true
|
// File: crates/router/src/types/storage/merchant_account.rs
// Module: router::src::types::storage::merchant_account
pub use diesel_models::merchant_account::{
MerchantAccount, MerchantAccountNew, MerchantAccountUpdateInternal,
};
pub use crate::types::domain::MerchantAccountUpdate;
|
crates/router/src/types/storage/merchant_account.rs
|
router::src::types::storage::merchant_account
| 61
| true
|
// File: crates/router/src/types/storage/payouts.rs
// Module: router::src::types::storage::payouts
pub use diesel_models::payouts::{Payouts, PayoutsNew, PayoutsUpdate, PayoutsUpdateInternal};
|
crates/router/src/types/storage/payouts.rs
|
router::src::types::storage::payouts
| 57
| true
|
// File: crates/router/src/types/storage/fraud_check.rs
// Module: router::src::types::storage::fraud_check
pub use diesel_models::fraud_check::{
FraudCheck, FraudCheckNew, FraudCheckUpdate, FraudCheckUpdateInternal,
};
|
crates/router/src/types/storage/fraud_check.rs
|
router::src::types::storage::fraud_check
| 55
| true
|
// File: crates/router/src/types/storage/revenue_recovery_redis_operation.rs
// Module: router::src::types::storage::revenue_recovery_redis_operation
use std::collections::HashMap;
use api_models::revenue_recovery_data_backfill::{self, RedisKeyType};
use common_enums::enums::CardNetwork;
use common_utils::{date_time, errors::CustomResult, id_type};
use error_stack::ResultExt;
use masking::{ExposeInterface, Secret};
use redis_interface::{DelReply, SetnxReply};
use router_env::{instrument, logger, tracing};
use serde::{Deserialize, Serialize};
use time::{Date, Duration, OffsetDateTime, PrimitiveDateTime};
use crate::{db::errors, types::storage::enums::RevenueRecoveryAlgorithmType, SessionState};
// Constants for retry window management
const RETRY_WINDOW_DAYS: i32 = 30;
const INITIAL_RETRY_COUNT: i32 = 0;
/// Payment processor token details including card information
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub struct PaymentProcessorTokenDetails {
pub payment_processor_token: String,
pub expiry_month: Option<Secret<String>>,
pub expiry_year: Option<Secret<String>>,
pub card_issuer: Option<String>,
pub last_four_digits: Option<String>,
pub card_network: Option<CardNetwork>,
pub card_type: Option<String>,
}
/// Represents the status and retry history of a payment processor token
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentProcessorTokenStatus {
/// Payment processor token details including card information and token ID
pub payment_processor_token_details: PaymentProcessorTokenDetails,
/// Payment intent ID that originally inserted this token
pub inserted_by_attempt_id: id_type::GlobalAttemptId,
/// Error code associated with the token failure
pub error_code: Option<String>,
/// Daily retry count history for the last 30 days (date -> retry_count)
pub daily_retry_history: HashMap<Date, i32>,
/// Scheduled time for the next retry attempt
pub scheduled_at: Option<PrimitiveDateTime>,
/// Indicates if the token is a hard decline (no retries allowed)
pub is_hard_decline: Option<bool>,
}
/// Token retry availability information with detailed wait times
#[derive(Debug, Clone)]
pub struct TokenRetryInfo {
pub monthly_wait_hours: i64, // Hours to wait for 30-day limit reset
pub daily_wait_hours: i64, // Hours to wait for daily limit reset
pub total_30_day_retries: i32, // Current total retry count in 30-day window
}
/// Complete token information with retry limits and wait times
#[derive(Debug, Clone)]
pub struct PaymentProcessorTokenWithRetryInfo {
/// The complete token status information
pub token_status: PaymentProcessorTokenStatus,
/// Hours to wait before next retry attempt (max of daily/monthly wait)
pub retry_wait_time_hours: i64,
/// Number of retries remaining in the 30-day rolling window
pub monthly_retry_remaining: i32,
// Current total retry count in 30-day window
pub total_30_day_retries: i32,
}
/// Redis-based token management struct
pub struct RedisTokenManager;
impl RedisTokenManager {
fn get_connector_customer_lock_key(connector_customer_id: &str) -> String {
format!("customer:{connector_customer_id}:status")
}
fn get_connector_customer_tokens_key(connector_customer_id: &str) -> String {
format!("customer:{connector_customer_id}:tokens")
}
/// Lock connector customer
#[instrument(skip_all)]
pub async fn lock_connector_customer_status(
state: &SessionState,
connector_customer_id: &str,
payment_id: &id_type::GlobalPaymentId,
) -> CustomResult<bool, errors::StorageError> {
let redis_conn =
state
.store
.get_redis_conn()
.change_context(errors::StorageError::RedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);
let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;
let result: bool = match redis_conn
.set_key_if_not_exists_with_expiry(
&lock_key.into(),
payment_id.get_string_repr(),
Some(*seconds),
)
.await
{
Ok(resp) => resp == SetnxReply::KeySet,
Err(error) => {
tracing::error!(operation = "lock_stream", err = ?error);
false
}
};
tracing::debug!(
connector_customer_id = connector_customer_id,
payment_id = payment_id.get_string_repr(),
lock_acquired = %result,
"Connector customer lock attempt"
);
Ok(result)
}
#[instrument(skip_all)]
pub async fn update_connector_customer_lock_ttl(
state: &SessionState,
connector_customer_id: &str,
exp_in_seconds: i64,
) -> CustomResult<bool, errors::StorageError> {
let redis_conn =
state
.store
.get_redis_conn()
.change_context(errors::StorageError::RedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);
let result: bool = redis_conn
.set_expiry(&lock_key.into(), exp_in_seconds)
.await
.map_or_else(
|error| {
tracing::error!(operation = "update_lock_ttl", err = ?error);
false
},
|_| true,
);
tracing::debug!(
connector_customer_id = connector_customer_id,
new_ttl_in_seconds = exp_in_seconds,
ttl_updated = %result,
"Connector customer lock TTL update with new expiry time"
);
Ok(result)
}
/// Unlock connector customer status
#[instrument(skip_all)]
pub async fn unlock_connector_customer_status(
state: &SessionState,
connector_customer_id: &str,
) -> CustomResult<bool, errors::StorageError> {
let redis_conn =
state
.store
.get_redis_conn()
.change_context(errors::StorageError::RedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);
match redis_conn.delete_key(&lock_key.into()).await {
Ok(DelReply::KeyDeleted) => {
tracing::debug!(
connector_customer_id = connector_customer_id,
"Connector customer unlocked"
);
Ok(true)
}
Ok(DelReply::KeyNotDeleted) => {
tracing::debug!("Tried to unlock a stream which is already unlocked");
Ok(false)
}
Err(err) => {
tracing::error!(?err, "Failed to delete lock key");
Ok(false)
}
}
}
/// Get all payment processor tokens for a connector customer
#[instrument(skip_all)]
pub async fn get_connector_customer_payment_processor_tokens(
state: &SessionState,
connector_customer_id: &str,
) -> CustomResult<HashMap<String, PaymentProcessorTokenStatus>, errors::StorageError> {
let redis_conn =
state
.store
.get_redis_conn()
.change_context(errors::StorageError::RedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);
let get_hash_err =
errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into());
let payment_processor_tokens: HashMap<String, String> = redis_conn
.get_hash_fields(&tokens_key.into())
.await
.change_context(get_hash_err)?;
let payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus> =
payment_processor_tokens
.into_iter()
.filter_map(|(token_id, token_data)| {
match serde_json::from_str::<PaymentProcessorTokenStatus>(&token_data) {
Ok(token_status) => Some((token_id, token_status)),
Err(err) => {
tracing::warn!(
connector_customer_id = %connector_customer_id,
token_id = %token_id,
error = %err,
"Failed to deserialize token data, skipping",
);
None
}
}
})
.collect();
tracing::debug!(
connector_customer_id = connector_customer_id,
"Fetched payment processor tokens",
);
Ok(payment_processor_token_info_map)
}
/// Update connector customer payment processor tokens or add if doesn't exist
#[instrument(skip_all)]
pub async fn update_or_add_connector_customer_payment_processor_tokens(
state: &SessionState,
connector_customer_id: &str,
payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus>,
) -> CustomResult<(), errors::StorageError> {
let redis_conn =
state
.store
.get_redis_conn()
.change_context(errors::StorageError::RedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);
// allocate capacity up-front to avoid rehashing
let mut serialized_payment_processor_tokens: HashMap<String, String> =
HashMap::with_capacity(payment_processor_token_info_map.len());
// serialize all tokens, preserving explicit error handling and attachable diagnostics
for (payment_processor_token_id, payment_processor_token_status) in
payment_processor_token_info_map
{
let serialized = serde_json::to_string(&payment_processor_token_status)
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Failed to serialize token status")?;
serialized_payment_processor_tokens.insert(payment_processor_token_id, serialized);
}
let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;
// Update or add tokens
redis_conn
.set_hash_fields(
&tokens_key.into(),
serialized_payment_processor_tokens,
Some(*seconds),
)
.await
.change_context(errors::StorageError::RedisError(
errors::RedisError::SetHashFieldFailed.into(),
))?;
tracing::info!(
connector_customer_id = %connector_customer_id,
"Successfully updated or added customer tokens",
);
Ok(())
}
/// Get current date in `yyyy-mm-dd` format.
pub fn get_current_date() -> String {
let today = date_time::now().date();
let (year, month, day) = (today.year(), today.month(), today.day());
format!("{year:04}-{month:02}-{day:02}",)
}
/// Normalize retry window to exactly `RETRY_WINDOW_DAYS` days (today to `RETRY_WINDOW_DAYS - 1` days ago).
pub fn normalize_retry_window(
payment_processor_token: &mut PaymentProcessorTokenStatus,
today: Date,
) {
let mut normalized_retry_history: HashMap<Date, i32> = HashMap::new();
for days_ago in 0..RETRY_WINDOW_DAYS {
let date = today - Duration::days(days_ago.into());
payment_processor_token
.daily_retry_history
.get(&date)
.map(|&retry_count| {
normalized_retry_history.insert(date, retry_count);
});
}
payment_processor_token.daily_retry_history = normalized_retry_history;
}
/// Get all payment processor tokens with retry information and wait times.
pub fn get_tokens_with_retry_metadata(
state: &SessionState,
payment_processor_token_info_map: &HashMap<String, PaymentProcessorTokenStatus>,
) -> HashMap<String, PaymentProcessorTokenWithRetryInfo> {
let today = OffsetDateTime::now_utc().date();
let card_config = &state.conf.revenue_recovery.card_config;
let mut result: HashMap<String, PaymentProcessorTokenWithRetryInfo> =
HashMap::with_capacity(payment_processor_token_info_map.len());
for (payment_processor_token_id, payment_processor_token_status) in
payment_processor_token_info_map.iter()
{
let card_network = payment_processor_token_status
.payment_processor_token_details
.card_network
.clone();
// Calculate retry information.
let retry_info = Self::payment_processor_token_retry_info(
state,
payment_processor_token_status,
today,
card_network.clone(),
);
// Determine the wait time (max of monthly and daily wait hours).
let retry_wait_time_hours = retry_info
.monthly_wait_hours
.max(retry_info.daily_wait_hours);
// Obtain network-specific limits and compute remaining monthly retries.
let card_network_config = card_config.get_network_config(card_network);
let monthly_retry_remaining = std::cmp::max(
0,
card_network_config.max_retry_count_for_thirty_day
- retry_info.total_30_day_retries,
);
// Build the per-token result struct.
let token_with_retry_info = PaymentProcessorTokenWithRetryInfo {
token_status: payment_processor_token_status.clone(),
retry_wait_time_hours,
monthly_retry_remaining,
total_30_day_retries: retry_info.total_30_day_retries,
};
result.insert(payment_processor_token_id.clone(), token_with_retry_info);
}
tracing::debug!("Fetched payment processor tokens with retry metadata",);
result
}
/// Sum retries over exactly the last 30 days
fn calculate_total_30_day_retries(token: &PaymentProcessorTokenStatus, today: Date) -> i32 {
(0..RETRY_WINDOW_DAYS)
.map(|i| {
let date = today - Duration::days(i.into());
token
.daily_retry_history
.get(&date)
.copied()
.unwrap_or(INITIAL_RETRY_COUNT)
})
.sum()
}
/// Calculate wait hours
fn calculate_wait_hours(target_date: Date, now: OffsetDateTime) -> i64 {
let expiry_time = target_date.midnight().assume_utc();
(expiry_time - now).whole_hours().max(0)
}
/// Calculate retry counts for exactly the last 30 days
pub fn payment_processor_token_retry_info(
state: &SessionState,
token: &PaymentProcessorTokenStatus,
today: Date,
network_type: Option<CardNetwork>,
) -> TokenRetryInfo {
let card_config = &state.conf.revenue_recovery.card_config;
let card_network_config = card_config.get_network_config(network_type);
let now = OffsetDateTime::now_utc();
let total_30_day_retries = Self::calculate_total_30_day_retries(token, today);
let monthly_wait_hours =
if total_30_day_retries >= card_network_config.max_retry_count_for_thirty_day {
(0..RETRY_WINDOW_DAYS)
.rev()
.map(|i| today - Duration::days(i.into()))
.find(|date| token.daily_retry_history.get(date).copied().unwrap_or(0) > 0)
.map(|date| Self::calculate_wait_hours(date + Duration::days(31), now))
.unwrap_or(0)
} else {
0
};
let today_retries = token
.daily_retry_history
.get(&today)
.copied()
.unwrap_or(INITIAL_RETRY_COUNT);
let daily_wait_hours = if today_retries >= card_network_config.max_retries_per_day {
Self::calculate_wait_hours(today + Duration::days(1), now)
} else {
0
};
TokenRetryInfo {
monthly_wait_hours,
daily_wait_hours,
total_30_day_retries,
}
}
// Upsert payment processor token
#[instrument(skip_all)]
pub async fn upsert_payment_processor_token(
state: &SessionState,
connector_customer_id: &str,
token_data: PaymentProcessorTokenStatus,
) -> CustomResult<bool, errors::StorageError> {
let mut token_map =
Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)
.await?;
let token_id = token_data
.payment_processor_token_details
.payment_processor_token
.clone();
let was_existing = token_map.contains_key(&token_id);
let error_code = token_data.error_code.clone();
let today = OffsetDateTime::now_utc().date();
token_map
.get_mut(&token_id)
.map(|existing_token| {
error_code.map(|err| existing_token.error_code = Some(err));
Self::normalize_retry_window(existing_token, today);
for (date, &value) in &token_data.daily_retry_history {
existing_token
.daily_retry_history
.entry(*date)
.and_modify(|v| *v += value)
.or_insert(value);
}
})
.or_else(|| {
token_map.insert(token_id.clone(), token_data);
None
});
Self::update_or_add_connector_customer_payment_processor_tokens(
state,
connector_customer_id,
token_map,
)
.await?;
tracing::debug!(
connector_customer_id = connector_customer_id,
"Upsert payment processor tokens",
);
Ok(!was_existing)
}
// Update payment processor token error code with billing connector response
#[instrument(skip_all)]
pub async fn update_payment_processor_token_error_code_from_process_tracker(
state: &SessionState,
connector_customer_id: &str,
error_code: &Option<String>,
is_hard_decline: &Option<bool>,
payment_processor_token_id: Option<&str>,
) -> CustomResult<bool, errors::StorageError> {
let today = OffsetDateTime::now_utc().date();
let updated_token = match payment_processor_token_id {
Some(token_id) => {
Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)
.await?
.values()
.find(|status| {
status
.payment_processor_token_details
.payment_processor_token
== token_id
})
.map(|status| PaymentProcessorTokenStatus {
payment_processor_token_details: status
.payment_processor_token_details
.clone(),
inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),
error_code: error_code.clone(),
daily_retry_history: status.daily_retry_history.clone(),
scheduled_at: None,
is_hard_decline: *is_hard_decline,
})
}
None => None,
};
match updated_token {
Some(mut token) => {
Self::normalize_retry_window(&mut token, today);
match token.error_code {
None => token.daily_retry_history.clear(),
Some(_) => {
let current_count = token
.daily_retry_history
.get(&today)
.copied()
.unwrap_or(INITIAL_RETRY_COUNT);
token.daily_retry_history.insert(today, current_count + 1);
}
}
let mut tokens_map = HashMap::new();
tokens_map.insert(
token
.payment_processor_token_details
.payment_processor_token
.clone(),
token.clone(),
);
Self::update_or_add_connector_customer_payment_processor_tokens(
state,
connector_customer_id,
tokens_map,
)
.await?;
tracing::debug!(
connector_customer_id = connector_customer_id,
"Updated payment processor tokens with error code",
);
Ok(true)
}
None => {
tracing::debug!(
connector_customer_id = connector_customer_id,
"No Token found with token id to update error code",
);
Ok(false)
}
}
}
// Update payment processor token schedule time
#[instrument(skip_all)]
pub async fn update_payment_processor_token_schedule_time(
state: &SessionState,
connector_customer_id: &str,
payment_processor_token: &str,
schedule_time: Option<PrimitiveDateTime>,
) -> CustomResult<bool, errors::StorageError> {
let updated_token =
Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)
.await?
.values()
.find(|status| {
status
.payment_processor_token_details
.payment_processor_token
== payment_processor_token
})
.map(|status| PaymentProcessorTokenStatus {
payment_processor_token_details: status.payment_processor_token_details.clone(),
inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),
error_code: status.error_code.clone(),
daily_retry_history: status.daily_retry_history.clone(),
scheduled_at: schedule_time,
is_hard_decline: status.is_hard_decline,
});
match updated_token {
Some(token) => {
let mut tokens_map = HashMap::new();
tokens_map.insert(
token
.payment_processor_token_details
.payment_processor_token
.clone(),
token.clone(),
);
Self::update_or_add_connector_customer_payment_processor_tokens(
state,
connector_customer_id,
tokens_map,
)
.await?;
tracing::debug!(
connector_customer_id = connector_customer_id,
"Updated payment processor tokens with schedule time",
);
Ok(true)
}
None => {
tracing::debug!(
connector_customer_id = connector_customer_id,
"payment processor tokens with not found",
);
Ok(false)
}
}
}
// Get payment processor token with schedule time
#[instrument(skip_all)]
pub async fn get_payment_processor_token_with_schedule_time(
state: &SessionState,
connector_customer_id: &str,
) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {
let tokens =
Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)
.await?;
let scheduled_token = tokens
.values()
.find(|status| status.scheduled_at.is_some())
.cloned();
tracing::debug!(
connector_customer_id = connector_customer_id,
"Fetched payment processor token with schedule time",
);
Ok(scheduled_token)
}
// Get payment processor token using token id
#[instrument(skip_all)]
pub async fn get_payment_processor_token_using_token_id(
state: &SessionState,
connector_customer_id: &str,
payment_processor_token: &str,
) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {
// Get all tokens for the customer
let tokens_map =
Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)
.await?;
let token_details = tokens_map.get(payment_processor_token).cloned();
tracing::debug!(
token_found = token_details.is_some(),
customer_id = connector_customer_id,
"Fetched payment processor token & Checked existence ",
);
Ok(token_details)
}
// Check if all tokens are hard declined or no token found for the customer
#[instrument(skip_all)]
pub async fn are_all_tokens_hard_declined(
state: &SessionState,
connector_customer_id: &str,
) -> CustomResult<bool, errors::StorageError> {
let tokens_map =
Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)
.await?;
let all_hard_declined = tokens_map
.values()
.all(|token| token.is_hard_decline.unwrap_or(false));
tracing::debug!(
connector_customer_id = connector_customer_id,
all_hard_declined,
"Checked if all tokens are hard declined or no token found for the customer",
);
Ok(all_hard_declined)
}
// Get token based on retry type
pub async fn get_token_based_on_retry_type(
state: &SessionState,
connector_customer_id: &str,
retry_algorithm_type: RevenueRecoveryAlgorithmType,
last_token_used: Option<&str>,
) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {
let mut token = None;
match retry_algorithm_type {
RevenueRecoveryAlgorithmType::Monitoring => {
logger::error!("Monitoring type found for Revenue Recovery retry payment");
}
RevenueRecoveryAlgorithmType::Cascading => {
token = match last_token_used {
Some(token_id) => {
Self::get_payment_processor_token_using_token_id(
state,
connector_customer_id,
token_id,
)
.await?
}
None => None,
};
}
RevenueRecoveryAlgorithmType::Smart => {
token = Self::get_payment_processor_token_with_schedule_time(
state,
connector_customer_id,
)
.await?;
}
}
token = token.and_then(|t| {
t.is_hard_decline
.unwrap_or(false)
.then(|| {
logger::error!("Token is hard declined");
})
.map_or(Some(t), |_| None)
});
Ok(token)
}
/// Get Redis key data for revenue recovery
#[instrument(skip_all)]
pub async fn get_redis_key_data_raw(
state: &SessionState,
connector_customer_id: &str,
key_type: &RedisKeyType,
) -> CustomResult<(bool, i64, Option<serde_json::Value>), errors::StorageError> {
let redis_conn =
state
.store
.get_redis_conn()
.change_context(errors::StorageError::RedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
let redis_key = match key_type {
RedisKeyType::Status => Self::get_connector_customer_lock_key(connector_customer_id),
RedisKeyType::Tokens => Self::get_connector_customer_tokens_key(connector_customer_id),
};
// Get TTL
let ttl = redis_conn
.get_ttl(&redis_key.clone().into())
.await
.map_err(|error| {
tracing::error!(operation = "get_ttl", err = ?error);
errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into())
})?;
// Get data based on key type and determine existence
let (key_exists, data) = match key_type {
RedisKeyType::Status => match redis_conn.get_key::<String>(&redis_key.into()).await {
Ok(status_value) => (true, serde_json::Value::String(status_value)),
Err(error) => {
tracing::error!(operation = "get_status_key", err = ?error);
(
false,
serde_json::Value::String(format!(
"Error retrieving status key: {}",
error
)),
)
}
},
RedisKeyType::Tokens => {
match redis_conn
.get_hash_fields::<HashMap<String, String>>(&redis_key.into())
.await
{
Ok(hash_fields) => {
let exists = !hash_fields.is_empty();
let data = if exists {
serde_json::to_value(hash_fields).unwrap_or(serde_json::Value::Null)
} else {
serde_json::Value::Object(serde_json::Map::new())
};
(exists, data)
}
Err(error) => {
tracing::error!(operation = "get_tokens_hash", err = ?error);
(false, serde_json::Value::Null)
}
}
}
};
tracing::debug!(
connector_customer_id = connector_customer_id,
key_type = ?key_type,
exists = key_exists,
ttl = ttl,
"Retrieved Redis key data"
);
Ok((key_exists, ttl, Some(data)))
}
/// Update Redis token with comprehensive card data
#[instrument(skip_all)]
pub async fn update_redis_token_with_comprehensive_card_data(
state: &SessionState,
customer_id: &str,
token: &str,
card_data: &revenue_recovery_data_backfill::ComprehensiveCardData,
cutoff_datetime: Option<PrimitiveDateTime>,
) -> CustomResult<(), errors::StorageError> {
// Get existing token data
let mut token_map =
Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;
// Find the token to update
let existing_token = token_map.get_mut(token).ok_or_else(|| {
tracing::warn!(
customer_id = customer_id,
"Token not found in parsed Redis data - may be corrupted or missing for "
);
error_stack::Report::new(errors::StorageError::ValueNotFound(
"Token not found in Redis".to_string(),
))
})?;
// Update the token details with new card data
card_data.card_type.as_ref().map(|card_type| {
existing_token.payment_processor_token_details.card_type = Some(card_type.clone())
});
card_data.card_exp_month.as_ref().map(|exp_month| {
existing_token.payment_processor_token_details.expiry_month = Some(exp_month.clone())
});
card_data.card_exp_year.as_ref().map(|exp_year| {
existing_token.payment_processor_token_details.expiry_year = Some(exp_year.clone())
});
card_data.card_network.as_ref().map(|card_network| {
existing_token.payment_processor_token_details.card_network = Some(card_network.clone())
});
card_data.card_issuer.as_ref().map(|card_issuer| {
existing_token.payment_processor_token_details.card_issuer = Some(card_issuer.clone())
});
// Update daily retry history if provided
card_data
.daily_retry_history
.as_ref()
.map(|retry_history| existing_token.daily_retry_history = retry_history.clone());
// If cutoff_datetime is provided and existing scheduled_at < cutoff_datetime, set to None
// If no scheduled_at value exists, leave it as None
existing_token.scheduled_at = existing_token
.scheduled_at
.and_then(|existing_scheduled_at| {
cutoff_datetime
.map(|cutoff| {
if existing_scheduled_at < cutoff {
tracing::info!(
customer_id = customer_id,
existing_scheduled_at = %existing_scheduled_at,
cutoff_datetime = %cutoff,
"Set scheduled_at to None because existing time is before cutoff time"
);
None
} else {
Some(existing_scheduled_at)
}
})
.unwrap_or(Some(existing_scheduled_at)) // No cutoff provided, keep existing value
});
// Save the updated token map back to Redis
Self::update_or_add_connector_customer_payment_processor_tokens(
state,
customer_id,
token_map,
)
.await?;
tracing::info!(
customer_id = customer_id,
"Updated Redis token data with comprehensive card data using struct"
);
Ok(())
}
}
|
crates/router/src/types/storage/revenue_recovery_redis_operation.rs
|
router::src::types::storage::revenue_recovery_redis_operation
| 6,544
| true
|
// File: crates/router/src/types/storage/cards_info.rs
// Module: router::src::types::storage::cards_info
pub use diesel_models::cards_info::{CardInfo, UpdateCardInfo};
|
crates/router/src/types/storage/cards_info.rs
|
router::src::types::storage::cards_info
| 41
| true
|
// File: crates/router/src/types/storage/payment_method.rs
// Module: router::src::types::storage::payment_method
use api_models::payment_methods;
use diesel_models::enums;
pub use diesel_models::payment_method::{
PaymentMethod, PaymentMethodNew, PaymentMethodUpdate, PaymentMethodUpdateInternal,
TokenizeCoreWorkflow,
};
use crate::types::{api, domain};
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PaymentTokenKind {
Temporary,
Permanent,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CardTokenData {
pub payment_method_id: Option<String>,
pub locker_id: Option<String>,
pub token: String,
pub network_token_locker_id: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CardTokenData {
pub payment_method_id: common_utils::id_type::GlobalPaymentMethodId,
pub locker_id: Option<String>,
pub token: String,
}
#[derive(Debug, Clone, serde::Serialize, Default, serde::Deserialize)]
pub struct PaymentMethodDataWithId {
pub payment_method: Option<enums::PaymentMethod>,
pub payment_method_data: Option<domain::PaymentMethodData>,
pub payment_method_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericTokenData {
pub token: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct WalletTokenData {
pub payment_method_id: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[cfg(feature = "v1")]
pub enum PaymentTokenData {
// The variants 'Temporary' and 'Permanent' are added for backwards compatibility
// with any tokenized data present in Redis at the time of deployment of this change
Temporary(GenericTokenData),
TemporaryGeneric(GenericTokenData),
Permanent(CardTokenData),
PermanentCard(CardTokenData),
AuthBankDebit(payment_methods::BankAccountTokenData),
WalletToken(WalletTokenData),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[cfg(feature = "v2")]
pub enum PaymentTokenData {
TemporaryGeneric(GenericTokenData),
PermanentCard(CardTokenData),
AuthBankDebit(payment_methods::BankAccountTokenData),
}
impl PaymentTokenData {
#[cfg(feature = "v1")]
pub fn permanent_card(
payment_method_id: Option<String>,
locker_id: Option<String>,
token: String,
network_token_locker_id: Option<String>,
) -> Self {
Self::PermanentCard(CardTokenData {
payment_method_id,
locker_id,
token,
network_token_locker_id,
})
}
#[cfg(feature = "v2")]
pub fn permanent_card(
payment_method_id: common_utils::id_type::GlobalPaymentMethodId,
locker_id: Option<String>,
token: String,
) -> Self {
Self::PermanentCard(CardTokenData {
payment_method_id,
locker_id,
token,
})
}
pub fn temporary_generic(token: String) -> Self {
Self::TemporaryGeneric(GenericTokenData { token })
}
#[cfg(feature = "v1")]
pub fn wallet_token(payment_method_id: String) -> Self {
Self::WalletToken(WalletTokenData { payment_method_id })
}
#[cfg(feature = "v1")]
pub fn is_permanent_card(&self) -> bool {
matches!(self, Self::PermanentCard(_) | Self::Permanent(_))
}
#[cfg(feature = "v2")]
pub fn is_permanent_card(&self) -> bool {
matches!(self, Self::PermanentCard(_))
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentMethodListContext {
pub card_details: Option<api::CardDetailFromLocker>,
pub hyperswitch_token_data: Option<PaymentTokenData>,
#[cfg(feature = "payouts")]
pub bank_transfer_details: Option<api::BankPayout>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum PaymentMethodListContext {
Card {
card_details: api::CardDetailFromLocker,
// TODO: Why can't these fields be mandatory?
token_data: Option<PaymentTokenData>,
},
Bank {
token_data: Option<PaymentTokenData>,
},
#[cfg(feature = "payouts")]
BankTransfer {
bank_transfer_details: api::BankPayout,
token_data: Option<PaymentTokenData>,
},
TemporaryToken {
token_data: Option<PaymentTokenData>,
},
}
#[cfg(feature = "v2")]
impl PaymentMethodListContext {
pub(crate) fn get_token_data(&self) -> Option<PaymentTokenData> {
match self {
Self::Card { token_data, .. }
| Self::Bank { token_data }
| Self::BankTransfer { token_data, .. }
| Self::TemporaryToken { token_data } => token_data.clone(),
}
}
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct PaymentMethodStatusTrackingData {
pub payment_method_id: String,
pub prev_status: enums::PaymentMethodStatus,
pub curr_status: enums::PaymentMethodStatus,
pub merchant_id: common_utils::id_type::MerchantId,
}
|
crates/router/src/types/storage/payment_method.rs
|
router::src::types::storage::payment_method
| 1,229
| true
|
// File: crates/router/src/types/storage/merchant_connector_account.rs
// Module: router::src::types::storage::merchant_connector_account
pub use diesel_models::merchant_connector_account::{
MerchantConnectorAccount, MerchantConnectorAccountNew, MerchantConnectorAccountUpdateInternal,
};
pub use crate::types::domain::MerchantConnectorAccountUpdate;
|
crates/router/src/types/storage/merchant_connector_account.rs
|
router::src::types::storage::merchant_connector_account
| 68
| true
|
// File: crates/router/src/types/storage/configs.rs
// Module: router::src::types::storage::configs
pub use diesel_models::configs::{Config, ConfigNew, ConfigUpdate, ConfigUpdateInternal};
|
crates/router/src/types/storage/configs.rs
|
router::src::types::storage::configs
| 44
| true
|
// File: crates/router/src/types/storage/blocklist_fingerprint.rs
// Module: router::src::types::storage::blocklist_fingerprint
pub use diesel_models::blocklist_fingerprint::{BlocklistFingerprint, BlocklistFingerprintNew};
|
crates/router/src/types/storage/blocklist_fingerprint.rs
|
router::src::types::storage::blocklist_fingerprint
| 51
| true
|
// File: crates/router/src/types/storage/routing_algorithm.rs
// Module: router::src::types::storage::routing_algorithm
pub use diesel_models::routing_algorithm::{
RoutingAlgorithm, RoutingAlgorithmMetadata, RoutingProfileMetadata,
};
|
crates/router/src/types/storage/routing_algorithm.rs
|
router::src::types::storage::routing_algorithm
| 48
| true
|
// File: crates/router/src/types/storage/address.rs
// Module: router::src::types::storage::address
pub use diesel_models::address::{Address, AddressNew, AddressUpdateInternal};
pub use crate::types::domain::AddressUpdate;
|
crates/router/src/types/storage/address.rs
|
router::src::types::storage::address
| 51
| true
|
// File: crates/router/src/types/storage/blocklist_lookup.rs
// Module: router::src::types::storage::blocklist_lookup
pub use diesel_models::blocklist_lookup::{BlocklistLookup, BlocklistLookupNew};
|
crates/router/src/types/storage/blocklist_lookup.rs
|
router::src::types::storage::blocklist_lookup
| 46
| true
|
// File: crates/router/src/types/storage/enums.rs
// Module: router::src::types::storage::enums
pub use diesel_models::enums::*;
|
crates/router/src/types/storage/enums.rs
|
router::src::types::storage::enums
| 32
| true
|
// File: crates/router/src/types/storage/blocklist.rs
// Module: router::src::types::storage::blocklist
pub use diesel_models::blocklist::{Blocklist, BlocklistNew};
|
crates/router/src/types/storage/blocklist.rs
|
router::src::types::storage::blocklist
| 41
| true
|
// File: crates/router/src/types/storage/user.rs
// Module: router::src::types::storage::user
pub use diesel_models::user::*;
|
crates/router/src/types/storage/user.rs
|
router::src::types::storage::user
| 31
| true
|
// File: crates/router/src/types/storage/user_role.rs
// Module: router::src::types::storage::user_role
pub use diesel_models::user_role::*;
|
crates/router/src/types/storage/user_role.rs
|
router::src::types::storage::user_role
| 34
| true
|
// File: crates/router/src/types/storage/locker_mock_up.rs
// Module: router::src::types::storage::locker_mock_up
pub use diesel_models::locker_mock_up::{LockerMockUp, LockerMockUpNew};
|
crates/router/src/types/storage/locker_mock_up.rs
|
router::src::types::storage::locker_mock_up
| 47
| true
|
// File: crates/router/src/types/storage/refund.rs
// Module: router::src::types::storage::refund
use api_models::payments::AmountFilter;
use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::errors::CustomResult;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl};
#[cfg(feature = "v1")]
use diesel_models::schema::refund::dsl;
#[cfg(feature = "v2")]
use diesel_models::schema_v2::refund::dsl;
use diesel_models::{
enums::{Currency, RefundStatus},
errors,
query::generics::db_metrics,
refund::Refund,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::refunds;
use crate::{connection::PgPooledConn, logger};
#[async_trait::async_trait]
pub trait RefundDbExt: Sized {
#[cfg(feature = "v1")]
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
limit: i64,
offset: i64,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
#[cfg(feature = "v2")]
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
limit: i64,
offset: i64,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
#[cfg(feature = "v1")]
async fn filter_by_meta_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &common_utils::types::TimeRange,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError>;
#[cfg(feature = "v1")]
async fn get_refunds_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError>;
#[cfg(feature = "v1")]
async fn get_refund_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError>;
#[cfg(feature = "v2")]
async fn get_refunds_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError>;
}
#[async_trait::async_trait]
impl RefundDbExt for Refund {
#[cfg(feature = "v1")]
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
limit: i64,
offset: i64,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.order(dsl::modified_at.desc())
.into_boxed();
let mut search_by_pay_or_ref_id = false;
if let (Some(pid), Some(ref_id)) = (
&refund_list_details.payment_id,
&refund_list_details.refund_id,
) {
search_by_pay_or_ref_id = true;
filter = filter
.filter(
dsl::payment_id
.eq(pid.to_owned())
.or(dsl::refund_id.eq(ref_id.to_owned())),
)
.limit(limit)
.offset(offset);
};
if !search_by_pay_or_ref_id {
match &refund_list_details.payment_id {
Some(pid) => {
filter = filter.filter(dsl::payment_id.eq(pid.to_owned()));
}
None => {
filter = filter.limit(limit).offset(offset);
}
};
}
if !search_by_pay_or_ref_id {
match &refund_list_details.refund_id {
Some(ref_id) => {
filter = filter.filter(dsl::refund_id.eq(ref_id.to_owned()));
}
None => {
filter = filter.limit(limit).offset(offset);
}
};
}
match &refund_list_details.profile_id {
Some(profile_id) => {
filter = filter
.filter(dsl::profile_id.eq_any(profile_id.to_owned()))
.limit(limit)
.offset(offset);
}
None => {
filter = filter.limit(limit).offset(offset);
}
};
if let Some(time_range) = refund_list_details.time_range {
filter = filter.filter(dsl::created_at.ge(time_range.start_time));
if let Some(end_time) = time_range.end_time {
filter = filter.filter(dsl::created_at.le(end_time));
}
}
filter = match refund_list_details.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => filter.filter(dsl::refund_amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.le(end)),
_ => filter,
};
if let Some(connector) = refund_list_details.connector.clone() {
filter = filter.filter(dsl::connector.eq_any(connector));
}
if let Some(merchant_connector_id) = refund_list_details.merchant_connector_id.clone() {
filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id));
}
if let Some(filter_currency) = &refund_list_details.currency {
filter = filter.filter(dsl::currency.eq_any(filter_currency.clone()));
}
if let Some(filter_refund_status) = &refund_list_details.refund_status {
filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status.clone()));
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
filter.get_results_async(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering records by predicate")
}
#[cfg(feature = "v2")]
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
limit: i64,
offset: i64,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.order(dsl::modified_at.desc())
.into_boxed();
if let Some(payment_id) = &refund_list_details.payment_id {
filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));
}
if let Some(refund_id) = &refund_list_details.refund_id {
filter = filter.filter(dsl::id.eq(refund_id.to_owned()));
}
if let Some(time_range) = &refund_list_details.time_range {
filter = filter.filter(dsl::created_at.ge(time_range.start_time));
if let Some(end_time) = time_range.end_time {
filter = filter.filter(dsl::created_at.le(end_time));
}
}
filter = match refund_list_details.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => filter.filter(dsl::refund_amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.le(end)),
_ => filter,
};
if let Some(connector) = refund_list_details.connector {
filter = filter.filter(dsl::connector.eq_any(connector));
}
if let Some(connector_id_list) = refund_list_details.connector_id_list {
filter = filter.filter(dsl::connector_id.eq_any(connector_id_list));
}
if let Some(filter_currency) = refund_list_details.currency {
filter = filter.filter(dsl::currency.eq_any(filter_currency));
}
if let Some(filter_refund_status) = refund_list_details.refund_status {
filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status));
}
filter = filter.limit(limit).offset(offset);
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
filter.get_results_async(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering records by predicate")
// todo!()
}
#[cfg(feature = "v1")]
async fn filter_by_meta_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &common_utils::types::TimeRange,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError> {
let start_time = refund_list_details.start_time;
let end_time = refund_list_details
.end_time
.unwrap_or_else(common_utils::date_time::now);
let filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.order(dsl::modified_at.desc())
.filter(dsl::created_at.ge(start_time))
.filter(dsl::created_at.le(end_time));
let filter_connector: Vec<String> = filter
.clone()
.select(dsl::connector)
.distinct()
.order_by(dsl::connector.asc())
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering records by connector")?;
let filter_currency: Vec<Currency> = filter
.clone()
.select(dsl::currency)
.distinct()
.order_by(dsl::currency.asc())
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering records by currency")?;
let filter_status: Vec<RefundStatus> = filter
.select(dsl::refund_status)
.distinct()
.order_by(dsl::refund_status.asc())
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering records by refund status")?;
let meta = api_models::refunds::RefundListMetaData {
connector: filter_connector,
currency: filter_currency,
refund_status: filter_status,
};
Ok(meta)
}
#[cfg(feature = "v1")]
async fn get_refunds_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.count()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.into_boxed();
let mut search_by_pay_or_ref_id = false;
if let (Some(pid), Some(ref_id)) = (
&refund_list_details.payment_id,
&refund_list_details.refund_id,
) {
search_by_pay_or_ref_id = true;
filter = filter.filter(
dsl::payment_id
.eq(pid.to_owned())
.or(dsl::refund_id.eq(ref_id.to_owned())),
);
};
if !search_by_pay_or_ref_id {
if let Some(pay_id) = &refund_list_details.payment_id {
filter = filter.filter(dsl::payment_id.eq(pay_id.to_owned()));
}
}
if !search_by_pay_or_ref_id {
if let Some(ref_id) = &refund_list_details.refund_id {
filter = filter.filter(dsl::refund_id.eq(ref_id.to_owned()));
}
}
if let Some(profile_id) = &refund_list_details.profile_id {
filter = filter.filter(dsl::profile_id.eq_any(profile_id.to_owned()));
}
if let Some(time_range) = refund_list_details.time_range {
filter = filter.filter(dsl::created_at.ge(time_range.start_time));
if let Some(end_time) = time_range.end_time {
filter = filter.filter(dsl::created_at.le(end_time));
}
}
filter = match refund_list_details.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => filter.filter(dsl::refund_amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.le(end)),
_ => filter,
};
if let Some(connector) = refund_list_details.connector.clone() {
filter = filter.filter(dsl::connector.eq_any(connector));
}
if let Some(merchant_connector_id) = refund_list_details.merchant_connector_id.clone() {
filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id))
}
if let Some(filter_currency) = &refund_list_details.currency {
filter = filter.filter(dsl::currency.eq_any(filter_currency.clone()));
}
if let Some(filter_refund_status) = &refund_list_details.refund_status {
filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status.clone()));
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
filter
.get_result_async::<i64>(conn)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering count of refunds")
}
#[cfg(feature = "v2")]
async fn get_refunds_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.count()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.into_boxed();
if let Some(payment_id) = &refund_list_details.payment_id {
filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));
}
if let Some(refund_id) = &refund_list_details.refund_id {
filter = filter.filter(dsl::id.eq(refund_id.to_owned()));
}
if let Some(time_range) = refund_list_details.time_range {
filter = filter.filter(dsl::created_at.ge(time_range.start_time));
if let Some(end_time) = time_range.end_time {
filter = filter.filter(dsl::created_at.le(end_time));
}
}
filter = match refund_list_details.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => filter.filter(dsl::refund_amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.le(end)),
_ => filter,
};
if let Some(connector) = refund_list_details.connector {
filter = filter.filter(dsl::connector.eq_any(connector));
}
if let Some(connector_id_list) = refund_list_details.connector_id_list {
filter = filter.filter(dsl::connector_id.eq_any(connector_id_list));
}
if let Some(filter_currency) = refund_list_details.currency {
filter = filter.filter(dsl::currency.eq_any(filter_currency));
}
if let Some(filter_refund_status) = refund_list_details.refund_status {
filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status));
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
filter
.get_result_async::<i64>(conn)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering count of refunds")
}
#[cfg(feature = "v1")]
async fn get_refund_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError> {
let mut query = <Self as HasTable>::table()
.group_by(dsl::refund_status)
.select((dsl::refund_status, diesel::dsl::count_star()))
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.into_boxed();
if let Some(profile_id) = profile_id_list {
query = query.filter(dsl::profile_id.eq_any(profile_id));
}
query = query.filter(dsl::created_at.ge(time_range.start_time));
query = match time_range.end_time {
Some(ending_at) => query.filter(dsl::created_at.le(ending_at)),
None => query,
};
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
query.get_results_async::<(RefundStatus, i64)>(conn),
db_metrics::DatabaseOperation::Count,
)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering status count of refunds")
}
}
|
crates/router/src/types/storage/refund.rs
|
router::src::types::storage::refund
| 4,166
| true
|
// File: crates/router/src/types/storage/business_profile.rs
// Module: router::src::types::storage::business_profile
pub use diesel_models::business_profile::{Profile, ProfileNew, ProfileUpdateInternal};
|
crates/router/src/types/storage/business_profile.rs
|
router::src::types::storage::business_profile
| 43
| true
|
// File: crates/router/src/types/storage/payment_link.rs
// Module: router::src::types::storage::payment_link
use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{associations::HasTable, ExpressionMethods, QueryDsl};
pub use diesel_models::{
payment_link::{PaymentLink, PaymentLinkNew},
schema::payment_link::dsl,
};
use error_stack::ResultExt;
use crate::{
connection::PgPooledConn,
core::errors::{self, CustomResult},
logger,
};
#[async_trait::async_trait]
pub trait PaymentLinkDbExt: Sized {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payment_link_list_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
}
#[async_trait::async_trait]
impl PaymentLinkDbExt for PaymentLink {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payment_link_list_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.order(dsl::created_at.desc())
.into_boxed();
if let Some(created_time) = payment_link_list_constraints.created {
filter = filter.filter(dsl::created_at.eq(created_time));
}
if let Some(created_time_lt) = payment_link_list_constraints.created_lt {
filter = filter.filter(dsl::created_at.lt(created_time_lt));
}
if let Some(created_time_gt) = payment_link_list_constraints.created_gt {
filter = filter.filter(dsl::created_at.gt(created_time_gt));
}
if let Some(created_time_lte) = payment_link_list_constraints.created_lte {
filter = filter.filter(dsl::created_at.le(created_time_lte));
}
if let Some(created_time_gte) = payment_link_list_constraints.created_gte {
filter = filter.filter(dsl::created_at.ge(created_time_gte));
}
if let Some(limit) = payment_link_list_constraints.limit {
filter = filter.limit(limit);
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
filter
.get_results_async(conn)
.await
// The query built here returns an empty Vec when no records are found, and if any error does occur,
// it would be an internal database error, due to which we are raising a DatabaseError::Unknown error
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering payment link by specified constraints")
}
}
|
crates/router/src/types/storage/payment_link.rs
|
router::src::types::storage::payment_link
| 614
| true
|
// File: crates/router/src/types/storage/generic_link.rs
// Module: router::src::types::storage::generic_link
pub use diesel_models::generic_link::{
GenericLink, GenericLinkData, GenericLinkNew, GenericLinkState, GenericLinkUpdateInternal,
PaymentMethodCollectLink, PayoutLink, PayoutLinkUpdate,
};
|
crates/router/src/types/storage/generic_link.rs
|
router::src::types::storage::generic_link
| 72
| true
|
// File: crates/router/src/types/storage/unified_translations.rs
// Module: router::src::types::storage::unified_translations
pub use diesel_models::unified_translations::{
UnifiedTranslations, UnifiedTranslationsNew, UnifiedTranslationsUpdate,
UnifiedTranslationsUpdateInternal,
};
|
crates/router/src/types/storage/unified_translations.rs
|
router::src::types::storage::unified_translations
| 59
| true
|
// File: crates/router/src/types/storage/api_keys.rs
// Module: router::src::types::storage::api_keys
#[cfg(feature = "email")]
pub use diesel_models::api_keys::ApiKeyExpiryTrackingData;
pub use diesel_models::api_keys::{ApiKey, ApiKeyNew, ApiKeyUpdate, HashedApiKey};
|
crates/router/src/types/storage/api_keys.rs
|
router::src::types::storage::api_keys
| 69
| true
|
// File: crates/router/src/types/storage/dashboard_metadata.rs
// Module: router::src::types::storage::dashboard_metadata
pub use diesel_models::user::dashboard_metadata::*;
|
crates/router/src/types/storage/dashboard_metadata.rs
|
router::src::types::storage::dashboard_metadata
| 36
| true
|
// File: crates/router/src/types/storage/customers.rs
// Module: router::src::types::storage::customers
pub use diesel_models::customers::{Customer, CustomerNew, CustomerUpdateInternal};
#[cfg(feature = "v2")]
pub use crate::types::domain::CustomerGeneralUpdate;
pub use crate::types::domain::CustomerUpdate;
|
crates/router/src/types/storage/customers.rs
|
router::src::types::storage::customers
| 72
| true
|
// File: crates/router/src/types/storage/gsm.rs
// Module: router::src::types::storage::gsm
pub use diesel_models::gsm::{
GatewayStatusMap, GatewayStatusMapperUpdateInternal, GatewayStatusMappingNew,
GatewayStatusMappingUpdate,
};
|
crates/router/src/types/storage/gsm.rs
|
router::src::types::storage::gsm
| 57
| true
|
// File: crates/router/src/types/storage/revenue_recovery.rs
// Module: router::src::types::storage::revenue_recovery
use std::{collections::HashMap, fmt::Debug};
use common_enums::enums::{self, CardNetwork};
use common_utils::{date_time, ext_traits::ValueExt, id_type};
use error_stack::ResultExt;
use external_services::grpc_client::{self as external_grpc_client, GrpcHeaders};
use hyperswitch_domain_models::{
business_profile, merchant_account, merchant_connector_account, merchant_key_store,
payment_method_data::{Card, PaymentMethodData},
payments::{payment_attempt::PaymentAttempt, PaymentIntent, PaymentStatusData},
};
use masking::PeekInterface;
use router_env::logger;
use serde::{Deserialize, Serialize};
use crate::{db::StorageInterface, routes::SessionState, types, workflows::revenue_recovery};
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct RevenueRecoveryWorkflowTrackingData {
pub merchant_id: id_type::MerchantId,
pub profile_id: id_type::ProfileId,
pub global_payment_id: id_type::GlobalPaymentId,
pub payment_attempt_id: id_type::GlobalAttemptId,
pub billing_mca_id: id_type::MerchantConnectorAccountId,
pub revenue_recovery_retry: enums::RevenueRecoveryAlgorithmType,
pub invoice_scheduled_time: Option<time::PrimitiveDateTime>,
}
#[derive(Debug, Clone)]
pub struct RevenueRecoveryPaymentData {
pub merchant_account: merchant_account::MerchantAccount,
pub profile: business_profile::Profile,
pub key_store: merchant_key_store::MerchantKeyStore,
pub billing_mca: merchant_connector_account::MerchantConnectorAccount,
pub retry_algorithm: enums::RevenueRecoveryAlgorithmType,
pub psync_data: Option<PaymentStatusData<types::api::PSync>>,
}
impl RevenueRecoveryPaymentData {
pub async fn get_schedule_time_based_on_retry_type(
&self,
state: &SessionState,
merchant_id: &id_type::MerchantId,
retry_count: i32,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
is_hard_decline: bool,
) -> Option<time::PrimitiveDateTime> {
if is_hard_decline {
logger::info!("Hard Decline encountered");
return None;
}
match self.retry_algorithm {
enums::RevenueRecoveryAlgorithmType::Monitoring => {
logger::error!("Monitoring type found for Revenue Recovery retry payment");
None
}
enums::RevenueRecoveryAlgorithmType::Cascading => {
logger::info!("Cascading type found for Revenue Recovery retry payment");
revenue_recovery::get_schedule_time_to_retry_mit_payments(
state.store.as_ref(),
merchant_id,
retry_count,
)
.await
}
enums::RevenueRecoveryAlgorithmType::Smart => None,
}
}
}
#[derive(Debug, serde::Deserialize, Clone, Default)]
pub struct RevenueRecoverySettings {
pub monitoring_threshold_in_seconds: i64,
pub retry_algorithm_type: enums::RevenueRecoveryAlgorithmType,
pub recovery_timestamp: RecoveryTimestamp,
pub card_config: RetryLimitsConfig,
pub redis_ttl_in_seconds: i64,
}
#[derive(Debug, serde::Deserialize, Clone)]
pub struct RecoveryTimestamp {
pub initial_timestamp_in_seconds: i64,
pub job_schedule_buffer_time_in_seconds: i64,
pub reopen_workflow_buffer_time_in_seconds: i64,
pub max_random_schedule_delay_in_seconds: i64,
pub redis_ttl_buffer_in_seconds: i64,
}
impl Default for RecoveryTimestamp {
fn default() -> Self {
Self {
initial_timestamp_in_seconds: 1,
job_schedule_buffer_time_in_seconds: 15,
reopen_workflow_buffer_time_in_seconds: 60,
max_random_schedule_delay_in_seconds: 300,
redis_ttl_buffer_in_seconds: 300,
}
}
}
#[derive(Debug, serde::Deserialize, Clone, Default)]
pub struct RetryLimitsConfig(pub HashMap<CardNetwork, NetworkRetryConfig>);
#[derive(Debug, serde::Deserialize, Clone, Default)]
pub struct NetworkRetryConfig {
pub max_retries_per_day: i32,
pub max_retry_count_for_thirty_day: i32,
}
impl RetryLimitsConfig {
pub fn get_network_config(&self, network: Option<CardNetwork>) -> &NetworkRetryConfig {
// Hardcoded fallback default config
static DEFAULT_CONFIG: NetworkRetryConfig = NetworkRetryConfig {
max_retries_per_day: 20,
max_retry_count_for_thirty_day: 20,
};
if let Some(net) = network {
self.0.get(&net).unwrap_or(&DEFAULT_CONFIG)
} else {
self.0.get(&CardNetwork::Visa).unwrap_or(&DEFAULT_CONFIG)
}
}
}
|
crates/router/src/types/storage/revenue_recovery.rs
|
router::src::types::storage::revenue_recovery
| 1,041
| true
|
// File: crates/router/src/types/storage/hyperswitch_ai_interaction.rs
// Module: router::src::types::storage::hyperswitch_ai_interaction
pub use diesel_models::hyperswitch_ai_interaction::*;
|
crates/router/src/types/storage/hyperswitch_ai_interaction.rs
|
router::src::types::storage::hyperswitch_ai_interaction
| 44
| true
|
// File: crates/router/src/types/storage/payout_attempt.rs
// Module: router::src::types::storage::payout_attempt
pub use diesel_models::payout_attempt::{
PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate, PayoutAttemptUpdateInternal,
};
|
crates/router/src/types/storage/payout_attempt.rs
|
router::src::types::storage::payout_attempt
| 59
| true
|
// File: crates/router/src/types/storage/authentication.rs
// Module: router::src::types::storage::authentication
pub use diesel_models::authentication::{Authentication, AuthenticationNew, AuthenticationUpdate};
|
crates/router/src/types/storage/authentication.rs
|
router::src::types::storage::authentication
| 39
| true
|
// File: crates/router/src/types/storage/merchant_key_store.rs
// Module: router::src::types::storage::merchant_key_store
pub use diesel_models::merchant_key_store::MerchantKeyStore;
|
crates/router/src/types/storage/merchant_key_store.rs
|
router::src::types::storage::merchant_key_store
| 42
| true
|
// File: crates/router/src/types/storage/ephemeral_key.rs
// Module: router::src::types::storage::ephemeral_key
#[cfg(feature = "v2")]
pub use diesel_models::ephemeral_key::{ClientSecretType, ClientSecretTypeNew};
pub use diesel_models::ephemeral_key::{EphemeralKey, EphemeralKeyNew};
#[cfg(feature = "v2")]
use crate::db::errors;
#[cfg(feature = "v2")]
use crate::types::transformers::ForeignTryFrom;
#[cfg(feature = "v2")]
impl ForeignTryFrom<ClientSecretType> for api_models::ephemeral_key::ClientSecretResponse {
type Error = errors::ApiErrorResponse;
fn foreign_try_from(from: ClientSecretType) -> Result<Self, errors::ApiErrorResponse> {
match from.resource_id {
common_utils::types::authentication::ResourceId::Payment(global_payment_id) => {
Err(errors::ApiErrorResponse::InternalServerError)
}
common_utils::types::authentication::ResourceId::PaymentMethodSession(
global_payment_id,
) => Err(errors::ApiErrorResponse::InternalServerError),
common_utils::types::authentication::ResourceId::Customer(global_customer_id) => {
Ok(Self {
resource_id: api_models::ephemeral_key::ResourceId::Customer(
global_customer_id.clone(),
),
created_at: from.created_at,
expires: from.expires,
secret: from.secret,
id: from.id,
})
}
}
}
}
|
crates/router/src/types/storage/ephemeral_key.rs
|
router::src::types::storage::ephemeral_key
| 317
| true
|
// File: crates/router/src/types/storage/reverse_lookup.rs
// Module: router::src::types::storage::reverse_lookup
pub use diesel_models::reverse_lookup::{ReverseLookup, ReverseLookupNew};
|
crates/router/src/types/storage/reverse_lookup.rs
|
router::src::types::storage::reverse_lookup
| 42
| true
|
// File: crates/router/src/types/storage/mandate.rs
// Module: router::src::types::storage::mandate
use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::errors::CustomResult;
use diesel::{associations::HasTable, ExpressionMethods, QueryDsl};
pub use diesel_models::mandate::{
Mandate, MandateNew, MandateUpdate, MandateUpdateInternal, SingleUseMandate,
};
use diesel_models::{errors, schema::mandate::dsl};
use error_stack::ResultExt;
use crate::{connection::PgPooledConn, logger};
#[async_trait::async_trait]
pub trait MandateDbExt: Sized {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
mandate_list_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
}
#[async_trait::async_trait]
impl MandateDbExt for Mandate {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
mandate_list_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.order(dsl::created_at.desc())
.into_boxed();
if let Some(created_time) = mandate_list_constraints.created_time {
filter = filter.filter(dsl::created_at.eq(created_time));
}
if let Some(created_time_lt) = mandate_list_constraints.created_time_lt {
filter = filter.filter(dsl::created_at.lt(created_time_lt));
}
if let Some(created_time_gt) = mandate_list_constraints.created_time_gt {
filter = filter.filter(dsl::created_at.gt(created_time_gt));
}
if let Some(created_time_lte) = mandate_list_constraints.created_time_lte {
filter = filter.filter(dsl::created_at.le(created_time_lte));
}
if let Some(created_time_gte) = mandate_list_constraints.created_time_gte {
filter = filter.filter(dsl::created_at.ge(created_time_gte));
}
if let Some(connector) = mandate_list_constraints.connector {
filter = filter.filter(dsl::connector.eq(connector));
}
if let Some(mandate_status) = mandate_list_constraints.mandate_status {
filter = filter.filter(dsl::mandate_status.eq(mandate_status));
}
if let Some(limit) = mandate_list_constraints.limit {
filter = filter.limit(limit);
}
if let Some(offset) = mandate_list_constraints.offset {
filter = filter.offset(offset);
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
filter
.get_results_async(conn)
.await
// The query built here returns an empty Vec when no records are found, and if any error does occur,
// it would be an internal database error, due to which we are raising a DatabaseError::Unknown error
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering mandates by specified constraints")
}
}
|
crates/router/src/types/storage/mandate.rs
|
router::src::types::storage::mandate
| 717
| true
|
// File: crates/router/src/types/storage/capture.rs
// Module: router::src::types::storage::capture
pub use diesel_models::capture::*;
|
crates/router/src/types/storage/capture.rs
|
router::src::types::storage::capture
| 32
| true
|
// File: crates/router/src/types/storage/authorization.rs
// Module: router::src::types::storage::authorization
pub use diesel_models::authorization::{Authorization, AuthorizationNew, AuthorizationUpdate};
|
crates/router/src/types/storage/authorization.rs
|
router::src::types::storage::authorization
| 40
| true
|
// File: crates/router/src/types/storage/user_authentication_method.rs
// Module: router::src::types::storage::user_authentication_method
pub use diesel_models::user_authentication_method::*;
|
crates/router/src/types/storage/user_authentication_method.rs
|
router::src::types::storage::user_authentication_method
| 37
| true
|
// File: crates/router/src/types/storage/file.rs
// Module: router::src::types::storage::file
pub use diesel_models::file::{
FileMetadata, FileMetadataNew, FileMetadataUpdate, FileMetadataUpdateInternal,
};
|
crates/router/src/types/storage/file.rs
|
router::src::types::storage::file
| 49
| true
|
// File: crates/router/src/types/api/connector_mapping.rs
// Module: router::src::types::api::connector_mapping
use std::str::FromStr;
use error_stack::{report, ResultExt};
use hyperswitch_connectors::connectors::{Paytm, Phonepe};
use crate::{
configs::settings::Connectors,
connector,
core::errors::{self, CustomResult},
services::connector_integration_interface::ConnectorEnum,
types::{self, api::enums},
};
/// Routing algorithm will output merchant connector identifier instead of connector name
/// In order to support backwards compatibility for older routing algorithms and merchant accounts
/// the support for connector name is retained
#[derive(Clone, Debug)]
pub struct ConnectorData {
pub connector: ConnectorEnum,
pub connector_name: types::Connector,
pub get_token: GetToken,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
// Normal flow will call the connector and follow the flow specific operations (capture, authorize)
// SessionTokenFromMetadata will avoid calling the connector instead create the session token ( for sdk )
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum GetToken {
GpayMetadata,
SamsungPayMetadata,
AmazonPayMetadata,
ApplePayMetadata,
PaypalSdkMetadata,
PazeMetadata,
Connector,
}
impl ConnectorData {
pub fn get_connector_by_name(
_connectors: &Connectors,
name: &str,
connector_type: GetToken,
connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
) -> CustomResult<Self, errors::ApiErrorResponse> {
let connector = Self::convert_connector(name)?;
let connector_name = enums::Connector::from_str(name)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("unable to parse connector name {name}"))?;
Ok(Self {
connector,
connector_name,
get_token: connector_type,
merchant_connector_id: connector_id,
})
}
#[cfg(feature = "payouts")]
pub fn get_payout_connector_by_name(
_connectors: &Connectors,
name: &str,
connector_type: GetToken,
connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
) -> CustomResult<Self, errors::ApiErrorResponse> {
let connector = Self::convert_connector(name)?;
let payout_connector_name = enums::PayoutConnectors::from_str(name)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("unable to parse payout connector name {name}"))?;
let connector_name = enums::Connector::from(payout_connector_name);
Ok(Self {
connector,
connector_name,
get_token: connector_type,
merchant_connector_id: connector_id,
})
}
pub fn get_external_vault_connector_by_name(
_connectors: &Connectors,
connector: String,
connector_type: GetToken,
connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
) -> CustomResult<Self, errors::ApiErrorResponse> {
let connector_enum = Self::convert_connector(&connector)?;
let external_vault_connector_name = enums::VaultConnectors::from_str(&connector)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!("unable to parse external vault connector name {connector:?}")
})?;
let connector_name = enums::Connector::from(external_vault_connector_name);
Ok(Self {
connector: connector_enum,
connector_name,
get_token: connector_type,
merchant_connector_id: connector_id,
})
}
pub fn convert_connector(
connector_name: &str,
) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> {
match enums::Connector::from_str(connector_name) {
Ok(name) => match name {
enums::Connector::Aci => Ok(ConnectorEnum::Old(Box::new(connector::Aci::new()))),
enums::Connector::Adyen => {
Ok(ConnectorEnum::Old(Box::new(connector::Adyen::new())))
}
enums::Connector::Affirm => {
Ok(ConnectorEnum::Old(Box::new(connector::Affirm::new())))
}
enums::Connector::Adyenplatform => Ok(ConnectorEnum::Old(Box::new(
connector::Adyenplatform::new(),
))),
enums::Connector::Airwallex => {
Ok(ConnectorEnum::Old(Box::new(connector::Airwallex::new())))
}
enums::Connector::Amazonpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Amazonpay::new())))
}
enums::Connector::Archipel => {
Ok(ConnectorEnum::Old(Box::new(connector::Archipel::new())))
}
enums::Connector::Authipay => {
Ok(ConnectorEnum::Old(Box::new(connector::Authipay::new())))
}
enums::Connector::Authorizedotnet => Ok(ConnectorEnum::Old(Box::new(
connector::Authorizedotnet::new(),
))),
enums::Connector::Bambora => {
Ok(ConnectorEnum::Old(Box::new(connector::Bambora::new())))
}
enums::Connector::Bamboraapac => {
Ok(ConnectorEnum::Old(Box::new(connector::Bamboraapac::new())))
}
enums::Connector::Bankofamerica => Ok(ConnectorEnum::Old(Box::new(
connector::Bankofamerica::new(),
))),
enums::Connector::Barclaycard => {
Ok(ConnectorEnum::Old(Box::new(connector::Barclaycard::new())))
}
enums::Connector::Billwerk => {
Ok(ConnectorEnum::Old(Box::new(connector::Billwerk::new())))
}
enums::Connector::Bitpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Bitpay::new())))
}
enums::Connector::Blackhawknetwork => Ok(ConnectorEnum::Old(Box::new(
connector::Blackhawknetwork::new(),
))),
enums::Connector::Bluesnap => {
Ok(ConnectorEnum::Old(Box::new(connector::Bluesnap::new())))
}
enums::Connector::Calida => {
Ok(ConnectorEnum::Old(Box::new(connector::Calida::new())))
}
enums::Connector::Boku => Ok(ConnectorEnum::Old(Box::new(connector::Boku::new()))),
enums::Connector::Braintree => {
Ok(ConnectorEnum::Old(Box::new(connector::Braintree::new())))
}
enums::Connector::Breadpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Breadpay::new())))
}
enums::Connector::Cashtocode => {
Ok(ConnectorEnum::Old(Box::new(connector::Cashtocode::new())))
}
enums::Connector::Celero => {
Ok(ConnectorEnum::Old(Box::new(connector::Celero::new())))
}
enums::Connector::Chargebee => {
Ok(ConnectorEnum::Old(Box::new(connector::Chargebee::new())))
}
enums::Connector::Checkbook => {
Ok(ConnectorEnum::Old(Box::new(connector::Checkbook::new())))
}
enums::Connector::Checkout => {
Ok(ConnectorEnum::Old(Box::new(connector::Checkout::new())))
}
enums::Connector::Coinbase => {
Ok(ConnectorEnum::Old(Box::new(connector::Coinbase::new())))
}
enums::Connector::Coingate => {
Ok(ConnectorEnum::Old(Box::new(connector::Coingate::new())))
}
enums::Connector::Cryptopay => {
Ok(ConnectorEnum::Old(Box::new(connector::Cryptopay::new())))
}
enums::Connector::CtpMastercard => {
Ok(ConnectorEnum::Old(Box::new(&connector::CtpMastercard)))
}
enums::Connector::Custombilling => Ok(ConnectorEnum::Old(Box::new(
connector::Custombilling::new(),
))),
enums::Connector::CtpVisa => Ok(ConnectorEnum::Old(Box::new(
connector::UnifiedAuthenticationService::new(),
))),
enums::Connector::Cybersource => {
Ok(ConnectorEnum::Old(Box::new(connector::Cybersource::new())))
}
enums::Connector::Datatrans => {
Ok(ConnectorEnum::Old(Box::new(connector::Datatrans::new())))
}
enums::Connector::Deutschebank => {
Ok(ConnectorEnum::Old(Box::new(connector::Deutschebank::new())))
}
enums::Connector::Digitalvirgo => {
Ok(ConnectorEnum::Old(Box::new(connector::Digitalvirgo::new())))
}
enums::Connector::Dlocal => {
Ok(ConnectorEnum::Old(Box::new(connector::Dlocal::new())))
}
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector1 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<1>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector2 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<2>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector3 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<3>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector4 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<4>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector5 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<5>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector6 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<6>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector7 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<7>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyBillingConnector => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<8>::new(),
))),
enums::Connector::Dwolla => {
Ok(ConnectorEnum::Old(Box::new(connector::Dwolla::new())))
}
enums::Connector::Ebanx => {
Ok(ConnectorEnum::Old(Box::new(connector::Ebanx::new())))
}
enums::Connector::Elavon => {
Ok(ConnectorEnum::Old(Box::new(connector::Elavon::new())))
}
enums::Connector::Facilitapay => {
Ok(ConnectorEnum::Old(Box::new(connector::Facilitapay::new())))
}
enums::Connector::Finix => {
Ok(ConnectorEnum::Old(Box::new(connector::Finix::new())))
}
enums::Connector::Fiserv => {
Ok(ConnectorEnum::Old(Box::new(connector::Fiserv::new())))
}
enums::Connector::Fiservemea => {
Ok(ConnectorEnum::Old(Box::new(connector::Fiservemea::new())))
}
enums::Connector::Fiuu => Ok(ConnectorEnum::Old(Box::new(connector::Fiuu::new()))),
enums::Connector::Flexiti => {
Ok(ConnectorEnum::Old(Box::new(connector::Flexiti::new())))
}
enums::Connector::Forte => {
Ok(ConnectorEnum::Old(Box::new(connector::Forte::new())))
}
enums::Connector::Getnet => {
Ok(ConnectorEnum::Old(Box::new(connector::Getnet::new())))
}
enums::Connector::Gigadat => {
Ok(ConnectorEnum::Old(Box::new(connector::Gigadat::new())))
}
enums::Connector::Globalpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Globalpay::new())))
}
enums::Connector::Globepay => {
Ok(ConnectorEnum::Old(Box::new(connector::Globepay::new())))
}
enums::Connector::Gocardless => {
Ok(ConnectorEnum::Old(Box::new(connector::Gocardless::new())))
}
enums::Connector::Hipay => {
Ok(ConnectorEnum::Old(Box::new(connector::Hipay::new())))
}
enums::Connector::Helcim => {
Ok(ConnectorEnum::Old(Box::new(connector::Helcim::new())))
}
enums::Connector::HyperswitchVault => {
Ok(ConnectorEnum::Old(Box::new(&connector::HyperswitchVault)))
}
enums::Connector::Iatapay => {
Ok(ConnectorEnum::Old(Box::new(connector::Iatapay::new())))
}
enums::Connector::Inespay => {
Ok(ConnectorEnum::Old(Box::new(connector::Inespay::new())))
}
enums::Connector::Itaubank => {
Ok(ConnectorEnum::Old(Box::new(connector::Itaubank::new())))
}
enums::Connector::Jpmorgan => {
Ok(ConnectorEnum::Old(Box::new(connector::Jpmorgan::new())))
}
enums::Connector::Juspaythreedsserver => Ok(ConnectorEnum::Old(Box::new(
connector::Juspaythreedsserver::new(),
))),
enums::Connector::Klarna => {
Ok(ConnectorEnum::Old(Box::new(connector::Klarna::new())))
}
enums::Connector::Loonio => {
Ok(ConnectorEnum::Old(Box::new(connector::Loonio::new())))
}
enums::Connector::Mollie => {
// enums::Connector::Moneris => Ok(ConnectorEnum::Old(Box::new(connector::Moneris))),
Ok(ConnectorEnum::Old(Box::new(connector::Mollie::new())))
}
enums::Connector::Moneris => {
Ok(ConnectorEnum::Old(Box::new(connector::Moneris::new())))
}
enums::Connector::Nexixpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Nexixpay::new())))
}
enums::Connector::Nmi => Ok(ConnectorEnum::Old(Box::new(connector::Nmi::new()))),
enums::Connector::Nomupay => {
Ok(ConnectorEnum::Old(Box::new(connector::Nomupay::new())))
}
enums::Connector::Noon => Ok(ConnectorEnum::Old(Box::new(connector::Noon::new()))),
enums::Connector::Nordea => {
Ok(ConnectorEnum::Old(Box::new(connector::Nordea::new())))
}
enums::Connector::Novalnet => {
Ok(ConnectorEnum::Old(Box::new(connector::Novalnet::new())))
}
enums::Connector::Nuvei => {
Ok(ConnectorEnum::Old(Box::new(connector::Nuvei::new())))
}
enums::Connector::Opennode => {
Ok(ConnectorEnum::Old(Box::new(connector::Opennode::new())))
}
enums::Connector::Paybox => {
Ok(ConnectorEnum::Old(Box::new(connector::Paybox::new())))
}
// "payeezy" => Ok(ConnectorIntegrationEnum::Old(Box::new(&connector::Payeezy)), As psync and rsync are not supported by this connector, it is added as template code for future usage
// enums::Connector::Payload => {
// Ok(ConnectorEnum::Old(Box::new(connector::Paybload::new())))
// }
enums::Connector::Payload => {
Ok(ConnectorEnum::Old(Box::new(connector::Payload::new())))
}
enums::Connector::Payme => {
Ok(ConnectorEnum::Old(Box::new(connector::Payme::new())))
}
enums::Connector::Payone => {
Ok(ConnectorEnum::Old(Box::new(connector::Payone::new())))
}
enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(connector::Payu::new()))),
enums::Connector::Peachpayments => Ok(ConnectorEnum::Old(Box::new(
hyperswitch_connectors::connectors::Peachpayments::new(),
))),
enums::Connector::Placetopay => {
Ok(ConnectorEnum::Old(Box::new(connector::Placetopay::new())))
}
enums::Connector::Powertranz => {
Ok(ConnectorEnum::Old(Box::new(connector::Powertranz::new())))
}
enums::Connector::Prophetpay => {
Ok(ConnectorEnum::Old(Box::new(&connector::Prophetpay)))
}
enums::Connector::Razorpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Razorpay::new())))
}
enums::Connector::Rapyd => {
Ok(ConnectorEnum::Old(Box::new(connector::Rapyd::new())))
}
enums::Connector::Recurly => {
Ok(ConnectorEnum::New(Box::new(connector::Recurly::new())))
}
enums::Connector::Redsys => {
Ok(ConnectorEnum::Old(Box::new(connector::Redsys::new())))
}
enums::Connector::Santander => {
Ok(ConnectorEnum::Old(Box::new(connector::Santander::new())))
}
enums::Connector::Shift4 => {
Ok(ConnectorEnum::Old(Box::new(connector::Shift4::new())))
}
enums::Connector::Silverflow => {
Ok(ConnectorEnum::Old(Box::new(connector::Silverflow::new())))
}
enums::Connector::Square => Ok(ConnectorEnum::Old(Box::new(&connector::Square))),
enums::Connector::Stax => Ok(ConnectorEnum::Old(Box::new(&connector::Stax))),
enums::Connector::Stripe => {
Ok(ConnectorEnum::Old(Box::new(connector::Stripe::new())))
}
enums::Connector::Stripebilling => Ok(ConnectorEnum::Old(Box::new(
connector::Stripebilling::new(),
))),
enums::Connector::Wise => Ok(ConnectorEnum::Old(Box::new(connector::Wise::new()))),
enums::Connector::Worldline => {
Ok(ConnectorEnum::Old(Box::new(&connector::Worldline)))
}
enums::Connector::Worldpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Worldpay::new())))
}
enums::Connector::Worldpayvantiv => Ok(ConnectorEnum::Old(Box::new(
connector::Worldpayvantiv::new(),
))),
enums::Connector::Worldpayxml => {
Ok(ConnectorEnum::Old(Box::new(connector::Worldpayxml::new())))
}
enums::Connector::Xendit => {
Ok(ConnectorEnum::Old(Box::new(connector::Xendit::new())))
}
enums::Connector::Mifinity => {
Ok(ConnectorEnum::Old(Box::new(connector::Mifinity::new())))
}
enums::Connector::Multisafepay => {
Ok(ConnectorEnum::Old(Box::new(connector::Multisafepay::new())))
}
enums::Connector::Netcetera => {
Ok(ConnectorEnum::Old(Box::new(&connector::Netcetera)))
}
enums::Connector::Nexinets => {
Ok(ConnectorEnum::Old(Box::new(&connector::Nexinets)))
}
// enums::Connector::Nexixpay => {
// Ok(ConnectorEnum::Old(Box::new(&connector::Nexixpay)))
// }
enums::Connector::Paypal => {
Ok(ConnectorEnum::Old(Box::new(connector::Paypal::new())))
}
enums::Connector::Paysafe => {
Ok(ConnectorEnum::Old(Box::new(connector::Paysafe::new())))
}
enums::Connector::Paystack => {
Ok(ConnectorEnum::Old(Box::new(connector::Paystack::new())))
}
// enums::Connector::Thunes => Ok(ConnectorEnum::Old(Box::new(connector::Thunes))),
enums::Connector::Tesouro => {
Ok(ConnectorEnum::Old(Box::new(connector::Tesouro::new())))
}
enums::Connector::Tokenex => Ok(ConnectorEnum::Old(Box::new(&connector::Tokenex))),
enums::Connector::Tokenio => {
Ok(ConnectorEnum::Old(Box::new(connector::Tokenio::new())))
}
enums::Connector::Trustpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Trustpay::new())))
}
enums::Connector::Trustpayments => Ok(ConnectorEnum::Old(Box::new(
connector::Trustpayments::new(),
))),
enums::Connector::Tsys => Ok(ConnectorEnum::Old(Box::new(connector::Tsys::new()))),
// enums::Connector::UnifiedAuthenticationService => Ok(ConnectorEnum::Old(Box::new(
// connector::UnifiedAuthenticationService,
// ))),
enums::Connector::Vgs => Ok(ConnectorEnum::Old(Box::new(&connector::Vgs))),
enums::Connector::Volt => Ok(ConnectorEnum::Old(Box::new(connector::Volt::new()))),
enums::Connector::Wellsfargo => {
Ok(ConnectorEnum::Old(Box::new(connector::Wellsfargo::new())))
}
// enums::Connector::Wellsfargopayout => {
// Ok(Box::new(connector::Wellsfargopayout::new()))
// }
enums::Connector::Zen => Ok(ConnectorEnum::Old(Box::new(&connector::Zen))),
enums::Connector::Zsl => Ok(ConnectorEnum::Old(Box::new(&connector::Zsl))),
enums::Connector::Plaid => {
Ok(ConnectorEnum::Old(Box::new(connector::Plaid::new())))
}
enums::Connector::Signifyd
| enums::Connector::Riskified
| enums::Connector::Gpayments
| enums::Connector::Threedsecureio
| enums::Connector::Cardinal
| enums::Connector::Taxjar => {
Err(report!(errors::ConnectorError::InvalidConnectorName)
.attach_printable(format!("invalid connector name: {connector_name}")))
.change_context(errors::ApiErrorResponse::InternalServerError)
}
enums::Connector::Phonepe => Ok(ConnectorEnum::Old(Box::new(Phonepe::new()))),
enums::Connector::Paytm => Ok(ConnectorEnum::Old(Box::new(Paytm::new()))),
},
Err(_) => Err(report!(errors::ConnectorError::InvalidConnectorName)
.attach_printable(format!("invalid connector name: {connector_name}")))
.change_context(errors::ApiErrorResponse::InternalServerError),
}
}
}
|
crates/router/src/types/api/connector_mapping.rs
|
router::src::types::api::connector_mapping
| 5,113
| true
|
// File: crates/router/src/types/api/fraud_check_v2.rs
// Module: router::src::types::api::fraud_check_v2
pub use hyperswitch_domain_models::router_flow_types::fraud_check::{
Checkout, Fulfillment, RecordReturn, Sale, Transaction,
};
pub use hyperswitch_interfaces::api::fraud_check_v2::{
FraudCheckCheckoutV2, FraudCheckFulfillmentV2, FraudCheckRecordReturnV2, FraudCheckSaleV2,
FraudCheckTransactionV2, FraudCheckV2,
};
|
crates/router/src/types/api/fraud_check_v2.rs
|
router::src::types::api::fraud_check_v2
| 117
| true
|
// File: crates/router/src/types/api/payouts_v2.rs
// Module: router::src::types::api::payouts_v2
pub use api_models::payouts::{
AchBankTransfer, BacsBankTransfer, Bank as BankPayout, CardPayout, PayoutActionRequest,
PayoutAttemptResponse, PayoutCreateRequest, PayoutCreateResponse, PayoutListConstraints,
PayoutListFilterConstraints, PayoutListFilters, PayoutListResponse, PayoutMethodData,
PayoutRequest, PayoutRetrieveBody, PayoutRetrieveRequest, PixBankTransfer, SepaBankTransfer,
Wallet as WalletPayout,
};
pub use hyperswitch_domain_models::router_flow_types::payouts::{
PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync,
};
pub use hyperswitch_interfaces::api::payouts_v2::{
PayoutCancelV2, PayoutCreateV2, PayoutEligibilityV2, PayoutFulfillV2, PayoutQuoteV2,
PayoutRecipientAccountV2, PayoutRecipientV2, PayoutSyncV2,
};
use crate::types::api as api_types;
pub trait PayoutsV2:
api_types::ConnectorCommon
+ PayoutCancelV2
+ PayoutCreateV2
+ PayoutEligibilityV2
+ PayoutFulfillV2
+ PayoutQuoteV2
+ PayoutRecipientV2
+ PayoutSyncV2
+ PayoutRecipientAccountV2
{
}
|
crates/router/src/types/api/payouts_v2.rs
|
router::src::types::api::payouts_v2
| 350
| true
|
// File: crates/router/src/types/api/payment_methods.rs
// Module: router::src::types::api::payment_methods
#[cfg(feature = "v2")]
pub use api_models::payment_methods::{
CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CardNetworkTokenizeRequest,
CardNetworkTokenizeResponse, CardType, CustomerPaymentMethodResponseItem,
DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest, GetTokenizePayloadResponse,
ListCountriesCurrenciesRequest, MigrateCardDetail, NetworkTokenDetailsPaymentMethod,
NetworkTokenDetailsResponse, NetworkTokenResponse, PaymentMethodCollectLinkRenderRequest,
PaymentMethodCollectLinkRequest, PaymentMethodCreate, PaymentMethodCreateData,
PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodIntentConfirm,
PaymentMethodIntentCreate, PaymentMethodListData, PaymentMethodListResponseForSession,
PaymentMethodMigrate, PaymentMethodMigrateResponse, PaymentMethodResponse,
PaymentMethodResponseData, PaymentMethodUpdate, PaymentMethodUpdateData, PaymentMethodsData,
ProxyCardDetails, RequestPaymentMethodTypes, TokenDataResponse, TokenDetailsResponse,
TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2,
TokenizedWalletValue1, TokenizedWalletValue2, TotalPaymentMethodCountResponse,
};
#[cfg(feature = "v1")]
pub use api_models::payment_methods::{
CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CardNetworkTokenizeRequest,
CardNetworkTokenizeResponse, CustomerPaymentMethod, CustomerPaymentMethodsListResponse,
DefaultPaymentMethod, DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest,
GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, MigrateCardDetail,
PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate,
PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId,
PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodMigrate,
PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData,
TokenizeCardRequest, TokenizeDataRequest, TokenizePayloadEncrypted, TokenizePayloadRequest,
TokenizePaymentMethodRequest, TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1,
TokenizedWalletValue2,
};
use error_stack::report;
use crate::core::{
errors::{self, RouterResult},
payments::helpers::validate_payment_method_type_against_payment_method,
};
#[cfg(feature = "v2")]
use crate::utils;
pub(crate) trait PaymentMethodCreateExt {
fn validate(&self) -> RouterResult<()>;
}
// convert self.payment_method_type to payment_method and compare it against self.payment_method
#[cfg(feature = "v1")]
impl PaymentMethodCreateExt for PaymentMethodCreate {
fn validate(&self) -> RouterResult<()> {
if let Some(pm) = self.payment_method {
if let Some(payment_method_type) = self.payment_method_type {
if !validate_payment_method_type_against_payment_method(pm, payment_method_type) {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid 'payment_method_type' provided".to_string()
})
.attach_printable("Invalid payment method type"));
}
}
}
Ok(())
}
}
#[cfg(feature = "v2")]
impl PaymentMethodCreateExt for PaymentMethodCreate {
fn validate(&self) -> RouterResult<()> {
utils::when(
!validate_payment_method_type_against_payment_method(
self.payment_method_type,
self.payment_method_subtype,
),
|| {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid 'payment_method_type' provided".to_string()
})
.attach_printable("Invalid payment method type"))
},
)?;
utils::when(
!Self::validate_payment_method_data_against_payment_method(
self.payment_method_type,
self.payment_method_data.clone(),
),
|| {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid 'payment_method_data' provided".to_string()
})
.attach_printable("Invalid payment method data"))
},
)?;
Ok(())
}
}
#[cfg(feature = "v2")]
impl PaymentMethodCreateExt for PaymentMethodIntentConfirm {
fn validate(&self) -> RouterResult<()> {
utils::when(
!validate_payment_method_type_against_payment_method(
self.payment_method_type,
self.payment_method_subtype,
),
|| {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid 'payment_method_type' provided".to_string()
})
.attach_printable("Invalid payment method type"))
},
)?;
utils::when(
!Self::validate_payment_method_data_against_payment_method(
self.payment_method_type,
self.payment_method_data.clone(),
),
|| {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid 'payment_method_data' provided".to_string()
})
.attach_printable("Invalid payment method data"))
},
)?;
Ok(())
}
}
|
crates/router/src/types/api/payment_methods.rs
|
router::src::types::api::payment_methods
| 1,096
| true
|
// File: crates/router/src/types/api/refunds.rs
// Module: router::src::types::api::refunds
#[cfg(feature = "v1")]
pub use api_models::refunds::RefundRequest;
pub use api_models::refunds::{
RefundListRequest, RefundListResponse, RefundResponse, RefundStatus, RefundType,
RefundUpdateRequest, RefundsRetrieveBody, RefundsRetrieveRequest,
};
#[cfg(feature = "v2")]
pub use api_models::refunds::{RefundMetadataUpdateRequest, RefundsCreateRequest};
pub use hyperswitch_domain_models::router_flow_types::refunds::{Execute, RSync};
pub use hyperswitch_interfaces::api::refunds::{Refund, RefundExecute, RefundSync};
use crate::types::{storage::enums as storage_enums, transformers::ForeignFrom};
impl ForeignFrom<storage_enums::RefundStatus> for RefundStatus {
fn foreign_from(status: storage_enums::RefundStatus) -> Self {
match status {
storage_enums::RefundStatus::Failure
| storage_enums::RefundStatus::TransactionFailure => Self::Failed,
storage_enums::RefundStatus::ManualReview => Self::Review,
storage_enums::RefundStatus::Pending => Self::Pending,
storage_enums::RefundStatus::Success => Self::Succeeded,
}
}
}
|
crates/router/src/types/api/refunds.rs
|
router::src::types::api::refunds
| 298
| true
|
// File: crates/router/src/types/api/cards.rs
// Module: router::src::types::api::cards
|
crates/router/src/types/api/cards.rs
|
router::src::types::api::cards
| 24
| true
|
// File: crates/router/src/types/api/payouts.rs
// Module: router::src::types::api::payouts
pub use api_models::payouts::{
AchBankTransfer, BacsBankTransfer, Bank as BankPayout, BankRedirect as BankRedirectPayout,
CardPayout, PaymentMethodTypeInfo, PayoutActionRequest, PayoutAttemptResponse,
PayoutCreateRequest, PayoutCreateResponse, PayoutEnabledPaymentMethodsInfo, PayoutLinkResponse,
PayoutListConstraints, PayoutListFilterConstraints, PayoutListFilters, PayoutListResponse,
PayoutMethodData, PayoutMethodDataResponse, PayoutRequest, PayoutRetrieveBody,
PayoutRetrieveRequest, PixBankTransfer, RequiredFieldsOverrideRequest, SepaBankTransfer,
Wallet as WalletPayout,
};
pub use hyperswitch_domain_models::router_flow_types::payouts::{
PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync,
};
pub use hyperswitch_interfaces::api::payouts::{
PayoutCancel, PayoutCreate, PayoutEligibility, PayoutFulfill, PayoutQuote, PayoutRecipient,
PayoutRecipientAccount, PayoutSync, Payouts,
};
pub use super::payouts_v2::{
PayoutCancelV2, PayoutCreateV2, PayoutEligibilityV2, PayoutFulfillV2, PayoutQuoteV2,
PayoutRecipientAccountV2, PayoutRecipientV2, PayoutSyncV2, PayoutsV2,
};
|
crates/router/src/types/api/payouts.rs
|
router::src::types::api::payouts
| 345
| true
|
// File: crates/router/src/types/api/refunds_v2.rs
// Module: router::src::types::api::refunds_v2
pub use hyperswitch_interfaces::api::refunds_v2::{RefundExecuteV2, RefundSyncV2, RefundV2};
|
crates/router/src/types/api/refunds_v2.rs
|
router::src::types::api::refunds_v2
| 60
| true
|
// File: crates/router/src/types/api/fraud_check.rs
// Module: router::src::types::api::fraud_check
use std::str::FromStr;
use api_models::enums;
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
pub use hyperswitch_domain_models::router_flow_types::fraud_check::{
Checkout, Fulfillment, RecordReturn, Sale, Transaction,
};
pub use hyperswitch_interfaces::api::fraud_check::{
FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, FraudCheckSale,
FraudCheckTransaction,
};
pub use super::fraud_check_v2::{
FraudCheckCheckoutV2, FraudCheckFulfillmentV2, FraudCheckRecordReturnV2, FraudCheckSaleV2,
FraudCheckTransactionV2, FraudCheckV2,
};
use super::{ConnectorData, SessionConnectorDatas};
use crate::{
connector,
core::{errors, payments::ActionType},
services::connector_integration_interface::ConnectorEnum,
};
#[derive(Clone)]
pub struct FraudCheckConnectorData {
pub connector: ConnectorEnum,
pub connector_name: enums::FrmConnectors,
}
pub enum ConnectorCallType {
PreDetermined(ConnectorRoutingData),
Retryable(Vec<ConnectorRoutingData>),
SessionMultiple(SessionConnectorDatas),
}
#[derive(Clone)]
pub struct ConnectorRoutingData {
pub connector_data: ConnectorData,
pub network: Option<common_enums::CardNetwork>,
// action_type is used for mandates currently
pub action_type: Option<ActionType>,
}
impl FraudCheckConnectorData {
pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> {
let connector_name = enums::FrmConnectors::from_str(name)
.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
.attach_printable_lazy(|| {
format!("unable to parse connector: {:?}", name.to_string())
})?;
let connector = Self::convert_connector(connector_name)?;
Ok(Self {
connector,
connector_name,
})
}
fn convert_connector(
connector_name: enums::FrmConnectors,
) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> {
match connector_name {
enums::FrmConnectors::Signifyd => {
Ok(ConnectorEnum::Old(Box::new(&connector::Signifyd)))
}
enums::FrmConnectors::Riskified => {
Ok(ConnectorEnum::Old(Box::new(connector::Riskified::new())))
}
}
}
}
|
crates/router/src/types/api/fraud_check.rs
|
router::src::types::api::fraud_check
| 544
| true
|
// File: crates/router/src/types/api/configs.rs
// Module: router::src::types::api::configs
#[derive(Clone, serde::Serialize, Debug, serde::Deserialize)]
pub struct Config {
pub key: String,
pub value: String,
}
#[derive(Clone, serde::Deserialize, Debug, serde::Serialize)]
pub struct ConfigUpdate {
#[serde(skip_deserializing)]
pub key: String,
pub value: String,
}
|
crates/router/src/types/api/configs.rs
|
router::src::types::api::configs
| 96
| true
|
// File: crates/router/src/types/api/payments.rs
// Module: router::src::types::api::payments
#[cfg(feature = "v2")]
pub use api_models::payments::{
PaymentAttemptListRequest, PaymentAttemptListResponse, PaymentsConfirmIntentRequest,
PaymentsCreateIntentRequest, PaymentsIntentResponse, PaymentsUpdateIntentRequest,
RecoveryPaymentsCreate,
};
#[cfg(feature = "v1")]
pub use api_models::payments::{
PaymentListFilterConstraints, PaymentListResponse, PaymentListResponseV2, PaymentRetrieveBody,
PaymentRetrieveBodyWithCredentials, PaymentsEligibilityRequest,
};
pub use api_models::{
feature_matrix::{
ConnectorFeatureMatrixResponse, FeatureMatrixListResponse, FeatureMatrixRequest,
},
payments::{
Address, AddressDetails, Amount, ApplepayPaymentMethod, AuthenticationForStartResponse,
Card, CryptoData, CustomerDetails, CustomerDetailsResponse, HyperswitchVaultSessionDetails,
MandateAmountData, MandateData, MandateTransactionType, MandateType,
MandateValidationFields, NextActionType, OpenBankingSessionToken, PayLaterData,
PaymentIdType, PaymentListConstraints, PaymentListFilters, PaymentListFiltersV2,
PaymentMethodData, PaymentMethodDataRequest, PaymentMethodDataResponse, PaymentOp,
PaymentsAggregateResponse, PaymentsApproveRequest, PaymentsCancelPostCaptureRequest,
PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest,
PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse,
PaymentsExtendAuthorizationRequest, PaymentsExternalAuthenticationRequest,
PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest,
PaymentsPostSessionTokensRequest, PaymentsPostSessionTokensResponse,
PaymentsRedirectRequest, PaymentsRedirectionResponse, PaymentsRejectRequest,
PaymentsRequest, PaymentsResponse, PaymentsResponseForm, PaymentsRetrieveRequest,
PaymentsSessionRequest, PaymentsSessionResponse, PaymentsStartRequest,
PaymentsUpdateMetadataRequest, PaymentsUpdateMetadataResponse, PgRedirectResponse,
PhoneDetails, RedirectionResponse, SessionToken, UrlDetails, VaultSessionDetails,
VerifyRequest, VerifyResponse, VgsSessionDetails, WalletData,
},
};
pub use common_types::payments::{AcceptanceType, CustomerAcceptance, OnlineMandate};
use error_stack::ResultExt;
pub use hyperswitch_domain_models::router_flow_types::payments::{
Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize,
CreateConnectorCustomer, CreateOrder, ExtendAuthorization, ExternalVaultProxy,
IncrementalAuthorization, InitPayment, PSync, PaymentCreateIntent, PaymentGetIntent,
PaymentMethodToken, PaymentUpdateIntent, PostCaptureVoid, PostProcessing, PostSessionTokens,
PreProcessing, RecordAttempt, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata,
Void,
};
pub use hyperswitch_interfaces::api::payments::{
ConnectorCustomer, MandateSetup, Payment, PaymentApprove, PaymentAuthorize,
PaymentAuthorizeSessionToken, PaymentCapture, PaymentIncrementalAuthorization,
PaymentPostCaptureVoid, PaymentPostSessionTokens, PaymentReject, PaymentSession,
PaymentSessionUpdate, PaymentSync, PaymentToken, PaymentUpdateMetadata, PaymentVoid,
PaymentsCompleteAuthorize, PaymentsCreateOrder, PaymentsPostProcessing, PaymentsPreProcessing,
TaxCalculation,
};
pub use super::payments_v2::{
ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2,
PaymentAuthorizeV2, PaymentCaptureV2, PaymentExtendAuthorizationV2,
PaymentIncrementalAuthorizationV2, PaymentPostCaptureVoidV2, PaymentPostSessionTokensV2,
PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2, PaymentSyncV2, PaymentTokenV2,
PaymentUpdateMetadataV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2,
PaymentsPostProcessingV2, PaymentsPreProcessingV2, TaxCalculationV2,
};
use crate::core::errors;
pub trait PaymentIdTypeExt {
#[cfg(feature = "v1")]
fn get_payment_intent_id(
&self,
) -> errors::CustomResult<common_utils::id_type::PaymentId, errors::ValidationError>;
#[cfg(feature = "v2")]
fn get_payment_intent_id(
&self,
) -> errors::CustomResult<common_utils::id_type::GlobalPaymentId, errors::ValidationError>;
}
impl PaymentIdTypeExt for PaymentIdType {
#[cfg(feature = "v1")]
fn get_payment_intent_id(
&self,
) -> errors::CustomResult<common_utils::id_type::PaymentId, errors::ValidationError> {
match self {
Self::PaymentIntentId(id) => Ok(id.clone()),
Self::ConnectorTransactionId(_)
| Self::PaymentAttemptId(_)
| Self::PreprocessingId(_) => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "payment_id",
})
.attach_printable("Expected payment intent ID but got connector transaction ID"),
}
}
#[cfg(feature = "v2")]
fn get_payment_intent_id(
&self,
) -> errors::CustomResult<common_utils::id_type::GlobalPaymentId, errors::ValidationError> {
match self {
Self::PaymentIntentId(id) => Ok(id.clone()),
Self::ConnectorTransactionId(_)
| Self::PaymentAttemptId(_)
| Self::PreprocessingId(_) => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "payment_id",
})
.attach_printable("Expected payment intent ID but got connector transaction ID"),
}
}
}
pub(crate) trait MandateValidationFieldsExt {
fn validate_and_get_mandate_type(
&self,
) -> errors::CustomResult<Option<MandateTransactionType>, errors::ValidationError>;
}
impl MandateValidationFieldsExt for MandateValidationFields {
fn validate_and_get_mandate_type(
&self,
) -> errors::CustomResult<Option<MandateTransactionType>, errors::ValidationError> {
match (&self.mandate_data, &self.recurring_details) {
(None, None) => Ok(None),
(Some(_), Some(_)) => Err(errors::ValidationError::InvalidValue {
message: "Expected one out of recurring_details and mandate_data but got both"
.to_string(),
}
.into()),
(_, Some(_)) => Ok(Some(MandateTransactionType::RecurringMandateTransaction)),
(Some(_), _) => Ok(Some(MandateTransactionType::NewMandateTransaction)),
}
}
}
#[cfg(feature = "v1")]
#[cfg(test)]
mod payments_test {
#![allow(clippy::expect_used, clippy::unwrap_used)]
use super::*;
#[allow(dead_code)]
fn card() -> Card {
Card {
card_number: "1234432112344321".to_string().try_into().unwrap(),
card_exp_month: "12".to_string().into(),
card_exp_year: "99".to_string().into(),
card_holder_name: Some(masking::Secret::new("JohnDoe".to_string())),
card_cvc: "123".to_string().into(),
card_issuer: Some("HDFC".to_string()),
card_network: Some(api_models::enums::CardNetwork::Visa),
bank_code: None,
card_issuing_country: None,
card_type: None,
nick_name: Some(masking::Secret::new("nick_name".into())),
}
}
#[allow(dead_code)]
fn payments_request() -> PaymentsRequest {
PaymentsRequest {
amount: Some(Amount::from(common_utils::types::MinorUnit::new(200))),
payment_method_data: Some(PaymentMethodDataRequest {
payment_method_data: Some(PaymentMethodData::Card(card())),
billing: None,
}),
..PaymentsRequest::default()
}
}
//#[test] // FIXME: Fix test
#[allow(dead_code)]
fn verify_payments_request() {
let pay_req = payments_request();
let serialized =
serde_json::to_string(&pay_req).expect("error serializing payments request");
let _deserialized_pay_req: PaymentsRequest =
serde_json::from_str(&serialized).expect("error de-serializing payments response");
//assert_eq!(pay_req, deserialized_pay_req)
}
// Intended to test the serialization and deserialization of the enum PaymentIdType
#[test]
fn test_connector_id_type() {
let sample_1 = PaymentIdType::PaymentIntentId(
common_utils::id_type::PaymentId::try_from(std::borrow::Cow::Borrowed(
"test_234565430uolsjdnf48i0",
))
.unwrap(),
);
let s_sample_1 = serde_json::to_string(&sample_1).unwrap();
let ds_sample_1 = serde_json::from_str::<PaymentIdType>(&s_sample_1).unwrap();
assert_eq!(ds_sample_1, sample_1)
}
}
|
crates/router/src/types/api/payments.rs
|
router::src::types::api::payments
| 1,950
| true
|
// File: crates/router/src/types/api/disputes.rs
// Module: router::src::types::api::disputes
pub use hyperswitch_interfaces::{
api::disputes::{
AcceptDispute, DefendDispute, Dispute, DisputeSync, FetchDisputes, SubmitEvidence,
},
disputes::DisputePayload,
};
use masking::{Deserialize, Serialize};
use crate::types;
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct DisputeId {
pub dispute_id: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DisputeFetchQueryData {
pub fetch_from: String,
pub fetch_till: String,
}
pub use hyperswitch_domain_models::router_flow_types::dispute::{
Accept, Defend, Dsync, Evidence, Fetch,
};
pub use super::disputes_v2::{
AcceptDisputeV2, DefendDisputeV2, DisputeSyncV2, DisputeV2, FetchDisputesV2, SubmitEvidenceV2,
};
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct DisputeEvidence {
pub cancellation_policy: Option<String>,
pub customer_communication: Option<String>,
pub customer_signature: Option<String>,
pub receipt: Option<String>,
pub refund_policy: Option<String>,
pub service_documentation: Option<String>,
pub shipping_documentation: Option<String>,
pub invoice_showing_distinct_transactions: Option<String>,
pub recurring_transaction_agreement: Option<String>,
pub uncategorized_file: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct AttachEvidenceRequest {
pub create_file_request: types::api::CreateFileRequest,
pub evidence_type: EvidenceType,
}
#[derive(Debug, serde::Deserialize, strum::Display, strum::EnumString, Clone, serde::Serialize)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum EvidenceType {
CancellationPolicy,
CustomerCommunication,
CustomerSignature,
Receipt,
RefundPolicy,
ServiceDocumentation,
ShippingDocumentation,
InvoiceShowingDistinctTransactions,
RecurringTransactionAgreement,
UncategorizedFile,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ProcessDisputePTData {
pub connector_name: String,
pub dispute_payload: types::DisputeSyncResponse,
pub merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct DisputeListPTData {
pub connector_name: String,
pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_id: common_utils::id_type::ProfileId,
pub created_from: time::PrimitiveDateTime,
pub created_till: time::PrimitiveDateTime,
}
|
crates/router/src/types/api/disputes.rs
|
router::src::types::api::disputes
| 611
| true
|
// File: crates/router/src/types/api/disputes_v2.rs
// Module: router::src::types::api::disputes_v2
pub use hyperswitch_interfaces::api::disputes_v2::{
AcceptDisputeV2, DefendDisputeV2, DisputeSyncV2, DisputeV2, FetchDisputesV2, SubmitEvidenceV2,
};
|
crates/router/src/types/api/disputes_v2.rs
|
router::src::types::api::disputes_v2
| 84
| true
|
// File: crates/router/src/types/api/bank_accounts.rs
// Module: router::src::types::api::bank_accounts
|
crates/router/src/types/api/bank_accounts.rs
|
router::src::types::api::bank_accounts
| 27
| true
|
// File: crates/router/src/types/api/enums.rs
// Module: router::src::types::api::enums
pub use api_models::enums::*;
|
crates/router/src/types/api/enums.rs
|
router::src::types::api::enums
| 32
| true
|
// File: crates/router/src/types/api/files.rs
// Module: router::src::types::api::files
use api_models::enums::FileUploadProvider;
pub use hyperswitch_domain_models::router_flow_types::files::{Retrieve, Upload};
pub use hyperswitch_interfaces::api::files::{FilePurpose, FileUpload, RetrieveFile, UploadFile};
use masking::{Deserialize, Serialize};
use serde_with::serde_as;
pub use super::files_v2::{FileUploadV2, RetrieveFileV2, UploadFileV2};
use crate::{
core::errors,
types::{self, transformers::ForeignTryFrom},
};
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct FileId {
pub file_id: String,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct FileRetrieveRequest {
pub file_id: String,
pub dispute_id: Option<String>,
}
#[derive(Debug)]
pub enum FileDataRequired {
Required,
NotRequired,
}
impl ForeignTryFrom<FileUploadProvider> for types::Connector {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(item: FileUploadProvider) -> Result<Self, Self::Error> {
match item {
FileUploadProvider::Stripe => Ok(Self::Stripe),
FileUploadProvider::Checkout => Ok(Self::Checkout),
FileUploadProvider::Worldpayvantiv => Ok(Self::Worldpayvantiv),
FileUploadProvider::Router => Err(errors::ApiErrorResponse::NotSupported {
message: "File upload provider is not a connector".to_owned(),
}
.into()),
}
}
}
impl ForeignTryFrom<&types::Connector> for FileUploadProvider {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(item: &types::Connector) -> Result<Self, Self::Error> {
match *item {
types::Connector::Stripe => Ok(Self::Stripe),
types::Connector::Checkout => Ok(Self::Checkout),
types::Connector::Worldpayvantiv => Ok(Self::Worldpayvantiv),
_ => Err(errors::ApiErrorResponse::NotSupported {
message: "Connector not supported as file provider".to_owned(),
}
.into()),
}
}
}
#[serde_as]
#[derive(Debug, Clone, serde::Serialize)]
pub struct CreateFileRequest {
pub file: Vec<u8>,
pub file_name: Option<String>,
pub file_size: i32,
#[serde_as(as = "serde_with::DisplayFromStr")]
pub file_type: mime::Mime,
pub purpose: FilePurpose,
pub dispute_id: Option<String>,
}
|
crates/router/src/types/api/files.rs
|
router::src::types::api::files
| 556
| true
|
// File: crates/router/src/types/api/verify_connector.rs
// Module: router::src::types::api::verify_connector
pub mod paypal;
pub mod stripe;
use error_stack::ResultExt;
use crate::{
consts,
core::errors,
services::{
self,
connector_integration_interface::{BoxedConnectorIntegrationInterface, ConnectorEnum},
},
types::{self, api, api::ConnectorCommon, domain, storage::enums as storage_enums},
SessionState,
};
#[derive(Clone)]
pub struct VerifyConnectorData {
pub connector: ConnectorEnum,
pub connector_auth: types::ConnectorAuthType,
pub card_details: domain::Card,
}
impl VerifyConnectorData {
fn get_payment_authorize_data(&self) -> types::PaymentsAuthorizeData {
types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(self.card_details.clone()),
email: None,
customer_name: None,
amount: 1000,
minor_amount: common_utils::types::MinorUnit::new(1000),
confirm: true,
order_tax_amount: None,
currency: storage_enums::Currency::USD,
metadata: None,
mandate_id: None,
webhook_url: None,
customer_id: None,
off_session: None,
browser_info: None,
session_token: None,
order_details: None,
order_category: None,
capture_method: None,
enrolled_for_3ds: false,
router_return_url: None,
surcharge_details: None,
setup_future_usage: None,
payment_experience: None,
payment_method_type: None,
statement_descriptor: None,
setup_mandate_details: None,
complete_authorize_url: None,
related_transaction_id: None,
statement_descriptor_suffix: None,
request_extended_authorization: None,
request_incremental_authorization: false,
authentication_data: None,
customer_acceptance: None,
split_payments: None,
merchant_order_reference_id: None,
integrity_object: None,
additional_payment_method_data: None,
shipping_cost: None,
merchant_account_id: None,
merchant_config_currency: None,
connector_testing_data: None,
order_id: None,
locale: None,
payment_channel: None,
enable_partial_authorization: None,
enable_overcapture: None,
is_stored_credential: None,
mit_category: None,
}
}
fn get_router_data<F, R1, R2>(
&self,
state: &SessionState,
request_data: R1,
access_token: Option<types::AccessToken>,
) -> types::RouterData<F, R1, R2> {
let attempt_id =
common_utils::generate_id_with_default_len(consts::VERIFY_CONNECTOR_ID_PREFIX);
types::RouterData {
flow: std::marker::PhantomData,
status: storage_enums::AttemptStatus::Started,
request: request_data,
response: Err(errors::ApiErrorResponse::InternalServerError.into()),
connector: self.connector.id().to_string(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
test_mode: None,
attempt_id: attempt_id.clone(),
description: None,
customer_id: None,
tenant_id: state.tenant.tenant_id.clone(),
merchant_id: common_utils::id_type::MerchantId::default(),
reference_id: None,
access_token,
session_token: None,
payment_method: storage_enums::PaymentMethod::Card,
payment_method_type: None,
amount_captured: None,
minor_amount_captured: None,
preprocessing_id: None,
connector_customer: None,
connector_auth_type: self.connector_auth.clone(),
connector_meta_data: None,
connector_wallets_details: None,
payment_method_token: None,
connector_api_version: None,
recurring_mandate_payment_data: None,
payment_method_status: None,
connector_request_reference_id: attempt_id,
address: types::PaymentAddress::new(None, None, None, None),
payment_id: common_utils::id_type::PaymentId::default()
.get_string_repr()
.to_owned(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
payment_method_balance: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
}
}
}
#[async_trait::async_trait]
pub trait VerifyConnector {
async fn verify(
state: &SessionState,
connector_data: VerifyConnectorData,
) -> errors::RouterResponse<()> {
let authorize_data = connector_data.get_payment_authorize_data();
let access_token = Self::get_access_token(state, connector_data.clone()).await?;
let router_data = connector_data.get_router_data(state, authorize_data, access_token);
let request = connector_data
.connector
.get_connector_integration()
.build_request(&router_data, &state.conf.connectors)
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Payment request cannot be built".to_string(),
})?
.ok_or(errors::ApiErrorResponse::InternalServerError)?;
let response =
services::call_connector_api(&state.to_owned(), request, "verify_connector_request")
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
match response {
Ok(_) => Ok(services::ApplicationResponse::StatusOk),
Err(error_response) => {
Self::handle_payment_error_response::<
api::Authorize,
types::PaymentFlowData,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>(
connector_data.connector.get_connector_integration(),
error_response,
)
.await
}
}
}
async fn get_access_token(
_state: &SessionState,
_connector_data: VerifyConnectorData,
) -> errors::CustomResult<Option<types::AccessToken>, errors::ApiErrorResponse> {
// AccessToken is None for the connectors without the AccessToken Flow.
// If a connector has that, then it should override this implementation.
Ok(None)
}
async fn handle_payment_error_response<F, ResourceCommonData, Req, Resp>(
// connector: &(dyn api::Connector + Sync),
connector: BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>,
error_response: types::Response,
) -> errors::RouterResponse<()> {
let error = connector
.get_error_response(error_response, None)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Err(errors::ApiErrorResponse::InvalidRequestData {
message: error.reason.unwrap_or(error.message),
}
.into())
}
async fn handle_access_token_error_response<F, ResourceCommonData, Req, Resp>(
connector: BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>,
error_response: types::Response,
) -> errors::RouterResult<Option<types::AccessToken>> {
let error = connector
.get_error_response(error_response, None)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Err(errors::ApiErrorResponse::InvalidRequestData {
message: error.reason.unwrap_or(error.message),
}
.into())
}
}
|
crates/router/src/types/api/verify_connector.rs
|
router::src::types::api::verify_connector
| 1,676
| true
|
// File: crates/router/src/types/api/authentication_v2.rs
// Module: router::src::types::api::authentication_v2
pub use hyperswitch_domain_models::router_request_types::authentication::MessageCategory;
pub use hyperswitch_interfaces::api::authentication_v2::ExternalAuthenticationV2;
|
crates/router/src/types/api/authentication_v2.rs
|
router::src::types::api::authentication_v2
| 61
| true
|
// File: crates/router/src/types/api/payment_link.rs
// Module: router::src::types::api::payment_link
pub use api_models::payments::RetrievePaymentLinkResponse;
use crate::{
consts::DEFAULT_SESSION_EXPIRY,
core::{errors::RouterResult, payment_link},
types::storage::{self},
};
#[async_trait::async_trait]
pub(crate) trait PaymentLinkResponseExt: Sized {
async fn from_db_payment_link(payment_link: storage::PaymentLink) -> RouterResult<Self>;
}
#[async_trait::async_trait]
impl PaymentLinkResponseExt for RetrievePaymentLinkResponse {
async fn from_db_payment_link(payment_link: storage::PaymentLink) -> RouterResult<Self> {
let session_expiry = payment_link.fulfilment_time.unwrap_or_else(|| {
payment_link
.created_at
.saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY))
});
let status = payment_link::check_payment_link_status(session_expiry);
Ok(Self {
link_to_pay: payment_link.link_to_pay,
payment_link_id: payment_link.payment_link_id,
amount: payment_link.amount,
description: payment_link.description,
created_at: payment_link.created_at,
merchant_id: payment_link.merchant_id,
expiry: payment_link.fulfilment_time,
currency: payment_link.currency,
status,
secure_link: payment_link.secure_link,
})
}
}
|
crates/router/src/types/api/payment_link.rs
|
router::src::types::api::payment_link
| 299
| true
|
// File: crates/router/src/types/api/poll.rs
// Module: router::src::types::api::poll
use serde;
#[derive(Default, Debug, serde::Deserialize, serde::Serialize)]
pub struct PollId {
pub poll_id: String,
}
|
crates/router/src/types/api/poll.rs
|
router::src::types::api::poll
| 55
| true
|
// File: crates/router/src/types/api/webhooks.rs
// Module: router::src::types::api::webhooks
pub use api_models::webhooks::{
AuthenticationIdType, IncomingWebhookDetails, IncomingWebhookEvent, MerchantWebhookConfig,
ObjectReferenceId, OutgoingWebhook, OutgoingWebhookContent, WebhookFlow,
};
pub use hyperswitch_interfaces::webhooks::{IncomingWebhook, IncomingWebhookRequestDetails};
|
crates/router/src/types/api/webhooks.rs
|
router::src::types::api::webhooks
| 94
| true
|
// File: crates/router/src/types/api/api_keys.rs
// Module: router::src::types::api::api_keys
pub use api_models::api_keys::{
ApiKeyExpiration, CreateApiKeyRequest, CreateApiKeyResponse, ListApiKeyConstraints,
RetrieveApiKeyResponse, RevokeApiKeyResponse, UpdateApiKeyRequest,
};
|
crates/router/src/types/api/api_keys.rs
|
router::src::types::api::api_keys
| 66
| true
|
// File: crates/router/src/types/api/payments_v2.rs
// Module: router::src::types::api::payments_v2
pub use hyperswitch_interfaces::api::payments_v2::{
ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2,
PaymentAuthorizeV2, PaymentCaptureV2, PaymentExtendAuthorizationV2,
PaymentIncrementalAuthorizationV2, PaymentPostCaptureVoidV2, PaymentPostSessionTokensV2,
PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2, PaymentSyncV2, PaymentTokenV2,
PaymentUpdateMetadataV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2,
PaymentsPostProcessingV2, PaymentsPreProcessingV2, TaxCalculationV2,
};
|
crates/router/src/types/api/payments_v2.rs
|
router::src::types::api::payments_v2
| 174
| true
|
// File: crates/router/src/types/api/customers.rs
// Module: router::src::types::api::customers
use api_models::customers;
pub use api_models::customers::{
CustomerDeleteResponse, CustomerListRequest, CustomerListRequestWithConstraints,
CustomerListResponse, CustomerRequest, CustomerUpdateRequest, CustomerUpdateRequestInternal,
};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::customer;
use serde::Serialize;
#[cfg(feature = "v1")]
use super::payments;
use crate::{
newtype,
types::{domain, ForeignFrom},
};
newtype!(
pub CustomerResponse = customers::CustomerResponse,
derives = (Debug, Clone, Serialize)
);
impl common_utils::events::ApiEventMetric for CustomerResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
self.0.get_api_event_type()
}
}
#[cfg(feature = "v1")]
impl ForeignFrom<(domain::Customer, Option<payments::AddressDetails>)> for CustomerResponse {
fn foreign_from((cust, address): (domain::Customer, Option<payments::AddressDetails>)) -> Self {
customers::CustomerResponse {
customer_id: cust.customer_id,
name: cust.name,
email: cust.email,
phone: cust.phone,
phone_country_code: cust.phone_country_code,
description: cust.description,
created_at: cust.created_at,
metadata: cust.metadata,
address,
default_payment_method_id: cust.default_payment_method_id,
tax_registration_id: cust.tax_registration_id,
}
.into()
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<customer::Customer> for CustomerResponse {
fn foreign_from(cust: domain::Customer) -> Self {
customers::CustomerResponse {
id: cust.id,
merchant_reference_id: cust.merchant_reference_id,
connector_customer_ids: cust.connector_customer,
name: cust.name,
email: cust.email,
phone: cust.phone,
phone_country_code: cust.phone_country_code,
description: cust.description,
created_at: cust.created_at,
metadata: cust.metadata,
default_billing_address: None,
default_shipping_address: None,
default_payment_method_id: cust.default_payment_method_id,
tax_registration_id: cust.tax_registration_id,
}
.into()
}
}
|
crates/router/src/types/api/customers.rs
|
router::src::types::api::customers
| 502
| true
|
// File: crates/router/src/types/api/authentication.rs
// Module: router::src::types::api::authentication
use std::str::FromStr;
use api_models::enums;
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
pub use hyperswitch_domain_models::{
router_flow_types::authentication::{
Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall,
},
router_request_types::authentication::MessageCategory,
};
use crate::{
connector, core::errors, services::connector_integration_interface::ConnectorEnum,
types::storage,
};
#[derive(Clone, serde::Deserialize, Debug, serde::Serialize)]
pub struct AcquirerDetails {
pub acquirer_bin: String,
pub acquirer_merchant_mid: String,
pub acquirer_country_code: Option<String>,
}
#[derive(Clone, serde::Deserialize, Debug, serde::Serialize)]
pub struct AuthenticationResponse {
pub trans_status: common_enums::TransactionStatus,
pub acs_url: Option<url::Url>,
pub challenge_request: Option<String>,
pub challenge_request_key: Option<String>,
pub acs_reference_number: Option<String>,
pub acs_trans_id: Option<String>,
pub three_dsserver_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
}
impl TryFrom<storage::Authentication> for AuthenticationResponse {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(authentication: storage::Authentication) -> Result<Self, Self::Error> {
let trans_status = authentication.trans_status.ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("trans_status must be populated in authentication table authentication call is successful")?;
let acs_url = authentication
.acs_url
.map(|url| url::Url::from_str(&url))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("not a valid URL")?;
Ok(Self {
trans_status,
acs_url,
challenge_request: authentication.challenge_request,
acs_reference_number: authentication.acs_reference_number,
acs_trans_id: authentication.acs_trans_id,
three_dsserver_trans_id: authentication.threeds_server_transaction_id,
acs_signed_content: authentication.acs_signed_content,
challenge_request_key: authentication.challenge_request_key,
})
}
}
#[derive(Clone, serde::Deserialize, Debug, serde::Serialize)]
pub struct PostAuthenticationResponse {
pub trans_status: String,
pub authentication_value: Option<masking::Secret<String>>,
pub eci: Option<String>,
}
#[derive(Clone)]
pub struct AuthenticationConnectorData {
pub connector: ConnectorEnum,
pub connector_name: enums::AuthenticationConnectors,
}
impl AuthenticationConnectorData {
pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> {
let connector_name = enums::AuthenticationConnectors::from_str(name)
.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
.attach_printable_lazy(|| format!("unable to parse connector: {name}"))?;
let connector = Self::convert_connector(connector_name)?;
Ok(Self {
connector,
connector_name,
})
}
fn convert_connector(
connector_name: enums::AuthenticationConnectors,
) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> {
match connector_name {
enums::AuthenticationConnectors::Threedsecureio => {
Ok(ConnectorEnum::Old(Box::new(&connector::Threedsecureio)))
}
enums::AuthenticationConnectors::Netcetera => {
Ok(ConnectorEnum::Old(Box::new(&connector::Netcetera)))
}
enums::AuthenticationConnectors::Gpayments => {
Ok(ConnectorEnum::Old(Box::new(connector::Gpayments::new())))
}
enums::AuthenticationConnectors::CtpMastercard => {
Ok(ConnectorEnum::Old(Box::new(&connector::CtpMastercard)))
}
enums::AuthenticationConnectors::CtpVisa => Ok(ConnectorEnum::Old(Box::new(
connector::UnifiedAuthenticationService::new(),
))),
enums::AuthenticationConnectors::UnifiedAuthenticationService => Ok(
ConnectorEnum::Old(Box::new(connector::UnifiedAuthenticationService::new())),
),
enums::AuthenticationConnectors::Juspaythreedsserver => Ok(ConnectorEnum::Old(
Box::new(connector::Juspaythreedsserver::new()),
)),
enums::AuthenticationConnectors::Cardinal => Ok(ConnectorEnum::Old(Box::new(
connector::UnifiedAuthenticationService::new(),
))),
}
}
}
|
crates/router/src/types/api/authentication.rs
|
router::src::types::api::authentication
| 988
| true
|
// File: crates/router/src/types/api/routing.rs
// Module: router::src::types::api::routing
pub use api_models::{
enums as api_enums,
routing::{
ConnectorVolumeSplit, RoutableChoiceKind, RoutableConnectorChoice, RoutingAlgorithmKind,
RoutingAlgorithmRef, RoutingConfigRequest, RoutingDictionary, RoutingDictionaryRecord,
StaticRoutingAlgorithm, StraightThroughAlgorithm,
},
};
use super::types::api as api_oss;
pub struct SessionRoutingChoice {
pub connector: api_oss::ConnectorData,
pub payment_method_type: api_enums::PaymentMethodType,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConnectorVolumeSplitV0 {
pub connector: RoutableConnectorChoice,
pub split: u8,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum RoutingAlgorithmV0 {
Single(Box<RoutableConnectorChoice>),
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplitV0>),
Custom { timestamp: i64 },
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct FrmRoutingAlgorithm {
pub data: String,
#[serde(rename = "type")]
pub algorithm_type: String,
}
|
crates/router/src/types/api/routing.rs
|
router::src::types::api::routing
| 293
| true
|
// File: crates/router/src/types/api/ephemeral_key.rs
// Module: router::src::types::api::ephemeral_key
pub use api_models::ephemeral_key::*;
|
crates/router/src/types/api/ephemeral_key.rs
|
router::src::types::api::ephemeral_key
| 41
| true
|
// File: crates/router/src/types/api/mandates.rs
// Module: router::src::types::api::mandates
use ::payment_methods::controller::PaymentMethodsController;
use api_models::mandates;
pub use api_models::mandates::{MandateId, MandateResponse, MandateRevokedResponse};
use common_utils::ext_traits::OptionExt;
use error_stack::ResultExt;
use serde::{Deserialize, Serialize};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payment_methods,
},
newtype,
routes::SessionState,
types::{
api, domain,
storage::{self, enums as storage_enums},
},
};
newtype!(
pub MandateCardDetails = mandates::MandateCardDetails,
derives = (Default, Debug, Deserialize, Serialize)
);
#[async_trait::async_trait]
pub(crate) trait MandateResponseExt: Sized {
async fn from_db_mandate(
state: &SessionState,
key_store: domain::MerchantKeyStore,
mandate: storage::Mandate,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<Self>;
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl MandateResponseExt for MandateResponse {
async fn from_db_mandate(
state: &SessionState,
key_store: domain::MerchantKeyStore,
mandate: storage::Mandate,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<Self> {
let db = &*state.store;
let payment_method = db
.find_payment_method(
&(state.into()),
&key_store,
&mandate.payment_method_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let pm = payment_method
.get_payment_method_type()
.get_required_value("payment_method")
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("payment_method not found")?;
let card = if pm == storage_enums::PaymentMethod::Card {
// if locker is disabled , decrypt the payment method data
let card_details = if state.conf.locker.locker_enabled {
let card = payment_methods::cards::get_card_from_locker(
state,
&payment_method.customer_id,
&payment_method.merchant_id,
payment_method
.locker_id
.as_ref()
.unwrap_or(payment_method.get_id()),
)
.await?;
payment_methods::transformers::get_card_detail(&payment_method, card)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting card details")?
} else {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(merchant_account.clone(), key_store),
));
payment_methods::cards::PmCards {
state,
merchant_context: &merchant_context,
}
.get_card_details_without_locker_fallback(&payment_method)
.await?
};
Some(MandateCardDetails::from(card_details).into_inner())
} else {
None
};
let payment_method_type = payment_method
.get_payment_method_subtype()
.map(|pmt| pmt.to_string());
let user_agent = mandate.get_user_agent_extended().unwrap_or_default();
Ok(Self {
mandate_id: mandate.mandate_id,
customer_acceptance: Some(api::payments::CustomerAcceptance {
acceptance_type: if mandate.customer_ip_address.is_some() {
api::payments::AcceptanceType::Online
} else {
api::payments::AcceptanceType::Offline
},
accepted_at: mandate.customer_accepted_at,
online: Some(api::payments::OnlineMandate {
ip_address: mandate.customer_ip_address,
user_agent,
}),
}),
card,
status: mandate.mandate_status,
payment_method: pm.to_string(),
payment_method_type,
payment_method_id: mandate.payment_method_id,
})
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl MandateResponseExt for MandateResponse {
async fn from_db_mandate(
state: &SessionState,
key_store: domain::MerchantKeyStore,
mandate: storage::Mandate,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<Self> {
todo!()
}
}
#[cfg(feature = "v1")]
impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails {
fn from(card_details_from_locker: api::payment_methods::CardDetailFromLocker) -> Self {
mandates::MandateCardDetails {
last4_digits: card_details_from_locker.last4_digits,
card_exp_month: card_details_from_locker.expiry_month.clone(),
card_exp_year: card_details_from_locker.expiry_year.clone(),
card_holder_name: card_details_from_locker.card_holder_name,
card_token: card_details_from_locker.card_token,
scheme: card_details_from_locker.scheme,
issuer_country: card_details_from_locker.issuer_country,
card_fingerprint: card_details_from_locker.card_fingerprint,
card_isin: card_details_from_locker.card_isin,
card_issuer: card_details_from_locker.card_issuer,
card_network: card_details_from_locker.card_network,
card_type: card_details_from_locker.card_type,
nick_name: card_details_from_locker.nick_name,
}
.into()
}
}
#[cfg(feature = "v2")]
impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails {
fn from(card_details_from_locker: api::payment_methods::CardDetailFromLocker) -> Self {
mandates::MandateCardDetails {
last4_digits: card_details_from_locker.last4_digits,
card_exp_month: card_details_from_locker.expiry_month.clone(),
card_exp_year: card_details_from_locker.expiry_year.clone(),
card_holder_name: card_details_from_locker.card_holder_name,
card_token: None,
scheme: None,
issuer_country: card_details_from_locker
.issuer_country
.map(|country| country.to_string()),
card_fingerprint: card_details_from_locker.card_fingerprint,
card_isin: card_details_from_locker.card_isin,
card_issuer: card_details_from_locker.card_issuer,
card_network: card_details_from_locker.card_network,
card_type: card_details_from_locker
.card_type
.as_ref()
.map(|c| c.to_string()),
nick_name: card_details_from_locker.nick_name,
}
.into()
}
}
|
crates/router/src/types/api/mandates.rs
|
router::src::types::api::mandates
| 1,460
| true
|
// File: crates/router/src/types/api/feature_matrix.rs
// Module: router::src::types::api::feature_matrix
use std::str::FromStr;
use error_stack::{report, ResultExt};
use crate::{
connector,
core::errors::{self, CustomResult},
services::connector_integration_interface::ConnectorEnum,
types::api::enums,
};
#[derive(Clone)]
pub struct FeatureMatrixConnectorData {}
impl FeatureMatrixConnectorData {
pub fn convert_connector(
connector_name: &str,
) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> {
match enums::Connector::from_str(connector_name) {
Ok(name) => match name {
enums::Connector::Aci => Ok(ConnectorEnum::Old(Box::new(connector::Aci::new()))),
enums::Connector::Adyen => {
Ok(ConnectorEnum::Old(Box::new(connector::Adyen::new())))
}
enums::Connector::Affirm => {
Ok(ConnectorEnum::Old(Box::new(connector::Affirm::new())))
}
enums::Connector::Adyenplatform => Ok(ConnectorEnum::Old(Box::new(
connector::Adyenplatform::new(),
))),
enums::Connector::Airwallex => {
Ok(ConnectorEnum::Old(Box::new(connector::Airwallex::new())))
}
enums::Connector::Amazonpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Amazonpay::new())))
}
enums::Connector::Archipel => {
Ok(ConnectorEnum::Old(Box::new(connector::Archipel::new())))
}
enums::Connector::Authipay => {
Ok(ConnectorEnum::Old(Box::new(connector::Authipay::new())))
}
enums::Connector::Authorizedotnet => Ok(ConnectorEnum::Old(Box::new(
connector::Authorizedotnet::new(),
))),
enums::Connector::Bambora => {
Ok(ConnectorEnum::Old(Box::new(connector::Bambora::new())))
}
enums::Connector::Bamboraapac => {
Ok(ConnectorEnum::Old(Box::new(connector::Bamboraapac::new())))
}
enums::Connector::Bankofamerica => Ok(ConnectorEnum::Old(Box::new(
connector::Bankofamerica::new(),
))),
enums::Connector::Barclaycard => {
Ok(ConnectorEnum::Old(Box::new(connector::Barclaycard::new())))
}
enums::Connector::Billwerk => {
Ok(ConnectorEnum::Old(Box::new(connector::Billwerk::new())))
}
enums::Connector::Bitpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Bitpay::new())))
}
enums::Connector::Blackhawknetwork => Ok(ConnectorEnum::Old(Box::new(
connector::Blackhawknetwork::new(),
))),
enums::Connector::Bluesnap => {
Ok(ConnectorEnum::Old(Box::new(connector::Bluesnap::new())))
}
enums::Connector::Calida => {
Ok(ConnectorEnum::Old(Box::new(connector::Calida::new())))
}
enums::Connector::Boku => Ok(ConnectorEnum::Old(Box::new(connector::Boku::new()))),
enums::Connector::Braintree => {
Ok(ConnectorEnum::Old(Box::new(connector::Braintree::new())))
}
enums::Connector::Breadpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Breadpay::new())))
}
enums::Connector::Cashtocode => {
Ok(ConnectorEnum::Old(Box::new(connector::Cashtocode::new())))
}
enums::Connector::Celero => {
Ok(ConnectorEnum::Old(Box::new(connector::Celero::new())))
}
enums::Connector::Chargebee => {
Ok(ConnectorEnum::Old(Box::new(connector::Chargebee::new())))
}
enums::Connector::Checkbook => {
Ok(ConnectorEnum::Old(Box::new(connector::Checkbook::new())))
}
enums::Connector::Checkout => {
Ok(ConnectorEnum::Old(Box::new(connector::Checkout::new())))
}
enums::Connector::Coinbase => {
Ok(ConnectorEnum::Old(Box::new(connector::Coinbase::new())))
}
enums::Connector::Coingate => {
Ok(ConnectorEnum::Old(Box::new(connector::Coingate::new())))
}
enums::Connector::Cryptopay => {
Ok(ConnectorEnum::Old(Box::new(connector::Cryptopay::new())))
}
enums::Connector::CtpMastercard => {
Ok(ConnectorEnum::Old(Box::new(&connector::CtpMastercard)))
}
enums::Connector::Custombilling => Ok(ConnectorEnum::Old(Box::new(
connector::Custombilling::new(),
))),
enums::Connector::CtpVisa => Ok(ConnectorEnum::Old(Box::new(
connector::UnifiedAuthenticationService::new(),
))),
enums::Connector::Cybersource => {
Ok(ConnectorEnum::Old(Box::new(connector::Cybersource::new())))
}
enums::Connector::Datatrans => {
Ok(ConnectorEnum::Old(Box::new(connector::Datatrans::new())))
}
enums::Connector::Deutschebank => {
Ok(ConnectorEnum::Old(Box::new(connector::Deutschebank::new())))
}
enums::Connector::Digitalvirgo => {
Ok(ConnectorEnum::Old(Box::new(connector::Digitalvirgo::new())))
}
enums::Connector::Dlocal => {
Ok(ConnectorEnum::Old(Box::new(connector::Dlocal::new())))
}
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector1 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<1>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector2 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<2>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector3 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<3>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector4 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<4>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector5 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<5>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector6 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<6>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector7 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<7>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyBillingConnector => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<8>::new(),
))),
enums::Connector::Dwolla => {
Ok(ConnectorEnum::Old(Box::new(connector::Dwolla::new())))
}
enums::Connector::Ebanx => {
Ok(ConnectorEnum::Old(Box::new(connector::Ebanx::new())))
}
enums::Connector::Elavon => {
Ok(ConnectorEnum::Old(Box::new(connector::Elavon::new())))
}
enums::Connector::Facilitapay => {
Ok(ConnectorEnum::Old(Box::new(connector::Facilitapay::new())))
}
enums::Connector::Finix => {
Ok(ConnectorEnum::Old(Box::new(connector::Finix::new())))
}
enums::Connector::Fiserv => {
Ok(ConnectorEnum::Old(Box::new(connector::Fiserv::new())))
}
enums::Connector::Fiservemea => {
Ok(ConnectorEnum::Old(Box::new(connector::Fiservemea::new())))
}
enums::Connector::Fiuu => Ok(ConnectorEnum::Old(Box::new(connector::Fiuu::new()))),
enums::Connector::Forte => {
Ok(ConnectorEnum::Old(Box::new(connector::Forte::new())))
}
enums::Connector::Flexiti => {
Ok(ConnectorEnum::Old(Box::new(connector::Flexiti::new())))
}
enums::Connector::Getnet => {
Ok(ConnectorEnum::Old(Box::new(connector::Getnet::new())))
}
enums::Connector::Gigadat => {
Ok(ConnectorEnum::Old(Box::new(connector::Gigadat::new())))
}
enums::Connector::Globalpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Globalpay::new())))
}
enums::Connector::Globepay => {
Ok(ConnectorEnum::Old(Box::new(connector::Globepay::new())))
}
enums::Connector::Gocardless => {
Ok(ConnectorEnum::Old(Box::new(connector::Gocardless::new())))
}
enums::Connector::Hipay => {
Ok(ConnectorEnum::Old(Box::new(connector::Hipay::new())))
}
enums::Connector::Helcim => {
Ok(ConnectorEnum::Old(Box::new(connector::Helcim::new())))
}
enums::Connector::HyperswitchVault => {
Ok(ConnectorEnum::Old(Box::new(&connector::HyperswitchVault)))
}
enums::Connector::Iatapay => {
Ok(ConnectorEnum::Old(Box::new(connector::Iatapay::new())))
}
enums::Connector::Inespay => {
Ok(ConnectorEnum::Old(Box::new(connector::Inespay::new())))
}
enums::Connector::Itaubank => {
Ok(ConnectorEnum::Old(Box::new(connector::Itaubank::new())))
}
enums::Connector::Jpmorgan => {
Ok(ConnectorEnum::Old(Box::new(connector::Jpmorgan::new())))
}
enums::Connector::Juspaythreedsserver => Ok(ConnectorEnum::Old(Box::new(
connector::Juspaythreedsserver::new(),
))),
enums::Connector::Klarna => {
Ok(ConnectorEnum::Old(Box::new(connector::Klarna::new())))
}
enums::Connector::Loonio => {
Ok(ConnectorEnum::Old(Box::new(connector::Loonio::new())))
}
enums::Connector::Mollie => {
// enums::Connector::Moneris => Ok(ConnectorEnum::Old(Box::new(connector::Moneris))),
Ok(ConnectorEnum::Old(Box::new(connector::Mollie::new())))
}
enums::Connector::Moneris => {
Ok(ConnectorEnum::Old(Box::new(connector::Moneris::new())))
}
enums::Connector::Nexixpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Nexixpay::new())))
}
enums::Connector::Nmi => Ok(ConnectorEnum::Old(Box::new(connector::Nmi::new()))),
enums::Connector::Nomupay => {
Ok(ConnectorEnum::Old(Box::new(connector::Nomupay::new())))
}
enums::Connector::Noon => Ok(ConnectorEnum::Old(Box::new(connector::Noon::new()))),
enums::Connector::Nordea => {
Ok(ConnectorEnum::Old(Box::new(connector::Nordea::new())))
}
enums::Connector::Novalnet => {
Ok(ConnectorEnum::Old(Box::new(connector::Novalnet::new())))
}
enums::Connector::Nuvei => {
Ok(ConnectorEnum::Old(Box::new(connector::Nuvei::new())))
}
enums::Connector::Opennode => {
Ok(ConnectorEnum::Old(Box::new(connector::Opennode::new())))
}
enums::Connector::Phonepe => {
Ok(ConnectorEnum::Old(Box::new(connector::Phonepe::new())))
}
enums::Connector::Paybox => {
Ok(ConnectorEnum::Old(Box::new(connector::Paybox::new())))
}
enums::Connector::Paytm => {
Ok(ConnectorEnum::Old(Box::new(connector::Paytm::new())))
}
// "payeezy" => Ok(ConnectorIntegrationEnum::Old(Box::new(&connector::Payeezy)), As psync and rsync are not supported by this connector, it is added as template code for future usage
// enums::Connector::Payload => {
// Ok(ConnectorEnum::Old(Box::new(connector::Paybload::new())))
// }
enums::Connector::Payload => {
Ok(ConnectorEnum::Old(Box::new(connector::Payload::new())))
}
enums::Connector::Payme => {
Ok(ConnectorEnum::Old(Box::new(connector::Payme::new())))
}
enums::Connector::Payone => {
Ok(ConnectorEnum::Old(Box::new(connector::Payone::new())))
}
enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(connector::Payu::new()))),
enums::Connector::Peachpayments => Ok(ConnectorEnum::Old(Box::new(
connector::Peachpayments::new(),
))),
enums::Connector::Placetopay => {
Ok(ConnectorEnum::Old(Box::new(connector::Placetopay::new())))
}
enums::Connector::Powertranz => {
Ok(ConnectorEnum::Old(Box::new(connector::Powertranz::new())))
}
enums::Connector::Prophetpay => {
Ok(ConnectorEnum::Old(Box::new(&connector::Prophetpay)))
}
enums::Connector::Razorpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Razorpay::new())))
}
enums::Connector::Rapyd => {
Ok(ConnectorEnum::Old(Box::new(connector::Rapyd::new())))
}
enums::Connector::Recurly => {
Ok(ConnectorEnum::New(Box::new(connector::Recurly::new())))
}
enums::Connector::Redsys => {
Ok(ConnectorEnum::Old(Box::new(connector::Redsys::new())))
}
enums::Connector::Santander => {
Ok(ConnectorEnum::Old(Box::new(connector::Santander::new())))
}
enums::Connector::Shift4 => {
Ok(ConnectorEnum::Old(Box::new(connector::Shift4::new())))
}
enums::Connector::Square => Ok(ConnectorEnum::Old(Box::new(&connector::Square))),
enums::Connector::Stax => Ok(ConnectorEnum::Old(Box::new(&connector::Stax))),
enums::Connector::Stripe => {
Ok(ConnectorEnum::Old(Box::new(connector::Stripe::new())))
}
enums::Connector::Stripebilling => Ok(ConnectorEnum::Old(Box::new(
connector::Stripebilling::new(),
))),
enums::Connector::Wise => Ok(ConnectorEnum::Old(Box::new(connector::Wise::new()))),
enums::Connector::Worldline => {
Ok(ConnectorEnum::Old(Box::new(&connector::Worldline)))
}
enums::Connector::Worldpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Worldpay::new())))
}
enums::Connector::Worldpayvantiv => Ok(ConnectorEnum::Old(Box::new(
connector::Worldpayvantiv::new(),
))),
enums::Connector::Worldpayxml => {
Ok(ConnectorEnum::Old(Box::new(connector::Worldpayxml::new())))
}
enums::Connector::Xendit => {
Ok(ConnectorEnum::Old(Box::new(connector::Xendit::new())))
}
enums::Connector::Mifinity => {
Ok(ConnectorEnum::Old(Box::new(connector::Mifinity::new())))
}
enums::Connector::Multisafepay => {
Ok(ConnectorEnum::Old(Box::new(connector::Multisafepay::new())))
}
enums::Connector::Netcetera => {
Ok(ConnectorEnum::Old(Box::new(&connector::Netcetera)))
}
enums::Connector::Nexinets => {
Ok(ConnectorEnum::Old(Box::new(&connector::Nexinets)))
}
// enums::Connector::Nexixpay => {
// Ok(ConnectorEnum::Old(Box::new(&connector::Nexixpay)))
// }
enums::Connector::Paypal => {
Ok(ConnectorEnum::Old(Box::new(connector::Paypal::new())))
}
enums::Connector::Paysafe => {
Ok(ConnectorEnum::Old(Box::new(connector::Paysafe::new())))
}
enums::Connector::Paystack => {
Ok(ConnectorEnum::Old(Box::new(connector::Paystack::new())))
}
// enums::Connector::Thunes => Ok(ConnectorEnum::Old(Box::new(connector::Thunes))),
enums::Connector::Tesouro => {
Ok(ConnectorEnum::Old(Box::new(connector::Tesouro::new())))
}
enums::Connector::Tokenex => Ok(ConnectorEnum::Old(Box::new(&connector::Tokenex))),
enums::Connector::Tokenio => {
Ok(ConnectorEnum::Old(Box::new(connector::Tokenio::new())))
}
enums::Connector::Trustpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Trustpay::new())))
}
enums::Connector::Trustpayments => Ok(ConnectorEnum::Old(Box::new(
connector::Trustpayments::new(),
))),
enums::Connector::Tsys => Ok(ConnectorEnum::Old(Box::new(connector::Tsys::new()))),
// enums::Connector::UnifiedAuthenticationService => Ok(ConnectorEnum::Old(Box::new(
// connector::UnifiedAuthenticationService,
// ))),
enums::Connector::Vgs => Ok(ConnectorEnum::Old(Box::new(&connector::Vgs))),
enums::Connector::Volt => Ok(ConnectorEnum::Old(Box::new(connector::Volt::new()))),
enums::Connector::Wellsfargo => {
Ok(ConnectorEnum::Old(Box::new(connector::Wellsfargo::new())))
}
// enums::Connector::Wellsfargopayout => {
// Ok(Box::new(connector::Wellsfargopayout::new()))
// }
enums::Connector::Zen => Ok(ConnectorEnum::Old(Box::new(&connector::Zen))),
enums::Connector::Zsl => Ok(ConnectorEnum::Old(Box::new(&connector::Zsl))),
enums::Connector::Plaid => {
Ok(ConnectorEnum::Old(Box::new(connector::Plaid::new())))
}
enums::Connector::Signifyd => {
Ok(ConnectorEnum::Old(Box::new(&connector::Signifyd)))
}
enums::Connector::Silverflow => {
Ok(ConnectorEnum::Old(Box::new(connector::Silverflow::new())))
}
enums::Connector::Riskified => {
Ok(ConnectorEnum::Old(Box::new(connector::Riskified::new())))
}
enums::Connector::Gpayments => {
Ok(ConnectorEnum::Old(Box::new(connector::Gpayments::new())))
}
enums::Connector::Threedsecureio => {
Ok(ConnectorEnum::Old(Box::new(&connector::Threedsecureio)))
}
enums::Connector::Taxjar => {
Ok(ConnectorEnum::Old(Box::new(connector::Taxjar::new())))
}
enums::Connector::Cardinal => {
Err(report!(errors::ConnectorError::InvalidConnectorName)
.attach_printable(format!("invalid connector name: {connector_name}")))
.change_context(errors::ApiErrorResponse::InternalServerError)
}
},
Err(_) => Err(report!(errors::ConnectorError::InvalidConnectorName)
.attach_printable(format!("invalid connector name: {connector_name}")))
.change_context(errors::ApiErrorResponse::InternalServerError),
}
}
}
|
crates/router/src/types/api/feature_matrix.rs
|
router::src::types::api::feature_matrix
| 4,494
| true
|
// File: crates/router/src/types/api/files_v2.rs
// Module: router::src::types::api::files_v2
pub use hyperswitch_domain_models::router_flow_types::files::{Retrieve, Upload};
pub use hyperswitch_interfaces::api::files_v2::{FileUploadV2, RetrieveFileV2, UploadFileV2};
|
crates/router/src/types/api/files_v2.rs
|
router::src::types::api::files_v2
| 72
| true
|
// File: crates/router/src/types/api/webhook_events.rs
// Module: router::src::types::api::webhook_events
pub use api_models::webhook_events::{
EventListConstraints, EventListConstraintsInternal, EventListItemResponse,
EventListRequestInternal, EventRetrieveResponse, OutgoingWebhookRequestContent,
OutgoingWebhookResponseContent, TotalEventsResponse, WebhookDeliveryAttemptListRequestInternal,
WebhookDeliveryRetryRequestInternal,
};
|
crates/router/src/types/api/webhook_events.rs
|
router::src::types::api::webhook_events
| 97
| true
|
// File: crates/router/src/types/api/admin.rs
// Module: router::src::types::api::admin
use std::collections::HashMap;
#[cfg(feature = "v2")]
pub use api_models::admin;
pub use api_models::{
admin::{
MaskedHeaders, MerchantAccountCreate, MerchantAccountDeleteResponse,
MerchantAccountResponse, MerchantAccountUpdate, MerchantConnectorCreate,
MerchantConnectorDeleteResponse, MerchantConnectorDetails, MerchantConnectorDetailsWrap,
MerchantConnectorId, MerchantConnectorResponse, MerchantDetails, MerchantId,
PaymentMethodsEnabled, ProfileCreate, ProfileResponse, ProfileUpdate, ToggleAllKVRequest,
ToggleAllKVResponse, ToggleKVRequest, ToggleKVResponse, WebhookDetails,
},
organization::{
OrganizationCreateRequest, OrganizationId, OrganizationResponse, OrganizationUpdateRequest,
},
};
use common_utils::{ext_traits::ValueExt, types::keymanager as km_types};
use diesel_models::{business_profile::CardTestingGuardConfig, organization::OrganizationBridge};
use error_stack::ResultExt;
use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;
use masking::{ExposeInterface, PeekInterface, Secret};
use crate::{
consts,
core::errors,
routes::SessionState,
types::{
domain::{
self,
types::{self as domain_types, AsyncLift},
},
transformers::{ForeignInto, ForeignTryFrom},
ForeignFrom,
},
utils,
};
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ProfileAcquirerConfigs {
pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>,
pub profile_id: common_utils::id_type::ProfileId,
}
impl From<ProfileAcquirerConfigs>
for Option<Vec<api_models::profile_acquirer::ProfileAcquirerResponse>>
{
fn from(item: ProfileAcquirerConfigs) -> Self {
item.acquirer_config_map.map(|config_map_val| {
let mut vec: Vec<_> = config_map_val.0.into_iter().collect();
vec.sort_by_key(|k| k.0.clone());
vec.into_iter()
.map(|(profile_acquirer_id, acquirer_config)| {
api_models::profile_acquirer::ProfileAcquirerResponse::from((
profile_acquirer_id,
&item.profile_id,
&acquirer_config,
))
})
.collect::<Vec<api_models::profile_acquirer::ProfileAcquirerResponse>>()
})
}
}
impl ForeignFrom<diesel_models::organization::Organization> for OrganizationResponse {
fn foreign_from(org: diesel_models::organization::Organization) -> Self {
Self {
#[cfg(feature = "v2")]
id: org.get_organization_id(),
#[cfg(feature = "v1")]
organization_id: org.get_organization_id(),
organization_name: org.get_organization_name(),
organization_details: org.organization_details,
metadata: org.metadata,
modified_at: org.modified_at,
created_at: org.created_at,
organization_type: org.organization_type,
}
}
}
#[cfg(feature = "v1")]
impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse {
type Error = error_stack::Report<errors::ParsingError>;
fn foreign_try_from(item: domain::MerchantAccount) -> Result<Self, Self::Error> {
let merchant_id = item.get_id().to_owned();
let primary_business_details: Vec<api_models::admin::PrimaryBusinessDetails> = item
.primary_business_details
.parse_value("primary_business_details")?;
let pm_collect_link_config: Option<api_models::admin::BusinessCollectLinkConfig> = item
.pm_collect_link_config
.map(|config| config.parse_value("pm_collect_link_config"))
.transpose()?;
Ok(Self {
merchant_id,
merchant_name: item.merchant_name,
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_details: item.merchant_details,
webhook_details: item.webhook_details.clone().map(ForeignInto::foreign_into),
routing_algorithm: item.routing_algorithm,
sub_merchants_enabled: item.sub_merchants_enabled,
parent_merchant_id: item.parent_merchant_id,
publishable_key: Some(item.publishable_key),
metadata: item.metadata,
locker_id: item.locker_id,
primary_business_details,
frm_routing_algorithm: item.frm_routing_algorithm,
#[cfg(feature = "payouts")]
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,
pm_collect_link_config,
product_type: item.product_type,
merchant_account_type: item.merchant_account_type,
})
}
}
#[cfg(feature = "v2")]
impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse {
type Error = error_stack::Report<errors::ValidationError>;
fn foreign_try_from(item: domain::MerchantAccount) -> Result<Self, Self::Error> {
use common_utils::ext_traits::OptionExt;
let id = item.get_id().to_owned();
let merchant_name = item
.merchant_name
.get_required_value("merchant_name")?
.into_inner();
Ok(Self {
id,
merchant_name,
merchant_details: item.merchant_details,
publishable_key: item.publishable_key,
metadata: item.metadata,
organization_id: item.organization_id,
recon_status: item.recon_status,
product_type: item.product_type,
})
}
}
#[cfg(feature = "v1")]
impl ForeignTryFrom<domain::Profile> for ProfileResponse {
type Error = error_stack::Report<errors::ParsingError>;
fn foreign_try_from(item: domain::Profile) -> Result<Self, Self::Error> {
let profile_id = item.get_id().to_owned();
let outgoing_webhook_custom_http_headers = item
.outgoing_webhook_custom_http_headers
.map(|headers| {
headers
.into_inner()
.expose()
.parse_value::<HashMap<String, Secret<String>>>(
"HashMap<String, Secret<String>>",
)
})
.transpose()?;
let masked_outgoing_webhook_custom_http_headers =
outgoing_webhook_custom_http_headers.map(MaskedHeaders::from_headers);
let card_testing_guard_config = item
.card_testing_guard_config
.or(Some(CardTestingGuardConfig::default()));
let (is_external_vault_enabled, external_vault_connector_details) =
item.external_vault_details.into();
Ok(Self {
merchant_id: item.merchant_id,
profile_id: profile_id.clone(),
profile_name: item.profile_name,
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,
webhook_details: item.webhook_details.map(ForeignInto::foreign_into),
metadata: item.metadata,
routing_algorithm: item.routing_algorithm,
intent_fulfillment_time: item.intent_fulfillment_time,
frm_routing_algorithm: item.frm_routing_algorithm,
#[cfg(feature = "payouts")]
payout_routing_algorithm: item.payout_routing_algorithm,
applepay_verified_domains: item.applepay_verified_domains,
payment_link_config: item.payment_link_config.map(ForeignInto::foreign_into),
session_expiry: item.session_expiry,
authentication_connector_details: item
.authentication_connector_details
.map(ForeignInto::foreign_into),
payout_link_config: item.payout_link_config.map(ForeignInto::foreign_into),
use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing,
extended_card_info_config: item
.extended_card_info_config
.map(|config| config.expose().parse_value("ExtendedCardInfoConfig"))
.transpose()?,
collect_shipping_details_from_wallet_connector: item
.collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector: item
.collect_billing_details_from_wallet_connector,
always_collect_billing_details_from_wallet_connector: item
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: item
.always_collect_shipping_details_from_wallet_connector,
is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled,
outgoing_webhook_custom_http_headers: masked_outgoing_webhook_custom_http_headers,
tax_connector_id: item.tax_connector_id,
is_tax_connector_enabled: item.is_tax_connector_enabled,
is_network_tokenization_enabled: item.is_network_tokenization_enabled,
is_auto_retries_enabled: item.is_auto_retries_enabled,
max_auto_retries_enabled: item.max_auto_retries_enabled,
always_request_extended_authorization: item.always_request_extended_authorization,
is_click_to_pay_enabled: item.is_click_to_pay_enabled,
authentication_product_ids: item.authentication_product_ids,
card_testing_guard_config: card_testing_guard_config.map(ForeignInto::foreign_into),
is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled,
force_3ds_challenge: item.force_3ds_challenge,
is_debit_routing_enabled: Some(item.is_debit_routing_enabled),
merchant_business_country: item.merchant_business_country,
is_pre_network_tokenization_enabled: item.is_pre_network_tokenization_enabled,
acquirer_configs: ProfileAcquirerConfigs {
acquirer_config_map: item.acquirer_config_map.clone(),
profile_id: profile_id.clone(),
}
.into(),
is_iframe_redirection_enabled: item.is_iframe_redirection_enabled,
merchant_category_code: item.merchant_category_code,
merchant_country_code: item.merchant_country_code,
dispute_polling_interval: item.dispute_polling_interval,
is_manual_retry_enabled: item.is_manual_retry_enabled,
always_enable_overcapture: item.always_enable_overcapture,
is_external_vault_enabled,
external_vault_connector_details: external_vault_connector_details
.map(ForeignFrom::foreign_from),
billing_processor_id: item.billing_processor_id,
is_l2_l3_enabled: Some(item.is_l2_l3_enabled),
})
}
}
#[cfg(feature = "v2")]
impl ForeignTryFrom<domain::Profile> for ProfileResponse {
type Error = error_stack::Report<errors::ParsingError>;
fn foreign_try_from(item: domain::Profile) -> Result<Self, Self::Error> {
let id = item.get_id().to_owned();
let outgoing_webhook_custom_http_headers = item
.outgoing_webhook_custom_http_headers
.map(|headers| {
headers
.into_inner()
.expose()
.parse_value::<HashMap<String, Secret<String>>>(
"HashMap<String, Secret<String>>",
)
})
.transpose()?;
let order_fulfillment_time = item
.order_fulfillment_time
.map(admin::OrderFulfillmentTime::try_new)
.transpose()
.change_context(errors::ParsingError::IntegerOverflow)?;
let masked_outgoing_webhook_custom_http_headers =
outgoing_webhook_custom_http_headers.map(MaskedHeaders::from_headers);
let card_testing_guard_config = item
.card_testing_guard_config
.or(Some(CardTestingGuardConfig::default()));
Ok(Self {
merchant_id: item.merchant_id,
id,
profile_name: item.profile_name,
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,
webhook_details: item.webhook_details.map(ForeignInto::foreign_into),
metadata: item.metadata,
applepay_verified_domains: item.applepay_verified_domains,
payment_link_config: item.payment_link_config.map(ForeignInto::foreign_into),
session_expiry: item.session_expiry,
authentication_connector_details: item
.authentication_connector_details
.map(ForeignInto::foreign_into),
payout_link_config: item.payout_link_config.map(ForeignInto::foreign_into),
use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing,
extended_card_info_config: item
.extended_card_info_config
.map(|config| config.expose().parse_value("ExtendedCardInfoConfig"))
.transpose()?,
collect_shipping_details_from_wallet_connector_if_required: item
.collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector_if_required: item
.collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: item
.always_collect_shipping_details_from_wallet_connector,
always_collect_billing_details_from_wallet_connector: item
.always_collect_billing_details_from_wallet_connector,
is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled,
outgoing_webhook_custom_http_headers: masked_outgoing_webhook_custom_http_headers,
order_fulfillment_time,
order_fulfillment_time_origin: item.order_fulfillment_time_origin,
should_collect_cvv_during_payment: item.should_collect_cvv_during_payment,
tax_connector_id: item.tax_connector_id,
is_tax_connector_enabled: item.is_tax_connector_enabled,
is_network_tokenization_enabled: item.is_network_tokenization_enabled,
is_click_to_pay_enabled: item.is_click_to_pay_enabled,
authentication_product_ids: item.authentication_product_ids,
card_testing_guard_config: card_testing_guard_config.map(ForeignInto::foreign_into),
is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled,
is_debit_routing_enabled: Some(item.is_debit_routing_enabled),
merchant_business_country: item.merchant_business_country,
is_iframe_redirection_enabled: item.is_iframe_redirection_enabled,
is_external_vault_enabled: item.is_external_vault_enabled,
is_l2_l3_enabled: None,
external_vault_connector_details: item
.external_vault_connector_details
.map(ForeignInto::foreign_into),
merchant_category_code: item.merchant_category_code,
merchant_country_code: item.merchant_country_code,
split_txns_enabled: item.split_txns_enabled,
revenue_recovery_retry_algorithm_type: item.revenue_recovery_retry_algorithm_type,
billing_processor_id: item.billing_processor_id,
})
}
}
#[cfg(feature = "v1")]
pub async fn create_profile_from_merchant_account(
state: &SessionState,
merchant_account: domain::MerchantAccount,
request: ProfileCreate,
key_store: &MerchantKeyStore,
) -> Result<domain::Profile, error_stack::Report<errors::ApiErrorResponse>> {
use common_utils::ext_traits::AsyncExt;
use diesel_models::business_profile::CardTestingGuardConfig;
use crate::core;
// Generate a unique profile id
let profile_id = common_utils::generate_profile_id_of_default_length();
let merchant_id = merchant_account.get_id().to_owned();
let current_time = common_utils::date_time::now();
let webhook_details = request.webhook_details.map(ForeignInto::foreign_into);
let payment_response_hash_key = request
.payment_response_hash_key
.or(merchant_account.payment_response_hash_key)
.unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64));
let payment_link_config = request.payment_link_config.map(ForeignInto::foreign_into);
let key_manager_state = state.into();
let outgoing_webhook_custom_http_headers = request
.outgoing_webhook_custom_http_headers
.async_map(|headers| {
core::payment_methods::cards::create_encrypted_data(
&key_manager_state,
key_store,
headers,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?;
let payout_link_config = request
.payout_link_config
.map(|payout_conf| match payout_conf.config.validate() {
Ok(_) => Ok(payout_conf.foreign_into()),
Err(e) => Err(error_stack::report!(
errors::ApiErrorResponse::InvalidRequestData {
message: e.to_string()
}
)),
})
.transpose()?;
let key = key_store.key.clone().into_inner();
let key_manager_state = state.into();
let card_testing_secret_key = Some(Secret::new(utils::generate_id(
consts::FINGERPRINT_SECRET_LENGTH,
"fs",
)));
let card_testing_guard_config = request
.card_testing_guard_config
.map(CardTestingGuardConfig::foreign_from)
.or(Some(CardTestingGuardConfig::default()));
Ok(domain::Profile::from(domain::ProfileSetter {
profile_id,
merchant_id,
profile_name: request.profile_name.unwrap_or("default".to_string()),
created_at: current_time,
modified_at: current_time,
return_url: request
.return_url
.map(|return_url| return_url.to_string())
.or(merchant_account.return_url),
enable_payment_response_hash: request
.enable_payment_response_hash
.unwrap_or(merchant_account.enable_payment_response_hash),
payment_response_hash_key: Some(payment_response_hash_key),
redirect_to_merchant_with_http_post: request
.redirect_to_merchant_with_http_post
.unwrap_or(merchant_account.redirect_to_merchant_with_http_post),
webhook_details: webhook_details.or(merchant_account.webhook_details),
metadata: request.metadata,
routing_algorithm: None,
intent_fulfillment_time: request
.intent_fulfillment_time
.map(i64::from)
.or(merchant_account.intent_fulfillment_time)
.or(Some(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME)),
frm_routing_algorithm: request
.frm_routing_algorithm
.or(merchant_account.frm_routing_algorithm),
#[cfg(feature = "payouts")]
payout_routing_algorithm: request
.payout_routing_algorithm
.or(merchant_account.payout_routing_algorithm),
#[cfg(not(feature = "payouts"))]
payout_routing_algorithm: None,
is_recon_enabled: merchant_account.is_recon_enabled,
applepay_verified_domains: request.applepay_verified_domains,
payment_link_config,
session_expiry: request
.session_expiry
.map(i64::from)
.or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)),
authentication_connector_details: request
.authentication_connector_details
.map(ForeignInto::foreign_into),
payout_link_config,
is_connector_agnostic_mit_enabled: request.is_connector_agnostic_mit_enabled,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
use_billing_as_payment_method_billing: request
.use_billing_as_payment_method_billing
.or(Some(true)),
collect_shipping_details_from_wallet_connector: request
.collect_shipping_details_from_wallet_connector
.or(Some(false)),
collect_billing_details_from_wallet_connector: request
.collect_billing_details_from_wallet_connector
.or(Some(false)),
always_collect_billing_details_from_wallet_connector: request
.always_collect_billing_details_from_wallet_connector
.or(Some(false)),
always_collect_shipping_details_from_wallet_connector: request
.always_collect_shipping_details_from_wallet_connector
.or(Some(false)),
outgoing_webhook_custom_http_headers,
tax_connector_id: request.tax_connector_id,
is_tax_connector_enabled: request.is_tax_connector_enabled,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: request.is_network_tokenization_enabled,
is_auto_retries_enabled: request.is_auto_retries_enabled.unwrap_or_default(),
max_auto_retries_enabled: request.max_auto_retries_enabled.map(i16::from),
always_request_extended_authorization: request.always_request_extended_authorization,
is_click_to_pay_enabled: request.is_click_to_pay_enabled,
authentication_product_ids: request.authentication_product_ids,
card_testing_guard_config,
card_testing_secret_key: card_testing_secret_key
.async_lift(|inner| async {
domain_types::crypto_operation(
&key_manager_state,
common_utils::type_name!(domain::Profile),
domain_types::CryptoOperation::EncryptOptional(inner),
km_types::Identifier::Merchant(key_store.merchant_id.clone()),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error while generating card testing secret key")?,
is_clear_pan_retries_enabled: request.is_clear_pan_retries_enabled.unwrap_or_default(),
force_3ds_challenge: request.force_3ds_challenge.unwrap_or_default(),
is_debit_routing_enabled: request.is_debit_routing_enabled.unwrap_or_default(),
merchant_business_country: request.merchant_business_country,
is_iframe_redirection_enabled: request.is_iframe_redirection_enabled,
is_pre_network_tokenization_enabled: request
.is_pre_network_tokenization_enabled
.unwrap_or_default(),
merchant_category_code: request.merchant_category_code,
merchant_country_code: request.merchant_country_code,
dispute_polling_interval: request.dispute_polling_interval,
is_manual_retry_enabled: request.is_manual_retry_enabled,
always_enable_overcapture: request.always_enable_overcapture,
external_vault_details: domain::ExternalVaultDetails::try_from((
request.is_external_vault_enabled,
request
.external_vault_connector_details
.map(ForeignInto::foreign_into),
))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error while generating external_vault_details")?,
billing_processor_id: request.billing_processor_id,
is_l2_l3_enabled: request.is_l2_l3_enabled.unwrap_or(false),
}))
}
|
crates/router/src/types/api/admin.rs
|
router::src::types::api::admin
| 4,711
| true
|
// File: crates/router/src/types/api/connector_onboarding.rs
// Module: router::src::types::api::connector_onboarding
pub mod paypal;
|
crates/router/src/types/api/connector_onboarding.rs
|
router::src::types::api::connector_onboarding
| 33
| true
|
// File: crates/router/src/types/api/connector_onboarding/paypal.rs
// Module: router::src::types::api::connector_onboarding::paypal
use api_models::connector_onboarding as api;
use error_stack::ResultExt;
use crate::core::errors::{ApiErrorResponse, RouterResult};
#[derive(serde::Deserialize, Debug)]
pub struct HateoasLink {
pub href: String,
pub rel: String,
pub method: String,
}
#[derive(serde::Deserialize, Debug)]
pub struct PartnerReferralResponse {
pub links: Vec<HateoasLink>,
}
#[derive(serde::Serialize, Debug)]
pub struct PartnerReferralRequest {
pub tracking_id: String,
pub operations: Vec<PartnerReferralOperations>,
pub products: Vec<PayPalProducts>,
pub capabilities: Vec<PayPalCapabilities>,
pub partner_config_override: PartnerConfigOverride,
pub legal_consents: Vec<LegalConsent>,
}
#[derive(serde::Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayPalProducts {
Ppcp,
AdvancedVaulting,
}
#[derive(serde::Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayPalCapabilities {
PaypalWalletVaultingAdvanced,
}
#[derive(serde::Serialize, Debug)]
pub struct PartnerReferralOperations {
pub operation: PayPalReferralOperationType,
pub api_integration_preference: PartnerReferralIntegrationPreference,
}
#[derive(serde::Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayPalReferralOperationType {
ApiIntegration,
}
#[derive(serde::Serialize, Debug)]
pub struct PartnerReferralIntegrationPreference {
pub rest_api_integration: PartnerReferralRestApiIntegration,
}
#[derive(serde::Serialize, Debug)]
pub struct PartnerReferralRestApiIntegration {
pub integration_method: IntegrationMethod,
pub integration_type: PayPalIntegrationType,
pub third_party_details: PartnerReferralThirdPartyDetails,
}
#[derive(serde::Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum IntegrationMethod {
Paypal,
}
#[derive(serde::Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayPalIntegrationType {
ThirdParty,
}
#[derive(serde::Serialize, Debug)]
pub struct PartnerReferralThirdPartyDetails {
pub features: Vec<PayPalFeatures>,
}
#[derive(serde::Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayPalFeatures {
Payment,
Refund,
Vault,
AccessMerchantInformation,
BillingAgreement,
ReadSellerDispute,
}
#[derive(serde::Serialize, Debug)]
pub struct PartnerConfigOverride {
pub partner_logo_url: String,
pub return_url: String,
}
#[derive(serde::Serialize, Debug)]
pub struct LegalConsent {
#[serde(rename = "type")]
pub consent_type: LegalConsentType,
pub granted: bool,
}
#[derive(serde::Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LegalConsentType {
ShareDataConsent,
}
impl PartnerReferralRequest {
pub fn new(tracking_id: String, return_url: String) -> Self {
Self {
tracking_id,
operations: vec![PartnerReferralOperations {
operation: PayPalReferralOperationType::ApiIntegration,
api_integration_preference: PartnerReferralIntegrationPreference {
rest_api_integration: PartnerReferralRestApiIntegration {
integration_method: IntegrationMethod::Paypal,
integration_type: PayPalIntegrationType::ThirdParty,
third_party_details: PartnerReferralThirdPartyDetails {
features: vec![
PayPalFeatures::Payment,
PayPalFeatures::Refund,
PayPalFeatures::Vault,
PayPalFeatures::AccessMerchantInformation,
PayPalFeatures::BillingAgreement,
PayPalFeatures::ReadSellerDispute,
],
},
},
},
}],
products: vec![PayPalProducts::Ppcp, PayPalProducts::AdvancedVaulting],
capabilities: vec![PayPalCapabilities::PaypalWalletVaultingAdvanced],
partner_config_override: PartnerConfigOverride {
partner_logo_url: "https://hyperswitch.io/img/websiteIcon.svg".to_string(),
return_url,
},
legal_consents: vec![LegalConsent {
consent_type: LegalConsentType::ShareDataConsent,
granted: true,
}],
}
}
}
#[derive(serde::Deserialize, Debug)]
pub struct SellerStatusResponse {
pub merchant_id: common_utils::id_type::MerchantId,
pub links: Vec<HateoasLink>,
}
#[derive(serde::Deserialize, Debug)]
pub struct SellerStatusDetailsResponse {
pub merchant_id: common_utils::id_type::MerchantId,
pub primary_email_confirmed: bool,
pub payments_receivable: bool,
pub products: Vec<SellerStatusProducts>,
}
#[derive(serde::Deserialize, Debug)]
pub struct SellerStatusProducts {
pub name: String,
pub vetting_status: Option<VettingStatus>,
}
#[derive(serde::Deserialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum VettingStatus {
NeedMoreData,
Subscribed,
Denied,
}
impl SellerStatusResponse {
pub fn extract_merchant_details_url(self, paypal_base_url: &str) -> RouterResult<String> {
self.links
.first()
.and_then(|link| link.href.strip_prefix('/'))
.map(|link| format!("{paypal_base_url}{link}"))
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Merchant details not received in onboarding status")
}
}
impl SellerStatusDetailsResponse {
pub fn check_payments_receivable(&self) -> Option<api::PayPalOnboardingStatus> {
if !self.payments_receivable {
return Some(api::PayPalOnboardingStatus::PaymentsNotReceivable);
}
None
}
pub fn check_ppcp_custom_status(&self) -> Option<api::PayPalOnboardingStatus> {
match self.get_ppcp_custom_status() {
Some(VettingStatus::Denied) => Some(api::PayPalOnboardingStatus::PpcpCustomDenied),
Some(VettingStatus::Subscribed) => None,
_ => Some(api::PayPalOnboardingStatus::MorePermissionsNeeded),
}
}
fn check_email_confirmation(&self) -> Option<api::PayPalOnboardingStatus> {
if !self.primary_email_confirmed {
return Some(api::PayPalOnboardingStatus::EmailNotVerified);
}
None
}
pub async fn get_eligibility_status(&self) -> RouterResult<api::PayPalOnboardingStatus> {
Ok(self
.check_payments_receivable()
.or(self.check_email_confirmation())
.or(self.check_ppcp_custom_status())
.unwrap_or(api::PayPalOnboardingStatus::Success(
api::PayPalOnboardingDone {
payer_id: self.get_payer_id(),
},
)))
}
fn get_ppcp_custom_status(&self) -> Option<VettingStatus> {
self.products
.iter()
.find(|product| product.name == "PPCP_CUSTOM")
.and_then(|ppcp_custom| ppcp_custom.vetting_status.clone())
}
fn get_payer_id(&self) -> common_utils::id_type::MerchantId {
self.merchant_id.to_owned()
}
}
impl PartnerReferralResponse {
pub fn extract_action_url(self) -> RouterResult<String> {
Ok(self
.links
.into_iter()
.find(|hateoas_link| hateoas_link.rel == "action_url")
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get action_url from paypal response")?
.href)
}
}
|
crates/router/src/types/api/connector_onboarding/paypal.rs
|
router::src::types::api::connector_onboarding::paypal
| 1,708
| true
|
// File: crates/router/src/types/api/verify_connector/paypal.rs
// Module: router::src::types::api::verify_connector::paypal
use error_stack::ResultExt;
use super::{VerifyConnector, VerifyConnectorData};
use crate::{
connector,
core::errors,
routes::SessionState,
services,
types::{self, api},
};
#[async_trait::async_trait]
impl VerifyConnector for connector::Paypal {
async fn get_access_token(
state: &SessionState,
connector_data: VerifyConnectorData,
) -> errors::CustomResult<Option<types::AccessToken>, errors::ApiErrorResponse> {
let token_data: types::AccessTokenRequestData =
connector_data.connector_auth.clone().try_into()?;
let router_data = connector_data.get_router_data(state, token_data, None);
let request = connector_data
.connector
.get_connector_integration()
.build_request(&router_data, &state.conf.connectors)
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Payment request cannot be built".to_string(),
})?
.ok_or(errors::ApiErrorResponse::InternalServerError)?;
let response = services::call_connector_api(&state.to_owned(), request, "get_access_token")
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
match response {
Ok(res) => Some(
connector_data
.connector
.get_connector_integration()
.handle_response(&router_data, None, res)
.change_context(errors::ApiErrorResponse::InternalServerError)?
.response
.map_err(|_| errors::ApiErrorResponse::InternalServerError.into()),
)
.transpose(),
Err(response_data) => {
Self::handle_access_token_error_response::<
api::AccessTokenAuth,
types::AccessTokenFlowData,
types::AccessTokenRequestData,
types::AccessToken,
>(
connector_data.connector.get_connector_integration(),
response_data,
)
.await
}
}
}
}
|
crates/router/src/types/api/verify_connector/paypal.rs
|
router::src::types::api::verify_connector::paypal
| 420
| true
|
// File: crates/router/src/types/api/verify_connector/stripe.rs
// Module: router::src::types::api::verify_connector::stripe
use error_stack::ResultExt;
use router_env::env;
use super::VerifyConnector;
use crate::{
connector, core::errors, services, types,
types::api::verify_connector::BoxedConnectorIntegrationInterface,
};
#[async_trait::async_trait]
impl VerifyConnector for connector::Stripe {
async fn handle_payment_error_response<F, ResourceCommonData, Req, Resp>(
connector: BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>,
error_response: types::Response,
) -> errors::RouterResponse<()> {
let error = connector
.get_error_response(error_response, None)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
match (env::which(), error.code.as_str()) {
// In situations where an attempt is made to process a payment using a
// Stripe production key along with a test card (which verify_connector is using),
// Stripe will respond with a "card_declined" error. In production,
// when this scenario occurs we will send back an "Ok" response.
(env::Env::Production, "card_declined") => Ok(services::ApplicationResponse::StatusOk),
_ => Err(errors::ApiErrorResponse::InvalidRequestData {
message: error.reason.unwrap_or(error.message),
}
.into()),
}
}
}
|
crates/router/src/types/api/verify_connector/stripe.rs
|
router::src::types::api::verify_connector::stripe
| 310
| true
|
// File: crates/router/src/types/domain/types.rs
// Module: router::src::types::domain::types
use ::payment_methods::state as pm_state;
use common_utils::types::keymanager::KeyManagerState;
pub use hyperswitch_domain_models::type_encryption::{
crypto_operation, AsyncLift, CryptoOperation, Lift, OptionalEncryptableJsonType,
};
use crate::{routes::app, types::api as api_types};
impl From<&app::SessionState> for KeyManagerState {
fn from(state: &app::SessionState) -> Self {
let conf = state.conf.key_manager.get_inner();
Self {
global_tenant_id: state.conf.multitenancy.global_tenant.tenant_id.clone(),
tenant_id: state.tenant.tenant_id.clone(),
enabled: conf.enabled,
url: conf.url.clone(),
client_idle_timeout: state.conf.proxy.idle_pool_connection_timeout,
#[cfg(feature = "km_forward_x_request_id")]
request_id: state.request_id,
#[cfg(feature = "keymanager_mtls")]
cert: conf.cert.clone(),
#[cfg(feature = "keymanager_mtls")]
ca: conf.ca.clone(),
infra_values: app::AppState::process_env_mappings(state.conf.infra_values.clone()),
}
}
}
impl From<&app::SessionState> for pm_state::PaymentMethodsState {
fn from(state: &app::SessionState) -> Self {
Self {
store: state.store.get_payment_methods_store(),
key_store: None,
key_manager_state: state.into(),
}
}
}
pub struct ConnectorConversionHandler;
impl hyperswitch_interfaces::api_client::ConnectorConverter for ConnectorConversionHandler {
fn get_connector_enum_by_name(
&self,
connector: &str,
) -> common_utils::errors::CustomResult<
hyperswitch_interfaces::connector_integration_interface::ConnectorEnum,
hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse,
> {
api_types::ConnectorData::convert_connector(connector)
}
}
impl From<app::SessionState> for subscriptions::state::SubscriptionState {
fn from(state: app::SessionState) -> Self {
Self {
store: state.store.get_subscription_store(),
key_store: None,
key_manager_state: (&state).into(),
api_client: state.api_client.clone(),
conf: subscriptions::state::SubscriptionConfig {
proxy: state.conf.proxy.clone(),
internal_merchant_id_profile_id_auth: state
.conf
.internal_merchant_id_profile_id_auth
.clone(),
internal_services: state.conf.internal_services.clone(),
connectors: state.conf.connectors.clone(),
},
tenant: state.tenant.clone(),
event_handler: Box::new(state.event_handler.clone()),
connector_converter: Box::new(ConnectorConversionHandler),
}
}
}
|
crates/router/src/types/domain/types.rs
|
router::src::types::domain::types
| 598
| true
|
// File: crates/router/src/types/domain/merchant_connector_account.rs
// Module: router::src::types::domain::merchant_connector_account
pub use hyperswitch_domain_models::merchant_connector_account::*;
|
crates/router/src/types/domain/merchant_connector_account.rs
|
router::src::types::domain::merchant_connector_account
| 40
| true
|
// File: crates/router/src/types/domain/payments.rs
// Module: router::src::types::domain::payments
pub use hyperswitch_domain_models::payment_method_data::{
AliPayQr, ApplePayFlow, ApplePayThirdPartySdkData, ApplePayWalletData, ApplepayPaymentMethod,
BankDebitData, BankRedirectData, BankTransferData, BoletoVoucherData, Card, CardDetail,
CardRedirectData, CardToken, CashappQr, CryptoData, GcashRedirection, GiftCardData,
GiftCardDetails, GoPayRedirection, GooglePayPaymentMethodInfo, GooglePayRedirectData,
GooglePayThirdPartySdkData, GooglePayWalletData, IndomaretVoucherData, KakaoPayRedirection,
MbWayRedirection, MifinityData, NetworkTokenData, OpenBankingData, PayLaterData,
PaymentMethodData, RealTimePaymentData, RevolutPayData, SamsungPayWalletData,
SepaAndBacsBillingDetails, SwishQrData, TokenizedBankDebitValue1, TokenizedBankDebitValue2,
TokenizedBankRedirectValue1, TokenizedBankRedirectValue2, TokenizedBankTransferValue1,
TokenizedBankTransferValue2, TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1,
TokenizedWalletValue2, TouchNGoRedirection, UpiCollectData, UpiData, UpiIntentData,
VoucherData, WalletData, WeChatPayQr,
};
|
crates/router/src/types/domain/payments.rs
|
router::src::types::domain::payments
| 325
| true
|
// File: crates/router/src/types/domain/address.rs
// Module: router::src::types::domain::address
use async_trait::async_trait;
use common_utils::{
crypto::{self, Encryptable},
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
id_type, pii, type_name,
types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
};
use diesel_models::{address::AddressUpdateInternal, enums};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret, SwitchStrategy};
use rustc_hash::FxHashMap;
use time::{OffsetDateTime, PrimitiveDateTime};
use super::{behaviour, types};
#[derive(Clone, Debug, serde::Serialize, router_derive::ToEncryption)]
pub struct Address {
pub address_id: String,
pub city: Option<String>,
pub country: Option<enums::CountryAlpha2>,
#[encrypt]
pub line1: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub line2: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub line3: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub state: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub zip: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub first_name: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub last_name: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub phone_number: Option<Encryptable<Secret<String>>>,
pub country_code: Option<String>,
#[serde(skip_serializing)]
#[serde(with = "custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(skip_serializing)]
#[serde(with = "custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub merchant_id: id_type::MerchantId,
pub updated_by: String,
#[encrypt]
pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,
#[encrypt]
pub origin_zip: Option<Encryptable<Secret<String>>>,
}
/// Based on the flow, appropriate address has to be used
/// In case of Payments, The `PaymentAddress`[PaymentAddress] has to be used
/// which contains only the `Address`[Address] object and `payment_id` and optional `customer_id`
#[derive(Debug, Clone)]
pub struct PaymentAddress {
pub address: Address,
pub payment_id: id_type::PaymentId,
// This is present in `PaymentAddress` because even `payouts` uses `PaymentAddress`
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, Clone)]
pub struct CustomerAddress {
pub address: Address,
pub customer_id: id_type::CustomerId,
}
#[async_trait]
impl behaviour::Conversion for CustomerAddress {
type DstType = diesel_models::address::Address;
type NewDstType = diesel_models::address::AddressNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let converted_address = Address::convert(self.address).await?;
Ok(diesel_models::address::Address {
customer_id: Some(self.customer_id),
payment_id: None,
..converted_address
})
}
async fn convert_back(
state: &KeyManagerState,
other: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let customer_id =
other
.customer_id
.clone()
.ok_or(ValidationError::MissingRequiredField {
field_name: "customer_id".to_string(),
})?;
let address = Address::convert_back(state, other, key, key_manager_identifier).await?;
Ok(Self {
address,
customer_id,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let address_new = Address::construct_new(self.address).await?;
Ok(Self::NewDstType {
customer_id: Some(self.customer_id),
payment_id: None,
..address_new
})
}
}
#[async_trait]
impl behaviour::Conversion for PaymentAddress {
type DstType = diesel_models::address::Address;
type NewDstType = diesel_models::address::AddressNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let converted_address = Address::convert(self.address).await?;
Ok(diesel_models::address::Address {
customer_id: self.customer_id,
payment_id: Some(self.payment_id),
..converted_address
})
}
async fn convert_back(
state: &KeyManagerState,
other: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let payment_id = other
.payment_id
.clone()
.ok_or(ValidationError::MissingRequiredField {
field_name: "payment_id".to_string(),
})?;
let customer_id = other.customer_id.clone();
let address = Address::convert_back(state, other, key, key_manager_identifier).await?;
Ok(Self {
address,
payment_id,
customer_id,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let address_new = Address::construct_new(self.address).await?;
Ok(Self::NewDstType {
customer_id: self.customer_id,
payment_id: Some(self.payment_id),
..address_new
})
}
}
#[async_trait]
impl behaviour::Conversion for Address {
type DstType = diesel_models::address::Address;
type NewDstType = diesel_models::address::AddressNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::address::Address {
address_id: self.address_id,
city: self.city,
country: self.country,
line1: self.line1.map(Encryption::from),
line2: self.line2.map(Encryption::from),
line3: self.line3.map(Encryption::from),
state: self.state.map(Encryption::from),
zip: self.zip.map(Encryption::from),
first_name: self.first_name.map(Encryption::from),
last_name: self.last_name.map(Encryption::from),
phone_number: self.phone_number.map(Encryption::from),
country_code: self.country_code,
created_at: self.created_at,
modified_at: self.modified_at,
merchant_id: self.merchant_id,
updated_by: self.updated_by,
email: self.email.map(Encryption::from),
payment_id: None,
customer_id: None,
origin_zip: self.origin_zip.map(Encryption::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: FxHashMap<String, Encryptable<Secret<String>>> = types::crypto_operation(
state,
type_name!(Self::DstType),
types::CryptoOperation::BatchDecrypt(EncryptedAddress::to_encryptable(
EncryptedAddress {
line1: other.line1,
line2: other.line2,
line3: other.line3,
state: other.state,
zip: other.zip,
first_name: other.first_name,
last_name: other.last_name,
phone_number: other.phone_number,
email: other.email,
origin_zip: other.origin_zip,
},
)),
identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting".to_string(),
})?;
let encryptable_address = EncryptedAddress::from_encryptable(decrypted).change_context(
ValidationError::InvalidValue {
message: "Failed while decrypting".to_string(),
},
)?;
Ok(Self {
address_id: other.address_id,
city: other.city,
country: other.country,
line1: encryptable_address.line1,
line2: encryptable_address.line2,
line3: encryptable_address.line3,
state: encryptable_address.state,
zip: encryptable_address.zip,
first_name: encryptable_address.first_name,
last_name: encryptable_address.last_name,
phone_number: encryptable_address.phone_number,
country_code: other.country_code,
created_at: other.created_at,
modified_at: other.modified_at,
updated_by: other.updated_by,
merchant_id: other.merchant_id,
email: encryptable_address.email.map(|email| {
let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
origin_zip: encryptable_address.origin_zip,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(Self::NewDstType {
address_id: self.address_id,
city: self.city,
country: self.country,
line1: self.line1.map(Encryption::from),
line2: self.line2.map(Encryption::from),
line3: self.line3.map(Encryption::from),
state: self.state.map(Encryption::from),
zip: self.zip.map(Encryption::from),
first_name: self.first_name.map(Encryption::from),
last_name: self.last_name.map(Encryption::from),
phone_number: self.phone_number.map(Encryption::from),
country_code: self.country_code,
merchant_id: self.merchant_id,
created_at: now,
modified_at: now,
updated_by: self.updated_by,
email: self.email.map(Encryption::from),
customer_id: None,
payment_id: None,
origin_zip: self.origin_zip.map(Encryption::from),
})
}
}
#[derive(Debug, Clone)]
pub enum AddressUpdate {
Update {
city: Option<String>,
country: Option<enums::CountryAlpha2>,
line1: crypto::OptionalEncryptableSecretString,
line2: crypto::OptionalEncryptableSecretString,
line3: crypto::OptionalEncryptableSecretString,
state: crypto::OptionalEncryptableSecretString,
zip: crypto::OptionalEncryptableSecretString,
first_name: crypto::OptionalEncryptableSecretString,
last_name: crypto::OptionalEncryptableSecretString,
phone_number: crypto::OptionalEncryptableSecretString,
country_code: Option<String>,
updated_by: String,
email: crypto::OptionalEncryptableEmail,
origin_zip: crypto::OptionalEncryptableSecretString,
},
}
impl From<AddressUpdate> for AddressUpdateInternal {
fn from(address_update: AddressUpdate) -> Self {
match address_update {
AddressUpdate::Update {
city,
country,
line1,
line2,
line3,
state,
zip,
first_name,
last_name,
phone_number,
country_code,
updated_by,
email,
origin_zip,
} => Self {
city,
country,
line1: line1.map(Encryption::from),
line2: line2.map(Encryption::from),
line3: line3.map(Encryption::from),
state: state.map(Encryption::from),
zip: zip.map(Encryption::from),
first_name: first_name.map(Encryption::from),
last_name: last_name.map(Encryption::from),
phone_number: phone_number.map(Encryption::from),
country_code,
modified_at: date_time::convert_to_pdt(OffsetDateTime::now_utc()),
updated_by,
email: email.map(Encryption::from),
origin_zip: origin_zip.map(Encryption::from),
},
}
}
}
|
crates/router/src/types/domain/address.rs
|
router::src::types::domain::address
| 2,619
| true
|
// File: crates/router/src/types/domain/event.rs
// Module: router::src::types::domain::event
use common_utils::{
crypto::{Encryptable, OptionalEncryptableSecretString},
encryption::Encryption,
type_name,
types::keymanager::{KeyManagerState, ToEncryptable},
};
use diesel_models::{
enums::{EventClass, EventObjectType, EventType, WebhookDeliveryAttempt},
events::{EventMetadata, EventUpdateInternal},
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use rustc_hash::FxHashMap;
use crate::{
errors::{CustomResult, ValidationError},
types::domain::types,
};
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct Event {
/// A string that uniquely identifies the event.
pub event_id: String,
/// Represents the type of event for the webhook.
pub event_type: EventType,
/// Represents the class of event for the webhook.
pub event_class: EventClass,
/// Indicates whether the current webhook delivery was successful.
pub is_webhook_notified: bool,
/// Reference to the object for which the webhook was created.
pub primary_object_id: String,
/// Type of the object type for which the webhook was created.
pub primary_object_type: EventObjectType,
/// The timestamp when the webhook was created.
pub created_at: time::PrimitiveDateTime,
/// Merchant Account identifier to which the object is associated with.
pub merchant_id: Option<common_utils::id_type::MerchantId>,
/// Business Profile identifier to which the object is associated with.
pub business_profile_id: Option<common_utils::id_type::ProfileId>,
/// The timestamp when the primary object was created.
pub primary_object_created_at: Option<time::PrimitiveDateTime>,
/// This allows the event to be uniquely identified to prevent multiple processing.
pub idempotent_event_id: Option<String>,
/// Links to the initial attempt of the event.
pub initial_attempt_id: Option<String>,
/// This field contains the encrypted request data sent as part of the event.
#[encrypt]
pub request: Option<Encryptable<Secret<String>>>,
/// This field contains the encrypted response data received as part of the event.
#[encrypt]
pub response: Option<Encryptable<Secret<String>>>,
/// Represents the event delivery type.
pub delivery_attempt: Option<WebhookDeliveryAttempt>,
/// Holds any additional data related to the event.
pub metadata: Option<EventMetadata>,
/// Indicates whether the event was ultimately delivered.
pub is_overall_delivery_successful: Option<bool>,
}
#[derive(Debug)]
pub enum EventUpdate {
UpdateResponse {
is_webhook_notified: bool,
response: OptionalEncryptableSecretString,
},
OverallDeliveryStatusUpdate {
is_overall_delivery_successful: bool,
},
}
impl From<EventUpdate> for EventUpdateInternal {
fn from(event_update: EventUpdate) -> Self {
match event_update {
EventUpdate::UpdateResponse {
is_webhook_notified,
response,
} => Self {
is_webhook_notified: Some(is_webhook_notified),
response: response.map(Into::into),
is_overall_delivery_successful: None,
},
EventUpdate::OverallDeliveryStatusUpdate {
is_overall_delivery_successful,
} => Self {
is_webhook_notified: None,
response: None,
is_overall_delivery_successful: Some(is_overall_delivery_successful),
},
}
}
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for Event {
type DstType = diesel_models::events::Event;
type NewDstType = diesel_models::events::EventNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::events::Event {
event_id: self.event_id,
event_type: self.event_type,
event_class: self.event_class,
is_webhook_notified: self.is_webhook_notified,
primary_object_id: self.primary_object_id,
primary_object_type: self.primary_object_type,
created_at: self.created_at,
merchant_id: self.merchant_id,
business_profile_id: self.business_profile_id,
primary_object_created_at: self.primary_object_created_at,
idempotent_event_id: self.idempotent_event_id,
initial_attempt_id: self.initial_attempt_id,
request: self.request.map(Into::into),
response: self.response.map(Into::into),
delivery_attempt: self.delivery_attempt,
metadata: self.metadata,
is_overall_delivery_successful: self.is_overall_delivery_successful,
})
}
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: common_utils::types::keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let decrypted = types::crypto_operation(
state,
type_name!(Self::DstType),
types::CryptoOperation::BatchDecrypt(EncryptedEvent::to_encryptable(EncryptedEvent {
request: item.request.clone(),
response: item.response.clone(),
})),
key_manager_identifier,
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting event data".to_string(),
})?;
let encryptable_event = EncryptedEvent::from_encryptable(decrypted).change_context(
ValidationError::InvalidValue {
message: "Failed while decrypting event data".to_string(),
},
)?;
Ok(Self {
event_id: item.event_id,
event_type: item.event_type,
event_class: item.event_class,
is_webhook_notified: item.is_webhook_notified,
primary_object_id: item.primary_object_id,
primary_object_type: item.primary_object_type,
created_at: item.created_at,
merchant_id: item.merchant_id,
business_profile_id: item.business_profile_id,
primary_object_created_at: item.primary_object_created_at,
idempotent_event_id: item.idempotent_event_id,
initial_attempt_id: item.initial_attempt_id,
request: encryptable_event.request,
response: encryptable_event.response,
delivery_attempt: item.delivery_attempt,
metadata: item.metadata,
is_overall_delivery_successful: item.is_overall_delivery_successful,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::events::EventNew {
event_id: self.event_id,
event_type: self.event_type,
event_class: self.event_class,
is_webhook_notified: self.is_webhook_notified,
primary_object_id: self.primary_object_id,
primary_object_type: self.primary_object_type,
created_at: self.created_at,
merchant_id: self.merchant_id,
business_profile_id: self.business_profile_id,
primary_object_created_at: self.primary_object_created_at,
idempotent_event_id: self.idempotent_event_id,
initial_attempt_id: self.initial_attempt_id,
request: self.request.map(Into::into),
response: self.response.map(Into::into),
delivery_attempt: self.delivery_attempt,
metadata: self.metadata,
is_overall_delivery_successful: self.is_overall_delivery_successful,
})
}
}
|
crates/router/src/types/domain/event.rs
|
router::src::types::domain::event
| 1,596
| true
|
// File: crates/router/src/types/domain/user.rs
// Module: router::src::types::domain::user
use std::{
collections::HashSet,
ops::{Deref, Not},
str::FromStr,
sync::LazyLock,
};
use api_models::{
admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api,
};
use common_enums::EntityType;
use common_utils::{
crypto::Encryptable, id_type, new_type::MerchantName, pii, type_name,
types::keymanager::Identifier,
};
use diesel_models::{
enums::{TotpStatus, UserRoleVersion, UserStatus},
organization::{self as diesel_org, Organization, OrganizationBridge},
user as storage_user,
user_role::{UserRole, UserRoleNew},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::api::ApplicationResponse;
use masking::{ExposeInterface, PeekInterface, Secret};
use rand::distributions::{Alphanumeric, DistString};
use time::PrimitiveDateTime;
use unicode_segmentation::UnicodeSegmentation;
#[cfg(feature = "keymanager_create")]
use {base64::Engine, common_utils::types::keymanager::EncryptionTransferRequest};
use crate::{
consts,
core::{
admin,
errors::{UserErrors, UserResult},
},
db::GlobalStorageInterface,
routes::SessionState,
services::{
self,
authentication::{AuthenticationDataWithOrg, UserFromToken},
},
types::{domain, transformers::ForeignFrom},
utils::{self, user::password},
};
pub mod dashboard_metadata;
pub mod decision_manager;
pub use decision_manager::*;
pub mod user_authentication_method;
use super::{types as domain_types, UserKeyStore};
#[derive(Clone)]
pub struct UserName(Secret<String>);
impl UserName {
pub fn new(name: Secret<String>) -> UserResult<Self> {
let name = name.expose();
let is_empty_or_whitespace = name.trim().is_empty();
let is_too_long = name.graphemes(true).count() > consts::user::MAX_NAME_LENGTH;
let forbidden_characters = ['/', '(', ')', '"', '<', '>', '\\', '{', '}'];
let contains_forbidden_characters = name.chars().any(|g| forbidden_characters.contains(&g));
if is_empty_or_whitespace || is_too_long || contains_forbidden_characters {
Err(UserErrors::NameParsingError.into())
} else {
Ok(Self(name.into()))
}
}
pub fn get_secret(self) -> Secret<String> {
self.0
}
}
impl TryFrom<pii::Email> for UserName {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: pii::Email) -> UserResult<Self> {
Self::new(Secret::new(
value
.peek()
.split_once('@')
.ok_or(UserErrors::InvalidEmailError)?
.0
.to_string(),
))
}
}
#[derive(Clone, Debug)]
pub struct UserEmail(pii::Email);
static BLOCKED_EMAIL: LazyLock<HashSet<String>> = LazyLock::new(|| {
let blocked_emails_content = include_str!("../../utils/user/blocker_emails.txt");
let blocked_emails: HashSet<String> = blocked_emails_content
.lines()
.map(|s| s.trim().to_owned())
.collect();
blocked_emails
});
impl UserEmail {
pub fn new(email: Secret<String, pii::EmailStrategy>) -> UserResult<Self> {
use validator::ValidateEmail;
let email_string = email.expose().to_lowercase();
let email =
pii::Email::from_str(&email_string).change_context(UserErrors::EmailParsingError)?;
if email_string.validate_email() {
let (_username, domain) = match email_string.as_str().split_once('@') {
Some((u, d)) => (u, d),
None => return Err(UserErrors::EmailParsingError.into()),
};
if BLOCKED_EMAIL.contains(domain) {
return Err(UserErrors::InvalidEmailError.into());
}
Ok(Self(email))
} else {
Err(UserErrors::EmailParsingError.into())
}
}
pub fn from_pii_email(email: pii::Email) -> UserResult<Self> {
let email_string = email.expose().map(|inner| inner.to_lowercase());
Self::new(email_string)
}
pub fn into_inner(self) -> pii::Email {
self.0
}
pub fn get_inner(&self) -> &pii::Email {
&self.0
}
pub fn get_secret(self) -> Secret<String, pii::EmailStrategy> {
(*self.0).clone()
}
pub fn extract_domain(&self) -> UserResult<&str> {
let (_username, domain) = self
.peek()
.split_once('@')
.ok_or(UserErrors::InternalServerError)?;
Ok(domain)
}
}
impl TryFrom<pii::Email> for UserEmail {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: pii::Email) -> Result<Self, Self::Error> {
Self::from_pii_email(value)
}
}
impl Deref for UserEmail {
type Target = Secret<String, pii::EmailStrategy>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Clone)]
pub struct UserPassword(Secret<String>);
impl UserPassword {
pub fn new(password: Secret<String>) -> UserResult<Self> {
let password = password.expose();
let mut has_upper_case = false;
let mut has_lower_case = false;
let mut has_numeric_value = false;
let mut has_special_character = false;
let mut has_whitespace = false;
for c in password.chars() {
has_upper_case = has_upper_case || c.is_uppercase();
has_lower_case = has_lower_case || c.is_lowercase();
has_numeric_value = has_numeric_value || c.is_numeric();
has_special_character = has_special_character || !c.is_alphanumeric();
has_whitespace = has_whitespace || c.is_whitespace();
}
let is_password_format_valid = has_upper_case
&& has_lower_case
&& has_numeric_value
&& has_special_character
&& !has_whitespace;
let is_too_long = password.graphemes(true).count() > consts::user::MAX_PASSWORD_LENGTH;
let is_too_short = password.graphemes(true).count() < consts::user::MIN_PASSWORD_LENGTH;
if is_too_short || is_too_long || !is_password_format_valid {
return Err(UserErrors::PasswordParsingError.into());
}
Ok(Self(password.into()))
}
pub fn new_password_without_validation(password: Secret<String>) -> UserResult<Self> {
let password = password.expose();
if password.is_empty() {
return Err(UserErrors::PasswordParsingError.into());
}
Ok(Self(password.into()))
}
pub fn get_secret(&self) -> Secret<String> {
self.0.clone()
}
}
#[derive(Clone)]
pub struct UserCompanyName(String);
impl UserCompanyName {
pub fn new(company_name: String) -> UserResult<Self> {
let company_name = company_name.trim();
let is_empty_or_whitespace = company_name.is_empty();
let is_too_long =
company_name.graphemes(true).count() > consts::user::MAX_COMPANY_NAME_LENGTH;
let is_all_valid_characters = company_name
.chars()
.all(|x| x.is_alphanumeric() || x.is_ascii_whitespace() || x == '_');
if is_empty_or_whitespace || is_too_long || !is_all_valid_characters {
Err(UserErrors::CompanyNameParsingError.into())
} else {
Ok(Self(company_name.to_string()))
}
}
pub fn get_secret(self) -> String {
self.0
}
}
#[derive(Clone)]
pub struct NewUserOrganization(diesel_org::OrganizationNew);
impl NewUserOrganization {
pub async fn insert_org_in_db(self, state: SessionState) -> UserResult<Organization> {
state
.accounts_store
.insert_organization(self.0)
.await
.map_err(|e| {
if e.current_context().is_db_unique_violation() {
e.change_context(UserErrors::DuplicateOrganizationId)
} else {
e.change_context(UserErrors::InternalServerError)
}
})
.attach_printable("Error while inserting organization")
}
pub fn get_organization_id(&self) -> id_type::OrganizationId {
self.0.get_organization_id()
}
}
impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserOrganization {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> {
let new_organization = api_org::OrganizationNew::new(
common_enums::OrganizationType::Standard,
Some(UserCompanyName::new(value.company_name)?.get_secret()),
);
let db_organization = ForeignFrom::foreign_from(new_organization);
Ok(Self(db_organization))
}
}
impl From<user_api::SignUpRequest> for NewUserOrganization {
fn from(_value: user_api::SignUpRequest) -> Self {
let new_organization =
api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None);
let db_organization = ForeignFrom::foreign_from(new_organization);
Self(db_organization)
}
}
impl From<user_api::ConnectAccountRequest> for NewUserOrganization {
fn from(_value: user_api::ConnectAccountRequest) -> Self {
let new_organization =
api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None);
let db_organization = ForeignFrom::foreign_from(new_organization);
Self(db_organization)
}
}
impl From<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for NewUserOrganization {
fn from(
(_value, org_id): (user_api::CreateInternalUserRequest, id_type::OrganizationId),
) -> Self {
let new_organization = api_org::OrganizationNew {
org_id,
org_type: common_enums::OrganizationType::Standard,
org_name: None,
};
let db_organization = ForeignFrom::foreign_from(new_organization);
Self(db_organization)
}
}
impl From<UserMerchantCreateRequestWithToken> for NewUserOrganization {
fn from(value: UserMerchantCreateRequestWithToken) -> Self {
Self(diesel_org::OrganizationNew::new(
value.2.org_id,
common_enums::OrganizationType::Standard,
Some(value.1.company_name),
))
}
}
impl From<user_api::PlatformAccountCreateRequest> for NewUserOrganization {
fn from(value: user_api::PlatformAccountCreateRequest) -> Self {
let new_organization = api_org::OrganizationNew::new(
common_enums::OrganizationType::Platform,
Some(value.organization_name.expose()),
);
let db_organization = ForeignFrom::foreign_from(new_organization);
Self(db_organization)
}
}
type InviteeUserRequestWithInvitedUserToken = (user_api::InviteUserRequest, UserFromToken);
impl From<InviteeUserRequestWithInvitedUserToken> for NewUserOrganization {
fn from(_value: InviteeUserRequestWithInvitedUserToken) -> Self {
let new_organization =
api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None);
let db_organization = ForeignFrom::foreign_from(new_organization);
Self(db_organization)
}
}
impl From<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUserOrganization {
fn from(
(_value, merchant_account_identifier): (
user_api::CreateTenantUserRequest,
MerchantAccountIdentifier,
),
) -> Self {
let new_organization = api_org::OrganizationNew {
org_id: merchant_account_identifier.org_id,
org_type: common_enums::OrganizationType::Standard,
org_name: None,
};
let db_organization = ForeignFrom::foreign_from(new_organization);
Self(db_organization)
}
}
impl ForeignFrom<api_models::user::UserOrgMerchantCreateRequest>
for diesel_models::organization::OrganizationNew
{
fn foreign_from(item: api_models::user::UserOrgMerchantCreateRequest) -> Self {
let org_id = id_type::OrganizationId::default();
let api_models::user::UserOrgMerchantCreateRequest {
organization_name,
organization_details,
metadata,
..
} = item;
let mut org_new_db = Self::new(
org_id,
common_enums::OrganizationType::Standard,
Some(organization_name.expose()),
);
org_new_db.organization_details = organization_details;
org_new_db.metadata = metadata;
org_new_db
}
}
#[derive(Clone)]
pub struct MerchantId(String);
impl MerchantId {
pub fn new(merchant_id: String) -> UserResult<Self> {
let merchant_id = merchant_id.trim().to_lowercase().replace(' ', "_");
let is_empty_or_whitespace = merchant_id.is_empty();
let is_all_valid_characters = merchant_id.chars().all(|x| x.is_alphanumeric() || x == '_');
if is_empty_or_whitespace || !is_all_valid_characters {
Err(UserErrors::MerchantIdParsingError.into())
} else {
Ok(Self(merchant_id.to_string()))
}
}
pub fn get_secret(&self) -> String {
self.0.clone()
}
}
impl TryFrom<MerchantId> for id_type::MerchantId {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: MerchantId) -> Result<Self, Self::Error> {
Self::try_from(std::borrow::Cow::from(value.0))
.change_context(UserErrors::MerchantIdParsingError)
.attach_printable("Could not convert user merchant_id to merchant_id type")
}
}
#[derive(Clone)]
pub struct NewUserMerchant {
merchant_id: id_type::MerchantId,
company_name: Option<UserCompanyName>,
new_organization: NewUserOrganization,
product_type: Option<common_enums::MerchantProductType>,
merchant_account_type: Option<common_enums::MerchantAccountRequestType>,
}
impl TryFrom<UserCompanyName> for MerchantName {
// We should ideally not get this error because all the validations are done for company name
type Error = error_stack::Report<UserErrors>;
fn try_from(company_name: UserCompanyName) -> Result<Self, Self::Error> {
Self::try_new(company_name.get_secret()).change_context(UserErrors::CompanyNameParsingError)
}
}
impl NewUserMerchant {
pub fn get_company_name(&self) -> Option<String> {
self.company_name.clone().map(UserCompanyName::get_secret)
}
pub fn get_merchant_id(&self) -> id_type::MerchantId {
self.merchant_id.clone()
}
pub fn get_new_organization(&self) -> NewUserOrganization {
self.new_organization.clone()
}
pub fn get_product_type(&self) -> Option<common_enums::MerchantProductType> {
self.product_type
}
pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> {
if state
.store
.get_merchant_key_store_by_merchant_id(
&(&state).into(),
&self.get_merchant_id(),
&state.store.get_master_key().to_vec().into(),
)
.await
.is_ok()
{
return Err(UserErrors::MerchantAccountCreationError(format!(
"Merchant with {:?} already exists",
self.get_merchant_id()
))
.into());
}
Ok(())
}
#[cfg(feature = "v2")]
fn create_merchant_account_request(&self) -> UserResult<admin_api::MerchantAccountCreate> {
let merchant_name = if let Some(company_name) = self.company_name.clone() {
MerchantName::try_from(company_name)
} else {
MerchantName::try_new("merchant".to_string())
.change_context(UserErrors::InternalServerError)
.attach_printable("merchant name validation failed")
}
.map(Secret::new)?;
Ok(admin_api::MerchantAccountCreate {
merchant_name,
organization_id: self.new_organization.get_organization_id(),
metadata: None,
merchant_details: None,
product_type: self.get_product_type(),
})
}
#[cfg(feature = "v1")]
fn create_merchant_account_request(&self) -> UserResult<admin_api::MerchantAccountCreate> {
Ok(admin_api::MerchantAccountCreate {
merchant_id: self.get_merchant_id(),
metadata: None,
locker_id: None,
return_url: None,
merchant_name: self.get_company_name().map(Secret::new),
webhook_details: None,
publishable_key: None,
organization_id: Some(self.new_organization.get_organization_id()),
merchant_details: None,
routing_algorithm: None,
parent_merchant_id: None,
sub_merchants_enabled: None,
frm_routing_algorithm: None,
#[cfg(feature = "payouts")]
payout_routing_algorithm: None,
primary_business_details: None,
payment_response_hash_key: None,
enable_payment_response_hash: None,
redirect_to_merchant_with_http_post: None,
pm_collect_link_config: None,
product_type: self.get_product_type(),
merchant_account_type: self.merchant_account_type,
})
}
#[cfg(feature = "v1")]
pub async fn create_new_merchant_and_insert_in_db(
&self,
state: SessionState,
) -> UserResult<domain::MerchantAccount> {
self.check_if_already_exists_in_db(state.clone()).await?;
let merchant_account_create_request = self
.create_merchant_account_request()
.attach_printable("Unable to construct merchant account create request")?;
let org_id = merchant_account_create_request
.clone()
.organization_id
.ok_or(UserErrors::InternalServerError)?;
let ApplicationResponse::Json(merchant_account_response) =
Box::pin(admin::create_merchant_account(
state.clone(),
merchant_account_create_request,
Some(AuthenticationDataWithOrg {
organization_id: org_id,
}),
))
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error while creating merchant")?
else {
return Err(UserErrors::InternalServerError.into());
};
let key_manager_state = &(&state).into();
let merchant_key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_account_response.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve merchant key store by merchant_id")?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(
key_manager_state,
&merchant_account_response.merchant_id,
&merchant_key_store,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve merchant account by merchant_id")?;
Ok(merchant_account)
}
#[cfg(feature = "v2")]
pub async fn create_new_merchant_and_insert_in_db(
&self,
state: SessionState,
) -> UserResult<domain::MerchantAccount> {
self.check_if_already_exists_in_db(state.clone()).await?;
let merchant_account_create_request = self
.create_merchant_account_request()
.attach_printable("unable to construct merchant account create request")?;
let ApplicationResponse::Json(merchant_account_response) = Box::pin(
admin::create_merchant_account(state.clone(), merchant_account_create_request, None),
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error while creating a merchant")?
else {
return Err(UserErrors::InternalServerError.into());
};
let profile_create_request = admin_api::ProfileCreate {
profile_name: consts::user::DEFAULT_PROFILE_NAME.to_string(),
..Default::default()
};
let key_manager_state = &(&state).into();
let merchant_key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_account_response.id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve merchant key store by merchant_id")?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(
key_manager_state,
&merchant_account_response.id,
&merchant_key_store,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve merchant account by merchant_id")?;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
merchant_account.clone(),
merchant_key_store,
)));
Box::pin(admin::create_profile(
state,
profile_create_request,
merchant_context,
))
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error while creating a profile")?;
Ok(merchant_account)
}
}
impl TryFrom<user_api::SignUpRequest> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::SignUpRequest) -> UserResult<Self> {
let merchant_id = id_type::MerchantId::new_from_unix_timestamp();
let new_organization = NewUserOrganization::from(value);
let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE);
Ok(Self {
company_name: None,
merchant_id,
new_organization,
product_type,
merchant_account_type: None,
})
}
}
impl TryFrom<user_api::ConnectAccountRequest> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::ConnectAccountRequest) -> UserResult<Self> {
let merchant_id = id_type::MerchantId::new_from_unix_timestamp();
let new_organization = NewUserOrganization::from(value);
let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE);
Ok(Self {
company_name: None,
merchant_id,
new_organization,
product_type,
merchant_account_type: None,
})
}
}
impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> {
let company_name = Some(UserCompanyName::new(value.company_name.clone())?);
let merchant_id = MerchantId::new(value.company_name.clone())?;
let new_organization = NewUserOrganization::try_from(value)?;
let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE);
Ok(Self {
company_name,
merchant_id: id_type::MerchantId::try_from(merchant_id)?,
new_organization,
product_type,
merchant_account_type: None,
})
}
}
impl TryFrom<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(
value: (user_api::CreateInternalUserRequest, id_type::OrganizationId),
) -> UserResult<Self> {
let merchant_id = id_type::MerchantId::get_internal_user_merchant_id(
consts::user_role::INTERNAL_USER_MERCHANT_ID,
);
let new_organization = NewUserOrganization::from(value);
Ok(Self {
company_name: None,
merchant_id,
new_organization,
product_type: None,
merchant_account_type: None,
})
}
}
impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: InviteeUserRequestWithInvitedUserToken) -> UserResult<Self> {
let merchant_id = value.clone().1.merchant_id;
let new_organization = NewUserOrganization::from(value);
Ok(Self {
company_name: None,
merchant_id,
new_organization,
product_type: None,
merchant_account_type: None,
})
}
}
impl From<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUserMerchant {
fn from(value: (user_api::CreateTenantUserRequest, MerchantAccountIdentifier)) -> Self {
let merchant_id = value.1.merchant_id.clone();
let new_organization = NewUserOrganization::from(value);
Self {
company_name: None,
merchant_id,
new_organization,
product_type: None,
merchant_account_type: None,
}
}
}
type UserMerchantCreateRequestWithToken =
(UserFromStorage, user_api::UserMerchantCreate, UserFromToken);
impl TryFrom<UserMerchantCreateRequestWithToken> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: UserMerchantCreateRequestWithToken) -> UserResult<Self> {
let merchant_id =
utils::user::generate_env_specific_merchant_id(value.1.company_name.clone())?;
let (user_from_storage, user_merchant_create, user_from_token) = value;
Ok(Self {
merchant_id,
company_name: Some(UserCompanyName::new(
user_merchant_create.company_name.clone(),
)?),
product_type: user_merchant_create.product_type,
merchant_account_type: user_merchant_create.merchant_account_type,
new_organization: NewUserOrganization::from((
user_from_storage,
user_merchant_create,
user_from_token,
)),
})
}
}
impl TryFrom<user_api::PlatformAccountCreateRequest> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::PlatformAccountCreateRequest) -> UserResult<Self> {
let merchant_id = utils::user::generate_env_specific_merchant_id(
value.organization_name.clone().expose(),
)?;
let new_organization = NewUserOrganization::from(value);
Ok(Self {
company_name: None,
merchant_id,
new_organization,
product_type: Some(consts::user::DEFAULT_PRODUCT_TYPE),
merchant_account_type: None,
})
}
}
#[derive(Debug, Clone)]
pub struct MerchantAccountIdentifier {
pub merchant_id: id_type::MerchantId,
pub org_id: id_type::OrganizationId,
}
#[derive(Clone)]
pub struct NewUser {
user_id: String,
name: UserName,
email: UserEmail,
password: Option<NewUserPassword>,
new_merchant: NewUserMerchant,
}
#[derive(Clone)]
pub struct NewUserPassword {
password: UserPassword,
is_temporary: bool,
}
impl Deref for NewUserPassword {
type Target = UserPassword;
fn deref(&self) -> &Self::Target {
&self.password
}
}
impl NewUser {
pub fn get_user_id(&self) -> String {
self.user_id.clone()
}
pub fn get_email(&self) -> UserEmail {
self.email.clone()
}
pub fn get_name(&self) -> Secret<String> {
self.name.clone().get_secret()
}
pub fn get_new_merchant(&self) -> NewUserMerchant {
self.new_merchant.clone()
}
pub fn get_password(&self) -> Option<UserPassword> {
self.password
.as_ref()
.map(|password| password.deref().clone())
}
pub async fn insert_user_in_db(
&self,
db: &dyn GlobalStorageInterface,
) -> UserResult<UserFromStorage> {
match db.insert_user(self.clone().try_into()?).await {
Ok(user) => Ok(user.into()),
Err(e) => {
if e.current_context().is_db_unique_violation() {
Err(e.change_context(UserErrors::UserExists))
} else {
Err(e.change_context(UserErrors::InternalServerError))
}
}
}
.attach_printable("Error while inserting user")
}
pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> {
if state
.global_store
.find_user_by_email(&self.get_email())
.await
.is_ok()
{
return Err(report!(UserErrors::UserExists));
}
Ok(())
}
pub async fn insert_user_and_merchant_in_db(
&self,
state: SessionState,
) -> UserResult<UserFromStorage> {
self.check_if_already_exists_in_db(state.clone()).await?;
let db = state.global_store.as_ref();
let merchant_id = self.get_new_merchant().get_merchant_id();
self.new_merchant
.create_new_merchant_and_insert_in_db(state.clone())
.await?;
let created_user = self.insert_user_in_db(db).await;
if created_user.is_err() {
let _ = admin::merchant_account_delete(state, merchant_id).await;
};
created_user
}
pub fn get_no_level_user_role(
self,
role_id: String,
user_status: UserStatus,
) -> NewUserRole<NoLevel> {
let now = common_utils::date_time::now();
let user_id = self.get_user_id();
NewUserRole {
status: user_status,
created_by: user_id.clone(),
last_modified_by: user_id.clone(),
user_id,
role_id,
created_at: now,
last_modified: now,
entity: NoLevel,
}
}
pub async fn insert_org_level_user_role_in_db(
self,
state: SessionState,
role_id: String,
user_status: UserStatus,
) -> UserResult<UserRole> {
let org_id = self
.get_new_merchant()
.get_new_organization()
.get_organization_id();
let org_user_role = self
.get_no_level_user_role(role_id, user_status)
.add_entity(OrganizationLevel {
tenant_id: state.tenant.tenant_id.clone(),
org_id,
});
org_user_role.insert_in_v2(&state).await
}
}
impl TryFrom<NewUser> for storage_user::UserNew {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: NewUser) -> UserResult<Self> {
let hashed_password = value
.password
.as_ref()
.map(|password| password::generate_password_hash(password.get_secret()))
.transpose()?;
let now = common_utils::date_time::now();
Ok(Self {
user_id: value.get_user_id(),
name: value.get_name(),
email: value.get_email().into_inner(),
password: hashed_password,
is_verified: false,
created_at: Some(now),
last_modified_at: Some(now),
totp_status: TotpStatus::NotSet,
totp_secret: None,
totp_recovery_codes: None,
last_password_modified_at: value
.password
.and_then(|password_inner| password_inner.is_temporary.not().then_some(now)),
lineage_context: None,
})
}
}
impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUser {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> {
let email = value.email.clone().try_into()?;
let name = UserName::new(value.name.clone())?;
let password = NewUserPassword {
password: UserPassword::new(value.password.clone())?,
is_temporary: false,
};
let user_id = uuid::Uuid::new_v4().to_string();
let new_merchant = NewUserMerchant::try_from(value)?;
Ok(Self {
name,
email,
password: Some(password),
user_id,
new_merchant,
})
}
}
impl TryFrom<user_api::SignUpRequest> for NewUser {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::SignUpRequest) -> UserResult<Self> {
let user_id = uuid::Uuid::new_v4().to_string();
let email = value.email.clone().try_into()?;
let name = UserName::try_from(value.email.clone())?;
let password = NewUserPassword {
password: UserPassword::new(value.password.clone())?,
is_temporary: false,
};
let new_merchant = NewUserMerchant::try_from(value)?;
Ok(Self {
user_id,
name,
email,
password: Some(password),
new_merchant,
})
}
}
impl TryFrom<user_api::ConnectAccountRequest> for NewUser {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::ConnectAccountRequest) -> UserResult<Self> {
let user_id = uuid::Uuid::new_v4().to_string();
let email = value.email.clone().try_into()?;
let name = UserName::try_from(value.email.clone())?;
let new_merchant = NewUserMerchant::try_from(value)?;
Ok(Self {
user_id,
name,
email,
password: None,
new_merchant,
})
}
}
impl TryFrom<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for NewUser {
type Error = error_stack::Report<UserErrors>;
fn try_from(
(value, org_id): (user_api::CreateInternalUserRequest, id_type::OrganizationId),
) -> UserResult<Self> {
let user_id = uuid::Uuid::new_v4().to_string();
let email = value.email.clone().try_into()?;
let name = UserName::new(value.name.clone())?;
let password = NewUserPassword {
password: UserPassword::new(value.password.clone())?,
is_temporary: false,
};
let new_merchant = NewUserMerchant::try_from((value, org_id))?;
Ok(Self {
user_id,
name,
email,
password: Some(password),
new_merchant,
})
}
}
impl TryFrom<UserMerchantCreateRequestWithToken> for NewUser {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: UserMerchantCreateRequestWithToken) -> Result<Self, Self::Error> {
let user = value.0.clone();
let new_merchant = NewUserMerchant::try_from(value)?;
let password = user
.0
.password
.map(UserPassword::new_password_without_validation)
.transpose()?
.map(|password| NewUserPassword {
password,
is_temporary: false,
});
Ok(Self {
user_id: user.0.user_id,
name: UserName::new(user.0.name)?,
email: user.0.email.clone().try_into()?,
password,
new_merchant,
})
}
}
impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUser {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: InviteeUserRequestWithInvitedUserToken) -> UserResult<Self> {
let user_id = uuid::Uuid::new_v4().to_string();
let email = value.0.email.clone().try_into()?;
let name = UserName::new(value.0.name.clone())?;
let password = cfg!(not(feature = "email")).then_some(NewUserPassword {
password: UserPassword::new(password::get_temp_password())?,
is_temporary: true,
});
let new_merchant = NewUserMerchant::try_from(value)?;
Ok(Self {
user_id,
name,
email,
password,
new_merchant,
})
}
}
impl TryFrom<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUser {
type Error = error_stack::Report<UserErrors>;
fn try_from(
(value, merchant_account_identifier): (
user_api::CreateTenantUserRequest,
MerchantAccountIdentifier,
),
) -> UserResult<Self> {
let user_id = uuid::Uuid::new_v4().to_string();
let email = value.email.clone().try_into()?;
let name = UserName::new(value.name.clone())?;
let password = NewUserPassword {
password: UserPassword::new(value.password.clone())?,
is_temporary: false,
};
let new_merchant = NewUserMerchant::from((value, merchant_account_identifier));
Ok(Self {
user_id,
name,
email,
password: Some(password),
new_merchant,
})
}
}
#[derive(Clone)]
pub struct UserFromStorage(pub storage_user::User);
impl From<storage_user::User> for UserFromStorage {
fn from(value: storage_user::User) -> Self {
Self(value)
}
}
impl UserFromStorage {
pub fn get_user_id(&self) -> &str {
self.0.user_id.as_str()
}
pub fn compare_password(&self, candidate: &Secret<String>) -> UserResult<()> {
if let Some(password) = self.0.password.as_ref() {
match password::is_correct_password(candidate, password) {
Ok(true) => Ok(()),
Ok(false) => Err(UserErrors::InvalidCredentials.into()),
Err(e) => Err(e),
}
} else {
Err(UserErrors::InvalidCredentials.into())
}
}
pub fn get_name(&self) -> Secret<String> {
self.0.name.clone()
}
pub fn get_email(&self) -> pii::Email {
self.0.email.clone()
}
#[cfg(feature = "email")]
pub fn get_verification_days_left(&self, state: &SessionState) -> UserResult<Option<i64>> {
if self.0.is_verified {
return Ok(None);
}
let allowed_unverified_duration =
time::Duration::days(state.conf.email.allowed_unverified_days);
let user_created = self.0.created_at.date();
let last_date_for_verification = user_created
.checked_add(allowed_unverified_duration)
.ok_or(UserErrors::InternalServerError)?;
let today = common_utils::date_time::now().date();
if today >= last_date_for_verification {
return Err(UserErrors::UnverifiedUser.into());
}
let days_left_for_verification = last_date_for_verification - today;
Ok(Some(days_left_for_verification.whole_days()))
}
pub fn is_verified(&self) -> bool {
self.0.is_verified
}
pub fn is_password_rotate_required(&self, state: &SessionState) -> UserResult<bool> {
let last_password_modified_at =
if let Some(last_password_modified_at) = self.0.last_password_modified_at {
last_password_modified_at.date()
} else {
return Ok(true);
};
let password_change_duration =
time::Duration::days(state.conf.user.password_validity_in_days.into());
let last_date_for_password_rotate = last_password_modified_at
.checked_add(password_change_duration)
.ok_or(UserErrors::InternalServerError)?;
let today = common_utils::date_time::now().date();
let days_left_for_password_rotate = last_date_for_password_rotate - today;
Ok(days_left_for_password_rotate.whole_days() < 0)
}
pub async fn get_or_create_key_store(&self, state: &SessionState) -> UserResult<UserKeyStore> {
let master_key = state.store.get_master_key();
let key_manager_state = &state.into();
let key_store_result = state
.global_store
.get_user_key_store_by_user_id(
key_manager_state,
self.get_user_id(),
&master_key.to_vec().into(),
)
.await;
if let Ok(key_store) = key_store_result {
Ok(key_store)
} else if key_store_result
.as_ref()
.map_err(|e| e.current_context().is_db_not_found())
.err()
.unwrap_or(false)
{
let key = services::generate_aes256_key()
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to generate aes 256 key")?;
#[cfg(feature = "keymanager_create")]
{
common_utils::keymanager::transfer_key_to_key_manager(
key_manager_state,
EncryptionTransferRequest {
identifier: Identifier::User(self.get_user_id().to_string()),
key: consts::BASE64_ENGINE.encode(key),
},
)
.await
.change_context(UserErrors::InternalServerError)?;
}
let key_store = UserKeyStore {
user_id: self.get_user_id().to_string(),
key: domain_types::crypto_operation(
key_manager_state,
type_name!(UserKeyStore),
domain_types::CryptoOperation::Encrypt(key.to_vec().into()),
Identifier::User(self.get_user_id().to_string()),
master_key,
)
.await
.and_then(|val| val.try_into_operation())
.change_context(UserErrors::InternalServerError)?,
created_at: common_utils::date_time::now(),
};
state
.global_store
.insert_user_key_store(key_manager_state, key_store, &master_key.to_vec().into())
.await
.change_context(UserErrors::InternalServerError)
} else {
Err(key_store_result
.err()
.map(|e| e.change_context(UserErrors::InternalServerError))
.unwrap_or(UserErrors::InternalServerError.into()))
}
}
pub fn get_totp_status(&self) -> TotpStatus {
self.0.totp_status
}
pub fn get_recovery_codes(&self) -> Option<Vec<Secret<String>>> {
self.0.totp_recovery_codes.clone()
}
pub async fn decrypt_and_get_totp_secret(
&self,
state: &SessionState,
) -> UserResult<Option<Secret<String>>> {
if self.0.totp_secret.is_none() {
return Ok(None);
}
let key_manager_state = &state.into();
let user_key_store = state
.global_store
.get_user_key_store_by_user_id(
key_manager_state,
self.get_user_id(),
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(UserErrors::InternalServerError)?;
Ok(domain_types::crypto_operation::<String, masking::WithType>(
key_manager_state,
type_name!(storage_user::User),
domain_types::CryptoOperation::DecryptOptional(self.0.totp_secret.clone()),
Identifier::User(user_key_store.user_id.clone()),
user_key_store.key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
.change_context(UserErrors::InternalServerError)?
.map(Encryptable::into_inner))
}
}
impl ForeignFrom<UserStatus> for user_role_api::UserStatus {
fn foreign_from(value: UserStatus) -> Self {
match value {
UserStatus::Active => Self::Active,
UserStatus::InvitationSent => Self::InvitationSent,
}
}
}
#[derive(Clone)]
pub struct RoleName(String);
impl RoleName {
pub fn new(name: String) -> UserResult<Self> {
let is_empty_or_whitespace = name.trim().is_empty();
let is_too_long = name.graphemes(true).count() > consts::user_role::MAX_ROLE_NAME_LENGTH;
if is_empty_or_whitespace || is_too_long || name.contains(' ') {
Err(UserErrors::RoleNameParsingError.into())
} else {
Ok(Self(name.to_lowercase()))
}
}
pub fn get_role_name(self) -> String {
self.0
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct RecoveryCodes(pub Vec<Secret<String>>);
impl RecoveryCodes {
pub fn generate_new() -> Self {
let mut rand = rand::thread_rng();
let recovery_codes = (0..consts::user::RECOVERY_CODES_COUNT)
.map(|_| {
let code_part_1 =
Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2);
let code_part_2 =
Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2);
Secret::new(format!("{code_part_1}-{code_part_2}"))
})
.collect::<Vec<_>>();
Self(recovery_codes)
}
pub fn get_hashed(&self) -> UserResult<Vec<Secret<String>>> {
self.0
.iter()
.cloned()
.map(password::generate_password_hash)
.collect::<Result<Vec<_>, _>>()
}
pub fn into_inner(self) -> Vec<Secret<String>> {
self.0
}
}
// This is for easier construction
#[derive(Clone)]
pub struct NoLevel;
#[derive(Clone)]
pub struct TenantLevel {
pub tenant_id: id_type::TenantId,
}
#[derive(Clone)]
pub struct OrganizationLevel {
pub tenant_id: id_type::TenantId,
pub org_id: id_type::OrganizationId,
}
#[derive(Clone)]
pub struct MerchantLevel {
pub tenant_id: id_type::TenantId,
pub org_id: id_type::OrganizationId,
pub merchant_id: id_type::MerchantId,
}
#[derive(Clone)]
pub struct ProfileLevel {
pub tenant_id: id_type::TenantId,
pub org_id: id_type::OrganizationId,
pub merchant_id: id_type::MerchantId,
pub profile_id: id_type::ProfileId,
}
#[derive(Clone)]
pub struct NewUserRole<E: Clone> {
pub user_id: String,
pub role_id: String,
pub status: UserStatus,
pub created_by: String,
pub last_modified_by: String,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub entity: E,
}
impl NewUserRole<NoLevel> {
pub fn add_entity<T>(self, entity: T) -> NewUserRole<T>
where
T: Clone,
{
NewUserRole {
entity,
user_id: self.user_id,
role_id: self.role_id,
status: self.status,
created_by: self.created_by,
last_modified_by: self.last_modified_by,
created_at: self.created_at,
last_modified: self.last_modified,
}
}
}
pub struct EntityInfo {
tenant_id: id_type::TenantId,
org_id: Option<id_type::OrganizationId>,
merchant_id: Option<id_type::MerchantId>,
profile_id: Option<id_type::ProfileId>,
entity_id: String,
entity_type: EntityType,
}
impl From<TenantLevel> for EntityInfo {
fn from(value: TenantLevel) -> Self {
Self {
entity_id: value.tenant_id.get_string_repr().to_owned(),
entity_type: EntityType::Tenant,
tenant_id: value.tenant_id,
org_id: None,
merchant_id: None,
profile_id: None,
}
}
}
impl From<OrganizationLevel> for EntityInfo {
fn from(value: OrganizationLevel) -> Self {
Self {
entity_id: value.org_id.get_string_repr().to_owned(),
entity_type: EntityType::Organization,
tenant_id: value.tenant_id,
org_id: Some(value.org_id),
merchant_id: None,
profile_id: None,
}
}
}
impl From<MerchantLevel> for EntityInfo {
fn from(value: MerchantLevel) -> Self {
Self {
entity_id: value.merchant_id.get_string_repr().to_owned(),
entity_type: EntityType::Merchant,
tenant_id: value.tenant_id,
org_id: Some(value.org_id),
merchant_id: Some(value.merchant_id),
profile_id: None,
}
}
}
impl From<ProfileLevel> for EntityInfo {
fn from(value: ProfileLevel) -> Self {
Self {
entity_id: value.profile_id.get_string_repr().to_owned(),
entity_type: EntityType::Profile,
tenant_id: value.tenant_id,
org_id: Some(value.org_id),
merchant_id: Some(value.merchant_id),
profile_id: Some(value.profile_id),
}
}
}
impl<E> NewUserRole<E>
where
E: Clone + Into<EntityInfo>,
{
fn convert_to_new_v2_role(self, entity: EntityInfo) -> UserRoleNew {
UserRoleNew {
user_id: self.user_id,
role_id: self.role_id,
status: self.status,
created_by: self.created_by,
last_modified_by: self.last_modified_by,
created_at: self.created_at,
last_modified: self.last_modified,
org_id: entity.org_id,
merchant_id: entity.merchant_id,
profile_id: entity.profile_id,
entity_id: Some(entity.entity_id),
entity_type: Some(entity.entity_type),
version: UserRoleVersion::V2,
tenant_id: entity.tenant_id,
}
}
pub async fn insert_in_v2(self, state: &SessionState) -> UserResult<UserRole> {
let entity = self.entity.clone();
let new_v2_role = self.convert_to_new_v2_role(entity.into());
state
.global_store
.insert_user_role(new_v2_role)
.await
.change_context(UserErrors::InternalServerError)
}
}
|
crates/router/src/types/domain/user.rs
|
router::src::types::domain::user
| 10,605
| true
|
// File: crates/router/src/types/domain/user_key_store.rs
// Module: router::src::types::domain::user_key_store
use common_utils::{
crypto::Encryptable,
date_time, type_name,
types::keymanager::{Identifier, KeyManagerState},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};
use masking::{PeekInterface, Secret};
use time::PrimitiveDateTime;
use crate::errors::{CustomResult, ValidationError};
#[derive(Clone, Debug, serde::Serialize)]
pub struct UserKeyStore {
pub user_id: String,
pub key: Encryptable<Secret<Vec<u8>>>,
pub created_at: PrimitiveDateTime,
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for UserKeyStore {
type DstType = diesel_models::user_key_store::UserKeyStore;
type NewDstType = diesel_models::user_key_store::UserKeyStoreNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::user_key_store::UserKeyStore {
key: self.key.into(),
user_id: self.user_id,
created_at: self.created_at,
})
}
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
_key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let identifier = Identifier::User(item.user_id.clone());
Ok(Self {
key: crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::Decrypt(item.key),
identifier,
key.peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
})?,
user_id: item.user_id,
created_at: item.created_at,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::user_key_store::UserKeyStoreNew {
user_id: self.user_id,
key: self.key.into(),
created_at: date_time::now(),
})
}
}
|
crates/router/src/types/domain/user_key_store.rs
|
router::src::types::domain::user_key_store
| 498
| true
|
// File: crates/router/src/types/domain/user/dashboard_metadata.rs
// Module: router::src::types::domain::user::dashboard_metadata
use api_models::user::dashboard_metadata as api;
use diesel_models::enums::DashboardMetadata as DBEnum;
use masking::Secret;
use time::PrimitiveDateTime;
pub enum MetaData {
ProductionAgreement(ProductionAgreementValue),
SetupProcessor(api::SetupProcessor),
ConfigureEndpoint(bool),
SetupComplete(bool),
FirstProcessorConnected(api::ProcessorConnected),
SecondProcessorConnected(api::ProcessorConnected),
ConfiguredRouting(api::ConfiguredRouting),
TestPayment(api::TestPayment),
IntegrationMethod(api::IntegrationMethod),
ConfigurationType(api::ConfigurationType),
IntegrationCompleted(bool),
StripeConnected(api::ProcessorConnected),
PaypalConnected(api::ProcessorConnected),
SPRoutingConfigured(api::ConfiguredRouting),
Feedback(api::Feedback),
ProdIntent(api::ProdIntent),
SPTestPayment(bool),
DownloadWoocom(bool),
ConfigureWoocom(bool),
SetupWoocomWebhook(bool),
IsMultipleConfiguration(bool),
IsChangePasswordRequired(bool),
OnboardingSurvey(api::OnboardingSurvey),
ReconStatus(api::ReconStatus),
}
impl From<&MetaData> for DBEnum {
fn from(value: &MetaData) -> Self {
match value {
MetaData::ProductionAgreement(_) => Self::ProductionAgreement,
MetaData::SetupProcessor(_) => Self::SetupProcessor,
MetaData::ConfigureEndpoint(_) => Self::ConfigureEndpoint,
MetaData::SetupComplete(_) => Self::SetupComplete,
MetaData::FirstProcessorConnected(_) => Self::FirstProcessorConnected,
MetaData::SecondProcessorConnected(_) => Self::SecondProcessorConnected,
MetaData::ConfiguredRouting(_) => Self::ConfiguredRouting,
MetaData::TestPayment(_) => Self::TestPayment,
MetaData::IntegrationMethod(_) => Self::IntegrationMethod,
MetaData::ConfigurationType(_) => Self::ConfigurationType,
MetaData::IntegrationCompleted(_) => Self::IntegrationCompleted,
MetaData::StripeConnected(_) => Self::StripeConnected,
MetaData::PaypalConnected(_) => Self::PaypalConnected,
MetaData::SPRoutingConfigured(_) => Self::SpRoutingConfigured,
MetaData::Feedback(_) => Self::Feedback,
MetaData::ProdIntent(_) => Self::ProdIntent,
MetaData::SPTestPayment(_) => Self::SpTestPayment,
MetaData::DownloadWoocom(_) => Self::DownloadWoocom,
MetaData::ConfigureWoocom(_) => Self::ConfigureWoocom,
MetaData::SetupWoocomWebhook(_) => Self::SetupWoocomWebhook,
MetaData::IsMultipleConfiguration(_) => Self::IsMultipleConfiguration,
MetaData::IsChangePasswordRequired(_) => Self::IsChangePasswordRequired,
MetaData::OnboardingSurvey(_) => Self::OnboardingSurvey,
MetaData::ReconStatus(_) => Self::ReconStatus,
}
}
}
#[derive(Debug, serde::Serialize)]
pub struct ProductionAgreementValue {
pub version: String,
pub ip_address: Secret<String, common_utils::pii::IpAddress>,
pub timestamp: PrimitiveDateTime,
}
|
crates/router/src/types/domain/user/dashboard_metadata.rs
|
router::src::types::domain::user::dashboard_metadata
| 672
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.