id stringlengths 11 116 | type stringclasses 1 value | granularity stringclasses 4 values | content stringlengths 16 477k | metadata dict |
|---|---|---|---|---|
fn_clm_router_convert_connector_-3346327450445685556 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/api/feature_matrix
// Implementation of None for 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),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 822,
"total_crates": null
} |
fn_clm_router_from_7067224423868750574 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/api/admin
// Implementation of Option<Vec<api_models::profile_acquirer::ProfileAcquirerResponse>> for From<ProfileAcquirerConfigs>
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>>()
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2616,
"total_crates": null
} |
fn_clm_router_foreign_try_from_7067224423868750574 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/api/admin
// Implementation of ProfileResponse for ForeignTryFrom<domain::Profile>
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,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 472,
"total_crates": null
} |
fn_clm_router_foreign_from_7067224423868750574 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/api/admin
// Implementation of OrganizationResponse for ForeignFrom<diesel_models::organization::Organization>
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,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 218,
"total_crates": null
} |
fn_clm_router_create_profile_from_merchant_account_7067224423868750574 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/api/admin
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),
}))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 153,
"total_crates": null
} |
fn_clm_router_new_-6481357865268317346 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/api/connector_onboarding/paypal
// Inherent implementation for 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,
}],
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14465,
"total_crates": null
} |
fn_clm_router_get_eligibility_status_-6481357865268317346 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/api/connector_onboarding/paypal
// Inherent implementation for SellerStatusDetailsResponse
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(),
},
)))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 37,
"total_crates": null
} |
fn_clm_router_extract_merchant_details_url_-6481357865268317346 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/api/connector_onboarding/paypal
// Inherent implementation for 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")
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 33,
"total_crates": null
} |
fn_clm_router_extract_action_url_-6481357865268317346 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/api/connector_onboarding/paypal
// Inherent implementation for 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)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_router_check_ppcp_custom_status_-6481357865268317346 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/api/connector_onboarding/paypal
// Inherent implementation for SellerStatusDetailsResponse
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),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 23,
"total_crates": null
} |
fn_clm_router_get_access_token_3880097457800758828 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/api/verify_connector/paypal
// Implementation of connector::Paypal for VerifyConnector
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
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 77,
"total_crates": null
} |
fn_clm_router_handle_payment_error_response_3490800656688766158 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/api/verify_connector/stripe
// Implementation of connector::Stripe for VerifyConnector
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()),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 20,
"total_crates": null
} |
fn_clm_router_from_-6225805728787523735 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/types
// Implementation of subscriptions::state::SubscriptionState for From<app::SessionState>
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),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2622,
"total_crates": null
} |
fn_clm_router_get_connector_enum_by_name_-6225805728787523735 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/types
// Implementation of ConnectorConversionHandler for hyperswitch_interfaces::api_client::ConnectorConverter
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)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 13,
"total_crates": null
} |
fn_clm_router_from_-7948631172357348352 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/address
// Implementation of AddressUpdateInternal for From<AddressUpdate>
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),
},
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2624,
"total_crates": null
} |
fn_clm_router_convert_-7948631172357348352 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/address
// Implementation of Address for behaviour::Conversion
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),
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 382,
"total_crates": null
} |
fn_clm_router_convert_back_-7948631172357348352 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/address
// Implementation of Address for behaviour::Conversion
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,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 144,
"total_crates": null
} |
fn_clm_router_construct_new_-7948631172357348352 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/address
// Implementation of Address for behaviour::Conversion
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),
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 36,
"total_crates": null
} |
fn_clm_router_from_-1585880191145417585 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/event
// Implementation of EventUpdateInternal for From<EventUpdate>
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),
},
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2602,
"total_crates": null
} |
fn_clm_router_convert_-1585880191145417585 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/event
// Implementation of Event for super::behaviour::Conversion
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,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 366,
"total_crates": null
} |
fn_clm_router_convert_back_-1585880191145417585 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/event
// Implementation of Event for super::behaviour::Conversion
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,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 130,
"total_crates": null
} |
fn_clm_router_construct_new_-1585880191145417585 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/event
// Implementation of Event for super::behaviour::Conversion
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,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 18,
"total_crates": null
} |
fn_clm_router_new_7620147297128252844 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/user
// Inherent implementation for 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()))
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14479,
"total_crates": null
} |
fn_clm_router_try_from_7620147297128252844 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/user
// Implementation of NewUser for TryFrom<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)>
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,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2675,
"total_crates": null
} |
fn_clm_router_from_7620147297128252844 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/user
// Implementation of EntityInfo for From<ProfileLevel>
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),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2604,
"total_crates": null
} |
fn_clm_router_into_inner_7620147297128252844 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/user
// Inherent implementation for RecoveryCodes
pub fn into_inner(self) -> Vec<Secret<String>> {
self.0
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2061,
"total_crates": null
} |
fn_clm_router_get_inner_7620147297128252844 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/user
// Inherent implementation for UserEmail
pub fn get_inner(&self) -> &pii::Email {
&self.0
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 594,
"total_crates": null
} |
fn_clm_router_convert_-8926710149912576507 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/user_key_store
// Implementation of UserKeyStore for super::behaviour::Conversion
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,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 364,
"total_crates": null
} |
fn_clm_router_convert_back_-8926710149912576507 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/user_key_store
// Implementation of UserKeyStore for super::behaviour::Conversion
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,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 122,
"total_crates": null
} |
fn_clm_router_construct_new_-8926710149912576507 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/user_key_store
// Implementation of UserKeyStore for super::behaviour::Conversion
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(),
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 18,
"total_crates": null
} |
fn_clm_router_from_4323264856331774228 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/user/dashboard_metadata
// Implementation of DBEnum for From<&MetaData>
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,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2600,
"total_crates": null
} |
fn_clm_router_new_-5620080041308775103 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/user/decision_manager
// Implementation of None for CurrentFlow
pub fn new(
token: auth::UserFromSinglePurposeToken,
current_flow: UserFlow,
) -> UserResult<Self> {
let flows = token.origin.get_flows();
let index = flows
.iter()
.position(|flow| flow == ¤t_flow)
.ok_or(UserErrors::InternalServerError)?;
let mut path = token.path;
path.push(current_flow.into());
Ok(Self {
origin: token.origin,
current_flow_index: index,
path,
tenant_id: token.tenant_id,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14475,
"total_crates": null
} |
fn_clm_router_from_-5620080041308775103 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/user/decision_manager
// Implementation of UserFlow for From<JWTFlow>
fn from(value: JWTFlow) -> Self {
Self::JWTFlow(value)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2602,
"total_crates": null
} |
fn_clm_router_next_-5620080041308775103 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/user/decision_manager
// Implementation of None for CurrentFlow
pub async fn next(self, user: UserFromStorage, state: &SessionState) -> UserResult<NextFlow> {
let flows = self.origin.get_flows();
let remaining_flows = flows.iter().skip(self.current_flow_index + 1);
for flow in remaining_flows {
if flow
.is_required(
&user,
&self.path,
state,
self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id),
)
.await?
{
return Ok(NextFlow {
origin: self.origin.clone(),
next_flow: *flow,
user,
path: self.path,
tenant_id: self.tenant_id,
});
}
}
Err(UserErrors::InternalServerError.into())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 199,
"total_crates": null
} |
fn_clm_router_skip_-5620080041308775103 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/user/decision_manager
// Implementation of None for NextFlow
pub async fn skip(self, user: UserFromStorage, state: &SessionState) -> UserResult<Self> {
let flows = self.origin.get_flows();
let index = flows
.iter()
.position(|flow| flow == &self.get_flow())
.ok_or(UserErrors::InternalServerError)?;
let remaining_flows = flows.iter().skip(index + 1);
for flow in remaining_flows {
if flow
.is_required(&user, &self.path, state, &state.tenant.tenant_id)
.await?
{
return Ok(Self {
origin: self.origin.clone(),
next_flow: *flow,
user,
path: self.path,
tenant_id: Some(state.tenant.tenant_id.clone()),
});
}
}
Err(UserErrors::InternalServerError.into())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 103,
"total_crates": null
} |
fn_clm_router_generate_jwt_-5620080041308775103 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/types/domain/user/decision_manager
// Implementation of None for JWTFlow
pub async fn generate_jwt(
self,
state: &SessionState,
next_flow: &NextFlow,
user_role: &UserRole,
) -> UserResult<Secret<String>> {
let user_id = next_flow.user.get_user_id();
// Fetch lineage context from DB
let lineage_context_from_db = state
.global_store
.find_user_by_id(user_id)
.await
.inspect_err(|e| {
logger::error!(
"Failed to fetch lineage context from DB for user {}: {:?}",
user_id,
e
)
})
.ok()
.and_then(|user| user.lineage_context);
let new_lineage_context = match lineage_context_from_db {
Some(ctx) => {
let tenant_id = ctx.tenant_id.clone();
let user_role_match_v2 = state
.global_store
.find_user_role_by_user_id_and_lineage(
&ctx.user_id,
&tenant_id,
&ctx.org_id,
&ctx.merchant_id,
&ctx.profile_id,
UserRoleVersion::V2,
)
.await
.inspect_err(|e| {
logger::error!("Failed to validate V2 role: {e:?}");
})
.map(|role| role.role_id == ctx.role_id)
.unwrap_or_default();
if user_role_match_v2 {
ctx
} else {
let user_role_match_v1 = state
.global_store
.find_user_role_by_user_id_and_lineage(
&ctx.user_id,
&tenant_id,
&ctx.org_id,
&ctx.merchant_id,
&ctx.profile_id,
UserRoleVersion::V1,
)
.await
.inspect_err(|e| {
logger::error!("Failed to validate V1 role: {e:?}");
})
.map(|role| role.role_id == ctx.role_id)
.unwrap_or_default();
if user_role_match_v1 {
ctx
} else {
// fallback to default lineage if cached context is invalid
Self::resolve_lineage_from_user_role(state, user_role, user_id).await?
}
}
}
None =>
// no cached context found
{
Self::resolve_lineage_from_user_role(state, user_role, user_id).await?
}
};
utils::user::spawn_async_lineage_context_update_to_db(
state,
user_id,
new_lineage_context.clone(),
);
auth::AuthToken::new_token(
new_lineage_context.user_id,
new_lineage_context.merchant_id,
new_lineage_context.role_id,
&state.conf,
new_lineage_context.org_id,
new_lineage_context.profile_id,
Some(new_lineage_context.tenant_id),
)
.await
.map(|token| token.into())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 72,
"total_crates": null
} |
fn_clm_router_create_vault_token_core_-2936789406217296800 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/tokenization
pub async fn create_vault_token_core(
state: SessionState,
merchant_account: &domain::MerchantAccount,
merchant_key_store: &domain::MerchantKeyStore,
req: api_models::tokenization::GenericTokenizationRequest,
) -> RouterResponse<api_models::tokenization::GenericTokenizationResponse> {
// Generate a unique vault ID
let vault_id = domain::VaultId::generate(uuid::Uuid::now_v7().to_string());
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let customer_id = req.customer_id.clone();
// Create vault request
let payload = pm_types::AddVaultRequest {
entity_id: req.customer_id.to_owned(),
vault_id: vault_id.clone(),
data: req.token_request.clone(),
ttl: state.conf.locker.ttl_for_storage_in_secs,
}
.encode_to_vec()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode Request")?;
// Call the vault service
let resp = pm_vault::call_to_vault::<pm_types::AddVault>(&state, payload.clone())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Call to vault failed")?;
// Parse the response
let stored_resp: pm_types::AddVaultResponse = resp
.parse_struct("AddVaultResponse")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse data into AddVaultResponse")?;
// Create new tokenization record
let tokenization_new = hyperswitch_domain_models::tokenization::Tokenization {
id: id_type::GlobalTokenId::generate(&state.conf.cell_information.id),
merchant_id: merchant_account.get_id().clone(),
customer_id: customer_id.clone(),
locker_id: stored_resp.vault_id.get_string_repr().to_string(),
created_at: common_utils::date_time::now(),
updated_at: common_utils::date_time::now(),
flag: enums::TokenizationFlag::Enabled,
version: enums::ApiVersion::V2,
};
// Insert into database
let tokenization = db
.insert_tokenization(
tokenization_new,
&(merchant_key_store.clone()),
key_manager_state,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert tokenization record")?;
// Convert to TokenizationResponse
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
api_models::tokenization::GenericTokenizationResponse {
id: tokenization.id,
created_at: tokenization.created_at,
flag: tokenization.flag,
},
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 78,
"total_crates": null
} |
fn_clm_router_delete_tokenized_data_core_-2936789406217296800 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/tokenization
pub async fn delete_tokenized_data_core(
state: SessionState,
merchant_context: domain::MerchantContext,
token_id: &id_type::GlobalTokenId,
payload: api_models::tokenization::DeleteTokenDataRequest,
) -> RouterResponse<api_models::tokenization::DeleteTokenDataResponse> {
let db = &*state.store;
let key_manager_state = &(&state).into();
// Retrieve the tokenization record
let tokenization_record = db
.get_entity_id_vault_id_by_token_id(
token_id,
merchant_context.get_merchant_key_store(),
key_manager_state,
)
.await
.to_not_found_response(errors::ApiErrorResponse::TokenizationRecordNotFound {
id: token_id.get_string_repr().to_string(),
})
.attach_printable("Failed to get tokenization record")?;
when(
tokenization_record.customer_id != payload.customer_id,
|| {
Err(errors::ApiErrorResponse::UnprocessableEntity {
message: "Tokenization record does not belong to the customer".to_string(),
})
},
)?;
when(tokenization_record.is_disabled(), || {
Err(errors::ApiErrorResponse::GenericNotFoundError {
message: "Tokenization is already disabled for the id".to_string(),
})
})?;
//fetch locker id
let vault_id = domain::VaultId::generate(tokenization_record.locker_id.clone());
//delete card from vault
pm_vault::delete_payment_method_data_from_vault_internal(
&state,
&merchant_context,
vault_id,
&tokenization_record.customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to delete payment method from vault")?;
//update the status with Disabled
let tokenization_update = hyperswitch_domain_models::tokenization::TokenizationUpdate::DeleteTokenizationRecordUpdate {
flag: Some(enums::TokenizationFlag::Disabled),
};
db.update_tokenization_record(
tokenization_record,
tokenization_update,
merchant_context.get_merchant_key_store(),
key_manager_state,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update tokenization record")?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
api_models::tokenization::DeleteTokenDataResponse {
id: token_id.clone(),
},
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 59,
"total_crates": null
} |
fn_clm_router_get_token_vault_core_-2936789406217296800 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/tokenization
pub async fn get_token_vault_core(
state: SessionState,
merchant_account: &domain::MerchantAccount,
merchant_key_store: &domain::MerchantKeyStore,
query: id_type::GlobalTokenId,
) -> CustomResult<serde_json::Value, errors::ApiErrorResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let tokenization_record = db
.get_entity_id_vault_id_by_token_id(
&query,
&(merchant_key_store.clone()),
key_manager_state,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get tokenization record")?;
if tokenization_record.flag == enums::TokenizationFlag::Disabled {
return Err(errors::ApiErrorResponse::GenericNotFoundError {
message: "Tokenization is disabled for the id".to_string(),
}
.into());
}
let vault_request = pm_types::VaultRetrieveRequest {
entity_id: tokenization_record.customer_id.clone(),
vault_id: hyperswitch_domain_models::payment_methods::VaultId::generate(
tokenization_record.locker_id.clone(),
),
};
let vault_data = pm_vault::retrieve_value_from_vault(&state, vault_request)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve vault data")?;
let data_json = vault_data
.get("data")
.cloned()
.unwrap_or(serde_json::Value::Null);
// Create the response
Ok(data_json)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 44,
"total_crates": null
} |
fn_clm_router_invalidate_2393948367201082179 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/cache
pub async fn invalidate(
state: SessionState,
key: &str,
) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ApiErrorResponse> {
let store = state.store.as_ref();
let result = redact_from_redis_and_publish(
store.get_cache_store().as_ref(),
[CacheKind::All(key.into())],
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
// If the message was published to atleast one channel
// then return status Ok
if result > 0 {
Ok(services::api::ApplicationResponse::StatusOk)
} else {
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate cache"))
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_router_rust_locker_migration_3249157156957504681 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/locker_migration
pub async fn rust_locker_migration(
state: SessionState,
merchant_id: &id_type::MerchantId,
) -> CustomResult<services::ApplicationResponse<MigrateCardResponse>, errors::ApiErrorResponse> {
use crate::db::customers::CustomerListConstraints;
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let merchant_account = db
.find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
// Handle cases where the number of customers is greater than the limit
let constraints = CustomerListConstraints {
limit: u16::MAX,
offset: None,
customer_id: None,
time_range: None,
};
let domain_customers = db
.list_customers_by_merchant_id(key_manager_state, merchant_id, &key_store, constraints)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let mut customers_moved = 0;
let mut cards_moved = 0;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
merchant_account.clone(),
key_store.clone(),
)));
for customer in domain_customers {
let result = db
.find_payment_method_by_customer_id_merchant_id_list(
key_manager_state,
&key_store,
&customer.customer_id,
merchant_id,
None,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.and_then(|pm| {
call_to_locker(
&state,
pm,
&customer.customer_id,
merchant_id,
&merchant_context,
)
})
.await?;
customers_moved += 1;
cards_moved += result;
}
Ok(services::api::ApplicationResponse::Json(
MigrateCardResponse {
status_code: "200".to_string(),
status_message: "Card migration completed".to_string(),
customers_moved,
cards_moved,
},
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 61,
"total_crates": null
} |
fn_clm_router_call_to_locker_3249157156957504681 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/locker_migration
pub async fn call_to_locker(
_state: &SessionState,
_payment_methods: Vec<domain::PaymentMethod>,
_customer_id: &id_type::CustomerId,
_merchant_id: &id_type::MerchantId,
_merchant_context: &domain::MerchantContext,
) -> CustomResult<usize, errors::ApiErrorResponse> {
todo!()
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 13,
"total_crates": null
} |
fn_clm_router_new_-6539017348782900403 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payment_methods
// Inherent implementation for RequiredFieldsInput
fn new(required_fields_config: settings::RequiredFields) -> Self {
Self {
required_fields_config,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14453,
"total_crates": null
} |
fn_clm_router_payment_methods_session_confirm_-6539017348782900403 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payment_methods
pub async fn payment_methods_session_confirm(
state: SessionState,
req_state: routes::app::ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
request: payment_methods::PaymentMethodSessionConfirmRequest,
) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> {
let db: &dyn StorageInterface = state.store.as_ref();
let key_manager_state = &(&state).into();
// Validate if the session still exists
let payment_method_session = db
.get_payment_methods_session(
key_manager_state,
merchant_context.get_merchant_key_store(),
&payment_method_session_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment methods session does not exist or has expired".to_string(),
})
.attach_printable("Failed to retrieve payment methods session from db")?;
let payment_method_session_billing = payment_method_session
.billing
.clone()
.map(|billing| billing.into_inner())
.map(From::from);
// Unify the billing address that we receive from the session and from the confirm request
let unified_billing_address = request
.payment_method_data
.billing
.clone()
.map(|payment_method_billing| {
payment_method_billing.unify_address(payment_method_session_billing.as_ref())
})
.or_else(|| payment_method_session_billing.clone());
let customer_id = payment_method_session.customer_id.clone();
let create_payment_method_request = get_payment_method_create_request(
request
.payment_method_data
.payment_method_data
.as_ref()
.get_required_value("payment_method_data")?,
request.payment_method_type,
request.payment_method_subtype,
customer_id.clone(),
unified_billing_address.as_ref(),
Some(&payment_method_session),
)
.attach_printable("Failed to create payment method request")?;
let (payment_method_response, payment_method) = Box::pin(create_payment_method_core(
&state,
&req_state,
create_payment_method_request.clone(),
&merchant_context,
&profile,
))
.await?;
let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
let token_data = get_pm_list_token_data(request.payment_method_type, &payment_method)?;
let intent_fulfillment_time = common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME;
// insert the token data into redis
if let Some(token_data) = token_data {
pm_routes::ParentPaymentMethodToken::create_key_for_token((
&parent_payment_method_token,
request.payment_method_type,
))
.insert(intent_fulfillment_time, token_data, &state)
.await?;
};
let update_payment_method_session = hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum::UpdateAssociatedPaymentMethods {
associated_payment_methods: Some(vec![parent_payment_method_token.clone()])
};
vault::insert_cvc_using_payment_token(
&state,
&parent_payment_method_token,
create_payment_method_request.payment_method_data.clone(),
request.payment_method_type,
intent_fulfillment_time,
merchant_context.get_merchant_key_store().key.get_inner(),
)
.await?;
let payment_method_session = db
.update_payment_method_session(
key_manager_state,
merchant_context.get_merchant_key_store(),
&payment_method_session_id,
update_payment_method_session,
payment_method_session,
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment methods session does not exist or has expired".to_string(),
})
.attach_printable("Failed to update payment methods session from db")?;
let payments_response = match &payment_method_session.psp_tokenization {
Some(common_types::payment_methods::PspTokenization {
tokenization_type: common_enums::TokenizationType::MultiUse,
..
}) => {
let zero_auth_request = construct_zero_auth_payments_request(
&request,
&payment_method_session,
&payment_method_response,
)?;
let payments_response = Box::pin(create_zero_auth_payment(
state.clone(),
req_state,
merchant_context.clone(),
profile.clone(),
zero_auth_request,
))
.await?;
Some(payments_response)
}
Some(common_types::payment_methods::PspTokenization {
tokenization_type: common_enums::TokenizationType::SingleUse,
..
}) => {
Box::pin(create_single_use_tokenization_flow(
state.clone(),
req_state.clone(),
merchant_context.clone(),
profile.clone(),
&create_payment_method_request.clone(),
&payment_method_response,
&payment_method_session,
))
.await?;
None
}
None => None,
};
let tokenization_response = match payment_method_session.tokenization_data.clone() {
Some(tokenization_data) => {
let tokenization_response = tokenization_core::create_vault_token_core(
state.clone(),
&merchant_context.get_merchant_account().clone(),
&merchant_context.get_merchant_key_store().clone(),
api_models::tokenization::GenericTokenizationRequest {
customer_id: customer_id.clone(),
token_request: tokenization_data,
},
)
.await?;
let token = match tokenization_response {
services::ApplicationResponse::Json(response) => Some(response),
_ => None,
};
Some(token)
}
None => None,
};
logger::debug!(?tokenization_response, "Tokenization response");
//TODO: update the payment method session with the payment id and payment method id
let payment_method_session_response = transformers::generate_payment_method_session_response(
payment_method_session,
Secret::new("CLIENT_SECRET_REDACTED".to_string()),
payments_response,
(tokenization_response.flatten()),
);
Ok(services::ApplicationResponse::Json(
payment_method_session_response,
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 145,
"total_crates": null
} |
fn_clm_router_render_pm_collect_link_-6539017348782900403 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payment_methods
pub async fn render_pm_collect_link(
state: SessionState,
merchant_context: domain::MerchantContext,
req: payment_methods::PaymentMethodCollectLinkRenderRequest,
) -> RouterResponse<services::GenericLinkFormData> {
let db: &dyn StorageInterface = &*state.store;
// Fetch pm collect link
let pm_collect_link = db
.find_pm_collect_link_by_link_id(&req.pm_collect_link_id)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment method collect link not found".to_string(),
})?;
// Check status and return form data accordingly
let has_expired = common_utils::date_time::now() > pm_collect_link.expiry;
let status = pm_collect_link.link_status;
let link_data = pm_collect_link.link_data;
let default_config = &state.conf.generic_link.payment_method_collect;
let default_ui_config = default_config.ui_config.clone();
let ui_config_data = common_utils::link_utils::GenericLinkUiConfigFormData {
merchant_name: link_data
.ui_config
.merchant_name
.unwrap_or(default_ui_config.merchant_name),
logo: link_data.ui_config.logo.unwrap_or(default_ui_config.logo),
theme: link_data
.ui_config
.theme
.clone()
.unwrap_or(default_ui_config.theme.clone()),
};
match status {
common_utils::link_utils::PaymentMethodCollectStatus::Initiated => {
// if expired, send back expired status page
if has_expired {
let expired_link_data = services::GenericExpiredLinkData {
title: "Payment collect link has expired".to_string(),
message: "This payment collect link has expired.".to_string(),
theme: link_data.ui_config.theme.unwrap_or(default_ui_config.theme),
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::ExpiredLink(expired_link_data),
locale: DEFAULT_LOCALE.to_string(),
},
)))
// else, send back form link
} else {
let customer_id = id_type::CustomerId::try_from(Cow::from(
pm_collect_link.primary_reference.clone(),
))
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "customer_id",
})?;
// Fetch customer
let customer = db
.find_customer_by_customer_id_merchant_id(
&(&state).into(),
&customer_id,
&req.merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Customer [{}] not found for link_id - {}",
pm_collect_link.primary_reference, pm_collect_link.link_id
),
})
.attach_printable(format!(
"customer [{}] not found",
pm_collect_link.primary_reference
))?;
let js_data = payment_methods::PaymentMethodCollectLinkDetails {
publishable_key: Secret::new(
merchant_context
.get_merchant_account()
.clone()
.publishable_key,
),
client_secret: link_data.client_secret.clone(),
pm_collect_link_id: pm_collect_link.link_id,
customer_id: customer.customer_id,
session_expiry: pm_collect_link.expiry,
return_url: pm_collect_link.return_url,
ui_config: ui_config_data,
enabled_payment_methods: link_data.enabled_payment_methods,
};
let serialized_css_content = String::new();
let serialized_js_content = format!(
"window.__PM_COLLECT_DETAILS = {}",
js_data
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize PaymentMethodCollectLinkDetails")?
);
let generic_form_data = services::GenericLinkFormData {
js_data: serialized_js_content,
css_data: serialized_css_content,
sdk_url: default_config.sdk_url.clone(),
html_meta_tags: String::new(),
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::PaymentMethodCollect(generic_form_data),
locale: DEFAULT_LOCALE.to_string(),
},
)))
}
}
// Send back status page
status => {
let js_data = payment_methods::PaymentMethodCollectLinkStatusDetails {
pm_collect_link_id: pm_collect_link.link_id,
customer_id: link_data.customer_id,
session_expiry: pm_collect_link.expiry,
return_url: pm_collect_link
.return_url
.as_ref()
.map(|url| url::Url::parse(url))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to parse return URL for payment method collect's status link",
)?,
ui_config: ui_config_data,
status,
};
let serialized_css_content = String::new();
let serialized_js_content = format!(
"window.__PM_COLLECT_DETAILS = {}",
js_data
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to serialize PaymentMethodCollectLinkStatusDetails"
)?
);
let generic_status_data = services::GenericLinkStatusData {
js_data: serialized_js_content,
css_data: serialized_css_content,
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::PaymentMethodCollectStatus(generic_status_data),
locale: DEFAULT_LOCALE.to_string(),
},
)))
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 117,
"total_crates": null
} |
fn_clm_router_create_single_use_tokenization_flow_-6539017348782900403 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payment_methods
async fn create_single_use_tokenization_flow(
state: SessionState,
req_state: routes::app::ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
payment_method_create_request: &payment_methods::PaymentMethodCreate,
payment_method: &api::PaymentMethodResponse,
payment_method_session: &domain::payment_methods::PaymentMethodSession,
) -> RouterResult<()> {
let customer_id = payment_method_create_request.customer_id.to_owned();
let connector_id = payment_method_create_request
.get_tokenize_connector_id()
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "psp_tokenization.connector_id",
})
.attach_printable("Failed to get tokenize connector id")?;
let db = &state.store;
let merchant_connector_account_details = db
.find_merchant_connector_account_by_id(
&(&state).into(),
&connector_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_id.get_string_repr().to_owned(),
})
.attach_printable("error while fetching merchant_connector_account from connector_id")?;
let auth_type = merchant_connector_account_details
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
let payment_method_data_request = types::PaymentMethodTokenizationData {
payment_method_data: domain::PaymentMethodData::try_from(
payment_method_create_request.payment_method_data.clone(),
)
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "card_cvc",
})
.attach_printable(
"Failed to convert type from Payment Method Create Data to Payment Method Data",
)?,
browser_info: None,
currency: api_models::enums::Currency::default(),
amount: None,
split_payments: None,
mandate_id: None,
setup_future_usage: None,
customer_acceptance: None,
setup_mandate_details: None,
};
let payment_method_session_address = types::PaymentAddress::new(
None,
payment_method_session
.billing
.clone()
.map(|address| address.into_inner()),
None,
None,
);
let mut router_data =
types::RouterData::<api::PaymentMethodToken, _, types::PaymentsResponseData> {
flow: std::marker::PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
customer_id: None,
connector_customer: None,
connector: merchant_connector_account_details
.connector_name
.to_string(),
payment_id: consts::IRRELEVANT_PAYMENT_INTENT_ID.to_string(), //Static
attempt_id: consts::IRRELEVANT_PAYMENT_ATTEMPT_ID.to_string(), //Static
tenant_id: state.tenant.tenant_id.clone(),
status: common_enums::enums::AttemptStatus::default(),
payment_method: common_enums::enums::PaymentMethod::Card,
payment_method_type: None,
connector_auth_type: auth_type,
description: None,
address: payment_method_session_address,
auth_type: common_enums::enums::AuthenticationType::default(),
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_api_version: None,
request: payment_method_data_request.clone(),
response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
connector_request_reference_id: payment_method_session.id.get_string_repr().to_string(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
dispute_id: None,
refund_id: None,
connector_response: None,
payment_method_status: None,
minor_amount_captured: 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,
};
let payment_method_token_response = Box::pin(tokenization::add_token_for_payment_method(
&mut router_data,
payment_method_data_request.clone(),
state.clone(),
&merchant_connector_account_details.clone(),
))
.await?;
let token_response = payment_method_token_response.token.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: (merchant_connector_account_details.clone())
.connector_name
.to_string(),
status_code: err.status_code,
reason: err.reason,
}
})?;
let value = domain::SingleUsePaymentMethodToken::get_single_use_token_from_payment_method_token(
token_response.clone().into(),
connector_id.clone(),
);
let key = domain::SingleUseTokenKey::store_key(&payment_method.id);
add_single_use_token_to_store(&state, key, value)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to store single use token")?;
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 107,
"total_crates": null
} |
fn_clm_router_payment_methods_session_create_-6539017348782900403 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payment_methods
pub async fn payment_methods_session_create(
state: SessionState,
merchant_context: domain::MerchantContext,
request: payment_methods::PaymentMethodSessionRequest,
) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
db.find_customer_by_global_id(
key_manager_state,
&request.customer_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let payment_methods_session_id =
id_type::GlobalPaymentMethodSessionId::generate(&state.conf.cell_information.id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodSessionId")?;
let encrypted_data = request
.encrypt_data(key_manager_state, merchant_context.get_merchant_key_store())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encrypt payment methods session data")?;
let billing = encrypted_data
.billing
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode billing address")?;
// If not passed in the request, use the default value from constants
let expires_in = request
.expires_in
.unwrap_or(consts::DEFAULT_PAYMENT_METHOD_SESSION_EXPIRY)
.into();
let expires_at = common_utils::date_time::now().saturating_add(Duration::seconds(expires_in));
let client_secret = payment_helpers::create_client_secret(
&state,
merchant_context.get_merchant_account().get_id(),
util_types::authentication::ResourceId::PaymentMethodSession(
payment_methods_session_id.clone(),
),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to create client secret")?;
let payment_method_session_domain_model =
hyperswitch_domain_models::payment_methods::PaymentMethodSession {
id: payment_methods_session_id,
customer_id: request.customer_id,
billing,
psp_tokenization: request.psp_tokenization,
network_tokenization: request.network_tokenization,
tokenization_data: request.tokenization_data,
expires_at,
return_url: request.return_url,
associated_payment_methods: None,
associated_payment: None,
associated_token_id: None,
};
db.insert_payment_methods_session(
key_manager_state,
merchant_context.get_merchant_key_store(),
payment_method_session_domain_model.clone(),
expires_in,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert payment methods session in db")?;
let response = transformers::generate_payment_method_session_response(
payment_method_session_domain_model,
client_secret.secret,
None,
None,
);
Ok(services::ApplicationResponse::Json(response))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 93,
"total_crates": null
} |
fn_clm_router_try_from_3507676463711217141 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/proxy
// Implementation of proxy_api_models::ProxyResponse for TryFrom<ProxyResponseWrapper>
fn try_from(wrapper: ProxyResponseWrapper) -> Result<Self, Self::Error> {
let res = wrapper.0;
let response_body: Value = res
.response
.parse_struct("ProxyResponse")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse the response")?;
let status_code = res.status_code;
let response_headers = proxy_api_models::Headers::from_header_map(res.headers.as_ref());
Ok(Self {
response: response_body,
status_code,
response_headers,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2667,
"total_crates": null
} |
fn_clm_router_execute_proxy_request_3507676463711217141 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/proxy
async fn execute_proxy_request(
state: &SessionState,
req_wrapper: &utils::ProxyRequestWrapper,
processed_body: Value,
) -> RouterResult<Response> {
let request = RequestBuilder::new()
.method(req_wrapper.get_method())
.attach_default_headers()
.headers(req_wrapper.get_headers())
.url(req_wrapper.get_destination_url())
.set_body(request::RequestContent::Json(Box::new(processed_body)))
.build();
let response = services::call_connector_api(state, request, "proxy")
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to call the destination");
response
.map(|inner| match inner {
Err(err_res) => {
logger::error!("Error while receiving response: {err_res:?}");
err_res
}
Ok(res) => res,
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while receiving response")
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 39,
"total_crates": null
} |
fn_clm_router_proxy_core_3507676463711217141 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/proxy
pub async fn proxy_core(
state: SessionState,
merchant_context: domain::MerchantContext,
req: proxy_api_models::ProxyRequest,
) -> RouterResponse<proxy_api_models::ProxyResponse> {
let req_wrapper = utils::ProxyRequestWrapper(req.clone());
let proxy_record = req_wrapper
.get_proxy_record(
&state,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let vault_data = proxy_record
.get_vault_data(&state, merchant_context)
.await?;
let processed_body =
interpolate_token_references_with_vault_data(req.request_body.clone(), &vault_data)?;
let res = execute_proxy_request(&state, &req_wrapper, processed_body).await?;
let proxy_response = proxy_api_models::ProxyResponse::try_from(ProxyResponseWrapper(res))?;
Ok(services::ApplicationResponse::Json(proxy_response))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 37,
"total_crates": null
} |
fn_clm_router_interpolate_token_references_with_vault_data_3507676463711217141 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/proxy
fn interpolate_token_references_with_vault_data(
value: Value,
vault_data: &Value,
) -> RouterResult<Value> {
match value {
Value::Object(obj) => {
let new_obj = obj
.into_iter()
.map(|(key, val)| interpolate_token_references_with_vault_data(val, vault_data).map(|processed| (key, processed)))
.collect::<Result<serde_json::Map<_, _>, error_stack::Report<errors::ApiErrorResponse>>>()?;
Ok(Value::Object(new_obj))
}
Value::String(s) => utils::parse_token(&s)
.map(|(_, token_ref)| extract_field_from_vault_data(vault_data, &token_ref.field))
.unwrap_or(Ok(Value::String(s.clone()))),
_ => Ok(value),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 31,
"total_crates": null
} |
fn_clm_router_find_field_recursively_in_vault_data_3507676463711217141 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/proxy
fn find_field_recursively_in_vault_data(
obj: &serde_json::Map<String, Value>,
field_name: &str,
) -> Option<Value> {
obj.get(field_name).cloned().or_else(|| {
obj.values()
.filter_map(|val| {
if let Value::Object(inner_obj) = val {
find_field_recursively_in_vault_data(inner_obj, field_name)
} else {
None
}
})
.next()
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 26,
"total_crates": null
} |
fn_clm_router_foreign_from_8360326204109888828 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/refunds
// Implementation of api::RefundResponse for ForeignFrom<diesel_refund::Refund>
fn foreign_from(refund: diesel_refund::Refund) -> Self {
let refund = refund;
Self {
payment_id: refund.payment_id,
refund_id: refund.refund_id,
amount: refund.refund_amount,
currency: refund.currency.to_string(),
reason: refund.refund_reason,
status: refund.refund_status.foreign_into(),
profile_id: refund.profile_id,
metadata: refund.metadata,
error_message: refund.refund_error_message,
error_code: refund.refund_error_code,
created_at: Some(refund.created_at),
updated_at: Some(refund.modified_at),
connector: refund.connector,
merchant_connector_id: refund.merchant_connector_id,
split_refunds: refund.split_refunds,
unified_code: refund.unified_code,
unified_message: refund.unified_message,
issuer_error_code: refund.issuer_error_code,
issuer_error_message: refund.issuer_error_message,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 216,
"total_crates": null
} |
fn_clm_router_trigger_refund_to_gateway_8360326204109888828 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/refunds
pub async fn trigger_refund_to_gateway(
state: &SessionState,
refund: &diesel_refund::Refund,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
creds_identifier: Option<String>,
split_refunds: Option<SplitRefundsRequest>,
) -> RouterResult<diesel_refund::Refund> {
let routed_through = payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve connector from payment attempt")?;
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
metrics::REFUND_COUNT.add(
1,
router_env::metric_attributes!(("connector", routed_through.clone())),
);
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&routed_through,
api::GetToken::Connector,
payment_attempt.merchant_connector_id.clone(),
)?;
let currency = payment_attempt.currency.ok_or_else(|| {
report!(errors::ApiErrorResponse::InternalServerError).attach_printable(
"Transaction in invalid. Missing field \"currency\" in payment_attempt.",
)
})?;
validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?;
let mut router_data = core_utils::construct_refund_router_data(
state,
&routed_through,
merchant_context,
(payment_attempt.get_total_amount(), currency),
payment_intent,
payment_attempt,
refund,
creds_identifier.clone(),
split_refunds,
)
.await?;
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
merchant_context,
&router_data,
creds_identifier.as_deref(),
))
.await?;
logger::debug!(refund_router_data=?router_data);
access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&payments::CallConnectorAction::Trigger,
);
let router_data_res = if !(add_access_token_result.connector_supports_access_token
&& router_data.access_token.is_none())
{
let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
api::Execute,
types::RefundsData,
types::RefundsResponseData,
> = connector.connector.get_connector_integration();
let router_data_res = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await;
let option_refund_error_update =
router_data_res
.as_ref()
.err()
.and_then(|error| match error.current_context() {
errors::ConnectorError::NotImplemented(message) => {
Some(diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: Some(
errors::ConnectorError::NotImplemented(message.to_owned())
.to_string(),
),
refund_error_code: Some("NOT_IMPLEMENTED".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
})
}
errors::ConnectorError::NotSupported { message, connector } => {
Some(diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: Some(format!(
"{message} is not supported by {connector}"
)),
refund_error_code: Some("NOT_SUPPORTED".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
})
}
_ => None,
});
// Update the refund status as failure if connector_error is NotImplemented
if let Some(refund_error_update) = option_refund_error_update {
state
.store
.update_refund(
refund.to_owned(),
refund_error_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while updating refund: refund_id: {}",
refund.refund_id
)
})?;
}
let mut refund_router_data_res = router_data_res.to_refund_failed_response()?;
// Initiating Integrity check
let integrity_result = check_refund_integrity(
&refund_router_data_res.request,
&refund_router_data_res.response,
);
refund_router_data_res.integrity_check = integrity_result;
refund_router_data_res
} else {
router_data
};
let refund_update = match router_data_res.response {
Err(err) => {
let option_gsm = helpers::get_gsm_record(
state,
Some(err.code.clone()),
Some(err.message.clone()),
connector.connector_name.to_string(),
consts::REFUND_FLOW_STR.to_string(),
)
.await;
// Note: Some connectors do not have a separate list of refund errors
// In such cases, the error codes and messages are stored under "Authorize" flow in GSM table
// So we will have to fetch the GSM using Authorize flow in case GSM is not found using "refund_flow"
let option_gsm = if option_gsm.is_none() {
helpers::get_gsm_record(
state,
Some(err.code.clone()),
Some(err.message.clone()),
connector.connector_name.to_string(),
consts::AUTHORIZE_FLOW_STR.to_string(),
)
.await
} else {
option_gsm
};
let gsm_unified_code = option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone());
let gsm_unified_message = option_gsm.and_then(|gsm| gsm.unified_message);
let (unified_code, unified_message) = if let Some((code, message)) =
gsm_unified_code.as_ref().zip(gsm_unified_message.as_ref())
{
(code.to_owned(), message.to_owned())
} else {
(
consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(),
consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(),
)
};
diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: err.reason.or(Some(err.message)),
refund_error_code: Some(err.code),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: Some(unified_code),
unified_message: Some(unified_message),
issuer_error_code: err.network_decline_code,
issuer_error_message: err.network_error_message,
}
}
Ok(response) => {
// match on connector integrity checks
match router_data_res.integrity_check.clone() {
Err(err) => {
let (refund_connector_transaction_id, processor_refund_data) =
err.connector_transaction_id.map_or((None, None), |txn_id| {
let (refund_id, refund_data) =
ConnectorTransactionId::form_id_and_data(txn_id);
(Some(refund_id), refund_data)
});
metrics::INTEGRITY_CHECK_FAILED.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
(
"merchant_id",
merchant_context.get_merchant_account().get_id().clone()
),
),
);
diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::ManualReview),
refund_error_message: Some(format!(
"Integrity Check Failed! as data mismatched for fields {}",
err.field_names
)),
refund_error_code: Some("IE".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: refund_connector_transaction_id,
processor_refund_data,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
}
}
Ok(()) => {
if response.refund_status == diesel_models::enums::RefundStatus::Success {
metrics::SUCCESSFUL_REFUND.add(
1,
router_env::metric_attributes!((
"connector",
connector.connector_name.to_string(),
)),
)
}
let (connector_refund_id, processor_refund_data) =
ConnectorTransactionId::form_id_and_data(response.connector_refund_id);
diesel_refund::RefundUpdate::Update {
connector_refund_id,
refund_status: response.refund_status,
sent_to_gateway: true,
refund_error_message: None,
refund_arn: "".to_string(),
updated_by: storage_scheme.to_string(),
processor_refund_data,
}
}
}
}
};
let response = state
.store
.update_refund(
refund.to_owned(),
refund_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while updating refund: refund_id: {}",
refund.refund_id
)
})?;
utils::trigger_refund_outgoing_webhook(
state,
merchant_context,
&response,
payment_attempt.profile_id.clone(),
)
.await
.map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error))
.ok();
Ok(response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 181,
"total_crates": null
} |
fn_clm_router_validate_and_create_refund_8360326204109888828 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/refunds
pub async fn validate_and_create_refund(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
refund_amount: MinorUnit,
req: refunds::RefundRequest,
creds_identifier: Option<String>,
) -> RouterResult<refunds::RefundResponse> {
let db = &*state.store;
let split_refunds = core_utils::get_split_refunds(SplitRefundInput {
split_payment_request: payment_intent.split_payments.clone(),
payment_charges: payment_attempt.charges.clone(),
charge_id: payment_attempt.charge_id.clone(),
refund_request: req.split_refunds.clone(),
})?;
// Only for initial dev and testing
let refund_type = req.refund_type.unwrap_or_default();
// If Refund Id not passed in request Generate one.
let refund_id = core_utils::get_or_generate_id("refund_id", &req.refund_id, "ref")?;
let predicate = req
.merchant_id
.as_ref()
.map(|merchant_id| merchant_id != merchant_context.get_merchant_account().get_id());
utils::when(predicate.unwrap_or(false), || {
Err(report!(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string()
})
.attach_printable("invalid merchant_id in request"))
})?;
let connector_transaction_id = payment_attempt.clone().connector_transaction_id.ok_or_else(|| {
report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Transaction in invalid. Missing field \"connector_transaction_id\" in payment_attempt.")
})?;
let all_refunds = db
.find_refund_by_merchant_id_connector_transaction_id(
merchant_context.get_merchant_account().get_id(),
&connector_transaction_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let currency = payment_attempt.currency.get_required_value("currency")?;
//[#249]: Add Connector Based Validation here.
validator::validate_payment_order_age(&payment_intent.created_at, state.conf.refund.max_age)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "created_at".to_string(),
expected_format: format!(
"created_at not older than {} days",
state.conf.refund.max_age,
),
})?;
let total_amount_captured = payment_intent
.amount_captured
.unwrap_or(payment_attempt.get_total_amount());
validator::validate_refund_amount(
total_amount_captured.get_amount_as_i64(),
&all_refunds,
refund_amount.get_amount_as_i64(),
)
.change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?;
validator::validate_maximum_refund_against_payment_attempt(
&all_refunds,
state.conf.refund.max_attempts,
)
.change_context(errors::ApiErrorResponse::MaximumRefundCount)?;
let connector = payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("No connector populated in payment attempt")?;
let (connector_transaction_id, processor_transaction_data) =
ConnectorTransactionId::form_id_and_data(connector_transaction_id);
let refund_create_req = diesel_refund::RefundNew {
refund_id: refund_id.to_string(),
internal_reference_id: utils::generate_id(consts::ID_LENGTH, "refid"),
external_reference_id: Some(refund_id.clone()),
payment_id: req.payment_id,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
connector_transaction_id,
connector,
refund_type: req.refund_type.unwrap_or_default().foreign_into(),
total_amount: payment_attempt.get_total_amount(),
refund_amount,
currency,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
refund_status: enums::RefundStatus::Pending,
metadata: req.metadata,
description: req.reason.clone(),
attempt_id: payment_attempt.attempt_id.clone(),
refund_reason: req.reason,
profile_id: payment_intent.profile_id.clone(),
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
charges: None,
split_refunds: req.split_refunds,
connector_refund_id: None,
sent_to_gateway: Default::default(),
refund_arn: None,
updated_by: Default::default(),
organization_id: merchant_context
.get_merchant_account()
.organization_id
.clone(),
processor_transaction_data,
processor_refund_data: None,
};
let refund = match db
.insert_refund(
refund_create_req,
merchant_context.get_merchant_account().storage_scheme,
)
.await
{
Ok(refund) => {
Box::pin(schedule_refund_execution(
state,
refund.clone(),
refund_type,
merchant_context,
payment_attempt,
payment_intent,
creds_identifier,
split_refunds,
))
.await?
}
Err(err) => {
if err.current_context().is_db_unique_violation() {
Err(errors::ApiErrorResponse::DuplicateRefundRequest)?
} else {
return Err(err)
.change_context(errors::ApiErrorResponse::RefundNotFound)
.attach_printable("Inserting Refund failed");
}
}
};
let unified_translated_message = if let (Some(unified_code), Some(unified_message)) =
(refund.unified_code.clone(), refund.unified_message.clone())
{
helpers::get_unified_translation(
state,
unified_code,
unified_message.clone(),
state.locale.to_string(),
)
.await
.or(Some(unified_message))
} else {
refund.unified_message
};
let refund = diesel_refund::Refund {
unified_message: unified_translated_message,
..refund
};
Ok(refund.foreign_into())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 162,
"total_crates": null
} |
fn_clm_router_sync_refund_with_gateway_8360326204109888828 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/refunds
pub async fn sync_refund_with_gateway(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
refund: &diesel_refund::Refund,
creds_identifier: Option<String>,
split_refunds: Option<SplitRefundsRequest>,
) -> RouterResult<diesel_refund::Refund> {
let connector_id = refund.connector.to_string();
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_id,
api::GetToken::Connector,
payment_attempt.merchant_connector_id.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector")?;
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let currency = payment_attempt.currency.get_required_value("currency")?;
let mut router_data = core_utils::construct_refund_router_data::<api::RSync>(
state,
&connector_id,
merchant_context,
(payment_attempt.get_total_amount(), currency),
payment_intent,
payment_attempt,
refund,
creds_identifier.clone(),
split_refunds,
)
.await?;
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
merchant_context,
&router_data,
creds_identifier.as_deref(),
))
.await?;
logger::debug!(refund_retrieve_router_data=?router_data);
access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&payments::CallConnectorAction::Trigger,
);
let router_data_res = if !(add_access_token_result.connector_supports_access_token
&& router_data.access_token.is_none())
{
let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
api::RSync,
types::RefundsData,
types::RefundsResponseData,
> = connector.connector.get_connector_integration();
let mut refund_sync_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_refund_failed_response()?;
// Initiating connector integrity checks
let integrity_result = check_refund_integrity(
&refund_sync_router_data.request,
&refund_sync_router_data.response,
);
refund_sync_router_data.integrity_check = integrity_result;
refund_sync_router_data
} else {
router_data
};
let refund_update = match router_data_res.response {
Err(error_message) => {
let refund_status = match error_message.status_code {
// marking failure for 2xx because this is genuine refund failure
200..=299 => Some(enums::RefundStatus::Failure),
_ => None,
};
diesel_refund::RefundUpdate::ErrorUpdate {
refund_status,
refund_error_message: error_message.reason.or(Some(error_message.message)),
refund_error_code: Some(error_message.code),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
issuer_error_code: error_message.network_decline_code,
issuer_error_message: error_message.network_error_message,
}
}
Ok(response) => match router_data_res.integrity_check.clone() {
Err(err) => {
metrics::INTEGRITY_CHECK_FAILED.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
(
"merchant_id",
merchant_context.get_merchant_account().get_id().clone()
),
),
);
let (refund_connector_transaction_id, processor_refund_data) = err
.connector_transaction_id
.map_or((None, None), |refund_id| {
let (refund_id, refund_data) =
ConnectorTransactionId::form_id_and_data(refund_id);
(Some(refund_id), refund_data)
});
diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::ManualReview),
refund_error_message: Some(format!(
"Integrity Check Failed! as data mismatched for fields {}",
err.field_names
)),
refund_error_code: Some("IE".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: refund_connector_transaction_id,
processor_refund_data,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
}
}
Ok(()) => {
let (connector_refund_id, processor_refund_data) =
ConnectorTransactionId::form_id_and_data(response.connector_refund_id);
diesel_refund::RefundUpdate::Update {
connector_refund_id,
refund_status: response.refund_status,
sent_to_gateway: true,
refund_error_message: None,
refund_arn: "".to_string(),
updated_by: storage_scheme.to_string(),
processor_refund_data,
}
}
},
};
let response = state
.store
.update_refund(
refund.to_owned(),
refund_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)
.attach_printable_lazy(|| {
format!(
"Unable to update refund with refund_id: {}",
refund.refund_id
)
})?;
utils::trigger_refund_outgoing_webhook(
state,
merchant_context,
&response,
payment_attempt.profile_id.clone(),
)
.await
.map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error))
.ok();
Ok(response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 92,
"total_crates": null
} |
fn_clm_router_refund_retrieve_core_8360326204109888828 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/refunds
pub async fn refund_retrieve_core(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: Option<common_utils::id_type::ProfileId>,
request: refunds::RefundsRetrieveRequest,
refund: diesel_refund::Refund,
) -> RouterResult<diesel_refund::Refund> {
let db = &*state.store;
let merchant_id = merchant_context.get_merchant_account().get_id();
core_utils::validate_profile_id_from_auth_layer(profile_id, &refund)?;
let payment_id = &refund.payment_id;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&(&state).into(),
payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_attempt = db
.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
&refund.connector_transaction_id,
payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
let creds_identifier = request
.merchant_connector_details
.as_ref()
.map(|mcd| mcd.creds_identifier.to_owned());
request
.merchant_connector_details
.to_owned()
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(db, merchant_id, mcd).await
})
.await
.transpose()?;
let split_refunds_req = core_utils::get_split_refunds(SplitRefundInput {
split_payment_request: payment_intent.split_payments.clone(),
payment_charges: payment_attempt.charges.clone(),
charge_id: payment_attempt.charge_id.clone(),
refund_request: refund.split_refunds.clone(),
})?;
let unified_translated_message = if let (Some(unified_code), Some(unified_message)) =
(refund.unified_code.clone(), refund.unified_message.clone())
{
helpers::get_unified_translation(
&state,
unified_code,
unified_message.clone(),
state.locale.to_string(),
)
.await
.or(Some(unified_message))
} else {
refund.unified_message
};
let refund = diesel_refund::Refund {
unified_message: unified_translated_message,
..refund
};
let response = if should_call_refund(&refund, request.force_sync.unwrap_or(false)) {
Box::pin(sync_refund_with_gateway(
&state,
&merchant_context,
&payment_attempt,
&payment_intent,
&refund,
creds_identifier,
split_refunds_req,
))
.await
} else {
Ok(refund)
}?;
Ok(response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 85,
"total_crates": null
} |
fn_clm_router_upsert_conditional_config_-1422686602865801355 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/conditional_config
pub async fn upsert_conditional_config(
state: SessionState,
merchant_context: domain::MerchantContext,
request: DecisionManager,
) -> RouterResponse<DecisionManagerRecord> {
use common_utils::ext_traits::{Encode, OptionExt, ValueExt};
use diesel_models::configs;
use storage_impl::redis::cache;
use super::routing::helpers::update_merchant_active_algorithm_ref;
let db = state.store.as_ref();
let (name, prog) = match request {
DecisionManager::DecisionManagerv0(ccr) => {
let name = ccr.name;
let prog = ccr
.algorithm
.get_required_value("algorithm")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "algorithm",
})
.attach_printable("Algorithm for config not given")?;
(name, prog)
}
DecisionManager::DecisionManagerv1(dmr) => {
let name = dmr.name;
let prog = dmr
.program
.get_required_value("program")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "program",
})
.attach_printable("Program for config not given")?;
(name, prog)
}
};
let timestamp = common_utils::date_time::now_unix_timestamp();
let mut algo_id: api_models::routing::RoutingAlgorithmRef = merchant_context
.get_merchant_account()
.routing_algorithm
.clone()
.map(|val| val.parse_value("routing algorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode the routing algorithm")?
.unwrap_or_default();
let key = merchant_context
.get_merchant_account()
.get_id()
.get_payment_config_routing_id();
let read_config_key = db.find_config_by_key(&key).await;
euclid::frontend::ast::lowering::lower_program(prog.clone())
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid Request Data".to_string(),
})
.attach_printable("The Request has an Invalid Comparison")?;
match read_config_key {
Ok(config) => {
let previous_record: DecisionManagerRecord = config
.config
.parse_struct("DecisionManagerRecord")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The Payment Config Key Not Found")?;
let new_algo = DecisionManagerRecord {
name: previous_record.name,
program: prog,
modified_at: timestamp,
created_at: previous_record.created_at,
};
let serialize_updated_str = new_algo
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize config to string")?;
let updated_config = configs::ConfigUpdate::Update {
config: Some(serialize_updated_str),
};
db.update_config_by_key(&key, updated_config)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error serializing the config")?;
algo_id.update_conditional_config_id(key.clone());
let config_key = cache::CacheKind::DecisionManager(key.into());
update_merchant_active_algorithm_ref(
&state,
merchant_context.get_merchant_key_store(),
config_key,
algo_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref")?;
Ok(service_api::ApplicationResponse::Json(new_algo))
}
Err(e) if e.current_context().is_db_not_found() => {
let new_rec = DecisionManagerRecord {
name: name
.get_required_value("name")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "name",
})
.attach_printable("name of the config not found")?,
program: prog,
modified_at: timestamp,
created_at: timestamp,
};
let serialized_str = new_rec
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error serializing the config")?;
let new_config = configs::ConfigNew {
key: key.clone(),
config: serialized_str,
};
db.insert_config(new_config)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error fetching the config")?;
algo_id.update_conditional_config_id(key.clone());
let config_key = cache::CacheKind::DecisionManager(key.into());
update_merchant_active_algorithm_ref(
&state,
merchant_context.get_merchant_key_store(),
config_key,
algo_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref")?;
Ok(service_api::ApplicationResponse::Json(new_rec))
}
Err(e) => Err(e)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error fetching payment config"),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 145,
"total_crates": null
} |
fn_clm_router_delete_conditional_config_-1422686602865801355 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/conditional_config
pub async fn delete_conditional_config(
state: SessionState,
merchant_context: domain::MerchantContext,
) -> RouterResponse<()> {
use common_utils::ext_traits::ValueExt;
use storage_impl::redis::cache;
use super::routing::helpers::update_merchant_active_algorithm_ref;
let db = state.store.as_ref();
let key = merchant_context
.get_merchant_account()
.get_id()
.get_payment_config_routing_id();
let mut algo_id: api_models::routing::RoutingAlgorithmRef = merchant_context
.get_merchant_account()
.routing_algorithm
.clone()
.map(|value| value.parse_value("routing algorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode the conditional_config algorithm")?
.unwrap_or_default();
algo_id.config_algo_id = None;
let config_key = cache::CacheKind::DecisionManager(key.clone().into());
update_merchant_active_algorithm_ref(
&state,
merchant_context.get_merchant_key_store(),
config_key,
algo_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update deleted algorithm ref")?;
db.delete_config_by_key(&key)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to delete routing config from DB")?;
Ok(service_api::ApplicationResponse::StatusOk)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 57,
"total_crates": null
} |
fn_clm_router_retrieve_conditional_config_-1422686602865801355 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/conditional_config
pub async fn retrieve_conditional_config(
state: SessionState,
key_store: domain::MerchantKeyStore,
profile: domain::Profile,
) -> RouterResponse<common_types::payments::DecisionManagerResponse> {
let db = state.store.as_ref();
let key_manager_state: &KeyManagerState = &(&state).into();
let profile_id = profile.get_id();
let record = profile
.three_ds_decision_manager_config
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The Conditional Config Record was not found")?;
let response = common_types::payments::DecisionManagerRecord {
name: record.name,
program: record.program,
created_at: record.created_at,
};
Ok(service_api::ApplicationResponse::Json(response))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 27,
"total_crates": null
} |
fn_clm_router_make_payout_data_-6158198400024997648 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payouts
pub async fn make_payout_data(
state: &SessionState,
merchant_context: &domain::MerchantContext,
auth_profile_id: Option<id_type::ProfileId>,
req: &payouts::PayoutRequest,
locale: &str,
) -> RouterResult<PayoutData> {
let db = &*state.store;
let merchant_id = merchant_context.get_merchant_account().get_id();
let payout_id = match req {
payouts::PayoutRequest::PayoutActionRequest(r) => r.payout_id.clone(),
payouts::PayoutRequest::PayoutCreateRequest(r) => {
r.payout_id.clone().unwrap_or(id_type::PayoutId::generate())
}
payouts::PayoutRequest::PayoutRetrieveRequest(r) => r.payout_id.clone(),
};
let browser_info = match req {
payouts::PayoutRequest::PayoutActionRequest(_) => None,
payouts::PayoutRequest::PayoutCreateRequest(r) => r.browser_info.clone().map(Into::into),
payouts::PayoutRequest::PayoutRetrieveRequest(_) => None,
};
let payouts = db
.find_payout_by_merchant_id_payout_id(
merchant_id,
&payout_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
core_utils::validate_profile_id_from_auth_layer(auth_profile_id, &payouts)?;
let payout_attempt_id =
utils::get_payout_attempt_id(payouts.payout_id.get_string_repr(), payouts.attempt_count);
let mut payout_attempt = db
.find_payout_attempt_by_merchant_id_payout_attempt_id(
merchant_id,
&payout_attempt_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
let customer_id = payouts.customer_id.as_ref();
// We have to do this because the function that is being used to create / get address is from payments
// which expects a payment_id
let payout_id_as_payment_id_type = id_type::PaymentId::try_from(std::borrow::Cow::Owned(
payouts.payout_id.get_string_repr().to_string(),
))
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "payout_id contains invalid data".to_string(),
})
.attach_printable("Error converting payout_id to PaymentId type")?;
let billing_address = payment_helpers::create_or_find_address_for_payment_by_request(
state,
None,
payouts.address_id.as_deref(),
merchant_id,
customer_id,
merchant_context.get_merchant_key_store(),
&payout_id_as_payment_id_type,
merchant_context.get_merchant_account().storage_scheme,
)
.await?
.map(|addr| domain_models::address::Address::from(&addr));
let payout_id = &payouts.payout_id;
let customer_details = customer_id
.async_map(|customer_id| async move {
db.find_customer_optional_by_customer_id_merchant_id(
&state.into(),
customer_id,
merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.map_err(|err| err.change_context(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| {
format!(
"Failed while fetching optional customer [id - {customer_id:?}] for payout [id - {}]", payout_id.get_string_repr()
)
})
})
.await
.transpose()?
.and_then(|c| c);
let profile_id = payout_attempt.profile_id.clone();
// Validate whether profile_id passed in request is valid and is linked to the merchant
let business_profile = validate_and_get_business_profile(
state,
merchant_context.get_merchant_key_store(),
&profile_id,
merchant_id,
)
.await?;
let payout_method_data_req = match req {
payouts::PayoutRequest::PayoutCreateRequest(r) => r.payout_method_data.to_owned(),
payouts::PayoutRequest::PayoutActionRequest(_) => {
match payout_attempt.payout_token.to_owned() {
Some(payout_token) => {
let customer_id = customer_details
.as_ref()
.map(|cd| cd.customer_id.to_owned())
.get_required_value("customer_id when payout_token is sent")?;
helpers::make_payout_method_data(
state,
None,
Some(&payout_token),
&customer_id,
merchant_context.get_merchant_account().get_id(),
payouts.payout_type,
merchant_context.get_merchant_key_store(),
None,
merchant_context.get_merchant_account().storage_scheme,
)
.await?
}
None => None,
}
}
payouts::PayoutRequest::PayoutRetrieveRequest(_) => None,
};
if let Some(payout_method_data) = payout_method_data_req.clone() {
let additional_payout_method_data =
helpers::get_additional_payout_data(&payout_method_data, &*state.store, &profile_id)
.await;
let update_additional_payout_method_data =
storage::PayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate {
additional_payout_method_data,
};
payout_attempt = db
.update_payout_attempt(
&payout_attempt,
update_additional_payout_method_data,
&payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating additional payout method data in payout_attempt")?;
};
let merchant_connector_account =
if payout_attempt.connector.is_some() && payout_attempt.merchant_connector_id.is_some() {
let connector_name = payout_attempt
.connector
.clone()
.get_required_value("connector_name")?;
Some(
payment_helpers::get_merchant_connector_account(
state,
merchant_context.get_merchant_account().get_id(),
None,
merchant_context.get_merchant_key_store(),
&profile_id,
connector_name.as_str(),
payout_attempt.merchant_connector_id.as_ref(),
)
.await?,
)
} else {
None
};
let payout_link = payouts
.payout_link_id
.clone()
.async_map(|link_id| async move {
db.find_payout_link_by_link_id(&link_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error fetching payout links from db")
})
.await
.transpose()?;
let payment_method = payouts
.payout_method_id
.clone()
.async_map(|pm_id| async move {
db.find_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
&pm_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")
})
.await
.transpose()?;
Ok(PayoutData {
billing_address,
business_profile,
customer_details,
payouts,
payout_attempt,
payout_method_data: payout_method_data_req.to_owned(),
merchant_connector_account,
should_terminate: false,
profile_id,
payout_link,
current_locale: locale.to_string(),
payment_method,
connector_transfer_method_id: None,
browser_info,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 212,
"total_crates": null
} |
fn_clm_router_payout_create_db_entries_-6158198400024997648 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payouts
pub async fn payout_create_db_entries(
state: &SessionState,
merchant_context: &domain::MerchantContext,
req: &payouts::PayoutCreateRequest,
payout_id: &id_type::PayoutId,
profile_id: &id_type::ProfileId,
stored_payout_method_data: Option<&payouts::PayoutMethodData>,
locale: &str,
customer: Option<&domain::Customer>,
payment_method: Option<PaymentMethod>,
) -> RouterResult<PayoutData> {
let db = &*state.store;
let merchant_id = merchant_context.get_merchant_account().get_id();
let customer_id = customer.map(|cust| cust.customer_id.clone());
// Validate whether profile_id passed in request is valid and is linked to the merchant
let business_profile = validate_and_get_business_profile(
state,
merchant_context.get_merchant_key_store(),
profile_id,
merchant_id,
)
.await?;
let payout_link = match req.payout_link {
Some(true) => Some(
create_payout_link(
state,
&business_profile,
&customer_id
.clone()
.get_required_value("customer.id when payout_link is true")?,
merchant_id,
req,
payout_id,
locale,
)
.await?,
),
_ => None,
};
// Get or create billing address
let (billing_address, address_id) = helpers::resolve_billing_address_for_payout(
state,
req.billing.as_ref(),
None,
payment_method.as_ref(),
merchant_context,
customer_id.as_ref(),
payout_id,
)
.await?;
// Make payouts entry
let currency = req.currency.to_owned().get_required_value("currency")?;
let (payout_method_id, payout_type) = match stored_payout_method_data {
Some(payout_method_data) => (
payment_method
.as_ref()
.map(|pm| pm.payment_method_id.clone()),
Some(api_enums::PayoutType::foreign_from(payout_method_data)),
),
None => {
(
payment_method
.as_ref()
.map(|pm| pm.payment_method_id.clone()),
match req.payout_type {
None => payment_method
.as_ref()
.and_then(|pm| pm.payment_method)
.map(|payment_method_enum| {
api_enums::PayoutType::foreign_try_from(payment_method_enum)
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"PaymentMethod {payment_method_enum:?} is not supported for payouts"
),
})
.attach_printable("Failed to convert PaymentMethod to PayoutType")
})
.transpose()?,
payout_type => payout_type,
},
)
}
};
let client_secret = utils::generate_id(
consts::ID_LENGTH,
format!("payout_{}_secret", payout_id.get_string_repr()).as_str(),
);
let amount = MinorUnit::from(req.amount.unwrap_or(api::Amount::Zero));
let status = if req.payout_method_data.is_some()
|| req.payout_token.is_some()
|| stored_payout_method_data.is_some()
{
match req.confirm {
Some(true) => storage_enums::PayoutStatus::RequiresCreation,
_ => storage_enums::PayoutStatus::RequiresConfirmation,
}
} else {
storage_enums::PayoutStatus::RequiresPayoutMethodData
};
let payouts_req = storage::PayoutsNew {
payout_id: payout_id.clone(),
merchant_id: merchant_id.to_owned(),
customer_id: customer_id.to_owned(),
address_id: address_id.to_owned(),
payout_type,
amount,
destination_currency: currency,
source_currency: currency,
description: req.description.to_owned(),
recurring: req.recurring.unwrap_or(false),
auto_fulfill: req.auto_fulfill.unwrap_or(false),
return_url: req.return_url.to_owned(),
entity_type: req.entity_type.unwrap_or_default(),
payout_method_id,
profile_id: profile_id.to_owned(),
attempt_count: 1,
metadata: req.metadata.clone(),
confirm: req.confirm,
payout_link_id: payout_link
.clone()
.map(|link_data| link_data.link_id.clone()),
client_secret: Some(client_secret),
priority: req.priority,
status,
created_at: common_utils::date_time::now(),
last_modified_at: common_utils::date_time::now(),
};
let payouts = db
.insert_payout(
payouts_req,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayout {
payout_id: payout_id.clone(),
})
.attach_printable("Error inserting payouts in db")?;
// Make payout_attempt entry
let payout_attempt_id = utils::get_payout_attempt_id(payout_id.get_string_repr(), 1);
let additional_pm_data_value = req
.payout_method_data
.clone()
.or(stored_payout_method_data.cloned())
.async_and_then(|payout_method_data| async move {
helpers::get_additional_payout_data(&payout_method_data, &*state.store, profile_id)
.await
})
.await
// If no payout method data in request but we have a stored payment method, populate from it
.or_else(|| {
payment_method.as_ref().and_then(|payment_method| {
payment_method
.get_payment_methods_data()
.and_then(|pmd| pmd.get_additional_payout_method_data())
})
});
let payout_attempt_req = storage::PayoutAttemptNew {
payout_attempt_id: payout_attempt_id.to_string(),
payout_id: payout_id.clone(),
additional_payout_method_data: additional_pm_data_value,
merchant_id: merchant_id.to_owned(),
merchant_order_reference_id: req.merchant_order_reference_id.clone(),
status,
business_country: req.business_country.to_owned(),
business_label: req.business_label.to_owned(),
payout_token: req.payout_token.to_owned(),
profile_id: profile_id.to_owned(),
customer_id,
address_id,
connector: None,
connector_payout_id: None,
is_eligible: None,
error_message: None,
error_code: None,
created_at: common_utils::date_time::now(),
last_modified_at: common_utils::date_time::now(),
merchant_connector_id: None,
routing_info: None,
unified_code: None,
unified_message: None,
payout_connector_metadata: None,
};
let payout_attempt = db
.insert_payout_attempt(
payout_attempt_req,
&payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayout {
payout_id: payout_id.clone(),
})
.attach_printable("Error inserting payout_attempt in db")?;
// Make PayoutData
Ok(PayoutData {
billing_address,
business_profile,
customer_details: customer.map(ToOwned::to_owned),
merchant_connector_account: None,
payouts,
payout_attempt,
payout_method_data: req
.payout_method_data
.as_ref()
.cloned()
.or(stored_payout_method_data.cloned()),
should_terminate: false,
profile_id: profile_id.to_owned(),
payout_link,
current_locale: locale.to_string(),
payment_method,
connector_transfer_method_id: None,
browser_info: req.browser_info.clone().map(Into::into),
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 201,
"total_crates": null
} |
fn_clm_router_create_payout_link_-6158198400024997648 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payouts
pub async fn create_payout_link(
state: &SessionState,
business_profile: &domain::Profile,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
req: &payouts::PayoutCreateRequest,
payout_id: &id_type::PayoutId,
locale: &str,
) -> RouterResult<PayoutLink> {
let payout_link_config_req = req.payout_link_config.to_owned();
// Fetch all configs
let default_config = &state.conf.generic_link.payout_link;
let profile_config = &business_profile.payout_link_config;
let profile_ui_config = profile_config.as_ref().map(|c| c.config.ui_config.clone());
let ui_config = payout_link_config_req
.as_ref()
.and_then(|config| config.ui_config.clone())
.or(profile_ui_config);
let test_mode_in_config = payout_link_config_req
.as_ref()
.and_then(|config| config.test_mode)
.or_else(|| profile_config.as_ref().and_then(|c| c.payout_test_mode));
let is_test_mode_enabled = test_mode_in_config.unwrap_or(false);
let allowed_domains = match (router_env::which(), is_test_mode_enabled) {
// Throw error in case test_mode was enabled in production
(Env::Production, true) => Err(report!(errors::ApiErrorResponse::LinkConfigurationError {
message: "test_mode cannot be true for creating payout_links in production".to_string()
})),
// Send empty set of whitelisted domains
(_, true) => {
Ok(HashSet::new())
},
// Otherwise, fetch and use allowed domains from profile config
(_, false) => {
profile_config
.as_ref()
.map(|config| config.config.allowed_domains.to_owned())
.get_required_value("allowed_domains")
.change_context(errors::ApiErrorResponse::LinkConfigurationError {
message:
"Payout links cannot be used without setting allowed_domains in profile. If you're using a non-production environment, you can set test_mode to true while in payout_link_config"
.to_string(),
})
}
}?;
// Form data to be injected in the link
let (logo, merchant_name, theme) = match ui_config {
Some(config) => (config.logo, config.merchant_name, config.theme),
_ => (None, None, None),
};
let payout_link_config = GenericLinkUiConfig {
logo,
merchant_name,
theme,
};
let client_secret = utils::generate_id(consts::ID_LENGTH, "payout_link_secret");
let base_url = profile_config
.as_ref()
.and_then(|c| c.config.domain_name.as_ref())
.map(|domain| format!("https://{domain}"))
.unwrap_or(state.base_url.clone());
let session_expiry = req
.session_expiry
.as_ref()
.map_or(default_config.expiry, |expiry| *expiry);
let url = format!(
"{base_url}/payout_link/{}/{}?locale={}",
merchant_id.get_string_repr(),
payout_id.get_string_repr(),
locale
);
let link = url::Url::parse(&url)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Failed to form payout link URL - {url}"))?;
let req_enabled_payment_methods = payout_link_config_req
.as_ref()
.and_then(|req| req.enabled_payment_methods.to_owned());
let amount = req
.amount
.as_ref()
.get_required_value("amount")
.attach_printable("amount is a required value when creating payout links")?;
let currency = req
.currency
.as_ref()
.get_required_value("currency")
.attach_printable("currency is a required value when creating payout links")?;
let payout_link_id = core_utils::get_or_generate_id(
"payout_link_id",
&payout_link_config_req
.as_ref()
.and_then(|config| config.payout_link_id.clone()),
"payout_link",
)?;
let form_layout = payout_link_config_req
.as_ref()
.and_then(|config| config.form_layout.to_owned())
.or_else(|| {
profile_config
.as_ref()
.and_then(|config| config.form_layout.to_owned())
});
let data = PayoutLinkData {
payout_link_id: payout_link_id.clone(),
customer_id: customer_id.clone(),
payout_id: payout_id.clone(),
link,
client_secret: Secret::new(client_secret),
session_expiry,
ui_config: payout_link_config,
enabled_payment_methods: req_enabled_payment_methods,
amount: MinorUnit::from(*amount),
currency: *currency,
allowed_domains,
form_layout,
test_mode: test_mode_in_config,
};
create_payout_link_db_entry(state, merchant_id, &data, req.return_url.clone()).await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 135,
"total_crates": null
} |
fn_clm_router_response_handler_-6158198400024997648 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payouts
pub async fn response_handler(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payout_data: &PayoutData,
) -> RouterResult<payouts::PayoutCreateResponse> {
let payout_attempt = payout_data.payout_attempt.to_owned();
let payouts = payout_data.payouts.to_owned();
let payout_method_id: Option<String> = payout_data.payment_method.as_ref().map(|pm| {
#[cfg(feature = "v1")]
{
pm.payment_method_id.clone()
}
#[cfg(feature = "v2")]
{
pm.id.clone().get_string_repr().to_string()
}
});
let payout_link = payout_data.payout_link.to_owned();
let billing_address = payout_data.billing_address.to_owned();
let customer_details = payout_data.customer_details.to_owned();
let customer_id = payouts.customer_id;
let billing = billing_address.map(From::from);
let translated_unified_message = helpers::get_translated_unified_code_and_message(
state,
payout_attempt.unified_code.as_ref(),
payout_attempt.unified_message.as_ref(),
&payout_data.current_locale,
)
.await?;
let additional_payout_method_data = payout_attempt.additional_payout_method_data.clone();
let payout_method_data =
additional_payout_method_data.map(payouts::PayoutMethodDataResponse::from);
let response = api::PayoutCreateResponse {
payout_id: payouts.payout_id.to_owned(),
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
merchant_order_reference_id: payout_attempt.merchant_order_reference_id.clone(),
amount: payouts.amount,
currency: payouts.destination_currency.to_owned(),
connector: payout_attempt.connector,
payout_type: payouts.payout_type.to_owned(),
payout_method_data,
billing,
auto_fulfill: payouts.auto_fulfill,
customer_id,
email: customer_details.as_ref().and_then(|c| c.email.clone()),
name: customer_details.as_ref().and_then(|c| c.name.clone()),
phone: customer_details.as_ref().and_then(|c| c.phone.clone()),
phone_country_code: customer_details
.as_ref()
.and_then(|c| c.phone_country_code.clone()),
customer: customer_details
.as_ref()
.map(payment_api_types::CustomerDetailsResponse::foreign_from),
client_secret: payouts.client_secret.to_owned(),
return_url: payouts.return_url.to_owned(),
business_country: payout_attempt.business_country,
business_label: payout_attempt.business_label,
description: payouts.description.to_owned(),
entity_type: payouts.entity_type.to_owned(),
recurring: payouts.recurring,
metadata: payouts.metadata,
merchant_connector_id: payout_attempt.merchant_connector_id.to_owned(),
status: payout_attempt.status.to_owned(),
error_message: payout_attempt.error_message.to_owned(),
error_code: payout_attempt.error_code,
profile_id: payout_attempt.profile_id,
created: Some(payouts.created_at),
connector_transaction_id: payout_attempt.connector_payout_id,
priority: payouts.priority,
attempts: None,
unified_code: payout_attempt.unified_code,
unified_message: translated_unified_message,
payout_link: payout_link
.map(|payout_link| {
url::Url::parse(payout_link.url.peek()).map(|link| PayoutLinkResponse {
payout_link_id: payout_link.link_id,
link: link.into(),
})
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse payout link's URL")?,
payout_method_id,
};
Ok(response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 131,
"total_crates": null
} |
fn_clm_router_payouts_filtered_list_core_-6158198400024997648 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payouts
pub async fn payouts_filtered_list_core(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id_list: Option<Vec<id_type::ProfileId>>,
filters: payouts::PayoutListFilterConstraints,
) -> RouterResponse<payouts::PayoutListResponse> {
let limit = &filters.limit;
validator::validate_payout_list_request_for_joins(*limit)?;
let db = state.store.as_ref();
let constraints = filters.clone().into();
let list: Vec<(
storage::Payouts,
storage::PayoutAttempt,
Option<diesel_models::Customer>,
Option<diesel_models::Address>,
)> = db
.filter_payouts_and_attempts(
merchant_context.get_merchant_account().get_id(),
&constraints,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
let list = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, list);
let data: Vec<api::PayoutCreateResponse> =
join_all(list.into_iter().map(|(p, pa, customer, address)| async {
let customer: Option<domain::Customer> = customer
.async_and_then(|cust| async {
domain::Customer::convert_back(
&(&state).into(),
cust,
&(merchant_context.get_merchant_key_store().clone()).key,
merchant_context
.get_merchant_key_store()
.merchant_id
.clone()
.into(),
)
.await
.map_err(|err| {
let msg = format!("failed to convert customer for id: {:?}", p.customer_id);
logger::warn!(?err, msg);
})
.ok()
})
.await;
let payout_addr: Option<payment_enums::Address> = address
.async_and_then(|addr| async {
domain::Address::convert_back(
&(&state).into(),
addr,
&(merchant_context.get_merchant_key_store().clone()).key,
merchant_context
.get_merchant_key_store()
.merchant_id
.clone()
.into(),
)
.await
.map(ForeignFrom::foreign_from)
.map_err(|err| {
let msg = format!("failed to convert address for id: {:?}", p.address_id);
logger::warn!(?err, msg);
})
.ok()
})
.await;
Some((p, pa, customer, payout_addr))
}))
.await
.into_iter()
.flatten()
.map(ForeignFrom::foreign_from)
.collect();
let active_payout_ids = db
.filter_active_payout_ids_by_constraints(
merchant_context.get_merchant_account().get_id(),
&constraints,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to filter active payout ids based on the constraints")?;
let total_count = db
.get_total_count_of_filtered_payouts(
merchant_context.get_merchant_account().get_id(),
&active_payout_ids,
filters.connector.clone(),
filters.currency.clone(),
filters.status.clone(),
filters.payout_method.clone(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed to fetch total count of filtered payouts for the given constraints - {filters:?}",
)
})?;
Ok(services::ApplicationResponse::Json(
api::PayoutListResponse {
size: data.len(),
data,
total_count: Some(total_count),
},
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 124,
"total_crates": null
} |
fn_clm_router_foreign_try_from_7030528573717545102 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/refunds_v2
// Implementation of api::RefundResponse for ForeignTryFrom<diesel_refund::Refund>
fn foreign_try_from(refund: diesel_refund::Refund) -> Result<Self, Self::Error> {
let refund = refund;
let profile_id = refund
.profile_id
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Profile id not found")?;
let connector_name = refund.connector;
let connector = Connector::from_str(&connector_name)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| {
format!("unable to parse connector name {connector_name:?}")
})?;
Ok(Self {
payment_id: refund.payment_id,
id: refund.id.clone(),
amount: refund.refund_amount,
currency: refund.currency,
reason: refund.refund_reason,
status: refunds::RefundStatus::foreign_from(refund.refund_status),
profile_id,
metadata: refund.metadata,
created_at: refund.created_at,
updated_at: refund.modified_at,
connector,
merchant_connector_id: refund.connector_id,
merchant_reference_id: Some(refund.merchant_reference_id),
error_details: Some(RefundErrorDetails {
code: refund.refund_error_code.unwrap_or_default(),
message: refund.refund_error_message.unwrap_or_default(),
}),
connector_refund_reference_id: None,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 450,
"total_crates": null
} |
fn_clm_router_foreign_from_7030528573717545102 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/refunds_v2
// Implementation of Option<diesel_refund::RefundUpdate> for ForeignFrom<(&errors::ConnectorError, enums::MerchantStorageScheme)>
fn foreign_from(
(from, storage_scheme): (&errors::ConnectorError, enums::MerchantStorageScheme),
) -> Self {
match from {
errors::ConnectorError::NotImplemented(message) => {
Some(diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: Some(
errors::ConnectorError::NotImplemented(message.to_owned()).to_string(),
),
refund_error_code: Some("NOT_IMPLEMENTED".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
})
}
errors::ConnectorError::NotSupported { message, connector } => {
Some(diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: Some(format!(
"{message} is not supported by {connector}"
)),
refund_error_code: Some("NOT_SUPPORTED".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
})
}
_ => None,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 226,
"total_crates": null
} |
fn_clm_router_validate_and_create_refund_7030528573717545102 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/refunds_v2
pub async fn validate_and_create_refund(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
refund_amount: common_utils_types::MinorUnit,
req: refunds::RefundsCreateRequest,
global_refund_id: id_type::GlobalRefundId,
merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>,
) -> errors::RouterResult<refunds::RefundResponse> {
let db = &*state.store;
let refund_type = req.refund_type.unwrap_or_default();
let merchant_reference_id = req.merchant_reference_id;
let predicate = req
.merchant_id
.as_ref()
.map(|merchant_id| merchant_id != merchant_context.get_merchant_account().get_id());
utils::when(predicate.unwrap_or(false), || {
Err(report!(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string()
})
.attach_printable("invalid merchant_id in request"))
})?;
let connector_payment_id = payment_attempt.clone().connector_payment_id.ok_or_else(|| {
report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Transaction in invalid. Missing field \"connector_transaction_id\" in payment_attempt.")
})?;
let all_refunds = db
.find_refund_by_merchant_id_connector_transaction_id(
merchant_context.get_merchant_account().get_id(),
&connector_payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let currency = payment_intent.amount_details.currency;
refunds_validator::validate_payment_order_age(
&payment_intent.created_at,
state.conf.refund.max_age,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "created_at".to_string(),
expected_format: format!(
"created_at not older than {} days",
state.conf.refund.max_age,
),
})?;
let total_amount_captured = payment_intent
.amount_captured
.unwrap_or(payment_attempt.get_total_amount());
refunds_validator::validate_refund_amount(
total_amount_captured.get_amount_as_i64(),
&all_refunds,
refund_amount.get_amount_as_i64(),
)
.change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?;
refunds_validator::validate_maximum_refund_against_payment_attempt(
&all_refunds,
state.conf.refund.max_attempts,
)
.change_context(errors::ApiErrorResponse::MaximumRefundCount)?;
let connector = payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("No connector populated in payment attempt")?;
let (connector_transaction_id, processor_transaction_data) =
common_utils_types::ConnectorTransactionId::form_id_and_data(connector_payment_id);
let refund_create_req = diesel_refund::RefundNew {
id: global_refund_id,
merchant_reference_id: merchant_reference_id.clone(),
external_reference_id: Some(merchant_reference_id.get_string_repr().to_string()),
payment_id: req.payment_id,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
connector_transaction_id,
connector,
refund_type: enums::RefundType::foreign_from(req.refund_type.unwrap_or_default()),
total_amount: payment_attempt.get_total_amount(),
refund_amount,
currency,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
refund_status: enums::RefundStatus::Pending,
metadata: req.metadata,
description: req.reason.clone(),
attempt_id: payment_attempt.id.clone(),
refund_reason: req.reason,
profile_id: Some(payment_intent.profile_id.clone()),
connector_id: payment_attempt.merchant_connector_id.clone(),
charges: None,
split_refunds: None,
connector_refund_id: None,
sent_to_gateway: Default::default(),
refund_arn: None,
updated_by: Default::default(),
organization_id: merchant_context
.get_merchant_account()
.organization_id
.clone(),
processor_transaction_data,
processor_refund_data: None,
};
let refund = match db
.insert_refund(
refund_create_req,
merchant_context.get_merchant_account().storage_scheme,
)
.await
{
Ok(refund) => {
Box::pin(schedule_refund_execution(
state,
refund.clone(),
refund_type,
merchant_context,
payment_attempt,
payment_intent,
merchant_connector_details,
))
.await?
}
Err(err) => {
if err.current_context().is_db_unique_violation() {
Err(errors::ApiErrorResponse::DuplicateRefundRequest)?
} else {
Err(err)
.change_context(errors::ApiErrorResponse::RefundFailed { data: None })
.attach_printable("Failed to insert refund")?
}
}
};
let unified_translated_message =
match (refund.unified_code.clone(), refund.unified_message.clone()) {
(Some(unified_code), Some(unified_message)) => helpers::get_unified_translation(
state,
unified_code,
unified_message.clone(),
state.locale.to_string(),
)
.await
.or(Some(unified_message)),
_ => refund.unified_message,
};
let refund = diesel_refund::Refund {
unified_message: unified_translated_message,
..refund
};
api::RefundResponse::foreign_try_from(refund)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 148,
"total_crates": null
} |
fn_clm_router_trigger_refund_to_gateway_7030528573717545102 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/refunds_v2
pub async fn trigger_refund_to_gateway(
state: &SessionState,
refund: &diesel_refund::Refund,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
) -> errors::RouterResult<diesel_refund::Refund> {
let db = &*state.store;
let mca_id = payment_attempt.get_attempt_merchant_connector_account_id()?;
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let mca = db
.find_merchant_connector_account_by_id(
&state.into(),
&mca_id,
merchant_context.get_merchant_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch merchant connector account")?;
metrics::REFUND_COUNT.add(
1,
router_env::metric_attributes!(("connector", mca_id.get_string_repr().to_string())),
);
let connector_enum = mca.connector_name;
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_enum.to_string(),
api::GetToken::Connector,
Some(mca_id.clone()),
)?;
refunds_validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?;
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(mca));
let mut router_data = core_utils::construct_refund_router_data(
state,
connector_enum,
merchant_context,
payment_intent,
payment_attempt,
refund,
&merchant_connector_account,
)
.await?;
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
merchant_context,
&router_data,
None,
))
.await?;
logger::debug!(refund_router_data=?router_data);
access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&payments::CallConnectorAction::Trigger,
);
let connector_response = Box::pin(call_connector_service(
state,
&connector,
add_access_token_result,
router_data,
))
.await;
let refund_update = get_refund_update_object(
state,
&connector,
&storage_scheme,
merchant_context,
&connector_response,
)
.await;
let response = match refund_update {
Some(refund_update) => state
.store
.update_refund(
refund.to_owned(),
refund_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while updating refund: refund_id: {}",
refund.id.get_string_repr()
)
})?,
None => refund.to_owned(),
};
// Implement outgoing webhooks here
connector_response.to_refund_failed_response()?;
Ok(response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 75,
"total_crates": null
} |
fn_clm_router_refund_retrieve_core_7030528573717545102 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/refunds_v2
pub async fn refund_retrieve_core(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: Option<id_type::ProfileId>,
request: refunds::RefundsRetrieveRequest,
refund: diesel_refund::Refund,
) -> errors::RouterResult<diesel_refund::Refund> {
let db = &*state.store;
let key_manager_state = &(&state).into();
core_utils::validate_profile_id_from_auth_layer(profile_id, &refund)?;
let payment_id = &refund.payment_id;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let active_attempt_id = payment_intent
.active_attempt_id
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Active attempt id not found")?;
let payment_attempt = db
.find_payment_attempt_by_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
&active_attempt_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
let unified_translated_message = if let (Some(unified_code), Some(unified_message)) =
(refund.unified_code.clone(), refund.unified_message.clone())
{
helpers::get_unified_translation(
&state,
unified_code,
unified_message.clone(),
state.locale.to_string(),
)
.await
.or(Some(unified_message))
} else {
refund.unified_message
};
let refund = diesel_refund::Refund {
unified_message: unified_translated_message,
..refund
};
let response = if should_call_refund(&refund, request.force_sync.unwrap_or(false)) {
if state.conf.merchant_id_auth.merchant_id_auth_enabled {
let merchant_connector_details = match request.merchant_connector_details {
Some(details) => details,
None => {
return Err(report!(errors::ApiErrorResponse::MissingRequiredField {
field_name: "merchant_connector_details"
}));
}
};
Box::pin(internal_sync_refund_with_gateway(
&state,
&merchant_context,
&payment_attempt,
&payment_intent,
&refund,
merchant_connector_details,
))
.await
} else {
Box::pin(sync_refund_with_gateway(
&state,
&merchant_context,
&payment_attempt,
&payment_intent,
&refund,
))
.await
}
} else {
Ok(refund)
}?;
Ok(response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 69,
"total_crates": null
} |
fn_clm_router_from_3068557274743282806 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/fraud_check
// Implementation of PaymentDetails for From<PaymentToFrmData>
fn from(payment_data: PaymentToFrmData) -> Self {
Self {
amount: common_utils::types::MinorUnit::from(payment_data.amount).get_amount_as_i64(),
currency: payment_data.payment_attempt.currency,
payment_method: payment_data.payment_attempt.payment_method,
payment_method_type: payment_data.payment_attempt.payment_method_type,
refund_transaction_id: None,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2604,
"total_crates": null
} |
fn_clm_router_should_call_frm_3068557274743282806 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/fraud_check
pub async fn should_call_frm<F, D>(
merchant_context: &domain::MerchantContext,
payment_data: &D,
state: &SessionState,
) -> RouterResult<(
bool,
Option<FrmRoutingAlgorithm>,
Option<common_utils::id_type::ProfileId>,
Option<FrmConfigsObject>,
)>
where
F: Send + Clone,
D: payments::OperationSessionGetters<F> + Send + Sync + Clone,
{
use common_utils::ext_traits::OptionExt;
use masking::ExposeInterface;
let db = &*state.store;
match merchant_context
.get_merchant_account()
.frm_routing_algorithm
.clone()
{
Some(frm_routing_algorithm_value) => {
let frm_routing_algorithm_struct: FrmRoutingAlgorithm = frm_routing_algorithm_value
.clone()
.parse_value("FrmRoutingAlgorithm")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "frm_routing_algorithm",
})
.attach_printable("Data field not found in frm_routing_algorithm")?;
let profile_id = payment_data
.get_payment_intent()
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?
.clone();
#[cfg(feature = "v1")]
let merchant_connector_account_from_db_option = db
.find_merchant_connector_account_by_profile_id_connector_name(
&state.into(),
&profile_id,
&frm_routing_algorithm_struct.data,
merchant_context.get_merchant_key_store(),
)
.await
.map_err(|error| {
logger::error!(
"{:?}",
error.change_context(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_context
.get_merchant_account()
.get_id()
.get_string_repr()
.to_owned(),
}
)
)
})
.ok();
let enabled_merchant_connector_account_from_db_option =
merchant_connector_account_from_db_option.and_then(|mca| {
if mca.disabled.unwrap_or(false) {
logger::info!("No eligible connector found for FRM");
None
} else {
Some(mca)
}
});
#[cfg(feature = "v2")]
let merchant_connector_account_from_db_option: Option<
domain::MerchantConnectorAccount,
> = {
let _ = key_store;
let _ = frm_routing_algorithm_struct;
let _ = profile_id;
todo!()
};
match enabled_merchant_connector_account_from_db_option {
Some(merchant_connector_account_from_db) => {
let frm_configs_option = merchant_connector_account_from_db
.frm_configs
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "frm_configs",
})
.ok();
match frm_configs_option {
Some(frm_configs_value) => {
let frm_configs_struct: Vec<api_models::admin::FrmConfigs> = frm_configs_value
.into_iter()
.map(|config| { config
.expose()
.parse_value("FrmConfigs")
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "frm_configs".to_string(),
expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","flow": "post"}]}]"#.to_string(),
})
})
.collect::<Result<Vec<_>, _>>()?;
let mut is_frm_connector_enabled = false;
let mut is_frm_pm_enabled = false;
let connector = payment_data.get_payment_attempt().connector.clone();
let filtered_frm_config = frm_configs_struct
.iter()
.filter(|frm_config| match (&connector, &frm_config.gateway) {
(Some(current_connector), Some(configured_connector)) => {
let is_enabled =
*current_connector == configured_connector.to_string();
if is_enabled {
is_frm_connector_enabled = true;
}
is_enabled
}
(None, _) | (_, None) => true,
})
.collect::<Vec<_>>();
let filtered_payment_methods = filtered_frm_config
.iter()
.map(|frm_config| {
let filtered_frm_config_by_pm = frm_config
.payment_methods
.iter()
.filter(|frm_config_pm| {
match (
payment_data.get_payment_attempt().payment_method,
frm_config_pm.payment_method,
) {
(
Some(current_pm),
Some(configured_connector_pm),
) => {
let is_enabled = current_pm.to_string()
== configured_connector_pm.to_string();
if is_enabled {
is_frm_pm_enabled = true;
}
is_enabled
}
(None, _) | (_, None) => true,
}
})
.collect::<Vec<_>>();
filtered_frm_config_by_pm
})
.collect::<Vec<_>>()
.concat();
let is_frm_enabled = is_frm_connector_enabled && is_frm_pm_enabled;
logger::debug!(
"is_frm_connector_enabled {:?}, is_frm_pm_enabled: {:?}, is_frm_enabled :{:?}",
is_frm_connector_enabled,
is_frm_pm_enabled,
is_frm_enabled
);
// filtered_frm_config...
// Panic Safety: we are first checking if the object is present... only if present, we try to fetch index 0
let frm_configs_object = FrmConfigsObject {
frm_enabled_gateway: filtered_frm_config
.first()
.and_then(|c| c.gateway),
frm_enabled_pm: filtered_payment_methods
.first()
.and_then(|pm| pm.payment_method),
// flow type should be consumed from payment_method.flow. To provide backward compatibility, if we don't find it there, we consume it from payment_method.payment_method_types[0].flow_type.
frm_preferred_flow_type: filtered_payment_methods
.first()
.and_then(|pm| pm.flow.clone())
.or(filtered_payment_methods.first().and_then(|pm| {
pm.payment_method_types.as_ref().and_then(|pmt| {
pmt.first().map(|pmts| pmts.flow.clone())
})
}))
.ok_or(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "frm_configs".to_string(),
expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","flow": "post"}]}]"#.to_string(),
})?,
};
logger::debug!(
"frm_routing_configs: {:?} {:?} {:?} {:?}",
frm_routing_algorithm_struct,
profile_id,
frm_configs_object,
is_frm_enabled
);
Ok((
is_frm_enabled,
Some(frm_routing_algorithm_struct),
Some(profile_id),
Some(frm_configs_object),
))
}
None => {
logger::error!("Cannot find frm_configs for FRM provider");
Ok((false, None, None, None))
}
}
}
None => {
logger::error!("Cannot find merchant connector account for FRM provider");
Ok((false, None, None, None))
}
}
}
_ => Ok((false, None, None, None)),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 131,
"total_crates": null
} |
fn_clm_router_make_frm_data_and_fraud_check_operation_3068557274743282806 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/fraud_check
pub async fn make_frm_data_and_fraud_check_operation<F, D>(
_db: &dyn StorageInterface,
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_data: D,
frm_routing_algorithm: FrmRoutingAlgorithm,
profile_id: common_utils::id_type::ProfileId,
frm_configs: FrmConfigsObject,
_customer: &Option<domain::Customer>,
) -> RouterResult<FrmInfo<F, D>>
where
F: Send + Clone,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
let order_details = payment_data
.get_payment_intent()
.order_details
.clone()
.or_else(||
// when the order_details are present within the meta_data, we need to take those to support backward compatibility
payment_data.get_payment_intent().metadata.clone().and_then(|meta| {
let order_details = meta.get("order_details").to_owned();
order_details.map(|order| vec![masking::Secret::new(order.to_owned())])
}))
.map(|order_details_value| {
order_details_value
.into_iter()
.map(|data| {
data.peek()
.to_owned()
.parse_value("OrderDetailsWithAmount")
.attach_printable("unable to parse OrderDetailsWithAmount")
})
.collect::<Result<Vec<_>, _>>()
.unwrap_or_default()
});
let frm_connector_details = ConnectorDetailsCore {
connector_name: frm_routing_algorithm.data,
profile_id,
};
let payment_to_frm_data = PaymentToFrmData {
amount: payment_data.get_amount(),
payment_intent: payment_data.get_payment_intent().to_owned(),
payment_attempt: payment_data.get_payment_attempt().to_owned(),
merchant_account: merchant_context.get_merchant_account().to_owned(),
address: payment_data.get_address().clone(),
connector_details: frm_connector_details.clone(),
order_details,
frm_metadata: payment_data.get_payment_intent().frm_metadata.clone(),
};
let fraud_check_operation: operation::BoxedFraudCheckOperation<F, D> =
fraud_check_operation_by_frm_preferred_flow_type(frm_configs.frm_preferred_flow_type);
let frm_data = fraud_check_operation
.to_get_tracker()?
.get_trackers(state, payment_to_frm_data, frm_connector_details)
.await?;
Ok(FrmInfo {
fraud_check_operation,
frm_data,
suggested_action: None,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 77,
"total_crates": null
} |
fn_clm_router_frm_fulfillment_core_3068557274743282806 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/fraud_check
pub async fn frm_fulfillment_core(
state: SessionState,
merchant_context: domain::MerchantContext,
req: frm_core_types::FrmFulfillmentRequest,
) -> RouterResponse<frm_types::FraudCheckResponseData> {
let db = &*state.clone().store;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&(&state).into(),
&req.payment_id.clone(),
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
match payment_intent.status {
IntentStatus::Succeeded => {
let invalid_request_error = errors::ApiErrorResponse::InvalidRequestData {
message: "no fraud check entry found for this payment_id".to_string(),
};
let existing_fraud_check = db
.find_fraud_check_by_payment_id_if_present(
req.payment_id.clone(),
merchant_context.get_merchant_account().get_id().clone(),
)
.await
.change_context(invalid_request_error.to_owned())?;
match existing_fraud_check {
Some(fraud_check) => {
if (matches!(fraud_check.frm_transaction_type, FraudCheckType::PreFrm)
&& fraud_check.last_step == FraudCheckLastStep::TransactionOrRecordRefund)
|| (matches!(fraud_check.frm_transaction_type, FraudCheckType::PostFrm)
&& fraud_check.last_step == FraudCheckLastStep::CheckoutOrSale)
{
Box::pin(make_fulfillment_api_call(
db,
fraud_check,
payment_intent,
state,
merchant_context,
req,
))
.await
} else {
Err(errors::ApiErrorResponse::PreconditionFailed {message:"Frm pre/post flow hasn't terminated yet, so fulfillment cannot be called".to_string(),}.into())
}
}
None => Err(invalid_request_error.into()),
}
}
_ => Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Fulfillment can be performed only for succeeded payment".to_string(),
}
.into()),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 61,
"total_crates": null
} |
fn_clm_router_make_fulfillment_api_call_3068557274743282806 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/fraud_check
pub async fn make_fulfillment_api_call(
db: &dyn StorageInterface,
fraud_check: FraudCheck,
payment_intent: PaymentIntent,
state: SessionState,
merchant_context: domain::MerchantContext,
req: frm_core_types::FrmFulfillmentRequest,
) -> RouterResponse<frm_types::FraudCheckResponseData> {
let payment_attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&payment_intent.active_attempt.get_id(),
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let connector_data = FraudCheckConnectorData::get_connector_by_name(&fraud_check.frm_name)?;
let connector_integration: services::BoxedFrmConnectorIntegrationInterface<
Fulfillment,
frm_types::FraudCheckFulfillmentData,
frm_types::FraudCheckResponseData,
> = connector_data.connector.get_connector_integration();
let router_data = frm_flows::fulfillment_flow::construct_fulfillment_router_data(
&state,
&payment_intent,
&payment_attempt,
&merchant_context,
fraud_check.frm_name.clone(),
req,
)
.await?;
let response = services::execute_connector_processing_step(
&state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
let fraud_check_copy = fraud_check.clone();
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status: fraud_check.frm_status,
frm_transaction_id: fraud_check.frm_transaction_id,
frm_reason: fraud_check.frm_reason,
frm_score: fraud_check.frm_score,
metadata: fraud_check.metadata,
modified_at: common_utils::date_time::now(),
last_step: FraudCheckLastStep::Fulfillment,
payment_capture_method: fraud_check.payment_capture_method,
};
let _updated = db
.update_fraud_check_response_with_attempt_id(fraud_check_copy, fraud_check_update)
.await
.map_err(|error| error.change_context(errors::ApiErrorResponse::PaymentNotFound))?;
let fulfillment_response =
response
.response
.map_err(|err| errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector_data.connector_name.clone().to_string(),
status_code: err.status_code,
reason: err.reason,
})?;
Ok(services::ApplicationResponse::Json(fulfillment_response))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 55,
"total_crates": null
} |
fn_clm_router_new_7548390033325919524 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/cards_info
// Inherent implementation for CardInfoBuilder<CardInfoFetch>
fn new() -> Self {
Self {
state: std::marker::PhantomData,
card_info: None,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14453,
"total_crates": null
} |
fn_clm_router_build_7548390033325919524 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/cards_info
// Inherent implementation for CardInfoBuilder<CardInfoResponse>
pub fn build(self) -> cards_info_api_types::CardInfoMigrateResponseRecord {
match self.card_info {
Some(card_info) => cards_info_api_types::CardInfoMigrateResponseRecord {
card_iin: Some(card_info.card_iin),
card_issuer: card_info.card_issuer,
card_network: card_info.card_network.map(|cn| cn.to_string()),
card_type: card_info.card_type,
card_sub_type: card_info.card_subtype,
card_issuing_country: card_info.card_issuing_country,
},
None => cards_info_api_types::CardInfoMigrateResponseRecord {
card_iin: None,
card_issuer: None,
card_network: None,
card_type: None,
card_sub_type: None,
card_issuing_country: None,
},
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 586,
"total_crates": null
} |
fn_clm_router_update_card_info_7548390033325919524 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/cards_info
// Inherent implementation for CardInfoMigrateExecutor<'a>
async fn update_card_info(&self) -> RouterResult<card_info_models::CardInfo> {
let db = self.state.store.as_ref();
let card_info = cards_info::CardsInfoInterface::update_card_info(
db,
self.record.card_iin.clone(),
card_info_models::UpdateCardInfo {
card_issuer: self.record.card_issuer.clone(),
card_network: self.record.card_network.clone(),
card_type: self.record.card_type.clone(),
card_subtype: self.record.card_subtype.clone(),
card_issuing_country: self.record.card_issuing_country.clone(),
bank_code_id: self.record.bank_code_id.clone(),
bank_code: self.record.bank_code.clone(),
country_code: self.record.country_code.clone(),
last_updated: Some(common_utils::date_time::now()),
last_updated_provider: self.record.last_updated_provider.clone(),
},
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "Card info with given key does not exist in our records".to_string(),
})
.attach_printable("Failed while updating card info")?;
Ok(card_info)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 52,
"total_crates": null
} |
fn_clm_router_add_card_info_7548390033325919524 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/cards_info
// Inherent implementation for CardInfoMigrateExecutor<'a>
async fn add_card_info(&self) -> RouterResult<card_info_models::CardInfo> {
let db = self.state.store.as_ref();
let card_info =
cards_info::CardsInfoInterface::add_card_info(db, self.record.clone().foreign_into())
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: "CardInfo with given key already exists in our records".to_string(),
})?;
Ok(card_info)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 32,
"total_crates": null
} |
fn_clm_router_retrieve_card_info_7548390033325919524 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/cards_info
pub async fn retrieve_card_info(
state: routes::SessionState,
merchant_context: domain::MerchantContext,
request: cards_info_api_types::CardsInfoRequest,
) -> RouterResponse<cards_info_api_types::CardInfoResponse> {
let db = state.store.as_ref();
verify_iin_length(&request.card_iin)?;
helpers::verify_payment_intent_time_and_client_secret(
&state,
&merchant_context,
request.client_secret,
)
.await?;
let card_info = db
.get_card_info(&request.card_iin)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve card information")?
.ok_or(report!(errors::ApiErrorResponse::InvalidCardIin))?;
Ok(ApplicationResponse::Json(
cards_info_api_types::CardInfoResponse::foreign_from(card_info),
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 31,
"total_crates": null
} |
fn_clm_router_redis_update_additional_details_for_revenue_recovery_2181482418558273679 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/revenue_recovery_data_backfill
pub async fn redis_update_additional_details_for_revenue_recovery(
state: SessionState,
request: UpdateTokenStatusRequest,
) -> RouterResult<ApplicationResponse<UpdateTokenStatusResponse>> {
// Get existing token
let existing_token = storage::revenue_recovery_redis_operation::
RedisTokenManager::get_payment_processor_token_using_token_id(
&state,
&request.connector_customer_id,
&request.payment_processor_token.clone().expose(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve existing token data")?;
// Check if token exists
let mut token_status = existing_token.ok_or_else(|| {
error_stack::Report::new(errors::ApiErrorResponse::GenericNotFoundError {
message: format!(
"Token '{:?}' not found for connector customer id:- '{}'",
request.payment_processor_token, request.connector_customer_id
),
})
})?;
let mut updated_fields = Vec::new();
// Handle scheduled_at update
match request.scheduled_at {
Some(ScheduledAtUpdate::SetToDateTime(dt)) => {
// Field provided with datetime - update schedule_at field with datetime
token_status.scheduled_at = Some(dt);
updated_fields.push(format!("scheduled_at: {}", dt));
logger::info!(
"Set scheduled_at to '{}' for token '{:?}'",
dt,
request.payment_processor_token
);
}
Some(ScheduledAtUpdate::SetToNull) => {
// Field provided with "null" variable - set schedule_at field to null
token_status.scheduled_at = None;
updated_fields.push("scheduled_at: set to null".to_string());
logger::info!(
"Set scheduled_at to null for token '{:?}'",
request.payment_processor_token
);
}
None => {
// Field not provided - we don't update schedule_at field
logger::debug!("scheduled_at not provided in request - leaving unchanged");
}
}
// Update is_hard_decline field
request.is_hard_decline.map(|is_hard_decline| {
token_status.is_hard_decline = Some(is_hard_decline);
updated_fields.push(format!("is_hard_decline: {}", is_hard_decline));
});
// Update error_code field
request.error_code.as_ref().map(|error_code| {
token_status.error_code = Some(error_code.clone());
updated_fields.push(format!("error_code: {}", error_code));
});
// Update Redis with modified token
let mut tokens_map = HashMap::new();
tokens_map.insert(
request.payment_processor_token.clone().expose(),
token_status,
);
storage::revenue_recovery_redis_operation::
RedisTokenManager::update_or_add_connector_customer_payment_processor_tokens(
&state,
&request.connector_customer_id,
tokens_map,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update token status in Redis")?;
let updated_fields_str = if updated_fields.is_empty() {
"no fields were updated".to_string()
} else {
updated_fields.join(", ")
};
let response = UpdateTokenStatusResponse {
updated: true,
message: format!(
"Successfully updated token '{:?}' for connector customer '{}'. Updated fields: {}",
request.payment_processor_token, request.connector_customer_id, updated_fields_str
),
};
logger::info!(
"Updated token status for connector customer {}, token: {:?}",
request.connector_customer_id,
request.payment_processor_token
);
Ok(ApplicationResponse::Json(response))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 69,
"total_crates": null
} |
fn_clm_router_parse_expiration_date_2181482418558273679 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/revenue_recovery_data_backfill
/// Parse expiration date
fn parse_expiration_date(
exp_date: Option<&str>,
) -> Result<(Option<String>, Option<String>), BackfillError> {
exp_date
.filter(|date| !date.is_empty())
.map(|date| {
date.split_once('/')
.ok_or_else(|| {
logger::warn!("Unrecognized expiration date format (MM/YY expected)");
BackfillError::CsvParsingError(
"Invalid expiration date format: expected MM/YY".to_string(),
)
})
.and_then(|(month_part, year_part)| {
let month = month_part.trim();
let year = year_part.trim();
logger::debug!("Split expiration date - parsing month and year");
// Validate and parse month
let month_num = month.parse::<u8>().map_err(|_| {
logger::warn!("Failed to parse month component in expiration date");
BackfillError::CsvParsingError(
"Invalid month format in expiration date".to_string(),
)
})?;
if !(1..=12).contains(&month_num) {
logger::warn!("Invalid month value in expiration date (not in range 1-12)");
return Err(BackfillError::CsvParsingError(
"Invalid month value in expiration date".to_string(),
));
}
// Handle year conversion
let final_year = match year.len() {
4 => &year[2..4], // Convert 4-digit to 2-digit
2 => year, // Already 2-digit
_ => {
logger::warn!(
"Invalid year length in expiration date (expected 2 or 4 digits)"
);
return Err(BackfillError::CsvParsingError(
"Invalid year format in expiration date".to_string(),
));
}
};
logger::debug!("Successfully parsed expiration date... ",);
Ok((Some(month.to_string()), Some(final_year.to_string())))
})
})
.unwrap_or_else(|| {
logger::debug!("Empty expiration date, returning None");
Ok((None, None))
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 47,
"total_crates": null
} |
fn_clm_router_unlock_connector_customer_status_2181482418558273679 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/revenue_recovery_data_backfill
pub async fn unlock_connector_customer_status(
state: SessionState,
connector_customer_id: String,
) -> RouterResult<ApplicationResponse<UnlockStatusResponse>> {
let unlocked = storage::revenue_recovery_redis_operation::
RedisTokenManager::unlock_connector_customer_status(&state, &connector_customer_id)
.await
.map_err(|e| {
logger::error!(
"Failed to unlock connector customer status for {}: {}",
connector_customer_id,
e
);
errors::ApiErrorResponse::InternalServerError
})?;
let response = UnlockStatusResponse { unlocked };
logger::info!(
"Unlock operation completed for connector customer {}: {}",
connector_customer_id,
unlocked
);
Ok(ApplicationResponse::Json(response))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 43,
"total_crates": null
} |
fn_clm_router_build_comprehensive_card_data_2181482418558273679 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/revenue_recovery_data_backfill
/// Build comprehensive card data from CSV record
fn build_comprehensive_card_data(
record: &RevenueRecoveryBackfillRequest,
) -> Result<ComprehensiveCardData, BackfillError> {
// Extract card type from request, if not present then update it with 'card'
let card_type = Some(determine_card_type(record.payment_method_sub_type));
// Parse expiration date
let (exp_month, exp_year) = parse_expiration_date(
record
.exp_date
.as_ref()
.map(|date| date.clone().expose())
.as_deref(),
)?;
let card_exp_month = exp_month.map(masking::Secret::new);
let card_exp_year = exp_year.map(masking::Secret::new);
// Extract card network
let card_network = record.card_network.clone();
// Extract card issuer and issuing country
let card_issuer = record
.clean_bank_name
.as_ref()
.filter(|value| !value.is_empty())
.cloned();
let card_issuing_country = record
.country_name
.as_ref()
.filter(|value| !value.is_empty())
.cloned();
// Parse daily retry history
let daily_retry_history = parse_daily_retry_history(record.daily_retry_history.as_deref());
Ok(ComprehensiveCardData {
card_type,
card_exp_month,
card_exp_year,
card_network,
card_issuer,
card_issuing_country,
daily_retry_history,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 43,
"total_crates": null
} |
fn_clm_router_process_payment_method_record_2181482418558273679 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/revenue_recovery_data_backfill
async fn process_payment_method_record(
state: &SessionState,
record: &RevenueRecoveryBackfillRequest,
cutoff_datetime: Option<time::PrimitiveDateTime>,
) -> Result<(), BackfillError> {
// Build comprehensive card data from CSV record
let card_data = match build_comprehensive_card_data(record) {
Ok(data) => data,
Err(e) => {
logger::warn!(
"Failed to build card data for connector customer id: {}, error: {}.",
record.customer_id_resp,
e
);
ComprehensiveCardData {
card_type: Some("card".to_string()),
card_exp_month: None,
card_exp_year: None,
card_network: None,
card_issuer: None,
card_issuing_country: None,
daily_retry_history: None,
}
}
};
logger::info!(
"Built comprehensive card data - card_type: {:?}, exp_month: {}, exp_year: {}, network: {:?}, issuer: {:?}, country: {:?}, daily_retry_history: {:?}",
card_data.card_type,
card_data.card_exp_month.as_ref().map(|_| "**").unwrap_or("None"),
card_data.card_exp_year.as_ref().map(|_| "**").unwrap_or("None"),
card_data.card_network,
card_data.card_issuer,
card_data.card_issuing_country,
card_data.daily_retry_history
);
// Update Redis if token exists and is valid
match record.token.as_ref().map(|token| token.clone().expose()) {
Some(token) if !token.is_empty() => {
logger::info!("Updating Redis for customer: {}", record.customer_id_resp,);
storage::revenue_recovery_redis_operation::
RedisTokenManager::update_redis_token_with_comprehensive_card_data(
state,
&record.customer_id_resp,
&token,
&card_data,
cutoff_datetime,
)
.await
.map_err(|e| {
logger::error!("Redis update failed: {}", e);
BackfillError::RedisError(format!("Token not found in Redis: {}", e))
})?;
}
_ => {
logger::info!(
"Skipping Redis update - token is missing, empty or 'nan': {:?}",
record.token
);
}
}
logger::info!(
"Successfully completed processing for connector customer id: {}",
record.customer_id_resp
);
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 23,
"total_crates": null
} |
fn_clm_router_set_config_-6910772825321165706 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/configs
pub async fn set_config(state: SessionState, config: api::Config) -> RouterResponse<api::Config> {
let store = state.store.as_ref();
let config = store
.insert_config(diesel_models::configs::ConfigNew {
key: config.key,
config: config.value,
})
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateConfig)
.attach_printable("Unknown error, while setting config key")?;
Ok(ApplicationResponse::Json(config.foreign_into()))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 25,
"total_crates": null
} |
fn_clm_router_update_config_-6910772825321165706 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/configs
pub async fn update_config(
state: SessionState,
config_update: &api::ConfigUpdate,
) -> RouterResponse<api::Config> {
let store = state.store.as_ref();
let config = store
.update_config_by_key(&config_update.key, config_update.foreign_into())
.await
.to_not_found_response(errors::ApiErrorResponse::ConfigNotFound)?;
Ok(ApplicationResponse::Json(config.foreign_into()))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 25,
"total_crates": null
} |
fn_clm_router_get_config_object_-6910772825321165706 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/configs
/// Get an object configuration value with superposition and database fallback
pub async fn get_config_object<T>(
state: &SessionState,
superposition_key: &str,
db_key: &str,
context: Option<ConfigContext>,
default_value: T,
) -> CustomResult<T, errors::StorageError>
where
T: serde::de::DeserializeOwned + serde::Serialize,
{
// Try superposition first if available
let superposition_result = if let Some(ref superposition_client) = state.superposition_service {
match superposition_client
.get_object_value(superposition_key, context.as_ref())
.await
{
Ok(json_value) => Some(
serde_json::from_value::<T>(json_value)
.change_context(errors::StorageError::DeserializationFailed),
),
Err(err) => {
router_env::logger::warn!(
"Failed to retrieve config from superposition, falling back to database: {:?}",
err
);
None
}
}
} else {
None
};
// Use superposition result or fall back to database
let result = if let Some(superposition_result) = superposition_result {
superposition_result
} else {
let config = state
.store
.find_config_by_key_unwrap_or(
db_key,
Some(
serde_json::to_string(&default_value)
.change_context(errors::StorageError::SerializationFailed)?,
),
)
.await?;
serde_json::from_str::<T>(&config.config)
.change_context(errors::StorageError::DeserializationFailed)
};
result
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 24,
"total_crates": null
} |
fn_clm_router_read_config_-6910772825321165706 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/configs
pub async fn read_config(state: SessionState, key: &str) -> RouterResponse<api::Config> {
let store = state.store.as_ref();
let config = store
.find_config_by_key(key)
.await
.to_not_found_response(errors::ApiErrorResponse::ConfigNotFound)?;
Ok(ApplicationResponse::Json(config.foreign_into()))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 23,
"total_crates": null
} |
fn_clm_router_config_delete_-6910772825321165706 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/configs
pub async fn config_delete(state: SessionState, key: String) -> RouterResponse<api::Config> {
let store = state.store.as_ref();
let config = store
.delete_config_by_key(&key)
.await
.to_not_found_response(errors::ApiErrorResponse::ConfigNotFound)?;
Ok(ApplicationResponse::Json(config.foreign_into()))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 23,
"total_crates": null
} |
fn_clm_router_initiate_payout_link_2093829381922594546 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payout_link
pub async fn initiate_payout_link(
state: SessionState,
merchant_context: domain::MerchantContext,
req: payouts::PayoutLinkInitiateRequest,
request_headers: &header::HeaderMap,
) -> RouterResponse<services::GenericLinkFormData> {
let db: &dyn StorageInterface = &*state.store;
let merchant_id = merchant_context.get_merchant_account().get_id();
// Fetch payout
let payout = db
.find_payout_by_merchant_id_payout_id(
merchant_id,
&req.payout_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
let payout_attempt = db
.find_payout_attempt_by_merchant_id_payout_attempt_id(
merchant_id,
&get_payout_attempt_id(payout.payout_id.get_string_repr(), payout.attempt_count),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
let payout_link_id = payout
.payout_link_id
.clone()
.get_required_value("payout link id")
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "payout link not found".to_string(),
})?;
// Fetch payout link
let payout_link = db
.find_payout_link_by_link_id(&payout_link_id)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payout link not found".to_string(),
})?;
let allowed_domains = validator::validate_payout_link_render_request_and_get_allowed_domains(
request_headers,
&payout_link,
)?;
// Check status and return form data accordingly
let has_expired = common_utils::date_time::now() > payout_link.expiry;
let status = payout_link.link_status.clone();
let link_data = payout_link.link_data.clone();
let default_config = &state.conf.generic_link.payout_link.clone();
let default_ui_config = default_config.ui_config.clone();
let ui_config_data = link_utils::GenericLinkUiConfigFormData {
merchant_name: link_data
.ui_config
.merchant_name
.unwrap_or(default_ui_config.merchant_name),
logo: link_data.ui_config.logo.unwrap_or(default_ui_config.logo),
theme: link_data
.ui_config
.theme
.clone()
.unwrap_or(default_ui_config.theme.clone()),
};
match (has_expired, &status) {
// Send back generic expired page
(true, _) | (_, &link_utils::PayoutLinkStatus::Invalidated) => {
let expired_link_data = services::GenericExpiredLinkData {
title: "Payout Expired".to_string(),
message: "This payout link has expired.".to_string(),
theme: link_data.ui_config.theme.unwrap_or(default_ui_config.theme),
};
if status != link_utils::PayoutLinkStatus::Invalidated {
let payout_link_update = PayoutLinkUpdate::StatusUpdate {
link_status: link_utils::PayoutLinkStatus::Invalidated,
};
db.update_payout_link(payout_link, payout_link_update)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout links in db")?;
}
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains,
data: GenericLinksData::ExpiredLink(expired_link_data),
locale: state.locale,
},
)))
}
// Initiate Payout link flow
(_, link_utils::PayoutLinkStatus::Initiated) => {
let customer_id = link_data.customer_id;
let required_amount_type = StringMajorUnitForConnector;
let amount = required_amount_type
.convert(payout.amount, payout.destination_currency)
.change_context(errors::ApiErrorResponse::CurrencyConversionFailed)?;
// Fetch customer
let customer = db
.find_customer_by_customer_id_merchant_id(
&(&state).into(),
&customer_id,
&req.merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Customer [{:?}] not found for link_id - {}",
customer_id, payout_link.link_id
),
})
.attach_printable_lazy(|| format!("customer [{customer_id:?}] not found"))?;
let address = payout
.address_id
.as_ref()
.async_map(|address_id| async {
db.find_address_by_address_id(
&(&state).into(),
address_id,
merchant_context.get_merchant_key_store(),
)
.await
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while fetching address [id - {:?}] for payout [id - {:?}]",
payout.address_id, payout.payout_id
)
})?;
let enabled_payout_methods =
filter_payout_methods(&state, &merchant_context, &payout, address.as_ref()).await?;
// Fetch default enabled_payout_methods
let mut default_enabled_payout_methods: Vec<link_utils::EnabledPaymentMethod> = vec![];
for (payment_method, payment_method_types) in
default_config.enabled_payment_methods.clone().into_iter()
{
let enabled_payment_method = link_utils::EnabledPaymentMethod {
payment_method,
payment_method_types,
};
default_enabled_payout_methods.push(enabled_payment_method);
}
let fallback_enabled_payout_methods = if enabled_payout_methods.is_empty() {
&default_enabled_payout_methods
} else {
&enabled_payout_methods
};
// Fetch enabled payout methods from the request. If not found, fetch the enabled payout methods from MCA,
// If none are configured for merchant connector accounts, fetch them from the default enabled payout methods.
let mut enabled_payment_methods = link_data
.enabled_payment_methods
.unwrap_or(fallback_enabled_payout_methods.to_vec());
// Sort payment methods (cards first)
enabled_payment_methods.sort_by(|a, b| match (a.payment_method, b.payment_method) {
(_, common_enums::PaymentMethod::Card) => Ordering::Greater,
(common_enums::PaymentMethod::Card, _) => Ordering::Less,
_ => Ordering::Equal,
});
let required_field_override = api::RequiredFieldsOverrideRequest {
billing: address
.as_ref()
.map(hyperswitch_domain_models::address::Address::from)
.map(From::from),
};
let enabled_payment_methods_with_required_fields = ForeignFrom::foreign_from((
&state.conf.payouts.required_fields,
enabled_payment_methods.clone(),
required_field_override,
));
let js_data = payouts::PayoutLinkDetails {
publishable_key: masking::Secret::new(
merchant_context
.get_merchant_account()
.clone()
.publishable_key,
),
client_secret: link_data.client_secret.clone(),
payout_link_id: payout_link.link_id,
payout_id: payout_link.primary_reference.clone(),
customer_id: customer.customer_id,
session_expiry: payout_link.expiry,
return_url: payout_link
.return_url
.as_ref()
.map(|url| url::Url::parse(url))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse payout status link's return URL")?,
ui_config: ui_config_data,
enabled_payment_methods,
enabled_payment_methods_with_required_fields,
amount,
currency: payout.destination_currency,
locale: state.locale.clone(),
form_layout: link_data.form_layout,
test_mode: link_data.test_mode.unwrap_or(false),
};
let serialized_css_content = String::new();
let serialized_js_content = format!(
"window.__PAYOUT_DETAILS = {}",
js_data
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize PaymentMethodCollectLinkDetails")?
);
let generic_form_data = services::GenericLinkFormData {
js_data: serialized_js_content,
css_data: serialized_css_content,
sdk_url: default_config.sdk_url.clone(),
html_meta_tags: String::new(),
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains,
data: GenericLinksData::PayoutLink(generic_form_data),
locale: state.locale.clone(),
},
)))
}
// Send back status page
(_, link_utils::PayoutLinkStatus::Submitted) => {
let translated_unified_message =
payout_helpers::get_translated_unified_code_and_message(
&state,
payout_attempt.unified_code.as_ref(),
payout_attempt.unified_message.as_ref(),
&state.locale.clone(),
)
.await?;
let js_data = payouts::PayoutLinkStatusDetails {
payout_link_id: payout_link.link_id,
payout_id: payout_link.primary_reference.clone(),
customer_id: link_data.customer_id,
session_expiry: payout_link.expiry,
return_url: payout_link
.return_url
.as_ref()
.map(|url| url::Url::parse(url))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse payout status link's return URL")?,
status: payout.status,
error_code: payout_attempt.unified_code,
error_message: translated_unified_message,
ui_config: ui_config_data,
test_mode: link_data.test_mode.unwrap_or(false),
};
let serialized_css_content = String::new();
let serialized_js_content = format!(
"window.__PAYOUT_DETAILS = {}",
js_data
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize PaymentMethodCollectLinkDetails")?
);
let generic_status_data = services::GenericLinkStatusData {
js_data: serialized_js_content,
css_data: serialized_css_content,
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains,
data: GenericLinksData::PayoutLinkStatus(generic_status_data),
locale: state.locale.clone(),
},
)))
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 221,
"total_crates": null
} |
fn_clm_router_filter_payout_methods_2093829381922594546 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payout_link
pub async fn filter_payout_methods(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payout: &hyperswitch_domain_models::payouts::payouts::Payouts,
address: Option<&domain::Address>,
) -> errors::RouterResult<Vec<link_utils::EnabledPaymentMethod>> {
use masking::ExposeInterface;
let db = &*state.store;
let key_manager_state = &state.into();
//Fetch all merchant connector accounts
let all_mcas = db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
key_manager_state,
merchant_context.get_merchant_account().get_id(),
false,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
// Filter MCAs based on profile_id and connector_type
let filtered_mcas = all_mcas.filter_based_on_profile_and_connector_type(
&payout.profile_id,
common_enums::ConnectorType::PayoutProcessor,
);
let mut response: Vec<link_utils::EnabledPaymentMethod> = vec![];
let mut payment_method_list_hm: HashMap<
common_enums::PaymentMethod,
HashSet<common_enums::PaymentMethodType>,
> = HashMap::new();
let mut bank_transfer_hash_set: HashSet<common_enums::PaymentMethodType> = HashSet::new();
let mut card_hash_set: HashSet<common_enums::PaymentMethodType> = HashSet::new();
let mut wallet_hash_set: HashSet<common_enums::PaymentMethodType> = HashSet::new();
let payout_filter_config = &state.conf.payout_method_filters.clone();
for mca in &filtered_mcas {
let payout_methods = match &mca.payment_methods_enabled {
Some(pm) => pm,
None => continue,
};
for payout_method in payout_methods.iter() {
let parse_result = serde_json::from_value::<api_models::admin::PaymentMethodsEnabled>(
payout_method.clone().expose(),
);
if let Ok(payment_methods_enabled) = parse_result {
let payment_method = payment_methods_enabled.payment_method;
let payment_method_types = match payment_methods_enabled.payment_method_types {
Some(payment_method_types) => payment_method_types,
None => continue,
};
let connector = mca.connector_name.clone();
let payout_filter = payout_filter_config.0.get(&connector);
for request_payout_method_type in &payment_method_types {
let currency_country_filter = check_currency_country_filters(
payout_filter,
request_payout_method_type,
payout.destination_currency,
address
.as_ref()
.and_then(|address| address.country)
.as_ref(),
)?;
if currency_country_filter.unwrap_or(true) {
match payment_method {
common_enums::PaymentMethod::Card => {
card_hash_set
.insert(request_payout_method_type.payment_method_type);
payment_method_list_hm
.insert(payment_method, card_hash_set.clone());
}
common_enums::PaymentMethod::Wallet => {
wallet_hash_set
.insert(request_payout_method_type.payment_method_type);
payment_method_list_hm
.insert(payment_method, wallet_hash_set.clone());
}
common_enums::PaymentMethod::BankTransfer => {
bank_transfer_hash_set
.insert(request_payout_method_type.payment_method_type);
payment_method_list_hm
.insert(payment_method, bank_transfer_hash_set.clone());
}
common_enums::PaymentMethod::CardRedirect
| common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::BankRedirect
| common_enums::PaymentMethod::Crypto
| common_enums::PaymentMethod::BankDebit
| common_enums::PaymentMethod::Reward
| common_enums::PaymentMethod::RealTimePayment
| common_enums::PaymentMethod::MobilePayment
| common_enums::PaymentMethod::Upi
| common_enums::PaymentMethod::Voucher
| common_enums::PaymentMethod::OpenBanking
| common_enums::PaymentMethod::GiftCard => continue,
}
}
}
}
}
}
for (payment_method, payment_method_types) in payment_method_list_hm {
if !payment_method_types.is_empty() {
let enabled_payment_method = link_utils::EnabledPaymentMethod {
payment_method,
payment_method_types,
};
response.push(enabled_payment_method);
}
}
Ok(response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 79,
"total_crates": null
} |
fn_clm_router_check_currency_country_filters_2093829381922594546 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payout_link
pub fn check_currency_country_filters(
payout_method_filter: Option<&PaymentMethodFilters>,
request_payout_method_type: &api_models::payment_methods::RequestPaymentMethodTypes,
currency: common_enums::Currency,
country: Option<&common_enums::CountryAlpha2>,
) -> errors::RouterResult<Option<bool>> {
if matches!(
request_payout_method_type.payment_method_type,
common_enums::PaymentMethodType::Credit | common_enums::PaymentMethodType::Debit
) {
Ok(Some(true))
} else {
let payout_method_type_filter =
payout_method_filter.and_then(|payout_method_filter: &PaymentMethodFilters| {
payout_method_filter
.0
.get(&PaymentMethodFilterKey::PaymentMethodType(
request_payout_method_type.payment_method_type,
))
});
let country_filter = country.as_ref().and_then(|country| {
payout_method_type_filter.and_then(|currency_country_filter| {
currency_country_filter
.country
.as_ref()
.map(|country_hash_set| country_hash_set.contains(country))
})
});
let currency_filter = payout_method_type_filter.and_then(|currency_country_filter| {
currency_country_filter
.currency
.as_ref()
.map(|currency_hash_set| currency_hash_set.contains(¤cy))
});
Ok(currency_filter.or(country_filter))
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 41,
"total_crates": null
} |
fn_clm_router_validate_auth_and_metadata_type_with_connector_9215758604401163811 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/connector_validation
// Implementation of None for ConnectorAuthTypeAndMetadataValidation<'_>
fn validate_auth_and_metadata_type_with_connector(
&self,
) -> Result<(), error_stack::Report<errors::ConnectorError>> {
use crate::connector::*;
match self.connector_name {
api_enums::Connector::Vgs => {
vgs::transformers::VgsAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Adyenplatform => {
adyenplatform::transformers::AdyenplatformAuthType::try_from(self.auth_type)?;
Ok(())
}
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyBillingConnector
| api_enums::Connector::DummyConnector1
| api_enums::Connector::DummyConnector2
| api_enums::Connector::DummyConnector3
| api_enums::Connector::DummyConnector4
| api_enums::Connector::DummyConnector5
| api_enums::Connector::DummyConnector6
| api_enums::Connector::DummyConnector7 => {
hyperswitch_connectors::connectors::dummyconnector::transformers::DummyConnectorAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Aci => {
aci::transformers::AciAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Adyen => {
adyen::transformers::AdyenAuthType::try_from(self.auth_type)?;
adyen::transformers::AdyenConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Affirm => {
affirm::transformers::AffirmAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Airwallex => {
airwallex::transformers::AirwallexAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Amazonpay => {
amazonpay::transformers::AmazonpayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Archipel => {
archipel::transformers::ArchipelAuthType::try_from(self.auth_type)?;
archipel::transformers::ArchipelConfigData::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Authipay => {
authipay::transformers::AuthipayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Authorizedotnet => {
authorizedotnet::transformers::AuthorizedotnetAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Bankofamerica => {
bankofamerica::transformers::BankOfAmericaAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Barclaycard => {
barclaycard::transformers::BarclaycardAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Billwerk => {
billwerk::transformers::BillwerkAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Bitpay => {
bitpay::transformers::BitpayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Bambora => {
bambora::transformers::BamboraAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Bamboraapac => {
bamboraapac::transformers::BamboraapacAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Boku => {
boku::transformers::BokuAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Bluesnap => {
bluesnap::transformers::BluesnapAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Blackhawknetwork => {
blackhawknetwork::transformers::BlackhawknetworkAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Calida => {
calida::transformers::CalidaAuthType::try_from(self.auth_type)?;
calida::transformers::CalidaMetadataObject::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Braintree => {
braintree::transformers::BraintreeAuthType::try_from(self.auth_type)?;
braintree::transformers::BraintreeMeta::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Breadpay => {
breadpay::transformers::BreadpayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Cardinal => Ok(()),
api_enums::Connector::Cashtocode => {
cashtocode::transformers::CashtocodeAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Chargebee => {
chargebee::transformers::ChargebeeAuthType::try_from(self.auth_type)?;
chargebee::transformers::ChargebeeMetadata::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Celero => {
celero::transformers::CeleroAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Checkbook => {
checkbook::transformers::CheckbookAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Checkout => {
checkout::transformers::CheckoutAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Coinbase => {
coinbase::transformers::CoinbaseAuthType::try_from(self.auth_type)?;
coinbase::transformers::CoinbaseConnectorMeta::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Coingate => {
coingate::transformers::CoingateAuthType::try_from(self.auth_type)?;
coingate::transformers::CoingateConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Cryptopay => {
cryptopay::transformers::CryptopayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::CtpMastercard => Ok(()),
api_enums::Connector::Custombilling => Ok(()),
api_enums::Connector::CtpVisa => Ok(()),
api_enums::Connector::Cybersource => {
cybersource::transformers::CybersourceAuthType::try_from(self.auth_type)?;
cybersource::transformers::CybersourceConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Datatrans => {
datatrans::transformers::DatatransAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Deutschebank => {
deutschebank::transformers::DeutschebankAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Digitalvirgo => {
digitalvirgo::transformers::DigitalvirgoAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Dlocal => {
dlocal::transformers::DlocalAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Dwolla => {
dwolla::transformers::DwollaAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Ebanx => {
ebanx::transformers::EbanxAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Elavon => {
elavon::transformers::ElavonAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Facilitapay => {
facilitapay::transformers::FacilitapayAuthType::try_from(self.auth_type)?;
facilitapay::transformers::FacilitapayConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Fiserv => {
fiserv::transformers::FiservAuthType::try_from(self.auth_type)?;
fiserv::transformers::FiservSessionObject::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Fiservemea => {
fiservemea::transformers::FiservemeaAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Fiuu => {
fiuu::transformers::FiuuAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Flexiti => {
flexiti::transformers::FlexitiAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Forte => {
forte::transformers::ForteAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Getnet => {
getnet::transformers::GetnetAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Gigadat => {
gigadat::transformers::GigadatAuthType::try_from(self.auth_type)?;
gigadat::transformers::GigadatConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Globalpay => {
globalpay::transformers::GlobalpayAuthType::try_from(self.auth_type)?;
globalpay::transformers::GlobalPayMeta::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Globepay => {
globepay::transformers::GlobepayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Gocardless => {
gocardless::transformers::GocardlessAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Gpayments => {
gpayments::transformers::GpaymentsAuthType::try_from(self.auth_type)?;
gpayments::transformers::GpaymentsMetaData::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Hipay => {
hipay::transformers::HipayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Helcim => {
helcim::transformers::HelcimAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::HyperswitchVault => {
hyperswitch_vault::transformers::HyperswitchVaultAuthType::try_from(
self.auth_type,
)?;
Ok(())
}
api_enums::Connector::Iatapay => {
iatapay::transformers::IatapayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Inespay => {
inespay::transformers::InespayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Itaubank => {
itaubank::transformers::ItaubankAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Jpmorgan => {
jpmorgan::transformers::JpmorganAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Juspaythreedsserver => Ok(()),
api_enums::Connector::Klarna => {
klarna::transformers::KlarnaAuthType::try_from(self.auth_type)?;
klarna::transformers::KlarnaConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Loonio => {
loonio::transformers::LoonioAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Mifinity => {
mifinity::transformers::MifinityAuthType::try_from(self.auth_type)?;
mifinity::transformers::MifinityConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Mollie => {
mollie::transformers::MollieAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Moneris => {
moneris::transformers::MonerisAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Multisafepay => {
multisafepay::transformers::MultisafepayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Netcetera => {
netcetera::transformers::NetceteraAuthType::try_from(self.auth_type)?;
netcetera::transformers::NetceteraMetaData::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Nexinets => {
nexinets::transformers::NexinetsAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Nexixpay => {
nexixpay::transformers::NexixpayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Nmi => {
nmi::transformers::NmiAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Nomupay => {
nomupay::transformers::NomupayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Noon => {
noon::transformers::NoonAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Nordea => {
nordea::transformers::NordeaAuthType::try_from(self.auth_type)?;
nordea::transformers::NordeaConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Novalnet => {
novalnet::transformers::NovalnetAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Nuvei => {
nuvei::transformers::NuveiAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Opennode => {
opennode::transformers::OpennodeAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Paybox => {
paybox::transformers::PayboxAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Payload => {
payload::transformers::PayloadAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Payme => {
payme::transformers::PaymeAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Paypal => {
paypal::transformers::PaypalAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Paysafe => {
paysafe::transformers::PaysafeAuthType::try_from(self.auth_type)?;
paysafe::transformers::PaysafeConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Payone => {
payone::transformers::PayoneAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Paystack => {
paystack::transformers::PaystackAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Payu => {
payu::transformers::PayuAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Peachpayments => {
peachpayments::transformers::PeachpaymentsAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Placetopay => {
placetopay::transformers::PlacetopayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Powertranz => {
powertranz::transformers::PowertranzAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Prophetpay => {
prophetpay::transformers::ProphetpayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Rapyd => {
rapyd::transformers::RapydAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Razorpay => {
razorpay::transformers::RazorpayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Recurly => {
recurly::transformers::RecurlyAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Redsys => {
redsys::transformers::RedsysAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Santander => {
santander::transformers::SantanderAuthType::try_from(self.auth_type)?;
santander::transformers::SantanderMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Shift4 => {
shift4::transformers::Shift4AuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Silverflow => {
silverflow::transformers::SilverflowAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Square => {
square::transformers::SquareAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Stax => {
stax::transformers::StaxAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Taxjar => {
taxjar::transformers::TaxjarAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Stripe => {
stripe::transformers::StripeAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Stripebilling => {
stripebilling::transformers::StripebillingAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Tesouro => {
tesouro::transformers::TesouroAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Trustpay => {
trustpay::transformers::TrustpayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Trustpayments => {
trustpayments::transformers::TrustpaymentsAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Tokenex => {
tokenex::transformers::TokenexAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Tokenio => {
tokenio::transformers::TokenioAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Tsys => {
tsys::transformers::TsysAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Volt => {
volt::transformers::VoltAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Wellsfargo => {
wellsfargo::transformers::WellsfargoAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Wise => {
wise::transformers::WiseAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Worldline => {
worldline::transformers::WorldlineAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Worldpay => {
worldpay::transformers::WorldpayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Worldpayvantiv => {
worldpayvantiv::transformers::WorldpayvantivAuthType::try_from(self.auth_type)?;
worldpayvantiv::transformers::WorldpayvantivMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Worldpayxml => {
worldpayxml::transformers::WorldpayxmlAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Xendit => {
xendit::transformers::XenditAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Zen => {
zen::transformers::ZenAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Zsl => {
zsl::transformers::ZslAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Signifyd => {
signifyd::transformers::SignifydAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Riskified => {
riskified::transformers::RiskifiedAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Plaid => {
PlaidAuthType::foreign_try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Threedsecureio => {
threedsecureio::transformers::ThreedsecureioAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Phonepe => {
phonepe::transformers::PhonepeAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Paytm => {
paytm::transformers::PaytmAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Finix => {
finix::transformers::FinixAuthType::try_from(self.auth_type)?;
Ok(())
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 293,
"total_crates": null
} |
fn_clm_router_validate_connector_auth_type_9215758604401163811 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/connector_validation
// Inherent implementation for ConnectorAuthTypeValidation<'_>
fn validate_connector_auth_type(
&self,
) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
let validate_non_empty_field = |field_value: &str, field_name: &str| {
if field_value.trim().is_empty() {
Err(errors::ApiErrorResponse::InvalidDataFormat {
field_name: format!("connector_account_details.{field_name}"),
expected_format: "a non empty String".to_string(),
}
.into())
} else {
Ok(())
}
};
match self.auth_type {
hyperswitch_domain_models::router_data::ConnectorAuthType::TemporaryAuth => Ok(()),
hyperswitch_domain_models::router_data::ConnectorAuthType::HeaderKey { api_key } => {
validate_non_empty_field(api_key.peek(), "api_key")
}
hyperswitch_domain_models::router_data::ConnectorAuthType::BodyKey {
api_key,
key1,
} => {
validate_non_empty_field(api_key.peek(), "api_key")?;
validate_non_empty_field(key1.peek(), "key1")
}
hyperswitch_domain_models::router_data::ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => {
validate_non_empty_field(api_key.peek(), "api_key")?;
validate_non_empty_field(key1.peek(), "key1")?;
validate_non_empty_field(api_secret.peek(), "api_secret")
}
hyperswitch_domain_models::router_data::ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => {
validate_non_empty_field(api_key.peek(), "api_key")?;
validate_non_empty_field(key1.peek(), "key1")?;
validate_non_empty_field(api_secret.peek(), "api_secret")?;
validate_non_empty_field(key2.peek(), "key2")
}
hyperswitch_domain_models::router_data::ConnectorAuthType::CurrencyAuthKey {
auth_key_map,
} => {
if auth_key_map.is_empty() {
Err(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_account_details.auth_key_map".to_string(),
expected_format: "a non empty map".to_string(),
}
.into())
} else {
Ok(())
}
}
hyperswitch_domain_models::router_data::ConnectorAuthType::CertificateAuth {
certificate,
private_key,
} => {
client::create_identity_from_certificate_and_key(
certificate.to_owned(),
private_key.to_owned(),
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name:
"connector_account_details.certificate or connector_account_details.private_key"
.to_string(),
expected_format:
"a valid base64 encoded string of PEM encoded Certificate and Private Key"
.to_string(),
})?;
Ok(())
}
hyperswitch_domain_models::router_data::ConnectorAuthType::NoKey => Ok(()),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 79,
"total_crates": null
} |
fn_clm_router_validate_auth_and_metadata_type_9215758604401163811 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/connector_validation
// Implementation of None for ConnectorAuthTypeAndMetadataValidation<'_>
pub fn validate_auth_and_metadata_type(
&self,
) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
let connector_auth_type_validation = ConnectorAuthTypeValidation {
auth_type: self.auth_type,
};
connector_auth_type_validation.validate_connector_auth_type()?;
self.validate_auth_and_metadata_type_with_connector()
.map_err(|err| match *err.current_context() {
errors::ConnectorError::InvalidConnectorName => {
err.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "The connector name is invalid".to_string(),
})
}
errors::ConnectorError::InvalidConnectorConfig { config: field_name } => err
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: format!("The {field_name} is invalid"),
}),
errors::ConnectorError::FailedToObtainAuthType => {
err.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "The auth type is invalid for the connector".to_string(),
})
}
_ => err.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "The request body is invalid".to_string(),
}),
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 40,
"total_crates": null
} |
fn_clm_router_verify_merchant_creds_for_applepay_-6954151620593007017 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/verification
pub async fn verify_merchant_creds_for_applepay(
state: SessionState,
body: verifications::ApplepayMerchantVerificationRequest,
merchant_id: common_utils::id_type::MerchantId,
profile_id: Option<common_utils::id_type::ProfileId>,
) -> CustomResult<services::ApplicationResponse<ApplepayMerchantResponse>, errors::ApiErrorResponse>
{
let applepay_merchant_configs = state.conf.applepay_merchant_configs.get_inner();
let applepay_internal_merchant_identifier = applepay_merchant_configs
.common_merchant_identifier
.clone()
.expose();
let cert_data = applepay_merchant_configs.merchant_cert.clone();
let key_data = applepay_merchant_configs.merchant_cert_key.clone();
let applepay_endpoint = &applepay_merchant_configs.applepay_endpoint;
let request_body = verifications::ApplepayMerchantVerificationConfigs {
domain_names: body.domain_names.clone(),
encrypt_to: applepay_internal_merchant_identifier.clone(),
partner_internal_merchant_identifier: applepay_internal_merchant_identifier,
partner_merchant_name: APPLEPAY_INTERNAL_MERCHANT_NAME.to_string(),
};
let apple_pay_merch_verification_req = services::RequestBuilder::new()
.method(services::Method::Post)
.url(applepay_endpoint)
.attach_default_headers()
.headers(vec![(
headers::CONTENT_TYPE.to_string(),
"application/json".to_string().into(),
)])
.set_body(RequestContent::Json(Box::new(request_body)))
.add_certificate(Some(cert_data))
.add_certificate_key(Some(key_data))
.build();
let response = services::call_connector_api(
&state,
apple_pay_merch_verification_req,
"verify_merchant_creds_for_applepay",
)
.await;
utils::log_applepay_verification_response_if_error(&response);
let applepay_response =
response.change_context(errors::ApiErrorResponse::InternalServerError)?;
// Error is already logged
match applepay_response {
Ok(_) => {
utils::check_existence_and_add_domain_to_db(
&state,
merchant_id,
profile_id,
body.merchant_connector_account_id.clone(),
body.domain_names.clone(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(services::api::ApplicationResponse::Json(
ApplepayMerchantResponse {
status_message: "Applepay verification Completed".to_string(),
},
))
}
Err(error) => {
logger::error!(?error);
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Applepay verification Failed".to_string(),
}
.into())
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 73,
"total_crates": null
} |
fn_clm_router_get_verified_apple_domains_with_mid_mca_id_-6954151620593007017 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/verification
pub async fn get_verified_apple_domains_with_mid_mca_id(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
) -> CustomResult<
services::ApplicationResponse<verifications::ApplepayVerifiedDomainsResponse>,
errors::ApiErrorResponse,
> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&db.get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::MerchantAccountNotFound)?;
#[cfg(feature = "v1")]
let verified_domains = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&merchant_id,
&merchant_connector_id,
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?
.applepay_verified_domains
.unwrap_or_default();
#[cfg(feature = "v2")]
let verified_domains = db
.find_merchant_connector_account_by_id(
key_manager_state,
&merchant_connector_id,
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?
.applepay_verified_domains
.unwrap_or_default();
Ok(services::api::ApplicationResponse::Json(
verifications::ApplepayVerifiedDomainsResponse { verified_domains },
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 41,
"total_crates": null
} |
fn_clm_router_payments_operation_core_-1425498721924818589 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments
pub async fn payments_operation_core<'a, F, Req, Op, FData, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
profile_id_from_auth_layer: Option<id_type::ProfileId>,
operation: Op,
req: Req,
call_connector_action: CallConnectorAction,
auth_flow: services::AuthFlow,
eligible_connectors: Option<Vec<common_enums::RoutableConnectors>>,
header_payload: HeaderPayload,
) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)>
where
F: Send + Clone + Sync + 'static,
Req: Authenticate + Clone,
Op: Operation<F, Req, Data = D> + Send + Sync,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
// To create connector flow specific interface data
D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, FData, Data = D>,
FData: Send + Sync + Clone + router_types::Capturable + 'static + serde::Serialize,
{
let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation);
tracing::Span::current().record(
"merchant_id",
merchant_context
.get_merchant_account()
.get_id()
.get_string_repr(),
);
let (operation, validate_result) = operation
.to_validate_request()?
.validate_request(&req, merchant_context)?;
tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id));
// get profile from headers
let operations::GetTrackerResponse {
operation,
customer_details,
mut payment_data,
business_profile,
mandate_type,
} = operation
.to_get_tracker()?
.get_trackers(
state,
&validate_result.payment_id,
&req,
merchant_context,
auth_flow,
&header_payload,
)
.await?;
operation
.to_get_tracker()?
.validate_request_with_state(state, &req, &mut payment_data, &business_profile)
.await?;
core_utils::validate_profile_id_from_auth_layer(
profile_id_from_auth_layer,
&payment_data.get_payment_intent().clone(),
)?;
let (operation, customer) = operation
.to_domain()?
// get_customer_details
.get_or_create_customer_details(
state,
&mut payment_data,
customer_details,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Failed while fetching/creating customer")?;
let authentication_type =
call_decision_manager(state, merchant_context, &business_profile, &payment_data).await?;
payment_data.set_authentication_type_in_attempt(authentication_type);
let connector = get_connector_choice(
&operation,
state,
&req,
merchant_context,
&business_profile,
&mut payment_data,
eligible_connectors,
mandate_type,
)
.await?;
let payment_method_token = get_decrypted_wallet_payment_method_token(
&operation,
state,
merchant_context,
&mut payment_data,
connector.as_ref(),
)
.await?;
payment_method_token.map(|token| payment_data.set_payment_method_token(Some(token)));
let (connector, debit_routing_output) = debit_routing::perform_debit_routing(
&operation,
state,
&business_profile,
&mut payment_data,
connector,
)
.await;
operation
.to_domain()?
.apply_three_ds_authentication_strategy(state, &mut payment_data, &business_profile)
.await?;
let should_add_task_to_process_tracker = should_add_task_to_process_tracker(&payment_data);
let locale = header_payload.locale.clone();
payment_data = tokenize_in_router_when_confirm_false_or_external_authentication(
state,
&operation,
&mut payment_data,
&validate_result,
merchant_context.get_merchant_key_store(),
&customer,
&business_profile,
)
.await?;
let mut connector_http_status_code = None;
let mut external_latency = None;
if let Some(connector_details) = connector {
// Fetch and check FRM configs
#[cfg(feature = "frm")]
let mut frm_info = None;
#[allow(unused_variables, unused_mut)]
let mut should_continue_transaction: bool = true;
#[cfg(feature = "frm")]
let mut should_continue_capture: bool = true;
#[cfg(feature = "frm")]
let frm_configs = if state.conf.frm.enabled {
Box::pin(frm_core::call_frm_before_connector_call(
&operation,
merchant_context,
&mut payment_data,
state,
&mut frm_info,
&customer,
&mut should_continue_transaction,
&mut should_continue_capture,
))
.await?
} else {
None
};
#[cfg(feature = "frm")]
logger::debug!(
"frm_configs: {:?}\nshould_continue_transaction: {:?}\nshould_continue_capture: {:?}",
frm_configs,
should_continue_transaction,
should_continue_capture,
);
let is_eligible_for_uas = helpers::is_merchant_eligible_authentication_service(
merchant_context.get_merchant_account().get_id(),
state,
)
.await?;
if is_eligible_for_uas {
operation
.to_domain()?
.call_unified_authentication_service_if_eligible(
state,
&mut payment_data,
&mut should_continue_transaction,
&connector_details,
&business_profile,
merchant_context.get_merchant_key_store(),
mandate_type,
)
.await?;
} else {
logger::info!(
"skipping authentication service call since the merchant is not eligible."
);
operation
.to_domain()?
.call_external_three_ds_authentication_if_eligible(
state,
&mut payment_data,
&mut should_continue_transaction,
&connector_details,
&business_profile,
merchant_context.get_merchant_key_store(),
mandate_type,
)
.await?;
};
operation
.to_domain()?
.payments_dynamic_tax_calculation(
state,
&mut payment_data,
&connector_details,
&business_profile,
merchant_context,
)
.await?;
if should_continue_transaction {
#[cfg(feature = "frm")]
match (
should_continue_capture,
payment_data.get_payment_attempt().capture_method,
) {
(
false,
Some(storage_enums::CaptureMethod::Automatic)
| Some(storage_enums::CaptureMethod::SequentialAutomatic),
)
| (false, Some(storage_enums::CaptureMethod::Scheduled)) => {
if let Some(info) = &mut frm_info {
if let Some(frm_data) = &mut info.frm_data {
frm_data.fraud_check.payment_capture_method =
payment_data.get_payment_attempt().capture_method;
}
}
payment_data
.set_capture_method_in_attempt(storage_enums::CaptureMethod::Manual);
logger::debug!("payment_id : {:?} capture method has been changed to manual, since it has configured Post FRM flow",payment_data.get_payment_attempt().payment_id);
}
_ => (),
};
payment_data = match connector_details {
ConnectorCallType::PreDetermined(ref connector) => {
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
let routable_connectors = convert_connector_data_to_routable_connectors(
std::slice::from_ref(connector),
)
.map_err(|e| logger::error!(routable_connector_error=?e))
.unwrap_or_default();
let schedule_time = if should_add_task_to_process_tracker {
payment_sync::get_sync_process_schedule_time(
&*state.store,
connector.connector_data.connector.id(),
merchant_context.get_merchant_account().get_id(),
0,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting process schedule time")?
} else {
None
};
let (merchant_connector_account, router_data, tokenization_action) =
call_connector_service_prerequisites(
state,
merchant_context,
connector.connector_data.clone(),
&operation,
&mut payment_data,
&customer,
&validate_result,
&business_profile,
false,
None,
)
.await?;
let (router_data, mca) = decide_unified_connector_service_call(
state,
req_state.clone(),
merchant_context,
connector.connector_data.clone(),
&operation,
&mut payment_data,
&customer,
call_connector_action.clone(),
&validate_result,
schedule_time,
header_payload.clone(),
#[cfg(feature = "frm")]
frm_info.as_ref().and_then(|fi| fi.suggested_action),
#[cfg(not(feature = "frm"))]
None,
&business_profile,
false,
<Req as Authenticate>::should_return_raw_response(&req),
merchant_connector_account,
router_data,
tokenization_action,
)
.await?;
let op_ref = &operation;
let should_trigger_post_processing_flows = is_operation_confirm(&operation);
let operation = Box::new(PaymentResponse);
connector_http_status_code = router_data.connector_http_status_code;
external_latency = router_data.external_latency;
//add connector http status code metrics
add_connector_http_status_code_metrics(connector_http_status_code);
operation
.to_post_update_tracker()?
.save_pm_and_mandate(
state,
&router_data,
merchant_context,
&mut payment_data,
&business_profile,
)
.await?;
let mut payment_data = operation
.to_post_update_tracker()?
.update_tracker(
state,
payment_data,
router_data,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
&locale,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
routable_connectors,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
&business_profile,
)
.await?;
if should_trigger_post_processing_flows {
complete_postprocessing_steps_if_required(
state,
merchant_context,
&customer,
&mca,
&connector.connector_data,
&mut payment_data,
op_ref,
Some(header_payload.clone()),
)
.await?;
}
if is_eligible_for_uas {
complete_confirmation_for_click_to_pay_if_required(
state,
merchant_context,
&payment_data,
)
.await?;
}
payment_data
}
ConnectorCallType::Retryable(ref connectors) => {
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
let routable_connectors =
convert_connector_data_to_routable_connectors(connectors)
.map_err(|e| logger::error!(routable_connector_error=?e))
.unwrap_or_default();
let mut connectors = connectors.clone().into_iter();
let (connector_data, routing_decision) =
get_connector_data_with_routing_decision(
&mut connectors,
&business_profile,
debit_routing_output,
)?;
let schedule_time = if should_add_task_to_process_tracker {
payment_sync::get_sync_process_schedule_time(
&*state.store,
connector_data.connector.id(),
merchant_context.get_merchant_account().get_id(),
0,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting process schedule time")?
} else {
None
};
let (merchant_connector_account, router_data, tokenization_action) =
call_connector_service_prerequisites(
state,
merchant_context,
connector_data.clone(),
&operation,
&mut payment_data,
&customer,
&validate_result,
&business_profile,
false,
routing_decision,
)
.await?;
let (router_data, mca) = decide_unified_connector_service_call(
state,
req_state.clone(),
merchant_context,
connector_data.clone(),
&operation,
&mut payment_data,
&customer,
call_connector_action.clone(),
&validate_result,
schedule_time,
header_payload.clone(),
#[cfg(feature = "frm")]
frm_info.as_ref().and_then(|fi| fi.suggested_action),
#[cfg(not(feature = "frm"))]
None,
&business_profile,
false,
<Req as Authenticate>::should_return_raw_response(&req),
merchant_connector_account,
router_data,
tokenization_action,
)
.await?;
#[cfg(all(feature = "retry", feature = "v1"))]
let mut router_data = router_data;
#[cfg(all(feature = "retry", feature = "v1"))]
{
use crate::core::payments::retry::{self, GsmValidation};
let config_bool = retry::config_should_call_gsm(
&*state.store,
merchant_context.get_merchant_account().get_id(),
&business_profile,
)
.await;
if config_bool && router_data.should_call_gsm() {
router_data = retry::do_gsm_actions(
state,
req_state.clone(),
&mut payment_data,
connectors,
&connector_data,
router_data,
merchant_context,
&operation,
&customer,
&validate_result,
schedule_time,
#[cfg(feature = "frm")]
frm_info.as_ref().and_then(|fi| fi.suggested_action),
#[cfg(not(feature = "frm"))]
None,
&business_profile,
)
.await?;
};
}
let op_ref = &operation;
let should_trigger_post_processing_flows = is_operation_confirm(&operation);
let operation = Box::new(PaymentResponse);
connector_http_status_code = router_data.connector_http_status_code;
external_latency = router_data.external_latency;
//add connector http status code metrics
add_connector_http_status_code_metrics(connector_http_status_code);
operation
.to_post_update_tracker()?
.save_pm_and_mandate(
state,
&router_data,
merchant_context,
&mut payment_data,
&business_profile,
)
.await?;
let mut payment_data = operation
.to_post_update_tracker()?
.update_tracker(
state,
payment_data,
router_data,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
&locale,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
routable_connectors,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
&business_profile,
)
.await?;
if should_trigger_post_processing_flows {
complete_postprocessing_steps_if_required(
state,
merchant_context,
&customer,
&mca,
&connector_data,
&mut payment_data,
op_ref,
Some(header_payload.clone()),
)
.await?;
}
if is_eligible_for_uas {
complete_confirmation_for_click_to_pay_if_required(
state,
merchant_context,
&payment_data,
)
.await?;
}
payment_data
}
ConnectorCallType::SessionMultiple(connectors) => {
let session_surcharge_details =
call_surcharge_decision_management_for_session_flow(
state,
merchant_context,
&business_profile,
payment_data.get_payment_attempt(),
payment_data.get_payment_intent(),
payment_data.get_billing_address(),
&connectors,
)
.await?;
Box::pin(call_multiple_connectors_service(
state,
merchant_context,
connectors,
&operation,
payment_data,
&customer,
session_surcharge_details,
&business_profile,
header_payload.clone(),
<Req as Authenticate>::should_return_raw_response(&req),
))
.await?
}
};
#[cfg(feature = "frm")]
if let Some(fraud_info) = &mut frm_info {
#[cfg(feature = "v1")]
Box::pin(frm_core::post_payment_frm_core(
state,
req_state,
merchant_context,
&mut payment_data,
fraud_info,
frm_configs
.clone()
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "frm_configs",
})
.attach_printable("Frm configs label not found")?,
&customer,
&mut should_continue_capture,
))
.await?;
}
} else {
(_, payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
validate_result.storage_scheme,
None,
merchant_context.get_merchant_key_store(),
#[cfg(feature = "frm")]
frm_info.and_then(|info| info.suggested_action),
#[cfg(not(feature = "frm"))]
None,
header_payload.clone(),
)
.await?;
}
let payment_intent_status = payment_data.get_payment_intent().status;
payment_data
.get_payment_attempt()
.payment_token
.as_ref()
.zip(payment_data.get_payment_attempt().payment_method)
.map(ParentPaymentMethodToken::create_key_for_token)
.async_map(|key_for_hyperswitch_token| async move {
if key_for_hyperswitch_token
.should_delete_payment_method_token(payment_intent_status)
{
let _ = key_for_hyperswitch_token.delete(state).await;
}
})
.await;
} else {
(_, payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
validate_result.storage_scheme,
None,
merchant_context.get_merchant_key_store(),
None,
header_payload.clone(),
)
.await?;
}
let cloned_payment_data = payment_data.clone();
let cloned_customer = customer.clone();
#[cfg(feature = "v1")]
operation
.to_domain()?
.store_extended_card_info_temporarily(
state,
payment_data.get_payment_intent().get_id(),
&business_profile,
payment_data.get_payment_method_data(),
)
.await?;
utils::trigger_payments_webhook(
merchant_context.clone(),
business_profile,
cloned_payment_data,
cloned_customer,
state,
operation,
)
.await
.map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error))
.ok();
Ok((
payment_data,
req,
customer,
connector_http_status_code,
external_latency,
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 356,
"total_crates": null
} |
fn_clm_router__connector<F, D>_-1425498721924818589 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments
ync fn decide_connector<F, D>(
state: SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
payment_data: &mut D,
request_straight_through: Option<api::routing::StraightThroughAlgorithm>,
routing_data: &mut storage::RoutingData,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
// If the connector was already decided previously, use the same connector
// This is in case of flows like payments_sync, payments_cancel where the successive operations
// with the connector have to be made using the same connector account.
if let Some(ref connector_name) = payment_data.get_payment_attempt().connector {
// Connector was already decided previously, use the same connector
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
payment_data
.get_payment_attempt()
.merchant_connector_id
.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received in 'routed_through'")?;
routing_data.routed_through = Some(connector_name.clone());
logger::debug!("euclid_routing: predetermined connector present in attempt");
return Ok(ConnectorCallType::PreDetermined(connector_data.into()));
}
if let Some(mandate_connector_details) = payment_data.get_mandate_connector().as_ref() {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&mandate_connector_details.connector,
api::GetToken::Connector,
mandate_connector_details.merchant_connector_id.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received in 'routed_through'")?;
routing_data.routed_through = Some(mandate_connector_details.connector.clone());
routing_data
.merchant_connector_id
.clone_from(&mandate_connector_details.merchant_connector_id);
logger::debug!("euclid_routing: predetermined mandate connector");
return Ok(ConnectorCallType::PreDetermined(connector_data.into()));
}
if let Some((pre_routing_results, storage_pm_type)) =
routing_data.routing_info.pre_routing_results.as_ref().zip(
payment_data
.get_payment_attempt()
.payment_method_type
.as_ref(),
)
{
if let (Some(routable_connector_choice), None) = (
pre_routing_results.get(storage_pm_type),
&payment_data.get_token_data(),
) {
let routable_connector_list = match routable_connector_choice {
storage::PreRoutingConnectorChoice::Single(routable_connector) => {
vec![routable_connector.clone()]
}
storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => {
routable_connector_list.clone()
}
};
let mut pre_routing_connector_data_list = vec![];
let first_routable_connector = routable_connector_list
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
routing_data.routed_through = Some(first_routable_connector.connector.to_string());
routing_data
.merchant_connector_id
.clone_from(&first_routable_connector.merchant_connector_id);
for connector_choice in routable_connector_list.clone() {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_choice.connector.to_string(),
api::GetToken::Connector,
connector_choice.merchant_connector_id.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?
.into();
pre_routing_connector_data_list.push(connector_data);
}
#[cfg(feature = "retry")]
let should_do_retry = retry::config_should_call_gsm(
&*state.store,
merchant_context.get_merchant_account().get_id(),
business_profile,
)
.await;
#[cfg(feature = "retry")]
if payment_data.get_payment_attempt().payment_method_type
== Some(storage_enums::PaymentMethodType::ApplePay)
&& should_do_retry
{
let retryable_connector_data = helpers::get_apple_pay_retryable_connectors(
&state,
merchant_context,
payment_data,
&pre_routing_connector_data_list,
first_routable_connector
.merchant_connector_id
.clone()
.as_ref(),
business_profile.clone(),
)
.await?;
if let Some(connector_data_list) = retryable_connector_data {
if connector_data_list.len() > 1 {
logger::info!("Constructed apple pay retryable connector list");
return Ok(ConnectorCallType::Retryable(connector_data_list));
}
}
}
logger::debug!("euclid_routing: pre-routing connector present");
let first_pre_routing_connector_data_list = pre_routing_connector_data_list
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
helpers::override_setup_future_usage_to_on_session(&*state.store, payment_data).await?;
return Ok(ConnectorCallType::PreDetermined(
first_pre_routing_connector_data_list.clone(),
));
}
}
if let Some(routing_algorithm) = request_straight_through {
let (mut connectors, check_eligibility) = routing::perform_straight_through_routing(
&routing_algorithm,
payment_data.get_creds_identifier(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed execution of straight through routing")?;
payment_data.set_routing_approach_in_attempt(Some(
common_enums::RoutingApproach::StraightThroughRouting,
));
if check_eligibility {
let transaction_data = core_routing::PaymentsDslInput::new(
payment_data.get_setup_mandate(),
payment_data.get_payment_attempt(),
payment_data.get_payment_intent(),
payment_data.get_payment_method_data(),
payment_data.get_address(),
payment_data.get_recurring_details(),
payment_data.get_currency(),
);
connectors = routing::perform_eligibility_analysis_with_fallback(
&state.clone(),
merchant_context.get_merchant_key_store(),
connectors,
&TransactionData::Payment(transaction_data),
eligible_connectors,
business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed eligibility analysis and fallback")?;
}
let connector_data = connectors
.into_iter()
.map(|conn| {
api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&conn.connector.to_string(),
api::GetToken::Connector,
conn.merchant_connector_id.clone(),
)
.map(|connector_data| connector_data.into())
})
.collect::<CustomResult<Vec<_>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
logger::debug!("euclid_routing: straight through connector present");
return decide_multiplex_connector_for_normal_or_recurring_payment(
&state,
payment_data,
routing_data,
connector_data,
mandate_type,
business_profile.is_connector_agnostic_mit_enabled,
business_profile.is_network_tokenization_enabled,
)
.await;
}
if let Some(ref routing_algorithm) = routing_data.routing_info.algorithm {
let (mut connectors, check_eligibility) = routing::perform_straight_through_routing(
routing_algorithm,
payment_data.get_creds_identifier(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed execution of straight through routing")?;
if check_eligibility {
let transaction_data = core_routing::PaymentsDslInput::new(
payment_data.get_setup_mandate(),
payment_data.get_payment_attempt(),
payment_data.get_payment_intent(),
payment_data.get_payment_method_data(),
payment_data.get_address(),
payment_data.get_recurring_details(),
payment_data.get_currency(),
);
connectors = routing::perform_eligibility_analysis_with_fallback(
&state,
merchant_context.get_merchant_key_store(),
connectors,
&TransactionData::Payment(transaction_data),
eligible_connectors,
business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed eligibility analysis and fallback")?;
}
logger::debug!("euclid_routing: single connector present in algorithm data");
let connector_data = connectors
.into_iter()
.map(|conn| {
api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&conn.connector.to_string(),
api::GetToken::Connector,
conn.merchant_connector_id,
)
.map(|connector_data| connector_data.into())
})
.collect::<CustomResult<Vec<_>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
return decide_multiplex_connector_for_normal_or_recurring_payment(
&state,
payment_data,
routing_data,
connector_data,
mandate_type,
business_profile.is_connector_agnostic_mit_enabled,
business_profile.is_network_tokenization_enabled,
)
.await;
}
let new_pd = payment_data.clone();
let transaction_data = core_routing::PaymentsDslInput::new(
new_pd.get_setup_mandate(),
new_pd.get_payment_attempt(),
new_pd.get_payment_intent(),
new_pd.get_payment_method_data(),
new_pd.get_address(),
new_pd.get_recurring_details(),
new_pd.get_currency(),
);
route_connector_v1_for_payments(
&state,
merchant_context,
business_profile,
payment_data,
transaction_data,
routing_data,
eligible_connectors,
mandate_type,
)
.await
}
#[cf
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 254,
"total_crates": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.