id
stringlengths
11
116
type
stringclasses
1 value
granularity
stringclasses
4 values
content
stringlengths
16
477k
metadata
dict
fn_clm_router_t_external_authentication<F: Cl_-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 payment_external_authentication<F: Clone + Sync>( state: SessionState, merchant_context: domain::MerchantContext, req: api_models::payments::PaymentsExternalAuthenticationRequest, ) -> RouterResponse<api_models::payments::PaymentsExternalAuthenticationResponse> { use super::unified_authentication_service::types::ExternalAuthentication; use crate::core::unified_authentication_service::{ types::UnifiedAuthenticationService, utils::external_authentication_update_trackers, }; let db = &*state.store; let key_manager_state = &(&state).into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_id = req.payment_id; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, &attempt_id.clone(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; if payment_attempt.external_three_ds_authentication_attempted != Some(true) { Err(errors::ApiErrorResponse::PreconditionFailed { message: "You cannot authenticate this payment because payment_attempt.external_three_ds_authentication_attempted is false".to_owned(), })? } helpers::validate_payment_status_against_allowed_statuses( payment_intent.status, &[storage_enums::IntentStatus::RequiresCustomerAction], "authenticate", )?; let optional_customer = match &payment_intent.customer_id { Some(customer_id) => Some( state .store .find_customer_by_customer_id_merchant_id( key_manager_state, customer_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("error while finding customer with customer_id {customer_id:?}") })?, ), None => None, }; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount(); let shipping_address = helpers::create_or_find_address_for_payment_by_request( &state, None, payment_intent.shipping_address_id.as_deref(), merchant_id, payment_intent.customer_id.as_ref(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, storage_scheme, ) .await?; let billing_address = helpers::create_or_find_address_for_payment_by_request( &state, None, payment_attempt .payment_method_billing_address_id .as_deref() .or(payment_intent.billing_address_id.as_deref()), merchant_id, payment_intent.customer_id.as_ref(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, storage_scheme, ) .await?; let authentication_connector = payment_attempt .authentication_connector .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("authentication_connector not found in payment_attempt")?; let merchant_connector_account = helpers::get_merchant_connector_account( &state, merchant_id, None, merchant_context.get_merchant_key_store(), profile_id, authentication_connector.as_str(), None, ) .await?; let authentication = db .find_authentication_by_merchant_id_authentication_id( merchant_id, &payment_attempt .authentication_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing authentication_id in payment_attempt")?, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while fetching authentication record")?; let business_profile = state .store .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), profile_id, ) .await .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_method_details = helpers::get_payment_method_details_from_payment_token( &state, &payment_attempt, &payment_intent, merchant_context.get_merchant_key_store(), storage_scheme, ) .await? .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing payment_method_details")?; let browser_info: Option<BrowserInformation> = payment_attempt .browser_info .clone() .map(|browser_information| browser_information.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let payment_connector_name = payment_attempt .connector .as_ref() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing connector in payment_attempt")?; let return_url = Some(helpers::create_authorize_url( &state.base_url, &payment_attempt.clone(), payment_connector_name, )); let mca_id_option = merchant_connector_account.get_mca_id(); // Bind temporary value let merchant_connector_account_id_or_connector_name = mca_id_option .as_ref() .map(|mca_id| mca_id.get_string_repr()) .unwrap_or(&authentication_connector); let webhook_url = helpers::create_webhook_url( &state.base_url, merchant_id, merchant_connector_account_id_or_connector_name, ); let authentication_details = business_profile .authentication_connector_details .clone() .get_required_value("authentication_connector_details") .attach_printable("authentication_connector_details not configured by the merchant")?; let authentication_response = if helpers::is_merchant_eligible_authentication_service( merchant_context.get_merchant_account().get_id(), &state, ) .await? { let auth_response = <ExternalAuthentication as UnifiedAuthenticationService>::authentication( &state, &business_profile, &payment_method_details.1, browser_info, Some(amount), Some(currency), authentication::MessageCategory::Payment, req.device_channel, authentication.clone(), return_url, req.sdk_information, req.threeds_method_comp_ind, optional_customer.and_then(|customer| customer.email.map(pii::Email::from)), webhook_url, &merchant_connector_account, &authentication_connector, Some(payment_intent.payment_id), ) .await?; let authentication = external_authentication_update_trackers( &state, auth_response, authentication.clone(), None, merchant_context.get_merchant_key_store(), None, None, None, None, ) .await?; authentication::AuthenticationResponse::try_from(authentication)? } else { Box::pin(authentication_core::perform_authentication( &state, business_profile.merchant_id, authentication_connector, payment_method_details.0, payment_method_details.1, billing_address .as_ref() .map(|address| address.into()) .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "billing_address", })?, shipping_address.as_ref().map(|address| address.into()), browser_info, merchant_connector_account, Some(amount), Some(currency), authentication::MessageCategory::Payment, req.device_channel, authentication, return_url, req.sdk_information, req.threeds_method_comp_ind, optional_customer.and_then(|customer| customer.email.map(pii::Email::from)), webhook_url, authentication_details.three_ds_requestor_url.clone(), payment_intent.psd2_sca_exemption_type, payment_intent.payment_id, payment_intent.force_3ds_challenge_trigger.unwrap_or(false), merchant_context.get_merchant_key_store(), )) .await? }; Ok(services::ApplicationResponse::Json( api_models::payments::PaymentsExternalAuthenticationResponse { transaction_status: authentication_response.trans_status, acs_url: authentication_response .acs_url .as_ref() .map(ToString::to_string), challenge_request: authentication_response.challenge_request, // If challenge_request_key is None, we send "creq" as a static value which is standard 3DS challenge form field name challenge_request_key: authentication_response .challenge_request_key .or(Some(consts::CREQ_CHALLENGE_REQUEST_KEY.to_string())), acs_reference_number: authentication_response.acs_reference_number, acs_trans_id: authentication_response.acs_trans_id, three_dsserver_trans_id: authentication_response.three_dsserver_trans_id, acs_signed_content: authentication_response.acs_signed_content, three_ds_requestor_url: authentication_details.three_ds_requestor_url, three_ds_requestor_app_url: authentication_details.three_ds_requestor_app_url, }, )) } #[in
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 234, "total_crates": null }
fn_clm_router_ _-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 // Inherent implementation for ilityHandler { ( state: SessionState, merchant_context: domain::MerchantContext, payment_eligibility_data: PaymentEligibilityData, business_profile: domain::Profile, ) -> Self { Self { state, merchant_context, payment_eligibility_data, business_profile, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 191, "total_crates": null }
fn_clm_router_connector_v1_for_payments<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 route_connector_v1_for_payments<F, D>( state: &SessionState, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, payment_data: &mut D, transaction_data: core_routing::PaymentsDslInput<'_>, 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, { let routing_algorithm_id = { let routing_algorithm = business_profile.routing_algorithm.clone(); let algorithm_ref = routing_algorithm .map(|ra| ra.parse_value::<api::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode merchant routing algorithm ref")? .unwrap_or_default(); algorithm_ref.algorithm_id }; let (connectors, routing_approach) = routing::perform_static_routing_v1( state, merchant_context.get_merchant_account().get_id(), routing_algorithm_id.as_ref(), business_profile, &TransactionData::Payment(transaction_data.clone()), ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; payment_data.set_routing_approach_in_attempt(routing_approach); #[cfg(all(feature = "v1", feature = "dynamic_routing"))] let payment_attempt = transaction_data.payment_attempt.clone(); let 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")?; // dynamic success based connector selection #[cfg(all(feature = "v1", feature = "dynamic_routing"))] let connectors = if let Some(algo) = business_profile.dynamic_routing_algorithm.clone() { let dynamic_routing_config: api_models::routing::DynamicRoutingAlgorithmRef = algo .parse_value("DynamicRoutingAlgorithmRef") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?; let dynamic_split = api_models::routing::RoutingVolumeSplit { routing_type: api_models::routing::RoutingType::Dynamic, split: dynamic_routing_config .dynamic_routing_volume_split .unwrap_or_default(), }; let static_split: api_models::routing::RoutingVolumeSplit = api_models::routing::RoutingVolumeSplit { routing_type: api_models::routing::RoutingType::Static, split: consts::DYNAMIC_ROUTING_MAX_VOLUME - dynamic_routing_config .dynamic_routing_volume_split .unwrap_or_default(), }; let volume_split_vec = vec![dynamic_split, static_split]; let routing_choice = routing::perform_dynamic_routing_volume_split(volume_split_vec, None) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to perform volume split on routing type")?; if routing_choice.routing_type.is_dynamic_routing() { if state.conf.open_router.dynamic_routing_enabled { routing::perform_dynamic_routing_with_open_router( state, connectors.clone(), business_profile, payment_attempt, payment_data, ) .await .map_err(|e| logger::error!(open_routing_error=?e)) .unwrap_or(connectors) } else { let dynamic_routing_config_params_interpolator = routing_helpers::DynamicRoutingConfigParamsInterpolator::new( payment_data.get_payment_attempt().payment_method, payment_data.get_payment_attempt().payment_method_type, payment_data.get_payment_attempt().authentication_type, payment_data.get_payment_attempt().currency, payment_data .get_billing_address() .and_then(|address| address.address) .and_then(|address| address.country), payment_data .get_payment_attempt() .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()), payment_data .get_payment_attempt() .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_isin")) .and_then(|card_isin| card_isin.as_str()) .map(|card_isin| card_isin.to_string()), ); routing::perform_dynamic_routing_with_intelligent_router( state, connectors.clone(), business_profile, dynamic_routing_config_params_interpolator, payment_data, ) .await .map_err(|e| logger::error!(dynamic_routing_error=?e)) .unwrap_or(connectors) } } else { connectors } } else { connectors }; 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")?; 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 } #[cf
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 168, "total_crates": null }
fn_clm_router_send_request_to_key_service_for_user_-1668682358098966
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/encryption pub async fn send_request_to_key_service_for_user( state: &SessionState, keys: Vec<UserKeyStore>, ) -> errors::CustomResult<usize, errors::ApiErrorResponse> { futures::future::try_join_all(keys.into_iter().map(|key| async move { let key_encoded = BASE64_ENGINE.encode(key.key.clone().into_inner().expose()); let req = EncryptionTransferRequest { identifier: Identifier::User(key.user_id.clone()), key: key_encoded, }; transfer_key_to_key_manager(&state.into(), req).await })) .await .change_context(errors::ApiErrorResponse::InternalServerError) .map(|v| v.len()) }
{ "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_send_request_to_key_service_for_merchant_-1668682358098966
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/encryption pub async fn send_request_to_key_service_for_merchant( state: &SessionState, keys: Vec<MerchantKeyStore>, ) -> errors::CustomResult<usize, errors::ApiErrorResponse> { let total = keys.len(); for key in keys { let key_encoded = BASE64_ENGINE.encode(key.key.clone().into_inner().expose()); let req = EncryptionTransferRequest { identifier: Identifier::Merchant(key.merchant_id.clone()), key: key_encoded, }; transfer_key_to_key_manager(&state.into(), req) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; } Ok(total) }
{ "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_transfer_encryption_key_-1668682358098966
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/encryption pub async fn transfer_encryption_key( state: &SessionState, req: MerchantKeyTransferRequest, ) -> errors::CustomResult<usize, errors::ApiErrorResponse> { let db = &*state.store; let key_stores = db .get_all_key_stores( &state.into(), &db.get_master_key().to_vec().into(), req.from, req.limit, ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; send_request_to_key_service_for_merchant(state, key_stores).await }
{ "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_submit_evidence_1762239463659967953
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/disputes pub async fn submit_evidence( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, req: dispute_models::SubmitEvidenceRequest, ) -> RouterResponse<dispute_models::DisputeResponse> { let db = &state.store; let dispute = state .store .find_dispute_by_merchant_id_dispute_id( merchant_context.get_merchant_account().get_id(), &req.dispute_id, ) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: req.dispute_id.clone(), })?; core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?; let dispute_id = dispute.dispute_id.clone(); common_utils::fp_utils::when( !core_utils::should_proceed_with_submit_evidence( dispute.dispute_stage, dispute.dispute_status, ), || { metrics::EVIDENCE_SUBMISSION_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC.add(1, &[]); Err(errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: format!( "Evidence cannot be submitted because the dispute is in {} stage and has {} status", dispute.dispute_stage, dispute.dispute_status ), }) }, )?; let submit_evidence_request_data = transformers::get_evidence_request_data(&state, &merchant_context, req, &dispute).await?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &dispute.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &dispute.attempt_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &dispute.connector, api::GetToken::Connector, dispute.merchant_connector_id.clone(), )?; let connector_integration: services::BoxedDisputeConnectorIntegrationInterface< api::Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse, > = connector_data.connector.get_connector_integration(); let router_data = core_utils::construct_submit_evidence_router_data( &state, &payment_intent, &payment_attempt, &merchant_context, &dispute, submit_evidence_request_data, ) .await?; let response = services::execute_connector_processing_step( &state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_dispute_failed_response() .attach_printable("Failed while calling submit evidence connector api")?; let submit_evidence_response = response .response .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: dispute.connector.clone(), status_code: err.status_code, reason: err.reason, })?; //Defend Dispute Optionally if connector expects to defend / submit evidence in a separate api call let (dispute_status, connector_status) = if connector_data .connector_name .requires_defend_dispute() { let connector_integration_defend_dispute: services::BoxedDisputeConnectorIntegrationInterface< api::Defend, DefendDisputeRequestData, DefendDisputeResponse, > = connector_data.connector.get_connector_integration(); let defend_dispute_router_data = core_utils::construct_defend_dispute_router_data( &state, &payment_intent, &payment_attempt, &merchant_context, &dispute, ) .await?; let defend_response = services::execute_connector_processing_step( &state, connector_integration_defend_dispute, &defend_dispute_router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_dispute_failed_response() .attach_printable("Failed while calling defend dispute connector api")?; let defend_dispute_response = defend_response.response.map_err(|err| { errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: dispute.connector.clone(), status_code: err.status_code, reason: err.reason, } })?; ( defend_dispute_response.dispute_status, defend_dispute_response.connector_status, ) } else { ( submit_evidence_response.dispute_status, submit_evidence_response.connector_status, ) }; let update_dispute = diesel_models::dispute::DisputeUpdate::StatusUpdate { dispute_status, connector_status, }; let updated_dispute = db .update_dispute(dispute.clone(), update_dispute) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: dispute_id.to_owned(), }) .attach_printable_lazy(|| { format!("Unable to update dispute with dispute_id: {dispute_id}") })?; let dispute_response = api_models::disputes::DisputeResponse::foreign_from(updated_dispute); Ok(services::ApplicationResponse::Json(dispute_response)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 107, "total_crates": null }
fn_clm_router_retrieve_dispute_1762239463659967953
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/disputes pub async fn retrieve_dispute( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, req: dispute_models::DisputeRetrieveRequest, ) -> RouterResponse<api_models::disputes::DisputeResponse> { let dispute = state .store .find_dispute_by_merchant_id_dispute_id( merchant_context.get_merchant_account().get_id(), &req.dispute_id, ) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: req.dispute_id, })?; core_utils::validate_profile_id_from_auth_layer(profile_id.clone(), &dispute)?; #[cfg(feature = "v1")] let dispute_response = if should_call_connector_for_dispute_sync(req.force_sync, dispute.dispute_status) { let db = &state.store; core_utils::validate_profile_id_from_auth_layer(profile_id.clone(), &dispute)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &dispute.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &dispute.attempt_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &dispute.connector, api::GetToken::Connector, dispute.merchant_connector_id.clone(), )?; let connector_integration: services::BoxedDisputeConnectorIntegrationInterface< api::Dsync, DisputeSyncData, DisputeSyncResponse, > = connector_data.connector.get_connector_integration(); let router_data = core_utils::construct_dispute_sync_router_data( &state, &payment_intent, &payment_attempt, &merchant_context, &dispute, ) .await?; let response = services::execute_connector_processing_step( &state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_dispute_failed_response() .attach_printable("Failed while calling accept dispute connector api")?; let dispute_sync_response = response.response.map_err(|err| { errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: dispute.connector.clone(), status_code: err.status_code, reason: err.reason, } })?; let business_profile = state .store .find_business_profile_by_profile_id( &(&state).into(), merchant_context.get_merchant_key_store(), &payment_attempt.profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: payment_attempt.profile_id.get_string_repr().to_owned(), })?; update_dispute_data( &state, merchant_context, business_profile, Some(dispute.clone()), dispute_sync_response, payment_attempt, dispute.connector.as_str(), ) .await .attach_printable("Dispute update failed")? } else { api_models::disputes::DisputeResponse::foreign_from(dispute) }; #[cfg(not(feature = "v1"))] let dispute_response = api_models::disputes::DisputeResponse::foreign_from(dispute); Ok(services::ApplicationResponse::Json(dispute_response)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 102, "total_crates": null }
fn_clm_router_accept_dispute_1762239463659967953
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/disputes pub async fn accept_dispute( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, req: disputes::DisputeId, ) -> RouterResponse<dispute_models::DisputeResponse> { let db = &state.store; let dispute = state .store .find_dispute_by_merchant_id_dispute_id( merchant_context.get_merchant_account().get_id(), &req.dispute_id, ) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: req.dispute_id, })?; core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?; let dispute_id = dispute.dispute_id.clone(); common_utils::fp_utils::when( !core_utils::should_proceed_with_accept_dispute( dispute.dispute_stage, dispute.dispute_status, ), || { metrics::ACCEPT_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC.add(1, &[]); Err(errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: format!( "This dispute cannot be accepted because the dispute is in {} stage and has {} status", dispute.dispute_stage, dispute.dispute_status ), }) }, )?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &dispute.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &dispute.attempt_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &dispute.connector, api::GetToken::Connector, dispute.merchant_connector_id.clone(), )?; let connector_integration: services::BoxedDisputeConnectorIntegrationInterface< api::Accept, AcceptDisputeRequestData, AcceptDisputeResponse, > = connector_data.connector.get_connector_integration(); let router_data = core_utils::construct_accept_dispute_router_data( &state, &payment_intent, &payment_attempt, &merchant_context, &dispute, ) .await?; let response = services::execute_connector_processing_step( &state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_dispute_failed_response() .attach_printable("Failed while calling accept dispute connector api")?; let accept_dispute_response = response .response .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: dispute.connector.clone(), status_code: err.status_code, reason: err.reason, })?; let update_dispute = diesel_models::dispute::DisputeUpdate::StatusUpdate { dispute_status: accept_dispute_response.dispute_status, connector_status: accept_dispute_response.connector_status.clone(), }; let updated_dispute = db .update_dispute(dispute.clone(), update_dispute) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Unable to update dispute with dispute_id: {dispute_id}") })?; let dispute_response = api_models::disputes::DisputeResponse::foreign_from(updated_dispute); Ok(services::ApplicationResponse::Json(dispute_response)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 87, "total_crates": null }
fn_clm_router_fetch_disputes_from_connector_1762239463659967953
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/disputes pub async fn fetch_disputes_from_connector( state: SessionState, merchant_context: domain::MerchantContext, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, req: FetchDisputesRequestData, ) -> RouterResponse<FetchDisputesResponse> { let db = &*state.store; let key_manager_state = &(&state).into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let merchant_connector_account = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, &merchant_connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), })?; let connector_name = merchant_connector_account.connector_name.clone(); let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_name, api::GetToken::Connector, Some(merchant_connector_id.clone()), )?; let connector_integration: services::BoxedDisputeConnectorIntegrationInterface< api::Fetch, FetchDisputesRequestData, FetchDisputesResponse, > = connector_data.connector.get_connector_integration(); let router_data = core_utils::construct_dispute_list_router_data(&state, merchant_connector_account, req) .await?; let response = services::execute_connector_processing_step( &state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_dispute_failed_response() .attach_printable("Failed while calling accept dispute connector api")?; let fetch_dispute_response = response .response .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: connector_name.clone(), status_code: err.status_code, reason: err.reason, })?; for dispute in &fetch_dispute_response { // check if payment already exist let payment_attempt = webhooks::incoming::get_payment_attempt_from_object_reference_id( &state, dispute.object_reference_id.clone(), &merchant_context, ) .await; if payment_attempt.is_ok() { let schedule_time = process_dispute::get_sync_process_schedule_time( &*state.store, &connector_name, merchant_id, 0, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting process schedule time")?; let response = add_process_dispute_task_to_pt( db, &connector_name, dispute, merchant_id.clone(), schedule_time, ) .await; match response { Err(report) if report .downcast_ref::<errors::StorageError>() .is_some_and(|error| { matches!(error, errors::StorageError::DuplicateValue { .. }) }) => { Ok(()) } Ok(_) => Ok(()), Err(_) => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while adding task to process tracker"), }?; } else { router_env::logger::info!("Disputed payment does not exist in our records"); } } Ok(services::ApplicationResponse::Json(fetch_dispute_response)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 74, "total_crates": null }
fn_clm_router_attach_evidence_1762239463659967953
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/disputes pub async fn attach_evidence( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, attach_evidence_request: api::AttachEvidenceRequest, ) -> RouterResponse<files_api_models::CreateFileResponse> { let db = &state.store; let dispute_id = attach_evidence_request .create_file_request .dispute_id .clone() .ok_or(errors::ApiErrorResponse::MissingDisputeId)?; let dispute = db .find_dispute_by_merchant_id_dispute_id( merchant_context.get_merchant_account().get_id(), &dispute_id, ) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: dispute_id.clone(), })?; core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?; common_utils::fp_utils::when( !(dispute.dispute_stage == storage_enums::DisputeStage::Dispute && dispute.dispute_status == storage_enums::DisputeStatus::DisputeOpened), || { metrics::ATTACH_EVIDENCE_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC.add(1, &[]); Err(errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: format!( "Evidence cannot be attached because the dispute is in {} stage and has {} status", dispute.dispute_stage, dispute.dispute_status ), }) }, )?; let create_file_response = Box::pin(files::files_create_core( state.clone(), merchant_context, attach_evidence_request.create_file_request, )) .await?; let file_id = match &create_file_response { services::ApplicationResponse::Json(res) => res.file_id.clone(), _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response received from files create core")?, }; let dispute_evidence: api::DisputeEvidence = dispute .evidence .clone() .parse_value("DisputeEvidence") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing dispute evidence record")?; let updated_dispute_evidence = transformers::update_dispute_evidence( dispute_evidence, attach_evidence_request.evidence_type, file_id, ); let update_dispute = diesel_models::dispute::DisputeUpdate::EvidenceUpdate { evidence: updated_dispute_evidence .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while encoding dispute evidence")? .into(), }; db.update_dispute(dispute, update_dispute) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: dispute_id.to_owned(), }) .attach_printable_lazy(|| { format!("Unable to update dispute with dispute_id: {dispute_id}") })?; Ok(create_file_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_foreign_try_from_3072341820160532237
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/unified_authentication_service // Implementation of AuthenticationAuthenticateResponse for ForeignTryFrom<( &Authentication, Option<masking::Secret<String>>, Option<String>, diesel_models::business_profile::AuthenticationConnectorDetails, )> fn foreign_try_from( (authentication, authentication_value, eci, authentication_details): ( &Authentication, Option<masking::Secret<String>>, Option<String>, diesel_models::business_profile::AuthenticationConnectorDetails, ), ) -> Result<Self, Self::Error> { let authentication_connector = authentication .authentication_connector .as_ref() .map(|connector| common_enums::AuthenticationConnectors::from_str(connector)) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Incorrect authentication connector stored in table")?; let acs_url = authentication .acs_url .clone() .map(|acs_url| url::Url::parse(&acs_url)) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse the url with param")?; let acquirer_details = AcquirerDetails { acquirer_bin: authentication.acquirer_bin.clone(), acquirer_merchant_id: authentication.acquirer_merchant_id.clone(), merchant_country_code: authentication.acquirer_country_code.clone(), }; Ok(Self { transaction_status: authentication.trans_status.clone(), acs_url, challenge_request: authentication.challenge_request.clone(), acs_reference_number: authentication.acs_reference_number.clone(), acs_trans_id: authentication.acs_trans_id.clone(), three_ds_server_transaction_id: authentication.threeds_server_transaction_id.clone(), acs_signed_content: authentication.acs_signed_content.clone(), three_ds_requestor_url: authentication_details.three_ds_requestor_url.clone(), three_ds_requestor_app_url: authentication_details.three_ds_requestor_app_url.clone(), error_code: None, error_message: authentication.error_message.clone(), authentication_value, status: authentication.authentication_status, authentication_connector, eci, authentication_id: authentication.authentication_id.clone(), acquirer_details: Some(acquirer_details), }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 478, "total_crates": null }
fn_clm_router_authentication_eligibility_core_3072341820160532237
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/unified_authentication_service pub async fn authentication_eligibility_core( state: SessionState, merchant_context: domain::MerchantContext, req: AuthenticationEligibilityRequest, authentication_id: common_utils::id_type::AuthenticationId, ) -> RouterResponse<AuthenticationEligibilityResponse> { let merchant_account = merchant_context.get_merchant_account(); let merchant_id = merchant_account.get_id(); let db = &*state.store; let authentication = db .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id) .await .to_not_found_response(ApiErrorResponse::AuthenticationNotFound { id: authentication_id.get_string_repr().to_owned(), })?; req.client_secret .clone() .map(|client_secret| { utils::authenticate_authentication_client_secret_and_check_expiry( client_secret.peek(), &authentication, ) }) .transpose()?; ensure_not_terminal_status(authentication.trans_status.clone())?; let key_manager_state = (&state).into(); let profile_id = core_utils::get_profile_id_from_business_details( &key_manager_state, None, None, &merchant_context, req.profile_id.as_ref(), db, true, ) .await?; let business_profile = db .find_business_profile_by_profile_id( &key_manager_state, merchant_context.get_merchant_key_store(), &profile_id, ) .await .to_not_found_response(ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let (authentication_connector, three_ds_connector_account) = auth_utils::get_authentication_connector_data( &state, merchant_context.get_merchant_key_store(), &business_profile, authentication.authentication_connector.clone(), ) .await?; let notification_url = match authentication_connector { common_enums::AuthenticationConnectors::Juspaythreedsserver => { Some(url::Url::parse(&format!( "{base_url}/authentication/{merchant_id}/{authentication_id}/redirect", base_url = state.base_url, merchant_id = merchant_id.get_string_repr(), authentication_id = authentication_id.get_string_repr() ))) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse notification url")? } _ => authentication .return_url .as_ref() .map(|url| url::Url::parse(url)) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse return url")?, }; let authentication_connector_name = authentication_connector.to_string(); let payment_method_data = domain::PaymentMethodData::from(req.payment_method_data.clone()); let amount = authentication .amount .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("no amount found in authentication table")?; let acquirer_details = authentication .profile_acquirer_id .clone() .and_then(|acquirer_id| { business_profile .acquirer_config_map .and_then(|acquirer_config_map| acquirer_config_map.0.get(&acquirer_id).cloned()) }); let metadata: Option<ThreeDsMetaData> = three_ds_connector_account .get_metadata() .map(|metadata| { metadata.expose().parse_value("ThreeDsMetaData").inspect_err(|err| { router_env::logger::warn!(parsing_error=?err,"Error while parsing ThreeDsMetaData"); }) }) .transpose() .change_context(ApiErrorResponse::InternalServerError)?; let merchant_country_code = authentication.acquirer_country_code.clone(); let merchant_details = Some(hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails { merchant_id: Some(authentication.merchant_id.get_string_repr().to_string()), merchant_name: acquirer_details.clone().map(|detail| detail.merchant_name.clone()).or(metadata.clone().and_then(|metadata| metadata.merchant_name)), merchant_category_code: business_profile.merchant_category_code.or(metadata.clone().and_then(|metadata| metadata.merchant_category_code)), endpoint_prefix: metadata.clone().and_then(|metadata| metadata.endpoint_prefix), three_ds_requestor_url: business_profile.authentication_connector_details.map(|details| details.three_ds_requestor_url), three_ds_requestor_id: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_id), three_ds_requestor_name: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_name), merchant_country_code: merchant_country_code.map(common_types::payments::MerchantCountryCode::new), notification_url, }); let domain_address = req .billing .clone() .map(hyperswitch_domain_models::address::Address::from); let pre_auth_response = <ExternalAuthentication as UnifiedAuthenticationService>::pre_authentication( &state, merchant_id, None, Some(&payment_method_data), req.payment_method_type, &three_ds_connector_account, &authentication_connector_name, &authentication_id, req.payment_method, amount, authentication.currency, None, merchant_details.as_ref(), domain_address.as_ref(), authentication.acquirer_bin.clone(), authentication.acquirer_merchant_id.clone(), ) .await?; let billing_details_encoded = req .billing .clone() .map(|billing| { common_utils::ext_traits::Encode::encode_to_value(&billing) .map(masking::Secret::<serde_json::Value>::new) }) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encode billing details to serde_json::Value")?; let shipping_details_encoded = req .shipping .clone() .map(|shipping| { common_utils::ext_traits::Encode::encode_to_value(&shipping) .map(masking::Secret::<serde_json::Value>::new) }) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encode shipping details to serde_json::Value")?; let encrypted_data = domain::types::crypto_operation( &key_manager_state, common_utils::type_name!(hyperswitch_domain_models::authentication::Authentication), domain::types::CryptoOperation::BatchEncrypt( hyperswitch_domain_models::authentication::UpdateEncryptableAuthentication::to_encryptable( hyperswitch_domain_models::authentication::UpdateEncryptableAuthentication { billing_address: billing_details_encoded, shipping_address: shipping_details_encoded, }, ), ), common_utils::types::keymanager::Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt authentication data".to_string())?; let encrypted_data = hyperswitch_domain_models::authentication::FromRequestEncryptableAuthentication::from_encryptable(encrypted_data) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to get encrypted data for authentication after encryption")?; let email_encrypted = req .email .clone() .async_lift(|inner| async { domain::types::crypto_operation( &key_manager_state, common_utils::type_name!(Authentication), domain::types::CryptoOperation::EncryptOptional(inner.map(|inner| inner.expose())), common_utils::types::keymanager::Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt email")?; let browser_info = req .browser_information .as_ref() .map(common_utils::ext_traits::Encode::encode_to_value) .transpose() .change_context(ApiErrorResponse::InvalidDataValue { field_name: "browser_information", })?; let updated_authentication = utils::external_authentication_update_trackers( &state, pre_auth_response, authentication.clone(), None, merchant_context.get_merchant_key_store(), encrypted_data .billing_address .map(common_utils::encryption::Encryption::from), encrypted_data .shipping_address .map(common_utils::encryption::Encryption::from), email_encrypted .clone() .map(common_utils::encryption::Encryption::from), browser_info, ) .await?; let response = AuthenticationEligibilityResponse::foreign_try_from(( updated_authentication, req.get_next_action_api( state.base_url, authentication_id.get_string_repr().to_string(), ) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to get next action api")?, profile_id, req.get_billing_address(), req.get_shipping_address(), req.get_browser_information(), email_encrypted, ))?; Ok(hyperswitch_domain_models::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": 301, "total_crates": null }
fn_clm_router_authentication_sync_core_3072341820160532237
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/unified_authentication_service pub async fn authentication_sync_core( state: SessionState, merchant_context: domain::MerchantContext, auth_flow: AuthFlow, req: AuthenticationSyncRequest, ) -> RouterResponse<AuthenticationSyncResponse> { let authentication_id = req.authentication_id; let merchant_account = merchant_context.get_merchant_account(); let merchant_id = merchant_account.get_id(); let db = &*state.store; let authentication = db .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id) .await .to_not_found_response(ApiErrorResponse::AuthenticationNotFound { id: authentication_id.get_string_repr().to_owned(), })?; req.client_secret .map(|client_secret| { utils::authenticate_authentication_client_secret_and_check_expiry( client_secret.peek(), &authentication, ) }) .transpose()?; let key_manager_state = (&state).into(); let profile_id = authentication.profile_id.clone(); let business_profile = db .find_business_profile_by_profile_id( &key_manager_state, merchant_context.get_merchant_key_store(), &profile_id, ) .await .to_not_found_response(ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let (authentication_connector, three_ds_connector_account) = auth_utils::get_authentication_connector_data( &state, merchant_context.get_merchant_key_store(), &business_profile, authentication.authentication_connector.clone(), ) .await?; let updated_authentication = match authentication.trans_status.clone() { Some(trans_status) if trans_status.clone().is_pending() => { let post_auth_response = ExternalAuthentication::post_authentication( &state, &business_profile, None, &three_ds_connector_account, &authentication_connector.to_string(), &authentication_id, common_enums::PaymentMethod::Card, merchant_id, Some(&authentication), ) .await?; utils::external_authentication_update_trackers( &state, post_auth_response, authentication.clone(), None, merchant_context.get_merchant_key_store(), None, None, None, None, ) .await? } _ => authentication, }; let (authentication_value, eci) = match auth_flow { AuthFlow::Client => (None, None), AuthFlow::Merchant => { if let Some(common_enums::TransactionStatus::Success) = updated_authentication.trans_status { let tokenised_data = crate::core::payment_methods::vault::get_tokenized_data( &state, authentication_id.get_string_repr(), false, merchant_context.get_merchant_key_store().key.get_inner(), ) .await .inspect_err(|err| router_env::logger::error!(tokenized_data_result=?err)) .attach_printable("cavv not present after authentication status is success")?; ( Some(masking::Secret::new(tokenised_data.value1)), updated_authentication.eci.clone(), ) } else { (None, None) } } }; let acquirer_details = Some(AcquirerDetails { acquirer_bin: updated_authentication.acquirer_bin.clone(), acquirer_merchant_id: updated_authentication.acquirer_merchant_id.clone(), merchant_country_code: updated_authentication.acquirer_country_code.clone(), }); let encrypted_data = domain::types::crypto_operation( &key_manager_state, common_utils::type_name!(hyperswitch_domain_models::authentication::Authentication), domain::types::CryptoOperation::BatchDecrypt( hyperswitch_domain_models::authentication::EncryptedAuthentication::to_encryptable( hyperswitch_domain_models::authentication::EncryptedAuthentication { billing_address: updated_authentication.billing_address, shipping_address: updated_authentication.shipping_address, }, ), ), common_utils::types::keymanager::Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt authentication data".to_string())?; let encrypted_data = hyperswitch_domain_models::authentication::FromRequestEncryptableAuthentication::from_encryptable(encrypted_data) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to get encrypted data for authentication after encryption")?; let email_decrypted = updated_authentication .email .clone() .async_lift(|inner| async { domain::types::crypto_operation( &key_manager_state, common_utils::type_name!(Authentication), domain::types::CryptoOperation::DecryptOptional(inner), common_utils::types::keymanager::Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt email")?; let browser_info = updated_authentication .browser_info .clone() .map(|browser_info| { browser_info.parse_value::<payments::BrowserInformation>("BrowserInformation") }) .transpose() .change_context(ApiErrorResponse::InternalServerError)?; let amount = updated_authentication .amount .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("amount failed to get amount from authentication table")?; let currency = updated_authentication .currency .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("currency failed to get currency from authentication table")?; let authentication_connector = updated_authentication .authentication_connector .map(|connector| common_enums::AuthenticationConnectors::from_str(&connector)) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Incorrect authentication connector stored in table")?; let billing = encrypted_data .billing_address .map(|billing| { billing .into_inner() .expose() .parse_value::<payments::Address>("Address") }) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse billing address")?; let shipping = encrypted_data .shipping_address .map(|shipping| { shipping .into_inner() .expose() .parse_value::<payments::Address>("Address") }) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse shipping address")?; let response = AuthenticationSyncResponse { authentication_id: authentication_id.clone(), merchant_id: merchant_id.clone(), status: updated_authentication.authentication_status, client_secret: updated_authentication .authentication_client_secret .map(masking::Secret::new), amount, currency, authentication_connector, force_3ds_challenge: updated_authentication.force_3ds_challenge, return_url: updated_authentication.return_url.clone(), created_at: updated_authentication.created_at, profile_id: updated_authentication.profile_id.clone(), psd2_sca_exemption_type: updated_authentication.psd2_sca_exemption_type, acquirer_details, error_message: updated_authentication.error_message.clone(), error_code: updated_authentication.error_code.clone(), authentication_value, threeds_server_transaction_id: updated_authentication.threeds_server_transaction_id.clone(), maximum_supported_3ds_version: updated_authentication.maximum_supported_version.clone(), connector_authentication_id: updated_authentication.connector_authentication_id.clone(), three_ds_method_data: updated_authentication.three_ds_method_data.clone(), three_ds_method_url: updated_authentication.three_ds_method_url.clone(), message_version: updated_authentication.message_version.clone(), connector_metadata: updated_authentication.connector_metadata.clone(), directory_server_id: updated_authentication.directory_server_id.clone(), billing, shipping, browser_information: browser_info, email: email_decrypted, transaction_status: updated_authentication.trans_status.clone(), acs_url: updated_authentication.acs_url.clone(), challenge_request: updated_authentication.challenge_request.clone(), acs_reference_number: updated_authentication.acs_reference_number.clone(), acs_trans_id: updated_authentication.acs_trans_id.clone(), acs_signed_content: updated_authentication.acs_signed_content, three_ds_requestor_url: business_profile .authentication_connector_details .clone() .map(|details| details.three_ds_requestor_url), three_ds_requestor_app_url: business_profile .authentication_connector_details .and_then(|details| details.three_ds_requestor_app_url), profile_acquirer_id: updated_authentication.profile_acquirer_id.clone(), eci, }; Ok(hyperswitch_domain_models::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": 249, "total_crates": null }
fn_clm_router_authentication_authenticate_core_3072341820160532237
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/unified_authentication_service pub async fn authentication_authenticate_core( state: SessionState, merchant_context: domain::MerchantContext, req: AuthenticationAuthenticateRequest, auth_flow: AuthFlow, ) -> RouterResponse<AuthenticationAuthenticateResponse> { let authentication_id = req.authentication_id.clone(); let merchant_account = merchant_context.get_merchant_account(); let merchant_id = merchant_account.get_id(); let db = &*state.store; let authentication = db .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id) .await .to_not_found_response(ApiErrorResponse::AuthenticationNotFound { id: authentication_id.get_string_repr().to_owned(), })?; req.client_secret .map(|client_secret| { utils::authenticate_authentication_client_secret_and_check_expiry( client_secret.peek(), &authentication, ) }) .transpose()?; ensure_not_terminal_status(authentication.trans_status.clone())?; let key_manager_state = (&state).into(); let profile_id = authentication.profile_id.clone(); let business_profile = db .find_business_profile_by_profile_id( &key_manager_state, merchant_context.get_merchant_key_store(), &profile_id, ) .await .to_not_found_response(ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let email_encrypted = authentication .email .clone() .async_lift(|inner| async { domain::types::crypto_operation( &key_manager_state, common_utils::type_name!(Authentication), domain::types::CryptoOperation::DecryptOptional(inner), common_utils::types::keymanager::Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to decrypt email from authentication table")?; let browser_info = authentication .browser_info .clone() .map(|browser_info| browser_info.parse_value::<BrowserInformation>("BrowserInformation")) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse browser information from authentication table")?; let (authentication_connector, three_ds_connector_account) = auth_utils::get_authentication_connector_data( &state, merchant_context.get_merchant_key_store(), &business_profile, authentication.authentication_connector.clone(), ) .await?; let authentication_details = business_profile .authentication_connector_details .clone() .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("authentication_connector_details not configured by the merchant")?; let connector_name_string = authentication_connector.to_string(); let mca_id_option = three_ds_connector_account.get_mca_id(); let merchant_connector_account_id_or_connector_name = mca_id_option .as_ref() .map(|mca_id| mca_id.get_string_repr()) .unwrap_or(&connector_name_string); let webhook_url = helpers::create_webhook_url( &state.base_url, merchant_id, merchant_connector_account_id_or_connector_name, ); let auth_response = <ExternalAuthentication as UnifiedAuthenticationService>::authentication( &state, &business_profile, &common_enums::PaymentMethod::Card, browser_info, authentication.amount, authentication.currency, MessageCategory::Payment, req.device_channel, authentication.clone(), None, req.sdk_information, req.threeds_method_comp_ind, email_encrypted.map(common_utils::pii::Email::from), webhook_url, &three_ds_connector_account, &authentication_connector.to_string(), None, ) .await?; let authentication = utils::external_authentication_update_trackers( &state, auth_response, authentication.clone(), None, merchant_context.get_merchant_key_store(), None, None, None, None, ) .await?; let (authentication_value, eci) = match auth_flow { AuthFlow::Client => (None, None), AuthFlow::Merchant => { if let Some(common_enums::TransactionStatus::Success) = authentication.trans_status { let tokenised_data = crate::core::payment_methods::vault::get_tokenized_data( &state, authentication_id.get_string_repr(), false, merchant_context.get_merchant_key_store().key.get_inner(), ) .await .inspect_err(|err| router_env::logger::error!(tokenized_data_result=?err)) .attach_printable("cavv not present after authentication status is success")?; ( Some(masking::Secret::new(tokenised_data.value1)), authentication.eci.clone(), ) } else { (None, None) } } }; let response = AuthenticationAuthenticateResponse::foreign_try_from(( &authentication, authentication_value, eci, authentication_details, ))?; Ok(hyperswitch_domain_models::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": 149, "total_crates": null }
fn_clm_router_authentication_create_core_3072341820160532237
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/unified_authentication_service pub async fn authentication_create_core( state: SessionState, merchant_context: domain::MerchantContext, req: AuthenticationCreateRequest, ) -> RouterResponse<AuthenticationResponse> { let db = &*state.store; let merchant_account = merchant_context.get_merchant_account(); let merchant_id = merchant_account.get_id(); let key_manager_state = (&state).into(); let profile_id = core_utils::get_profile_id_from_business_details( &key_manager_state, None, None, &merchant_context, req.profile_id.as_ref(), db, true, ) .await?; let business_profile = db .find_business_profile_by_profile_id( &key_manager_state, merchant_context.get_merchant_key_store(), &profile_id, ) .await .to_not_found_response(ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let organization_id = merchant_account.organization_id.clone(); let authentication_id = common_utils::id_type::AuthenticationId::generate_authentication_id( consts::AUTHENTICATION_ID_PREFIX, ); let force_3ds_challenge = Some( req.force_3ds_challenge .unwrap_or(business_profile.force_3ds_challenge), ); // Priority logic: First check req.acquirer_details, then fallback to profile_acquirer_id lookup let (acquirer_bin, acquirer_merchant_id, acquirer_country_code) = if let Some(acquirer_details) = &req.acquirer_details { // Priority 1: Use acquirer_details from request if present ( acquirer_details.acquirer_bin.clone(), acquirer_details.acquirer_merchant_id.clone(), acquirer_details.merchant_country_code.clone(), ) } else { // Priority 2: Fallback to profile_acquirer_id lookup let acquirer_details = req.profile_acquirer_id.clone().and_then(|acquirer_id| { business_profile .acquirer_config_map .and_then(|acquirer_config_map| { acquirer_config_map.0.get(&acquirer_id).cloned() }) }); acquirer_details .as_ref() .map(|details| { ( Some(details.acquirer_bin.clone()), Some(details.acquirer_assigned_merchant_id.clone()), business_profile .merchant_country_code .map(|code| code.get_country_code().to_owned()), ) }) .unwrap_or((None, None, None)) }; let new_authentication = create_new_authentication( &state, merchant_id.clone(), req.authentication_connector .map(|connector| connector.to_string()), profile_id.clone(), None, None, &authentication_id, None, common_enums::AuthenticationStatus::Started, None, organization_id, force_3ds_challenge, req.psd2_sca_exemption_type, acquirer_bin, acquirer_merchant_id, acquirer_country_code, Some(req.amount), Some(req.currency), req.return_url, req.profile_acquirer_id.clone(), ) .await?; let acquirer_details = Some(AcquirerDetails { acquirer_bin: new_authentication.acquirer_bin.clone(), acquirer_merchant_id: new_authentication.acquirer_merchant_id.clone(), merchant_country_code: new_authentication.acquirer_country_code.clone(), }); let amount = new_authentication .amount .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("amount failed to get amount from authentication table")?; let currency = new_authentication .currency .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("currency failed to get currency from authentication table")?; let response = AuthenticationResponse::foreign_try_from(( new_authentication.clone(), amount, currency, profile_id, acquirer_details, new_authentication.profile_acquirer_id, ))?; Ok(hyperswitch_domain_models::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": 103, "total_crates": null }
fn_clm_router_add_entry_to_blocklist_-1093982227785358990
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/blocklist pub async fn add_entry_to_blocklist( state: SessionState, merchant_context: domain::MerchantContext, body: api_blocklist::AddToBlocklistRequest, ) -> RouterResponse<api_blocklist::AddToBlocklistResponse> { utils::insert_entry_into_blocklist( &state, merchant_context.get_merchant_account().get_id(), body, ) .await .map(services::ApplicationResponse::Json) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 21, "total_crates": null }
fn_clm_router_remove_entry_from_blocklist_-1093982227785358990
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/blocklist pub async fn remove_entry_from_blocklist( state: SessionState, merchant_context: domain::MerchantContext, body: api_blocklist::DeleteFromBlocklistRequest, ) -> RouterResponse<api_blocklist::DeleteFromBlocklistResponse> { utils::delete_entry_from_blocklist( &state, merchant_context.get_merchant_account().get_id(), body, ) .await .map(services::ApplicationResponse::Json) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 21, "total_crates": null }
fn_clm_router_list_blocklist_entries_-1093982227785358990
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/blocklist pub async fn list_blocklist_entries( state: SessionState, merchant_context: domain::MerchantContext, query: api_blocklist::ListBlocklistQuery, ) -> RouterResponse<Vec<api_blocklist::BlocklistResponse>> { utils::list_blocklist_entries_for_merchant( &state, merchant_context.get_merchant_account().get_id(), query, ) .await .map(services::ApplicationResponse::Json) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 21, "total_crates": null }
fn_clm_router_toggle_blocklist_guard_-1093982227785358990
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/blocklist pub async fn toggle_blocklist_guard( state: SessionState, merchant_context: domain::MerchantContext, query: api_blocklist::ToggleBlocklistQuery, ) -> RouterResponse<api_blocklist::ToggleBlocklistResponse> { utils::toggle_blocklist_guard_for_merchant( &state, merchant_context.get_merchant_account().get_id(), query, ) .await .map(services::ApplicationResponse::Json) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 21, "total_crates": null }
fn_clm_router_list_user_roles_details_4183922362388472259
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/user pub async fn list_user_roles_details( state: SessionState, user_from_token: auth::UserFromToken, request: user_api::GetUserRoleDetailsRequest, _req_state: ReqState, ) -> UserResponse<Vec<user_api::GetUserRoleDetailsResponseV2>> { let required_user = utils::user::get_user_from_db_by_email(&state, request.email.try_into()?) .await .to_not_found_response(UserErrors::InvalidRoleOperation)?; let requestor_role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .to_not_found_response(UserErrors::InternalServerError) .attach_printable("Failed to fetch role info")?; if requestor_role_info.is_internal() { return Err(UserErrors::InvalidRoleOperationWithMessage( "Internal roles are not allowed for this operation".to_string(), ) .into()); } let user_roles_set = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: required_user.get_user_id(), tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: Some(&user_from_token.org_id), merchant_id: (requestor_role_info.get_entity_type() <= EntityType::Merchant) .then_some(&user_from_token.merchant_id), profile_id: (requestor_role_info.get_entity_type() <= EntityType::Profile) .then_some(&user_from_token.profile_id), entity_id: None, version: None, status: None, limit: None, }) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to fetch user roles")? .into_iter() .collect::<HashSet<_>>(); let org_name = state .accounts_store .find_organization_by_org_id(&user_from_token.org_id) .await .change_context(UserErrors::InternalServerError) .attach_printable("Org id not found")? .get_organization_name(); let org = NameIdUnit { id: user_from_token.org_id.clone(), name: org_name, }; let (merchant_ids, merchant_profile_ids) = user_roles_set.iter().try_fold( (Vec::new(), Vec::new()), |(mut merchant, mut merchant_profile), user_role| { let (_, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError) .attach_printable("Failed to compute entity id and type")?; match entity_type { EntityType::Merchant => { let merchant_id = user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError) .attach_printable( "Merchant id not found in user role for merchant level entity", )?; merchant.push(merchant_id) } EntityType::Profile => { let merchant_id = user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError) .attach_printable( "Merchant id not found in user role for merchant level entity", )?; let profile_id = user_role .profile_id .clone() .ok_or(UserErrors::InternalServerError) .attach_printable( "Profile id not found in user role for profile level entity", )?; merchant.push(merchant_id.clone()); merchant_profile.push((merchant_id, profile_id)) } EntityType::Tenant | EntityType::Organization => (), }; Ok::<_, error_stack::Report<UserErrors>>((merchant, merchant_profile)) }, )?; let merchant_map = state .store .list_multiple_merchant_accounts(&(&state).into(), merchant_ids) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while listing merchant accounts")? .into_iter() .map(|merchant_account| { ( merchant_account.get_id().to_owned(), merchant_account.merchant_name.clone(), ) }) .collect::<HashMap<_, _>>(); let key_manager_state = &(&state).into(); let profile_map = futures::future::try_join_all(merchant_profile_ids.iter().map( |merchant_profile_id| async { let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_profile_id.0, &state.store.get_master_key().to_vec().into(), ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve merchant key store by merchant_id")?; state .store .find_business_profile_by_profile_id( key_manager_state, &merchant_key_store, &merchant_profile_id.1, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve business profile") }, )) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to construct profile map")? .into_iter() .map(|profile| (profile.get_id().to_owned(), profile.profile_name)) .collect::<HashMap<_, _>>(); let role_name_map = futures::future::try_join_all( user_roles_set .iter() .map(|user_role| user_role.role_id.clone()) .collect::<HashSet<_>>() .into_iter() .map(|role_id| async { let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; Ok::<_, error_stack::Report<_>>((role_id, role_info.get_role_name().to_string())) }), ) .await? .into_iter() .collect::<HashMap<_, _>>(); let role_details_list: Vec<_> = user_roles_set .iter() .map(|user_role| { let (_, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; let (merchant, profile) = match entity_type { EntityType::Tenant | EntityType::Organization => (None, None), EntityType::Merchant => { let merchant_id = &user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError)?; ( Some(NameIdUnit { id: merchant_id.clone(), name: merchant_map .get(merchant_id) .ok_or(UserErrors::InternalServerError)? .to_owned(), }), None, ) } EntityType::Profile => { let merchant_id = &user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError)?; let profile_id = &user_role .profile_id .clone() .ok_or(UserErrors::InternalServerError)?; ( Some(NameIdUnit { id: merchant_id.clone(), name: merchant_map .get(merchant_id) .ok_or(UserErrors::InternalServerError)? .to_owned(), }), Some(NameIdUnit { id: profile_id.clone(), name: profile_map .get(profile_id) .ok_or(UserErrors::InternalServerError)? .to_owned(), }), ) } }; Ok(user_api::GetUserRoleDetailsResponseV2 { role_id: user_role.role_id.clone(), org: org.clone(), merchant, profile, status: user_role.status.foreign_into(), entity_type, role_name: role_name_map .get(&user_role.role_id) .ok_or(UserErrors::InternalServerError) .cloned()?, }) }) .collect::<Result<Vec<_>, UserErrors>>()?; Ok(ApplicationResponse::Json(role_details_list)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 246, "total_crates": null }
fn_clm_router_handle_existing_user_invitation_4183922362388472259
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/user async fn handle_existing_user_invitation( state: &SessionState, user_from_token: &auth::UserFromToken, request: &user_api::InviteUserRequest, invitee_user_from_db: domain::UserFromStorage, role_info: roles::RoleInfo, auth_id: &Option<String>, ) -> UserResult<InviteMultipleUserResponse> { let now = common_utils::date_time::now(); if state .global_store .find_user_role_by_user_id_and_lineage( invitee_user_from_db.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V1, ) .await .is_err_and(|err| err.current_context().is_db_not_found()) .not() { return Err(UserErrors::UserExists.into()); } if state .global_store .find_user_role_by_user_id_and_lineage( invitee_user_from_db.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V2, ) .await .is_err_and(|err| err.current_context().is_db_not_found()) .not() { return Err(UserErrors::UserExists.into()); } let (org_id, merchant_id, profile_id) = match role_info.get_entity_type() { EntityType::Tenant => { return Err(UserErrors::InvalidRoleOperationWithMessage( "Tenant roles are not allowed for this operation".to_string(), ) .into()); } EntityType::Organization => (Some(&user_from_token.org_id), None, None), EntityType::Merchant => ( Some(&user_from_token.org_id), Some(&user_from_token.merchant_id), None, ), EntityType::Profile => ( Some(&user_from_token.org_id), Some(&user_from_token.merchant_id), Some(&user_from_token.profile_id), ), }; if state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: invitee_user_from_db.get_user_id(), tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id, merchant_id, profile_id, entity_id: None, version: None, status: None, limit: Some(1), }) .await .is_ok_and(|data| data.is_empty().not()) { return Err(UserErrors::UserExists.into()); } let user_role = domain::NewUserRole { user_id: invitee_user_from_db.get_user_id().to_owned(), role_id: request.role_id.clone(), status: { if cfg!(feature = "email") { UserStatus::InvitationSent } else { UserStatus::Active } }, created_by: user_from_token.user_id.clone(), last_modified_by: user_from_token.user_id.clone(), created_at: now, last_modified: now, entity: domain::NoLevel, }; let _user_role = match role_info.get_entity_type() { EntityType::Tenant => { return Err(UserErrors::InvalidRoleOperationWithMessage( "Tenant roles are not allowed for this operation".to_string(), ) .into()); } EntityType::Organization => { user_role .add_entity(domain::OrganizationLevel { tenant_id: user_from_token .tenant_id .clone() .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), }) .insert_in_v2(state) .await? } EntityType::Merchant => { user_role .add_entity(domain::MerchantLevel { tenant_id: user_from_token .tenant_id .clone() .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), merchant_id: user_from_token.merchant_id.clone(), }) .insert_in_v2(state) .await? } EntityType::Profile => { user_role .add_entity(domain::ProfileLevel { tenant_id: user_from_token .tenant_id .clone() .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), merchant_id: user_from_token.merchant_id.clone(), profile_id: user_from_token.profile_id.clone(), }) .insert_in_v2(state) .await? } }; let is_email_sent; #[cfg(feature = "email")] { let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; let entity = match role_info.get_entity_type() { EntityType::Tenant => { return Err(UserErrors::InvalidRoleOperationWithMessage( "Tenant roles are not allowed for this operation".to_string(), ) .into()); } EntityType::Organization => email_types::Entity { entity_id: user_from_token.org_id.get_string_repr().to_owned(), entity_type: EntityType::Organization, }, EntityType::Merchant => email_types::Entity { entity_id: user_from_token.merchant_id.get_string_repr().to_owned(), entity_type: EntityType::Merchant, }, EntityType::Profile => email_types::Entity { entity_id: user_from_token.profile_id.get_string_repr().to_owned(), entity_type: EntityType::Profile, }, }; let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity( state, user_from_token, role_info.get_entity_type(), ) .await?; let email_contents = email_types::InviteUser { recipient_email: invitee_email, user_name: domain::UserName::new(invitee_user_from_db.get_name())?, settings: state.conf.clone(), entity, auth_id: auth_id.clone(), theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; is_email_sent = state .email_client .compose_and_send_email( user_utils::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await .map(|email_result| logger::info!(?email_result)) .map_err(|email_result| logger::error!(?email_result)) .is_ok(); } #[cfg(not(feature = "email"))] { is_email_sent = false; } Ok(InviteMultipleUserResponse { email: request.email.clone(), is_email_sent, password: None, error: None, }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 191, "total_crates": null }
fn_clm_router_switch_merchant_for_user_in_org_4183922362388472259
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/user pub async fn switch_merchant_for_user_in_org( state: SessionState, request: user_api::SwitchMerchantRequest, user_from_token: auth::UserFromToken, ) -> UserResponse<user_api::TokenResponse> { if user_from_token.merchant_id == request.merchant_id { return Err(UserErrors::InvalidRoleOperationWithMessage( "User switching to same merchant".to_string(), ) .into()); } let key_manager_state = &(&state).into(); let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve role information")?; // Check if the role is internal and handle separately let (org_id, merchant_id, profile_id, role_id) = if role_info.is_internal() { let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &request.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(UserErrors::MerchantIdNotFound)?; let merchant_account = state .store .find_merchant_account_by_merchant_id( key_manager_state, &request.merchant_id, &merchant_key_store, ) .await .to_not_found_response(UserErrors::MerchantIdNotFound)?; let profile_id = state .store .list_profile_by_merchant_id( key_manager_state, &merchant_key_store, &request.merchant_id, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to list business profiles by merchant_id")? .pop() .ok_or(UserErrors::InternalServerError) .attach_printable("No business profile found for the given merchant_id")? .get_id() .to_owned(); ( merchant_account.organization_id, request.merchant_id, profile_id, user_from_token.role_id.clone(), ) } else { // Match based on the other entity types match role_info.get_entity_type() { EntityType::Tenant | EntityType::Organization => { let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &request.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(UserErrors::MerchantIdNotFound)?; let merchant_id = state .store .find_merchant_account_by_merchant_id( key_manager_state, &request.merchant_id, &merchant_key_store, ) .await .change_context(UserErrors::MerchantIdNotFound)? .organization_id .eq(&user_from_token.org_id) .then(|| request.merchant_id.clone()) .ok_or_else(|| { UserErrors::InvalidRoleOperationWithMessage( "No such merchant_id found for the user in the org".to_string(), ) })?; let profile_id = state .store .list_profile_by_merchant_id( key_manager_state, &merchant_key_store, &merchant_id, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to list business profiles by merchant_id")? .pop() .ok_or(UserErrors::InternalServerError) .attach_printable("No business profile found for the merchant_id")? .get_id() .to_owned(); ( user_from_token.org_id.clone(), merchant_id, profile_id, user_from_token.role_id.clone(), ) } EntityType::Merchant | EntityType::Profile => { let user_role = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: Some(&user_from_token.org_id), merchant_id: Some(&request.merchant_id), profile_id: None, entity_id: None, version: None, status: Some(UserStatus::Active), limit: Some(1), }) .await .change_context(UserErrors::InternalServerError) .attach_printable( "Failed to list user roles for the given user_id, org_id and merchant_id", )? .pop() .ok_or(UserErrors::InvalidRoleOperationWithMessage( "No user role associated with the requested merchant_id".to_string(), ))?; let (merchant_id, profile_id) = utils::user_role::get_single_merchant_id_and_profile_id(&state, &user_role) .await?; ( user_from_token.org_id, merchant_id, profile_id, user_role.role_id, ) } } }; let lineage_context = LineageContext { user_id: user_from_token.user_id.clone(), merchant_id: merchant_id.clone(), role_id: role_id.clone(), org_id: org_id.clone(), profile_id: profile_id.clone(), tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id) .clone(), }; utils::user::spawn_async_lineage_context_update_to_db( &state, &user_from_token.user_id, lineage_context, ); let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, merchant_id.clone(), org_id.clone(), role_id.clone(), profile_id, user_from_token.tenant_id.clone(), ) .await?; utils::user_role::set_role_info_in_cache_by_role_id_org_id( &state, &role_id, &org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await; let response = user_api::TokenResponse { token: token.clone(), token_type: common_enums::TokenPurpose::UserInfo, }; auth::cookies::set_cookie_response(response, token) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 171, "total_crates": null }
fn_clm_router_handle_new_user_invitation_4183922362388472259
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/user async fn handle_new_user_invitation( state: &SessionState, user_from_token: &auth::UserFromToken, request: &user_api::InviteUserRequest, role_info: roles::RoleInfo, req_state: ReqState, auth_id: &Option<String>, ) -> UserResult<InviteMultipleUserResponse> { let new_user = domain::NewUser::try_from((request.clone(), user_from_token.clone()))?; new_user .insert_user_in_db(state.global_store.as_ref()) .await .change_context(UserErrors::InternalServerError)?; let invitation_status = if cfg!(feature = "email") { UserStatus::InvitationSent } else { UserStatus::Active }; let now = common_utils::date_time::now(); let user_role = domain::NewUserRole { user_id: new_user.get_user_id().to_owned(), role_id: request.role_id.clone(), status: invitation_status, created_by: user_from_token.user_id.clone(), last_modified_by: user_from_token.user_id.clone(), created_at: now, last_modified: now, entity: domain::NoLevel, }; let _user_role = match role_info.get_entity_type() { EntityType::Tenant => { return Err(UserErrors::InvalidRoleOperationWithMessage( "Tenant roles are not allowed for this operation".to_string(), ) .into()); } EntityType::Organization => { user_role .add_entity(domain::OrganizationLevel { tenant_id: user_from_token .tenant_id .clone() .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), }) .insert_in_v2(state) .await? } EntityType::Merchant => { user_role .add_entity(domain::MerchantLevel { tenant_id: user_from_token .tenant_id .clone() .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), merchant_id: user_from_token.merchant_id.clone(), }) .insert_in_v2(state) .await? } EntityType::Profile => { user_role .add_entity(domain::ProfileLevel { tenant_id: user_from_token .tenant_id .clone() .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), merchant_id: user_from_token.merchant_id.clone(), profile_id: user_from_token.profile_id.clone(), }) .insert_in_v2(state) .await? } }; let is_email_sent; #[cfg(feature = "email")] { // TODO: Adding this to avoid clippy lints // Will be adding actual usage for this variable later let _ = req_state.clone(); let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; let entity = match role_info.get_entity_type() { EntityType::Tenant => { return Err(UserErrors::InvalidRoleOperationWithMessage( "Tenant roles are not allowed for this operation".to_string(), ) .into()); } EntityType::Organization => email_types::Entity { entity_id: user_from_token.org_id.get_string_repr().to_owned(), entity_type: EntityType::Organization, }, EntityType::Merchant => email_types::Entity { entity_id: user_from_token.merchant_id.get_string_repr().to_owned(), entity_type: EntityType::Merchant, }, EntityType::Profile => email_types::Entity { entity_id: user_from_token.profile_id.get_string_repr().to_owned(), entity_type: EntityType::Profile, }, }; let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity( state, user_from_token, role_info.get_entity_type(), ) .await?; let email_contents = email_types::InviteUser { recipient_email: invitee_email, user_name: domain::UserName::new(new_user.get_name())?, settings: state.conf.clone(), entity, auth_id: auth_id.clone(), theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; let send_email_result = state .email_client .compose_and_send_email( user_utils::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await; logger::info!(?send_email_result); is_email_sent = send_email_result.is_ok(); } #[cfg(not(feature = "email"))] { is_email_sent = false; let invited_user_token = auth::UserFromToken { user_id: new_user.get_user_id(), merchant_id: user_from_token.merchant_id.clone(), org_id: user_from_token.org_id.clone(), role_id: request.role_id.clone(), profile_id: user_from_token.profile_id.clone(), tenant_id: user_from_token.tenant_id.clone(), }; let set_metadata_request = SetMetaDataRequest::IsChangePasswordRequired; dashboard_metadata::set_metadata( state.clone(), invited_user_token, set_metadata_request, req_state, ) .await?; } Ok(InviteMultipleUserResponse { is_email_sent, password: new_user .get_password() .map(|password| password.get_secret()), email: request.email.clone(), error: None, }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 163, "total_crates": null }
fn_clm_router_connect_account_4183922362388472259
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/user pub async fn connect_account( state: SessionState, request: user_api::ConnectAccountRequest, auth_id: Option<String>, theme_id: Option<String>, ) -> UserResponse<user_api::ConnectAccountResponse> { let user_email = domain::UserEmail::from_pii_email(request.email.clone())?; utils::user::validate_email_domain_auth_type_using_db( &state, &user_email, UserAuthType::MagicLink, ) .await?; let find_user = state.global_store.find_user_by_email(&user_email).await; if let Ok(found_user) = find_user { let user_from_db: domain::UserFromStorage = found_user.into(); let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?; let email_contents = email_types::MagicLink { recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, settings: state.conf.clone(), user_name: domain::UserName::new(user_from_db.get_name())?, auth_id, theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; let send_email_result = state .email_client .compose_and_send_email( user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await; logger::info!(?send_email_result); Ok(ApplicationResponse::Json( user_api::ConnectAccountResponse { is_email_sent: send_email_result.is_ok(), user_id: user_from_db.get_user_id().to_string(), }, )) } else if find_user .as_ref() .map_err(|e| e.current_context().is_db_not_found()) .err() .unwrap_or(false) { if matches!(env::which(), env::Env::Production) { return Err(report!(UserErrors::InvalidCredentials)); } let new_user = domain::NewUser::try_from(request)?; let _ = new_user .get_new_merchant() .get_new_organization() .insert_org_in_db(state.clone()) .await?; let user_from_db = new_user .insert_user_and_merchant_in_db(state.clone()) .await?; let _user_role = new_user .insert_org_level_user_role_in_db( state.clone(), common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(), UserStatus::Active, ) .await?; let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?; let magic_link_email = email_types::VerifyEmail { recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, settings: state.conf.clone(), auth_id, theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; let magic_link_result = state .email_client .compose_and_send_email( user_utils::get_base_url(&state), Box::new(magic_link_email), state.conf.proxy.https_url.as_ref(), ) .await; logger::info!(?magic_link_result); if state.tenant.tenant_id.get_string_repr() == common_utils::consts::DEFAULT_TENANT { let welcome_to_community_email = email_types::WelcomeToCommunity { recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, }; let welcome_email_result = state .email_client .compose_and_send_email( user_utils::get_base_url(&state), Box::new(welcome_to_community_email), state.conf.proxy.https_url.as_ref(), ) .await; logger::info!(?welcome_email_result); } Ok(ApplicationResponse::Json( user_api::ConnectAccountResponse { is_email_sent: magic_link_result.is_ok(), user_id: user_from_db.get_user_id().to_string(), }, )) } else { Err(find_user .err() .map(|e| e.change_context(UserErrors::InternalServerError)) .unwrap_or(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": 159, "total_crates": null }
fn_clm_router_list_invitations_for_user_966849743309655410
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/user_role pub async fn list_invitations_for_user( state: SessionState, user_from_token: auth::UserIdFromAuth, ) -> UserResponse<Vec<user_role_api::ListInvitationForUserResponse>> { let user_roles = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: Some(UserStatus::InvitationSent), limit: None, }) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to list user roles by user id and invitation sent")? .into_iter() .collect::<HashSet<_>>(); let (org_ids, merchant_ids, profile_ids_with_merchant_ids) = user_roles.iter().try_fold( (Vec::new(), Vec::new(), Vec::new()), |(mut org_ids, mut merchant_ids, mut profile_ids_with_merchant_ids), user_role| { let (_, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError) .attach_printable("Failed to compute entity id and type")?; match entity_type { EntityType::Tenant => { return Err(report!(UserErrors::InternalServerError)) .attach_printable("Tenant roles are not allowed for this operation"); } EntityType::Organization => org_ids.push( user_role .org_id .clone() .ok_or(UserErrors::InternalServerError)?, ), EntityType::Merchant => merchant_ids.push( user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError)?, ), EntityType::Profile => profile_ids_with_merchant_ids.push(( user_role .profile_id .clone() .ok_or(UserErrors::InternalServerError)?, user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError)?, )), } Ok::<_, error_stack::Report<UserErrors>>(( org_ids, merchant_ids, profile_ids_with_merchant_ids, )) }, )?; let org_name_map = futures::future::try_join_all(org_ids.into_iter().map(|org_id| async { let org_name = state .accounts_store .find_organization_by_org_id(&org_id) .await .change_context(UserErrors::InternalServerError)? .get_organization_name() .map(Secret::new); Ok::<_, error_stack::Report<UserErrors>>((org_id, org_name)) })) .await? .into_iter() .collect::<HashMap<_, _>>(); let key_manager_state = &(&state).into(); let merchant_name_map = state .store .list_multiple_merchant_accounts(key_manager_state, merchant_ids) .await .change_context(UserErrors::InternalServerError)? .into_iter() .map(|merchant| { ( merchant.get_id().clone(), merchant .merchant_name .map(|encryptable_name| encryptable_name.into_inner()), ) }) .collect::<HashMap<_, _>>(); let master_key = &state.store.get_master_key().to_vec().into(); let profile_name_map = futures::future::try_join_all(profile_ids_with_merchant_ids.iter().map( |(profile_id, merchant_id)| async { let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id(key_manager_state, merchant_id, master_key) .await .change_context(UserErrors::InternalServerError)?; let business_profile = state .store .find_business_profile_by_profile_id( key_manager_state, &merchant_key_store, profile_id, ) .await .change_context(UserErrors::InternalServerError)?; Ok::<_, error_stack::Report<UserErrors>>(( profile_id.clone(), Secret::new(business_profile.profile_name), )) }, )) .await? .into_iter() .collect::<HashMap<_, _>>(); user_roles .into_iter() .map(|user_role| { let (entity_id, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError) .attach_printable("Failed to compute entity id and type")?; let entity_name = match entity_type { EntityType::Tenant => { return Err(report!(UserErrors::InternalServerError)) .attach_printable("Tenant roles are not allowed for this operation"); } EntityType::Organization => user_role .org_id .as_ref() .and_then(|org_id| org_name_map.get(org_id).cloned()) .ok_or(UserErrors::InternalServerError)?, EntityType::Merchant => user_role .merchant_id .as_ref() .and_then(|merchant_id| merchant_name_map.get(merchant_id).cloned()) .ok_or(UserErrors::InternalServerError)?, EntityType::Profile => user_role .profile_id .as_ref() .map(|profile_id| profile_name_map.get(profile_id).cloned()) .ok_or(UserErrors::InternalServerError)?, }; Ok(user_role_api::ListInvitationForUserResponse { entity_id, entity_type, entity_name, role_id: user_role.role_id, }) }) .collect::<Result<Vec<_>, _>>() .map(ApplicationResponse::Json) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 169, "total_crates": null }
fn_clm_router_delete_user_role_966849743309655410
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/user_role pub async fn delete_user_role( state: SessionState, user_from_token: auth::UserFromToken, request: user_role_api::DeleteUserRoleRequest, _req_state: ReqState, ) -> UserResponse<()> { let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_email(&domain::UserEmail::from_pii_email(request.email)?) .await .map_err(|e| { if e.current_context().is_db_not_found() { e.change_context(UserErrors::InvalidRoleOperation) .attach_printable("User not found in our records") } else { e.change_context(UserErrors::InternalServerError) } })? .into(); if user_from_db.get_user_id() == user_from_token.user_id { return Err(report!(UserErrors::InvalidDeleteOperation)) .attach_printable("User deleting himself"); } let deletion_requestor_role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; let mut user_role_deleted_flag = false; // Find in V2 let user_role_v2 = match state .global_store .find_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V2, ) .await { Ok(user_role) => Some(user_role), Err(e) => { if e.current_context().is_db_not_found() { None } else { return Err(UserErrors::InternalServerError.into()); } } }; if let Some(role_to_be_deleted) = user_role_v2 { let target_role_info = roles::RoleInfo::from_role_id_in_lineage( &state, &role_to_be_deleted.role_id, &user_from_token.merchant_id, &user_from_token.org_id, &user_from_token.profile_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; if !target_role_info.is_deletable() { return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!( "Invalid operation, role_id = {} is not deletable", role_to_be_deleted.role_id )); } if deletion_requestor_role_info.get_entity_type() < target_role_info.get_entity_type() { return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!( "Invalid operation, deletion requestor = {} cannot delete target = {}", deletion_requestor_role_info.get_entity_type(), target_role_info.get_entity_type() )); } user_role_deleted_flag = true; state .global_store .delete_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V2, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while deleting user role")?; } // Find in V1 let user_role_v1 = match state .global_store .find_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V1, ) .await { Ok(user_role) => Some(user_role), Err(e) => { if e.current_context().is_db_not_found() { None } else { return Err(UserErrors::InternalServerError.into()); } } }; if let Some(role_to_be_deleted) = user_role_v1 { let target_role_info = roles::RoleInfo::from_role_id_in_lineage( &state, &role_to_be_deleted.role_id, &user_from_token.merchant_id, &user_from_token.org_id, &user_from_token.profile_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; if !target_role_info.is_deletable() { return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!( "Invalid operation, role_id = {} is not deletable", role_to_be_deleted.role_id )); } if deletion_requestor_role_info.get_entity_type() < target_role_info.get_entity_type() { return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!( "Invalid operation, deletion requestor = {} cannot delete target = {}", deletion_requestor_role_info.get_entity_type(), target_role_info.get_entity_type() )); } user_role_deleted_flag = true; state .global_store .delete_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V1, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while deleting user role")?; } if !user_role_deleted_flag { return Err(report!(UserErrors::InvalidDeleteOperation)) .attach_printable("User is not associated with the merchant"); } // Check if user has any more role associations let remaining_roles = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user_from_db.get_user_id(), tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: None, limit: None, }) .await .change_context(UserErrors::InternalServerError)?; // If user has no more role associated with him then deleting user if remaining_roles.is_empty() { state .global_store .delete_user_by_user_id(user_from_db.get_user_id()) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while deleting user entry")?; } auth::blacklist::insert_user_in_blacklist(&state, user_from_db.get_user_id()).await?; Ok(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": 154, "total_crates": null }
fn_clm_router_update_user_role_966849743309655410
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/user_role pub async fn update_user_role( state: SessionState, user_from_token: auth::UserFromToken, req: user_role_api::UpdateUserRoleRequest, _req_state: ReqState, ) -> UserResponse<()> { let role_info = roles::RoleInfo::from_role_id_in_lineage( &state, &req.role_id, &user_from_token.merchant_id, &user_from_token.org_id, &user_from_token.profile_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .to_not_found_response(UserErrors::InvalidRoleId)?; if !role_info.is_updatable() { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable(format!("User role cannot be updated to {}", req.role_id)); } let user_to_be_updated = utils::user::get_user_from_db_by_email(&state, domain::UserEmail::try_from(req.email)?) .await .to_not_found_response(UserErrors::InvalidRoleOperation) .attach_printable("User not found in our records".to_string())?; if user_from_token.user_id == user_to_be_updated.get_user_id() { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("User Changing their own role"); } let updator_role = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; let mut is_updated = false; let v2_user_role_to_be_updated = match state .global_store .find_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V2, ) .await { Ok(user_role) => Some(user_role), Err(e) => { if e.current_context().is_db_not_found() { None } else { return Err(UserErrors::InternalServerError.into()); } } }; if let Some(user_role) = v2_user_role_to_be_updated { let role_to_be_updated = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_role.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; if !role_to_be_updated.is_updatable() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "User role cannot be updated from {}", role_to_be_updated.get_role_id() )); } if role_info.get_entity_type() != role_to_be_updated.get_entity_type() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "Upgrade and downgrade of roles is not allowed, user_entity_type = {} req_entity_type = {}", role_to_be_updated.get_entity_type(), role_info.get_entity_type(), )); } if updator_role.get_entity_type() < role_to_be_updated.get_entity_type() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "Invalid operation, update requestor = {} cannot update target = {}", updator_role.get_entity_type(), role_to_be_updated.get_entity_type() )); } state .global_store .update_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, Some(&user_from_token.merchant_id), Some(&user_from_token.profile_id), UserRoleUpdate::UpdateRole { role_id: req.role_id.clone(), modified_by: user_from_token.user_id.clone(), }, UserRoleVersion::V2, ) .await .change_context(UserErrors::InternalServerError)?; is_updated = true; } let v1_user_role_to_be_updated = match state .global_store .find_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V1, ) .await { Ok(user_role) => Some(user_role), Err(e) => { if e.current_context().is_db_not_found() { None } else { return Err(UserErrors::InternalServerError.into()); } } }; if let Some(user_role) = v1_user_role_to_be_updated { let role_to_be_updated = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_role.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; if !role_to_be_updated.is_updatable() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "User role cannot be updated from {}", role_to_be_updated.get_role_id() )); } if role_info.get_entity_type() != role_to_be_updated.get_entity_type() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "Upgrade and downgrade of roles is not allowed, user_entity_type = {} req_entity_type = {}", role_to_be_updated.get_entity_type(), role_info.get_entity_type(), )); } if updator_role.get_entity_type() < role_to_be_updated.get_entity_type() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "Invalid operation, update requestor = {} cannot update target = {}", updator_role.get_entity_type(), role_to_be_updated.get_entity_type() )); } state .global_store .update_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, Some(&user_from_token.merchant_id), Some(&user_from_token.profile_id), UserRoleUpdate::UpdateRole { role_id: req.role_id.clone(), modified_by: user_from_token.user_id, }, UserRoleVersion::V1, ) .await .change_context(UserErrors::InternalServerError)?; is_updated = true; } if !is_updated { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("User with given email is not found in the organization")?; } auth::blacklist::insert_user_in_blacklist(&state, user_to_be_updated.get_user_id()).await?; Ok(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": 152, "total_crates": null }
fn_clm_router_list_users_in_lineage_966849743309655410
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/user_role pub async fn list_users_in_lineage( state: SessionState, user_from_token: auth::UserFromToken, request: user_role_api::ListUsersInEntityRequest, ) -> UserResponse<Vec<user_role_api::ListUsersInEntityResponse>> { let requestor_role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; let user_roles_set: HashSet<_> = match utils::user_role::get_min_entity( requestor_role_info.get_entity_type(), request.entity_type, )? { EntityType::Tenant => { let mut org_users = utils::user_role::fetch_user_roles_by_payload( &state, ListUserRolesByOrgIdPayload { user_id: None, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: &user_from_token.org_id, merchant_id: None, profile_id: None, version: None, limit: None, }, request.entity_type, ) .await?; // Fetch tenant user let tenant_user = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: None, limit: None, }) .await .change_context(UserErrors::InternalServerError)?; org_users.extend(tenant_user); org_users } EntityType::Organization => { utils::user_role::fetch_user_roles_by_payload( &state, ListUserRolesByOrgIdPayload { user_id: None, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: &user_from_token.org_id, merchant_id: None, profile_id: None, version: None, limit: None, }, request.entity_type, ) .await? } EntityType::Merchant => { utils::user_role::fetch_user_roles_by_payload( &state, ListUserRolesByOrgIdPayload { user_id: None, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: &user_from_token.org_id, merchant_id: Some(&user_from_token.merchant_id), profile_id: None, version: None, limit: None, }, request.entity_type, ) .await? } EntityType::Profile => { utils::user_role::fetch_user_roles_by_payload( &state, ListUserRolesByOrgIdPayload { user_id: None, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: &user_from_token.org_id, merchant_id: Some(&user_from_token.merchant_id), profile_id: Some(&user_from_token.profile_id), version: None, limit: None, }, request.entity_type, ) .await? } }; // This filtering is needed because for org level users in V1, merchant_id is present. // Due to this, we get org level users in merchant level users list. let user_roles_set = user_roles_set .into_iter() .filter_map(|user_role| { let (_entity_id, entity_type) = user_role.get_entity_id_and_type()?; (entity_type <= requestor_role_info.get_entity_type()).then_some(user_role) }) .collect::<HashSet<_>>(); let mut email_map = state .global_store .find_users_by_user_ids( user_roles_set .iter() .map(|user_role| user_role.user_id.clone()) .collect(), ) .await .change_context(UserErrors::InternalServerError)? .into_iter() .map(|user| (user.user_id.clone(), user.email)) .collect::<HashMap<_, _>>(); let role_info_map = futures::future::try_join_all(user_roles_set.iter().map(|user_role| async { roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_role.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .map(|role_info| { ( user_role.role_id.clone(), user_role_api::role::MinimalRoleInfo { role_id: user_role.role_id.clone(), role_name: role_info.get_role_name().to_string(), }, ) }) })) .await .change_context(UserErrors::InternalServerError)? .into_iter() .collect::<HashMap<_, _>>(); let user_role_map = user_roles_set .into_iter() .fold(HashMap::new(), |mut map, user_role| { map.entry(user_role.user_id) .or_insert(Vec::with_capacity(1)) .push(user_role.role_id); map }); Ok(ApplicationResponse::Json( user_role_map .into_iter() .map(|(user_id, role_id_vec)| { Ok::<_, error_stack::Report<UserErrors>>(user_role_api::ListUsersInEntityResponse { email: email_map .remove(&user_id) .ok_or(UserErrors::InternalServerError)?, roles: role_id_vec .into_iter() .map(|role_id| { role_info_map .get(&role_id) .cloned() .ok_or(UserErrors::InternalServerError) }) .collect::<Result<Vec<_>, _>>()?, }) }) .collect::<Result<Vec<_>, _>>()?, )) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 147, "total_crates": null }
fn_clm_router_accept_invitations_pre_auth_966849743309655410
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/user_role pub async fn accept_invitations_pre_auth( state: SessionState, user_token: auth::UserFromSinglePurposeToken, req: user_role_api::AcceptInvitationsPreAuthRequest, ) -> UserResponse<user_api::TokenResponse> { let lineages = futures::future::try_join_all(req.into_iter().map(|entity| { utils::user_role::get_lineage_for_user_id_and_entity_for_accepting_invite( &state, &user_token.user_id, user_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), entity.entity_id, entity.entity_type, ) })) .await? .into_iter() .flatten() .collect::<Vec<_>>(); let update_results = futures::future::join_all(lineages.iter().map( |(org_id, merchant_id, profile_id)| async { let (update_v1_result, update_v2_result) = utils::user_role::update_v1_and_v2_user_roles_in_db( &state, user_token.user_id.as_str(), user_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id, merchant_id.as_ref(), profile_id.as_ref(), UserRoleUpdate::UpdateStatus { status: UserStatus::Active, modified_by: user_token.user_id.clone(), }, ) .await; if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found()) || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found()) { Err(report!(UserErrors::InternalServerError)) } else { Ok(()) } }, )) .await; if update_results.is_empty() || update_results.iter().all(Result::is_err) { return Err(UserErrors::MerchantIdNotFound.into()); } let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_id(user_token.user_id.as_str()) .await .change_context(UserErrors::InternalServerError)? .into(); let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::MerchantSelect.into())?; let next_flow = current_flow.next(user_from_db.clone(), &state).await?; let token = next_flow.get_token(&state).await?; let response = user_api::TokenResponse { token: token.clone(), token_type: next_flow.get_flow().into(), }; auth::cookies::set_cookie_response(response, token) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 95, "total_crates": null }
fn_clm_router_files_create_core_-4249580086622461386
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/files pub async fn files_create_core( state: SessionState, merchant_context: domain::MerchantContext, create_file_request: api::CreateFileRequest, ) -> RouterResponse<files::CreateFileResponse> { helpers::validate_file_upload( &state, merchant_context.clone(), create_file_request.clone(), ) .await?; let file_id = common_utils::generate_id(consts::ID_LENGTH, "file"); let file_key = format!( "{}/{}", merchant_context .get_merchant_account() .get_id() .get_string_repr(), file_id ); let file_new: diesel_models::FileMetadataNew = diesel_models::file::FileMetadataNew { file_id: file_id.clone(), merchant_id: merchant_context.get_merchant_account().get_id().clone(), file_name: create_file_request.file_name.clone(), file_size: create_file_request.file_size, file_type: create_file_request.file_type.to_string(), provider_file_id: None, file_upload_provider: None, available: false, connector_label: None, profile_id: None, merchant_connector_id: None, }; let file_metadata_object = state .store .insert_file_metadata(file_new) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to insert file_metadata")?; let (provider_file_id, file_upload_provider, profile_id, merchant_connector_id) = Box::pin( helpers::upload_and_get_provider_provider_file_id_profile_id( &state, &merchant_context, &create_file_request, file_key.clone(), ), ) .await?; // Update file metadata let update_file_metadata = diesel_models::file::FileMetadataUpdate::Update { provider_file_id: Some(provider_file_id), file_upload_provider: Some(file_upload_provider), available: true, profile_id, merchant_connector_id, }; state .store .as_ref() .update_file_metadata(file_metadata_object, update_file_metadata) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Unable to update file_metadata with file_id: {file_id}") })?; Ok(ApplicationResponse::Json(files::CreateFileResponse { file_id, })) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 58, "total_crates": null }
fn_clm_router_files_retrieve_core_-4249580086622461386
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/files pub async fn files_retrieve_core( state: SessionState, merchant_context: domain::MerchantContext, req: api::FileRetrieveRequest, ) -> RouterResponse<serde_json::Value> { let file_metadata_object = state .store .as_ref() .find_file_metadata_by_merchant_id_file_id( merchant_context.get_merchant_account().get_id(), &req.file_id, ) .await .change_context(errors::ApiErrorResponse::FileNotFound) .attach_printable("Unable to retrieve file_metadata")?; let file_info = helpers::retrieve_file_and_provider_file_id_from_file_id( &state, Some(req.file_id), req.dispute_id, &merchant_context, api::FileDataRequired::Required, ) .await?; let content_type = file_metadata_object .file_type .parse::<mime::Mime>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse file content type")?; Ok(ApplicationResponse::FileData(( file_info .file_data .ok_or(errors::ApiErrorResponse::FileNotAvailable) .attach_printable("File data not found")?, content_type, ))) }
{ "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_files_delete_core_-4249580086622461386
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/files pub async fn files_delete_core( state: SessionState, merchant_context: domain::MerchantContext, req: api::FileId, ) -> RouterResponse<serde_json::Value> { helpers::delete_file_using_file_id(&state, req.file_id.clone(), &merchant_context).await?; state .store .as_ref() .delete_file_metadata_by_merchant_id_file_id( merchant_context.get_merchant_account().get_id(), &req.file_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to delete file_metadata")?; Ok(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": 29, "total_crates": null }
fn_clm_router_call_unified_connector_service_for_webhook_-5218144731209746389
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/unified_connector_service /// High-level abstraction for calling UCS webhook transformation /// This provides a clean interface similar to payment flow UCS calls pub async fn call_unified_connector_service_for_webhook( state: &SessionState, merchant_context: &MerchantContext, connector_name: &str, body: &actix_web::web::Bytes, request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, merchant_connector_account: Option< &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, >, ) -> RouterResult<( api_models::webhooks::IncomingWebhookEvent, bool, WebhookTransformData, )> { let ucs_client = state .grpc_client .unified_connector_service_client .as_ref() .ok_or_else(|| { error_stack::report!(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("UCS client is not available for webhook processing") })?; // Build webhook secrets from merchant connector account let webhook_secrets = merchant_connector_account.and_then(|mca| { #[cfg(feature = "v1")] let mca_type = MerchantConnectorAccountType::DbVal(Box::new(mca.clone())); #[cfg(feature = "v2")] let mca_type = MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(mca.clone())); build_webhook_secrets_from_merchant_connector_account(&mca_type) .map_err(|e| { logger::warn!( build_error=?e, connector_name=connector_name, "Failed to build webhook secrets from merchant connector account in call_unified_connector_service_for_webhook" ); e }) .ok() .flatten() }); // Build UCS transform request using new webhook transformers let transform_request = transformers::build_webhook_transform_request( body, request_details, webhook_secrets, merchant_context .get_merchant_account() .get_id() .get_string_repr(), connector_name, )?; // Build connector auth metadata let connector_auth_metadata = merchant_connector_account .map(|mca| { #[cfg(feature = "v1")] let mca_type = MerchantConnectorAccountType::DbVal(Box::new(mca.clone())); #[cfg(feature = "v2")] let mca_type = MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( mca.clone(), )); build_unified_connector_service_auth_metadata(mca_type, merchant_context) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to build UCS auth metadata")? .ok_or_else(|| { error_stack::report!(errors::ApiErrorResponse::InternalServerError).attach_printable( "Missing merchant connector account for UCS webhook transformation", ) })?; let profile_id = merchant_connector_account .as_ref() .map(|mca| mca.profile_id.clone()) .unwrap_or(consts::PROFILE_ID_UNAVAILABLE.clone()); // Build gRPC headers let grpc_headers = state .get_grpc_headers_ucs(ExecutionMode::Primary) .lineage_ids(LineageIds::new( merchant_context.get_merchant_account().get_id().clone(), profile_id, )) .external_vault_proxy_metadata(None) .merchant_reference_id(None) .build(); // Make UCS call - client availability already verified match ucs_client .transform_incoming_webhook(transform_request, connector_auth_metadata, grpc_headers) .await { Ok(response) => { let transform_response = response.into_inner(); let transform_data = transformers::transform_ucs_webhook_response(transform_response)?; // UCS handles everything internally - event type, source verification, decoding Ok(( transform_data.event_type, transform_data.source_verified, transform_data, )) } Err(err) => { // When UCS is configured, we don't fall back to direct connector processing Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable(format!("UCS webhook processing failed: {err}")) } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 111, "total_crates": null }
fn_clm_router_build_unified_connector_service_payment_method_-5218144731209746389
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/unified_connector_service pub fn build_unified_connector_service_payment_method( payment_method_data: hyperswitch_domain_models::payment_method_data::PaymentMethodData, payment_method_type: PaymentMethodType, ) -> CustomResult<payments_grpc::PaymentMethod, UnifiedConnectorServiceError> { match payment_method_data { hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(card) => { let card_exp_month = card .get_card_expiry_month_2_digit() .attach_printable("Failed to extract 2-digit expiry month from card") .change_context(UnifiedConnectorServiceError::InvalidDataFormat { field_name: "card_exp_month", })? .peek() .to_string(); let card_network = card .card_network .clone() .map(payments_grpc::CardNetwork::foreign_try_from) .transpose()?; let card_details = CardDetails { card_number: Some( CardNumber::from_str(&card.card_number.get_card_no()).change_context( UnifiedConnectorServiceError::RequestEncodingFailedWithReason( "Failed to parse card number".to_string(), ), )?, ), card_exp_month: Some(card_exp_month.into()), card_exp_year: Some(card.get_expiry_year_4_digit().expose().into()), card_cvc: Some(card.card_cvc.expose().into()), card_holder_name: card.card_holder_name.map(|name| name.expose().into()), card_issuer: card.card_issuer.clone(), card_network: card_network.map(|card_network| card_network.into()), card_type: card.card_type.clone(), bank_code: card.bank_code.clone(), nick_name: card.nick_name.map(|n| n.expose()), card_issuing_country_alpha2: card.card_issuing_country.clone(), }; let grpc_card_type = match payment_method_type { PaymentMethodType::Credit => { payments_grpc::card_payment_method_type::CardType::Credit(card_details) } PaymentMethodType::Debit => { payments_grpc::card_payment_method_type::CardType::Debit(card_details) } _ => { return Err(UnifiedConnectorServiceError::NotImplemented(format!( "Unimplemented payment method subtype: {payment_method_type:?}" )) .into()); } }; Ok(payments_grpc::PaymentMethod { payment_method: Some(PaymentMethod::Card(CardPaymentMethodType { card_type: Some(grpc_card_type), })), }) } hyperswitch_domain_models::payment_method_data::PaymentMethodData::Upi(upi_data) => { let upi_type = match upi_data { hyperswitch_domain_models::payment_method_data::UpiData::UpiCollect( upi_collect_data, ) => { let upi_details = payments_grpc::UpiCollect { vpa_id: upi_collect_data.vpa_id.map(|vpa| vpa.expose().into()), }; PaymentMethod::UpiCollect(upi_details) } hyperswitch_domain_models::payment_method_data::UpiData::UpiIntent(_) => { let upi_details = payments_grpc::UpiIntent { app_name: None }; PaymentMethod::UpiIntent(upi_details) } hyperswitch_domain_models::payment_method_data::UpiData::UpiQr(_) => { let upi_details = payments_grpc::UpiQr {}; PaymentMethod::UpiQr(upi_details) } }; Ok(payments_grpc::PaymentMethod { payment_method: Some(upi_type), }) } hyperswitch_domain_models::payment_method_data::PaymentMethodData::Reward => { match payment_method_type { PaymentMethodType::ClassicReward => Ok(payments_grpc::PaymentMethod { payment_method: Some(PaymentMethod::Reward(RewardPaymentMethodType { reward_type: 1, })), }), PaymentMethodType::Evoucher => Ok(payments_grpc::PaymentMethod { payment_method: Some(PaymentMethod::Reward(RewardPaymentMethodType { reward_type: 2, })), }), _ => Err(UnifiedConnectorServiceError::NotImplemented(format!( "Unimplemented payment method subtype: {payment_method_type:?}" )) .into()), } } _ => Err(UnifiedConnectorServiceError::NotImplemented(format!( "Unimplemented payment method: {payment_method_data:?}" )) .into()), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 104, "total_crates": null }
fn_clm_router_build_unified_connector_service_auth_metadata_-5218144731209746389
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/unified_connector_service pub fn build_unified_connector_service_auth_metadata( #[cfg(feature = "v1")] merchant_connector_account: MerchantConnectorAccountType, #[cfg(feature = "v2")] merchant_connector_account: MerchantConnectorAccountTypeDetails, merchant_context: &MerchantContext, ) -> CustomResult<ConnectorAuthMetadata, UnifiedConnectorServiceError> { #[cfg(feature = "v1")] let auth_type: ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(UnifiedConnectorServiceError::FailedToObtainAuthType) .attach_printable("Failed while parsing value for ConnectorAuthType")?; #[cfg(feature = "v2")] let auth_type: ConnectorAuthType = merchant_connector_account .get_connector_account_details() .change_context(UnifiedConnectorServiceError::FailedToObtainAuthType) .attach_printable("Failed to obtain ConnectorAuthType")?; let connector_name = { #[cfg(feature = "v1")] { merchant_connector_account .get_connector_name() .ok_or(UnifiedConnectorServiceError::MissingConnectorName) .attach_printable("Missing connector name")? } #[cfg(feature = "v2")] { merchant_connector_account .get_connector_name() .map(|connector| connector.to_string()) .ok_or(UnifiedConnectorServiceError::MissingConnectorName) .attach_printable("Missing connector name")? } }; let merchant_id = merchant_context .get_merchant_account() .get_id() .get_string_repr(); match &auth_type { ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Ok(ConnectorAuthMetadata { connector_name, auth_type: consts::UCS_AUTH_SIGNATURE_KEY.to_string(), api_key: Some(api_key.clone()), key1: Some(key1.clone()), api_secret: Some(api_secret.clone()), auth_key_map: None, merchant_id: Secret::new(merchant_id.to_string()), }), ConnectorAuthType::BodyKey { api_key, key1 } => Ok(ConnectorAuthMetadata { connector_name, auth_type: consts::UCS_AUTH_BODY_KEY.to_string(), api_key: Some(api_key.clone()), key1: Some(key1.clone()), api_secret: None, auth_key_map: None, merchant_id: Secret::new(merchant_id.to_string()), }), ConnectorAuthType::HeaderKey { api_key } => Ok(ConnectorAuthMetadata { connector_name, auth_type: consts::UCS_AUTH_HEADER_KEY.to_string(), api_key: Some(api_key.clone()), key1: None, api_secret: None, auth_key_map: None, merchant_id: Secret::new(merchant_id.to_string()), }), ConnectorAuthType::CurrencyAuthKey { auth_key_map } => Ok(ConnectorAuthMetadata { connector_name, auth_type: consts::UCS_AUTH_CURRENCY_AUTH_KEY.to_string(), api_key: None, key1: None, api_secret: None, auth_key_map: Some(auth_key_map.clone()), merchant_id: Secret::new(merchant_id.to_string()), }), _ => Err(UnifiedConnectorServiceError::FailedToObtainAuthType) .attach_printable("Unsupported ConnectorAuthType for header injection"), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 104, "total_crates": null }
fn_clm_router_ucs_logging_wrapper_-5218144731209746389
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/unified_connector_service pub async fn ucs_logging_wrapper<T, F, Fut, Req, Resp, GrpcReq, GrpcResp>( router_data: RouterData<T, Req, Resp>, state: &SessionState, grpc_request: GrpcReq, grpc_header_builder: external_services::grpc_client::GrpcHeadersUcsBuilderFinal, handler: F, ) -> RouterResult<RouterData<T, Req, Resp>> where T: std::fmt::Debug + Clone + Send + 'static, Req: std::fmt::Debug + Clone + Send + Sync + 'static, Resp: std::fmt::Debug + Clone + Send + Sync + 'static, GrpcReq: serde::Serialize, GrpcResp: serde::Serialize, F: FnOnce( RouterData<T, Req, Resp>, GrpcReq, external_services::grpc_client::GrpcHeadersUcs, ) -> Fut + Send, Fut: std::future::Future<Output = RouterResult<(RouterData<T, Req, Resp>, GrpcResp)>> + Send, { tracing::Span::current().record("connector_name", &router_data.connector); tracing::Span::current().record("flow_type", std::any::type_name::<T>()); tracing::Span::current().record("payment_id", &router_data.payment_id); // Capture request data for logging let connector_name = router_data.connector.clone(); let payment_id = router_data.payment_id.clone(); let merchant_id = router_data.merchant_id.clone(); let refund_id = router_data.refund_id.clone(); let dispute_id = router_data.dispute_id.clone(); let grpc_header = grpc_header_builder.build(); // Log the actual gRPC request with masking let grpc_request_body = masking::masked_serialize(&grpc_request) .unwrap_or_else(|_| serde_json::json!({"error": "failed_to_serialize_grpc_request"})); // Update connector call count metrics for UCS operations crate::routes::metrics::CONNECTOR_CALL_COUNT.add( 1, router_env::metric_attributes!( ("connector", connector_name.clone()), ( "flow", std::any::type_name::<T>() .split("::") .last() .unwrap_or_default() ), ), ); // Execute UCS function and measure timing let start_time = Instant::now(); let result = handler(router_data, grpc_request, grpc_header).await; let external_latency = start_time.elapsed().as_millis(); // Create and emit connector event after UCS call let (status_code, response_body, router_result) = match result { Ok((updated_router_data, grpc_response)) => { let status = updated_router_data .connector_http_status_code .unwrap_or(200); // Log the actual gRPC response let grpc_response_body = serde_json::to_value(&grpc_response).unwrap_or_else( |_| serde_json::json!({"error": "failed_to_serialize_grpc_response"}), ); (status, Some(grpc_response_body), Ok(updated_router_data)) } Err(error) => { // Update error metrics for UCS calls crate::routes::metrics::CONNECTOR_ERROR_RESPONSE_COUNT.add( 1, router_env::metric_attributes!(("connector", connector_name.clone(),)), ); let error_body = serde_json::json!({ "error": error.to_string(), "error_type": "ucs_call_failed" }); (500, Some(error_body), Err(error)) } }; let mut connector_event = ConnectorEvent::new( state.tenant.tenant_id.clone(), connector_name, std::any::type_name::<T>(), grpc_request_body, "grpc://unified-connector-service".to_string(), Method::Post, payment_id, merchant_id, state.request_id.as_ref(), external_latency, refund_id, dispute_id, status_code, ); // Set response body based on status code if let Some(body) = response_body { match status_code { 400..=599 => { connector_event.set_error_response_body(&body); } _ => { connector_event.set_response_body(&body); } } } // Emit event state.event_handler.log_event(&connector_event); router_result }
{ "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_build_unified_connector_service_payment_method_for_external_proxy_-5218144731209746389
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/unified_connector_service pub fn build_unified_connector_service_payment_method_for_external_proxy( payment_method_data: hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData, payment_method_type: PaymentMethodType, ) -> CustomResult<payments_grpc::PaymentMethod, UnifiedConnectorServiceError> { match payment_method_data { hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::Card( external_vault_card, ) => { let card_network = external_vault_card .card_network .clone() .map(payments_grpc::CardNetwork::foreign_try_from) .transpose()?; let card_details = CardDetails { card_number: Some(CardNumber::from_str(external_vault_card.card_number.peek()).change_context( UnifiedConnectorServiceError::RequestEncodingFailedWithReason("Failed to parse card number".to_string()) )?), card_exp_month: Some(external_vault_card.card_exp_month.expose().into()), card_exp_year: Some(external_vault_card.card_exp_year.expose().into()), card_cvc: Some(external_vault_card.card_cvc.expose().into()), card_holder_name: external_vault_card.card_holder_name.map(|name| name.expose().into()), card_issuer: external_vault_card.card_issuer.clone(), card_network: card_network.map(|card_network| card_network.into()), card_type: external_vault_card.card_type.clone(), bank_code: external_vault_card.bank_code.clone(), nick_name: external_vault_card.nick_name.map(|n| n.expose()), card_issuing_country_alpha2: external_vault_card.card_issuing_country.clone(), }; let grpc_card_type = match payment_method_type { PaymentMethodType::Credit => { payments_grpc::card_payment_method_type::CardType::CreditProxy(card_details) } PaymentMethodType::Debit => { payments_grpc::card_payment_method_type::CardType::DebitProxy(card_details) } _ => { return Err(UnifiedConnectorServiceError::NotImplemented(format!( "Unimplemented payment method subtype: {payment_method_type:?}" )) .into()); } }; Ok(payments_grpc::PaymentMethod { payment_method: Some(PaymentMethod::Card(CardPaymentMethodType { card_type: Some(grpc_card_type), })), }) } hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::VaultToken(_) => { Err(UnifiedConnectorServiceError::NotImplemented(format!( "Unimplemented payment method subtype: {payment_method_type:?}" )) .into()) } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 74, "total_crates": null }
fn_clm_router_verify_external_token_-8083920335894949583
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/external_service_auth pub async fn verify_external_token( state: SessionState, json_payload: external_service_auth_api::ExternalVerifyTokenRequest, external_service_type: ExternalServiceType, ) -> RouterResponse<external_service_auth_api::ExternalVerifyTokenResponse> { let token_from_payload = json_payload.token.expose(); let token = authentication::decode_jwt::<ExternalToken>(&token_from_payload, &state) .await .change_context(errors::ApiErrorResponse::Unauthorized)?; fp_utils::when( authentication::blacklist::check_user_in_blacklist(&state, &token.user_id, token.exp) .await?, || Err(errors::ApiErrorResponse::InvalidJwtToken), )?; token.check_service_type(&external_service_type)?; let user_in_db = state .global_store .find_user_by_id(&token.user_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("User not found in database")?; let email = user_in_db.email.clone(); let name = user_in_db.name; Ok(service_api::ApplicationResponse::Json( external_service_auth_api::ExternalVerifyTokenResponse::Hypersense { user_id: user_in_db.user_id, merchant_id: token.merchant_id, name, email, }, )) }
{ "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_generate_external_token_-8083920335894949583
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/external_service_auth pub async fn generate_external_token( state: SessionState, user: authentication::UserFromToken, external_service_type: ExternalServiceType, ) -> RouterResponse<external_service_auth_api::ExternalTokenResponse> { let token = ExternalToken::new_token( user.user_id.clone(), user.merchant_id.clone(), &state.conf, external_service_type.clone(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed to create external token for params [user_id, mid, external_service_type] [{}, {:?}, {:?}]", user.user_id, user.merchant_id, external_service_type, ) })?; Ok(service_api::ApplicationResponse::Json( external_service_auth_api::ExternalTokenResponse { 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": 29, "total_crates": null }
fn_clm_router_signout_external_token_-8083920335894949583
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/external_service_auth pub async fn signout_external_token( state: SessionState, json_payload: external_service_auth_api::ExternalSignoutTokenRequest, ) -> RouterResponse<()> { let token = authentication::decode_jwt::<ExternalToken>(&json_payload.token.expose(), &state) .await .change_context(errors::ApiErrorResponse::Unauthorized)?; authentication::blacklist::insert_user_in_blacklist(&state, &token.user_id) .await .change_context(errors::ApiErrorResponse::InvalidJwtToken)?; 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": 21, "total_crates": null }
fn_clm_router_verify_connector_credentials_-3879481470325202830
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/verify_connector pub async fn verify_connector_credentials( state: SessionState, req: VerifyConnectorRequest, _profile_id: Option<common_utils::id_type::ProfileId>, ) -> errors::RouterResponse<()> { let boxed_connector = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &req.connector_name.to_string(), api::GetToken::Connector, None, ) .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)?; let card_details = utils::get_test_card_details(req.connector_name)?.ok_or( errors::ApiErrorResponse::FlowNotSupported { flow: "Verify credentials".to_string(), connector: req.connector_name.to_string(), }, )?; match req.connector_name { Connector::Stripe => { connector::Stripe::verify( &state, types::VerifyConnectorData { connector: boxed_connector.connector, connector_auth: req.connector_account_details.foreign_into(), card_details, }, ) .await } Connector::Paypal => connector::Paypal::get_access_token( &state, types::VerifyConnectorData { connector: boxed_connector.connector, connector_auth: req.connector_account_details.foreign_into(), card_details, }, ) .await .map(|_| services::ApplicationResponse::StatusOk), _ => Err(errors::ApiErrorResponse::FlowNotSupported { flow: "Verify credentials".to_string(), connector: req.connector_name.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": 43, "total_crates": null }
fn_clm_router_form_payment_link_data_279346092998530328
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_link pub async fn form_payment_link_data( state: &SessionState, merchant_context: domain::MerchantContext, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResult<(PaymentLink, PaymentLinkData, PaymentLinkConfig)> { let db = &*state.store; let key_manager_state = &state.into(); 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_link_id = payment_intent .payment_link_id .get_required_value("payment_link_id") .change_context(errors::ApiErrorResponse::PaymentLinkNotFound)?; let merchant_name_from_merchant_account = merchant_context .get_merchant_account() .merchant_name .clone() .map(|merchant_name| merchant_name.into_inner().peek().to_owned()) .unwrap_or_default(); let payment_link = db .find_payment_link_by_payment_link_id(&payment_link_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; let payment_link_config = if let Some(pl_config_value) = payment_link.payment_link_config.clone() { extract_payment_link_config(pl_config_value)? } else { PaymentLinkConfig { theme: DEFAULT_BACKGROUND_COLOR.to_string(), logo: DEFAULT_MERCHANT_LOGO.to_string(), seller_name: merchant_name_from_merchant_account, sdk_layout: DEFAULT_SDK_LAYOUT.to_owned(), display_sdk_only: DEFAULT_DISPLAY_SDK_ONLY, enabled_saved_payment_method: DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, hide_card_nickname_field: DEFAULT_HIDE_CARD_NICKNAME_FIELD, show_card_form_by_default: DEFAULT_SHOW_CARD_FORM, allowed_domains: DEFAULT_ALLOWED_DOMAINS, transaction_details: None, background_image: None, details_layout: None, branding_visibility: None, payment_button_text: None, custom_message_for_card_terms: None, payment_button_colour: None, skip_status_screen: None, background_colour: None, payment_button_text_colour: None, sdk_ui_rules: None, payment_link_ui_rules: None, enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, payment_form_header_text: None, payment_form_label_type: None, show_card_terms: None, is_setup_mandate_flow: None, color_icon_card_cvc_error: None, } }; let profile_id = payment_link .profile_id .clone() .or(payment_intent.profile_id) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Profile id missing in payment link and payment intent")?; let business_profile = db .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let return_url = if let Some(payment_create_return_url) = payment_intent.return_url.clone() { payment_create_return_url } else { business_profile .return_url .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "return_url", })? }; let (currency, client_secret) = validate_sdk_requirements( payment_intent.currency, payment_intent.client_secret.clone(), )?; let required_conversion_type = StringMajorUnitForCore; let amount = required_conversion_type .convert(payment_intent.amount, currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; let order_details = validate_order_details(payment_intent.order_details.clone(), currency)?; let session_expiry = payment_link.fulfilment_time.unwrap_or_else(|| { payment_intent .created_at .saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY)) }); // converting first letter of merchant name to upperCase let merchant_name = capitalize_first_char(&payment_link_config.seller_name); let payment_link_status = check_payment_link_status(session_expiry); let is_payment_link_terminal_state = check_payment_link_invalid_conditions( payment_intent.status, &[ storage_enums::IntentStatus::Cancelled, storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Processing, storage_enums::IntentStatus::RequiresCapture, storage_enums::IntentStatus::RequiresMerchantAction, storage_enums::IntentStatus::Succeeded, storage_enums::IntentStatus::PartiallyCaptured, storage_enums::IntentStatus::RequiresCustomerAction, ], ); let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, &merchant_id, &attempt_id.clone(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; if is_payment_link_terminal_state || payment_link_status == api_models::payments::PaymentLinkStatus::Expired { let status = match payment_link_status { api_models::payments::PaymentLinkStatus::Active => { logger::info!("displaying status page as the requested payment link has reached terminal state with payment status as {:?}", payment_intent.status); PaymentLinkStatusWrap::IntentStatus(payment_intent.status) } api_models::payments::PaymentLinkStatus::Expired => { if is_payment_link_terminal_state { logger::info!("displaying status page as the requested payment link has reached terminal state with payment status as {:?}", payment_intent.status); PaymentLinkStatusWrap::IntentStatus(payment_intent.status) } else { logger::info!( "displaying status page as the requested payment link has expired" ); PaymentLinkStatusWrap::PaymentLinkStatus( api_models::payments::PaymentLinkStatus::Expired, ) } } }; let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, &merchant_id, &attempt_id.clone(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_details = api_models::payments::PaymentLinkStatusDetails { amount, currency, payment_id: payment_intent.payment_id, merchant_name, merchant_logo: payment_link_config.logo.clone(), created: payment_link.created_at, status, error_code: payment_attempt.error_code, error_message: payment_attempt.error_message, redirect: false, theme: payment_link_config.theme.clone(), return_url: return_url.clone(), locale: Some(state.clone().locale), transaction_details: payment_link_config.transaction_details.clone(), unified_code: payment_attempt.unified_code, unified_message: payment_attempt.unified_message, capture_method: payment_attempt.capture_method, setup_future_usage_applied: payment_attempt.setup_future_usage_applied, }; return Ok(( payment_link, PaymentLinkData::PaymentLinkStatusDetails(Box::new(payment_details)), payment_link_config, )); }; let payment_link_details = api_models::payments::PaymentLinkDetails { amount, currency, payment_id: payment_intent.payment_id, merchant_name, order_details, return_url, session_expiry, pub_key: merchant_context .get_merchant_account() .publishable_key .to_owned(), client_secret, merchant_logo: payment_link_config.logo.clone(), max_items_visible_after_collapse: 3, theme: payment_link_config.theme.clone(), merchant_description: payment_intent.description, sdk_layout: payment_link_config.sdk_layout.clone(), display_sdk_only: payment_link_config.display_sdk_only, hide_card_nickname_field: payment_link_config.hide_card_nickname_field, show_card_form_by_default: payment_link_config.show_card_form_by_default, locale: Some(state.clone().locale), transaction_details: payment_link_config.transaction_details.clone(), background_image: payment_link_config.background_image.clone(), details_layout: payment_link_config.details_layout, branding_visibility: payment_link_config.branding_visibility, payment_button_text: payment_link_config.payment_button_text.clone(), custom_message_for_card_terms: payment_link_config.custom_message_for_card_terms.clone(), payment_button_colour: payment_link_config.payment_button_colour.clone(), skip_status_screen: payment_link_config.skip_status_screen, background_colour: payment_link_config.background_colour.clone(), payment_button_text_colour: payment_link_config.payment_button_text_colour.clone(), sdk_ui_rules: payment_link_config.sdk_ui_rules.clone(), status: payment_intent.status, enable_button_only_on_form_ready: payment_link_config.enable_button_only_on_form_ready, payment_form_header_text: payment_link_config.payment_form_header_text.clone(), payment_form_label_type: payment_link_config.payment_form_label_type, show_card_terms: payment_link_config.show_card_terms, is_setup_mandate_flow: payment_link_config.is_setup_mandate_flow, color_icon_card_cvc_error: payment_link_config.color_icon_card_cvc_error.clone(), capture_method: payment_attempt.capture_method, setup_future_usage_applied: payment_attempt.setup_future_usage_applied, }; Ok(( payment_link, PaymentLinkData::PaymentLinkDetails(Box::new(payment_link_details)), payment_link_config, )) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 186, "total_crates": null }
fn_clm_router_get_payment_link_status_279346092998530328
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_link pub async fn get_payment_link_status( state: SessionState, merchant_context: domain::MerchantContext, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResponse<services::PaymentLinkFormData> { let db = &*state.store; let key_manager_state = &(&state).into(); let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, &merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, &merchant_id, &attempt_id.clone(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_link_id = payment_intent .payment_link_id .get_required_value("payment_link_id") .change_context(errors::ApiErrorResponse::PaymentLinkNotFound)?; let merchant_name_from_merchant_account = merchant_context .get_merchant_account() .merchant_name .clone() .map(|merchant_name| merchant_name.into_inner().peek().to_owned()) .unwrap_or_default(); let payment_link = db .find_payment_link_by_payment_link_id(&payment_link_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; let payment_link_config = if let Some(pl_config_value) = payment_link.payment_link_config { extract_payment_link_config(pl_config_value)? } else { PaymentLinkConfig { theme: DEFAULT_BACKGROUND_COLOR.to_string(), logo: DEFAULT_MERCHANT_LOGO.to_string(), seller_name: merchant_name_from_merchant_account, sdk_layout: DEFAULT_SDK_LAYOUT.to_owned(), display_sdk_only: DEFAULT_DISPLAY_SDK_ONLY, enabled_saved_payment_method: DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, hide_card_nickname_field: DEFAULT_HIDE_CARD_NICKNAME_FIELD, show_card_form_by_default: DEFAULT_SHOW_CARD_FORM, allowed_domains: DEFAULT_ALLOWED_DOMAINS, transaction_details: None, background_image: None, details_layout: None, branding_visibility: None, payment_button_text: None, custom_message_for_card_terms: None, payment_button_colour: None, skip_status_screen: None, background_colour: None, payment_button_text_colour: None, sdk_ui_rules: None, payment_link_ui_rules: None, enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, payment_form_header_text: None, payment_form_label_type: None, show_card_terms: None, is_setup_mandate_flow: None, color_icon_card_cvc_error: None, } }; let currency = payment_intent .currency .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "currency", })?; let required_conversion_type = StringMajorUnitForCore; let amount = required_conversion_type .convert(payment_attempt.get_total_amount(), currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; // converting first letter of merchant name to upperCase let merchant_name = capitalize_first_char(&payment_link_config.seller_name); let css_script = get_color_scheme_css(&payment_link_config); let profile_id = payment_link .profile_id .or(payment_intent.profile_id) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Profile id missing in payment link and payment intent")?; let business_profile = db .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let return_url = if let Some(payment_create_return_url) = payment_intent.return_url.clone() { payment_create_return_url } else { business_profile .return_url .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "return_url", })? }; let (unified_code, unified_message) = if let Some((code, message)) = payment_attempt .unified_code .as_ref() .zip(payment_attempt.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(), ) }; let unified_translated_message = helpers::get_unified_translation( &state, unified_code.to_owned(), unified_message.to_owned(), state.locale.clone(), ) .await .or(Some(unified_message)); let payment_details = api_models::payments::PaymentLinkStatusDetails { amount, currency, payment_id: payment_intent.payment_id, merchant_name, merchant_logo: payment_link_config.logo.clone(), created: payment_link.created_at, status: PaymentLinkStatusWrap::IntentStatus(payment_intent.status), error_code: payment_attempt.error_code, error_message: payment_attempt.error_message, redirect: true, theme: payment_link_config.theme.clone(), return_url, locale: Some(state.locale.clone()), transaction_details: payment_link_config.transaction_details, unified_code: Some(unified_code), unified_message: unified_translated_message, capture_method: payment_attempt.capture_method, setup_future_usage_applied: payment_attempt.setup_future_usage_applied, }; let js_script = get_js_script(&PaymentLinkData::PaymentLinkStatusDetails(Box::new( payment_details, )))?; let payment_link_status_data = services::PaymentLinkStatusData { js_script, css_script, }; Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_status_data), ))) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 147, "total_crates": null }
fn_clm_router_initiate_secure_payment_link_flow_279346092998530328
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_link pub async fn initiate_secure_payment_link_flow( state: SessionState, merchant_context: domain::MerchantContext, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, request_headers: &header::HeaderMap, ) -> RouterResponse<services::PaymentLinkFormData> { let (payment_link, payment_link_details, payment_link_config) = form_payment_link_data(&state, merchant_context, merchant_id, payment_id).await?; validator::validate_secure_payment_link_render_request( request_headers, &payment_link, &payment_link_config, )?; let css_script = get_payment_link_css_script(&payment_link_config)?; match payment_link_details { PaymentLinkData::PaymentLinkStatusDetails(ref status_details) => { let js_script = get_js_script(&payment_link_details)?; let payment_link_error_data = services::PaymentLinkStatusData { js_script, css_script, }; logger::info!( "payment link data, for building payment link status page {:?}", status_details ); Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data), ))) } PaymentLinkData::PaymentLinkDetails(link_details) => { let secure_payment_link_details = api_models::payments::SecurePaymentLinkDetails { enabled_saved_payment_method: payment_link_config.enabled_saved_payment_method, hide_card_nickname_field: payment_link_config.hide_card_nickname_field, show_card_form_by_default: payment_link_config.show_card_form_by_default, payment_link_details: *link_details.to_owned(), payment_button_text: payment_link_config.payment_button_text, custom_message_for_card_terms: payment_link_config.custom_message_for_card_terms, payment_button_colour: payment_link_config.payment_button_colour, skip_status_screen: payment_link_config.skip_status_screen, background_colour: payment_link_config.background_colour, payment_button_text_colour: payment_link_config.payment_button_text_colour, sdk_ui_rules: payment_link_config.sdk_ui_rules, enable_button_only_on_form_ready: payment_link_config .enable_button_only_on_form_ready, payment_form_header_text: payment_link_config.payment_form_header_text, payment_form_label_type: payment_link_config.payment_form_label_type, show_card_terms: payment_link_config.show_card_terms, color_icon_card_cvc_error: payment_link_config.color_icon_card_cvc_error, }; let payment_details_str = serde_json::to_string(&secure_payment_link_details) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentLinkData")?; let url_encoded_str = urlencoding::encode(&payment_details_str); let js_script = format!("window.__PAYMENT_DETAILS = '{url_encoded_str}';"); let html_meta_tags = get_meta_tags_html(&link_details); let payment_link_data = services::PaymentLinkFormData { js_script, sdk_url: state.conf.payment_link.sdk_url.clone(), css_script, html_meta_tags, }; let allowed_domains = payment_link_config .allowed_domains .clone() .ok_or(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| { format!( "Invalid list of allowed_domains found - {:?}", payment_link_config.allowed_domains.clone() ) })?; if allowed_domains.is_empty() { return Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| { format!( "Invalid list of allowed_domains found - {:?}", payment_link_config.allowed_domains.clone() ) }); } let link_data = GenericLinks { allowed_domains, data: GenericLinksData::SecurePaymentLink(payment_link_data), locale: DEFAULT_LOCALE.to_string(), }; logger::info!( "payment link data, for building secure payment link {:?}", link_data ); Ok(services::ApplicationResponse::GenericLinkForm(Box::new( link_data, ))) } } }
{ "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_camel_to_kebab_279346092998530328
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_link fn camel_to_kebab(s: &str) -> String { let mut result = String::new(); if s.is_empty() { return result; } let chars: Vec<char> = s.chars().collect(); for (i, &ch) in chars.iter().enumerate() { if ch.is_uppercase() { let should_add_dash = i > 0 && (chars.get(i - 1).map(|c| c.is_lowercase()).unwrap_or(false) || (i + 1 < chars.len() && chars.get(i + 1).map(|c| c.is_lowercase()).unwrap_or(false) && chars.get(i - 1).map(|c| c.is_uppercase()).unwrap_or(false))); if should_add_dash { result.push('-'); } result.push(ch.to_ascii_lowercase()); } else { result.push(ch); } } result }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 51, "total_crates": null }
fn_clm_router_validate_order_details_279346092998530328
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_link fn validate_order_details( order_details: Option<Vec<Secret<serde_json::Value>>>, currency: api_models::enums::Currency, ) -> Result< Option<Vec<api_models::payments::OrderDetailsWithStringAmount>>, error_stack::Report<errors::ApiErrorResponse>, > { let required_conversion_type = StringMajorUnitForCore; let order_details = order_details .map(|order_details| { order_details .iter() .map(|data| { data.to_owned() .parse_value("OrderDetailsWithAmount") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "OrderDetailsWithAmount", }) .attach_printable("Unable to parse OrderDetailsWithAmount") }) .collect::<Result<Vec<api_models::payments::OrderDetailsWithAmount>, _>>() }) .transpose()?; let updated_order_details = match order_details { Some(mut order_details) => { let mut order_details_amount_string_array: Vec< api_models::payments::OrderDetailsWithStringAmount, > = Vec::new(); for order in order_details.iter_mut() { let mut order_details_amount_string : api_models::payments::OrderDetailsWithStringAmount = Default::default(); if order.product_img_link.is_none() { order_details_amount_string.product_img_link = Some(DEFAULT_PRODUCT_IMG.to_string()) } else { order_details_amount_string .product_img_link .clone_from(&order.product_img_link) }; order_details_amount_string.amount = required_conversion_type .convert(order.amount, currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; order_details_amount_string.product_name = capitalize_first_char(&order.product_name.clone()); order_details_amount_string.quantity = order.quantity; order_details_amount_string_array.push(order_details_amount_string) } Some(order_details_amount_string_array) } None => None, }; Ok(updated_order_details) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 41, "total_crates": null }
fn_clm_router_send_recon_request_-8914743855173559517
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/recon pub async fn send_recon_request( state: SessionState, auth_data: authentication::AuthenticationDataWithUser, ) -> RouterResponse<recon_api::ReconStatusResponse> { #[cfg(not(feature = "email"))] return Ok(service_api::ApplicationResponse::Json( recon_api::ReconStatusResponse { recon_status: enums::ReconStatus::NotRequested, }, )); #[cfg(feature = "email")] { let user_in_db = &auth_data.user; let merchant_id = auth_data.merchant_account.get_id().clone(); let theme = theme_utils::get_most_specific_theme_using_lineage( &state.clone(), ThemeLineage::Merchant { tenant_id: state.tenant.tenant_id.clone(), org_id: auth_data.merchant_account.get_org_id().clone(), merchant_id: merchant_id.clone(), }, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!( "Failed to fetch theme for merchant_id = {merchant_id:?}", ))?; let user_email = user_in_db.email.clone(); let email_contents = email_types::ProFeatureRequest { feature_name: consts::RECON_FEATURE_TAG.to_string(), merchant_id: merchant_id.clone(), user_name: domain::UserName::new(user_in_db.name.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to form username")?, user_email: domain::UserEmail::from_pii_email(user_email.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert recipient's email to UserEmail")?, recipient_email: domain::UserEmail::from_pii_email( state.conf.email.recon_recipient_email.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert recipient's email to UserEmail")?, subject: format!( "{} {}", consts::EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST, user_email.expose().peek() ), theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; state .email_client .compose_and_send_email( user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to compose and send email for ProFeatureRequest [Recon]") .async_and_then(|_| async { let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate { recon_status: enums::ReconStatus::Requested, }; let db = &*state.store; let key_manager_state = &(&state).into(); let response = db .update_merchant( key_manager_state, auth_data.merchant_account, updated_merchant_account, &auth_data.key_store, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Failed while updating merchant's recon status: {merchant_id:?}") })?; Ok(service_api::ApplicationResponse::Json( recon_api::ReconStatusResponse { recon_status: response.recon_status, }, )) }) .await } }
{ "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_recon_merchant_account_update_-8914743855173559517
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/recon pub async fn recon_merchant_account_update( state: SessionState, auth: authentication::AuthenticationData, req: recon_api::ReconUpdateMerchantRequest, ) -> RouterResponse<api_types::MerchantAccountResponse> { let db = &*state.store; let key_manager_state = &(&state).into(); let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate { recon_status: req.recon_status, }; let merchant_id = auth.merchant_account.get_id().clone(); let updated_merchant_account = db .update_merchant( key_manager_state, auth.merchant_account.clone(), updated_merchant_account, &auth.key_store, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Failed while updating merchant's recon status: {merchant_id:?}") })?; #[cfg(feature = "email")] { let user_email = &req.user_email.clone(); let theme = theme_utils::get_most_specific_theme_using_lineage( &state.clone(), ThemeLineage::Merchant { tenant_id: state.tenant.tenant_id.clone(), org_id: auth.merchant_account.get_org_id().clone(), merchant_id: merchant_id.clone(), }, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!( "Failed to fetch theme for merchant_id = {merchant_id:?}", ))?; let email_contents = email_types::ReconActivation { recipient_email: domain::UserEmail::from_pii_email(user_email.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to convert recipient's email to UserEmail from pii::Email", )?, user_name: domain::UserName::new(Secret::new("HyperSwitch User".to_string())) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to form username")?, subject: consts::EMAIL_SUBJECT_APPROVAL_RECON_REQUEST, theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; if req.recon_status == enums::ReconStatus::Active { let _ = state .email_client .compose_and_send_email( user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await .inspect_err(|err| { router_env::logger::error!( "Failed to compose and send email notifying them of recon activation: {}", err ) }) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to compose and send email for ReconActivation"); } } Ok(service_api::ApplicationResponse::Json( api_types::MerchantAccountResponse::foreign_try_from(updated_merchant_account) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_account", })?, )) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 97, "total_crates": null }
fn_clm_router_verify_recon_token_-8914743855173559517
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/recon pub async fn verify_recon_token( state: SessionState, user_with_role: authentication::UserFromTokenWithRoleInfo, ) -> UserResponse<recon_api::VerifyTokenResponse> { let user = user_with_role.user; let user_in_db = user .get_user_from_db(&state) .await .attach_printable_lazy(|| { format!( "Failed to fetch the user from DB for user_id - {}", user.user_id ) })?; let acl = user_with_role.role_info.get_recon_acl(); let optional_acl_str = serde_json::to_string(&acl) .inspect_err(|err| router_env::logger::error!("Failed to serialize acl to string: {}", err)) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to serialize acl to string. Using empty ACL") .ok(); Ok(service_api::ApplicationResponse::Json( recon_api::VerifyTokenResponse { merchant_id: user.merchant_id.to_owned(), user_email: user_in_db.0.email, acl: optional_acl_str, }, )) }
{ "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_generate_recon_token_-8914743855173559517
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/recon pub async fn generate_recon_token( state: SessionState, user_with_role: authentication::UserFromTokenWithRoleInfo, ) -> RouterResponse<recon_api::ReconTokenResponse> { let user = user_with_role.user; let token = authentication::ReconToken::new_token( user.user_id.clone(), user.merchant_id.clone(), &state.conf, user.org_id.clone(), user.profile_id.clone(), user.tenant_id, user_with_role.role_info, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed to create recon token for params [user_id, org_id, mid, pid] [{}, {:?}, {:?}, {:?}]", user.user_id, user.org_id, user.merchant_id, user.profile_id, ) })?; Ok(service_api::ApplicationResponse::Json( recon_api::ReconTokenResponse { 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": 31, "total_crates": null }
fn_clm_router_retrieve_poll_status_-3060921957797650472
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/poll pub async fn retrieve_poll_status( state: SessionState, req: crate::types::api::PollId, merchant_context: domain::MerchantContext, ) -> RouterResponse<PollResponse> { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let request_poll_id = req.poll_id; // prepend 'poll_{merchant_id}_' to restrict access to only fetching Poll IDs, as this is a freely passed string in the request let poll_id = super::utils::get_poll_id( merchant_context.get_merchant_account().get_id(), request_poll_id.clone(), ); let redis_value = redis_conn .get_key::<Option<String>>(&poll_id.as_str().into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Error while fetching the value for {} from redis", poll_id.clone() ) })? .ok_or(errors::ApiErrorResponse::PollNotFound { id: request_poll_id.clone(), })?; let status = redis_value .parse_enum("PollStatus") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing PollStatus")?; let poll_response = PollResponse { poll_id: request_poll_id, status, }; Ok(ApplicationResponse::Json(poll_response)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 47, "total_crates": null }
fn_clm_router_new_-5063512207973406543
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/api_keys // Implementation of None for PlaintextApiKey pub fn new(length: usize) -> Self { let env = router_env::env::prefix_for_env(); let key = common_utils::crypto::generate_cryptographically_secure_random_string(length); Self(format!("{env}_{key}").into()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14471, "total_crates": null }
fn_clm_router_from_-5063512207973406543
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/api_keys // Implementation of HashedApiKey for From<storage::HashedApiKey> fn from(hashed_api_key: storage::HashedApiKey) -> Self { Self(hashed_api_key.into_inner()) }
{ "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_peek_-5063512207973406543
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/api_keys // Implementation of None for PlaintextApiKey pub fn peek(&self) -> &str { self.0.peek() }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 1205, "total_crates": null }
fn_clm_router_update_api_key_-5063512207973406543
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/api_keys pub async fn update_api_key( state: SessionState, api_key: api::UpdateApiKeyRequest, ) -> RouterResponse<api::RetrieveApiKeyResponse> { let merchant_id = api_key.merchant_id.clone(); let key_id = api_key.key_id.clone(); let store = state.store.as_ref(); let api_key = store .update_api_key( merchant_id.to_owned(), key_id.to_owned(), api_key.foreign_into(), ) .await .to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?; let state_inner = state.clone(); let hashed_api_key = api_key.hashed_api_key.clone(); let key_id_inner = api_key.key_id.clone(); let expires_at = api_key.expires_at; authentication::decision::spawn_tracked_job( async move { authentication::decision::add_api_key( &state_inner, hashed_api_key.into_inner().into(), merchant_id.clone(), key_id_inner, expires_at.map(authentication::decision::convert_expiry), ) .await }, authentication::decision::ADD, ); #[cfg(feature = "email")] { let expiry_reminder_days = state.conf.api_keys.get_inner().expiry_reminder_days.clone(); let task_id = generate_task_id_for_api_key_expiry_workflow(&key_id); // In order to determine how to update the existing process in the process_tracker table, // we need access to the current entry in the table. let existing_process_tracker_task = store .find_process_by_id(task_id.as_str()) .await .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed .attach_printable( "Failed to retrieve API key expiry reminder task from process tracker", )?; // If process exist if existing_process_tracker_task.is_some() { if api_key.expires_at.is_some() { // Process exist in process, update the process with new schedule_time update_api_key_expiry_task(store, &api_key, expiry_reminder_days) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to update API key expiry reminder task in process tracker", )?; } // If an expiry is set to 'never' else { // Process exist in process, revoke it revoke_api_key_expiry_task(store, &key_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to revoke API key expiry reminder task in process tracker", )?; } } // This case occurs if the expiry for an API key is set to 'never' during its creation. If so, // process in tracker was not created. else if api_key.expires_at.is_some() { // Process doesn't exist in process_tracker table, so create new entry with // schedule_time based on new expiry set. add_api_key_expiry_task(store, &api_key, expiry_reminder_days) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to insert API key expiry reminder task to process tracker", )?; } } Ok(ApplicationResponse::Json(api_key.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": 98, "total_crates": null }
fn_clm_router_create_api_key_-5063512207973406543
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/api_keys pub async fn create_api_key( state: SessionState, api_key: api::CreateApiKeyRequest, key_store: domain::MerchantKeyStore, ) -> RouterResponse<api::CreateApiKeyResponse> { let api_key_config = state.conf.api_keys.get_inner(); let store = state.store.as_ref(); let merchant_id = key_store.merchant_id.clone(); let hash_key = api_key_config.get_hash_key()?; let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH); let api_key = storage::ApiKeyNew { key_id: PlaintextApiKey::new_key_id(), merchant_id: merchant_id.to_owned(), name: api_key.name, description: api_key.description, hashed_api_key: plaintext_api_key.keyed_hash(hash_key.peek()).into(), prefix: plaintext_api_key.prefix(), created_at: date_time::now(), expires_at: api_key.expiration.into(), last_used: None, }; let api_key = store .insert_api_key(api_key) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert new API key")?; let state_inner = state.clone(); let hashed_api_key = api_key.hashed_api_key.clone(); let merchant_id_inner = merchant_id.clone(); let key_id = api_key.key_id.clone(); let expires_at = api_key.expires_at; authentication::decision::spawn_tracked_job( async move { authentication::decision::add_api_key( &state_inner, hashed_api_key.into_inner().into(), merchant_id_inner, key_id, expires_at.map(authentication::decision::convert_expiry), ) .await }, authentication::decision::ADD, ); metrics::API_KEY_CREATED.add( 1, router_env::metric_attributes!(("merchant", merchant_id.clone())), ); // Add process to process_tracker for email reminder, only if expiry is set to future date // If the `api_key` is set to expire in less than 7 days, the merchant is not notified about it's expiry #[cfg(feature = "email")] { if api_key.expires_at.is_some() { let expiry_reminder_days = state.conf.api_keys.get_inner().expiry_reminder_days.clone(); add_api_key_expiry_task(store, &api_key, expiry_reminder_days) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert API key expiry reminder to process tracker")?; } } Ok(ApplicationResponse::Json( (api_key, plaintext_api_key).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": 81, "total_crates": null }
fn_clm_router_from_-4232768965017489164
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/errors // Implementation of VecLinearErrorStack<'a> for From<Vec<NestedErrorStack<'a>>> fn from(value: Vec<NestedErrorStack<'a>>) -> Self { let multi_layered_errors: Vec<_> = value .into_iter() .flat_map(|current_error| { [LinearErrorStack { context: current_error.context, attachments: current_error.attachments, }] .into_iter() .chain(Into::<VecLinearErrorStack<'a>>::into(current_error.sources).0) }) .collect(); Self(multi_layered_errors) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 2614, "total_crates": null }
fn_clm_router_http_not_implemented_-4232768965017489164
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/errors pub fn http_not_implemented() -> actix_web::HttpResponse<BoxBody> { ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Default, } .error_response() }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 21, "total_crates": null }
fn_clm_router_is_webhook_delivery_retryable_error_-4232768965017489164
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/errors // Inherent implementation for WebhooksFlowError pub(crate) fn is_webhook_delivery_retryable_error(&self) -> bool { match self { Self::MerchantConfigNotFound | Self::MerchantWebhookDetailsNotFound | Self::MerchantWebhookUrlNotConfigured | Self::OutgoingWebhookResponseEncodingFailed => false, Self::WebhookEventUpdationFailed | Self::OutgoingWebhookSigningFailed | Self::CallToMerchantFailed | Self::NotReceivedByMerchant | Self::DisputeWebhookValidationFailed | Self::OutgoingWebhookEncodingFailed | Self::OutgoingWebhookProcessTrackerTaskUpdateFailed | Self::OutgoingWebhookRetrySchedulingFailed | Self::IdGenerationFailed => true, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 21, "total_crates": null }
fn_clm_router_redact_customer_details_and_generate_response_-2635540255479864309
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/customers // Implementation of id_type::CustomerId for CustomerDeleteBridge async fn redact_customer_details_and_generate_response<'a>( &'a self, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse> { let customer_orig = db .find_customer_by_customer_id_merchant_id( key_manager_state, self, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()?; let customer_mandates = db .find_mandate_by_merchant_id_customer_id( merchant_context.get_merchant_account().get_id(), self, ) .await .switch()?; for mandate in customer_mandates.into_iter() { if mandate.mandate_status == enums::MandateStatus::Active { Err(errors::CustomersErrorResponse::MandateActive)? } } match db .find_payment_method_by_customer_id_merchant_id_list( key_manager_state, merchant_context.get_merchant_key_store(), self, merchant_context.get_merchant_account().get_id(), None, ) .await { // check this in review Ok(customer_payment_methods) => { for pm in customer_payment_methods.into_iter() { if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) { cards::PmCards { state, merchant_context, } .delete_card_from_locker( self, merchant_context.get_merchant_account().get_id(), pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await .switch()?; if let Some(network_token_ref_id) = pm.network_token_requestor_reference_id { network_tokenization::delete_network_token_from_locker_and_token_service( state, self, merchant_context.get_merchant_account().get_id(), pm.payment_method_id.clone(), pm.network_token_locker_id, network_token_ref_id, merchant_context, ) .await .switch()?; } } db.delete_payment_method_by_merchant_id_payment_method_id( key_manager_state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().get_id(), &pm.payment_method_id, ) .await .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable( "failed to delete payment method while redacting customer details", )?; } } Err(error) => { if error.current_context().is_db_not_found() { Ok(()) } else { Err(error) .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable( "failed find_payment_method_by_customer_id_merchant_id_list", ) }? } }; let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let identifier = Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ); let redacted_encrypted_value: Encryptable<Secret<_>> = types::crypto_operation( key_manager_state, type_name!(storage::Address), types::CryptoOperation::Encrypt(REDACTED.to_string().into()), identifier.clone(), key, ) .await .and_then(|val| val.try_into_operation()) .switch()?; let redacted_encrypted_email = Encryptable::new( redacted_encrypted_value .clone() .into_inner() .switch_strategy(), redacted_encrypted_value.clone().into_encrypted(), ); let update_address = storage::AddressUpdate::Update { city: Some(REDACTED.to_string()), country: None, line1: Some(redacted_encrypted_value.clone()), line2: Some(redacted_encrypted_value.clone()), line3: Some(redacted_encrypted_value.clone()), state: Some(redacted_encrypted_value.clone()), zip: Some(redacted_encrypted_value.clone()), first_name: Some(redacted_encrypted_value.clone()), last_name: Some(redacted_encrypted_value.clone()), phone_number: Some(redacted_encrypted_value.clone()), country_code: Some(REDACTED.to_string()), updated_by: merchant_context .get_merchant_account() .storage_scheme .to_string(), email: Some(redacted_encrypted_email), origin_zip: Some(redacted_encrypted_value.clone()), }; match db .update_address_by_merchant_id_customer_id( key_manager_state, self, merchant_context.get_merchant_account().get_id(), update_address, merchant_context.get_merchant_key_store(), ) .await { Ok(_) => Ok(()), Err(error) => { if error.current_context().is_db_not_found() { Ok(()) } else { Err(error) .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("failed update_address_by_merchant_id_customer_id") } } }?; let updated_customer = storage::CustomerUpdate::Update { name: Some(redacted_encrypted_value.clone()), email: Some( types::crypto_operation( key_manager_state, type_name!(storage::Customer), types::CryptoOperation::Encrypt(REDACTED.to_string().into()), identifier, key, ) .await .and_then(|val| val.try_into_operation()) .switch()?, ), phone: Box::new(Some(redacted_encrypted_value.clone())), description: Some(Description::from_str_unchecked(REDACTED)), phone_country_code: Some(REDACTED.to_string()), metadata: Box::new(None), connector_customer: Box::new(None), address_id: None, tax_registration_id: Some(redacted_encrypted_value.clone()), }; db.update_customer_by_customer_id_merchant_id( key_manager_state, self.clone(), merchant_context.get_merchant_account().get_id().to_owned(), customer_orig, updated_customer, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()?; let response = customers::CustomerDeleteResponse { customer_id: self.clone(), customer_deleted: true, address_deleted: true, payment_methods_deleted: true, }; metrics::CUSTOMER_REDACTED.add(1, &[]); Ok(services::ApplicationResponse::Json(response)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 221, "total_crates": null }
fn_clm_router_create_domain_model_from_request_-2635540255479864309
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/customers // Implementation of customers::CustomerUpdateRequest for CustomerUpdateBridge async fn create_domain_model_from_request<'a>( &'a self, connector_customer_details: &'a Option< Vec<payment_methods_domain::ConnectorCustomerDetails>, >, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, domain_customer: &'a domain::Customer, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> { let default_billing_address = self.get_default_customer_billing_address(); let encrypted_customer_billing_address = default_billing_address .async_map(|billing_address| { create_encrypted_data( key_manager_state, merchant_context.get_merchant_key_store(), billing_address, ) }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Unable to encrypt default customer billing address")?; let default_shipping_address = self.get_default_customer_shipping_address(); let encrypted_customer_shipping_address = default_shipping_address .async_map(|shipping_address| { create_encrypted_data( key_manager_state, merchant_context.get_merchant_key_store(), shipping_address, ) }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Unable to encrypt default customer shipping address")?; let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let encrypted_data = types::crypto_operation( key_manager_state, type_name!(domain::Customer), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: self.name.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), phone: self.phone.clone(), tax_registration_id: self.tax_registration_id.clone(), }, ), ), Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), key, ) .await .and_then(|val| val.try_into_batchoperation()) .switch()?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::CustomersErrorResponse::InternalServerError)?; let response = db .update_customer_by_global_id( key_manager_state, &domain_customer.id, domain_customer.to_owned(), storage::CustomerUpdate::Update(Box::new(storage::CustomerGeneralUpdate { name: encryptable_customer.name, email: Box::new(encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable })), phone: Box::new(encryptable_customer.phone), tax_registration_id: encryptable_customer.tax_registration_id, phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), description: self.description.clone(), connector_customer: Box::new(None), default_billing_address: encrypted_customer_billing_address.map(Into::into), default_shipping_address: encrypted_customer_shipping_address.map(Into::into), default_payment_method_id: Some(self.default_payment_method_id.clone()), status: None, })), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()?; Ok(response) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 148, "total_crates": null }
fn_clm_router_generate_response_-2635540255479864309
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/customers // Implementation of customers::CustomerUpdateRequest for CustomerUpdateBridge fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from(customer.clone()), )) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 71, "total_crates": null }
fn_clm_router_update_address_if_sent_-2635540255479864309
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/customers // Inherent implementation for AddressStructForDbUpdate<'_> async fn update_address_if_sent( &self, db: &dyn StorageInterface, ) -> errors::CustomResult<Option<domain::Address>, errors::CustomersErrorResponse> { let address = if let Some(addr) = &self.update_customer.address { match self.domain_customer.address_id.clone() { Some(address_id) => { let customer_address: api_models::payments::AddressDetails = addr.clone(); let update_address = self .update_customer .get_address_update( self.state, customer_address, self.key_store.key.get_inner().peek(), self.merchant_account.storage_scheme, self.merchant_account.get_id().clone(), ) .await .switch() .attach_printable("Failed while encrypting Address while Update")?; Some( db.update_address( self.key_manager_state, address_id, update_address, self.key_store, ) .await .switch() .attach_printable(format!( "Failed while updating address: merchant_id: {:?}, customer_id: {:?}", self.merchant_account.get_id(), self.domain_customer.customer_id ))?, ) } None => { let customer_address: api_models::payments::AddressDetails = addr.clone(); let address = self .update_customer .get_domain_address( self.state, customer_address, self.merchant_account.get_id(), &self.domain_customer.customer_id, self.key_store.key.get_inner().peek(), self.merchant_account.storage_scheme, ) .await .switch() .attach_printable("Failed while encrypting address")?; Some( db.insert_address_for_customers( self.key_manager_state, address, self.key_store, ) .await .switch() .attach_printable("Failed while inserting new address")?, ) } } } else { match &self.domain_customer.address_id { Some(address_id) => Some( db.find_address_by_address_id( self.key_manager_state, address_id, self.key_store, ) .await .switch()?, ), None => None, } }; Ok(address) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 56, "total_crates": null }
fn_clm_router_create_customer_-2635540255479864309
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/customers pub async fn create_customer( state: SessionState, merchant_context: domain::MerchantContext, customer_data: customers::CustomerRequest, connector_customer_details: Option<Vec<payment_methods_domain::ConnectorCustomerDetails>>, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db: &dyn StorageInterface = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_reference_id = customer_data.get_merchant_reference_id(); let merchant_id = merchant_context.get_merchant_account().get_id(); let merchant_reference_id_customer = MerchantReferenceIdForCustomer { merchant_reference_id: merchant_reference_id.as_ref(), merchant_id, merchant_account: merchant_context.get_merchant_account(), key_store: merchant_context.get_merchant_key_store(), key_manager_state, }; // We first need to validate whether the customer with the given customer id already exists // this may seem like a redundant db call, as the insert_customer will anyway return this error // // Consider a scenario where the address is inserted and then when inserting the customer, // it errors out, now the address that was inserted is not deleted merchant_reference_id_customer .verify_if_merchant_reference_not_present_by_optional_merchant_reference_id(db) .await?; let domain_customer = customer_data .create_domain_model_from_request( &connector_customer_details, db, &merchant_reference_id, &merchant_context, key_manager_state, &state, ) .await?; let customer = db .insert_customer( domain_customer, key_manager_state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_duplicate_response(errors::CustomersErrorResponse::CustomerAlreadyExists)?; customer_data.generate_response(&customer) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 52, "total_crates": null }
fn_clm_router_update_gsm_rule_4586374256725578912
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/gsm pub async fn update_gsm_rule( state: SessionState, gsm_request: gsm_api_types::GsmUpdateRequest, ) -> RouterResponse<gsm_api_types::GsmResponse> { let db = state.store.as_ref(); let connector = gsm_request.connector.clone(); let flow = gsm_request.flow.clone(); let code = gsm_request.code.clone(); let sub_flow = gsm_request.sub_flow.clone(); let message = gsm_request.message.clone(); let gsm_db_record = GsmInterface::find_gsm_rule(db, connector.to_string(), flow, sub_flow, code, message) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "GSM with given key does not exist in our records".to_string(), })?; let inferred_feature_info = <( common_enums::GsmFeature, common_types::domain::GsmFeatureData, )>::foreign_from((&gsm_request, gsm_db_record)); let gsm_api_types::GsmUpdateRequest { connector, flow, sub_flow, code, message, decision, status, router_error, step_up_possible, unified_code, unified_message, error_category, clear_pan_possible, feature, feature_data, } = gsm_request; GsmInterface::update_gsm_rule( db, connector.to_string(), flow, sub_flow, code, message, hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate { decision, status, router_error: Some(router_error), step_up_possible: feature_data .as_ref() .and_then(|feature_data| feature_data.get_retry_feature_data()) .map(|retry_feature_data| retry_feature_data.is_step_up_possible()) .or(step_up_possible), unified_code, unified_message, error_category, clear_pan_possible: feature_data .as_ref() .and_then(|feature_data| feature_data.get_retry_feature_data()) .map(|retry_feature_data| retry_feature_data.is_clear_pan_possible()) .or(clear_pan_possible), feature_data: feature_data.or(Some(inferred_feature_info.1)), feature: feature.or(Some(inferred_feature_info.0)), }, ) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "GSM with given key does not exist in our records".to_string(), }) .attach_printable("Failed while updating Gsm rule") .map(|gsm| services::ApplicationResponse::Json(gsm.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": 85, "total_crates": null }
fn_clm_router_delete_gsm_rule_4586374256725578912
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/gsm pub async fn delete_gsm_rule( state: SessionState, gsm_request: gsm_api_types::GsmDeleteRequest, ) -> RouterResponse<gsm_api_types::GsmDeleteResponse> { let db = state.store.as_ref(); let gsm_api_types::GsmDeleteRequest { connector, flow, sub_flow, code, message, } = gsm_request; match GsmInterface::delete_gsm_rule( db, connector.to_string(), flow.to_owned(), sub_flow.to_owned(), code.to_owned(), message.to_owned(), ) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "GSM with given key does not exist in our records".to_string(), }) .attach_printable("Failed while Deleting Gsm rule") { Ok(is_deleted) => { if is_deleted { Ok(services::ApplicationResponse::Json( gsm_api_types::GsmDeleteResponse { gsm_rule_delete: true, connector, flow, sub_flow, code, }, )) } else { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while Deleting Gsm rule, got response as false") } } Err(err) => Err(err), } }
{ "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_create_gsm_rule_4586374256725578912
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/gsm pub async fn create_gsm_rule( state: SessionState, gsm_rule: gsm_api_types::GsmCreateRequest, ) -> RouterResponse<gsm_api_types::GsmResponse> { let db = state.store.as_ref(); GsmInterface::add_gsm_rule(db, gsm_rule.foreign_into()) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: "GSM with given key already exists in our records".to_string(), }) .map(|gsm| services::ApplicationResponse::Json(gsm.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": 29, "total_crates": null }
fn_clm_router_retrieve_gsm_rule_4586374256725578912
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/gsm pub async fn retrieve_gsm_rule( state: SessionState, gsm_request: gsm_api_types::GsmRetrieveRequest, ) -> RouterResponse<gsm_api_types::GsmResponse> { let db = state.store.as_ref(); let gsm_api_types::GsmRetrieveRequest { connector, flow, sub_flow, code, message, } = gsm_request; GsmInterface::find_gsm_rule(db, connector.to_string(), flow, sub_flow, code, message) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "GSM with given key does not exist in our records".to_string(), }) .map(|gsm| services::ApplicationResponse::Json(gsm.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": 29, "total_crates": null }
fn_clm_router_perform_execute_payment_-1148879514641238739
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 pub async fn perform_execute_payment( state: &SessionState, execute_task_process: &storage::ProcessTracker, profile: &domain::Profile, merchant_context: domain::MerchantContext, tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData, revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData, payment_intent: &PaymentIntent, ) -> Result<(), sch_errors::ProcessTrackerError> { let db = &*state.store; let mut revenue_recovery_metadata = payment_intent .feature_metadata .as_ref() .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone()) .get_required_value("Payment Revenue Recovery Metadata")? .convert_back(); let decision = types::Decision::get_decision_based_on_params( state, payment_intent.status, revenue_recovery_metadata .payment_connector_transmission .unwrap_or_default(), payment_intent.active_attempt_id.clone(), revenue_recovery_payment_data, &tracking_data.global_payment_id, ) .await?; // TODO decide if its a global failure or is it requeueable error match decision { types::Decision::Execute => { let connector_customer_id = revenue_recovery_metadata.get_connector_customer_id(); let last_token_used = payment_intent .feature_metadata .as_ref() .and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref()) .map(|rr| { rr.billing_connector_payment_details .payment_processor_token .clone() }); let processor_token = storage::revenue_recovery_redis_operation::RedisTokenManager::get_token_based_on_retry_type( state, &connector_customer_id, tracking_data.revenue_recovery_retry, last_token_used.as_deref(), ) .await .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Failed to fetch token details from redis".to_string(), })? .ok_or(errors::ApiErrorResponse::GenericNotFoundError { message: "Failed to fetch token details from redis".to_string(), })?; logger::info!("Token fetched from redis success"); let card_info = api_models::payments::AdditionalCardInfo::foreign_from(&processor_token); // record attempt call let record_attempt = api::record_internal_attempt_api( state, payment_intent, revenue_recovery_payment_data, &revenue_recovery_metadata, card_info, &processor_token .payment_processor_token_details .payment_processor_token, ) .await; match record_attempt { Ok(record_attempt_response) => { let action = Box::pin(types::Action::execute_payment( state, revenue_recovery_payment_data.merchant_account.get_id(), payment_intent, execute_task_process, profile, merchant_context, revenue_recovery_payment_data, &revenue_recovery_metadata, &record_attempt_response.id, )) .await?; Box::pin(action.execute_payment_task_response_handler( state, payment_intent, execute_task_process, revenue_recovery_payment_data, &mut revenue_recovery_metadata, )) .await?; } Err(err) => { logger::error!("Error while recording attempt: {:?}", err); let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Pending, business_status: Some(String::from( business_status::EXECUTE_WORKFLOW_REQUEUE, )), }; db.as_scheduler() .update_process(execute_task_process.clone(), pt_update) .await?; } } } types::Decision::Psync(attempt_status, attempt_id) => { // find if a psync task is already present let task = PSYNC_WORKFLOW; let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; let process_tracker_id = attempt_id.get_psync_revenue_recovery_id(task, runner); let psync_process = db.find_process_by_id(&process_tracker_id).await?; match psync_process { Some(_) => { let pcr_status: types::RevenueRecoveryPaymentsAttemptStatus = attempt_status.foreign_into(); pcr_status .update_pt_status_based_on_attempt_status_for_execute_payment( db, execute_task_process, ) .await?; } None => { // insert new psync task insert_psync_pcr_task_to_pt( revenue_recovery_payment_data.billing_mca.get_id().clone(), db, revenue_recovery_payment_data .merchant_account .get_id() .clone(), payment_intent.get_id().clone(), revenue_recovery_payment_data.profile.get_id().clone(), attempt_id.clone(), storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, tracking_data.revenue_recovery_retry, ) .await?; // finish the current task db.as_scheduler() .finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC, ) .await?; } }; } types::Decision::ReviewForSuccessfulPayment => { // Finish the current task since the payment was a success // And mark it as review as it might have happened through the external system db.finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW, ) .await?; } types::Decision::ReviewForFailedPayment(triggered_by) => { match triggered_by { enums::TriggeredBy::Internal => { // requeue the current tasks to update the fields for rescheduling a payment let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Pending, business_status: Some(String::from( business_status::EXECUTE_WORKFLOW_REQUEUE, )), }; db.as_scheduler() .update_process(execute_task_process.clone(), pt_update) .await?; } enums::TriggeredBy::External => { logger::debug!("Failed Payment Attempt Triggered By External"); // Finish the current task since the payment was a failure by an external source db.as_scheduler() .finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW, ) .await?; } }; } types::Decision::InvalidDecision => { db.finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_COMPLETE, ) .await?; logger::warn!("Abnormal State Identified") } } Ok(()) }
{ "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_perform_calculate_workflow_-1148879514641238739
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 pub async fn perform_calculate_workflow( state: &SessionState, process: &storage::ProcessTracker, profile: &domain::Profile, merchant_context: domain::MerchantContext, tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData, revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData, payment_intent: &PaymentIntent, ) -> Result<(), sch_errors::ProcessTrackerError> { let db = &*state.store; let merchant_id = revenue_recovery_payment_data.merchant_account.get_id(); let profile_id = revenue_recovery_payment_data.profile.get_id(); let billing_mca_id = revenue_recovery_payment_data.billing_mca.get_id(); let mut event_type: Option<common_enums::EventType> = None; logger::info!( process_id = %process.id, payment_id = %tracking_data.global_payment_id.get_string_repr(), "Starting CALCULATE_WORKFLOW..." ); // 1. Extract connector_customer_id and token_list from tracking_data let connector_customer_id = payment_intent .extract_connector_customer_id_from_payment_intent() .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to extract customer ID from payment intent")?; let merchant_context_from_revenue_recovery_payment_data = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( revenue_recovery_payment_data.merchant_account.clone(), revenue_recovery_payment_data.key_store.clone(), ))); let retry_algorithm_type = match profile .revenue_recovery_retry_algorithm_type .filter(|retry_type| *retry_type != common_enums::RevenueRecoveryAlgorithmType::Monitoring) // ignore Monitoring in profile .unwrap_or(tracking_data.revenue_recovery_retry) // fallback to tracking_data { common_enums::RevenueRecoveryAlgorithmType::Smart => common_enums::RevenueRecoveryAlgorithmType::Smart, common_enums::RevenueRecoveryAlgorithmType::Cascading => common_enums::RevenueRecoveryAlgorithmType::Cascading, common_enums::RevenueRecoveryAlgorithmType::Monitoring => { return Err(sch_errors::ProcessTrackerError::ProcessUpdateFailed); } }; // External Payments which enter the calculate workflow for the first time will have active attempt id as None // Then we dont need to send an webhook to the merchant as its not a failure from our side. // Thus we dont need to a payment get call for such payments. let active_payment_attempt_id = payment_intent.active_attempt_id.as_ref(); let payments_response = get_payment_response_using_payment_get_operation( state, &tracking_data.global_payment_id, revenue_recovery_payment_data, &merchant_context_from_revenue_recovery_payment_data, active_payment_attempt_id, ) .await?; // 2. Get best available token let best_time_to_schedule = match revenue_recovery_workflow::get_token_with_schedule_time_based_on_retry_algorithm_type( state, &connector_customer_id, payment_intent, retry_algorithm_type, process.retry_count, ) .await { Ok(token_opt) => token_opt, Err(e) => { logger::error!( error = ?e, connector_customer_id = %connector_customer_id, "Failed to get best PSP token" ); None } }; match best_time_to_schedule { Some(scheduled_time) => { logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, "Found best available token, creating EXECUTE_WORKFLOW task" ); // reset active attmept id and payment connector transmission before going to execute workflow let _ = Box::pin(reset_connector_transmission_and_active_attempt_id_before_pushing_to_execute_workflow( state, payment_intent, revenue_recovery_payment_data, active_payment_attempt_id )).await?; // 3. If token found: create EXECUTE_WORKFLOW task and finish CALCULATE_WORKFLOW insert_execute_pcr_task_to_pt( &tracking_data.billing_mca_id, state, &tracking_data.merchant_id, payment_intent, &tracking_data.profile_id, &tracking_data.payment_attempt_id, storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, retry_algorithm_type, scheduled_time, ) .await?; db.as_scheduler() .finish_process_with_business_status( process.clone(), business_status::CALCULATE_WORKFLOW_SCHEDULED, ) .await .map_err(|e| { logger::error!( process_id = %process.id, error = ?e, "Failed to update CALCULATE_WORKFLOW status to complete" ); sch_errors::ProcessTrackerError::ProcessUpdateFailed })?; logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, "CALCULATE_WORKFLOW completed successfully" ); } None => { let scheduled_token = match storage::revenue_recovery_redis_operation:: RedisTokenManager::get_payment_processor_token_with_schedule_time(state, &connector_customer_id) .await { Ok(scheduled_token_opt) => scheduled_token_opt, Err(e) => { logger::error!( error = ?e, connector_customer_id = %connector_customer_id, "Failed to get PSP token status" ); None } }; match scheduled_token { Some(scheduled_token) => { // Update scheduled time to scheduled time + 15 minutes // here scheduled_time is the wait time 15 minutes is a buffer time that we are adding logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, "No token but time available, rescheduling for scheduled time + 15 mins" ); update_calculate_job_schedule_time( db, process, time::Duration::seconds( state .conf .revenue_recovery .recovery_timestamp .job_schedule_buffer_time_in_seconds, ), scheduled_token.scheduled_at, &connector_customer_id, ) .await?; } None => { let hard_decline_flag = storage::revenue_recovery_redis_operation:: RedisTokenManager::are_all_tokens_hard_declined( state, &connector_customer_id ) .await .ok() .unwrap_or(false); match hard_decline_flag { false => { logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, "Hard decline flag is false, rescheduling for scheduled time + 15 mins" ); update_calculate_job_schedule_time( db, process, time::Duration::seconds( state .conf .revenue_recovery .recovery_timestamp .job_schedule_buffer_time_in_seconds, ), Some(common_utils::date_time::now()), &connector_customer_id, ) .await?; } true => { // Finish calculate workflow with CALCULATE_WORKFLOW_FINISH logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, "No token available, finishing CALCULATE_WORKFLOW" ); db.as_scheduler() .finish_process_with_business_status( process.clone(), business_status::CALCULATE_WORKFLOW_FINISH, ) .await .map_err(|e| { logger::error!( process_id = %process.id, error = ?e, "Failed to finish CALCULATE_WORKFLOW" ); sch_errors::ProcessTrackerError::ProcessUpdateFailed })?; event_type = Some(common_enums::EventType::PaymentFailed); logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, "CALCULATE_WORKFLOW finished successfully" ); } } } } } } let _outgoing_webhook = event_type.and_then(|event_kind| { payments_response.map(|resp| Some((event_kind, resp))) }) .flatten() .async_map(|(event_kind, response)| async move { let _ = RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status( state, common_enums::EventClass::Payments, event_kind, payment_intent, &merchant_context, profile, tracking_data.payment_attempt_id.get_string_repr().to_string(), response ) .await .map_err(|e| { logger::error!( error = ?e, "Failed to send outgoing webhook" ); e }) .ok(); } ).await; Ok(()) }
{ "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_resume_revenue_recovery_process_tracker_-1148879514641238739
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 pub async fn resume_revenue_recovery_process_tracker( state: SessionState, id: id_type::GlobalPaymentId, request_retrigger: revenue_recovery::RevenueRecoveryRetriggerRequest, ) -> RouterResponse<revenue_recovery::RevenueRecoveryResponse> { let db = &*state.store; let task = request_retrigger.revenue_recovery_task; let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; let process_tracker_id = id.get_execute_revenue_recovery_id(&task, runner); let process_tracker = db .find_process_by_id(&process_tracker_id) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound) .attach_printable("error retrieving the process tracker id")? .get_required_value("Process Tracker") .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Entry For the following id doesn't exists".to_owned(), })?; let tracking_data = process_tracker .tracking_data .clone() .parse_value::<pcr::RevenueRecoveryWorkflowTrackingData>("PCRWorkflowTrackingData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize Pcr Workflow Tracking Data")?; //Call payment intent to check the status let request = PaymentsGetIntentRequest { id: id.clone() }; let revenue_recovery_payment_data = revenue_recovery_workflow::extract_data_and_perform_action(&state, &tracking_data) .await .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Failed to extract the revenue recovery data".to_owned(), })?; let merchant_context_from_revenue_recovery_payment_data = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( revenue_recovery_payment_data.merchant_account.clone(), revenue_recovery_payment_data.key_store.clone(), ))); let create_intent_response = payments::payments_intent_core::< router_api_types::PaymentGetIntent, router_api_types::payments::PaymentsIntentResponse, _, _, PaymentIntentData<router_api_types::PaymentGetIntent>, >( state.clone(), state.get_req_state(), merchant_context_from_revenue_recovery_payment_data, revenue_recovery_payment_data.profile.clone(), payments::operations::PaymentGetIntent, request, tracking_data.global_payment_id.clone(), hyperswitch_domain_models::payments::HeaderPayload::default(), ) .await?; let response = create_intent_response .get_json_body() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response from payments core")?; match response.status { enums::IntentStatus::Failed => { let pt_update = storage::ProcessTrackerUpdate::Update { name: process_tracker.name.clone(), tracking_data: Some(process_tracker.tracking_data.clone()), business_status: Some(request_retrigger.business_status.clone()), status: Some(request_retrigger.status), updated_at: Some(common_utils::date_time::now()), retry_count: Some(process_tracker.retry_count + 1), schedule_time: Some(request_retrigger.schedule_time.unwrap_or( common_utils::date_time::now().saturating_add(time::Duration::seconds(600)), )), }; let updated_pt = db .update_process(process_tracker, pt_update) .await .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Failed to update the process tracker".to_owned(), })?; let response = revenue_recovery::RevenueRecoveryResponse { id: updated_pt.id, name: updated_pt.name, schedule_time_for_payment: updated_pt.schedule_time, schedule_time_for_psync: None, status: updated_pt.status, business_status: updated_pt.business_status, }; Ok(ApplicationResponse::Json(response)) } enums::IntentStatus::Succeeded | enums::IntentStatus::Cancelled | enums::IntentStatus::CancelledPostCapture | enums::IntentStatus::Processing | enums::IntentStatus::RequiresCustomerAction | enums::IntentStatus::RequiresMerchantAction | enums::IntentStatus::RequiresPaymentMethod | enums::IntentStatus::RequiresConfirmation | enums::IntentStatus::RequiresCapture | enums::IntentStatus::PartiallyCaptured | enums::IntentStatus::PartiallyCapturedAndCapturable | enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | enums::IntentStatus::Conflicted | enums::IntentStatus::Expired => Err(report!(errors::ApiErrorResponse::NotSupported { message: "Invalid Payment Status ".to_owned(), })), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 91, "total_crates": null }
fn_clm_router_upsert_calculate_pcr_task_-1148879514641238739
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 pub async fn upsert_calculate_pcr_task( billing_connector_account: &domain::MerchantConnectorAccount, state: &SessionState, merchant_context: &domain::MerchantContext, recovery_intent_from_payment_intent: &domain_revenue_recovery::RecoveryPaymentIntent, business_profile: &domain::Profile, intent_retry_count: u16, payment_attempt_id: Option<id_type::GlobalAttemptId>, runner: storage::ProcessTrackerRunner, revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType, ) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { router_env::logger::info!("Starting calculate_job..."); let task = "CALCULATE_WORKFLOW"; let db = &*state.store; let payment_id = &recovery_intent_from_payment_intent.payment_id; // Create process tracker ID in the format: CALCULATE_WORKFLOW_{payment_intent_id} let process_tracker_id = format!("{runner}_{task}_{}", payment_id.get_string_repr()); // Scheduled time is now because this will be the first entry in // process tracker and we dont want to wait let schedule_time = common_utils::date_time::now(); let payment_attempt_id = payment_attempt_id .ok_or(error_stack::report!( errors::RevenueRecoveryError::PaymentAttemptIdNotFound )) .attach_printable("payment attempt id is required for calculate workflow tracking")?; // Check if a process tracker entry already exists for this payment intent let existing_entry = db .as_scheduler() .find_process_by_id(&process_tracker_id) .await .change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError) .attach_printable( "Failed to check for existing calculate workflow process tracker entry", )?; match existing_entry { Some(existing_process) => { router_env::logger::error!( "Found existing CALCULATE_WORKFLOW task with id: {}", existing_process.id ); } None => { // No entry exists - create a new one router_env::logger::info!( "No existing CALCULATE_WORKFLOW task found for payment_intent_id: {}, creating new entry scheduled for 1 hour from now", payment_id.get_string_repr() ); // Create tracking data let calculate_workflow_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData { billing_mca_id: billing_connector_account.get_id(), global_payment_id: payment_id.clone(), merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), profile_id: business_profile.get_id().to_owned(), payment_attempt_id, revenue_recovery_retry, invoice_scheduled_time: None, }; let tag = ["PCR"]; let task = "CALCULATE_WORKFLOW"; let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, calculate_workflow_tracking_data, Some(1), schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::RevenueRecoveryError::ProcessTrackerCreationError) .attach_printable("Failed to construct calculate workflow process tracker entry")?; // Insert into process tracker with status New db.as_scheduler() .insert_process(process_tracker_entry) .await .change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError) .attach_printable( "Failed to enter calculate workflow process_tracker_entry in DB", )?; router_env::logger::info!( "Successfully created new CALCULATE_WORKFLOW task for payment_intent_id: {}", payment_id.get_string_repr() ); metrics::TASKS_ADDED_COUNT.add( 1, router_env::metric_attributes!(("flow", "CalculateWorkflow")), ); } } Ok(webhooks::WebhookResponseTracker::Payment { payment_id: payment_id.clone(), status: recovery_intent_from_payment_intent.status, }) }
{ "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_insert_execute_pcr_task_to_pt_-1148879514641238739
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 async fn insert_execute_pcr_task_to_pt( billing_mca_id: &id_type::MerchantConnectorAccountId, state: &SessionState, merchant_id: &id_type::MerchantId, payment_intent: &PaymentIntent, profile_id: &id_type::ProfileId, payment_attempt_id: &id_type::GlobalAttemptId, runner: storage::ProcessTrackerRunner, revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType, schedule_time: time::PrimitiveDateTime, ) -> Result<storage::ProcessTracker, sch_errors::ProcessTrackerError> { let task = "EXECUTE_WORKFLOW"; let payment_id = payment_intent.id.clone(); let process_tracker_id = format!("{runner}_{task}_{}", payment_id.get_string_repr()); // Check if a process tracker entry already exists for this payment intent let existing_entry = state .store .find_process_by_id(&process_tracker_id) .await .map_err(|e| { logger::error!( payment_id = %payment_id.get_string_repr(), process_tracker_id = %process_tracker_id, error = ?e, "Failed to check for existing execute workflow process tracker entry" ); sch_errors::ProcessTrackerError::ProcessUpdateFailed })?; match existing_entry { Some(existing_process) if existing_process.business_status == business_status::EXECUTE_WORKFLOW_FAILURE || existing_process.business_status == business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC => { // Entry exists with EXECUTE_WORKFLOW_COMPLETE status - update it logger::info!( payment_id = %payment_id.get_string_repr(), process_tracker_id = %process_tracker_id, current_retry_count = %existing_process.retry_count, "Found existing EXECUTE_WORKFLOW task with COMPLETE status, updating to PENDING with incremented retry count" ); let mut tracking_data: pcr::RevenueRecoveryWorkflowTrackingData = serde_json::from_value(existing_process.tracking_data.clone()) .change_context(errors::RecoveryError::ValueNotFound) .attach_printable( "Failed to deserialize the tracking data from process tracker", )?; tracking_data.revenue_recovery_retry = revenue_recovery_retry; let tracking_data_json = serde_json::to_value(&tracking_data) .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to serialize the tracking data to json")?; let pt_update = storage::ProcessTrackerUpdate::Update { name: Some(task.to_string()), retry_count: Some(existing_process.clone().retry_count + 1), schedule_time: Some(schedule_time), tracking_data: Some(tracking_data_json), business_status: Some(String::from(business_status::PENDING)), status: Some(enums::ProcessTrackerStatus::Pending), updated_at: Some(common_utils::date_time::now()), }; let updated_process = state .store .update_process(existing_process, pt_update) .await .map_err(|e| { logger::error!( payment_id = %payment_id.get_string_repr(), process_tracker_id = %process_tracker_id, error = ?e, "Failed to update existing execute workflow process tracker entry" ); sch_errors::ProcessTrackerError::ProcessUpdateFailed })?; logger::info!( payment_id = %payment_id.get_string_repr(), process_tracker_id = %process_tracker_id, new_retry_count = %updated_process.retry_count, "Successfully updated existing EXECUTE_WORKFLOW task" ); Ok(updated_process) } Some(existing_process) => { // Entry exists but business status is not EXECUTE_WORKFLOW_COMPLETE logger::info!( payment_id = %payment_id.get_string_repr(), process_tracker_id = %process_tracker_id, current_business_status = %existing_process.business_status, ); Ok(existing_process) } None => { // No entry exists - create a new one logger::info!( payment_id = %payment_id.get_string_repr(), process_tracker_id = %process_tracker_id, "No existing EXECUTE_WORKFLOW task found, creating new entry" ); let execute_workflow_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData { billing_mca_id: billing_mca_id.clone(), global_payment_id: payment_id.clone(), merchant_id: merchant_id.clone(), profile_id: profile_id.clone(), payment_attempt_id: payment_attempt_id.clone(), revenue_recovery_retry, invoice_scheduled_time: Some(schedule_time), }; let tag = ["PCR"]; let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id.clone(), task, runner, tag, execute_workflow_tracking_data, Some(1), schedule_time, common_types::consts::API_VERSION, ) .map_err(|e| { logger::error!( payment_id = %payment_id.get_string_repr(), error = ?e, "Failed to construct execute workflow process tracker entry" ); sch_errors::ProcessTrackerError::ProcessUpdateFailed })?; let response = state .store .insert_process(process_tracker_entry) .await .map_err(|e| { logger::error!( payment_id = %payment_id.get_string_repr(), error = ?e, "Failed to insert execute workflow process tracker entry" ); sch_errors::ProcessTrackerError::ProcessUpdateFailed })?; metrics::TASKS_ADDED_COUNT.add( 1, router_env::metric_attributes!(("flow", "RevenueRecoveryExecute")), ); logger::info!( payment_id = %payment_id.get_string_repr(), process_tracker_id = %response.id, "Successfully created new EXECUTE_WORKFLOW task" ); Ok(response) } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 57, "total_crates": null }
fn_clm_router_get_forex_exchange_rates_7837204676890815437
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/currency pub async fn get_forex_exchange_rates( state: SessionState, ) -> CustomResult<ExchangeRates, AnalyticsError> { let forex_api = state.conf.forex_api.get_inner(); let mut attempt = 1; logger::info!("Starting forex exchange rates fetch"); loop { logger::info!("Attempting to fetch forex rates - Attempt {attempt} of {DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS}"); match get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds).await { Ok(rates) => { logger::info!("Successfully fetched forex rates"); return Ok((*rates.data).clone()); } Err(error) => { let is_retryable = matches!( error.current_context(), ForexCacheError::CouldNotAcquireLock | ForexCacheError::EntryNotFound | ForexCacheError::ForexDataUnavailable | ForexCacheError::LocalReadError | ForexCacheError::LocalWriteError | ForexCacheError::RedisConnectionError | ForexCacheError::RedisLockReleaseFailed | ForexCacheError::RedisWriteError | ForexCacheError::WriteLockNotAcquired ); if !is_retryable { return Err(error.change_context(AnalyticsError::ForexFetchFailed)); } if attempt >= DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS { logger::error!("Failed to fetch forex rates after {DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS} attempts"); return Err(error.change_context(AnalyticsError::ForexFetchFailed)); } logger::warn!( "Forex rates fetch failed with retryable error, retrying in {attempt} seconds" ); tokio::time::sleep(std::time::Duration::from_secs(attempt * 2)).await; attempt += 1; } } } }
{ "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_retrieve_forex_7837204676890815437
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/currency pub async fn retrieve_forex( state: SessionState, ) -> CustomResult<ApplicationResponse<currency::FxExchangeRatesCacheEntry>, ApiErrorResponse> { let forex_api = state.conf.forex_api.get_inner(); Ok(ApplicationResponse::Json( get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds) .await .change_context(ApiErrorResponse::GenericNotFoundError { message: "Unable to fetch forex rates".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": 23, "total_crates": null }
fn_clm_router_convert_forex_7837204676890815437
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/currency pub async fn convert_forex( state: SessionState, amount: i64, to_currency: String, from_currency: String, ) -> CustomResult< ApplicationResponse<api_models::currency::CurrencyConversionResponse>, ApiErrorResponse, > { Ok(ApplicationResponse::Json( Box::pin(convert_currency( state.clone(), amount, to_currency, from_currency, )) .await .change_context(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": 23, "total_crates": null }
fn_clm_router_payments_check_gift_card_balance_core_-5357651786607545962
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/gift_card pub async fn payments_check_gift_card_balance_core( state: SessionState, merchant_context: domain::MerchantContext, profile: domain::Profile, _req_state: ReqState, req: PaymentsGiftCardBalanceCheckRequest, _header_payload: HeaderPayload, payment_id: id_type::GlobalPaymentId, ) -> RouterResponse<GiftCardBalanceCheckResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_intent = db .find_payment_intent_by_id( key_manager_state, &payment_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let redis_conn = db .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not get redis connection")?; let gift_card_connector_id: String = redis_conn .get_key(&payment_id.get_gift_card_connector_key().as_str().into()) .await .attach_printable("Failed to fetch gift card connector from redis") .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "No connector found with Gift Card Support".to_string(), })?; let gift_card_connector_id = id_type::MerchantConnectorAccountId::wrap(gift_card_connector_id) .attach_printable("Failed to deserialize MCA") .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "No connector found with Gift Card Support".to_string(), })?; let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( helpers::get_merchant_connector_account_v2( &state, merchant_context.get_merchant_key_store(), Some(&gift_card_connector_id), ) .await .attach_printable( "failed to fetch merchant connector account for gift card balance check", )?, )); let connector_name = merchant_connector_account .get_connector_name() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Connector name not present for gift card balance check")?; // always get the connector name from this call let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_name.to_string(), api::GetToken::Connector, merchant_connector_account.get_mca_id(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?; let connector_auth_type = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError)?; let resource_common_data = GiftCardBalanceCheckFlowData; let router_data: RouterDataV2< GiftCardBalanceCheck, GiftCardBalanceCheckFlowData, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData, > = RouterDataV2 { flow: PhantomData, resource_common_data, tenant_id: state.tenant.tenant_id.clone(), connector_auth_type, request: GiftCardBalanceCheckRequestData { payment_method_data: domain::PaymentMethodData::GiftCard(Box::new( req.gift_card_data.into(), )), currency: Some(payment_intent.amount_details.currency), minor_amount: Some(payment_intent.amount_details.order_amount), }, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), }; let old_router_data = GiftCardBalanceCheckFlowData::to_old_router_data(router_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Cannot construct router data for making the gift card balance check api call", )?; let connector_integration: services::BoxedGiftCardBalanceCheckIntegrationInterface< GiftCardBalanceCheck, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData, > = connector_data.connector.get_connector_integration(); let connector_response = services::execute_connector_processing_step( &state, connector_integration, &old_router_data, CallConnectorAction::Trigger, None, None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while calling gift card balance check connector api")?; let gift_card_balance = connector_response .response .map_err(|_| errors::ApiErrorResponse::UnprocessableEntity { message: "Error while fetching gift card balance".to_string(), }) .attach_printable("Connector returned invalid response")?; let balance = gift_card_balance.balance; let currency = gift_card_balance.currency; let remaining_amount = if (payment_intent.amount_details.order_amount - balance).is_greater_than(0) { payment_intent.amount_details.order_amount - balance } else { MinorUnit::zero() }; let needs_additional_pm_data = remaining_amount.is_greater_than(0); let resp = GiftCardBalanceCheckResponse { payment_id: payment_intent.id.clone(), balance, currency, needs_additional_pm_data, remaining_amount, }; Ok(services::ApplicationResponse::Json(resp)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 123, "total_crates": null }
fn_clm_router_update_profile_acquirer_config_-8042167996165869982
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/profile_acquirer pub async fn update_profile_acquirer_config( state: SessionState, profile_id: common_utils::id_type::ProfileId, profile_acquirer_id: common_utils::id_type::ProfileAcquirerId, request: profile_acquirer::ProfileAcquirerUpdate, merchant_context: domain::MerchantContext, ) -> RouterResponse<profile_acquirer::ProfileAcquirerResponse> { let db = state.store.as_ref(); let key_manager_state = (&state).into(); let merchant_key_store = merchant_context.get_merchant_key_store(); let mut business_profile = db .find_business_profile_by_profile_id(&key_manager_state, merchant_key_store, &profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let acquirer_config_map = business_profile .acquirer_config_map .as_mut() .ok_or(errors::ApiErrorResponse::ProfileAcquirerNotFound { profile_id: profile_id.get_string_repr().to_owned(), profile_acquirer_id: profile_acquirer_id.get_string_repr().to_owned(), }) .attach_printable("no acquirer config found in business profile")?; let mut potential_updated_config = acquirer_config_map .0 .get(&profile_acquirer_id) .ok_or_else(|| errors::ApiErrorResponse::ProfileAcquirerNotFound { profile_id: profile_id.get_string_repr().to_owned(), profile_acquirer_id: profile_acquirer_id.get_string_repr().to_owned(), })? .clone(); // updating value in existing acquirer config request .acquirer_assigned_merchant_id .map(|val| potential_updated_config.acquirer_assigned_merchant_id = val); request .merchant_name .map(|val| potential_updated_config.merchant_name = val); request .network .map(|val| potential_updated_config.network = val); request .acquirer_bin .map(|val| potential_updated_config.acquirer_bin = val); request .acquirer_ica .map(|val| potential_updated_config.acquirer_ica = Some(val.clone())); request .acquirer_fraud_rate .map(|val| potential_updated_config.acquirer_fraud_rate = val); // checking for duplicates in the acquirerConfigMap match acquirer_config_map .0 .iter() .find(|(_existing_id, existing_config_val_ref)| { **existing_config_val_ref == potential_updated_config }) { Some((conflicting_id_of_found_item, _)) => { Err(error_stack::report!(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Duplicate acquirer configuration. This configuration already exists for profile_acquirer_id '{}' under profile_id '{}'.", conflicting_id_of_found_item.get_string_repr(), profile_id.get_string_repr() ), })) } None => Ok(()), }?; acquirer_config_map .0 .insert(profile_acquirer_id.clone(), potential_updated_config); let updated_map_for_db_update = business_profile.acquirer_config_map.clone(); let profile_update = domain::ProfileUpdate::AcquirerConfigMapUpdate { acquirer_config_map: updated_map_for_db_update, }; let updated_business_profile = db .update_profile_by_profile_id( &key_manager_state, merchant_key_store, business_profile, profile_update, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update business profile with updated acquirer config")?; let final_acquirer_details = updated_business_profile .acquirer_config_map .as_ref() .and_then(|configs_wrapper| configs_wrapper.0.get(&profile_acquirer_id)) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get updated acquirer config after DB update")?; let response = profile_acquirer::ProfileAcquirerResponse::from(( profile_acquirer_id, &profile_id, final_acquirer_details, )); Ok(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": 99, "total_crates": null }
fn_clm_router_create_profile_acquirer_-8042167996165869982
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/profile_acquirer pub async fn create_profile_acquirer( state: SessionState, request: profile_acquirer::ProfileAcquirerCreate, merchant_context: domain::MerchantContext, ) -> RouterResponse<profile_acquirer::ProfileAcquirerResponse> { let db = state.store.as_ref(); let profile_acquirer_id = common_utils::generate_profile_acquirer_id_of_default_length(); let key_manager_state: KeyManagerState = (&state).into(); let merchant_key_store = merchant_context.get_merchant_key_store(); let mut business_profile = db .find_business_profile_by_profile_id( &key_manager_state, merchant_key_store, &request.profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: request.profile_id.get_string_repr().to_owned(), })?; let incoming_acquirer_config = common_types::domain::AcquirerConfig { acquirer_assigned_merchant_id: request.acquirer_assigned_merchant_id.clone(), merchant_name: request.merchant_name.clone(), network: request.network.clone(), acquirer_bin: request.acquirer_bin.clone(), acquirer_ica: request.acquirer_ica.clone(), acquirer_fraud_rate: request.acquirer_fraud_rate, }; // Check for duplicates before proceeding business_profile .acquirer_config_map .as_ref() .map_or(Ok(()), |configs_wrapper| { match configs_wrapper.0.values().any(|existing_config| existing_config == &incoming_acquirer_config) { true => Err(error_stack::report!( errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Duplicate acquirer configuration found for profile_id: {}. Conflicting configuration: {:?}", request.profile_id.get_string_repr(), incoming_acquirer_config ), } )), false => Ok(()), } })?; // Get a mutable reference to the HashMap inside AcquirerConfigMap, // initializing if it's None or the inner HashMap is not present. let configs_map = &mut business_profile .acquirer_config_map .get_or_insert_with(|| { common_types::domain::AcquirerConfigMap(std::collections::HashMap::new()) }) .0; configs_map.insert( profile_acquirer_id.clone(), incoming_acquirer_config.clone(), ); let profile_update = domain::ProfileUpdate::AcquirerConfigMapUpdate { acquirer_config_map: business_profile.acquirer_config_map.clone(), }; let updated_business_profile = db .update_profile_by_profile_id( &key_manager_state, merchant_key_store, business_profile, profile_update, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update business profile with new acquirer config")?; let updated_acquire_details = updated_business_profile .acquirer_config_map .as_ref() .and_then(|acquirer_configs_wrapper| acquirer_configs_wrapper.0.get(&profile_acquirer_id)) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get updated acquirer config")?; let response = profile_acquirer::ProfileAcquirerResponse::from(( profile_acquirer_id, &request.profile_id, updated_acquire_details, )); Ok(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": 81, "total_crates": null }
fn_clm_router_new_-8521077291469798264
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/debit_routing // Inherent implementation for ExtractedCardInfo fn new( co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>, card_type: Option<String>, card_isin: Option<Secret<String>>, ) -> Self { Self { co_badged_card_data, card_type, card_isin, } }
{ "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_check_for_debit_routing_connector_in_profile_-8521077291469798264
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/debit_routing pub async fn check_for_debit_routing_connector_in_profile< F: Clone, D: OperationSessionGetters<F>, >( state: &SessionState, business_profile_id: &id_type::ProfileId, payment_data: &D, ) -> bool { logger::debug!("Checking for debit routing connector in profile"); let debit_routing_supported_connectors = state.conf.debit_routing_config.supported_connectors.clone(); let transaction_data = super::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(), ); let fallback_config_optional = super::routing::helpers::get_merchant_default_config( &*state.clone().store, business_profile_id.get_string_repr(), &enums::TransactionType::from(&TransactionData::Payment(transaction_data)), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .map_err(|error| { logger::warn!(?error, "Failed to fetch default connector for a profile"); }) .ok(); let is_debit_routable_connector_present = fallback_config_optional .map(|fallback_config| { fallback_config.iter().any(|fallback_config_connector| { debit_routing_supported_connectors.contains(&api_enums::Connector::from( fallback_config_connector.connector, )) }) }) .unwrap_or(false); is_debit_routable_connector_present }
{ "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_handle_retryable_connector_-8521077291469798264
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/debit_routing async fn handle_retryable_connector<F, D>( state: &SessionState, debit_routing_supported_connectors: HashSet<api_enums::Connector>, connector_data_list: Vec<api::ConnectorRoutingData>, payment_data: &mut D, acquirer_country: enums::CountryAlpha2, ) -> Option<DebitRoutingResult> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let key_manager_state = &(state).into(); let db = state.store.as_ref(); let profile_id = payment_data.get_payment_attempt().profile_id.clone(); let merchant_id = payment_data.get_payment_attempt().merchant_id.clone(); let is_any_debit_routing_connector_supported = connector_data_list.iter().any(|connector_data| { debit_routing_supported_connectors .contains(&connector_data.connector_data.connector_name) }); if is_any_debit_routing_connector_supported { let debit_routing_output = get_debit_routing_output::<F, D>(state, payment_data, acquirer_country).await?; 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) .map_err(|error| { logger::error!( "Failed to get merchant key store by merchant_id {:?}", error ) }) .ok()?; let connector_routing_data = build_connector_routing_data( state, &profile_id, &key_store, connector_data_list.clone(), debit_routing_output .co_badged_card_networks_info .clone() .get_card_networks(), ) .await .map_err(|error| { logger::error!( "Failed to build connector routing data for debit routing {:?}", error ) }) .ok()?; if !connector_routing_data.is_empty() { return Some(DebitRoutingResult { debit_routing_connector_call_type: ConnectorCallType::Retryable( connector_routing_data, ), debit_routing_output, }); }; } None }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 51, "total_crates": null }
fn_clm_router_handle_pre_determined_connector_-8521077291469798264
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/debit_routing async fn handle_pre_determined_connector<F, D>( state: &SessionState, debit_routing_supported_connectors: HashSet<api_enums::Connector>, connector_data: &api::ConnectorRoutingData, payment_data: &mut D, acquirer_country: enums::CountryAlpha2, ) -> Option<DebitRoutingResult> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let db = state.store.as_ref(); let key_manager_state = &(state).into(); let merchant_id = payment_data.get_payment_attempt().merchant_id.clone(); let profile_id = payment_data.get_payment_attempt().profile_id.clone(); if debit_routing_supported_connectors.contains(&connector_data.connector_data.connector_name) { logger::debug!("Chosen connector is supported for debit routing"); let debit_routing_output = get_debit_routing_output::<F, D>(state, payment_data, acquirer_country).await?; logger::debug!( "Sorted co-badged networks info: {:?}", debit_routing_output.co_badged_card_networks_info ); 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) .map_err(|error| { logger::error!( "Failed to get merchant key store by merchant_id {:?}", error ) }) .ok()?; let connector_routing_data = build_connector_routing_data( state, &profile_id, &key_store, vec![connector_data.clone()], debit_routing_output .co_badged_card_networks_info .clone() .get_card_networks(), ) .await .map_err(|error| { logger::error!( "Failed to build connector routing data for debit routing {:?}", error ) }) .ok()?; if !connector_routing_data.is_empty() { return Some(DebitRoutingResult { debit_routing_connector_call_type: ConnectorCallType::Retryable( connector_routing_data, ), debit_routing_output, }); } } None }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 45, "total_crates": null }
fn_clm_router_get_debit_routing_output_-8521077291469798264
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/debit_routing pub async fn get_debit_routing_output< F: Clone + Send, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, >( state: &SessionState, payment_data: &mut D, acquirer_country: enums::CountryAlpha2, ) -> Option<open_router::DebitRoutingOutput> { logger::debug!("Fetching sorted card networks"); let card_info = extract_card_info(payment_data); let saved_co_badged_card_data = card_info.co_badged_card_data; let saved_card_type = card_info.card_type; let card_isin = card_info.card_isin; match ( saved_co_badged_card_data .clone() .zip(saved_card_type.clone()), card_isin.clone(), ) { (None, None) => { logger::debug!("Neither co-badged data nor ISIN found; skipping routing"); None } _ => { let co_badged_card_data = saved_co_badged_card_data .zip(saved_card_type) .and_then(|(co_badged, card_type)| { open_router::DebitRoutingRequestData::try_from((co_badged, card_type)) .map(Some) .map_err(|error| { logger::warn!("Failed to convert co-badged card data: {:?}", error); }) .ok() }) .flatten(); if co_badged_card_data.is_none() && card_isin.is_none() { logger::debug!("Neither co-badged data nor ISIN found; skipping routing"); return None; } let co_badged_card_request = open_router::CoBadgedCardRequest { merchant_category_code: enums::DecisionEngineMerchantCategoryCode::Mcc0001, acquirer_country, co_badged_card_data, }; routing::perform_open_routing_for_debit_routing( state, co_badged_card_request, card_isin, payment_data, ) .await .map_err(|error| { logger::warn!(?error, "Debit routing call to open router failed"); }) .ok() } } }
{ "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_perform_pre_authentication_6084713569188227082
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/authentication pub async fn perform_pre_authentication( state: &SessionState, key_store: &domain::MerchantKeyStore, card: hyperswitch_domain_models::payment_method_data::Card, token: String, business_profile: &domain::Profile, acquirer_details: Option<types::AcquirerDetails>, payment_id: common_utils::id_type::PaymentId, organization_id: common_utils::id_type::OrganizationId, force_3ds_challenge: Option<bool>, psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, ) -> CustomResult< hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore, ApiErrorResponse, > { let (authentication_connector, three_ds_connector_account) = utils::get_authentication_connector_data(state, key_store, business_profile, None).await?; let authentication_connector_name = authentication_connector.to_string(); let authentication = utils::create_new_authentication( state, business_profile.merchant_id.clone(), authentication_connector_name.clone(), token, business_profile.get_id().to_owned(), payment_id.clone(), three_ds_connector_account .get_mca_id() .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Error while finding mca_id from merchant_connector_account")?, organization_id, force_3ds_challenge, psd2_sca_exemption_type, ) .await?; let authentication = if authentication_connector.is_separate_version_call_required() { let router_data: core_types::authentication::PreAuthNVersionCallRouterData = transformers::construct_pre_authentication_router_data( state, authentication_connector_name.clone(), card.clone(), &three_ds_connector_account, business_profile.merchant_id.clone(), payment_id.clone(), )?; let router_data = utils::do_auth_connector_call( state, authentication_connector_name.clone(), router_data, ) .await?; let updated_authentication = utils::update_trackers( state, router_data, authentication, acquirer_details.clone(), key_store, ) .await?; // from version call response, we will get to know the maximum supported 3ds version. // If the version is not greater than or equal to 3DS 2.0, We should not do the successive pre authentication call. if !updated_authentication.is_separate_authn_required() { return Ok(hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore{ authentication: updated_authentication, cavv: None, // since cavv wont be present in pre_authentication step }); } updated_authentication } else { authentication }; let router_data: core_types::authentication::PreAuthNRouterData = transformers::construct_pre_authentication_router_data( state, authentication_connector_name.clone(), card, &three_ds_connector_account, business_profile.merchant_id.clone(), payment_id, )?; let router_data = utils::do_auth_connector_call(state, authentication_connector_name, router_data).await?; let authentication_update = utils::update_trackers( state, router_data, authentication, acquirer_details, key_store, ) .await?; Ok( hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore { authentication: authentication_update, cavv: None, // since cavv wont be present in pre_authentication step }, ) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 67, "total_crates": null }
fn_clm_router_perform_post_authentication_6084713569188227082
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/authentication pub async fn perform_post_authentication( state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: domain::Profile, authentication_id: common_utils::id_type::AuthenticationId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult< hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore, ApiErrorResponse, > { let (authentication_connector, three_ds_connector_account) = utils::get_authentication_connector_data(state, key_store, &business_profile, None).await?; let is_pull_mechanism_enabled = check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata( three_ds_connector_account .get_metadata() .map(|metadata| metadata.expose()), ); let authentication = state .store .find_authentication_by_merchant_id_authentication_id( &business_profile.merchant_id, &authentication_id, ) .await .to_not_found_response(ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Error while fetching authentication record with authentication_id {}", authentication_id.get_string_repr() ) })?; let authentication_update = if !authentication.authentication_status.is_terminal_status() && is_pull_mechanism_enabled { // trigger in case of authenticate flow let router_data = transformers::construct_post_authentication_router_data( state, authentication_connector.to_string(), business_profile, three_ds_connector_account, &authentication, payment_id, )?; let router_data = utils::do_auth_connector_call(state, authentication_connector.to_string(), router_data) .await?; utils::update_trackers(state, router_data, authentication, None, key_store).await? } else { // trigger in case of webhook flow authentication }; // getting authentication value from temp locker before moving ahead with authrisation let tokenized_data = crate::core::payment_methods::vault::get_tokenized_data( state, authentication_id.get_string_repr(), false, key_store.key.get_inner(), ) .await .inspect_err(|err| router_env::logger::error!(tokenized_data_result=?err)) .attach_printable("cavv not present after authentication flow") .ok(); let authentication_store = hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore { cavv: tokenized_data.map(|data| masking::Secret::new(data.value1)), authentication: authentication_update, }; Ok(authentication_store) }
{ "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_perform_authentication_6084713569188227082
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/authentication pub async fn perform_authentication( state: &SessionState, merchant_id: common_utils::id_type::MerchantId, authentication_connector: String, payment_method_data: domain::PaymentMethodData, payment_method: common_enums::PaymentMethod, billing_address: hyperswitch_domain_models::address::Address, shipping_address: Option<hyperswitch_domain_models::address::Address>, browser_details: Option<core_types::BrowserInformation>, merchant_connector_account: payments_core::helpers::MerchantConnectorAccountType, amount: Option<common_utils::types::MinorUnit>, currency: Option<Currency>, message_category: api::authentication::MessageCategory, device_channel: payments::DeviceChannel, authentication_data: storage::Authentication, return_url: Option<String>, sdk_information: Option<payments::SdkInformation>, threeds_method_comp_ind: payments::ThreeDsCompletionIndicator, email: Option<common_utils::pii::Email>, webhook_url: String, three_ds_requestor_url: String, psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, payment_id: common_utils::id_type::PaymentId, force_3ds_challenge: bool, merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, ) -> CustomResult<api::authentication::AuthenticationResponse, ApiErrorResponse> { let router_data = transformers::construct_authentication_router_data( state, merchant_id, authentication_connector.clone(), payment_method_data, payment_method, billing_address, shipping_address, browser_details, amount, currency, message_category, device_channel, merchant_connector_account, authentication_data.clone(), return_url, sdk_information, threeds_method_comp_ind, email, webhook_url, three_ds_requestor_url, psd2_sca_exemption_type, payment_id, force_3ds_challenge, )?; let response = Box::pin(utils::do_auth_connector_call( state, authentication_connector.clone(), router_data, )) .await?; let authentication = utils::update_trackers( state, response.clone(), authentication_data, None, merchant_key_store, ) .await?; response .response .map_err(|err| ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: authentication_connector, status_code: err.status_code, reason: err.reason, })?; api::authentication::AuthenticationResponse::try_from(authentication) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 30, "total_crates": null }
fn_clm_router_new_-233841303944682868
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/routing // Inherent implementation for PaymentsDslInput<'a> pub fn new( setup_mandate: Option<&'a mandates::MandateData>, payment_attempt: &'a storage::PaymentAttempt, payment_intent: &'a storage::PaymentIntent, payment_method_data: Option<&'a domain::PaymentMethodData>, address: &'a payment_address::PaymentAddress, recurring_details: Option<&'a mandates_api::RecurringDetails>, currency: storage_enums::Currency, ) -> Self { Self { setup_mandate, payment_attempt, payment_intent, payment_method_data, address, recurring_details, currency, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14463, "total_crates": null }
fn_clm_router_link_routing_config_-233841303944682868
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/routing pub async fn link_routing_config( state: SessionState, merchant_context: domain::MerchantContext, authentication_profile_id: Option<common_utils::id_type::ProfileId>, algorithm_id: common_utils::id_type::RoutingId, transaction_type: enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_LINK_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let routing_algorithm = db .find_routing_algorithm_by_algorithm_id_merchant_id( &algorithm_id, merchant_context.get_merchant_account().get_id(), ) .await .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?; let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_context.get_merchant_key_store(), Some(&routing_algorithm.profile_id), merchant_context.get_merchant_account().get_id(), ) .await? .get_required_value("Profile") .change_context(errors::ApiErrorResponse::ProfileNotFound { id: routing_algorithm.profile_id.get_string_repr().to_owned(), })?; core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?; match routing_algorithm.kind { diesel_models::enums::RoutingAlgorithmKind::Dynamic => { let mut dynamic_routing_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile .dynamic_routing_algorithm .clone() .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to deserialize Dynamic routing algorithm ref from business profile", )? .unwrap_or_default(); utils::when( matches!( dynamic_routing_ref.success_based_algorithm, Some(routing::SuccessBasedAlgorithm { algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp { algorithm_id: Some(ref id), timestamp: _ }, enabled_feature: _ }) if id == &algorithm_id ) || matches!( dynamic_routing_ref.elimination_routing_algorithm, Some(routing::EliminationRoutingAlgorithm { algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp { algorithm_id: Some(ref id), timestamp: _ }, enabled_feature: _ }) if id == &algorithm_id ) || matches!( dynamic_routing_ref.contract_based_routing, Some(routing::ContractRoutingAlgorithm { algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp { algorithm_id: Some(ref id), timestamp: _ }, enabled_feature: _ }) if id == &algorithm_id ), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Algorithm is already active".to_string(), }) }, )?; if routing_algorithm.name == helpers::SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM { dynamic_routing_ref.update_algorithm_id( algorithm_id, dynamic_routing_ref .success_based_algorithm .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "missing success_based_algorithm in dynamic_algorithm_ref from business_profile table", )? .enabled_feature, routing_types::DynamicRoutingType::SuccessRateBasedRouting, ); // Call to DE here to update SR configs #[cfg(all(feature = "dynamic_routing", feature = "v1"))] { if state.conf.open_router.dynamic_routing_enabled { let existing_config = helpers::get_decision_engine_active_dynamic_routing_algorithm( &state, business_profile.get_id(), api_models::open_router::DecisionEngineDynamicAlgorithmType::SuccessRate, ) .await; if let Ok(Some(_config)) = existing_config { update_decision_engine_dynamic_routing_setup( &state, business_profile.get_id(), routing_algorithm.algorithm_data.clone(), routing_types::DynamicRoutingType::SuccessRateBasedRouting, &mut dynamic_routing_ref, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to update the success rate routing config in Decision Engine", )?; } else { let data: routing_types::SuccessBasedRoutingConfig = routing_algorithm.algorithm_data .clone() .parse_value("SuccessBasedRoutingConfig") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to deserialize SuccessBasedRoutingConfig from routing algorithm data", )?; enable_decision_engine_dynamic_routing_setup( &state, business_profile.get_id(), routing_types::DynamicRoutingType::SuccessRateBasedRouting, &mut dynamic_routing_ref, Some(routing_types::DynamicRoutingPayload::SuccessBasedRoutingPayload(data)), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to setup decision engine dynamic routing")?; } } } } else if routing_algorithm.name == helpers::ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM { dynamic_routing_ref.update_algorithm_id( algorithm_id, dynamic_routing_ref .elimination_routing_algorithm .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "missing elimination_routing_algorithm in dynamic_algorithm_ref from business_profile table", )? .enabled_feature, routing_types::DynamicRoutingType::EliminationRouting, ); #[cfg(all(feature = "dynamic_routing", feature = "v1"))] { if state.conf.open_router.dynamic_routing_enabled { let existing_config = helpers::get_decision_engine_active_dynamic_routing_algorithm( &state, business_profile.get_id(), api_models::open_router::DecisionEngineDynamicAlgorithmType::Elimination, ) .await; if let Ok(Some(_config)) = existing_config { update_decision_engine_dynamic_routing_setup( &state, business_profile.get_id(), routing_algorithm.algorithm_data.clone(), routing_types::DynamicRoutingType::EliminationRouting, &mut dynamic_routing_ref, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to update the elimination routing config in Decision Engine", )?; } else { let data: routing_types::EliminationRoutingConfig = routing_algorithm.algorithm_data .clone() .parse_value("EliminationRoutingConfig") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to deserialize EliminationRoutingConfig from routing algorithm data", )?; enable_decision_engine_dynamic_routing_setup( &state, business_profile.get_id(), routing_types::DynamicRoutingType::EliminationRouting, &mut dynamic_routing_ref, Some( routing_types::DynamicRoutingPayload::EliminationRoutingPayload( data, ), ), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to setup decision engine dynamic routing")?; } } } } else if routing_algorithm.name == helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM { dynamic_routing_ref.update_algorithm_id( algorithm_id, dynamic_routing_ref .contract_based_routing .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "missing contract_based_routing in dynamic_algorithm_ref from business_profile table", )? .enabled_feature, routing_types::DynamicRoutingType::ContractBasedRouting, ); } helpers::update_business_profile_active_dynamic_algorithm_ref( db, key_manager_state, merchant_context.get_merchant_key_store(), business_profile.clone(), dynamic_routing_ref, ) .await?; } diesel_models::enums::RoutingAlgorithmKind::Single | diesel_models::enums::RoutingAlgorithmKind::Priority | diesel_models::enums::RoutingAlgorithmKind::Advanced | diesel_models::enums::RoutingAlgorithmKind::VolumeSplit | diesel_models::enums::RoutingAlgorithmKind::ThreeDsDecisionRule => { let mut routing_ref: routing_types::RoutingAlgorithmRef = business_profile .routing_algorithm .clone() .map(|val| val.parse_value("RoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to deserialize routing algorithm ref from business profile", )? .unwrap_or_default(); utils::when(routing_algorithm.algorithm_for != transaction_type, || { Err(errors::ApiErrorResponse::PreconditionFailed { message: format!( "Cannot use {}'s routing algorithm for {} operation", routing_algorithm.algorithm_for, transaction_type ), }) })?; utils::when( routing_ref.algorithm_id == Some(algorithm_id.clone()), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Algorithm is already active".to_string(), }) }, )?; routing_ref.update_algorithm_id(algorithm_id); helpers::update_profile_active_algorithm_ref( db, key_manager_state, merchant_context.get_merchant_key_store(), business_profile.clone(), routing_ref, &transaction_type, ) .await?; } }; if let Some(euclid_routing_id) = routing_algorithm.decision_engine_routing_id.clone() { let routing_algo = ActivateRoutingConfigRequest { created_by: business_profile.get_id().get_string_repr().to_string(), routing_algorithm_id: euclid_routing_id, }; let link_result = link_de_euclid_routing_algorithm(&state, routing_algo).await; match link_result { Ok(_) => { router_env::logger::info!( routing_flow=?"link_routing_algorithm", is_equal=?true, "decision_engine_euclid" ); } Err(e) => { router_env::logger::info!( routing_flow=?"link_routing_algorithm", is_equal=?false, error=?e, "decision_engine_euclid" ); } } } // redact cgraph cache on rule activation helpers::redact_cgraph_cache( &state, merchant_context.get_merchant_account().get_id(), business_profile.get_id(), ) .await?; // redact routing cache on rule activation helpers::redact_routing_cache( &state, merchant_context.get_merchant_account().get_id(), business_profile.get_id(), ) .await?; metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( routing_algorithm.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": 216, "total_crates": null }
fn_clm_router_contract_based_dynamic_routing_setup_-233841303944682868
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/routing pub async fn contract_based_dynamic_routing_setup( state: SessionState, merchant_context: domain::MerchantContext, profile_id: common_utils::id_type::ProfileId, feature_to_enable: routing_types::DynamicRoutingFeatures, config: Option<routing_types::ContractBasedRoutingConfig>, ) -> RouterResult<service_api::ApplicationResponse<routing_types::RoutingDictionaryRecord>> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let business_profile: domain::Profile = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_context.get_merchant_key_store(), Some(&profile_id), merchant_context.get_merchant_account().get_id(), ) .await? .get_required_value("Profile") .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let mut dynamic_routing_algo_ref: Option<routing_types::DynamicRoutingAlgorithmRef> = business_profile .dynamic_routing_algorithm .clone() .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to deserialize dynamic routing algorithm ref from business profile", ) .ok() .flatten(); utils::when( dynamic_routing_algo_ref .as_mut() .and_then(|algo| { algo.contract_based_routing.as_mut().map(|contract_algo| { *contract_algo.get_enabled_features() == feature_to_enable && contract_algo .clone() .get_algorithm_id_with_timestamp() .algorithm_id .is_some() }) }) .unwrap_or(false), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Contract Routing with specified features is already enabled".to_string(), }) }, )?; if feature_to_enable == routing::DynamicRoutingFeatures::None { let algorithm = dynamic_routing_algo_ref .clone() .get_required_value("dynamic_routing_algo_ref") .attach_printable("Failed to get dynamic_routing_algo_ref")?; return helpers::disable_dynamic_routing_algorithm( &state, merchant_context.get_merchant_key_store().clone(), business_profile, algorithm, routing_types::DynamicRoutingType::ContractBasedRouting, ) .await; } let config = config .get_required_value("ContractBasedRoutingConfig") .attach_printable("Failed to get ContractBasedRoutingConfig from request")?; let merchant_id = business_profile.merchant_id.clone(); let algorithm_id = common_utils::generate_routing_id_of_default_length(); let timestamp = common_utils::date_time::now(); let algo = RoutingAlgorithm { algorithm_id: algorithm_id.clone(), profile_id: profile_id.clone(), merchant_id, name: helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(), description: None, kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic, algorithm_data: serde_json::json!(config), created_at: timestamp, modified_at: timestamp, algorithm_for: common_enums::TransactionType::Payment, decision_engine_routing_id: None, }; // 1. if dynamic_routing_algo_ref already present, insert contract based algo and disable success based // 2. if dynamic_routing_algo_ref is not present, create a new dynamic_routing_algo_ref with contract algo set up let final_algorithm = if let Some(mut algo) = dynamic_routing_algo_ref { algo.update_algorithm_id( algorithm_id, feature_to_enable, routing_types::DynamicRoutingType::ContractBasedRouting, ); if feature_to_enable == routing::DynamicRoutingFeatures::DynamicConnectorSelection { algo.disable_algorithm_id(routing_types::DynamicRoutingType::SuccessRateBasedRouting); } algo } else { let contract_algo = routing_types::ContractRoutingAlgorithm { algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp::new(Some( algorithm_id.clone(), )), enabled_feature: feature_to_enable, }; routing_types::DynamicRoutingAlgorithmRef { success_based_algorithm: None, elimination_routing_algorithm: None, dynamic_routing_volume_split: None, contract_based_routing: Some(contract_algo), is_merchant_created_in_decision_engine: dynamic_routing_algo_ref .as_ref() .is_some_and(|algo| algo.is_merchant_created_in_decision_engine), } }; // validate the contained mca_ids let mut contained_mca = Vec::new(); if let Some(info_vec) = &config.label_info { for info in info_vec { utils::when( contained_mca.iter().any(|mca_id| mca_id == &info.mca_id), || { Err(error_stack::Report::new( errors::ApiErrorResponse::InvalidRequestData { message: "Duplicate mca configuration received".to_string(), }, )) }, )?; contained_mca.push(info.mca_id.to_owned()); } let validation_futures: Vec<_> = info_vec .iter() .map(|info| async { let mca_id = info.mca_id.clone(); let label = info.label.clone(); let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_context.get_merchant_account().get_id(), &mca_id, merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: mca_id.get_string_repr().to_owned(), })?; utils::when(mca.connector_name != label, || { Err(error_stack::Report::new( errors::ApiErrorResponse::InvalidRequestData { message: "Incorrect mca configuration received".to_string(), }, )) })?; Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(()) }) .collect(); futures::future::try_join_all(validation_futures).await?; } let record = db .insert_routing_algorithm(algo) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to insert record in routing algorithm table")?; helpers::update_business_profile_active_dynamic_algorithm_ref( db, key_manager_state, merchant_context.get_merchant_key_store(), business_profile, final_algorithm, ) .await?; let new_record = record.foreign_into(); metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add( 1, router_env::metric_attributes!(("profile_id", profile_id.get_string_repr().to_string())), ); Ok(service_api::ApplicationResponse::Json(new_record)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 175, "total_crates": null }
fn_clm_router_create_routing_algorithm_under_profile_-233841303944682868
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/routing pub async fn create_routing_algorithm_under_profile( state: SessionState, merchant_context: domain::MerchantContext, authentication_profile_id: Option<common_utils::id_type::ProfileId>, request: routing_types::RoutingConfigRequest, transaction_type: enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { use api_models::routing::StaticRoutingAlgorithm as EuclidAlgorithm; metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let name = request .name .get_required_value("name") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "name" }) .attach_printable("Name of config not given")?; let description = request .description .get_required_value("description") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "description", }) .attach_printable("Description of config not given")?; let algorithm = request .algorithm .clone() .get_required_value("algorithm") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "algorithm", }) .attach_printable("Algorithm of config not given")?; let algorithm_id = common_utils::generate_routing_id_of_default_length(); let profile_id = request .profile_id .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "profile_id", }) .attach_printable("Profile_id not provided")?; let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_context.get_merchant_key_store(), Some(&profile_id), merchant_context.get_merchant_account().get_id(), ) .await? .get_required_value("Profile")?; core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?; if algorithm.should_validate_connectors_in_routing_config() { helpers::validate_connectors_in_routing_config( &state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().get_id(), &profile_id, &algorithm, ) .await?; } let mut decision_engine_routing_id: Option<String> = None; if let Some(euclid_algorithm) = request.algorithm.clone() { let maybe_static_algorithm: Option<StaticRoutingAlgorithm> = match euclid_algorithm { EuclidAlgorithm::Advanced(program) => match program.try_into() { Ok(internal_program) => Some(StaticRoutingAlgorithm::Advanced(internal_program)), Err(e) => { router_env::logger::error!(decision_engine_error = ?e, "decision_engine_euclid"); None } }, EuclidAlgorithm::Single(conn) => { Some(StaticRoutingAlgorithm::Single(Box::new(conn.into()))) } EuclidAlgorithm::Priority(connectors) => { let converted: Vec<ConnectorInfo> = connectors.into_iter().map(Into::into).collect(); Some(StaticRoutingAlgorithm::Priority(converted)) } EuclidAlgorithm::VolumeSplit(splits) => { let converted: Vec<VolumeSplit<ConnectorInfo>> = splits.into_iter().map(Into::into).collect(); Some(StaticRoutingAlgorithm::VolumeSplit(converted)) } EuclidAlgorithm::ThreeDsDecisionRule(_) => { router_env::logger::error!( "decision_engine_euclid: ThreeDsDecisionRules are not yet implemented" ); None } }; if let Some(static_algorithm) = maybe_static_algorithm { let routing_rule = RoutingRule { rule_id: Some(algorithm_id.clone().get_string_repr().to_owned()), name: name.clone(), description: Some(description.clone()), created_by: profile_id.get_string_repr().to_string(), algorithm: static_algorithm, algorithm_for: transaction_type.into(), metadata: Some(RoutingMetadata { kind: algorithm.get_kind().foreign_into(), }), }; match create_de_euclid_routing_algo(&state, &routing_rule).await { Ok(id) => { decision_engine_routing_id = Some(id); } Err(e) if matches!( e.current_context(), errors::RoutingError::DecisionEngineValidationError(_) ) => { if let errors::RoutingError::DecisionEngineValidationError(msg) = e.current_context() { router_env::logger::error!( decision_engine_euclid_error = ?msg, decision_engine_euclid_request = ?routing_rule, "failed to create rule in decision_engine with validation error" ); } } Err(e) => { router_env::logger::error!( decision_engine_euclid_error = ?e, decision_engine_euclid_request = ?routing_rule, "failed to create rule in decision_engine" ); } } } } if decision_engine_routing_id.is_some() { router_env::logger::info!(routing_flow=?"create_euclid_routing_algorithm", is_equal=?"true", "decision_engine_euclid"); } else { router_env::logger::info!(routing_flow=?"create_euclid_routing_algorithm", is_equal=?"false", "decision_engine_euclid"); } let timestamp = common_utils::date_time::now(); let algo = RoutingAlgorithm { algorithm_id: algorithm_id.clone(), profile_id, merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), name: name.clone(), description: Some(description.clone()), kind: algorithm.get_kind().foreign_into(), algorithm_data: serde_json::json!(algorithm), created_at: timestamp, modified_at: timestamp, algorithm_for: transaction_type.to_owned(), decision_engine_routing_id, }; let record = db .insert_routing_algorithm(algo) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let new_record = record.foreign_into(); metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(new_record)) }
{ "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_migrate_rules_for_profile_-233841303944682868
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/routing pub async fn migrate_rules_for_profile( state: SessionState, merchant_context: domain::MerchantContext, query_params: routing_types::RuleMigrationQuery, ) -> RouterResult<routing_types::RuleMigrationResult> { use api_models::routing::StaticRoutingAlgorithm as EuclidAlgorithm; let profile_id = query_params.profile_id.clone(); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_key_store = merchant_context.get_merchant_key_store(); let merchant_id = merchant_context.get_merchant_account().get_id(); let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_key_store, Some(&profile_id), merchant_id, ) .await? .get_required_value("Profile") .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; #[cfg(feature = "v1")] let active_payment_routing_ids: Vec<Option<common_utils::id_type::RoutingId>> = vec![ business_profile .get_payment_routing_algorithm() .attach_printable("Failed to get payment routing algorithm")? .unwrap_or_default() .algorithm_id, business_profile .get_payout_routing_algorithm() .attach_printable("Failed to get payout routing algorithm")? .unwrap_or_default() .algorithm_id, ]; #[cfg(feature = "v2")] let active_payment_routing_ids = [business_profile.routing_algorithm_id.clone()]; let routing_metadatas = state .store .list_routing_algorithm_metadata_by_profile_id( &profile_id, i64::from(query_params.validated_limit()), i64::from(query_params.offset.unwrap_or_default()), ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let mut response_list = Vec::new(); let mut error_list = Vec::new(); let mut push_error = |algorithm_id, msg: String| { error_list.push(RuleMigrationError { profile_id: profile_id.clone(), algorithm_id, error: msg, }); }; for routing_metadata in routing_metadatas { let algorithm_id = routing_metadata.algorithm_id.clone(); let algorithm = match db .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id) .await { Ok(algo) => algo, Err(e) => { router_env::logger::error!(?e, ?algorithm_id, "Failed to fetch routing algorithm"); push_error(algorithm_id, format!("Fetch error: {e:?}")); continue; } }; let parsed_result = algorithm .algorithm_data .parse_value::<EuclidAlgorithm>("EuclidAlgorithm"); let maybe_static_algorithm: Option<StaticRoutingAlgorithm> = match parsed_result { Ok(EuclidAlgorithm::Advanced(program)) => match program.try_into() { Ok(ip) => Some(StaticRoutingAlgorithm::Advanced(ip)), Err(e) => { router_env::logger::error!( ?e, ?algorithm_id, "Failed to convert advanced program" ); push_error(algorithm_id.clone(), format!("Conversion error: {e:?}")); None } }, Ok(EuclidAlgorithm::Single(conn)) => { Some(StaticRoutingAlgorithm::Single(Box::new(conn.into()))) } Ok(EuclidAlgorithm::Priority(connectors)) => Some(StaticRoutingAlgorithm::Priority( connectors.into_iter().map(Into::into).collect(), )), Ok(EuclidAlgorithm::VolumeSplit(splits)) => Some(StaticRoutingAlgorithm::VolumeSplit( splits.into_iter().map(Into::into).collect(), )), Ok(EuclidAlgorithm::ThreeDsDecisionRule(_)) => { router_env::logger::info!( ?algorithm_id, "Skipping 3DS rule migration (not supported yet)" ); push_error(algorithm_id.clone(), "3DS migration not implemented".into()); None } Err(e) => { router_env::logger::error!(?e, ?algorithm_id, "Failed to parse algorithm"); push_error(algorithm_id.clone(), format!("Parse error: {e:?}")); None } }; let Some(static_algorithm) = maybe_static_algorithm else { continue; }; let routing_rule = RoutingRule { rule_id: Some(algorithm.algorithm_id.clone().get_string_repr().to_string()), name: algorithm.name.clone(), description: algorithm.description.clone(), created_by: profile_id.get_string_repr().to_string(), algorithm: static_algorithm, algorithm_for: algorithm.algorithm_for.into(), metadata: Some(RoutingMetadata { kind: algorithm.kind, }), }; match create_de_euclid_routing_algo(&state, &routing_rule).await { Ok(decision_engine_routing_id) => { let mut is_active_rule = false; if active_payment_routing_ids.contains(&Some(algorithm.algorithm_id.clone())) { link_de_euclid_routing_algorithm( &state, ActivateRoutingConfigRequest { created_by: profile_id.get_string_repr().to_string(), routing_algorithm_id: decision_engine_routing_id.clone(), }, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to link active routing algorithm")?; is_active_rule = true; } response_list.push(RuleMigrationResponse { profile_id: profile_id.clone(), euclid_algorithm_id: algorithm.algorithm_id.clone(), decision_engine_algorithm_id: decision_engine_routing_id, is_active_rule, }); } Err(err) => { router_env::logger::error!( decision_engine_rule_migration_error = ?err, algorithm_id = ?algorithm.algorithm_id, "Failed to insert into decision engine" ); push_error( algorithm.algorithm_id.clone(), format!("Insertion error: {err:?}"), ); } } } Ok(routing_types::RuleMigrationResult { success: response_list, errors: error_list, }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 147, "total_crates": null }
fn_clm_router_retrieve_surcharge_decision_config_2454053583406145797
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/surcharge_decision_config pub async fn retrieve_surcharge_decision_config( state: SessionState, merchant_context: domain::MerchantContext, ) -> RouterResponse<SurchargeDecisionManagerResponse> { let db = state.store.as_ref(); let algorithm_id = merchant_context .get_merchant_account() .get_id() .get_payment_method_surcharge_routing_id(); let algo_config = db .find_config_by_key(&algorithm_id) .await .change_context(errors::ApiErrorResponse::ResourceIdNotFound) .attach_printable("The surcharge conditional config was not found in the DB")?; let record: SurchargeDecisionManagerRecord = algo_config .config .parse_struct("SurchargeDecisionConfigsRecord") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("The Surcharge Decision Config Record was not found")?; Ok(service_api::ApplicationResponse::Json(record)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 35, "total_crates": null }
fn_clm_router_upsert_surcharge_decision_config_2454053583406145797
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/surcharge_decision_config pub async fn upsert_surcharge_decision_config( _state: SessionState, _merchant_context: domain::MerchantContext, _request: SurchargeDecisionConfigReq, ) -> RouterResponse<SurchargeDecisionManagerRecord> { 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_delete_surcharge_decision_config_2454053583406145797
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/surcharge_decision_config pub async fn delete_surcharge_decision_config( _state: SessionState, _merchant_context: domain::MerchantContext, ) -> RouterResponse<()> { 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_health_check_redis_-3899550709035071783
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/health_check // Implementation of app::SessionState for HealthCheckInterface async fn health_check_redis(&self) -> CustomResult<HealthState, errors::HealthCheckRedisError> { let db = &*self.store; let redis_conn = db .get_redis_conn() .change_context(errors::HealthCheckRedisError::RedisConnectionError)?; redis_conn .serialize_and_set_key_with_expiry(&"test_key".into(), "test_value", 30) .await .change_context(errors::HealthCheckRedisError::SetFailed)?; logger::debug!("Redis set_key was successful"); redis_conn .get_key::<()>(&"test_key".into()) .await .change_context(errors::HealthCheckRedisError::GetFailed)?; logger::debug!("Redis get_key was successful"); redis_conn .delete_key(&"test_key".into()) .await .change_context(errors::HealthCheckRedisError::DeleteFailed)?; logger::debug!("Redis delete_key was successful"); Ok(HealthState::Running) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 37, "total_crates": null }
fn_clm_router_health_check_analytics_-3899550709035071783
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/health_check // Implementation of app::SessionState for HealthCheckInterface async fn health_check_analytics( &self, ) -> CustomResult<HealthState, errors::HealthCheckDBError> { let analytics = &self.pool; match analytics { analytics::AnalyticsProvider::Sqlx(client) => client .deep_health_check() .await .change_context(errors::HealthCheckDBError::SqlxAnalyticsError), analytics::AnalyticsProvider::Clickhouse(client) => client .deep_health_check() .await .change_context(errors::HealthCheckDBError::ClickhouseAnalyticsError), analytics::AnalyticsProvider::CombinedCkh(sqlx_client, ckh_client) => { sqlx_client .deep_health_check() .await .change_context(errors::HealthCheckDBError::SqlxAnalyticsError)?; ckh_client .deep_health_check() .await .change_context(errors::HealthCheckDBError::ClickhouseAnalyticsError) } analytics::AnalyticsProvider::CombinedSqlx(sqlx_client, ckh_client) => { sqlx_client .deep_health_check() .await .change_context(errors::HealthCheckDBError::SqlxAnalyticsError)?; ckh_client .deep_health_check() .await .change_context(errors::HealthCheckDBError::ClickhouseAnalyticsError) } }?; Ok(HealthState::Running) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 35, "total_crates": null }
fn_clm_router_health_check_db_-3899550709035071783
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/health_check // Implementation of app::SessionState for HealthCheckInterface async fn health_check_db(&self) -> CustomResult<HealthState, errors::HealthCheckDBError> { let db = &*self.store; db.health_check_db().await?; Ok(HealthState::Running) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 25, "total_crates": null }
fn_clm_router_health_check_outgoing_-3899550709035071783
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/health_check // Implementation of app::SessionState for HealthCheckInterface async fn health_check_outgoing( &self, ) -> CustomResult<HealthState, errors::HealthCheckOutGoing> { let request = services::Request::new(services::Method::Get, consts::OUTGOING_CALL_URL); services::call_connector_api(self, request, "outgoing_health_check") .await .map_err(|err| errors::HealthCheckOutGoing::OutGoingFailed { message: err.to_string(), })? .map_err(|err| errors::HealthCheckOutGoing::OutGoingFailed { message: format!( "Got a non 200 status while making outgoing request. Error {:?}", err.response ), })?; logger::debug!("Outgoing request successful"); Ok(HealthState::Running) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 24, "total_crates": null }