text
stringlengths
81
477k
file_path
stringlengths
22
92
module
stringlengths
13
87
token_count
int64
24
94.8k
has_source_code
bool
1 class
// File: crates/router/src/workflows/api_key_expiry.rs // Module: router::src::workflows::api_key_expiry use common_utils::{errors::ValidationError, ext_traits::ValueExt, types::user::ThemeLineage}; use diesel_models::{ enums as storage_enums, process_tracker::business_status, ApiKeyExpiryTrackingData, }; use router_env::logger; use scheduler::{workflows::ProcessTrackerWorkflow, SchedulerSessionState}; use crate::{ consts, errors, logger::error, routes::{metrics, SessionState}, services::email::types::ApiKeyExpiryReminder, types::{api, domain::UserEmail, storage}, utils::{ user::{self as user_utils, theme as theme_utils}, OptionExt, }, }; pub struct ApiKeyExpiryWorkflow; #[async_trait::async_trait] impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow { async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let db = &*state.store; let tracking_data: ApiKeyExpiryTrackingData = process .tracking_data .clone() .parse_value("ApiKeyExpiryTrackingData")?; let key_manager_satte = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_satte, &tracking_data.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await?; let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_satte, &tracking_data.merchant_id, &key_store, ) .await?; let email_id = merchant_account .merchant_details .clone() .parse_value::<api::MerchantDetails>("MerchantDetails")? .primary_email .ok_or(errors::ProcessTrackerError::EValidationError( ValidationError::MissingRequiredField { field_name: "email".to_string(), } .into(), ))?; let task_id = process.id.clone(); let retry_count = process.retry_count; let api_key_name = tracking_data.api_key_name.clone(); let prefix = tracking_data.prefix.clone(); let expires_in = tracking_data .expiry_reminder_days .get( usize::try_from(retry_count) .map_err(|_| errors::ProcessTrackerError::TypeConversionError)?, ) .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?; let theme = theme_utils::get_most_specific_theme_using_lineage( state, ThemeLineage::Merchant { tenant_id: state.tenant.tenant_id.clone(), org_id: merchant_account.get_org_id().clone(), merchant_id: merchant_account.get_id().clone(), }, ) .await .map_err(|err| { logger::error!(?err, "Failed to get theme"); errors::ProcessTrackerError::EApiErrorResponse })?; let email_contents = ApiKeyExpiryReminder { recipient_email: UserEmail::from_pii_email(email_id).map_err(|error| { logger::error!( ?error, "Failed to convert recipient's email to UserEmail from pii::Email" ); errors::ProcessTrackerError::EApiErrorResponse })?, subject: consts::EMAIL_SUBJECT_API_KEY_EXPIRY, expires_in: *expires_in, api_key_name, prefix, 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 .clone() .compose_and_send_email( user_utils::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await .map_err(errors::ProcessTrackerError::EEmailError)?; // If all the mails have been sent, then retry_count would be equal to length of the expiry_reminder_days vector if retry_count == i32::try_from(tracking_data.expiry_reminder_days.len() - 1) .map_err(|_| errors::ProcessTrackerError::TypeConversionError)? { state .get_db() .as_scheduler() .finish_process_with_business_status(process, business_status::COMPLETED_BY_PT) .await? } // If tasks are remaining that has to be scheduled else { let expiry_reminder_day = tracking_data .expiry_reminder_days .get( usize::try_from(retry_count + 1) .map_err(|_| errors::ProcessTrackerError::TypeConversionError)?, ) .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?; let updated_schedule_time = tracking_data.api_key_expiry.map(|api_key_expiry| { api_key_expiry.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day))) }); let updated_process_tracker_data = storage::ProcessTrackerUpdate::Update { name: None, retry_count: Some(retry_count + 1), schedule_time: updated_schedule_time, tracking_data: None, business_status: None, status: Some(storage_enums::ProcessTrackerStatus::New), updated_at: Some(common_utils::date_time::now()), }; let task_ids = vec![task_id]; db.process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data) .await?; // Remaining tasks are re-scheduled, so will be resetting the added count metrics::TASKS_RESET_COUNT .add(1, router_env::metric_attributes!(("flow", "ApiKeyExpiry"))); } Ok(()) } async fn error_handler<'a>( &'a self, _state: &'a SessionState, process: storage::ProcessTracker, _error: errors::ProcessTrackerError, ) -> errors::CustomResult<(), errors::ProcessTrackerError> { error!(%process.id, "Failed while executing workflow"); Ok(()) } }
crates/router/src/workflows/api_key_expiry.rs
router::src::workflows::api_key_expiry
1,348
true
// File: crates/router/src/workflows/outgoing_webhook_retry.rs // Module: router::src::workflows::outgoing_webhook_retry #[cfg(feature = "payouts")] use api_models::payouts as payout_models; use api_models::{ enums::EventType, webhook_events::OutgoingWebhookRequestContent, webhooks::{OutgoingWebhook, OutgoingWebhookContent}, }; use common_utils::{ consts::DEFAULT_LOCALE, ext_traits::{StringExt, ValueExt}, id_type, }; use diesel_models::process_tracker::business_status; use error_stack::ResultExt; use masking::PeekInterface; use router_env::tracing::{self, instrument}; use scheduler::{ consumer::{self, workflows::ProcessTrackerWorkflow}, types::process_data, utils as scheduler_utils, }; #[cfg(feature = "payouts")] use crate::core::payouts; use crate::{ core::{ payments, webhooks::{self as webhooks_core, types::OutgoingWebhookTrackingData}, }, db::StorageInterface, errors, logger, routes::{app::ReqState, SessionState}, types::{domain, storage}, }; pub struct OutgoingWebhookRetryWorkflow; #[async_trait::async_trait] impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { #[cfg(feature = "v1")] #[instrument(skip_all)] async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let delivery_attempt = storage::enums::WebhookDeliveryAttempt::AutomaticRetry; let tracking_data: OutgoingWebhookTrackingData = process .tracking_data .clone() .parse_value("OutgoingWebhookTrackingData")?; let db = &*state.store; let key_manager_state = &state.into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &tracking_data.merchant_id, &db.get_master_key().to_vec().into(), ) .await?; let business_profile = db .find_business_profile_by_profile_id( key_manager_state, &key_store, &tracking_data.business_profile_id, ) .await?; let event_id = webhooks_core::utils::generate_event_id(); let idempotent_event_id = webhooks_core::utils::get_idempotent_event_id( &tracking_data.primary_object_id, tracking_data.event_type, delivery_attempt, ) .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("Failed to generate idempotent event ID")?; let initial_event = match &tracking_data.initial_attempt_id { Some(initial_attempt_id) => { db.find_event_by_merchant_id_event_id( key_manager_state, &business_profile.merchant_id, initial_attempt_id, &key_store, ) .await? } // Tracking data inserted by old version of application, fetch event using old event ID // format None => { let old_event_id = format!( "{}_{}", tracking_data.primary_object_id, tracking_data.event_type ); db.find_event_by_merchant_id_event_id( key_manager_state, &business_profile.merchant_id, &old_event_id, &key_store, ) .await? } }; let now = common_utils::date_time::now(); let new_event = domain::Event { event_id, event_type: initial_event.event_type, event_class: initial_event.event_class, is_webhook_notified: false, primary_object_id: initial_event.primary_object_id, primary_object_type: initial_event.primary_object_type, created_at: now, merchant_id: Some(business_profile.merchant_id.clone()), business_profile_id: Some(business_profile.get_id().to_owned()), primary_object_created_at: initial_event.primary_object_created_at, idempotent_event_id: Some(idempotent_event_id), initial_attempt_id: Some(initial_event.event_id.clone()), request: initial_event.request, response: None, delivery_attempt: Some(delivery_attempt), metadata: initial_event.metadata, is_overall_delivery_successful: Some(false), }; let event = db .insert_event(key_manager_state, new_event, &key_store) .await .inspect_err(|error| { logger::error!(?error, "Failed to insert event in events table"); })?; match &event.request { Some(request) => { let request_content: OutgoingWebhookRequestContent = request .get_inner() .peek() .parse_struct("OutgoingWebhookRequestContent")?; Box::pin(webhooks_core::trigger_webhook_and_raise_event( state.clone(), business_profile, &key_store, event, request_content, delivery_attempt, None, Some(process), )) .await; } // Event inserted by old version of application, fetch current information about // resource None => { let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_state, &tracking_data.merchant_id, &key_store, ) .await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account.clone(), key_store.clone()), )); // TODO: Add request state for the PT flows as well let (content, event_type) = Box::pin(get_outgoing_webhook_content_and_event_type( state.clone(), state.get_req_state(), merchant_account.clone(), key_store.clone(), &tracking_data, )) .await?; match event_type { // Resource status is same as the event type of the current event Some(event_type) if event_type == tracking_data.event_type => { let outgoing_webhook = OutgoingWebhook { merchant_id: tracking_data.merchant_id.clone(), event_id: event.event_id.clone(), event_type, content: content.clone(), timestamp: event.created_at, }; let request_content = webhooks_core::get_outgoing_webhook_request( &merchant_context, outgoing_webhook, &business_profile, ) .map_err(|error| { logger::error!( ?error, "Failed to obtain outgoing webhook request content" ); errors::ProcessTrackerError::EApiErrorResponse })?; Box::pin(webhooks_core::trigger_webhook_and_raise_event( state.clone(), business_profile, &key_store, event, request_content, delivery_attempt, Some(content), Some(process), )) .await; } // Resource status has changed since the event was created, finish task _ => { logger::warn!( %event.event_id, "The current status of the resource `{:?}` (event type: {:?}) and the status of \ the resource when the event was created (event type: {:?}) differ, finishing task", tracking_data.primary_object_id, event_type, tracking_data.event_type ); db.as_scheduler() .finish_process_with_business_status( process.clone(), business_status::RESOURCE_STATUS_MISMATCH, ) .await?; } } } }; Ok(()) } #[cfg(feature = "v2")] async fn execute_workflow<'a>( &'a self, _state: &'a SessionState, _process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { todo!() } #[instrument(skip_all)] async fn error_handler<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, error: errors::ProcessTrackerError, ) -> errors::CustomResult<(), errors::ProcessTrackerError> { consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await } } /// Get the schedule time for the specified retry count. /// /// The schedule time can be configured in configs with this key: `pt_mapping_outgoing_webhooks`. /// /// ```json /// { /// "default_mapping": { /// "start_after": 60, /// "frequency": [300], /// "count": [5] /// }, /// "custom_merchant_mapping": { /// "merchant_id1": { /// "start_after": 30, /// "frequency": [300], /// "count": [2] /// } /// } /// } /// ``` /// /// This configuration value represents: /// - `default_mapping.start_after`: The first retry attempt should happen after 60 seconds by /// default. /// - `default_mapping.frequency` and `count`: The next 5 retries should have an interval of 300 /// seconds between them by default. /// - `custom_merchant_mapping.merchant_id1`: Merchant-specific retry configuration for merchant /// with merchant ID `merchant_id1`. #[cfg(feature = "v1")] #[instrument(skip_all)] pub(crate) async fn get_webhook_delivery_retry_schedule_time( db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, retry_count: i32, ) -> Option<time::PrimitiveDateTime> { let key = "pt_mapping_outgoing_webhooks"; let result = db .find_config_by_key(key) .await .map(|value| value.config) .and_then(|config| { config .parse_struct("OutgoingWebhookRetryProcessTrackerMapping") .change_context(errors::StorageError::DeserializationFailed) }); let mapping = result.map_or_else( |error| { if error.current_context().is_db_not_found() { logger::debug!("Outgoing webhooks retry config `{key}` not found, ignoring"); } else { logger::error!( ?error, "Failed to read outgoing webhooks retry config `{key}`" ); } process_data::OutgoingWebhookRetryProcessTrackerMapping::default() }, |mapping| { logger::debug!(?mapping, "Using custom outgoing webhooks retry config"); mapping }, ); let time_delta = scheduler_utils::get_outgoing_webhook_retry_schedule_time( mapping, merchant_id, retry_count, ); scheduler_utils::get_time_from_delta(time_delta) } /// Schedule the webhook delivery task for retry #[cfg(feature = "v1")] #[instrument(skip_all)] pub(crate) async fn retry_webhook_delivery_task( db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, process: storage::ProcessTracker, ) -> errors::CustomResult<(), errors::StorageError> { let schedule_time = get_webhook_delivery_retry_schedule_time(db, merchant_id, process.retry_count + 1).await; match schedule_time { Some(schedule_time) => { db.as_scheduler() .retry_process(process, schedule_time) .await } None => { db.as_scheduler() .finish_process_with_business_status(process, business_status::RETRIES_EXCEEDED) .await } } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn get_outgoing_webhook_content_and_event_type( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, tracking_data: &OutgoingWebhookTrackingData, ) -> Result<(OutgoingWebhookContent, Option<EventType>), errors::ProcessTrackerError> { use api_models::{ disputes::DisputeRetrieveRequest, mandates::MandateId, payments::{PaymentIdType, PaymentsResponse, PaymentsRetrieveRequest}, refunds::{RefundResponse, RefundsRetrieveRequest}, }; use crate::{ core::{ disputes::retrieve_dispute, mandate::get_mandate, payments::{payments_core, CallConnectorAction, PaymentStatus}, refunds::refund_retrieve_core_with_refund_id, }, services::{ApplicationResponse, AuthFlow}, types::{api::PSync, transformers::ForeignFrom}, }; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); match tracking_data.event_class { diesel_models::enums::EventClass::Payments => { let payment_id = tracking_data.primary_object_id.clone(); let payment_id = id_type::PaymentId::try_from(std::borrow::Cow::Owned(payment_id)) .map_err(|payment_id_parsing_error| { logger::error!( ?payment_id_parsing_error, "Failed to parse payment ID from tracking data" ); errors::ProcessTrackerError::DeserializationFailed })?; let request = PaymentsRetrieveRequest { resource_id: PaymentIdType::PaymentIntentId(payment_id), merchant_id: Some(tracking_data.merchant_id.clone()), force_sync: false, ..Default::default() }; let payments_response = match Box::pin(payments_core::< PSync, PaymentsResponse, _, _, _, payments::PaymentData<PSync>, >( state, req_state, merchant_context.clone(), None, PaymentStatus, request, AuthFlow::Client, CallConnectorAction::Avoid, None, hyperswitch_domain_models::payments::HeaderPayload::default(), )) .await? { ApplicationResponse::Json(payments_response) | ApplicationResponse::JsonWithHeaders((payments_response, _)) => { Ok(payments_response) } ApplicationResponse::StatusOk | ApplicationResponse::TextPlain(_) | ApplicationResponse::JsonForRedirection(_) | ApplicationResponse::Form(_) | ApplicationResponse::GenericLinkForm(_) | ApplicationResponse::PaymentLinkForm(_) | ApplicationResponse::FileData(_) => { Err(errors::ProcessTrackerError::ResourceFetchingFailed { resource_name: tracking_data.primary_object_id.clone(), }) } }?; let event_type: Option<EventType> = payments_response.status.into(); logger::debug!(current_resource_status=%payments_response.status); Ok(( OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)), event_type, )) } diesel_models::enums::EventClass::Refunds => { let refund_id = tracking_data.primary_object_id.clone(); let request = RefundsRetrieveRequest { refund_id, force_sync: Some(false), merchant_connector_details: None, }; let refund = Box::pin(refund_retrieve_core_with_refund_id( state, merchant_context.clone(), None, request, )) .await?; let event_type: Option<EventType> = refund.refund_status.into(); logger::debug!(current_resource_status=%refund.refund_status); let refund_response = RefundResponse::foreign_from(refund); Ok(( OutgoingWebhookContent::RefundDetails(Box::new(refund_response)), event_type, )) } diesel_models::enums::EventClass::Disputes => { let dispute_id = tracking_data.primary_object_id.clone(); let request = DisputeRetrieveRequest { dispute_id, force_sync: None, }; let dispute_response = match Box::pin(retrieve_dispute( state, merchant_context.clone(), None, request, )) .await? { ApplicationResponse::Json(dispute_response) | ApplicationResponse::JsonWithHeaders((dispute_response, _)) => { Ok(dispute_response) } ApplicationResponse::StatusOk | ApplicationResponse::TextPlain(_) | ApplicationResponse::JsonForRedirection(_) | ApplicationResponse::Form(_) | ApplicationResponse::GenericLinkForm(_) | ApplicationResponse::PaymentLinkForm(_) | ApplicationResponse::FileData(_) => { Err(errors::ProcessTrackerError::ResourceFetchingFailed { resource_name: tracking_data.primary_object_id.clone(), }) } } .map(Box::new)?; let event_type = Some(EventType::from(dispute_response.dispute_status)); logger::debug!(current_resource_status=%dispute_response.dispute_status); Ok(( OutgoingWebhookContent::DisputeDetails(dispute_response), event_type, )) } diesel_models::enums::EventClass::Mandates => { let mandate_id = tracking_data.primary_object_id.clone(); let request = MandateId { mandate_id }; let mandate_response = match get_mandate(state, merchant_context.clone(), request).await? { ApplicationResponse::Json(mandate_response) | ApplicationResponse::JsonWithHeaders((mandate_response, _)) => { Ok(mandate_response) } ApplicationResponse::StatusOk | ApplicationResponse::TextPlain(_) | ApplicationResponse::JsonForRedirection(_) | ApplicationResponse::Form(_) | ApplicationResponse::GenericLinkForm(_) | ApplicationResponse::PaymentLinkForm(_) | ApplicationResponse::FileData(_) => { Err(errors::ProcessTrackerError::ResourceFetchingFailed { resource_name: tracking_data.primary_object_id.clone(), }) } } .map(Box::new)?; let event_type: Option<EventType> = mandate_response.status.into(); logger::debug!(current_resource_status=%mandate_response.status); Ok(( OutgoingWebhookContent::MandateDetails(mandate_response), event_type, )) } #[cfg(feature = "payouts")] diesel_models::enums::EventClass::Payouts => { let payout_id = tracking_data.primary_object_id.clone(); let request = payout_models::PayoutRequest::PayoutActionRequest( payout_models::PayoutActionRequest { payout_id: id_type::PayoutId::try_from(std::borrow::Cow::Owned(payout_id))?, }, ); let payout_data = Box::pin(payouts::make_payout_data( &state, &merchant_context, None, &request, DEFAULT_LOCALE, )) .await?; let payout_create_response = payouts::response_handler(&state, &merchant_context, &payout_data).await?; let event_type: Option<EventType> = payout_data.payout_attempt.status.into(); logger::debug!(current_resource_status=%payout_data.payout_attempt.status); Ok(( OutgoingWebhookContent::PayoutDetails(Box::new(payout_create_response)), event_type, )) } } }
crates/router/src/workflows/outgoing_webhook_retry.rs
router::src::workflows::outgoing_webhook_retry
4,053
true
// File: crates/router/src/workflows/dispute_list.rs // Module: router::src::workflows::dispute_list use std::ops::Deref; use common_utils::ext_traits::{StringExt, ValueExt}; use diesel_models::process_tracker::business_status; use error_stack::ResultExt; use router_env::{logger, tracing::Instrument}; use scheduler::{ consumer::{self, types::process_data, workflows::ProcessTrackerWorkflow}, errors as sch_errors, utils as scheduler_utils, }; use crate::{ core::disputes, db::StorageInterface, errors, routes::SessionState, types::{api, domain, storage}, }; pub struct DisputeListWorkflow; /// This workflow fetches disputes from the connector for a given time range /// and creates a process tracker task for each dispute. /// It also schedules the next dispute list sync after dispute_polling_hours. #[async_trait::async_trait] impl ProcessTrackerWorkflow<SessionState> for DisputeListWorkflow { #[cfg(feature = "v2")] async fn execute_workflow<'a>( &'a self, _state: &'a SessionState, _process: storage::ProcessTracker, ) -> Result<(), sch_errors::ProcessTrackerError> { todo!() } #[cfg(feature = "v1")] async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), sch_errors::ProcessTrackerError> { let db = &*state.store; let tracking_data: api::DisputeListPTData = process .tracking_data .clone() .parse_value("ProcessDisputePTData")?; let key_manager_state = &state.into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &tracking_data.merchant_id, &db.get_master_key().to_vec().into(), ) .await?; let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_state, &tracking_data.merchant_id.clone(), &key_store, ) .await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); let business_profile = state .store .find_business_profile_by_profile_id( &(state).into(), merchant_context.get_merchant_key_store(), &tracking_data.profile_id, ) .await?; if process.retry_count == 0 { let m_db = state.clone().store; let m_tracking_data = tracking_data.clone(); let dispute_polling_interval = *business_profile .dispute_polling_interval .unwrap_or_default() .deref(); tokio::spawn( async move { schedule_next_dispute_list_task( &*m_db, &m_tracking_data, dispute_polling_interval, ) .await .map_err(|error| { logger::error!( "Failed to add dispute list task to process tracker: {error}" ) }) } .in_current_span(), ); }; let response = Box::pin(disputes::fetch_disputes_from_connector( state.clone(), merchant_context, tracking_data.merchant_connector_id, hyperswitch_domain_models::router_request_types::FetchDisputesRequestData { created_from: tracking_data.created_from, created_till: tracking_data.created_till, }, )) .await .attach_printable("Dispute update failed"); if response.is_err() { retry_sync_task( db, tracking_data.connector_name, tracking_data.merchant_id, process, ) .await?; } else { state .store .as_scheduler() .finish_process_with_business_status(process, business_status::COMPLETED_BY_PT) .await? } Ok(()) } async fn error_handler<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, error: sch_errors::ProcessTrackerError, ) -> errors::CustomResult<(), sch_errors::ProcessTrackerError> { consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await } } pub async fn get_sync_process_schedule_time( db: &dyn StorageInterface, connector: &str, merchant_id: &common_utils::id_type::MerchantId, retry_count: i32, ) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { let mapping: common_utils::errors::CustomResult< process_data::ConnectorPTMapping, errors::StorageError, > = db .find_config_by_key(&format!("pt_mapping_{connector}")) .await .map(|value| value.config) .and_then(|config| { config .parse_struct("ConnectorPTMapping") .change_context(errors::StorageError::DeserializationFailed) }); let mapping = match mapping { Ok(x) => x, Err(error) => { logger::info!(?error, "Redis Mapping Error"); process_data::ConnectorPTMapping::default() } }; let time_delta = scheduler_utils::get_schedule_time(mapping, merchant_id, retry_count); Ok(scheduler_utils::get_time_from_delta(time_delta)) } /// Schedule the task for retry /// /// Returns bool which indicates whether this was the last retry or not pub async fn retry_sync_task( db: &dyn StorageInterface, connector: String, merchant_id: common_utils::id_type::MerchantId, pt: storage::ProcessTracker, ) -> Result<bool, sch_errors::ProcessTrackerError> { let schedule_time: Option<time::PrimitiveDateTime> = get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1).await?; match schedule_time { Some(s_time) => { db.as_scheduler().retry_process(pt, s_time).await?; Ok(false) } None => { db.as_scheduler() .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED) .await?; Ok(true) } } } #[cfg(feature = "v1")] pub async fn schedule_next_dispute_list_task( db: &dyn StorageInterface, tracking_data: &api::DisputeListPTData, dispute_polling_interval: i32, ) -> Result<(), errors::ProcessTrackerError> { let new_created_till = tracking_data .created_till .checked_add(time::Duration::hours(i64::from(dispute_polling_interval))) .ok_or(sch_errors::ProcessTrackerError::TypeConversionError)?; let fetch_request = hyperswitch_domain_models::router_request_types::FetchDisputesRequestData { created_from: tracking_data.created_till, created_till: new_created_till, }; disputes::add_dispute_list_task_to_pt( db, &tracking_data.connector_name, tracking_data.merchant_id.clone(), tracking_data.merchant_connector_id.clone(), tracking_data.profile_id.clone(), fetch_request, ) .await?; Ok(()) }
crates/router/src/workflows/dispute_list.rs
router::src::workflows::dispute_list
1,573
true
// File: crates/router/src/workflows/payment_sync.rs // Module: router::src::workflows::payment_sync #[cfg(feature = "v2")] use common_utils::ext_traits::AsyncExt; use common_utils::ext_traits::{OptionExt, StringExt, ValueExt}; use diesel_models::process_tracker::business_status; use error_stack::ResultExt; use router_env::logger; use scheduler::{ consumer::{self, types::process_data, workflows::ProcessTrackerWorkflow}, errors as sch_errors, utils as scheduler_utils, }; #[cfg(feature = "v2")] use crate::workflows::revenue_recovery::update_token_expiry_based_on_schedule_time; use crate::{ consts, core::{ errors::StorageErrorExt, payments::{self as payment_flows, operations}, }, db::StorageInterface, errors, routes::SessionState, services, types::{ api, domain, storage::{self, enums}, }, utils, }; pub struct PaymentsSyncWorkflow; #[async_trait::async_trait] impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow { #[cfg(feature = "v2")] async fn execute_workflow<'a>( &'a self, _state: &'a SessionState, _process: storage::ProcessTracker, ) -> Result<(), sch_errors::ProcessTrackerError> { todo!() } #[cfg(feature = "v1")] async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), sch_errors::ProcessTrackerError> { let db: &dyn StorageInterface = &*state.store; let tracking_data: api::PaymentsRetrieveRequest = process .tracking_data .clone() .parse_value("PaymentsRetrieveRequest")?; let key_manager_state = &state.into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, tracking_data .merchant_id .as_ref() .get_required_value("merchant_id")?, &db.get_master_key().to_vec().into(), ) .await?; let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_state, tracking_data .merchant_id .as_ref() .get_required_value("merchant_id")?, &key_store, ) .await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); // TODO: Add support for ReqState in PT flows let (mut payment_data, _, customer, _, _) = Box::pin(payment_flows::payments_operation_core::< api::PSync, _, _, _, payment_flows::PaymentData<api::PSync>, >( state, state.get_req_state(), &merchant_context, None, operations::PaymentStatus, tracking_data.clone(), payment_flows::CallConnectorAction::Trigger, services::AuthFlow::Client, None, hyperswitch_domain_models::payments::HeaderPayload::default(), )) .await?; let terminal_status = [ enums::AttemptStatus::RouterDeclined, enums::AttemptStatus::Charged, enums::AttemptStatus::AutoRefunded, enums::AttemptStatus::Voided, enums::AttemptStatus::VoidFailed, enums::AttemptStatus::CaptureFailed, enums::AttemptStatus::Failure, ]; match &payment_data.payment_attempt.status { status if terminal_status.contains(status) => { state .store .as_scheduler() .finish_process_with_business_status(process, business_status::COMPLETED_BY_PT) .await? } _ => { let connector = payment_data .payment_attempt .connector .clone() .ok_or(sch_errors::ProcessTrackerError::MissingRequiredField)?; let is_last_retry = retry_sync_task( db, connector, payment_data.payment_attempt.merchant_id.clone(), process, ) .await?; // If the payment status is still processing and there is no connector transaction_id // then change the payment status to failed if all retries exceeded if is_last_retry && payment_data.payment_attempt.status == enums::AttemptStatus::Pending && payment_data .payment_attempt .connector_transaction_id .as_ref() .is_none() { let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::PGStatusUpdate { status: api_models::enums::IntentStatus::Failed,updated_by: merchant_account.storage_scheme.to_string(), incremental_authorization_allowed: Some(false), feature_metadata: payment_data.payment_intent.feature_metadata.clone().map(masking::Secret::new), }; let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ErrorUpdate { connector: None, status: api_models::enums::AttemptStatus::Failure, error_code: None, error_message: None, error_reason: Some(Some( consts::REQUEST_TIMEOUT_ERROR_MESSAGE_FROM_PSYNC.to_string(), )), amount_capturable: Some(common_utils::types::MinorUnit::new(0)), updated_by: merchant_account.storage_scheme.to_string(), unified_code: None, unified_message: None, connector_transaction_id: None, payment_method_data: None, authentication_type: None, issuer_error_code: None, issuer_error_message: None, network_details:None }; payment_data.payment_attempt = db .update_payment_attempt_with_attempt_id( payment_data.payment_attempt, payment_attempt_update, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_data.payment_intent = db .update_payment_intent( &state.into(), payment_data.payment_intent, payment_intent_update, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let profile_id = payment_data .payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not find profile_id in payment intent")?; let business_profile = db .find_business_profile_by_profile_id( key_manager_state, &key_store, profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; // Trigger the outgoing webhook to notify the merchant about failed payment let operation = operations::PaymentStatus; Box::pin(utils::trigger_payments_webhook( merchant_context, business_profile, payment_data, customer, state, operation, )) .await .map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error)) .ok(); } } }; Ok(()) } async fn error_handler<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, error: sch_errors::ProcessTrackerError, ) -> errors::CustomResult<(), sch_errors::ProcessTrackerError> { consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await } } /// Get the next schedule time /// /// The schedule time can be configured in configs by this key `pt_mapping_trustpay` /// ```json /// { /// "default_mapping": { /// "start_after": 60, /// "frequency": [300], /// "count": [5] /// }, /// "max_retries_count": 5 /// } /// ``` /// /// This config represents /// /// `start_after`: The first psync should happen after 60 seconds /// /// `frequency` and `count`: The next 5 retries should have an interval of 300 seconds between them pub async fn get_sync_process_schedule_time( db: &dyn StorageInterface, connector: &str, merchant_id: &common_utils::id_type::MerchantId, retry_count: i32, ) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { let mapping: common_utils::errors::CustomResult< process_data::ConnectorPTMapping, errors::StorageError, > = db .find_config_by_key(&format!("pt_mapping_{connector}")) .await .map(|value| value.config) .and_then(|config| { config .parse_struct("ConnectorPTMapping") .change_context(errors::StorageError::DeserializationFailed) }); let mapping = match mapping { Ok(x) => x, Err(error) => { logger::info!(?error, "Redis Mapping Error"); process_data::ConnectorPTMapping::default() } }; let time_delta = scheduler_utils::get_schedule_time(mapping, merchant_id, retry_count); Ok(scheduler_utils::get_time_from_delta(time_delta)) } /// Schedule the task for retry /// /// Returns bool which indicates whether this was the last retry or not pub async fn retry_sync_task( db: &dyn StorageInterface, connector: String, merchant_id: common_utils::id_type::MerchantId, pt: storage::ProcessTracker, ) -> Result<bool, sch_errors::ProcessTrackerError> { let schedule_time = get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1).await?; match schedule_time { Some(s_time) => { db.as_scheduler().retry_process(pt, s_time).await?; Ok(false) } None => { db.as_scheduler() .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED) .await?; Ok(true) } } } /// Schedule the task for retry and update redis token expiry time /// /// Returns bool which indicates whether this was the last retry or not #[cfg(feature = "v2")] pub async fn recovery_retry_sync_task( state: &SessionState, connector_customer_id: Option<String>, connector: String, merchant_id: common_utils::id_type::MerchantId, pt: storage::ProcessTracker, ) -> Result<bool, sch_errors::ProcessTrackerError> { let db = &*state.store; let schedule_time = get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1).await?; match schedule_time { Some(s_time) => { db.as_scheduler().retry_process(pt, s_time).await?; connector_customer_id .async_map(|id| async move { let _ = update_token_expiry_based_on_schedule_time(state, &id, Some(s_time)) .await .map_err(|e| { logger::error!( error = ?e, connector_customer_id = %id, "Failed to update the token expiry time in redis" ); e }); }) .await; Ok(false) } None => { db.as_scheduler() .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED) .await?; Ok(true) } } } #[cfg(test)] mod tests { #![allow(clippy::expect_used, clippy::unwrap_used)] use super::*; #[test] fn test_get_default_schedule_time() { let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("-")).unwrap(); let schedule_time_delta = scheduler_utils::get_schedule_time( process_data::ConnectorPTMapping::default(), &merchant_id, 0, ) .unwrap(); let first_retry_time_delta = scheduler_utils::get_schedule_time( process_data::ConnectorPTMapping::default(), &merchant_id, 1, ) .unwrap(); let cpt_default = process_data::ConnectorPTMapping::default().default_mapping; assert_eq!( vec![schedule_time_delta, first_retry_time_delta], vec![ cpt_default.start_after, cpt_default.frequencies.first().unwrap().0 ] ); } }
crates/router/src/workflows/payment_sync.rs
router::src::workflows::payment_sync
2,671
true
// File: crates/router/src/workflows/revenue_recovery.rs // Module: router::src::workflows::revenue_recovery #[cfg(feature = "v2")] use std::collections::HashMap; #[cfg(feature = "v2")] use api_models::{enums::RevenueRecoveryAlgorithmType, payments::PaymentsGetIntentRequest}; use common_utils::errors::CustomResult; #[cfg(feature = "v2")] use common_utils::{ ext_traits::AsyncExt, ext_traits::{StringExt, ValueExt}, id_type, }; #[cfg(feature = "v2")] use diesel_models::types::BillingConnectorPaymentMethodDetails; #[cfg(feature = "v2")] use error_stack::{Report, ResultExt}; #[cfg(all(feature = "revenue_recovery", feature = "v2"))] use external_services::{ date_time, grpc_client::revenue_recovery::recovery_decider_client as external_grpc_client, }; #[cfg(feature = "v2")] use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, payments::{payment_attempt, PaymentConfirmData, PaymentIntent, PaymentIntentData}, router_flow_types, router_flow_types::Authorize, }; #[cfg(feature = "v2")] use masking::{ExposeInterface, PeekInterface, Secret}; #[cfg(feature = "v2")] use rand::Rng; use router_env::{ logger, tracing::{self, instrument}, }; use scheduler::{ consumer::{self, workflows::ProcessTrackerWorkflow}, errors, }; #[cfg(feature = "v2")] use scheduler::{types::process_data, utils as scheduler_utils}; #[cfg(feature = "v2")] use storage_impl::errors as storage_errors; #[cfg(feature = "v2")] use time::Date; #[cfg(feature = "v2")] use crate::core::payments::operations; #[cfg(feature = "v2")] use crate::routes::app::ReqState; #[cfg(feature = "v2")] use crate::services; #[cfg(feature = "v2")] use crate::types::storage::{ revenue_recovery::RetryLimitsConfig, revenue_recovery_redis_operation::{ PaymentProcessorTokenStatus, PaymentProcessorTokenWithRetryInfo, RedisTokenManager, }, }; #[cfg(feature = "v2")] use crate::workflows::revenue_recovery::pcr::api; #[cfg(feature = "v2")] use crate::{ core::{ payments, revenue_recovery::{self as pcr}, }, db::StorageInterface, errors::StorageError, types::{ api::{self as api_types}, domain, storage::{ revenue_recovery as pcr_storage_types, revenue_recovery_redis_operation::PaymentProcessorTokenDetails, }, }, }; use crate::{routes::SessionState, types::storage}; pub struct ExecutePcrWorkflow; #[cfg(feature = "v2")] pub const REVENUE_RECOVERY: &str = "revenue_recovery"; #[async_trait::async_trait] impl ProcessTrackerWorkflow<SessionState> for ExecutePcrWorkflow { #[cfg(feature = "v1")] async fn execute_workflow<'a>( &'a self, _state: &'a SessionState, _process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { Ok(()) } #[cfg(feature = "v2")] async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let tracking_data = process .tracking_data .clone() .parse_value::<pcr_storage_types::RevenueRecoveryWorkflowTrackingData>( "PCRWorkflowTrackingData", )?; let request = PaymentsGetIntentRequest { id: tracking_data.global_payment_id.clone(), }; let revenue_recovery_payment_data = extract_data_and_perform_action(state, &tracking_data).await?; let merchant_context_from_revenue_recovery_payment_data = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( revenue_recovery_payment_data.merchant_account.clone(), revenue_recovery_payment_data.key_store.clone(), ))); let (payment_data, _, _) = payments::payments_intent_operation_core::< api_types::PaymentGetIntent, _, _, PaymentIntentData<api_types::PaymentGetIntent>, >( state, state.get_req_state(), merchant_context_from_revenue_recovery_payment_data.clone(), revenue_recovery_payment_data.profile.clone(), payments::operations::PaymentGetIntent, request, tracking_data.global_payment_id.clone(), hyperswitch_domain_models::payments::HeaderPayload::default(), ) .await?; match process.name.as_deref() { Some("EXECUTE_WORKFLOW") => { Box::pin(pcr::perform_execute_payment( state, &process, &revenue_recovery_payment_data.profile.clone(), merchant_context_from_revenue_recovery_payment_data.clone(), &tracking_data, &revenue_recovery_payment_data, &payment_data.payment_intent, )) .await } Some("PSYNC_WORKFLOW") => { Box::pin(pcr::perform_payments_sync( state, &process, &revenue_recovery_payment_data.profile.clone(), merchant_context_from_revenue_recovery_payment_data.clone(), &tracking_data, &revenue_recovery_payment_data, &payment_data.payment_intent, )) .await?; Ok(()) } Some("CALCULATE_WORKFLOW") => { Box::pin(pcr::perform_calculate_workflow( state, &process, &revenue_recovery_payment_data.profile.clone(), merchant_context_from_revenue_recovery_payment_data, &tracking_data, &revenue_recovery_payment_data, &payment_data.payment_intent, )) .await } _ => Err(errors::ProcessTrackerError::JobNotFound), } } #[instrument(skip_all)] async fn error_handler<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, error: errors::ProcessTrackerError, ) -> CustomResult<(), errors::ProcessTrackerError> { logger::error!("Encountered error"); consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await } } #[cfg(feature = "v2")] pub(crate) async fn extract_data_and_perform_action( state: &SessionState, tracking_data: &pcr_storage_types::RevenueRecoveryWorkflowTrackingData, ) -> Result<pcr_storage_types::RevenueRecoveryPaymentData, errors::ProcessTrackerError> { let db = &state.store; let key_manager_state = &state.into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &tracking_data.merchant_id, &db.get_master_key().to_vec().into(), ) .await?; let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_state, &tracking_data.merchant_id, &key_store, ) .await?; let profile = db .find_business_profile_by_profile_id( key_manager_state, &key_store, &tracking_data.profile_id, ) .await?; let billing_mca = db .find_merchant_connector_account_by_id( key_manager_state, &tracking_data.billing_mca_id, &key_store, ) .await?; let pcr_payment_data = pcr_storage_types::RevenueRecoveryPaymentData { merchant_account, profile: profile.clone(), key_store, billing_mca, retry_algorithm: profile .revenue_recovery_retry_algorithm_type .unwrap_or(tracking_data.revenue_recovery_retry), psync_data: None, }; Ok(pcr_payment_data) } #[cfg(feature = "v2")] pub(crate) async fn get_schedule_time_to_retry_mit_payments( db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, retry_count: i32, ) -> Option<time::PrimitiveDateTime> { let key = "pt_mapping_pcr_retries"; let result = db .find_config_by_key(key) .await .map(|value| value.config) .and_then(|config| { config .parse_struct("RevenueRecoveryPaymentProcessTrackerMapping") .change_context(StorageError::DeserializationFailed) }); let mapping = result.map_or_else( |error| { if error.current_context().is_db_not_found() { logger::debug!("Revenue Recovery retry config `{key}` not found, ignoring"); } else { logger::error!( ?error, "Failed to read Revenue Recovery retry config `{key}`" ); } process_data::RevenueRecoveryPaymentProcessTrackerMapping::default() }, |mapping| { logger::debug!(?mapping, "Using custom pcr payments retry config"); mapping }, ); let time_delta = scheduler_utils::get_pcr_payments_retry_schedule_time(mapping, merchant_id, retry_count); scheduler_utils::get_time_from_delta(time_delta) } #[cfg(feature = "v2")] pub(crate) async fn get_schedule_time_for_smart_retry( state: &SessionState, payment_intent: &PaymentIntent, retry_after_time: Option<prost_types::Timestamp>, token_with_retry_info: &PaymentProcessorTokenWithRetryInfo, ) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { let card_config = &state.conf.revenue_recovery.card_config; // Not populating it right now let first_error_message = "None".to_string(); let retry_count_left = token_with_retry_info.monthly_retry_remaining; let pg_error_code = token_with_retry_info.token_status.error_code.clone(); let card_info = token_with_retry_info .token_status .payment_processor_token_details .clone(); let billing_state = payment_intent .billing_address .as_ref() .and_then(|addr_enc| addr_enc.get_inner().address.as_ref()) .and_then(|details| details.state.as_ref()) .cloned(); let revenue_recovery_metadata = payment_intent .feature_metadata .as_ref() .and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref()); let card_network = card_info.card_network.clone(); let total_retry_count_within_network = card_config.get_network_config(card_network.clone()); let card_network_str = card_network.map(|network| network.to_string()); let card_issuer_str = card_info.card_issuer.clone(); let card_funding_str = match card_info.card_type.as_deref() { Some("card") => None, Some(s) => Some(s.to_string()), None => None, }; let start_time_primitive = payment_intent.created_at; let recovery_timestamp_config = &state.conf.revenue_recovery.recovery_timestamp; let modified_start_time_primitive = start_time_primitive.saturating_add( time::Duration::seconds(recovery_timestamp_config.initial_timestamp_in_seconds), ); let start_time_proto = date_time::convert_to_prost_timestamp(modified_start_time_primitive); let merchant_id = Some(payment_intent.merchant_id.get_string_repr().to_string()); let invoice_amount = Some( payment_intent .amount_details .order_amount .get_amount_as_i64(), ); let invoice_currency = Some(payment_intent.amount_details.currency.to_string()); let billing_country = payment_intent .billing_address .as_ref() .and_then(|addr_enc| addr_enc.get_inner().address.as_ref()) .and_then(|details| details.country.as_ref()) .map(|country| country.to_string()); let billing_city = payment_intent .billing_address .as_ref() .and_then(|addr_enc| addr_enc.get_inner().address.as_ref()) .and_then(|details| details.city.as_ref()) .cloned(); let first_pg_error_code = revenue_recovery_metadata .and_then(|metadata| metadata.first_payment_attempt_pg_error_code.clone()); let first_network_advice_code = revenue_recovery_metadata .and_then(|metadata| metadata.first_payment_attempt_network_advice_code.clone()); let first_network_error_code = revenue_recovery_metadata .and_then(|metadata| metadata.first_payment_attempt_network_decline_code.clone()); let invoice_due_date = revenue_recovery_metadata .and_then(|metadata| metadata.invoice_next_billing_time) .map(date_time::convert_to_prost_timestamp); let decider_request = InternalDeciderRequest { first_error_message, billing_state, card_funding: card_funding_str, card_network: card_network_str, card_issuer: card_issuer_str, invoice_start_time: Some(start_time_proto), retry_count: Some(token_with_retry_info.total_30_day_retries.into()), merchant_id, invoice_amount, invoice_currency, invoice_due_date, billing_country, billing_city, attempt_currency: None, attempt_status: None, attempt_amount: None, pg_error_code, network_advice_code: None, network_error_code: None, first_pg_error_code, first_network_advice_code, first_network_error_code, attempt_response_time: None, payment_method_type: None, payment_gateway: None, retry_count_left: Some(retry_count_left.into()), total_retry_count_within_network: Some( total_retry_count_within_network .max_retry_count_for_thirty_day .into(), ), first_error_msg_time: None, wait_time: retry_after_time, }; if let Some(mut client) = state.grpc_client.recovery_decider_client.clone() { match client .decide_on_retry(decider_request.into(), state.get_recovery_grpc_headers()) .await { Ok(grpc_response) => Ok(grpc_response .retry_flag .then_some(()) .and(grpc_response.retry_time) .and_then(|prost_ts| { match date_time::convert_from_prost_timestamp(&prost_ts) { Ok(pdt) => Some(pdt), Err(e) => { logger::error!( "Failed to convert retry_time from prost::Timestamp: {e:?}" ); None // If conversion fails, treat as no valid retry time } } })), Err(e) => { logger::error!("Recovery decider gRPC call failed: {e:?}"); Ok(None) } } } else { logger::debug!("Recovery decider client is not configured"); Ok(None) } } #[cfg(feature = "v2")] #[derive(Debug)] struct InternalDeciderRequest { first_error_message: String, billing_state: Option<Secret<String>>, card_funding: Option<String>, card_network: Option<String>, card_issuer: Option<String>, invoice_start_time: Option<prost_types::Timestamp>, retry_count: Option<i64>, merchant_id: Option<String>, invoice_amount: Option<i64>, invoice_currency: Option<String>, invoice_due_date: Option<prost_types::Timestamp>, billing_country: Option<String>, billing_city: Option<String>, attempt_currency: Option<String>, attempt_status: Option<String>, attempt_amount: Option<i64>, pg_error_code: Option<String>, network_advice_code: Option<String>, network_error_code: Option<String>, first_pg_error_code: Option<String>, first_network_advice_code: Option<String>, first_network_error_code: Option<String>, attempt_response_time: Option<prost_types::Timestamp>, payment_method_type: Option<String>, payment_gateway: Option<String>, retry_count_left: Option<i64>, total_retry_count_within_network: Option<i64>, first_error_msg_time: Option<prost_types::Timestamp>, wait_time: Option<prost_types::Timestamp>, } #[cfg(feature = "v2")] impl From<InternalDeciderRequest> for external_grpc_client::DeciderRequest { fn from(internal_request: InternalDeciderRequest) -> Self { Self { first_error_message: internal_request.first_error_message, billing_state: internal_request.billing_state.map(|s| s.peek().to_string()), card_funding: internal_request.card_funding, card_network: internal_request.card_network, card_issuer: internal_request.card_issuer, invoice_start_time: internal_request.invoice_start_time, retry_count: internal_request.retry_count, merchant_id: internal_request.merchant_id, invoice_amount: internal_request.invoice_amount, invoice_currency: internal_request.invoice_currency, invoice_due_date: internal_request.invoice_due_date, billing_country: internal_request.billing_country, billing_city: internal_request.billing_city, attempt_currency: internal_request.attempt_currency, attempt_status: internal_request.attempt_status, attempt_amount: internal_request.attempt_amount, pg_error_code: internal_request.pg_error_code, network_advice_code: internal_request.network_advice_code, network_error_code: internal_request.network_error_code, first_pg_error_code: internal_request.first_pg_error_code, first_network_advice_code: internal_request.first_network_advice_code, first_network_error_code: internal_request.first_network_error_code, attempt_response_time: internal_request.attempt_response_time, payment_method_type: internal_request.payment_method_type, payment_gateway: internal_request.payment_gateway, retry_count_left: internal_request.retry_count_left, total_retry_count_within_network: internal_request.total_retry_count_within_network, first_error_msg_time: internal_request.first_error_msg_time, wait_time: internal_request.wait_time, } } } #[cfg(feature = "v2")] #[derive(Debug, Clone)] pub struct ScheduledToken { pub token_details: PaymentProcessorTokenDetails, pub schedule_time: time::PrimitiveDateTime, } #[cfg(feature = "v2")] pub fn calculate_difference_in_seconds(scheduled_time: time::PrimitiveDateTime) -> i64 { let now_utc = time::OffsetDateTime::now_utc(); let scheduled_offset_dt = scheduled_time.assume_utc(); let difference = scheduled_offset_dt - now_utc; difference.whole_seconds() } #[cfg(feature = "v2")] pub async fn update_token_expiry_based_on_schedule_time( state: &SessionState, connector_customer_id: &str, delayed_schedule_time: Option<time::PrimitiveDateTime>, ) -> CustomResult<(), errors::ProcessTrackerError> { let expiry_buffer = state .conf .revenue_recovery .recovery_timestamp .redis_ttl_buffer_in_seconds; delayed_schedule_time .async_map(|t| async move { let expiry_time = calculate_difference_in_seconds(t) + expiry_buffer; RedisTokenManager::update_connector_customer_lock_ttl( state, connector_customer_id, expiry_time, ) .await .change_context(errors::ProcessTrackerError::ERedisError( errors::RedisError::RedisConnectionError.into(), )) }) .await .transpose()?; Ok(()) } #[cfg(feature = "v2")] pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type( state: &SessionState, connector_customer_id: &str, payment_intent: &PaymentIntent, retry_algorithm_type: RevenueRecoveryAlgorithmType, retry_count: i32, ) -> CustomResult<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { let mut scheduled_time = None; match retry_algorithm_type { RevenueRecoveryAlgorithmType::Monitoring => { logger::error!("Monitoring type found for Revenue Recovery retry payment"); } RevenueRecoveryAlgorithmType::Cascading => { let time = get_schedule_time_to_retry_mit_payments( state.store.as_ref(), &payment_intent.merchant_id, retry_count, ) .await .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?; scheduled_time = Some(time); } RevenueRecoveryAlgorithmType::Smart => { scheduled_time = get_best_psp_token_available_for_smart_retry( state, connector_customer_id, payment_intent, ) .await .change_context(errors::ProcessTrackerError::EApiErrorResponse)?; } } let delayed_schedule_time = scheduled_time.map(|time| add_random_delay_to_schedule_time(state, time)); let _ = update_token_expiry_based_on_schedule_time( state, connector_customer_id, delayed_schedule_time, ) .await; Ok(delayed_schedule_time) } #[cfg(feature = "v2")] pub async fn get_best_psp_token_available_for_smart_retry( state: &SessionState, connector_customer_id: &str, payment_intent: &PaymentIntent, ) -> CustomResult<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { // Lock using payment_id let locked = RedisTokenManager::lock_connector_customer_status( state, connector_customer_id, &payment_intent.id, ) .await .change_context(errors::ProcessTrackerError::ERedisError( errors::RedisError::RedisConnectionError.into(), ))?; match !locked { true => Ok(None), false => { // Get existing tokens from Redis let existing_tokens = RedisTokenManager::get_connector_customer_payment_processor_tokens( state, connector_customer_id, ) .await .change_context(errors::ProcessTrackerError::ERedisError( errors::RedisError::RedisConnectionError.into(), ))?; // TODO: Insert into payment_intent_feature_metadata (DB operation) let result = RedisTokenManager::get_tokens_with_retry_metadata(state, &existing_tokens); let best_token_time = call_decider_for_payment_processor_tokens_select_closet_time( state, &result, payment_intent, connector_customer_id, ) .await .change_context(errors::ProcessTrackerError::EApiErrorResponse)?; Ok(best_token_time) } } } #[cfg(feature = "v2")] pub async fn calculate_smart_retry_time( state: &SessionState, payment_intent: &PaymentIntent, token_with_retry_info: &PaymentProcessorTokenWithRetryInfo, ) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { let wait_hours = token_with_retry_info.retry_wait_time_hours; let current_time = time::OffsetDateTime::now_utc(); let future_time = current_time + time::Duration::hours(wait_hours); // Timestamp after which retry can be done without penalty let future_timestamp = Some(prost_types::Timestamp { seconds: future_time.unix_timestamp(), nanos: 0, }); get_schedule_time_for_smart_retry( state, payment_intent, future_timestamp, token_with_retry_info, ) .await } #[cfg(feature = "v2")] async fn process_token_for_retry( state: &SessionState, token_with_retry_info: &PaymentProcessorTokenWithRetryInfo, payment_intent: &PaymentIntent, ) -> Result<Option<ScheduledToken>, errors::ProcessTrackerError> { let token_status: &PaymentProcessorTokenStatus = &token_with_retry_info.token_status; let inserted_by_attempt_id = &token_status.inserted_by_attempt_id; let skip = token_status.is_hard_decline.unwrap_or(false); match skip { true => { logger::info!( "Skipping decider call due to hard decline token inserted by attempt_id: {}", inserted_by_attempt_id.get_string_repr() ); Ok(None) } false => { let schedule_time = calculate_smart_retry_time(state, payment_intent, token_with_retry_info).await?; Ok(schedule_time.map(|schedule_time| ScheduledToken { token_details: token_status.payment_processor_token_details.clone(), schedule_time, })) } } } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn call_decider_for_payment_processor_tokens_select_closet_time( state: &SessionState, processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>, payment_intent: &PaymentIntent, connector_customer_id: &str, ) -> CustomResult<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { tracing::debug!("Filtered payment attempts based on payment tokens",); let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new(); for token_with_retry_info in processor_tokens.values() { let token_details = &token_with_retry_info .token_status .payment_processor_token_details; let error_code = token_with_retry_info.token_status.error_code.clone(); match error_code { None => { let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1); let schedule_time = time::PrimitiveDateTime::new( utc_schedule_time.date(), utc_schedule_time.time(), ); tokens_with_schedule_time = vec![ScheduledToken { token_details: token_details.clone(), schedule_time, }]; tracing::debug!( "Found payment processor token with no error code scheduling it for {schedule_time}", ); break; } Some(_) => { process_token_for_retry(state, token_with_retry_info, payment_intent) .await? .map(|token_with_schedule_time| { tokens_with_schedule_time.push(token_with_schedule_time) }); } } } let best_token = tokens_with_schedule_time .iter() .min_by_key(|token| token.schedule_time) .cloned(); match best_token { None => { RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id) .await .change_context(errors::ProcessTrackerError::EApiErrorResponse)?; tracing::debug!("No payment processor tokens available for scheduling"); Ok(None) } Some(token) => { tracing::debug!("Found payment processor token with least schedule time"); RedisTokenManager::update_payment_processor_token_schedule_time( state, connector_customer_id, &token.token_details.payment_processor_token, Some(token.schedule_time), ) .await .change_context(errors::ProcessTrackerError::EApiErrorResponse)?; Ok(Some(token.schedule_time)) } } } #[cfg(feature = "v2")] pub async fn check_hard_decline( state: &SessionState, payment_attempt: &payment_attempt::PaymentAttempt, ) -> Result<bool, error_stack::Report<storage_impl::errors::RecoveryError>> { let error_message = payment_attempt .error .as_ref() .map(|details| details.message.clone()); let error_code = payment_attempt .error .as_ref() .map(|details| details.code.clone()); let connector_name = payment_attempt .connector .clone() .ok_or(storage_impl::errors::RecoveryError::ValueNotFound) .attach_printable("unable to derive payment connector from payment attempt")?; let gsm_record = payments::helpers::get_gsm_record( state, error_code, error_message, connector_name, REVENUE_RECOVERY.to_string(), ) .await; let is_hard_decline = gsm_record .and_then(|record| record.error_category) .map(|category| category == common_enums::ErrorCategory::HardDecline) .unwrap_or(false); Ok(is_hard_decline) } #[cfg(feature = "v2")] pub fn add_random_delay_to_schedule_time( state: &SessionState, schedule_time: time::PrimitiveDateTime, ) -> time::PrimitiveDateTime { let mut rng = rand::thread_rng(); let delay_limit = state .conf .revenue_recovery .recovery_timestamp .max_random_schedule_delay_in_seconds; let random_secs = rng.gen_range(1..=delay_limit); logger::info!("Adding random delay of {random_secs} seconds to schedule time"); schedule_time + time::Duration::seconds(random_secs) }
crates/router/src/workflows/revenue_recovery.rs
router::src::workflows::revenue_recovery
6,032
true
// File: crates/router/src/workflows/attach_payout_account_workflow.rs // Module: router::src::workflows::attach_payout_account_workflow use common_utils::{ consts::DEFAULT_LOCALE, ext_traits::{OptionExt, ValueExt}, }; use scheduler::{ consumer::{self, workflows::ProcessTrackerWorkflow}, errors, }; use crate::{ core::payouts, errors as core_errors, routes::SessionState, types::{api, domain, storage}, }; pub struct AttachPayoutAccountWorkflow; #[async_trait::async_trait] impl ProcessTrackerWorkflow<SessionState> for AttachPayoutAccountWorkflow { async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { // Gather context let db = &*state.store; let tracking_data: api::PayoutRetrieveRequest = process .tracking_data .clone() .parse_value("PayoutRetrieveRequest")?; let merchant_id = tracking_data .merchant_id .clone() .get_required_value("merchant_id")?; let key_manager_state = &state.into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &db.get_master_key().to_vec().into(), ) .await?; let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await?; let request = api::payouts::PayoutRequest::PayoutRetrieveRequest(tracking_data); let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); let mut payout_data = Box::pin(payouts::make_payout_data( state, &merchant_context, None, &request, DEFAULT_LOCALE, )) .await?; payouts::payouts_core(state, &merchant_context, &mut payout_data, None, None).await?; Ok(()) } async fn error_handler<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, error: errors::ProcessTrackerError, ) -> core_errors::CustomResult<(), errors::ProcessTrackerError> { consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await } }
crates/router/src/workflows/attach_payout_account_workflow.rs
router::src::workflows::attach_payout_account_workflow
541
true
// File: crates/router/src/workflows/payment_method_status_update.rs // Module: router::src::workflows::payment_method_status_update use common_utils::ext_traits::ValueExt; use error_stack::ResultExt; use scheduler::{ consumer::types::process_data, utils as pt_utils, workflows::ProcessTrackerWorkflow, }; use crate::{ errors, logger::error, routes::SessionState, types::storage::{self, PaymentMethodStatusTrackingData}, }; pub struct PaymentMethodStatusUpdateWorkflow; #[async_trait::async_trait] impl ProcessTrackerWorkflow<SessionState> for PaymentMethodStatusUpdateWorkflow { #[cfg(feature = "v1")] async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let db = &*state.store; let tracking_data: PaymentMethodStatusTrackingData = process .tracking_data .clone() .parse_value("PaymentMethodStatusTrackingData")?; let retry_count = process.retry_count; let pm_id = tracking_data.payment_method_id; let prev_pm_status = tracking_data.prev_status; let curr_pm_status = tracking_data.curr_status; let merchant_id = tracking_data.merchant_id; let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &state.store.get_master_key().to_vec().into(), ) .await?; let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await?; let payment_method = db .find_payment_method( &(state.into()), &key_store, &pm_id, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode billing address")?; if payment_method.status != prev_pm_status { return db .as_scheduler() .finish_process_with_business_status(process, "PROCESS_ALREADY_COMPLETED") .await .map_err(Into::<errors::ProcessTrackerError>::into); } let pm_update = storage::PaymentMethodUpdate::StatusUpdate { status: Some(curr_pm_status), }; let res = db .update_payment_method( &(state.into()), &key_store, payment_method, pm_update, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment method"); if let Ok(_pm) = res { db.as_scheduler() .finish_process_with_business_status(process, "COMPLETED_BY_PT") .await?; } else { let mapping = process_data::PaymentMethodsPTMapping::default(); let time_delta = if retry_count == 0 { Some(mapping.default_mapping.start_after) } else { pt_utils::get_delay(retry_count + 1, &mapping.default_mapping.frequencies) }; let schedule_time = pt_utils::get_time_from_delta(time_delta); match schedule_time { Some(s_time) => db .as_scheduler() .retry_process(process, s_time) .await .map_err(Into::<errors::ProcessTrackerError>::into)?, None => db .as_scheduler() .finish_process_with_business_status(process, "RETRIES_EXCEEDED") .await .map_err(Into::<errors::ProcessTrackerError>::into)?, }; }; Ok(()) } #[cfg(feature = "v2")] async fn execute_workflow<'a>( &'a self, _state: &'a SessionState, _process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { todo!() } async fn error_handler<'a>( &'a self, _state: &'a SessionState, process: storage::ProcessTracker, _error: errors::ProcessTrackerError, ) -> errors::CustomResult<(), errors::ProcessTrackerError> { error!(%process.id, "Failed while executing workflow"); Ok(()) } }
crates/router/src/workflows/payment_method_status_update.rs
router::src::workflows::payment_method_status_update
924
true
// File: crates/router/src/workflows/refund_router.rs // Module: router::src::workflows::refund_router use scheduler::consumer::workflows::ProcessTrackerWorkflow; #[cfg(feature = "v1")] use crate::core::refunds as refund_flow; use crate::{errors, logger::error, routes::SessionState, types::storage}; pub struct RefundWorkflowRouter; #[async_trait::async_trait] impl ProcessTrackerWorkflow<SessionState> for RefundWorkflowRouter { #[cfg(feature = "v1")] async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { Ok(Box::pin(refund_flow::start_refund_workflow(state, &process)).await?) } #[cfg(feature = "v2")] async fn execute_workflow<'a>( &'a self, _state: &'a SessionState, _process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { todo!() } async fn error_handler<'a>( &'a self, _state: &'a SessionState, process: storage::ProcessTracker, _error: errors::ProcessTrackerError, ) -> errors::CustomResult<(), errors::ProcessTrackerError> { error!(%process.id, "Failed while executing workflow"); Ok(()) } }
crates/router/src/workflows/refund_router.rs
router::src::workflows::refund_router
307
true
// File: crates/router/src/utils/ext_traits.rs // Module: router::src::utils::ext_traits pub use hyperswitch_domain_models::ext_traits::OptionExt; use crate::core::errors::{self, CustomResult}; pub trait ValidateCall<T, F> { fn validate_opt(self, func: F) -> CustomResult<(), errors::ValidationError>; } impl<T, F> ValidateCall<T, F> for Option<&T> where F: Fn(&T) -> CustomResult<(), errors::ValidationError>, { fn validate_opt(self, func: F) -> CustomResult<(), errors::ValidationError> { match self { Some(val) => func(val), None => Ok(()), } } }
crates/router/src/utils/ext_traits.rs
router::src::utils::ext_traits
152
true
// File: crates/router/src/utils/user.rs // Module: router::src::utils::user use std::sync::Arc; #[cfg(feature = "v1")] use api_models::admin as admin_api; use api_models::user as user_api; #[cfg(feature = "v1")] use common_enums::connector_enums; use common_enums::UserAuthType; #[cfg(feature = "v1")] use common_utils::ext_traits::ValueExt; use common_utils::{ encryption::Encryption, errors::CustomResult, id_type, type_name, types::{keymanager::Identifier, user::LineageContext}, }; use diesel_models::organization::{self, OrganizationBridge}; use error_stack::ResultExt; #[cfg(feature = "v1")] use hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount as DomainMerchantConnectorAccount; #[cfg(feature = "v1")] use masking::PeekInterface; use masking::{ExposeInterface, Secret}; use redis_interface::RedisConnectionPool; use router_env::{env, logger}; #[cfg(feature = "v1")] use crate::types::AdditionalMerchantData; use crate::{ consts::user::{REDIS_SSO_PREFIX, REDIS_SSO_TTL}, core::errors::{StorageError, UserErrors, UserResult}, routes::SessionState, services::{ authentication::{AuthToken, UserFromToken}, authorization::roles::RoleInfo, }, types::{ domain::{self, MerchantAccount, UserFromStorage}, transformers::ForeignFrom, }, }; pub mod dashboard_metadata; pub mod password; #[cfg(feature = "dummy_connector")] pub mod sample_data; pub mod theme; pub mod two_factor_auth; impl UserFromToken { pub async fn get_merchant_account_from_db( &self, state: SessionState, ) -> UserResult<MerchantAccount> { let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &self.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .map_err(|e| { if e.current_context().is_db_not_found() { e.change_context(UserErrors::MerchantIdNotFound) } else { e.change_context(UserErrors::InternalServerError) } })?; let merchant_account = state .store .find_merchant_account_by_merchant_id(key_manager_state, &self.merchant_id, &key_store) .await .map_err(|e| { if e.current_context().is_db_not_found() { e.change_context(UserErrors::MerchantIdNotFound) } else { e.change_context(UserErrors::InternalServerError) } })?; Ok(merchant_account) } pub async fn get_user_from_db(&self, state: &SessionState) -> UserResult<UserFromStorage> { let user = state .global_store .find_user_by_id(&self.user_id) .await .change_context(UserErrors::InternalServerError)?; Ok(user.into()) } pub async fn get_role_info_from_db(&self, state: &SessionState) -> UserResult<RoleInfo> { RoleInfo::from_role_id_org_id_tenant_id( state, &self.role_id, &self.org_id, self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError) } } pub async fn generate_jwt_auth_token_with_attributes( state: &SessionState, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, role_id: String, profile_id: id_type::ProfileId, tenant_id: Option<id_type::TenantId>, ) -> UserResult<Secret<String>> { let token = AuthToken::new_token( user_id, merchant_id, role_id, &state.conf, org_id, profile_id, tenant_id, ) .await?; Ok(Secret::new(token)) } #[allow(unused_variables)] pub fn get_verification_days_left( state: &SessionState, user: &UserFromStorage, ) -> UserResult<Option<i64>> { #[cfg(feature = "email")] return user.get_verification_days_left(state); #[cfg(not(feature = "email"))] return Ok(None); } pub async fn get_user_from_db_by_email( state: &SessionState, email: domain::UserEmail, ) -> CustomResult<UserFromStorage, StorageError> { state .global_store .find_user_by_email(&email) .await .map(UserFromStorage::from) } pub fn get_redis_connection_for_global_tenant( state: &SessionState, ) -> UserResult<Arc<RedisConnectionPool>> { state .global_store .get_redis_conn() .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get redis connection") } impl ForeignFrom<&user_api::AuthConfig> for UserAuthType { fn foreign_from(from: &user_api::AuthConfig) -> Self { match *from { user_api::AuthConfig::OpenIdConnect { .. } => Self::OpenIdConnect, user_api::AuthConfig::Password => Self::Password, user_api::AuthConfig::MagicLink => Self::MagicLink, } } } pub async fn construct_public_and_private_db_configs( state: &SessionState, auth_config: &user_api::AuthConfig, encryption_key: &[u8], id: String, ) -> UserResult<(Option<Encryption>, Option<serde_json::Value>)> { match auth_config { user_api::AuthConfig::OpenIdConnect { private_config, public_config, } => { let private_config_value = serde_json::to_value(private_config.clone()) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to convert auth config to json")?; let encrypted_config = domain::types::crypto_operation::<serde_json::Value, masking::WithType>( &state.into(), type_name!(diesel_models::user::User), domain::types::CryptoOperation::Encrypt(private_config_value.into()), Identifier::UserAuth(id), encryption_key, ) .await .and_then(|val| val.try_into_operation()) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to encrypt auth config")?; Ok(( Some(encrypted_config.into()), Some( serde_json::to_value(public_config.clone()) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to convert auth config to json")?, ), )) } user_api::AuthConfig::Password | user_api::AuthConfig::MagicLink => Ok((None, None)), } } pub fn parse_value<T>(value: serde_json::Value, type_name: &str) -> UserResult<T> where T: serde::de::DeserializeOwned, { serde_json::from_value::<T>(value) .change_context(UserErrors::InternalServerError) .attach_printable(format!("Unable to parse {type_name}")) } pub async fn decrypt_oidc_private_config( state: &SessionState, encrypted_config: Option<Encryption>, id: String, ) -> UserResult<user_api::OpenIdConnectPrivateConfig> { let user_auth_key = hex::decode( state .conf .user_auth_methods .get_inner() .encryption_key .clone() .expose(), ) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to decode DEK")?; let private_config = domain::types::crypto_operation::<serde_json::Value, masking::WithType>( &state.into(), type_name!(diesel_models::user::User), domain::types::CryptoOperation::DecryptOptional(encrypted_config), Identifier::UserAuth(id), &user_auth_key, ) .await .and_then(|val| val.try_into_optionaloperation()) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to decrypt private config")? .ok_or(UserErrors::InternalServerError) .attach_printable("Private config not found")? .into_inner() .expose(); serde_json::from_value::<user_api::OpenIdConnectPrivateConfig>(private_config) .change_context(UserErrors::InternalServerError) .attach_printable("unable to parse OpenIdConnectPrivateConfig") } pub async fn set_sso_id_in_redis( state: &SessionState, oidc_state: Secret<String>, sso_id: String, ) -> UserResult<()> { let connection = get_redis_connection_for_global_tenant(state)?; let key = get_oidc_key(&oidc_state.expose()); connection .set_key_with_expiry(&key.into(), sso_id, REDIS_SSO_TTL) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to set sso id in redis") } pub async fn get_sso_id_from_redis( state: &SessionState, oidc_state: Secret<String>, ) -> UserResult<String> { let connection = get_redis_connection_for_global_tenant(state)?; let key = get_oidc_key(&oidc_state.expose()); connection .get_key::<Option<String>>(&key.into()) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get sso id from redis")? .ok_or(UserErrors::SSOFailed) .attach_printable("Cannot find oidc state in redis. Oidc state invalid or expired") } fn get_oidc_key(oidc_state: &str) -> String { format!("{REDIS_SSO_PREFIX}{oidc_state}") } pub fn get_oidc_sso_redirect_url(state: &SessionState, provider: &str) -> String { format!("{}/redirect/oidc/{}", state.conf.user.base_url, provider) } pub fn is_sso_auth_type(auth_type: UserAuthType) -> bool { match auth_type { UserAuthType::OpenIdConnect => true, UserAuthType::Password | UserAuthType::MagicLink => false, } } #[cfg(feature = "v1")] pub fn create_merchant_account_request_for_org( req: user_api::UserOrgMerchantCreateRequest, org: organization::Organization, product_type: common_enums::MerchantProductType, ) -> UserResult<api_models::admin::MerchantAccountCreate> { let merchant_id = generate_env_specific_merchant_id(req.merchant_name.clone().expose())?; let company_name = domain::UserCompanyName::new(req.merchant_name.expose())?; Ok(api_models::admin::MerchantAccountCreate { merchant_id, metadata: None, locker_id: None, return_url: None, merchant_name: Some(Secret::new(company_name.get_secret())), webhook_details: None, publishable_key: None, organization_id: Some(org.get_organization_id()), merchant_details: None, routing_algorithm: None, parent_merchant_id: None, sub_merchants_enabled: None, frm_routing_algorithm: None, #[cfg(feature = "payouts")] payout_routing_algorithm: None, primary_business_details: None, payment_response_hash_key: None, enable_payment_response_hash: None, redirect_to_merchant_with_http_post: None, pm_collect_link_config: None, product_type: Some(product_type), merchant_account_type: None, }) } pub async fn validate_email_domain_auth_type_using_db( state: &SessionState, email: &domain::UserEmail, required_auth_type: UserAuthType, ) -> UserResult<()> { let domain = email.extract_domain()?; let user_auth_methods = state .store .list_user_authentication_methods_for_email_domain(domain) .await .change_context(UserErrors::InternalServerError)?; (user_auth_methods.is_empty() || user_auth_methods .iter() .any(|auth_method| auth_method.auth_type == required_auth_type)) .then_some(()) .ok_or(UserErrors::InvalidUserAuthMethodOperation.into()) } pub fn spawn_async_lineage_context_update_to_db( state: &SessionState, user_id: &str, lineage_context: LineageContext, ) { let state = state.clone(); let lineage_context = lineage_context.clone(); let user_id = user_id.to_owned(); tokio::spawn(async move { match state .global_store .update_user_by_user_id( &user_id, diesel_models::user::UserUpdate::LineageContextUpdate { lineage_context }, ) .await { Ok(_) => { logger::debug!("Successfully updated lineage context for user {}", user_id); } Err(e) => { logger::error!( "Failed to update lineage context for user {}: {:?}", user_id, e ); } } }); } pub fn generate_env_specific_merchant_id(value: String) -> UserResult<id_type::MerchantId> { if matches!(env::which(), env::Env::Production) { let raw_id = domain::MerchantId::new(value)?; Ok(id_type::MerchantId::try_from(raw_id)?) } else { Ok(id_type::MerchantId::new_from_unix_timestamp()) } } pub fn get_base_url(state: &SessionState) -> &str { if !state.conf.multitenancy.enabled { &state.conf.user.base_url } else { &state.tenant.user.control_center_url } } #[cfg(feature = "v1")] pub async fn build_cloned_connector_create_request( source_mca: DomainMerchantConnectorAccount, destination_profile_id: Option<id_type::ProfileId>, destination_connector_label: Option<String>, ) -> UserResult<admin_api::MerchantConnectorCreate> { let source_mca_name = source_mca .connector_name .parse::<connector_enums::Connector>() .change_context(UserErrors::InternalServerError) .attach_printable("Invalid connector name received")?; let payment_methods_enabled = source_mca .payment_methods_enabled .clone() .map(|data| { let val = data.into_iter().map(|secret| secret.expose()).collect(); serde_json::Value::Array(val) .parse_value("PaymentMethods") .change_context(UserErrors::InternalServerError) .attach_printable("Unable to deserialize PaymentMethods") }) .transpose()?; let frm_configs = source_mca .frm_configs .as_ref() .map(|configs_vec| { configs_vec .iter() .map(|config_secret| { config_secret .peek() .clone() .parse_value("FrmConfigs") .change_context(UserErrors::InternalServerError) .attach_printable("Unable to deserialize FrmConfigs") }) .collect::<Result<Vec<_>, _>>() }) .transpose()?; let connector_webhook_details = source_mca .connector_webhook_details .map(|webhook_details| { serde_json::Value::parse_value( webhook_details.expose(), "MerchantConnectorWebhookDetails", ) .change_context(UserErrors::InternalServerError) .attach_printable("Unable to deserialize connector_webhook_details") }) .transpose()?; let connector_wallets_details = source_mca .connector_wallets_details .map(|secret_value| { secret_value .into_inner() .expose() .parse_value::<admin_api::ConnectorWalletDetails>("ConnectorWalletDetails") .change_context(UserErrors::InternalServerError) .attach_printable("Unable to parse ConnectorWalletDetails from Value") }) .transpose()?; let additional_merchant_data = source_mca .additional_merchant_data .map(|secret_value| { secret_value .into_inner() .expose() .parse_value::<AdditionalMerchantData>("AdditionalMerchantData") .change_context(UserErrors::InternalServerError) .attach_printable("Unable to parse AdditionalMerchantData from Value") }) .transpose()? .map(admin_api::AdditionalMerchantData::foreign_from); Ok(admin_api::MerchantConnectorCreate { connector_type: source_mca.connector_type, connector_name: source_mca_name, connector_label: destination_connector_label.or(source_mca.connector_label.clone()), merchant_connector_id: None, connector_account_details: Some(source_mca.connector_account_details.clone().into_inner()), test_mode: source_mca.test_mode, disabled: source_mca.disabled, payment_methods_enabled, metadata: source_mca.metadata, business_country: source_mca.business_country, business_label: source_mca.business_label.clone(), business_sub_label: source_mca.business_sub_label.clone(), frm_configs, connector_webhook_details, profile_id: destination_profile_id, pm_auth_config: source_mca.pm_auth_config.clone(), connector_wallets_details, status: Some(source_mca.status), additional_merchant_data, }) }
crates/router/src/utils/user.rs
router::src::utils::user
3,734
true
// File: crates/router/src/utils/user_role.rs // Module: router::src::utils::user_role use std::{ cmp, collections::{HashMap, HashSet}, }; use api_models::user_role::role as role_api; use common_enums::{EntityType, ParentGroup, PermissionGroup}; use common_utils::id_type; use diesel_models::{ enums::{UserRoleVersion, UserStatus}, role::ListRolesByEntityPayload, user_role::{UserRole, UserRoleUpdate}, }; use error_stack::{report, Report, ResultExt}; use router_env::logger; use storage_impl::errors::StorageError; use strum::IntoEnumIterator; use crate::{ consts, core::errors::{UserErrors, UserResult}, db::{ errors::StorageErrorExt, user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload}, }, routes::SessionState, services::authorization::{ self as authz, permission_groups::{ParentGroupExt, PermissionGroupExt}, permissions, roles, }, types::domain, }; pub fn validate_role_groups(groups: &[PermissionGroup]) -> UserResult<()> { if groups.is_empty() { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("Role groups cannot be empty"); } let unique_groups: HashSet<_> = groups.iter().copied().collect(); if unique_groups.contains(&PermissionGroup::InternalManage) { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("Invalid groups present in the custom role"); } if unique_groups.len() != groups.len() { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("Duplicate permission group found"); } Ok(()) } pub async fn validate_role_name( state: &SessionState, role_name: &domain::RoleName, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, profile_id: &id_type::ProfileId, entity_type: &EntityType, ) -> UserResult<()> { let role_name_str = role_name.clone().get_role_name(); let is_present_in_predefined_roles = roles::predefined_roles::PREDEFINED_ROLES .iter() .any(|(_, role_info)| role_info.get_role_name() == role_name_str); let entity_type_for_role = match entity_type { EntityType::Tenant | EntityType::Organization => ListRolesByEntityPayload::Organization, EntityType::Merchant => ListRolesByEntityPayload::Merchant(merchant_id.to_owned()), EntityType::Profile => { ListRolesByEntityPayload::Profile(merchant_id.to_owned(), profile_id.to_owned()) } }; let is_present_in_custom_role = match state .global_store .generic_list_roles_by_entity_type( entity_type_for_role, false, tenant_id.to_owned(), org_id.to_owned(), ) .await { Ok(roles_list) => roles_list .iter() .any(|role| role.role_name == role_name_str), Err(e) => { if e.current_context().is_db_not_found() { false } else { return Err(UserErrors::InternalServerError.into()); } } }; if is_present_in_predefined_roles || is_present_in_custom_role { return Err(UserErrors::RoleNameAlreadyExists.into()); } Ok(()) } pub async fn set_role_info_in_cache_by_user_role( state: &SessionState, user_role: &UserRole, ) -> bool { let Some(ref org_id) = user_role.org_id else { return false; }; set_role_info_in_cache_if_required( state, user_role.role_id.as_str(), org_id, &user_role.tenant_id, ) .await .map_err(|e| logger::error!("Error setting permissions in cache {:?}", e)) .is_ok() } pub async fn set_role_info_in_cache_by_role_id_org_id( state: &SessionState, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> bool { set_role_info_in_cache_if_required(state, role_id, org_id, tenant_id) .await .map_err(|e| logger::error!("Error setting permissions in cache {:?}", e)) .is_ok() } pub async fn set_role_info_in_cache_if_required( state: &SessionState, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> UserResult<()> { if roles::predefined_roles::PREDEFINED_ROLES.contains_key(role_id) { return Ok(()); } let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(state, role_id, org_id, tenant_id) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error getting role_info from role_id")?; authz::set_role_info_in_cache( state, role_id, &role_info, i64::try_from(consts::JWT_TOKEN_TIME_IN_SECS) .change_context(UserErrors::InternalServerError)?, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error setting permissions in redis") } pub async fn update_v1_and_v2_user_roles_in_db( state: &SessionState, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, update: UserRoleUpdate, ) -> ( Result<UserRole, Report<StorageError>>, Result<UserRole, Report<StorageError>>, ) { let updated_v1_role = state .global_store .update_user_role_by_user_id_and_lineage( user_id, tenant_id, org_id, merchant_id, profile_id, update.clone(), UserRoleVersion::V1, ) .await .map_err(|e| { logger::error!("Error updating user_role {e:?}"); e }); let updated_v2_role = state .global_store .update_user_role_by_user_id_and_lineage( user_id, tenant_id, org_id, merchant_id, profile_id, update, UserRoleVersion::V2, ) .await .map_err(|e| { logger::error!("Error updating user_role {e:?}"); e }); (updated_v1_role, updated_v2_role) } pub async fn get_single_org_id( state: &SessionState, user_role: &UserRole, ) -> UserResult<id_type::OrganizationId> { let (_, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; match entity_type { EntityType::Tenant => Ok(state .store .list_merchant_and_org_ids(&state.into(), 1, None) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get merchants list for org")? .pop() .ok_or(UserErrors::InternalServerError) .attach_printable("No merchants to get merchant or org id")? .1), EntityType::Organization | EntityType::Merchant | EntityType::Profile => user_role .org_id .clone() .ok_or(UserErrors::InternalServerError) .attach_printable("Org_id not found"), } } pub async fn get_single_merchant_id( state: &SessionState, user_role: &UserRole, org_id: &id_type::OrganizationId, ) -> UserResult<id_type::MerchantId> { let (_, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; match entity_type { EntityType::Tenant | EntityType::Organization => Ok(state .store .list_merchant_accounts_by_organization_id(&state.into(), org_id) .await .to_not_found_response(UserErrors::InvalidRoleOperationWithMessage( "Invalid Org Id".to_string(), ))? .first() .ok_or(UserErrors::InternalServerError) .attach_printable("No merchants found for org_id")? .get_id() .clone()), EntityType::Merchant | EntityType::Profile => user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError) .attach_printable("merchant_id not found"), } } pub async fn get_single_profile_id( state: &SessionState, user_role: &UserRole, merchant_id: &id_type::MerchantId, ) -> UserResult<id_type::ProfileId> { let (_, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; match entity_type { EntityType::Tenant | EntityType::Organization | EntityType::Merchant => { let key_store = state .store .get_merchant_key_store_by_merchant_id( &state.into(), merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .change_context(UserErrors::InternalServerError)?; Ok(state .store .list_profile_by_merchant_id(&state.into(), &key_store, merchant_id) .await .change_context(UserErrors::InternalServerError)? .pop() .ok_or(UserErrors::InternalServerError)? .get_id() .to_owned()) } EntityType::Profile => user_role .profile_id .clone() .ok_or(UserErrors::InternalServerError) .attach_printable("profile_id not found"), } } pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite( state: &SessionState, user_id: &str, tenant_id: &id_type::TenantId, entity_id: String, entity_type: EntityType, ) -> UserResult< Option<( id_type::OrganizationId, Option<id_type::MerchantId>, Option<id_type::ProfileId>, )>, > { match entity_type { EntityType::Tenant => Err(UserErrors::InvalidRoleOperationWithMessage( "Tenant roles are not allowed for this operation".to_string(), ) .into()), EntityType::Organization => { let Ok(org_id) = id_type::OrganizationId::try_from(std::borrow::Cow::from(entity_id.clone())) else { return Ok(None); }; let user_roles = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id, tenant_id, org_id: Some(&org_id), merchant_id: None, profile_id: None, entity_id: None, version: None, status: Some(UserStatus::InvitationSent), limit: None, }) .await .change_context(UserErrors::InternalServerError)? .into_iter() .collect::<HashSet<_>>(); if user_roles.len() > 1 { return Ok(None); } if let Some(user_role) = user_roles.into_iter().next() { let (_entity_id, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; if entity_type != EntityType::Organization { return Ok(None); } return Ok(Some(( user_role.org_id.ok_or(UserErrors::InternalServerError)?, None, None, ))); } Ok(None) } EntityType::Merchant => { let Ok(merchant_id) = id_type::MerchantId::wrap(entity_id) else { return Ok(None); }; let user_roles = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id, tenant_id, org_id: None, merchant_id: Some(&merchant_id), profile_id: None, entity_id: None, version: None, status: Some(UserStatus::InvitationSent), limit: None, }) .await .change_context(UserErrors::InternalServerError)? .into_iter() .collect::<HashSet<_>>(); if user_roles.len() > 1 { return Ok(None); } if let Some(user_role) = user_roles.into_iter().next() { let (_entity_id, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; if entity_type != EntityType::Merchant { return Ok(None); } return Ok(Some(( user_role.org_id.ok_or(UserErrors::InternalServerError)?, Some(merchant_id), None, ))); } Ok(None) } EntityType::Profile => { let Ok(profile_id) = id_type::ProfileId::try_from(std::borrow::Cow::from(entity_id)) else { return Ok(None); }; let user_roles = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id, tenant_id: &state.tenant.tenant_id, org_id: None, merchant_id: None, profile_id: Some(&profile_id), entity_id: None, version: None, status: Some(UserStatus::InvitationSent), limit: None, }) .await .change_context(UserErrors::InternalServerError)? .into_iter() .collect::<HashSet<_>>(); if user_roles.len() > 1 { return Ok(None); } if let Some(user_role) = user_roles.into_iter().next() { let (_entity_id, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; if entity_type != EntityType::Profile { return Ok(None); } return Ok(Some(( user_role.org_id.ok_or(UserErrors::InternalServerError)?, Some( user_role .merchant_id .ok_or(UserErrors::InternalServerError)?, ), Some(profile_id), ))); } Ok(None) } } } pub async fn get_single_merchant_id_and_profile_id( state: &SessionState, user_role: &UserRole, ) -> UserResult<(id_type::MerchantId, id_type::ProfileId)> { let org_id = get_single_org_id(state, user_role).await?; let merchant_id = get_single_merchant_id(state, user_role, &org_id).await?; let profile_id = get_single_profile_id(state, user_role, &merchant_id).await?; Ok((merchant_id, profile_id)) } pub async fn fetch_user_roles_by_payload( state: &SessionState, payload: ListUserRolesByOrgIdPayload<'_>, request_entity_type: Option<EntityType>, ) -> UserResult<HashSet<UserRole>> { Ok(state .global_store .list_user_roles_by_org_id(payload) .await .change_context(UserErrors::InternalServerError)? .into_iter() .filter_map(|user_role| { let (_entity_id, entity_type) = user_role.get_entity_id_and_type()?; request_entity_type .is_none_or(|req_entity_type| entity_type == req_entity_type) .then_some(user_role) }) .collect::<HashSet<_>>()) } pub fn get_min_entity( user_entity: EntityType, filter_entity: Option<EntityType>, ) -> UserResult<EntityType> { let Some(filter_entity) = filter_entity else { return Ok(user_entity); }; if user_entity < filter_entity { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "{user_entity} level user requesting data for {filter_entity:?} level", )); } Ok(cmp::min(user_entity, filter_entity)) } pub fn parent_group_info_request_to_permission_groups( parent_groups: &[role_api::ParentGroupInfoRequest], ) -> Result<Vec<PermissionGroup>, UserErrors> { parent_groups .iter() .try_fold(Vec::new(), |mut permission_groups, parent_group| { let scopes = &parent_group.scopes; if scopes.is_empty() { return Err(UserErrors::InvalidRoleOperation); } let available_scopes = parent_group.name.get_available_scopes(); if !scopes.iter().all(|scope| available_scopes.contains(scope)) { return Err(UserErrors::InvalidRoleOperation); } let groups = PermissionGroup::iter() .filter(|group| { group.parent() == parent_group.name && scopes.contains(&group.scope()) }) .collect::<Vec<_>>(); permission_groups.extend(groups); Ok(permission_groups) }) } pub fn permission_groups_to_parent_group_info( permission_groups: &[PermissionGroup], entity_type: EntityType, ) -> Vec<role_api::ParentGroupInfo> { let parent_groups_map: HashMap<ParentGroup, Vec<common_enums::PermissionScope>> = permission_groups .iter() .fold(HashMap::new(), |mut acc, group| { let parent = group.parent(); let scope = group.scope(); acc.entry(parent).or_default().push(scope); acc }); parent_groups_map .into_iter() .filter_map(|(name, scopes)| { let unique_scopes = scopes .into_iter() .collect::<HashSet<_>>() .into_iter() .collect(); let filtered_resources = permissions::filter_resources_by_entity_type(name.resources(), entity_type)?; Some(role_api::ParentGroupInfo { name, resources: filtered_resources, scopes: unique_scopes, }) }) .collect() } pub fn resources_to_description( resources: Vec<common_enums::Resource>, entity_type: EntityType, ) -> Option<String> { if resources.is_empty() { return None; } let filtered_resources = permissions::filter_resources_by_entity_type(resources, entity_type)?; let description = filtered_resources .iter() .map(|res| permissions::get_resource_name(*res, entity_type)) .collect::<Option<Vec<_>>>()? .join(", "); Some(description) }
crates/router/src/utils/user_role.rs
router::src::utils::user_role
3,976
true
// File: crates/router/src/utils/verify_connector.rs // Module: router::src::utils::verify_connector use api_models::enums::Connector; use error_stack::ResultExt; use crate::{core::errors, types::domain}; pub fn generate_card_from_details( card_number: String, card_exp_year: String, card_exp_month: String, card_cvv: String, ) -> errors::RouterResult<domain::Card> { Ok(domain::Card { card_number: card_number .parse::<cards::CardNumber>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing card number")?, card_issuer: None, card_cvc: masking::Secret::new(card_cvv), card_network: None, card_exp_year: masking::Secret::new(card_exp_year), card_exp_month: masking::Secret::new(card_exp_month), nick_name: None, card_type: None, card_issuing_country: None, bank_code: None, card_holder_name: None, co_badged_card_data: None, }) } pub fn get_test_card_details( connector_name: Connector, ) -> errors::RouterResult<Option<domain::Card>> { match connector_name { Connector::Stripe => Some(generate_card_from_details( "4242424242424242".to_string(), "2025".to_string(), "12".to_string(), "100".to_string(), )) .transpose(), Connector::Paypal => Some(generate_card_from_details( "4111111111111111".to_string(), "2025".to_string(), "02".to_string(), "123".to_string(), )) .transpose(), _ => Ok(None), } }
crates/router/src/utils/verify_connector.rs
router::src::utils::verify_connector
418
true
// File: crates/router/src/utils/storage_partitioning.rs // Module: router::src::utils::storage_partitioning pub use storage_impl::redis::kv_store::{KvStorePartition, PartitionKey};
crates/router/src/utils/storage_partitioning.rs
router::src::utils::storage_partitioning
43
true
// File: crates/router/src/utils/currency.rs // Module: router::src::utils::currency use std::{ collections::HashMap, ops::Deref, str::FromStr, sync::{Arc, LazyLock}, }; use api_models::enums; use common_utils::{date_time, errors::CustomResult, events::ApiEventMetric, ext_traits::AsyncExt}; use currency_conversion::types::{CurrencyFactors, ExchangeRates}; use error_stack::ResultExt; use masking::PeekInterface; use redis_interface::DelReply; use router_env::{instrument, tracing}; use rust_decimal::Decimal; use strum::IntoEnumIterator; use tokio::sync::RwLock; use tracing_futures::Instrument; use crate::{ logger, routes::app::settings::{Conversion, DefaultExchangeRates}, services, SessionState, }; const REDIX_FOREX_CACHE_KEY: &str = "{forex_cache}_lock"; const REDIX_FOREX_CACHE_DATA: &str = "{forex_cache}_data"; const FOREX_API_TIMEOUT: u64 = 5; const FOREX_BASE_URL: &str = "https://openexchangerates.org/api/latest.json?app_id="; const FOREX_BASE_CURRENCY: &str = "&base=USD"; const FALLBACK_FOREX_BASE_URL: &str = "http://apilayer.net/api/live?access_key="; const FALLBACK_FOREX_API_CURRENCY_PREFIX: &str = "USD"; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct FxExchangeRatesCacheEntry { pub data: Arc<ExchangeRates>, timestamp: i64, } static FX_EXCHANGE_RATES_CACHE: LazyLock<RwLock<Option<FxExchangeRatesCacheEntry>>> = LazyLock::new(|| RwLock::new(None)); impl ApiEventMetric for FxExchangeRatesCacheEntry {} #[derive(Debug, Clone, thiserror::Error)] pub enum ForexError { #[error("API error")] ApiError, #[error("API timeout")] ApiTimeout, #[error("API unresponsive")] ApiUnresponsive, #[error("Conversion error")] ConversionError, #[error("Could not acquire the lock for cache entry")] CouldNotAcquireLock, #[error("Provided currency not acceptable")] CurrencyNotAcceptable, #[error("Forex configuration error: {0}")] ConfigurationError(String), #[error("Incorrect entries in default Currency response")] DefaultCurrencyParsingError, #[error("Entry not found in cache")] EntryNotFound, #[error("Forex data unavailable")] ForexDataUnavailable, #[error("Expiration time invalid")] InvalidLogExpiry, #[error("Error reading local")] LocalReadError, #[error("Error writing to local cache")] LocalWriteError, #[error("Json Parsing error")] ParsingError, #[error("Aws Kms decryption error")] AwsKmsDecryptionFailed, #[error("Error connecting to redis")] RedisConnectionError, #[error("Not able to release write lock")] RedisLockReleaseFailed, #[error("Error writing to redis")] RedisWriteError, #[error("Not able to acquire write lock")] WriteLockNotAcquired, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] struct ForexResponse { pub rates: HashMap<String, FloatDecimal>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] struct FallbackForexResponse { pub quotes: HashMap<String, FloatDecimal>, } #[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize)] #[serde(transparent)] struct FloatDecimal(#[serde(with = "rust_decimal::serde::float")] Decimal); impl Deref for FloatDecimal { type Target = Decimal; fn deref(&self) -> &Self::Target { &self.0 } } impl FxExchangeRatesCacheEntry { fn new(exchange_rate: ExchangeRates) -> Self { Self { data: Arc::new(exchange_rate), timestamp: date_time::now_unix_timestamp(), } } fn is_expired(&self, data_expiration_delay: u32) -> bool { self.timestamp + i64::from(data_expiration_delay) < date_time::now_unix_timestamp() } } async fn retrieve_forex_from_local_cache() -> Option<FxExchangeRatesCacheEntry> { FX_EXCHANGE_RATES_CACHE.read().await.clone() } async fn save_forex_data_to_local_cache( exchange_rates_cache_entry: FxExchangeRatesCacheEntry, ) -> CustomResult<(), ForexError> { let mut local = FX_EXCHANGE_RATES_CACHE.write().await; *local = Some(exchange_rates_cache_entry); logger::debug!("forex_log: forex saved in cache"); Ok(()) } impl TryFrom<DefaultExchangeRates> for ExchangeRates { type Error = error_stack::Report<ForexError>; fn try_from(value: DefaultExchangeRates) -> Result<Self, Self::Error> { let mut conversion_usable: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); for (curr, conversion) in value.conversion { let enum_curr = enums::Currency::from_str(curr.as_str()) .change_context(ForexError::ConversionError) .attach_printable("Unable to Convert currency received")?; conversion_usable.insert(enum_curr, CurrencyFactors::from(conversion)); } let base_curr = enums::Currency::from_str(value.base_currency.as_str()) .change_context(ForexError::ConversionError) .attach_printable("Unable to convert base currency")?; Ok(Self { base_currency: base_curr, conversion: conversion_usable, }) } } impl From<Conversion> for CurrencyFactors { fn from(value: Conversion) -> Self { Self { to_factor: value.to_factor, from_factor: value.from_factor, } } } #[instrument(skip_all)] pub async fn get_forex_rates( state: &SessionState, data_expiration_delay: u32, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { if let Some(local_rates) = retrieve_forex_from_local_cache().await { if local_rates.is_expired(data_expiration_delay) { // expired local data logger::debug!("forex_log: Forex stored in cache is expired"); call_forex_api_and_save_data_to_cache_and_redis(state, Some(local_rates)).await } else { // Valid data present in local logger::debug!("forex_log: forex found in cache"); Ok(local_rates) } } else { // No data in local call_api_if_redis_forex_data_expired(state, data_expiration_delay).await } } async fn call_api_if_redis_forex_data_expired( state: &SessionState, data_expiration_delay: u32, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { match retrieve_forex_data_from_redis(state).await { Ok(Some(data)) => { call_forex_api_if_redis_data_expired(state, data, data_expiration_delay).await } Ok(None) => { // No data in local as well as redis call_forex_api_and_save_data_to_cache_and_redis(state, None).await?; Err(ForexError::ForexDataUnavailable.into()) } Err(error) => { // Error in deriving forex rates from redis logger::error!("forex_error: {:?}", error); call_forex_api_and_save_data_to_cache_and_redis(state, None).await?; Err(ForexError::ForexDataUnavailable.into()) } } } async fn call_forex_api_and_save_data_to_cache_and_redis( state: &SessionState, stale_redis_data: Option<FxExchangeRatesCacheEntry>, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { // spawn a new thread and do the api fetch and write operations on redis. let forex_api_key = state.conf.forex_api.get_inner().api_key.peek(); if forex_api_key.is_empty() { Err(ForexError::ConfigurationError("api_keys not provided".into()).into()) } else { let state = state.clone(); tokio::spawn( async move { acquire_redis_lock_and_call_forex_api(&state) .await .map_err(|err| { logger::error!(forex_error=?err); }) .ok(); } .in_current_span(), ); stale_redis_data.ok_or(ForexError::EntryNotFound.into()) } } async fn acquire_redis_lock_and_call_forex_api( state: &SessionState, ) -> CustomResult<(), ForexError> { let lock_acquired = acquire_redis_lock(state).await?; if !lock_acquired { Err(ForexError::CouldNotAcquireLock.into()) } else { logger::debug!("forex_log: redis lock acquired"); let api_rates = fetch_forex_rates_from_primary_api(state).await; match api_rates { Ok(rates) => save_forex_data_to_cache_and_redis(state, rates).await, Err(error) => { logger::error!(forex_error=?error,"primary_forex_error"); // API not able to fetch data call secondary service let secondary_api_rates = fetch_forex_rates_from_fallback_api(state).await; match secondary_api_rates { Ok(rates) => save_forex_data_to_cache_and_redis(state, rates).await, Err(error) => { release_redis_lock(state).await?; Err(error) } } } } } } async fn save_forex_data_to_cache_and_redis( state: &SessionState, forex: FxExchangeRatesCacheEntry, ) -> CustomResult<(), ForexError> { save_forex_data_to_redis(state, &forex) .await .async_and_then(|_rates| release_redis_lock(state)) .await .async_and_then(|_val| save_forex_data_to_local_cache(forex.clone())) .await } async fn call_forex_api_if_redis_data_expired( state: &SessionState, redis_data: FxExchangeRatesCacheEntry, data_expiration_delay: u32, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { match is_redis_expired(Some(redis_data.clone()).as_ref(), data_expiration_delay).await { Some(redis_forex) => { // Valid data present in redis let exchange_rates = FxExchangeRatesCacheEntry::new(redis_forex.as_ref().clone()); logger::debug!("forex_log: forex response found in redis"); save_forex_data_to_local_cache(exchange_rates.clone()).await?; Ok(exchange_rates) } None => { // redis expired call_forex_api_and_save_data_to_cache_and_redis(state, Some(redis_data)).await } } } async fn fetch_forex_rates_from_primary_api( state: &SessionState, ) -> Result<FxExchangeRatesCacheEntry, error_stack::Report<ForexError>> { let forex_api_key = state.conf.forex_api.get_inner().api_key.peek(); logger::debug!("forex_log: Primary api call for forex fetch"); let forex_url: String = format!("{FOREX_BASE_URL}{forex_api_key}{FOREX_BASE_CURRENCY}"); let forex_request = services::RequestBuilder::new() .method(services::Method::Get) .url(&forex_url) .build(); logger::info!(primary_forex_request=?forex_request,"forex_log: Primary api call for forex fetch"); let response = state .api_client .send_request( &state.clone(), forex_request, Some(FOREX_API_TIMEOUT), false, ) .await .change_context(ForexError::ApiUnresponsive) .attach_printable("Primary forex fetch api unresponsive")?; let forex_response = response .json::<ForexResponse>() .await .change_context(ForexError::ParsingError) .attach_printable( "Unable to parse response received from primary api into ForexResponse", )?; logger::info!(primary_forex_response=?forex_response,"forex_log"); let mut conversions: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); for enum_curr in enums::Currency::iter() { match forex_response.rates.get(&enum_curr.to_string()) { Some(rate) => { let from_factor = match Decimal::new(1, 0).checked_div(**rate) { Some(rate) => rate, None => { logger::error!( "forex_error: Rates for {} not received from API", &enum_curr ); continue; } }; let currency_factors = CurrencyFactors::new(**rate, from_factor); conversions.insert(enum_curr, currency_factors); } None => { logger::error!( "forex_error: Rates for {} not received from API", &enum_curr ); } }; } Ok(FxExchangeRatesCacheEntry::new(ExchangeRates::new( enums::Currency::USD, conversions, ))) } pub async fn fetch_forex_rates_from_fallback_api( state: &SessionState, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { let fallback_forex_api_key = state.conf.forex_api.get_inner().fallback_api_key.peek(); let fallback_forex_url: String = format!("{FALLBACK_FOREX_BASE_URL}{fallback_forex_api_key}"); let fallback_forex_request = services::RequestBuilder::new() .method(services::Method::Get) .url(&fallback_forex_url) .build(); logger::info!(fallback_forex_request=?fallback_forex_request,"forex_log: Fallback api call for forex fetch"); let response = state .api_client .send_request( &state.clone(), fallback_forex_request, Some(FOREX_API_TIMEOUT), false, ) .await .change_context(ForexError::ApiUnresponsive) .attach_printable("Fallback forex fetch api unresponsive")?; let fallback_forex_response = response .json::<FallbackForexResponse>() .await .change_context(ForexError::ParsingError) .attach_printable( "Unable to parse response received from fallback api into ForexResponse", )?; logger::info!(fallback_forex_response=?fallback_forex_response,"forex_log"); let mut conversions: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); for enum_curr in enums::Currency::iter() { match fallback_forex_response.quotes.get( format!( "{}{}", FALLBACK_FOREX_API_CURRENCY_PREFIX, &enum_curr.to_string() ) .as_str(), ) { Some(rate) => { let from_factor = match Decimal::new(1, 0).checked_div(**rate) { Some(rate) => rate, None => { logger::error!( "forex_error: Rates for {} not received from API", &enum_curr ); continue; } }; let currency_factors = CurrencyFactors::new(**rate, from_factor); conversions.insert(enum_curr, currency_factors); } None => { if enum_curr == enums::Currency::USD { let currency_factors = CurrencyFactors::new(Decimal::new(1, 0), Decimal::new(1, 0)); conversions.insert(enum_curr, currency_factors); } else { logger::error!( "forex_error: Rates for {} not received from API", &enum_curr ); } } }; } let rates = FxExchangeRatesCacheEntry::new(ExchangeRates::new(enums::Currency::USD, conversions)); match acquire_redis_lock(state).await { Ok(_) => { save_forex_data_to_cache_and_redis(state, rates.clone()).await?; Ok(rates) } Err(e) => Err(e), } } async fn release_redis_lock( state: &SessionState, ) -> Result<DelReply, error_stack::Report<ForexError>> { logger::debug!("forex_log: Releasing redis lock"); state .store .get_redis_conn() .change_context(ForexError::RedisConnectionError)? .delete_key(&REDIX_FOREX_CACHE_KEY.into()) .await .change_context(ForexError::RedisLockReleaseFailed) .attach_printable("Unable to release redis lock") } async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexError> { let forex_api = state.conf.forex_api.get_inner(); logger::debug!("forex_log: Acquiring redis lock"); state .store .get_redis_conn() .change_context(ForexError::RedisConnectionError)? .set_key_if_not_exists_with_expiry( &REDIX_FOREX_CACHE_KEY.into(), "", Some(i64::from(forex_api.redis_lock_timeout_in_seconds)), ) .await .map(|val| matches!(val, redis_interface::SetnxReply::KeySet)) .change_context(ForexError::CouldNotAcquireLock) .attach_printable("Unable to acquire redis lock") } async fn save_forex_data_to_redis( app_state: &SessionState, forex_exchange_cache_entry: &FxExchangeRatesCacheEntry, ) -> CustomResult<(), ForexError> { let forex_api = app_state.conf.forex_api.get_inner(); logger::debug!("forex_log: Saving forex to redis"); app_state .store .get_redis_conn() .change_context(ForexError::RedisConnectionError)? .serialize_and_set_key_with_expiry( &REDIX_FOREX_CACHE_DATA.into(), forex_exchange_cache_entry, i64::from(forex_api.redis_ttl_in_seconds), ) .await .change_context(ForexError::RedisWriteError) .attach_printable("Unable to save forex data to redis") } async fn retrieve_forex_data_from_redis( app_state: &SessionState, ) -> CustomResult<Option<FxExchangeRatesCacheEntry>, ForexError> { logger::debug!("forex_log: Retrieving forex from redis"); app_state .store .get_redis_conn() .change_context(ForexError::RedisConnectionError)? .get_and_deserialize_key(&REDIX_FOREX_CACHE_DATA.into(), "FxExchangeRatesCache") .await .change_context(ForexError::EntryNotFound) .attach_printable("Forex entry not found in redis") } async fn is_redis_expired( redis_cache: Option<&FxExchangeRatesCacheEntry>, data_expiration_delay: u32, ) -> Option<Arc<ExchangeRates>> { redis_cache.and_then(|cache| { if cache.timestamp + i64::from(data_expiration_delay) > date_time::now_unix_timestamp() { Some(cache.data.clone()) } else { logger::debug!("forex_log: Forex stored in redis is expired"); None } }) } #[instrument(skip_all)] pub async fn convert_currency( state: SessionState, amount: i64, to_currency: String, from_currency: String, ) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexError> { let forex_api = state.conf.forex_api.get_inner(); let rates = get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds) .await .change_context(ForexError::ApiError)?; let to_currency = enums::Currency::from_str(to_currency.as_str()) .change_context(ForexError::CurrencyNotAcceptable) .attach_printable("The provided currency is not acceptable")?; let from_currency = enums::Currency::from_str(from_currency.as_str()) .change_context(ForexError::CurrencyNotAcceptable) .attach_printable("The provided currency is not acceptable")?; let converted_amount = currency_conversion::conversion::convert(&rates.data, from_currency, to_currency, amount) .change_context(ForexError::ConversionError) .attach_printable("Unable to perform currency conversion")?; Ok(api_models::currency::CurrencyConversionResponse { converted_amount: converted_amount.to_string(), currency: to_currency.to_string(), }) }
crates/router/src/utils/currency.rs
router::src::utils::currency
4,439
true
// File: crates/router/src/utils/db_utils.rs // Module: router::src::utils::db_utils use crate::{ core::errors::{self, utils::RedisErrorExt}, routes::metrics, }; /// Generates hscan field pattern. Suppose the field is pa_1234_ref_1211 it will generate /// pa_1234_ref_* pub fn generate_hscan_pattern_for_refund(sk: &str) -> String { sk.split('_') .take(3) .chain(["*"]) .collect::<Vec<&str>>() .join("_") } // The first argument should be a future while the second argument should be a closure that returns a future for a database call pub async fn try_redis_get_else_try_database_get<F, RFut, DFut, T>( redis_fut: RFut, database_call_closure: F, ) -> error_stack::Result<T, errors::StorageError> where F: FnOnce() -> DFut, RFut: futures::Future<Output = error_stack::Result<T, redis_interface::errors::RedisError>>, DFut: futures::Future<Output = error_stack::Result<T, errors::StorageError>>, { let redis_output = redis_fut.await; match redis_output { Ok(output) => Ok(output), Err(redis_error) => match redis_error.current_context() { redis_interface::errors::RedisError::NotFound => { metrics::KV_MISS.add(1, &[]); database_call_closure().await } // Keeping the key empty here since the error would never go here. _ => Err(redis_error.to_redis_failed_response("")), }, } }
crates/router/src/utils/db_utils.rs
router::src::utils::db_utils
362
true
// File: crates/router/src/utils/connector_onboarding.rs // Module: router::src::utils::connector_onboarding use diesel_models::{ConfigNew, ConfigUpdate}; use error_stack::ResultExt; use super::errors::StorageErrorExt; use crate::{ consts, core::errors::{ApiErrorResponse, NotImplementedMessage, RouterResult}, routes::{app::settings, SessionState}, types::{self, api::enums}, }; pub mod paypal; pub fn get_connector_auth( connector: enums::Connector, connector_data: &settings::ConnectorOnboarding, ) -> RouterResult<types::ConnectorAuthType> { match connector { enums::Connector::Paypal => Ok(types::ConnectorAuthType::BodyKey { api_key: connector_data.paypal.client_secret.clone(), key1: connector_data.paypal.client_id.clone(), }), _ => Err(ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Reason(format!( "Onboarding is not implemented for {connector}", )), } .into()), } } pub fn is_enabled( connector: types::Connector, conf: &settings::ConnectorOnboarding, ) -> Option<bool> { match connector { enums::Connector::Paypal => Some(conf.paypal.enabled), _ => None, } } pub async fn check_if_connector_exists( state: &SessionState, connector_id: &common_utils::id_type::MerchantConnectorAccountId, merchant_id: &common_utils::id_type::MerchantId, ) -> RouterResult<()> { let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?; #[cfg(feature = "v1")] let _connector = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, connector_id, &key_store, ) .await .to_not_found_response(ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_id.get_string_repr().to_string(), })?; #[cfg(feature = "v2")] { let _ = connector_id; let _ = key_store; todo!() }; Ok(()) } pub async fn set_tracking_id_in_configs( state: &SessionState, connector_id: &common_utils::id_type::MerchantConnectorAccountId, connector: enums::Connector, ) -> RouterResult<()> { let timestamp = common_utils::date_time::now_unix_timestamp().to_string(); let find_config = state .store .find_config_by_key(&build_key(connector_id, connector)) .await; if find_config.is_ok() { state .store .update_config_by_key( &build_key(connector_id, connector), ConfigUpdate::Update { config: Some(timestamp), }, ) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Error updating data in configs table")?; } else if find_config .as_ref() .map_err(|e| e.current_context().is_db_not_found()) .err() .unwrap_or(false) { state .store .insert_config(ConfigNew { key: build_key(connector_id, connector), config: timestamp, }) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Error inserting data in configs table")?; } else { find_config.change_context(ApiErrorResponse::InternalServerError)?; } Ok(()) } pub async fn get_tracking_id_from_configs( state: &SessionState, connector_id: &common_utils::id_type::MerchantConnectorAccountId, connector: enums::Connector, ) -> RouterResult<String> { let timestamp = state .store .find_config_by_key_unwrap_or( &build_key(connector_id, connector), Some(common_utils::date_time::now_unix_timestamp().to_string()), ) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Error getting data from configs table")? .config; Ok(format!("{}_{}", connector_id.get_string_repr(), timestamp)) } fn build_key( connector_id: &common_utils::id_type::MerchantConnectorAccountId, connector: enums::Connector, ) -> String { format!( "{}_{}_{}", consts::CONNECTOR_ONBOARDING_CONFIG_PREFIX, connector, connector_id.get_string_repr(), ) }
crates/router/src/utils/connector_onboarding.rs
router::src::utils::connector_onboarding
1,009
true
// File: crates/router/src/utils/chat.rs // Module: router::src::utils::chat use api_models::chat as chat_api; use common_utils::{ crypto::{EncodeMessage, GcmAes256}, encryption::Encryption, }; use diesel_models::hyperswitch_ai_interaction::HyperswitchAiInteractionNew; use error_stack::ResultExt; use masking::ExposeInterface; use crate::{ core::errors::{self, CustomResult}, routes::SessionState, services::authentication as auth, }; pub async fn construct_hyperswitch_ai_interaction( state: &SessionState, user_from_token: &auth::UserFromToken, req: &chat_api::ChatRequest, response: &chat_api::ChatResponse, request_id: &str, ) -> CustomResult<HyperswitchAiInteractionNew, errors::ApiErrorResponse> { let encryption_key = state.conf.chat.get_inner().encryption_key.clone().expose(); let key = match hex::decode(&encryption_key) { Ok(key) => key, Err(e) => { router_env::logger::error!("Failed to decode encryption key: {}", e); // Fallback to using the string as bytes, which was the previous behavior encryption_key.as_bytes().to_vec() } }; let encrypted_user_query_bytes = GcmAes256 .encode_message(&key, &req.message.clone().expose().into_bytes()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt user query")?; let encrypted_response_bytes = serde_json::to_vec(&response.response.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize response for encryption") .and_then(|bytes| { GcmAes256 .encode_message(&key, &bytes) .change_context(errors::ApiErrorResponse::InternalServerError) }) .attach_printable("Failed to encrypt response")?; Ok(HyperswitchAiInteractionNew { id: request_id.to_owned(), session_id: Some(request_id.to_string()), user_id: Some(user_from_token.user_id.clone()), merchant_id: Some(user_from_token.merchant_id.get_string_repr().to_string()), profile_id: Some(user_from_token.profile_id.get_string_repr().to_string()), org_id: Some(user_from_token.org_id.get_string_repr().to_string()), role_id: Some(user_from_token.role_id.clone()), user_query: Some(Encryption::new(encrypted_user_query_bytes.into())), response: Some(Encryption::new(encrypted_response_bytes.into())), database_query: response.query_executed.clone().map(|q| q.expose()), interaction_status: Some(response.status.clone()), created_at: common_utils::date_time::now(), }) }
crates/router/src/utils/chat.rs
router::src::utils::chat
603
true
// File: crates/router/src/utils/connector_onboarding/paypal.rs // Module: router::src::utils::connector_onboarding::paypal use common_utils::request::{Method, Request, RequestBuilder, RequestContent}; use error_stack::ResultExt; use http::header; use crate::{ connector, core::errors::{ApiErrorResponse, RouterResult}, routes::SessionState, types, types::api::{ enums, verify_connector::{self as verify_connector_types, VerifyConnector}, }, utils::verify_connector as verify_connector_utils, }; pub async fn generate_access_token(state: SessionState) -> RouterResult<types::AccessToken> { let connector = enums::Connector::Paypal; let boxed_connector = types::api::ConnectorData::convert_connector(connector.to_string().as_str())?; let connector_auth = super::get_connector_auth(connector, state.conf.connector_onboarding.get_inner())?; connector::Paypal::get_access_token( &state, verify_connector_types::VerifyConnectorData { connector: boxed_connector, connector_auth, card_details: verify_connector_utils::get_test_card_details(connector)?.ok_or( ApiErrorResponse::FlowNotSupported { flow: "Connector onboarding".to_string(), connector: connector.to_string(), }, )?, }, ) .await? .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Error occurred while retrieving access token") } pub fn build_paypal_post_request<T>( url: String, body: T, access_token: String, ) -> RouterResult<Request> where T: serde::Serialize + Send + 'static, { Ok(RequestBuilder::new() .method(Method::Post) .url(&url) .attach_default_headers() .header( header::AUTHORIZATION.to_string().as_str(), format!("Bearer {access_token}").as_str(), ) .header( header::CONTENT_TYPE.to_string().as_str(), "application/json", ) .set_body(RequestContent::Json(Box::new(body))) .build()) } pub fn build_paypal_get_request(url: String, access_token: String) -> RouterResult<Request> { Ok(RequestBuilder::new() .method(Method::Get) .url(&url) .attach_default_headers() .header( header::AUTHORIZATION.to_string().as_str(), format!("Bearer {access_token}").as_str(), ) .build()) }
crates/router/src/utils/connector_onboarding/paypal.rs
router::src::utils::connector_onboarding::paypal
534
true
// File: crates/router/src/utils/user/theme.rs // Module: router::src::utils::user::theme use std::path::PathBuf; use common_enums::EntityType; use common_utils::{ext_traits::AsyncExt, id_type, types::user::ThemeLineage}; use diesel_models::user::theme::Theme; use error_stack::ResultExt; use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; use crate::{ core::errors::{StorageErrorExt, UserErrors, UserResult}, routes::SessionState, services::authentication::UserFromToken, }; fn get_theme_dir_key(theme_id: &str) -> PathBuf { ["themes", theme_id].iter().collect() } pub fn get_specific_file_key(theme_id: &str, file_name: &str) -> PathBuf { let mut path = get_theme_dir_key(theme_id); path.push(file_name); path } pub fn get_theme_file_key(theme_id: &str) -> PathBuf { get_specific_file_key(theme_id, "theme.json") } fn path_buf_to_str(path: &PathBuf) -> UserResult<&str> { path.to_str() .ok_or(UserErrors::InternalServerError) .attach_printable(format!("Failed to convert path {path:#?} to string")) } pub async fn retrieve_file_from_theme_bucket( state: &SessionState, path: &PathBuf, ) -> UserResult<Vec<u8>> { state .theme_storage_client .retrieve_file(path_buf_to_str(path)?) .await .change_context(UserErrors::ErrorRetrievingFile) } pub async fn upload_file_to_theme_bucket( state: &SessionState, path: &PathBuf, data: Vec<u8>, ) -> UserResult<()> { state .theme_storage_client .upload_file(path_buf_to_str(path)?, data) .await .change_context(UserErrors::ErrorUploadingFile) } pub async fn validate_lineage(state: &SessionState, lineage: &ThemeLineage) -> UserResult<()> { match lineage { ThemeLineage::Tenant { tenant_id } => { validate_tenant(state, tenant_id)?; Ok(()) } ThemeLineage::Organization { tenant_id, org_id } => { validate_tenant(state, tenant_id)?; validate_org(state, org_id).await?; Ok(()) } ThemeLineage::Merchant { tenant_id, org_id, merchant_id, } => { validate_tenant(state, tenant_id)?; validate_org(state, org_id).await?; validate_merchant(state, org_id, merchant_id).await?; Ok(()) } ThemeLineage::Profile { tenant_id, org_id, merchant_id, profile_id, } => { validate_tenant(state, tenant_id)?; validate_org(state, org_id).await?; let key_store = validate_merchant_and_get_key_store(state, org_id, merchant_id).await?; validate_profile(state, profile_id, merchant_id, &key_store).await?; Ok(()) } } } fn validate_tenant(state: &SessionState, tenant_id: &id_type::TenantId) -> UserResult<()> { if &state.tenant.tenant_id != tenant_id { return Err(UserErrors::InvalidThemeLineage("tenant_id".to_string()).into()); } Ok(()) } async fn validate_org(state: &SessionState, org_id: &id_type::OrganizationId) -> UserResult<()> { state .accounts_store .find_organization_by_org_id(org_id) .await .to_not_found_response(UserErrors::InvalidThemeLineage("org_id".to_string())) .map(|_| ()) } async fn validate_merchant_and_get_key_store( state: &SessionState, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, ) -> UserResult<MerchantKeyStore> { let key_store = state .store .get_merchant_key_store_by_merchant_id( &state.into(), merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(UserErrors::InvalidThemeLineage("merchant_id".to_string()))?; let merchant_account = state .store .find_merchant_account_by_merchant_id(&state.into(), merchant_id, &key_store) .await .to_not_found_response(UserErrors::InvalidThemeLineage("merchant_id".to_string()))?; if &merchant_account.organization_id != org_id { return Err(UserErrors::InvalidThemeLineage("merchant_id".to_string()).into()); } Ok(key_store) } async fn validate_merchant( state: &SessionState, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, ) -> UserResult<()> { validate_merchant_and_get_key_store(state, org_id, merchant_id) .await .map(|_| ()) } async fn validate_profile( state: &SessionState, profile_id: &id_type::ProfileId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, ) -> UserResult<()> { state .store .find_business_profile_by_merchant_id_profile_id( &state.into(), key_store, merchant_id, profile_id, ) .await .to_not_found_response(UserErrors::InvalidThemeLineage("profile_id".to_string())) .map(|_| ()) } pub async fn get_most_specific_theme_using_token_and_min_entity( state: &SessionState, user_from_token: &UserFromToken, min_entity: EntityType, ) -> UserResult<Option<Theme>> { get_most_specific_theme_using_lineage( state, ThemeLineage::new( min_entity, user_from_token .tenant_id .clone() .unwrap_or(state.tenant.tenant_id.clone()), user_from_token.org_id.clone(), user_from_token.merchant_id.clone(), user_from_token.profile_id.clone(), ), ) .await } pub async fn get_most_specific_theme_using_lineage( state: &SessionState, lineage: ThemeLineage, ) -> UserResult<Option<Theme>> { match state .store .find_most_specific_theme_in_lineage(lineage) .await { Ok(theme) => Ok(Some(theme)), Err(e) => { if e.current_context().is_db_not_found() { Ok(None) } else { Err(e.change_context(UserErrors::InternalServerError)) } } } } pub async fn get_theme_using_optional_theme_id( state: &SessionState, theme_id: Option<String>, ) -> UserResult<Option<Theme>> { match theme_id .async_map(|theme_id| state.store.find_theme_by_theme_id(theme_id)) .await .transpose() { Ok(theme) => Ok(theme), Err(e) => { if e.current_context().is_db_not_found() { Ok(None) } else { Err(e.change_context(UserErrors::InternalServerError)) } } } } pub async fn get_theme_lineage_from_user_token( user_from_token: &UserFromToken, state: &SessionState, request_entity_type: &EntityType, ) -> UserResult<ThemeLineage> { let tenant_id = user_from_token .tenant_id .clone() .unwrap_or(state.tenant.tenant_id.clone()); let org_id = user_from_token.org_id.clone(); let merchant_id = user_from_token.merchant_id.clone(); let profile_id = user_from_token.profile_id.clone(); Ok(ThemeLineage::new( *request_entity_type, tenant_id, org_id, merchant_id, profile_id, )) } pub async fn can_user_access_theme( user: &UserFromToken, user_entity_type: &EntityType, theme: &Theme, ) -> UserResult<()> { if user_entity_type < &theme.entity_type { return Err(UserErrors::ThemeNotFound.into()); } match theme.entity_type { EntityType::Tenant => { if user.tenant_id.as_ref() == Some(&theme.tenant_id) && theme.org_id.is_none() && theme.merchant_id.is_none() && theme.profile_id.is_none() { Ok(()) } else { Err(UserErrors::ThemeNotFound.into()) } } EntityType::Organization => { if user.tenant_id.as_ref() == Some(&theme.tenant_id) && theme.org_id.as_ref() == Some(&user.org_id) && theme.merchant_id.is_none() && theme.profile_id.is_none() { Ok(()) } else { Err(UserErrors::ThemeNotFound.into()) } } EntityType::Merchant => { if user.tenant_id.as_ref() == Some(&theme.tenant_id) && theme.org_id.as_ref() == Some(&user.org_id) && theme.merchant_id.as_ref() == Some(&user.merchant_id) && theme.profile_id.is_none() { Ok(()) } else { Err(UserErrors::ThemeNotFound.into()) } } EntityType::Profile => { if user.tenant_id.as_ref() == Some(&theme.tenant_id) && theme.org_id.as_ref() == Some(&user.org_id) && theme.merchant_id.as_ref() == Some(&user.merchant_id) && theme.profile_id.as_ref() == Some(&user.profile_id) { Ok(()) } else { Err(UserErrors::ThemeNotFound.into()) } } } }
crates/router/src/utils/user/theme.rs
router::src::utils::user::theme
2,103
true
// File: crates/router/src/utils/user/dashboard_metadata.rs // Module: router::src::utils::user::dashboard_metadata use std::{net::IpAddr, ops::Not, str::FromStr}; use actix_web::http::header::HeaderMap; use api_models::user::dashboard_metadata::{ GetMetaDataRequest, GetMultipleMetaDataPayload, ProdIntent, SetMetaDataRequest, }; use common_utils::id_type; use diesel_models::{ enums::DashboardMetadata as DBEnum, user::dashboard_metadata::{DashboardMetadata, DashboardMetadataNew, DashboardMetadataUpdate}, }; use error_stack::{report, ResultExt}; use masking::{ExposeInterface, PeekInterface, Secret}; use router_env::logger; use crate::{ core::errors::{UserErrors, UserResult}, headers, SessionState, }; pub async fn insert_merchant_scoped_metadata_to_db( state: &SessionState, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, metadata_key: DBEnum, metadata_value: impl serde::Serialize, ) -> UserResult<DashboardMetadata> { let now = common_utils::date_time::now(); let data_value = serde_json::to_value(metadata_value) .change_context(UserErrors::InternalServerError) .attach_printable("Error Converting Struct To Serde Value")?; state .store .insert_metadata(DashboardMetadataNew { user_id: None, merchant_id, org_id, data_key: metadata_key, data_value: Secret::from(data_value), created_by: user_id.clone(), created_at: now, last_modified_by: user_id, last_modified_at: now, }) .await .map_err(|e| { if e.current_context().is_db_unique_violation() { return e.change_context(UserErrors::MetadataAlreadySet); } e.change_context(UserErrors::InternalServerError) }) } pub async fn insert_user_scoped_metadata_to_db( state: &SessionState, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, metadata_key: DBEnum, metadata_value: impl serde::Serialize, ) -> UserResult<DashboardMetadata> { let now = common_utils::date_time::now(); let data_value = serde_json::to_value(metadata_value) .change_context(UserErrors::InternalServerError) .attach_printable("Error Converting Struct To Serde Value")?; state .store .insert_metadata(DashboardMetadataNew { user_id: Some(user_id.clone()), merchant_id, org_id, data_key: metadata_key, data_value: Secret::from(data_value), created_by: user_id.clone(), created_at: now, last_modified_by: user_id, last_modified_at: now, }) .await .map_err(|e| { if e.current_context().is_db_unique_violation() { return e.change_context(UserErrors::MetadataAlreadySet); } e.change_context(UserErrors::InternalServerError) }) } pub async fn get_merchant_scoped_metadata_from_db( state: &SessionState, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, metadata_keys: Vec<DBEnum>, ) -> UserResult<Vec<DashboardMetadata>> { state .store .find_merchant_scoped_dashboard_metadata(&merchant_id, &org_id, metadata_keys) .await .change_context(UserErrors::InternalServerError) .attach_printable("DB Error Fetching DashboardMetaData") } pub async fn get_user_scoped_metadata_from_db( state: &SessionState, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, metadata_keys: Vec<DBEnum>, ) -> UserResult<Vec<DashboardMetadata>> { match state .store .find_user_scoped_dashboard_metadata(&user_id, &merchant_id, &org_id, metadata_keys) .await { Ok(data) => Ok(data), Err(e) => { if e.current_context().is_db_not_found() { return Ok(Vec::with_capacity(0)); } Err(e .change_context(UserErrors::InternalServerError) .attach_printable("DB Error Fetching DashboardMetaData")) } } } pub async fn update_merchant_scoped_metadata( state: &SessionState, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, metadata_key: DBEnum, metadata_value: impl serde::Serialize, ) -> UserResult<DashboardMetadata> { let data_value = serde_json::to_value(metadata_value) .change_context(UserErrors::InternalServerError) .attach_printable("Error Converting Struct To Serde Value")?; state .store .update_metadata( None, merchant_id, org_id, metadata_key, DashboardMetadataUpdate::UpdateData { data_key: metadata_key, data_value: Secret::from(data_value), last_modified_by: user_id, }, ) .await .change_context(UserErrors::InternalServerError) } pub async fn update_user_scoped_metadata( state: &SessionState, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, metadata_key: DBEnum, metadata_value: impl serde::Serialize, ) -> UserResult<DashboardMetadata> { let data_value = serde_json::to_value(metadata_value) .change_context(UserErrors::InternalServerError) .attach_printable("Error Converting Struct To Serde Value")?; state .store .update_metadata( Some(user_id.clone()), merchant_id, org_id, metadata_key, DashboardMetadataUpdate::UpdateData { data_key: metadata_key, data_value: Secret::from(data_value), last_modified_by: user_id, }, ) .await .change_context(UserErrors::InternalServerError) } pub fn deserialize_to_response<T>(data: Option<&DashboardMetadata>) -> UserResult<Option<T>> where T: serde::de::DeserializeOwned, { data.map(|metadata| serde_json::from_value(metadata.data_value.clone().expose())) .transpose() .change_context(UserErrors::InternalServerError) .attach_printable("Error Serializing Metadata from DB") } pub fn separate_metadata_type_based_on_scope( metadata_keys: Vec<DBEnum>, ) -> (Vec<DBEnum>, Vec<DBEnum>) { let (mut merchant_scoped, mut user_scoped) = ( Vec::with_capacity(metadata_keys.len()), Vec::with_capacity(metadata_keys.len()), ); for key in metadata_keys { match key { DBEnum::ProductionAgreement | DBEnum::SetupProcessor | DBEnum::ConfigureEndpoint | DBEnum::SetupComplete | DBEnum::FirstProcessorConnected | DBEnum::SecondProcessorConnected | DBEnum::ConfiguredRouting | DBEnum::TestPayment | DBEnum::IntegrationMethod | DBEnum::ConfigurationType | DBEnum::IntegrationCompleted | DBEnum::StripeConnected | DBEnum::PaypalConnected | DBEnum::SpRoutingConfigured | DBEnum::SpTestPayment | DBEnum::DownloadWoocom | DBEnum::ConfigureWoocom | DBEnum::SetupWoocomWebhook | DBEnum::OnboardingSurvey | DBEnum::IsMultipleConfiguration | DBEnum::ReconStatus | DBEnum::ProdIntent => merchant_scoped.push(key), DBEnum::Feedback | DBEnum::IsChangePasswordRequired => user_scoped.push(key), } } (merchant_scoped, user_scoped) } pub fn is_update_required(metadata: &UserResult<DashboardMetadata>) -> bool { match metadata { Ok(_) => false, Err(e) => matches!(e.current_context(), UserErrors::MetadataAlreadySet), } } pub fn is_backfill_required(metadata_key: DBEnum) -> bool { matches!( metadata_key, DBEnum::StripeConnected | DBEnum::PaypalConnected ) } pub fn set_ip_address_if_required( request: &mut SetMetaDataRequest, headers: &HeaderMap, ) -> UserResult<()> { if let SetMetaDataRequest::ProductionAgreement(req) = request { let ip_address_from_request: Secret<String, common_utils::pii::IpAddress> = headers .get(headers::X_FORWARDED_FOR) .ok_or(report!(UserErrors::IpAddressParsingFailed)) .attach_printable("X-Forwarded-For header not found")? .to_str() .change_context(UserErrors::IpAddressParsingFailed) .attach_printable("Error converting Header Value to Str")? .split(',') .next() .and_then(|ip| { let ip_addr: Result<IpAddr, _> = ip.parse(); ip_addr.ok() }) .ok_or(report!(UserErrors::IpAddressParsingFailed)) .attach_printable("Error Parsing header value to ip")? .to_string() .into(); req.ip_address = Some(ip_address_from_request) } Ok(()) } pub fn parse_string_to_enums(query: String) -> UserResult<GetMultipleMetaDataPayload> { Ok(GetMultipleMetaDataPayload { results: query .split(',') .map(GetMetaDataRequest::from_str) .collect::<Result<Vec<GetMetaDataRequest>, _>>() .change_context(UserErrors::InvalidMetadataRequest) .attach_printable("Error Parsing to DashboardMetadata enums")?, }) } fn not_contains_string(value: Option<&str>, value_to_be_checked: &str) -> bool { value.is_some_and(|mail| !mail.contains(value_to_be_checked)) } pub fn is_prod_email_required(data: &ProdIntent, user_email: String) -> bool { let poc_email_check = not_contains_string( data.poc_email.as_ref().map(|email| email.peek().as_str()), "juspay", ); let business_website_check = not_contains_string(data.business_website.as_ref().map(|s| s.as_str()), "juspay") && not_contains_string( data.business_website.as_ref().map(|s| s.as_str()), "hyperswitch", ); let user_email_check = not_contains_string(Some(&user_email), "juspay"); if (poc_email_check && business_website_check && user_email_check).not() { logger::info!(prod_intent_email = poc_email_check); logger::info!(prod_intent_email = business_website_check); logger::info!(prod_intent_email = user_email_check); } poc_email_check && business_website_check && user_email_check }
crates/router/src/utils/user/dashboard_metadata.rs
router::src::utils::user::dashboard_metadata
2,357
true
// File: crates/router/src/utils/user/password.rs // Module: router::src::utils::user::password use argon2::{ password_hash::{ rand_core::OsRng, Error as argon2Err, PasswordHash, PasswordHasher, PasswordVerifier, SaltString, }, Argon2, }; use common_utils::errors::CustomResult; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret}; use rand::{seq::SliceRandom, Rng}; use crate::core::errors::UserErrors; pub fn generate_password_hash( password: Secret<String>, ) -> CustomResult<Secret<String>, UserErrors> { let salt = SaltString::generate(&mut OsRng); let argon2 = Argon2::default(); let password_hash = argon2 .hash_password(password.expose().as_bytes(), &salt) .change_context(UserErrors::InternalServerError)?; Ok(Secret::new(password_hash.to_string())) } pub fn is_correct_password( candidate: &Secret<String>, password: &Secret<String>, ) -> CustomResult<bool, UserErrors> { let password = password.peek(); let parsed_hash = PasswordHash::new(password).change_context(UserErrors::InternalServerError)?; let result = Argon2::default().verify_password(candidate.peek().as_bytes(), &parsed_hash); match result { Ok(_) => Ok(true), Err(argon2Err::Password) => Ok(false), Err(e) => Err(e), } .change_context(UserErrors::InternalServerError) } pub fn get_index_for_correct_recovery_code( candidate: &Secret<String>, recovery_codes: &[Secret<String>], ) -> CustomResult<Option<usize>, UserErrors> { for (index, recovery_code) in recovery_codes.iter().enumerate() { let is_match = is_correct_password(candidate, recovery_code)?; if is_match { return Ok(Some(index)); } } Ok(None) } pub fn get_temp_password() -> Secret<String> { let uuid_pass = uuid::Uuid::new_v4().to_string(); let mut rng = rand::thread_rng(); let special_chars: Vec<char> = "!@#$%^&*()-_=+[]{}|;:,.<>?".chars().collect(); let special_char = special_chars.choose(&mut rng).unwrap_or(&'@'); Secret::new(format!( "{}{}{}{}{}", uuid_pass, rng.gen_range('A'..='Z'), special_char, rng.gen_range('a'..='z'), rng.gen_range('0'..='9'), )) }
crates/router/src/utils/user/password.rs
router::src::utils::user::password
561
true
// File: crates/router/src/utils/user/two_factor_auth.rs // Module: router::src::utils::user::two_factor_auth use common_utils::pii; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface}; use totp_rs::{Algorithm, TOTP}; use crate::{ consts, core::errors::{UserErrors, UserResult}, routes::SessionState, }; pub fn generate_default_totp( email: pii::Email, secret: Option<masking::Secret<String>>, issuer: String, ) -> UserResult<TOTP> { let secret = secret .map(|sec| totp_rs::Secret::Encoded(sec.expose())) .unwrap_or_else(totp_rs::Secret::generate_secret) .to_bytes() .change_context(UserErrors::InternalServerError)?; TOTP::new( Algorithm::SHA1, consts::user::TOTP_DIGITS, consts::user::TOTP_TOLERANCE, consts::user::TOTP_VALIDITY_DURATION_IN_SECONDS, secret, Some(issuer), email.expose().expose(), ) .change_context(UserErrors::InternalServerError) } pub async fn check_totp_in_redis(state: &SessionState, user_id: &str) -> UserResult<bool> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); redis_conn .exists::<()>(&key.into()) .await .change_context(UserErrors::InternalServerError) } pub async fn check_recovery_code_in_redis(state: &SessionState, user_id: &str) -> UserResult<bool> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); redis_conn .exists::<()>(&key.into()) .await .change_context(UserErrors::InternalServerError) } pub async fn insert_totp_in_redis(state: &SessionState, user_id: &str) -> UserResult<()> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); redis_conn .set_key_with_expiry( &key.as_str().into(), common_utils::date_time::now_unix_timestamp(), state.conf.user.two_factor_auth_expiry_in_secs, ) .await .change_context(UserErrors::InternalServerError) } pub async fn insert_totp_secret_in_redis( state: &SessionState, user_id: &str, secret: &masking::Secret<String>, ) -> UserResult<()> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .set_key_with_expiry( &get_totp_secret_key(user_id).into(), secret.peek(), consts::user::REDIS_TOTP_SECRET_TTL_IN_SECS, ) .await .change_context(UserErrors::InternalServerError) } pub async fn get_totp_secret_from_redis( state: &SessionState, user_id: &str, ) -> UserResult<Option<masking::Secret<String>>> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .get_key::<Option<String>>(&get_totp_secret_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|secret| secret.map(Into::into)) } pub async fn delete_totp_secret_from_redis(state: &SessionState, user_id: &str) -> UserResult<()> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .delete_key(&get_totp_secret_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|_| ()) } fn get_totp_secret_key(user_id: &str) -> String { format!("{}{}", consts::user::REDIS_TOTP_SECRET_PREFIX, user_id) } pub async fn insert_recovery_code_in_redis(state: &SessionState, user_id: &str) -> UserResult<()> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); redis_conn .set_key_with_expiry( &key.as_str().into(), common_utils::date_time::now_unix_timestamp(), state.conf.user.two_factor_auth_expiry_in_secs, ) .await .change_context(UserErrors::InternalServerError) } pub async fn delete_totp_from_redis(state: &SessionState, user_id: &str) -> UserResult<()> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); redis_conn .delete_key(&key.into()) .await .change_context(UserErrors::InternalServerError) .map(|_| ()) } pub async fn delete_recovery_code_from_redis( state: &SessionState, user_id: &str, ) -> UserResult<()> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); redis_conn .delete_key(&key.into()) .await .change_context(UserErrors::InternalServerError) .map(|_| ()) } fn get_totp_attempts_key(user_id: &str) -> String { format!("{}{}", consts::user::REDIS_TOTP_ATTEMPTS_PREFIX, user_id) } fn get_recovery_code_attempts_key(user_id: &str) -> String { format!( "{}{}", consts::user::REDIS_RECOVERY_CODE_ATTEMPTS_PREFIX, user_id ) } pub async fn insert_totp_attempts_in_redis( state: &SessionState, user_id: &str, user_totp_attempts: u8, ) -> UserResult<()> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .set_key_with_expiry( &get_totp_attempts_key(user_id).into(), user_totp_attempts, consts::user::REDIS_TOTP_ATTEMPTS_TTL_IN_SECS, ) .await .change_context(UserErrors::InternalServerError) } pub async fn get_totp_attempts_from_redis(state: &SessionState, user_id: &str) -> UserResult<u8> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .get_key::<Option<u8>>(&get_totp_attempts_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|v| v.unwrap_or(0)) } pub async fn insert_recovery_code_attempts_in_redis( state: &SessionState, user_id: &str, user_recovery_code_attempts: u8, ) -> UserResult<()> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .set_key_with_expiry( &get_recovery_code_attempts_key(user_id).into(), user_recovery_code_attempts, consts::user::REDIS_RECOVERY_CODE_ATTEMPTS_TTL_IN_SECS, ) .await .change_context(UserErrors::InternalServerError) } pub async fn get_recovery_code_attempts_from_redis( state: &SessionState, user_id: &str, ) -> UserResult<u8> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .get_key::<Option<u8>>(&get_recovery_code_attempts_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|v| v.unwrap_or(0)) } pub async fn delete_totp_attempts_from_redis( state: &SessionState, user_id: &str, ) -> UserResult<()> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .delete_key(&get_totp_attempts_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|_| ()) } pub async fn delete_recovery_code_attempts_from_redis( state: &SessionState, user_id: &str, ) -> UserResult<()> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .delete_key(&get_recovery_code_attempts_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|_| ()) }
crates/router/src/utils/user/two_factor_auth.rs
router::src::utils::user::two_factor_auth
1,863
true
// File: crates/router/src/utils/user/sample_data.rs // Module: router::src::utils::user::sample_data use api_models::{ enums::Connector::{DummyConnector4, DummyConnector7}, user::sample_data::SampleDataRequest, }; use common_utils::{ id_type, types::{AmountConvertor, ConnectorTransactionId, MinorUnit, StringMinorUnitForConnector}, }; #[cfg(feature = "v1")] use diesel_models::user::sample_data::PaymentAttemptBatchNew; use diesel_models::{enums as storage_enums, DisputeNew, RefundNew}; use error_stack::ResultExt; use hyperswitch_domain_models::payments::PaymentIntent; use rand::{prelude::SliceRandom, thread_rng, Rng}; use time::OffsetDateTime; use crate::{ consts, core::errors::sample_data::{SampleDataError, SampleDataResult}, types::domain, SessionState, }; #[cfg(feature = "v1")] #[allow(clippy::type_complexity)] pub async fn generate_sample_data( state: &SessionState, req: SampleDataRequest, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, ) -> SampleDataResult< Vec<( PaymentIntent, PaymentAttemptBatchNew, Option<RefundNew>, Option<DisputeNew>, )>, > { let sample_data_size: usize = req.record.unwrap_or(100); let key_manager_state = &state.into(); if !(10..=100).contains(&sample_data_size) { return Err(SampleDataError::InvalidRange.into()); } let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .change_context(SampleDataError::InternalServerError)?; let merchant_from_db = state .store .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .change_context::<SampleDataError>(SampleDataError::DataDoesNotExist)?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_from_db.clone(), key_store, ))); #[cfg(feature = "v1")] let (profile_id_result, business_country_default, business_label_default) = { let merchant_parsed_details: Vec<api_models::admin::PrimaryBusinessDetails> = serde_json::from_value(merchant_from_db.primary_business_details.clone()) .change_context(SampleDataError::InternalServerError) .attach_printable("Error while parsing primary business details")?; let business_country_default = merchant_parsed_details.first().map(|x| x.country); let business_label_default = merchant_parsed_details.first().map(|x| x.business.clone()); let profile_id = crate::core::utils::get_profile_id_from_business_details( key_manager_state, business_country_default, business_label_default.as_ref(), &merchant_context, req.profile_id.as_ref(), &*state.store, false, ) .await; (profile_id, business_country_default, business_label_default) }; #[cfg(feature = "v2")] let (profile_id_result, business_country_default, business_label_default) = { let profile_id = req .profile_id.clone() .ok_or(hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse::MissingRequiredField { field_name: "profile_id", }); (profile_id, None, None) }; let profile_id = match profile_id_result { Ok(id) => id.clone(), Err(error) => { router_env::logger::error!( "Profile ID not found in business details. Attempting to fetch from the database {error:?}" ); state .store .list_profile_by_merchant_id( key_manager_state, merchant_context.get_merchant_key_store(), merchant_id, ) .await .change_context(SampleDataError::InternalServerError) .attach_printable("Failed to get business profile")? .first() .ok_or(SampleDataError::InternalServerError)? .get_id() .to_owned() } }; // 10 percent payments should be failed #[allow(clippy::as_conversions)] let failure_attempts = usize::try_from((sample_data_size as f32 / 10.0).round() as i64) .change_context(SampleDataError::InvalidParameters)?; let failure_after_attempts = sample_data_size / failure_attempts; // 20 percent refunds for payments #[allow(clippy::as_conversions)] let number_of_refunds = usize::try_from((sample_data_size as f32 / 5.0).round() as i64) .change_context(SampleDataError::InvalidParameters)?; let mut refunds_count = 0; // 2 disputes if generated data size is between 50 and 100, 1 dispute if it is less than 50. let number_of_disputes: usize = if sample_data_size >= 50 { 2 } else { 1 }; let mut disputes_count = 0; let mut random_array: Vec<usize> = (1..=sample_data_size).collect(); // Shuffle the array let mut rng = thread_rng(); random_array.shuffle(&mut rng); let mut res: Vec<( PaymentIntent, PaymentAttemptBatchNew, Option<RefundNew>, Option<DisputeNew>, )> = Vec::new(); let start_time = req .start_time .unwrap_or(common_utils::date_time::now() - time::Duration::days(7)) .assume_utc() .unix_timestamp(); let end_time = req .end_time .unwrap_or_else(common_utils::date_time::now) .assume_utc() .unix_timestamp(); let current_time = common_utils::date_time::now().assume_utc().unix_timestamp(); let min_amount = req.min_amount.unwrap_or(100); let max_amount = req.max_amount.unwrap_or(min_amount + 100); if min_amount > max_amount || start_time > end_time || start_time > current_time || end_time > current_time { return Err(SampleDataError::InvalidParameters.into()); }; let currency_vec = req.currency.unwrap_or(vec![common_enums::Currency::USD]); let currency_vec_len = currency_vec.len(); let connector_vec = req .connector .unwrap_or(vec![DummyConnector4, DummyConnector7]); let connector_vec_len = connector_vec.len(); let auth_type = req.auth_type.unwrap_or(vec![ common_enums::AuthenticationType::ThreeDs, common_enums::AuthenticationType::NoThreeDs, ]); let auth_type_len = auth_type.len(); if currency_vec_len == 0 || connector_vec_len == 0 || auth_type_len == 0 { return Err(SampleDataError::InvalidParameters.into()); } // This has to be an internal server error because, this function failing means that the intended functionality is not working as expected let dashboard_customer_id = id_type::CustomerId::try_from(std::borrow::Cow::from("hs-dashboard-user")) .change_context(SampleDataError::InternalServerError)?; for num in 1..=sample_data_size { let payment_id = id_type::PaymentId::generate_test_payment_id_for_sample_data(); let attempt_id = payment_id.get_attempt_id(1); let client_secret = payment_id.generate_client_secret(); let amount = thread_rng().gen_range(min_amount..=max_amount); let created_at @ modified_at @ last_synced = OffsetDateTime::from_unix_timestamp(thread_rng().gen_range(start_time..=end_time)) .map(common_utils::date_time::convert_to_pdt) .unwrap_or( req.start_time.unwrap_or_else(|| { common_utils::date_time::now() - time::Duration::days(7) }), ); let session_expiry = created_at.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)); // After some set of payments sample data will have a failed attempt let is_failed_payment = (random_array.get(num - 1).unwrap_or(&0) % failure_after_attempts) == 0; let payment_intent = PaymentIntent { payment_id: payment_id.clone(), merchant_id: merchant_id.clone(), status: match is_failed_payment { true => common_enums::IntentStatus::Failed, _ => common_enums::IntentStatus::Succeeded, }, amount: MinorUnit::new(amount * 100), currency: Some( *currency_vec .get((num - 1) % currency_vec_len) .unwrap_or(&common_enums::Currency::USD), ), description: Some("This is a sample payment".to_string()), created_at, modified_at, last_synced: Some(last_synced), client_secret: Some(client_secret), business_country: business_country_default, business_label: business_label_default.clone(), active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID( attempt_id.clone(), ), attempt_count: 1, customer_id: Some(dashboard_customer_id.clone()), amount_captured: Some(MinorUnit::new(amount * 100)), profile_id: Some(profile_id.clone()), return_url: Default::default(), metadata: Default::default(), connector_id: Default::default(), shipping_address_id: Default::default(), billing_address_id: Default::default(), statement_descriptor_name: Default::default(), statement_descriptor_suffix: Default::default(), setup_future_usage: Default::default(), off_session: Default::default(), order_details: Default::default(), allowed_payment_method_types: Default::default(), connector_metadata: Default::default(), feature_metadata: Default::default(), merchant_decision: Default::default(), payment_link_id: Default::default(), payment_confirm_source: Default::default(), updated_by: merchant_from_db.storage_scheme.to_string(), surcharge_applicable: Default::default(), request_incremental_authorization: Default::default(), incremental_authorization_allowed: Default::default(), authorization_count: Default::default(), fingerprint_id: None, session_expiry: Some(session_expiry), request_external_three_ds_authentication: None, split_payments: None, frm_metadata: Default::default(), customer_details: None, billing_details: None, merchant_order_reference_id: Default::default(), shipping_details: None, is_payment_processor_token_flow: None, organization_id: org_id.clone(), shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, processor_merchant_id: merchant_id.clone(), created_by: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, is_iframe_redirection_enabled: None, is_payment_id_from_merchant: None, payment_channel: None, order_date: None, discount_amount: None, duty_amount: None, tax_status: None, shipping_amount_tax: None, enable_partial_authorization: None, enable_overcapture: None, mit_category: None, }; let (connector_transaction_id, processor_transaction_data) = ConnectorTransactionId::form_id_and_data(attempt_id.clone()); let payment_attempt = PaymentAttemptBatchNew { attempt_id: attempt_id.clone(), payment_id: payment_id.clone(), connector_transaction_id: Some(connector_transaction_id), merchant_id: merchant_id.clone(), status: match is_failed_payment { true => common_enums::AttemptStatus::Failure, _ => common_enums::AttemptStatus::Charged, }, amount: MinorUnit::new(amount * 100), currency: payment_intent.currency, connector: Some( (*connector_vec .get((num - 1) % connector_vec_len) .unwrap_or(&DummyConnector4)) .to_string(), ), payment_method: Some(common_enums::PaymentMethod::Card), payment_method_type: Some(get_payment_method_type(thread_rng().gen_range(1..=2))), authentication_type: Some( *auth_type .get((num - 1) % auth_type_len) .unwrap_or(&common_enums::AuthenticationType::NoThreeDs), ), error_message: match is_failed_payment { true => Some("This is a test payment which has a failed status".to_string()), _ => None, }, error_code: match is_failed_payment { true => Some("HS001".to_string()), _ => None, }, confirm: true, created_at, modified_at, last_synced: Some(last_synced), amount_to_capture: Some(MinorUnit::new(amount * 100)), connector_response_reference_id: Some(attempt_id.clone()), updated_by: merchant_from_db.storage_scheme.to_string(), save_to_locker: None, offer_amount: None, surcharge_amount: None, tax_amount: None, payment_method_id: None, capture_method: None, capture_on: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, connector_metadata: None, payment_experience: None, payment_method_data: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, mandate_details: None, error_reason: None, multiple_capture_count: None, amount_capturable: MinorUnit::new(i64::default()), merchant_connector_id: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, net_amount: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, mandate_data: None, payment_method_billing_address_id: None, fingerprint_id: None, charge_id: None, client_source: None, client_version: None, customer_acceptance: None, profile_id: profile_id.clone(), organization_id: org_id.clone(), shipping_cost: None, order_tax_amount: None, processor_transaction_data, connector_mandate_detail: None, request_extended_authorization: None, extended_authorization_applied: None, capture_before: None, card_discovery: None, processor_merchant_id: Some(merchant_id.clone()), created_by: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, network_details: None, is_stored_credential: None, authorized_amount: None, }; let refund = if refunds_count < number_of_refunds && !is_failed_payment { refunds_count += 1; let (connector_transaction_id, processor_transaction_data) = ConnectorTransactionId::form_id_and_data(attempt_id.clone()); Some(RefundNew { refund_id: common_utils::generate_id_with_default_len("test"), internal_reference_id: common_utils::generate_id_with_default_len("test"), external_reference_id: None, payment_id: payment_id.clone(), attempt_id: attempt_id.clone(), merchant_id: merchant_id.clone(), connector_transaction_id, connector_refund_id: None, description: Some("This is a sample refund".to_string()), created_at, modified_at, refund_reason: Some("Sample Refund".to_string()), connector: payment_attempt .connector .clone() .unwrap_or(DummyConnector4.to_string()), currency: *currency_vec .get((num - 1) % currency_vec_len) .unwrap_or(&common_enums::Currency::USD), total_amount: MinorUnit::new(amount * 100), refund_amount: MinorUnit::new(amount * 100), refund_status: common_enums::RefundStatus::Success, sent_to_gateway: true, refund_type: diesel_models::enums::RefundType::InstantRefund, metadata: None, refund_arn: None, profile_id: payment_intent.profile_id.clone(), updated_by: merchant_from_db.storage_scheme.to_string(), merchant_connector_id: payment_attempt.merchant_connector_id.clone(), charges: None, split_refunds: None, organization_id: org_id.clone(), processor_refund_data: None, processor_transaction_data, }) } else { None }; let dispute = if disputes_count < number_of_disputes && !is_failed_payment && refund.is_none() { disputes_count += 1; let currency = payment_intent .currency .unwrap_or(common_enums::Currency::USD); Some(DisputeNew { dispute_id: common_utils::generate_id_with_default_len("test"), amount: StringMinorUnitForConnector::convert( &StringMinorUnitForConnector, MinorUnit::new(amount * 100), currency, ) .change_context(SampleDataError::InternalServerError)?, currency: currency.to_string(), dispute_stage: storage_enums::DisputeStage::Dispute, dispute_status: storage_enums::DisputeStatus::DisputeOpened, payment_id: payment_id.clone(), attempt_id: attempt_id.clone(), merchant_id: merchant_id.clone(), connector_status: "Sample connector status".into(), connector_dispute_id: common_utils::generate_id_with_default_len("test"), connector_reason: Some("Sample Dispute".into()), connector_reason_code: Some("123".into()), challenge_required_by: None, connector_created_at: None, connector_updated_at: None, connector: payment_attempt .connector .clone() .unwrap_or(DummyConnector4.to_string()), evidence: None, profile_id: payment_intent.profile_id.clone(), merchant_connector_id: payment_attempt.merchant_connector_id.clone(), dispute_amount: MinorUnit::new(amount * 100), organization_id: org_id.clone(), dispute_currency: Some(payment_intent.currency.unwrap_or_default()), }) } else { None }; res.push((payment_intent, payment_attempt, refund, dispute)); } Ok(res) } fn get_payment_method_type(num: u8) -> common_enums::PaymentMethodType { let rem: u8 = (num) % 2; match rem { 0 => common_enums::PaymentMethodType::Debit, _ => common_enums::PaymentMethodType::Credit, } }
crates/router/src/utils/user/sample_data.rs
router::src::utils::user::sample_data
4,109
true
// File: crates/router/src/configs/defaults.rs // Module: router::src::configs::defaults use std::collections::HashSet; #[cfg(feature = "payouts")] pub mod payout_required_fields; impl Default for super::settings::Server { fn default() -> Self { Self { port: 8080, workers: num_cpus::get_physical(), host: "localhost".into(), request_body_limit: 16 * 1024, // POST request body is limited to 16KiB shutdown_timeout: 30, #[cfg(feature = "tls")] tls: None, } } } impl Default for super::settings::CorsSettings { fn default() -> Self { Self { origins: HashSet::from_iter(["http://localhost:8080".to_string()]), allowed_methods: HashSet::from_iter( ["GET", "PUT", "POST", "DELETE"] .into_iter() .map(ToString::to_string), ), wildcard_origin: false, max_age: 30, } } } impl Default for super::settings::Database { fn default() -> Self { Self { username: String::new(), password: String::new().into(), host: "localhost".into(), port: 5432, dbname: String::new(), pool_size: 5, connection_timeout: 10, queue_strategy: Default::default(), min_idle: None, max_lifetime: None, } } } impl Default for super::settings::Locker { fn default() -> Self { Self { host: "localhost".into(), host_rs: "localhost".into(), mock_locker: true, basilisk_host: "localhost".into(), locker_signing_key_id: "1".into(), //true or false locker_enabled: true, //Time to live for storage entries in locker ttl_for_storage_in_secs: 60 * 60 * 24 * 365 * 7, decryption_scheme: Default::default(), } } } impl Default for super::settings::SupportedConnectors { fn default() -> Self { Self { wallets: ["klarna", "braintree"].map(Into::into).into(), /* cards: [ "adyen", "authorizedotnet", "braintree", "checkout", "cybersource", "fiserv", "rapyd", "stripe", ] .map(Into::into) .into(), */ } } } impl Default for super::settings::Refund { fn default() -> Self { Self { max_attempts: 10, max_age: 365, } } } impl Default for super::settings::EphemeralConfig { fn default() -> Self { Self { validity: 1 } } } #[cfg(feature = "kv_store")] impl Default for super::settings::DrainerSettings { fn default() -> Self { Self { stream_name: "DRAINER_STREAM".into(), num_partitions: 64, max_read_count: 100, shutdown_interval: 1000, loop_interval: 100, } } } #[cfg(feature = "kv_store")] impl Default for super::settings::KvConfig { fn default() -> Self { Self { ttl: 900, soft_kill: Some(false), } } } #[allow(clippy::derivable_impls)] impl Default for super::settings::ApiKeys { fn default() -> Self { Self { // Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating // hashes of API keys hash_key: String::new().into(), // Specifies the number of days before API key expiry when email reminders should be sent #[cfg(feature = "email")] expiry_reminder_days: vec![7, 3, 1], // Hex-encoded key used for calculating checksum for partial auth #[cfg(feature = "partial-auth")] checksum_auth_key: String::new().into(), // context used for blake3 #[cfg(feature = "partial-auth")] checksum_auth_context: String::new().into(), #[cfg(feature = "partial-auth")] enable_partial_auth: false, } } }
crates/router/src/configs/defaults.rs
router::src::configs::defaults
974
true
// File: crates/router/src/configs/secrets_transformers.rs // Module: router::src::configs::secrets_transformers use common_utils::{errors::CustomResult, ext_traits::AsyncExt}; use hyperswitch_interfaces::secrets_interface::{ secret_handler::SecretsHandler, secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, SecretManagementInterface, SecretsManagementError, }; use crate::settings::{self, Settings}; #[async_trait::async_trait] impl SecretsHandler for settings::Database { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let db = value.get_inner(); let db_password = secret_management_client .get_secret(db.password.clone()) .await?; Ok(value.transition_state(|db| Self { password: db_password, ..db })) } } #[async_trait::async_trait] impl SecretsHandler for settings::Jwekey { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let jwekey = value.get_inner(); let ( vault_encryption_key, rust_locker_encryption_key, vault_private_key, tunnel_private_key, ) = tokio::try_join!( secret_management_client.get_secret(jwekey.vault_encryption_key.clone()), secret_management_client.get_secret(jwekey.rust_locker_encryption_key.clone()), secret_management_client.get_secret(jwekey.vault_private_key.clone()), secret_management_client.get_secret(jwekey.tunnel_private_key.clone()) )?; Ok(value.transition_state(|_| Self { vault_encryption_key, rust_locker_encryption_key, vault_private_key, tunnel_private_key, })) } } #[cfg(feature = "olap")] #[async_trait::async_trait] impl SecretsHandler for settings::ConnectorOnboarding { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let onboarding_config = &value.get_inner().paypal; let (client_id, client_secret, partner_id) = tokio::try_join!( secret_management_client.get_secret(onboarding_config.client_id.clone()), secret_management_client.get_secret(onboarding_config.client_secret.clone()), secret_management_client.get_secret(onboarding_config.partner_id.clone()) )?; Ok(value.transition_state(|onboarding_config| Self { paypal: settings::PayPalOnboarding { client_id, client_secret, partner_id, ..onboarding_config.paypal }, })) } } #[async_trait::async_trait] impl SecretsHandler for settings::ForexApi { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let forex_api = value.get_inner(); let (api_key, fallback_api_key) = tokio::try_join!( secret_management_client.get_secret(forex_api.api_key.clone()), secret_management_client.get_secret(forex_api.fallback_api_key.clone()), )?; Ok(value.transition_state(|forex_api| Self { api_key, fallback_api_key, ..forex_api })) } } #[async_trait::async_trait] impl SecretsHandler for settings::ApiKeys { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let api_keys = value.get_inner(); let hash_key = secret_management_client .get_secret(api_keys.hash_key.clone()) .await?; #[cfg(feature = "email")] let expiry_reminder_days = api_keys.expiry_reminder_days.clone(); #[cfg(feature = "partial-auth")] let enable_partial_auth = api_keys.enable_partial_auth; #[cfg(feature = "partial-auth")] let (checksum_auth_context, checksum_auth_key) = { if enable_partial_auth { let checksum_auth_context = secret_management_client .get_secret(api_keys.checksum_auth_context.clone()) .await?; let checksum_auth_key = secret_management_client .get_secret(api_keys.checksum_auth_key.clone()) .await?; (checksum_auth_context, checksum_auth_key) } else { (String::new().into(), String::new().into()) } }; Ok(value.transition_state(|_| Self { hash_key, #[cfg(feature = "email")] expiry_reminder_days, #[cfg(feature = "partial-auth")] checksum_auth_key, #[cfg(feature = "partial-auth")] checksum_auth_context, #[cfg(feature = "partial-auth")] enable_partial_auth, })) } } #[async_trait::async_trait] impl SecretsHandler for settings::ApplePayDecryptConfig { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let applepay_decrypt_keys = value.get_inner(); let ( apple_pay_ppc, apple_pay_ppc_key, apple_pay_merchant_cert, apple_pay_merchant_cert_key, ) = tokio::try_join!( secret_management_client.get_secret(applepay_decrypt_keys.apple_pay_ppc.clone()), secret_management_client.get_secret(applepay_decrypt_keys.apple_pay_ppc_key.clone()), secret_management_client .get_secret(applepay_decrypt_keys.apple_pay_merchant_cert.clone()), secret_management_client .get_secret(applepay_decrypt_keys.apple_pay_merchant_cert_key.clone()), )?; Ok(value.transition_state(|_| Self { apple_pay_ppc, apple_pay_ppc_key, apple_pay_merchant_cert, apple_pay_merchant_cert_key, })) } } #[async_trait::async_trait] impl SecretsHandler for settings::PazeDecryptConfig { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let paze_decrypt_keys = value.get_inner(); let (paze_private_key, paze_private_key_passphrase) = tokio::try_join!( secret_management_client.get_secret(paze_decrypt_keys.paze_private_key.clone()), secret_management_client .get_secret(paze_decrypt_keys.paze_private_key_passphrase.clone()), )?; Ok(value.transition_state(|_| Self { paze_private_key, paze_private_key_passphrase, })) } } #[async_trait::async_trait] impl SecretsHandler for settings::ApplepayMerchantConfigs { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let applepay_merchant_configs = value.get_inner(); let (merchant_cert, merchant_cert_key, common_merchant_identifier) = tokio::try_join!( secret_management_client.get_secret(applepay_merchant_configs.merchant_cert.clone()), secret_management_client .get_secret(applepay_merchant_configs.merchant_cert_key.clone()), secret_management_client .get_secret(applepay_merchant_configs.common_merchant_identifier.clone()), )?; Ok(value.transition_state(|applepay_merchant_configs| Self { merchant_cert, merchant_cert_key, common_merchant_identifier, ..applepay_merchant_configs })) } } #[async_trait::async_trait] impl SecretsHandler for settings::KeyManagerConfig { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, _secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { #[cfg(feature = "keymanager_mtls")] let keyconfig = value.get_inner(); #[cfg(feature = "keymanager_mtls")] let ca = if keyconfig.enabled { _secret_management_client .get_secret(keyconfig.ca.clone()) .await? } else { keyconfig.ca.clone() }; #[cfg(feature = "keymanager_mtls")] let cert = if keyconfig.enabled { _secret_management_client .get_secret(keyconfig.cert.clone()) .await? } else { keyconfig.ca.clone() }; Ok(value.transition_state(|keyconfig| Self { #[cfg(feature = "keymanager_mtls")] ca, #[cfg(feature = "keymanager_mtls")] cert, ..keyconfig })) } } #[async_trait::async_trait] impl SecretsHandler for settings::Secrets { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let secrets = value.get_inner(); let (jwt_secret, admin_api_key, master_enc_key) = tokio::try_join!( secret_management_client.get_secret(secrets.jwt_secret.clone()), secret_management_client.get_secret(secrets.admin_api_key.clone()), secret_management_client.get_secret(secrets.master_enc_key.clone()) )?; Ok(value.transition_state(|_| Self { jwt_secret, admin_api_key, master_enc_key, })) } } #[async_trait::async_trait] impl SecretsHandler for settings::UserAuthMethodSettings { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let user_auth_methods = value.get_inner(); let encryption_key = secret_management_client .get_secret(user_auth_methods.encryption_key.clone()) .await?; Ok(value.transition_state(|_| Self { encryption_key })) } } #[async_trait::async_trait] impl SecretsHandler for settings::ChatSettings { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let chat_settings = value.get_inner(); let encryption_key = if chat_settings.enabled { secret_management_client .get_secret(chat_settings.encryption_key.clone()) .await? } else { chat_settings.encryption_key.clone() }; Ok(value.transition_state(|chat_settings| Self { encryption_key, ..chat_settings })) } } #[async_trait::async_trait] impl SecretsHandler for settings::NetworkTokenizationService { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let network_tokenization = value.get_inner(); let token_service_api_key = secret_management_client .get_secret(network_tokenization.token_service_api_key.clone()) .await?; let public_key = secret_management_client .get_secret(network_tokenization.public_key.clone()) .await?; let private_key = secret_management_client .get_secret(network_tokenization.private_key.clone()) .await?; let webhook_source_verification_key = secret_management_client .get_secret(network_tokenization.webhook_source_verification_key.clone()) .await?; Ok(value.transition_state(|network_tokenization| Self { public_key, private_key, token_service_api_key, webhook_source_verification_key, ..network_tokenization })) } } /// # Panics /// /// Will panic even if kms decryption fails for at least one field pub(crate) async fn fetch_raw_secrets( conf: Settings<SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> Settings<RawSecret> { #[allow(clippy::expect_used)] let master_database = settings::Database::convert_to_raw_secret(conf.master_database, secret_management_client) .await .expect("Failed to decrypt master database configuration"); #[cfg(feature = "olap")] #[allow(clippy::expect_used)] let analytics = analytics::AnalyticsConfig::convert_to_raw_secret(conf.analytics, secret_management_client) .await .expect("Failed to decrypt analytics configuration"); #[cfg(feature = "olap")] #[allow(clippy::expect_used)] let replica_database = settings::Database::convert_to_raw_secret(conf.replica_database, secret_management_client) .await .expect("Failed to decrypt replica database configuration"); #[allow(clippy::expect_used)] let secrets = settings::Secrets::convert_to_raw_secret(conf.secrets, secret_management_client) .await .expect("Failed to decrypt secrets"); #[allow(clippy::expect_used)] let forex_api = settings::ForexApi::convert_to_raw_secret(conf.forex_api, secret_management_client) .await .expect("Failed to decrypt forex api configs"); #[allow(clippy::expect_used)] let jwekey = settings::Jwekey::convert_to_raw_secret(conf.jwekey, secret_management_client) .await .expect("Failed to decrypt jwekey configs"); #[allow(clippy::expect_used)] let api_keys = settings::ApiKeys::convert_to_raw_secret(conf.api_keys, secret_management_client) .await .expect("Failed to decrypt api_keys configs"); #[cfg(feature = "olap")] #[allow(clippy::expect_used)] let connector_onboarding = settings::ConnectorOnboarding::convert_to_raw_secret( conf.connector_onboarding, secret_management_client, ) .await .expect("Failed to decrypt connector_onboarding configs"); #[allow(clippy::expect_used)] let applepay_decrypt_keys = settings::ApplePayDecryptConfig::convert_to_raw_secret( conf.applepay_decrypt_keys, secret_management_client, ) .await .expect("Failed to decrypt applepay decrypt configs"); #[allow(clippy::expect_used)] let paze_decrypt_keys = if let Some(paze_keys) = conf.paze_decrypt_keys { Some( settings::PazeDecryptConfig::convert_to_raw_secret(paze_keys, secret_management_client) .await .expect("Failed to decrypt paze decrypt configs"), ) } else { None }; #[allow(clippy::expect_used)] let applepay_merchant_configs = settings::ApplepayMerchantConfigs::convert_to_raw_secret( conf.applepay_merchant_configs, secret_management_client, ) .await .expect("Failed to decrypt applepay merchant configs"); #[allow(clippy::expect_used)] let payment_method_auth = settings::PaymentMethodAuth::convert_to_raw_secret( conf.payment_method_auth, secret_management_client, ) .await .expect("Failed to decrypt payment method auth configs"); #[allow(clippy::expect_used)] let key_manager = settings::KeyManagerConfig::convert_to_raw_secret( conf.key_manager, secret_management_client, ) .await .expect("Failed to decrypt keymanager configs"); #[allow(clippy::expect_used)] let user_auth_methods = settings::UserAuthMethodSettings::convert_to_raw_secret( conf.user_auth_methods, secret_management_client, ) .await .expect("Failed to decrypt user_auth_methods configs"); #[allow(clippy::expect_used)] let network_tokenization_service = conf .network_tokenization_service .async_map(|network_tokenization_service| async { settings::NetworkTokenizationService::convert_to_raw_secret( network_tokenization_service, secret_management_client, ) .await .expect("Failed to decrypt network tokenization service configs") }) .await; #[allow(clippy::expect_used)] let chat = settings::ChatSettings::convert_to_raw_secret(conf.chat, secret_management_client) .await .expect("Failed to decrypt chat configs"); #[allow(clippy::expect_used)] let superposition = external_services::superposition::SuperpositionClientConfig::convert_to_raw_secret( conf.superposition, secret_management_client, ) .await .expect("Failed to decrypt superposition config"); Settings { server: conf.server, chat, master_database, redis: conf.redis, log: conf.log, #[cfg(feature = "kv_store")] drainer: conf.drainer, encryption_management: conf.encryption_management, secrets_management: conf.secrets_management, proxy: conf.proxy, env: conf.env, key_manager, #[cfg(feature = "olap")] replica_database, secrets, fallback_merchant_ids_api_key_auth: conf.fallback_merchant_ids_api_key_auth, locker: conf.locker, connectors: conf.connectors, forex_api, refund: conf.refund, eph_key: conf.eph_key, scheduler: conf.scheduler, jwekey, webhooks: conf.webhooks, pm_filters: conf.pm_filters, payout_method_filters: conf.payout_method_filters, bank_config: conf.bank_config, api_keys, file_storage: conf.file_storage, tokenization: conf.tokenization, connector_customer: conf.connector_customer, #[cfg(feature = "dummy_connector")] dummy_connector: conf.dummy_connector, #[cfg(feature = "email")] email: conf.email, user: conf.user, mandates: conf.mandates, zero_mandates: conf.zero_mandates, network_transaction_id_supported_connectors: conf .network_transaction_id_supported_connectors, list_dispute_supported_connectors: conf.list_dispute_supported_connectors, required_fields: conf.required_fields, delayed_session_response: conf.delayed_session_response, webhook_source_verification_call: conf.webhook_source_verification_call, billing_connectors_payment_sync: conf.billing_connectors_payment_sync, billing_connectors_invoice_sync: conf.billing_connectors_invoice_sync, payment_method_auth, connector_request_reference_id_config: conf.connector_request_reference_id_config, #[cfg(feature = "payouts")] payouts: conf.payouts, applepay_decrypt_keys, paze_decrypt_keys, google_pay_decrypt_keys: conf.google_pay_decrypt_keys, multiple_api_version_supported_connectors: conf.multiple_api_version_supported_connectors, applepay_merchant_configs, lock_settings: conf.lock_settings, temp_locker_enable_config: conf.temp_locker_enable_config, generic_link: conf.generic_link, payment_link: conf.payment_link, #[cfg(feature = "olap")] analytics, #[cfg(feature = "olap")] opensearch: conf.opensearch, #[cfg(feature = "kv_store")] kv_config: conf.kv_config, #[cfg(feature = "frm")] frm: conf.frm, #[cfg(feature = "olap")] report_download_config: conf.report_download_config, events: conf.events, #[cfg(feature = "olap")] connector_onboarding, cors: conf.cors, unmasked_headers: conf.unmasked_headers, saved_payment_methods: conf.saved_payment_methods, multitenancy: conf.multitenancy, user_auth_methods, decision: conf.decision, locker_based_open_banking_connectors: conf.locker_based_open_banking_connectors, grpc_client: conf.grpc_client, crm: conf.crm, #[cfg(feature = "v2")] cell_information: conf.cell_information, network_tokenization_supported_card_networks: conf .network_tokenization_supported_card_networks, network_tokenization_service, network_tokenization_supported_connectors: conf.network_tokenization_supported_connectors, theme: conf.theme, platform: conf.platform, l2_l3_data_config: conf.l2_l3_data_config, authentication_providers: conf.authentication_providers, open_router: conf.open_router, #[cfg(feature = "v2")] revenue_recovery: conf.revenue_recovery, debit_routing_config: conf.debit_routing_config, clone_connector_allowlist: conf.clone_connector_allowlist, merchant_id_auth: conf.merchant_id_auth, internal_merchant_id_profile_id_auth: conf.internal_merchant_id_profile_id_auth, infra_values: conf.infra_values, enhancement: conf.enhancement, proxy_status_mapping: conf.proxy_status_mapping, internal_services: conf.internal_services, superposition, comparison_service: conf.comparison_service, } }
crates/router/src/configs/secrets_transformers.rs
router::src::configs::secrets_transformers
4,552
true
// File: crates/router/src/configs/settings.rs // Module: router::src::configs::settings use std::{ collections::{HashMap, HashSet}, path::PathBuf, sync::Arc, }; #[cfg(feature = "olap")] use analytics::{opensearch::OpenSearchConfig, ReportConfig}; use api_models::enums; use common_utils::{ ext_traits::ConfigExt, id_type, types::{user::EmailThemeConfig, Url}, }; use config::{Environment, File}; use error_stack::ResultExt; #[cfg(feature = "email")] use external_services::email::EmailSettings; use external_services::{ crm::CrmManagerConfig, file_storage::FileStorageConfig, grpc_client::GrpcClientSettings, managers::{ encryption_management::EncryptionManagementConfig, secrets_management::SecretsManagementConfig, }, superposition::SuperpositionClientConfig, }; pub use hyperswitch_interfaces::{ configs::{ Connectors, GlobalTenant, InternalMerchantIdProfileIdAuthSettings, InternalServicesConfig, Tenant, TenantUserConfig, }, secrets_interface::secret_state::{ RawSecret, SecretState, SecretStateContainer, SecuredSecret, }, types::Proxy, }; use masking::Secret; pub use payment_methods::configs::settings::{ BankRedirectConfig, BanksVector, ConnectorBankNames, ConnectorFields, EligiblePaymentMethods, Mandates, PaymentMethodAuth, PaymentMethodType, RequiredFieldFinal, RequiredFields, SupportedConnectorsForMandate, SupportedPaymentMethodTypesForMandate, SupportedPaymentMethodsForMandate, ZeroMandates, }; use redis_interface::RedisSettings; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use rust_decimal::Decimal; use scheduler::SchedulerSettings; use serde::Deserialize; use storage_impl::config::QueueStrategy; #[cfg(feature = "olap")] use crate::analytics::{AnalyticsConfig, AnalyticsProvider}; #[cfg(feature = "v2")] use crate::types::storage::revenue_recovery; use crate::{ configs, core::errors::{ApplicationError, ApplicationResult}, env::{self, Env}, events::EventsConfig, routes::app, AppState, }; pub const REQUIRED_FIELDS_CONFIG_FILE: &str = "payment_required_fields_v2.toml"; #[derive(clap::Parser, Default)] #[cfg_attr(feature = "vergen", command(version = router_env::version!()))] pub struct CmdLineConf { /// Config file. /// Application will look for "config/config.toml" if this option isn't specified. #[arg(short = 'f', long, value_name = "FILE")] pub config_path: Option<PathBuf>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct Settings<S: SecretState> { pub server: Server, pub proxy: Proxy, pub env: Env, pub chat: SecretStateContainer<ChatSettings, S>, pub master_database: SecretStateContainer<Database, S>, #[cfg(feature = "olap")] pub replica_database: SecretStateContainer<Database, S>, pub redis: RedisSettings, pub log: Log, pub secrets: SecretStateContainer<Secrets, S>, pub fallback_merchant_ids_api_key_auth: Option<FallbackMerchantIds>, pub locker: Locker, pub key_manager: SecretStateContainer<KeyManagerConfig, S>, pub connectors: Connectors, pub forex_api: SecretStateContainer<ForexApi, S>, pub refund: Refund, pub eph_key: EphemeralConfig, pub scheduler: Option<SchedulerSettings>, #[cfg(feature = "kv_store")] pub drainer: DrainerSettings, pub jwekey: SecretStateContainer<Jwekey, S>, pub webhooks: WebhooksSettings, pub pm_filters: ConnectorFilters, pub bank_config: BankRedirectConfig, pub api_keys: SecretStateContainer<ApiKeys, S>, pub file_storage: FileStorageConfig, pub encryption_management: EncryptionManagementConfig, pub secrets_management: SecretsManagementConfig, pub tokenization: TokenizationConfig, pub connector_customer: ConnectorCustomer, #[cfg(feature = "dummy_connector")] pub dummy_connector: DummyConnector, #[cfg(feature = "email")] pub email: EmailSettings, pub user: UserSettings, pub crm: CrmManagerConfig, pub cors: CorsSettings, pub mandates: Mandates, pub zero_mandates: ZeroMandates, pub network_transaction_id_supported_connectors: NetworkTransactionIdSupportedConnectors, pub list_dispute_supported_connectors: ListDiputeSupportedConnectors, pub required_fields: RequiredFields, pub delayed_session_response: DelayedSessionConfig, pub webhook_source_verification_call: WebhookSourceVerificationCall, pub billing_connectors_payment_sync: BillingConnectorPaymentsSyncCall, pub billing_connectors_invoice_sync: BillingConnectorInvoiceSyncCall, pub payment_method_auth: SecretStateContainer<PaymentMethodAuth, S>, pub connector_request_reference_id_config: ConnectorRequestReferenceIdConfig, #[cfg(feature = "payouts")] pub payouts: Payouts, pub payout_method_filters: ConnectorFilters, pub l2_l3_data_config: L2L3DataConfig, pub debit_routing_config: DebitRoutingConfig, pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConfig, S>, pub paze_decrypt_keys: Option<SecretStateContainer<PazeDecryptConfig, S>>, pub google_pay_decrypt_keys: Option<GooglePayDecryptConfig>, pub multiple_api_version_supported_connectors: MultipleApiVersionSupportedConnectors, pub applepay_merchant_configs: SecretStateContainer<ApplepayMerchantConfigs, S>, pub lock_settings: LockSettings, pub temp_locker_enable_config: TempLockerEnableConfig, pub generic_link: GenericLink, pub payment_link: PaymentLink, #[cfg(feature = "olap")] pub analytics: SecretStateContainer<AnalyticsConfig, S>, #[cfg(feature = "kv_store")] pub kv_config: KvConfig, #[cfg(feature = "frm")] pub frm: Frm, #[cfg(feature = "olap")] pub report_download_config: ReportConfig, #[cfg(feature = "olap")] pub opensearch: OpenSearchConfig, pub events: EventsConfig, #[cfg(feature = "olap")] pub connector_onboarding: SecretStateContainer<ConnectorOnboarding, S>, pub unmasked_headers: UnmaskedHeaders, pub multitenancy: Multitenancy, pub saved_payment_methods: EligiblePaymentMethods, pub user_auth_methods: SecretStateContainer<UserAuthMethodSettings, S>, pub decision: Option<DecisionConfig>, pub locker_based_open_banking_connectors: LockerBasedRecipientConnectorList, pub grpc_client: GrpcClientSettings, #[cfg(feature = "v2")] pub cell_information: CellInformation, pub network_tokenization_supported_card_networks: NetworkTokenizationSupportedCardNetworks, pub network_tokenization_service: Option<SecretStateContainer<NetworkTokenizationService, S>>, pub network_tokenization_supported_connectors: NetworkTokenizationSupportedConnectors, pub theme: ThemeSettings, pub platform: Platform, pub authentication_providers: AuthenticationProviders, pub open_router: OpenRouter, #[cfg(feature = "v2")] pub revenue_recovery: revenue_recovery::RevenueRecoverySettings, pub clone_connector_allowlist: Option<CloneConnectorAllowlistConfig>, pub merchant_id_auth: MerchantIdAuthSettings, pub internal_merchant_id_profile_id_auth: InternalMerchantIdProfileIdAuthSettings, #[serde(default)] pub infra_values: Option<HashMap<String, String>>, #[serde(default)] pub enhancement: Option<HashMap<String, String>>, pub superposition: SecretStateContainer<SuperpositionClientConfig, S>, pub proxy_status_mapping: ProxyStatusMapping, pub internal_services: InternalServicesConfig, pub comparison_service: Option<ComparisonServiceConfig>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct DebitRoutingConfig { #[serde(deserialize_with = "deserialize_hashmap")] pub connector_supported_debit_networks: HashMap<enums::Connector, HashSet<enums::CardNetwork>>, #[serde(deserialize_with = "deserialize_hashset")] pub supported_currencies: HashSet<enums::Currency>, #[serde(deserialize_with = "deserialize_hashset")] pub supported_connectors: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct OpenRouter { pub dynamic_routing_enabled: bool, pub static_routing_enabled: bool, pub url: String, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct CloneConnectorAllowlistConfig { #[serde(deserialize_with = "deserialize_merchant_ids")] pub merchant_ids: HashSet<id_type::MerchantId>, #[serde(deserialize_with = "deserialize_hashset")] pub connector_names: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone)] pub struct ComparisonServiceConfig { pub url: Url, pub enabled: bool, pub timeout_secs: Option<u64>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct Platform { pub enabled: bool, pub allow_connected_merchants: bool, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct ChatSettings { pub enabled: bool, pub hyperswitch_ai_host: String, pub encryption_key: Secret<String>, } #[derive(Debug, Clone, Default, Deserialize)] pub struct Multitenancy { pub tenants: TenantConfig, pub enabled: bool, pub global_tenant: GlobalTenant, } impl Multitenancy { pub fn get_tenants(&self) -> &HashMap<id_type::TenantId, Tenant> { &self.tenants.0 } pub fn get_tenant_ids(&self) -> Vec<id_type::TenantId> { self.tenants .0 .values() .map(|tenant| tenant.tenant_id.clone()) .collect() } pub fn get_tenant(&self, tenant_id: &id_type::TenantId) -> Option<&Tenant> { self.tenants.0.get(tenant_id) } } #[derive(Debug, Deserialize, Clone, Default)] pub struct DecisionConfig { pub base_url: String, } #[derive(Debug, Clone, Default)] pub struct TenantConfig(pub HashMap<id_type::TenantId, Tenant>); impl TenantConfig { /// # Panics /// /// Panics if Failed to create event handler pub async fn get_store_interface_map( &self, storage_impl: &app::StorageImpl, conf: &configs::Settings, cache_store: Arc<storage_impl::redis::RedisStore>, testable: bool, ) -> HashMap<id_type::TenantId, Box<dyn app::StorageInterface>> { #[allow(clippy::expect_used)] let event_handler = conf .events .get_event_handler() .await .expect("Failed to create event handler"); futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async { let store = AppState::get_store_interface( storage_impl, &event_handler, conf, tenant, cache_store.clone(), testable, ) .await .get_storage_interface(); (tenant_name.clone(), store) })) .await .into_iter() .collect() } /// # Panics /// /// Panics if Failed to create event handler pub async fn get_accounts_store_interface_map( &self, storage_impl: &app::StorageImpl, conf: &configs::Settings, cache_store: Arc<storage_impl::redis::RedisStore>, testable: bool, ) -> HashMap<id_type::TenantId, Box<dyn app::AccountsStorageInterface>> { #[allow(clippy::expect_used)] let event_handler = conf .events .get_event_handler() .await .expect("Failed to create event handler"); futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async { let store = AppState::get_store_interface( storage_impl, &event_handler, conf, tenant, cache_store.clone(), testable, ) .await .get_accounts_storage_interface(); (tenant_name.clone(), store) })) .await .into_iter() .collect() } #[cfg(feature = "olap")] pub async fn get_pools_map( &self, analytics_config: &AnalyticsConfig, ) -> HashMap<id_type::TenantId, AnalyticsProvider> { futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async { ( tenant_name.clone(), AnalyticsProvider::from_conf(analytics_config, tenant).await, ) })) .await .into_iter() .collect() } } #[derive(Debug, Deserialize, Clone, Default)] pub struct L2L3DataConfig { pub enabled: bool, } #[derive(Debug, Deserialize, Clone, Default)] pub struct UnmaskedHeaders { #[serde(deserialize_with = "deserialize_hashset")] pub keys: HashSet<String>, } #[cfg(feature = "frm")] #[derive(Debug, Deserialize, Clone, Default)] pub struct Frm { pub enabled: bool, } #[derive(Debug, Deserialize, Clone)] pub struct KvConfig { pub ttl: u32, pub soft_kill: Option<bool>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct KeyManagerConfig { pub enabled: bool, pub url: String, #[cfg(feature = "keymanager_mtls")] pub cert: Secret<String>, #[cfg(feature = "keymanager_mtls")] pub ca: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct GenericLink { pub payment_method_collect: GenericLinkEnvConfig, pub payout_link: GenericLinkEnvConfig, } #[derive(Debug, Deserialize, Clone)] pub struct GenericLinkEnvConfig { pub sdk_url: url::Url, pub expiry: u32, pub ui_config: GenericLinkEnvUiConfig, #[serde(deserialize_with = "deserialize_hashmap")] pub enabled_payment_methods: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, } impl Default for GenericLinkEnvConfig { fn default() -> Self { Self { #[allow(clippy::expect_used)] sdk_url: url::Url::parse("http://localhost:9050/HyperLoader.js") .expect("Failed to parse default SDK URL"), expiry: 900, ui_config: GenericLinkEnvUiConfig::default(), enabled_payment_methods: HashMap::default(), } } } #[derive(Debug, Deserialize, Clone)] pub struct GenericLinkEnvUiConfig { pub logo: url::Url, pub merchant_name: Secret<String>, pub theme: String, } #[allow(clippy::panic)] impl Default for GenericLinkEnvUiConfig { fn default() -> Self { Self { #[allow(clippy::expect_used)] logo: url::Url::parse("https://hyperswitch.io/favicon.ico") .expect("Failed to parse default logo URL"), merchant_name: Secret::new("HyperSwitch".to_string()), theme: "#4285F4".to_string(), } } } #[derive(Debug, Deserialize, Clone)] pub struct PaymentLink { pub sdk_url: url::Url, } impl Default for PaymentLink { fn default() -> Self { Self { #[allow(clippy::expect_used)] sdk_url: url::Url::parse("https://beta.hyperswitch.io/v0/HyperLoader.js") .expect("Failed to parse default SDK URL"), } } } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct ForexApi { pub api_key: Secret<String>, pub fallback_api_key: Secret<String>, pub data_expiration_delay_in_seconds: u32, pub redis_lock_timeout_in_seconds: u32, pub redis_ttl_in_seconds: u32, } #[derive(Debug, Deserialize, Clone, Default)] pub struct DefaultExchangeRates { pub base_currency: String, pub conversion: HashMap<String, Conversion>, pub timestamp: i64, } #[derive(Debug, Deserialize, Clone, Default)] pub struct Conversion { #[serde(with = "rust_decimal::serde::str")] pub to_factor: Decimal, #[serde(with = "rust_decimal::serde::str")] pub from_factor: Decimal, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct ApplepayMerchantConfigs { pub merchant_cert: Secret<String>, pub merchant_cert_key: Secret<String>, pub common_merchant_identifier: Secret<String>, pub applepay_endpoint: String, } #[derive(Debug, Deserialize, Clone, Default)] pub struct MultipleApiVersionSupportedConnectors { #[serde(deserialize_with = "deserialize_hashset")] pub supported_connectors: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] pub struct TokenizationConfig(pub HashMap<String, PaymentMethodTokenFilter>); #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] pub struct TempLockerEnableConfig(pub HashMap<String, TempLockerEnablePaymentMethodFilter>); #[derive(Debug, Deserialize, Clone, Default)] pub struct ConnectorCustomer { #[cfg(feature = "payouts")] #[serde(deserialize_with = "deserialize_hashset")] pub payout_connector_list: HashSet<enums::PayoutConnectors>, } #[cfg(feature = "dummy_connector")] #[derive(Debug, Deserialize, Clone, Default)] pub struct DummyConnector { pub enabled: bool, pub payment_ttl: i64, pub payment_duration: u64, pub payment_tolerance: u64, pub payment_retrieve_duration: u64, pub payment_retrieve_tolerance: u64, pub payment_complete_duration: i64, pub payment_complete_tolerance: i64, pub refund_ttl: i64, pub refund_duration: u64, pub refund_tolerance: u64, pub refund_retrieve_duration: u64, pub refund_retrieve_tolerance: u64, pub authorize_ttl: i64, pub assets_base_url: String, pub default_return_url: String, pub slack_invite_url: String, pub discord_invite_url: String, } #[derive(Debug, Deserialize, Clone)] pub struct CorsSettings { #[serde(default, deserialize_with = "deserialize_hashset")] pub origins: HashSet<String>, #[serde(default)] pub wildcard_origin: bool, pub max_age: usize, #[serde(deserialize_with = "deserialize_hashset")] pub allowed_methods: HashSet<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct AuthenticationProviders { #[serde(deserialize_with = "deserialize_connector_list")] pub click_to_pay: HashSet<enums::Connector>, } fn deserialize_connector_list<'a, D>(deserializer: D) -> Result<HashSet<enums::Connector>, D::Error> where D: serde::Deserializer<'a>, { use serde::de::Error; #[derive(Deserialize)] struct Wrapper { connector_list: String, } let wrapper = Wrapper::deserialize(deserializer)?; wrapper .connector_list .split(',') .map(|s| s.trim().parse().map_err(D::Error::custom)) .collect() } #[derive(Debug, Deserialize, Clone, Default)] pub struct NetworkTransactionIdSupportedConnectors { #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<enums::Connector>, } /// Connectors that support only dispute list API for syncing disputes with Hyperswitch #[derive(Debug, Deserialize, Clone, Default)] pub struct ListDiputeSupportedConnectors { #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct NetworkTokenizationSupportedCardNetworks { #[serde(deserialize_with = "deserialize_hashset")] pub card_networks: HashSet<enums::CardNetwork>, } #[derive(Debug, Deserialize, Clone)] pub struct NetworkTokenizationService { pub generate_token_url: url::Url, pub fetch_token_url: url::Url, pub token_service_api_key: Secret<String>, pub public_key: Secret<String>, pub private_key: Secret<String>, pub key_id: String, pub delete_token_url: url::Url, pub check_token_status_url: url::Url, pub webhook_source_verification_key: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct PaymentMethodTokenFilter { #[serde(deserialize_with = "deserialize_hashset")] pub payment_method: HashSet<diesel_models::enums::PaymentMethod>, pub payment_method_type: Option<PaymentMethodTypeTokenFilter>, pub long_lived_token: bool, pub apple_pay_pre_decrypt_flow: Option<ApplePayPreDecryptFlow>, pub google_pay_pre_decrypt_flow: Option<GooglePayPreDecryptFlow>, pub flow: Option<PaymentFlow>, } #[derive(Debug, Deserialize, Clone, PartialEq)] #[serde(deny_unknown_fields, rename_all = "snake_case")] pub enum PaymentFlow { Mandates, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(deny_unknown_fields, rename_all = "snake_case")] pub enum ApplePayPreDecryptFlow { #[default] ConnectorTokenization, NetworkTokenization, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(deny_unknown_fields, rename_all = "snake_case")] pub enum GooglePayPreDecryptFlow { #[default] ConnectorTokenization, NetworkTokenization, } #[derive(Debug, Deserialize, Clone, Default)] pub struct TempLockerEnablePaymentMethodFilter { #[serde(deserialize_with = "deserialize_hashset")] pub payment_method: HashSet<diesel_models::enums::PaymentMethod>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde( deny_unknown_fields, tag = "type", content = "list", rename_all = "snake_case" )] pub enum PaymentMethodTypeTokenFilter { #[serde(deserialize_with = "deserialize_hashset")] EnableOnly(HashSet<diesel_models::enums::PaymentMethodType>), #[serde(deserialize_with = "deserialize_hashset")] DisableOnly(HashSet<diesel_models::enums::PaymentMethodType>), #[default] AllAccepted, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] pub struct ConnectorFilters(pub HashMap<String, PaymentMethodFilters>); #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] pub struct PaymentMethodFilters(pub HashMap<PaymentMethodFilterKey, CurrencyCountryFlowFilter>); #[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash)] #[serde(untagged)] pub enum PaymentMethodFilterKey { PaymentMethodType(enums::PaymentMethodType), CardNetwork(enums::CardNetwork), } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct CurrencyCountryFlowFilter { #[serde(deserialize_with = "deserialize_optional_hashset")] pub currency: Option<HashSet<enums::Currency>>, #[serde(deserialize_with = "deserialize_optional_hashset")] pub country: Option<HashSet<enums::CountryAlpha2>>, pub not_available_flows: Option<NotAvailableFlows>, } #[derive(Debug, Deserialize, Copy, Clone, Default)] #[serde(default)] pub struct NotAvailableFlows { pub capture_method: Option<enums::CaptureMethod>, } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Clone)] #[cfg_attr(feature = "v2", derive(Default))] // Configs are read from the config file in config/payout_required_fields.toml pub struct PayoutRequiredFields(pub HashMap<enums::PaymentMethod, PaymentMethodType>); #[derive(Debug, Default, Deserialize, Clone)] #[serde(default)] pub struct Secrets { pub jwt_secret: Secret<String>, pub admin_api_key: Secret<String>, pub master_enc_key: Secret<String>, } #[derive(Debug, Default, Deserialize, Clone)] #[serde(default)] pub struct FallbackMerchantIds { #[serde(deserialize_with = "deserialize_merchant_ids")] pub merchant_ids: HashSet<id_type::MerchantId>, } #[derive(Debug, Clone, Default, Deserialize)] pub struct UserSettings { pub password_validity_in_days: u16, pub two_factor_auth_expiry_in_secs: i64, pub totp_issuer_name: String, pub base_url: String, pub force_two_factor_auth: bool, pub force_cookies: bool, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Locker { pub host: String, pub host_rs: String, pub mock_locker: bool, pub basilisk_host: String, pub locker_signing_key_id: String, pub locker_enabled: bool, pub ttl_for_storage_in_secs: i64, pub decryption_scheme: DecryptionScheme, } #[derive(Debug, Deserialize, Clone, Default)] pub enum DecryptionScheme { #[default] #[serde(rename = "RSA-OAEP")] RsaOaep, #[serde(rename = "RSA-OAEP-256")] RsaOaep256, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Refund { pub max_attempts: usize, pub max_age: i64, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct EphemeralConfig { pub validity: i64, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct Jwekey { pub vault_encryption_key: Secret<String>, pub rust_locker_encryption_key: Secret<String>, pub vault_private_key: Secret<String>, pub tunnel_private_key: Secret<String>, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Server { pub port: u16, pub workers: usize, pub host: String, pub request_body_limit: usize, pub shutdown_timeout: u64, #[cfg(feature = "tls")] pub tls: Option<ServerTls>, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Database { pub username: String, pub password: Secret<String>, pub host: String, pub port: u16, pub dbname: String, pub pool_size: u32, pub connection_timeout: u64, pub queue_strategy: QueueStrategy, pub min_idle: Option<u32>, pub max_lifetime: Option<u64>, } impl From<Database> for storage_impl::config::Database { fn from(val: Database) -> Self { Self { username: val.username, password: val.password, host: val.host, port: val.port, dbname: val.dbname, pool_size: val.pool_size, connection_timeout: val.connection_timeout, queue_strategy: val.queue_strategy, min_idle: val.min_idle, max_lifetime: val.max_lifetime, } } } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct SupportedConnectors { pub wallets: Vec<String>, } #[cfg(feature = "kv_store")] #[derive(Debug, Clone, Deserialize)] #[serde(default)] pub struct DrainerSettings { pub stream_name: String, pub num_partitions: u8, pub max_read_count: u64, pub shutdown_interval: u32, // in milliseconds pub loop_interval: u32, // in milliseconds } #[derive(Debug, Clone, Default, Deserialize)] #[serde(default)] pub struct MerchantIdAuthSettings { pub merchant_id_auth_enabled: bool, } #[derive(Debug, Clone, Default, Deserialize)] #[serde(default)] pub struct ProxyStatusMapping { pub proxy_connector_http_status_code: bool, } #[derive(Debug, Clone, Default, Deserialize)] #[serde(default)] pub struct WebhooksSettings { pub outgoing_enabled: bool, pub ignore_error: WebhookIgnoreErrorSettings, pub redis_lock_expiry_seconds: u32, } #[derive(Debug, Clone, Deserialize, Default)] #[serde(default)] pub struct WebhookIgnoreErrorSettings { pub event_type: Option<bool>, pub payment_not_found: Option<bool>, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct ApiKeys { /// Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating /// hashes of API keys pub hash_key: Secret<String>, // Specifies the number of days before API key expiry when email reminders should be sent #[cfg(feature = "email")] pub expiry_reminder_days: Vec<u8>, #[cfg(feature = "partial-auth")] pub checksum_auth_context: Secret<String>, #[cfg(feature = "partial-auth")] pub checksum_auth_key: Secret<String>, #[cfg(feature = "partial-auth")] pub enable_partial_auth: bool, } #[derive(Debug, Deserialize, Clone, Default)] pub struct DelayedSessionConfig { #[serde(deserialize_with = "deserialize_hashset")] pub connectors_with_delayed_session_response: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct WebhookSourceVerificationCall { #[serde(deserialize_with = "deserialize_hashset")] pub connectors_with_webhook_source_verification_call: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct BillingConnectorPaymentsSyncCall { #[serde(deserialize_with = "deserialize_hashset")] pub billing_connectors_which_require_payment_sync: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct BillingConnectorInvoiceSyncCall { #[serde(deserialize_with = "deserialize_hashset")] pub billing_connectors_which_requires_invoice_sync_call: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct ApplePayDecryptConfig { pub apple_pay_ppc: Secret<String>, pub apple_pay_ppc_key: Secret<String>, pub apple_pay_merchant_cert: Secret<String>, pub apple_pay_merchant_cert_key: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct PazeDecryptConfig { pub paze_private_key: Secret<String>, pub paze_private_key_passphrase: Secret<String>, } #[derive(Debug, Deserialize, Clone)] pub struct GooglePayDecryptConfig { pub google_pay_root_signing_keys: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct LockerBasedRecipientConnectorList { #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct ConnectorRequestReferenceIdConfig { pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<id_type::MerchantId>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct UserAuthMethodSettings { pub encryption_key: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct NetworkTokenizationSupportedConnectors { #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<enums::Connector>, } impl Settings<SecuredSecret> { pub fn new() -> ApplicationResult<Self> { Self::with_config_path(None) } pub fn with_config_path(config_path: Option<PathBuf>) -> ApplicationResult<Self> { // Configuration values are picked up in the following priority order (1 being least // priority): // 1. Defaults from the implementation of the `Default` trait. // 2. Values from config file. The config file accessed depends on the environment // specified by the `RUN_ENV` environment variable. `RUN_ENV` can be one of // `development`, `sandbox` or `production`. If nothing is specified for `RUN_ENV`, // `/config/development.toml` file is read. // 3. Environment variables prefixed with `ROUTER` and each level separated by double // underscores. // // Values in config file override the defaults in `Default` trait, and the values set using // environment variables override both the defaults and the config file values. let environment = env::which(); let config_path = router_env::Config::config_path(&environment.to_string(), config_path); let config = router_env::Config::builder(&environment.to_string()) .change_context(ApplicationError::ConfigurationError)? .add_source(File::from(config_path).required(false)); #[cfg(feature = "v2")] let config = { let required_fields_config_file = router_env::Config::get_config_directory().join(REQUIRED_FIELDS_CONFIG_FILE); config.add_source(File::from(required_fields_config_file).required(false)) }; let config = config .add_source( Environment::with_prefix("ROUTER") .try_parsing(true) .separator("__") .list_separator(",") .with_list_parse_key("log.telemetry.route_to_trace") .with_list_parse_key("redis.cluster_urls") .with_list_parse_key("events.kafka.brokers") .with_list_parse_key("connectors.supported.wallets") .with_list_parse_key("connector_request_reference_id_config.merchant_ids_send_payment_id_as_connector_request_id"), ) .build() .change_context(ApplicationError::ConfigurationError)?; let mut settings: Self = serde_path_to_error::deserialize(config) .attach_printable("Unable to deserialize application configuration") .change_context(ApplicationError::ConfigurationError)?; #[cfg(feature = "v1")] { settings.required_fields = RequiredFields::new(&settings.bank_config); } Ok(settings) } pub fn validate(&self) -> ApplicationResult<()> { self.server.validate()?; self.master_database.get_inner().validate()?; #[cfg(feature = "olap")] self.replica_database.get_inner().validate()?; // The logger may not yet be initialized when validating the application configuration #[allow(clippy::print_stderr)] self.redis.validate().map_err(|error| { eprintln!("{error}"); ApplicationError::InvalidConfigurationValueError("Redis configuration".into()) })?; if self.log.file.enabled { if self.log.file.file_name.is_default_or_empty() { return Err(error_stack::Report::from( ApplicationError::InvalidConfigurationValueError( "log file name must not be empty".into(), ), )); } if self.log.file.path.is_default_or_empty() { return Err(error_stack::Report::from( ApplicationError::InvalidConfigurationValueError( "log directory path must not be empty".into(), ), )); } } self.secrets.get_inner().validate()?; self.locker.validate()?; self.connectors.validate("connectors")?; self.chat.get_inner().validate()?; self.cors.validate()?; self.scheduler .as_ref() .map(|scheduler_settings| scheduler_settings.validate()) .transpose()?; #[cfg(feature = "kv_store")] self.drainer.validate()?; self.api_keys.get_inner().validate()?; self.file_storage .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; self.crm .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; self.lock_settings.validate()?; self.events.validate()?; #[cfg(feature = "olap")] self.opensearch.validate()?; self.encryption_management .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; self.secrets_management .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; self.generic_link.payment_method_collect.validate()?; self.generic_link.payout_link.validate()?; #[cfg(feature = "v2")] self.cell_information.validate()?; self.network_tokenization_service .as_ref() .map(|x| x.get_inner().validate()) .transpose()?; self.paze_decrypt_keys .as_ref() .map(|x| x.get_inner().validate()) .transpose()?; self.google_pay_decrypt_keys .as_ref() .map(|x| x.validate()) .transpose()?; self.key_manager.get_inner().validate()?; #[cfg(feature = "email")] self.email .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; self.theme .storage .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; self.platform.validate()?; self.open_router.validate()?; // Validate gRPC client settings #[cfg(feature = "revenue_recovery")] self.grpc_client .recovery_decider_client .as_ref() .map(|config| config.validate()) .transpose() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; self.superposition .get_inner() .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; Ok(()) } } impl Settings<RawSecret> { #[cfg(feature = "kv_store")] pub fn is_kv_soft_kill_mode(&self) -> bool { self.kv_config.soft_kill.unwrap_or(false) } #[cfg(not(feature = "kv_store"))] pub fn is_kv_soft_kill_mode(&self) -> bool { false } } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Clone, Default)] pub struct Payouts { pub payout_eligibility: bool, #[serde(default)] pub required_fields: PayoutRequiredFields, } #[derive(Debug, Clone, Default)] pub struct LockSettings { pub redis_lock_expiry_seconds: u32, pub delay_between_retries_in_milliseconds: u32, pub lock_retries: u32, } impl<'de> Deserialize<'de> for LockSettings { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Inner { redis_lock_expiry_seconds: u32, delay_between_retries_in_milliseconds: u32, } let Inner { redis_lock_expiry_seconds, delay_between_retries_in_milliseconds, } = Inner::deserialize(deserializer)?; let redis_lock_expiry_milliseconds = redis_lock_expiry_seconds * 1000; Ok(Self { redis_lock_expiry_seconds, delay_between_retries_in_milliseconds, lock_retries: redis_lock_expiry_milliseconds / delay_between_retries_in_milliseconds, }) } } #[cfg(feature = "olap")] #[derive(Debug, Deserialize, Clone, Default)] pub struct ConnectorOnboarding { pub paypal: PayPalOnboarding, } #[cfg(feature = "olap")] #[derive(Debug, Deserialize, Clone, Default)] pub struct PayPalOnboarding { pub client_id: Secret<String>, pub client_secret: Secret<String>, pub partner_id: Secret<String>, pub enabled: bool, } #[cfg(feature = "tls")] #[derive(Debug, Deserialize, Clone)] pub struct ServerTls { /// Port to host the TLS secure server on pub port: u16, /// Use a different host (optional) (defaults to the host provided in [`Server`] config) pub host: Option<String>, /// private key file path associated with TLS (path to the private key file (`pem` format)) pub private_key: PathBuf, /// certificate file associated with TLS (path to the certificate file (`pem` format)) pub certificate: PathBuf, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Deserialize, PartialEq, Eq)] pub struct CellInformation { pub id: id_type::CellId, } #[cfg(feature = "v2")] impl Default for CellInformation { fn default() -> Self { // We provide a static default cell id for constructing application settings. // This will only panic at application startup if we're unable to construct the default, // around the time of deserializing application settings. // And a panic at application startup is considered acceptable. #[allow(clippy::expect_used)] let cell_id = id_type::CellId::from_string("defid").expect("Failed to create a default for Cell Id"); Self { id: cell_id } } } #[derive(Debug, Deserialize, Clone, Default)] pub struct ThemeSettings { pub storage: FileStorageConfig, pub email_config: EmailThemeConfig, } fn deserialize_hashmap_inner<K, V>( value: HashMap<String, String>, ) -> Result<HashMap<K, HashSet<V>>, String> where K: Eq + std::str::FromStr + std::hash::Hash, V: Eq + std::str::FromStr + std::hash::Hash, <K as std::str::FromStr>::Err: std::fmt::Display, <V as std::str::FromStr>::Err: std::fmt::Display, { let (values, errors) = value .into_iter() .map( |(k, v)| match (K::from_str(k.trim()), deserialize_hashset_inner(v)) { (Err(error), _) => Err(format!( "Unable to deserialize `{}` as `{}`: {error}", k, std::any::type_name::<K>() )), (_, Err(error)) => Err(error), (Ok(key), Ok(value)) => Ok((key, value)), }, ) .fold( (HashMap::new(), Vec::new()), |(mut values, mut errors), result| match result { Ok((key, value)) => { values.insert(key, value); (values, errors) } Err(error) => { errors.push(error); (values, errors) } }, ); if !errors.is_empty() { Err(format!("Some errors occurred:\n{}", errors.join("\n"))) } else { Ok(values) } } fn deserialize_hashmap<'a, D, K, V>(deserializer: D) -> Result<HashMap<K, HashSet<V>>, D::Error> where D: serde::Deserializer<'a>, K: Eq + std::str::FromStr + std::hash::Hash, V: Eq + std::str::FromStr + std::hash::Hash, <K as std::str::FromStr>::Err: std::fmt::Display, <V as std::str::FromStr>::Err: std::fmt::Display, { use serde::de::Error; deserialize_hashmap_inner(<HashMap<String, String>>::deserialize(deserializer)?) .map_err(D::Error::custom) } fn deserialize_hashset_inner<T>(value: impl AsRef<str>) -> Result<HashSet<T>, String> where T: Eq + std::str::FromStr + std::hash::Hash, <T as std::str::FromStr>::Err: std::fmt::Display, { let (values, errors) = value .as_ref() .trim() .split(',') .map(|s| { T::from_str(s.trim()).map_err(|error| { format!( "Unable to deserialize `{}` as `{}`: {error}", s.trim(), std::any::type_name::<T>() ) }) }) .fold( (HashSet::new(), Vec::new()), |(mut values, mut errors), result| match result { Ok(t) => { values.insert(t); (values, errors) } Err(error) => { errors.push(error); (values, errors) } }, ); if !errors.is_empty() { Err(format!("Some errors occurred:\n{}", errors.join("\n"))) } else { Ok(values) } } fn deserialize_hashset<'a, D, T>(deserializer: D) -> Result<HashSet<T>, D::Error> where D: serde::Deserializer<'a>, T: Eq + std::str::FromStr + std::hash::Hash, <T as std::str::FromStr>::Err: std::fmt::Display, { use serde::de::Error; deserialize_hashset_inner(<String>::deserialize(deserializer)?).map_err(D::Error::custom) } fn deserialize_optional_hashset<'a, D, T>(deserializer: D) -> Result<Option<HashSet<T>>, D::Error> where D: serde::Deserializer<'a>, T: Eq + std::str::FromStr + std::hash::Hash, <T as std::str::FromStr>::Err: std::fmt::Display, { use serde::de::Error; <Option<String>>::deserialize(deserializer).map(|value| { value.map_or(Ok(None), |inner: String| { let list = deserialize_hashset_inner(inner).map_err(D::Error::custom)?; match list.len() { 0 => Ok(None), _ => Ok(Some(list)), } }) })? } fn deserialize_merchant_ids_inner( value: impl AsRef<str>, ) -> Result<HashSet<id_type::MerchantId>, String> { let (values, errors) = value .as_ref() .trim() .split(',') .map(|s| { let trimmed = s.trim(); id_type::MerchantId::wrap(trimmed.to_owned()).map_err(|error| { format!("Unable to deserialize `{trimmed}` as `MerchantId`: {error}") }) }) .fold( (HashSet::new(), Vec::new()), |(mut values, mut errors), result| match result { Ok(t) => { values.insert(t); (values, errors) } Err(error) => { errors.push(error); (values, errors) } }, ); if !errors.is_empty() { Err(format!("Some errors occurred:\n{}", errors.join("\n"))) } else { Ok(values) } } fn deserialize_merchant_ids<'de, D>( deserializer: D, ) -> Result<HashSet<id_type::MerchantId>, D::Error> where D: serde::Deserializer<'de>, { let s = String::deserialize(deserializer)?; deserialize_merchant_ids_inner(s).map_err(serde::de::Error::custom) } impl<'de> Deserialize<'de> for TenantConfig { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] struct Inner { base_url: String, schema: String, accounts_schema: String, redis_key_prefix: String, clickhouse_database: String, user: TenantUserConfig, } let hashmap = <HashMap<id_type::TenantId, Inner>>::deserialize(deserializer)?; Ok(Self( hashmap .into_iter() .map(|(key, value)| { ( key.clone(), Tenant { tenant_id: key, base_url: value.base_url, schema: value.schema, accounts_schema: value.accounts_schema, redis_key_prefix: value.redis_key_prefix, clickhouse_database: value.clickhouse_database, user: value.user, }, ) }) .collect(), )) } } #[cfg(test)] mod hashmap_deserialization_test { #![allow(clippy::unwrap_used)] use std::collections::{HashMap, HashSet}; use serde::de::{ value::{Error as ValueError, MapDeserializer}, IntoDeserializer, }; use super::deserialize_hashmap; #[test] fn test_payment_method_and_payment_method_types() { use diesel_models::enums::{PaymentMethod, PaymentMethodType}; let input_map: HashMap<String, String> = HashMap::from([ ("bank_transfer".to_string(), "ach,bacs".to_string()), ("wallet".to_string(), "paypal,venmo".to_string()), ]); let deserializer: MapDeserializer< '_, std::collections::hash_map::IntoIter<String, String>, ValueError, > = input_map.into_deserializer(); let result = deserialize_hashmap::<'_, _, PaymentMethod, PaymentMethodType>(deserializer); let expected_result = HashMap::from([ ( PaymentMethod::BankTransfer, HashSet::from([PaymentMethodType::Ach, PaymentMethodType::Bacs]), ), ( PaymentMethod::Wallet, HashSet::from([PaymentMethodType::Paypal, PaymentMethodType::Venmo]), ), ]); assert!(result.is_ok()); assert_eq!(result.unwrap(), expected_result); } #[test] fn test_payment_method_and_payment_method_types_with_spaces() { use diesel_models::enums::{PaymentMethod, PaymentMethodType}; let input_map: HashMap<String, String> = HashMap::from([ (" bank_transfer ".to_string(), " ach , bacs ".to_string()), ("wallet ".to_string(), " paypal , pix , venmo ".to_string()), ]); let deserializer: MapDeserializer< '_, std::collections::hash_map::IntoIter<String, String>, ValueError, > = input_map.into_deserializer(); let result = deserialize_hashmap::<'_, _, PaymentMethod, PaymentMethodType>(deserializer); let expected_result = HashMap::from([ ( PaymentMethod::BankTransfer, HashSet::from([PaymentMethodType::Ach, PaymentMethodType::Bacs]), ), ( PaymentMethod::Wallet, HashSet::from([ PaymentMethodType::Paypal, PaymentMethodType::Pix, PaymentMethodType::Venmo, ]), ), ]); assert!(result.is_ok()); assert_eq!(result.unwrap(), expected_result); } #[test] fn test_payment_method_deserializer_error() { use diesel_models::enums::{PaymentMethod, PaymentMethodType}; let input_map: HashMap<String, String> = HashMap::from([ ("unknown".to_string(), "ach,bacs".to_string()), ("wallet".to_string(), "paypal,unknown".to_string()), ]); let deserializer: MapDeserializer< '_, std::collections::hash_map::IntoIter<String, String>, ValueError, > = input_map.into_deserializer(); let result = deserialize_hashmap::<'_, _, PaymentMethod, PaymentMethodType>(deserializer); assert!(result.is_err()); } } #[cfg(test)] mod hashset_deserialization_test { #![allow(clippy::unwrap_used)] use std::collections::HashSet; use serde::de::{ value::{Error as ValueError, StrDeserializer}, IntoDeserializer, }; use super::deserialize_hashset; #[test] fn test_payment_method_hashset_deserializer() { use diesel_models::enums::PaymentMethod; let deserializer: StrDeserializer<'_, ValueError> = "wallet,card".into_deserializer(); let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer); let expected_payment_methods = HashSet::from([PaymentMethod::Wallet, PaymentMethod::Card]); assert!(payment_methods.is_ok()); assert_eq!(payment_methods.unwrap(), expected_payment_methods); } #[test] fn test_payment_method_hashset_deserializer_with_spaces() { use diesel_models::enums::PaymentMethod; let deserializer: StrDeserializer<'_, ValueError> = "wallet, card, bank_debit".into_deserializer(); let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer); let expected_payment_methods = HashSet::from([ PaymentMethod::Wallet, PaymentMethod::Card, PaymentMethod::BankDebit, ]); assert!(payment_methods.is_ok()); assert_eq!(payment_methods.unwrap(), expected_payment_methods); } #[test] fn test_payment_method_hashset_deserializer_error() { use diesel_models::enums::PaymentMethod; let deserializer: StrDeserializer<'_, ValueError> = "wallet, card, unknown".into_deserializer(); let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer); assert!(payment_methods.is_err()); } }
crates/router/src/configs/settings.rs
router::src::configs::settings
11,329
true
// File: crates/router/src/configs/validations.rs // Module: router::src::configs::validations use common_utils::ext_traits::ConfigExt; use masking::PeekInterface; use storage_impl::errors::ApplicationError; impl super::settings::Secrets { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.jwt_secret.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "JWT secret must not be empty".into(), )) })?; when(self.admin_api_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "admin API key must not be empty".into(), )) })?; when(self.master_enc_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Master encryption key must not be empty".into(), )) }) } } impl super::settings::Locker { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(!self.mock_locker && self.host.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "locker host must not be empty when mock locker is disabled".into(), )) })?; when( !self.mock_locker && self.basilisk_host.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "basilisk host must not be empty when mock locker is disabled".into(), )) }, ) } } impl super::settings::Server { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.host.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "server host must not be empty".into(), )) })?; when(self.workers == 0, || { Err(ApplicationError::InvalidConfigurationValueError( "number of workers must be greater than 0".into(), )) }) } } impl super::settings::Database { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.host.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "database host must not be empty".into(), )) })?; when(self.dbname.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "database name must not be empty".into(), )) })?; when(self.username.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "database user username must not be empty".into(), )) })?; when(self.password.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "database user password must not be empty".into(), )) }) } } impl super::settings::SupportedConnectors { pub fn validate(&self) -> Result<(), ApplicationError> { common_utils::fp_utils::when(self.wallets.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "list of connectors supporting wallets must not be empty".into(), )) }) } } impl super::settings::CorsSettings { pub fn validate(&self) -> Result<(), ApplicationError> { common_utils::fp_utils::when(self.wildcard_origin && !self.origins.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Allowed Origins must be empty when wildcard origin is true".to_string(), )) })?; common_utils::fp_utils::when(!self.wildcard_origin && self.origins.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Allowed origins must not be empty. Please either enable wildcard origin or provide Allowed Origin".to_string(), )) }) } } #[cfg(feature = "kv_store")] impl super::settings::DrainerSettings { pub fn validate(&self) -> Result<(), ApplicationError> { common_utils::fp_utils::when(self.stream_name.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "drainer stream name must not be empty".into(), )) }) } } impl super::settings::ApiKeys { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.hash_key.peek().is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "API key hashing key must not be empty".into(), )) })?; #[cfg(feature = "email")] when(self.expiry_reminder_days.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "API key expiry reminder days must not be empty".into(), )) })?; Ok(()) } } impl super::settings::LockSettings { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.redis_lock_expiry_seconds.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "redis_lock_expiry_seconds must not be empty or 0".into(), )) })?; when( self.delay_between_retries_in_milliseconds .is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "delay_between_retries_in_milliseconds must not be empty or 0".into(), )) }, )?; when(self.lock_retries.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "lock_retries must not be empty or 0".into(), )) }) } } impl super::settings::WebhooksSettings { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.redis_lock_expiry_seconds.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "redis_lock_expiry_seconds must not be empty or 0".into(), )) }) } } impl super::settings::GenericLinkEnvConfig { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.expiry == 0, || { Err(ApplicationError::InvalidConfigurationValueError( "link's expiry should not be 0".into(), )) }) } } #[cfg(feature = "v2")] impl super::settings::CellInformation { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::{fp_utils::when, id_type}; when(self == &Self::default(), || { Err(ApplicationError::InvalidConfigurationValueError( "CellId cannot be set to a default".into(), )) }) } } impl super::settings::NetworkTokenizationService { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.token_service_api_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "token_service_api_key must not be empty".into(), )) })?; when(self.public_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "public_key must not be empty".into(), )) })?; when(self.key_id.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "key_id must not be empty".into(), )) })?; when(self.private_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "private_key must not be empty".into(), )) })?; when( self.webhook_source_verification_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "webhook_source_verification_key must not be empty".into(), )) }, ) } } impl super::settings::PazeDecryptConfig { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.paze_private_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "paze_private_key must not be empty".into(), )) })?; when( self.paze_private_key_passphrase.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "paze_private_key_passphrase must not be empty".into(), )) }, ) } } impl super::settings::GooglePayDecryptConfig { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when( self.google_pay_root_signing_keys.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "google_pay_root_signing_keys must not be empty".into(), )) }, ) } } impl super::settings::KeyManagerConfig { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; #[cfg(feature = "keymanager_mtls")] when( self.enabled && (self.ca.is_default_or_empty() || self.cert.is_default_or_empty()), || { Err(ApplicationError::InvalidConfigurationValueError( "Invalid CA or Certificate for Keymanager.".into(), )) }, )?; when(self.enabled && self.url.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Invalid URL for Keymanager".into(), )) }) } } impl super::settings::Platform { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(!self.enabled && self.allow_connected_merchants, || { Err(ApplicationError::InvalidConfigurationValueError( "platform.allow_connected_merchants cannot be true when platform.enabled is false" .into(), )) }) } } impl super::settings::OpenRouter { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when( (self.dynamic_routing_enabled || self.static_routing_enabled) && self.url.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "OpenRouter base URL must not be empty when it is enabled".into(), )) }, ) } } impl super::settings::ChatSettings { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.enabled && self.hyperswitch_ai_host.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "hyperswitch ai host must be set if chat is enabled".into(), )) }) } }
crates/router/src/configs/validations.rs
router::src::configs::validations
2,330
true
// File: crates/router/src/configs/defaults/payout_required_fields.rs // Module: router::src::configs::defaults::payout_required_fields use std::collections::HashMap; use api_models::{ enums::{ CountryAlpha2, FieldType, PaymentMethod::{BankTransfer, Card, Wallet}, PaymentMethodType, PayoutConnectors, }, payment_methods::RequiredFieldInfo, }; use crate::settings::{ ConnectorFields, PaymentMethodType as PaymentMethodTypeInfo, PayoutRequiredFields, RequiredFieldFinal, }; #[cfg(feature = "v1")] impl Default for PayoutRequiredFields { fn default() -> Self { Self(HashMap::from([ ( Card, PaymentMethodTypeInfo(HashMap::from([ // Adyen get_connector_payment_method_type_fields( PayoutConnectors::Adyenplatform, PaymentMethodType::Debit, ), get_connector_payment_method_type_fields( PayoutConnectors::Adyenplatform, PaymentMethodType::Credit, ), ])), ), ( BankTransfer, PaymentMethodTypeInfo(HashMap::from([ // Adyen get_connector_payment_method_type_fields( PayoutConnectors::Adyenplatform, PaymentMethodType::SepaBankTransfer, ), // Ebanx get_connector_payment_method_type_fields( PayoutConnectors::Ebanx, PaymentMethodType::Pix, ), // Wise get_connector_payment_method_type_fields( PayoutConnectors::Wise, PaymentMethodType::Bacs, ), ])), ), ( Wallet, PaymentMethodTypeInfo(HashMap::from([ // Adyen get_connector_payment_method_type_fields( PayoutConnectors::Adyenplatform, PaymentMethodType::Paypal, ), ])), ), ])) } } fn get_billing_details_for_payment_method( connector: PayoutConnectors, payment_method_type: PaymentMethodType, ) -> HashMap<String, RequiredFieldInfo> { match connector { PayoutConnectors::Adyenplatform => { let mut fields = HashMap::from([ ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "billing.address.line1".to_string(), display_name: "billing_address_line1".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "billing.address.line2".to_string(), display_name: "billing_address_line2".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "billing.address.city".to_string(), display_name: "billing_address_city".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "billing.address.country".to_string(), display_name: "billing_address_country".to_string(), field_type: FieldType::UserAddressCountry { options: get_countries_for_connector(connector) .iter() .map(|country| country.to_string()) .collect::<Vec<String>>(), }, value: None, }, ), ]); // Add first_name for bank payouts only if payment_method_type == PaymentMethodType::SepaBankTransfer { fields.insert( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "billing.address.first_name".to_string(), display_name: "billing_address_first_name".to_string(), field_type: FieldType::Text, value: None, }, ); } fields } _ => get_billing_details(connector), } } #[cfg(feature = "v1")] fn get_connector_payment_method_type_fields( connector: PayoutConnectors, payment_method_type: PaymentMethodType, ) -> (PaymentMethodType, ConnectorFields) { let mut common_fields = get_billing_details_for_payment_method(connector, payment_method_type); match payment_method_type { // Card PaymentMethodType::Debit => { common_fields.extend(get_card_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } PaymentMethodType::Credit => { common_fields.extend(get_card_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } // Banks PaymentMethodType::Bacs => { common_fields.extend(get_bacs_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } PaymentMethodType::Pix => { common_fields.extend(get_pix_bank_transfer_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } PaymentMethodType::SepaBankTransfer => { common_fields.extend(get_sepa_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } // Wallets PaymentMethodType::Paypal => { common_fields.extend(get_paypal_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } // Bank Redirect PaymentMethodType::Interac => { common_fields.extend(get_interac_fields(connector)); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } _ => ( payment_method_type, ConnectorFields { fields: HashMap::new(), }, ), } } fn get_card_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([ ( "payout_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payout_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: FieldType::UserCardNumber, value: None, }, ), ( "payout_method_data.card.expiry_month".to_string(), RequiredFieldInfo { required_field: "payout_method_data.card.expiry_month".to_string(), display_name: "exp_month".to_string(), field_type: FieldType::UserCardExpiryMonth, value: None, }, ), ( "payout_method_data.card.expiry_year".to_string(), RequiredFieldInfo { required_field: "payout_method_data.card.expiry_year".to_string(), display_name: "exp_year".to_string(), field_type: FieldType::UserCardExpiryYear, value: None, }, ), ( "payout_method_data.card.card_holder_name".to_string(), RequiredFieldInfo { required_field: "payout_method_data.card.card_holder_name".to_string(), display_name: "card_holder_name".to_string(), field_type: FieldType::UserFullName, value: None, }, ), ]) } fn get_bacs_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([ ( "payout_method_data.bank.bank_sort_code".to_string(), RequiredFieldInfo { required_field: "payout_method_data.bank.bank_sort_code".to_string(), display_name: "bank_sort_code".to_string(), field_type: FieldType::Text, value: None, }, ), ( "payout_method_data.bank.bank_account_number".to_string(), RequiredFieldInfo { required_field: "payout_method_data.bank.bank_account_number".to_string(), display_name: "bank_account_number".to_string(), field_type: FieldType::Text, value: None, }, ), ]) } fn get_pix_bank_transfer_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([ ( "payout_method_data.bank.bank_account_number".to_string(), RequiredFieldInfo { required_field: "payout_method_data.bank.bank_account_number".to_string(), display_name: "bank_account_number".to_string(), field_type: FieldType::Text, value: None, }, ), ( "payout_method_data.bank.pix_key".to_string(), RequiredFieldInfo { required_field: "payout_method_data.bank.pix_key".to_string(), display_name: "pix_key".to_string(), field_type: FieldType::Text, value: None, }, ), ]) } fn get_sepa_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([ ( "payout_method_data.bank.iban".to_string(), RequiredFieldInfo { required_field: "payout_method_data.bank.iban".to_string(), display_name: "iban".to_string(), field_type: FieldType::Text, value: None, }, ), ( "payout_method_data.bank.bic".to_string(), RequiredFieldInfo { required_field: "payout_method_data.bank.bic".to_string(), display_name: "bic".to_string(), field_type: FieldType::Text, value: None, }, ), ]) } fn get_paypal_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([( "payout_method_data.wallet.telephone_number".to_string(), RequiredFieldInfo { required_field: "payout_method_data.wallet.telephone_number".to_string(), display_name: "telephone_number".to_string(), field_type: FieldType::Text, value: None, }, )]) } fn get_interac_fields(connector: PayoutConnectors) -> HashMap<String, RequiredFieldInfo> { match connector { PayoutConnectors::Loonio => HashMap::from([ ( "payout_method_data.bank_redirect.interac.email".to_string(), RequiredFieldInfo { required_field: "payout_method_data.bank_redirect.interac.email".to_string(), display_name: "email".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "billing.address.first_name".to_string(), display_name: "billing_address_first_name".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "billing.address.last_name".to_string(), display_name: "billing_address_last_name".to_string(), field_type: FieldType::Text, value: None, }, ), ]), PayoutConnectors::Gigadat => HashMap::from([ ( "payout_method_data.bank_redirect.interac.email".to_string(), RequiredFieldInfo { required_field: "payout_method_data.bank_redirect.interac.email".to_string(), display_name: "email".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "billing.address.first_name".to_string(), display_name: "billing_address_first_name".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "billing.address.last_name".to_string(), display_name: "billing_address_last_name".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone".to_string(), field_type: FieldType::UserPhoneNumber, value: None, }, ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: FieldType::UserPhoneNumberCountryCode, value: None, }, ), ]), _ => HashMap::from([]), } } fn get_countries_for_connector(connector: PayoutConnectors) -> Vec<CountryAlpha2> { match connector { PayoutConnectors::Adyenplatform => vec![ CountryAlpha2::ES, CountryAlpha2::SK, CountryAlpha2::AT, CountryAlpha2::NL, CountryAlpha2::DE, CountryAlpha2::BE, CountryAlpha2::FR, CountryAlpha2::FI, CountryAlpha2::PT, CountryAlpha2::IE, CountryAlpha2::EE, CountryAlpha2::LT, CountryAlpha2::LV, CountryAlpha2::IT, CountryAlpha2::CZ, CountryAlpha2::DE, CountryAlpha2::HU, CountryAlpha2::NO, CountryAlpha2::PL, CountryAlpha2::SE, CountryAlpha2::GB, CountryAlpha2::CH, ], PayoutConnectors::Stripe => vec![CountryAlpha2::US], _ => vec![], } } fn get_billing_details(connector: PayoutConnectors) -> HashMap<String, RequiredFieldInfo> { match connector { PayoutConnectors::Adyen => HashMap::from([ ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "billing.address.line1".to_string(), display_name: "billing_address_line1".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "billing.address.line2".to_string(), display_name: "billing_address_line2".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "billing.address.city".to_string(), display_name: "billing_address_city".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "billing.address.zip".to_string(), display_name: "billing_address_zip".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "billing.address.country".to_string(), display_name: "billing_address_country".to_string(), field_type: FieldType::UserAddressCountry { options: get_countries_for_connector(connector) .iter() .map(|country| country.to_string()) .collect::<Vec<String>>(), }, value: None, }, ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "billing.address.first_name".to_string(), display_name: "billing_address_first_name".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "billing.address.last_name".to_string(), display_name: "billing_address_last_name".to_string(), field_type: FieldType::Text, value: None, }, ), ]), PayoutConnectors::Wise => HashMap::from([ ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "billing.address.line1".to_string(), display_name: "billing_address_line1".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "billing.address.city".to_string(), display_name: "billing_address_city".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "billing.address.state".to_string(), display_name: "billing_address_state".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "billing.address.zip".to_string(), display_name: "billing_address_zip".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "billing.address.country".to_string(), display_name: "billing_address_country".to_string(), field_type: FieldType::UserAddressCountry { options: get_countries_for_connector(connector) .iter() .map(|country| country.to_string()) .collect::<Vec<String>>(), }, value: None, }, ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "billing.address.first_name".to_string(), display_name: "billing_address_first_name".to_string(), field_type: FieldType::Text, value: None, }, ), ]), _ => HashMap::from([]), } }
crates/router/src/configs/defaults/payout_required_fields.rs
router::src::configs::defaults::payout_required_fields
4,041
true
// File: crates/router/src/connector/utils.rs // Module: router::src::connector::utils use std::{ collections::{HashMap, HashSet}, ops::Deref, str::FromStr, sync::LazyLock, }; #[cfg(feature = "payouts")] use api_models::payouts::{self, PayoutVendorAccountDetails}; use api_models::{ enums::{CanadaStatesAbbreviation, UsStatesAbbreviation}, payments, }; use base64::Engine; use common_utils::{ date_time, errors::{ParsingError, ReportSwitchExt}, ext_traits::StringExt, id_type, pii::{self, Email, IpAddress}, types::{AmountConvertor, MinorUnit}, }; use diesel_models::{enums, types::OrderDetailsWithAmount}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ network_tokenization::NetworkTokenNumber, payments::payment_attempt::PaymentAttempt, }; use masking::{Deserialize, ExposeInterface, Secret}; use regex::Regex; #[cfg(feature = "frm")] use crate::types::fraud_check; use crate::{ consts, core::{ errors::{self, ApiErrorResponse, CustomResult}, payments::{types::AuthenticationData, PaymentData}, }, pii::PeekInterface, types::{ self, api, domain, storage::enums as storage_enums, transformers::{ForeignFrom, ForeignTryFrom}, BrowserInformation, PaymentsCancelData, ResponseId, }, utils::{OptionExt, ValueExt}, }; pub fn missing_field_err( message: &'static str, ) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + 'static> { Box::new(move || { errors::ConnectorError::MissingRequiredField { field_name: message, } .into() }) } type Error = error_stack::Report<errors::ConnectorError>; pub trait AccessTokenRequestInfo { fn get_request_id(&self) -> Result<Secret<String>, Error>; } impl AccessTokenRequestInfo for types::RefreshTokenRouterData { fn get_request_id(&self) -> Result<Secret<String>, Error> { self.request .id .clone() .ok_or_else(missing_field_err("request.id")) } } pub trait RouterData { fn get_billing(&self) -> Result<&hyperswitch_domain_models::address::Address, Error>; fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error>; fn get_billing_phone(&self) -> Result<&hyperswitch_domain_models::address::PhoneDetails, Error>; fn get_description(&self) -> Result<String, Error>; fn get_billing_address( &self, ) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error>; fn get_shipping_address( &self, ) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error>; fn get_shipping_address_with_phone_number( &self, ) -> Result<&hyperswitch_domain_models::address::Address, Error>; fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error>; fn get_session_token(&self) -> Result<String, Error>; fn get_billing_first_name(&self) -> Result<Secret<String>, Error>; fn get_billing_full_name(&self) -> Result<Secret<String>, Error>; fn get_billing_last_name(&self) -> Result<Secret<String>, Error>; fn get_billing_line1(&self) -> Result<Secret<String>, Error>; fn get_billing_city(&self) -> Result<String, Error>; fn get_billing_email(&self) -> Result<Email, Error>; fn get_billing_phone_number(&self) -> Result<Secret<String>, Error>; fn to_connector_meta<T>(&self) -> Result<T, Error> where T: serde::de::DeserializeOwned; fn is_three_ds(&self) -> bool; fn get_payment_method_token(&self) -> Result<types::PaymentMethodToken, Error>; fn get_customer_id(&self) -> Result<id_type::CustomerId, Error>; fn get_connector_customer_id(&self) -> Result<String, Error>; fn get_preprocessing_id(&self) -> Result<String, Error>; fn get_recurring_mandate_payment_data( &self, ) -> Result<types::RecurringMandatePaymentData, Error>; #[cfg(feature = "payouts")] fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error>; #[cfg(feature = "payouts")] fn get_quote_id(&self) -> Result<String, Error>; fn get_optional_billing(&self) -> Option<&hyperswitch_domain_models::address::Address>; fn get_optional_shipping(&self) -> Option<&hyperswitch_domain_models::address::Address>; fn get_optional_shipping_line1(&self) -> Option<Secret<String>>; fn get_optional_shipping_line2(&self) -> Option<Secret<String>>; fn get_optional_shipping_line3(&self) -> Option<Secret<String>>; fn get_optional_shipping_city(&self) -> Option<String>; fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2>; fn get_optional_shipping_zip(&self) -> Option<Secret<String>>; fn get_optional_shipping_state(&self) -> Option<Secret<String>>; fn get_optional_shipping_first_name(&self) -> Option<Secret<String>>; fn get_optional_shipping_last_name(&self) -> Option<Secret<String>>; fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>>; fn get_optional_shipping_email(&self) -> Option<Email>; fn get_optional_billing_full_name(&self) -> Option<Secret<String>>; fn get_optional_billing_line1(&self) -> Option<Secret<String>>; fn get_optional_billing_line2(&self) -> Option<Secret<String>>; fn get_optional_billing_city(&self) -> Option<String>; fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2>; fn get_optional_billing_zip(&self) -> Option<Secret<String>>; fn get_optional_billing_state(&self) -> Option<Secret<String>>; fn get_optional_billing_first_name(&self) -> Option<Secret<String>>; fn get_optional_billing_last_name(&self) -> Option<Secret<String>>; fn get_optional_billing_phone_number(&self) -> Option<Secret<String>>; fn get_optional_billing_email(&self) -> Option<Email>; } pub trait PaymentResponseRouterData { fn get_attempt_status_for_db_update<F>( &self, payment_data: &PaymentData<F>, amount_captured: Option<i64>, amount_capturable: Option<i64>, ) -> CustomResult<enums::AttemptStatus, ApiErrorResponse> where F: Clone; } #[cfg(feature = "v1")] impl<Flow, Request, Response> PaymentResponseRouterData for types::RouterData<Flow, Request, Response> where Request: types::Capturable, { fn get_attempt_status_for_db_update<F>( &self, payment_data: &PaymentData<F>, amount_captured: Option<i64>, amount_capturable: Option<i64>, ) -> CustomResult<enums::AttemptStatus, ApiErrorResponse> where F: Clone, { match self.status { enums::AttemptStatus::Voided => { if payment_data.payment_intent.amount_captured > Some(MinorUnit::new(0)) { Ok(enums::AttemptStatus::PartialCharged) } else { Ok(self.status) } } enums::AttemptStatus::Charged => { let captured_amount = types::Capturable::get_captured_amount( &self.request, amount_captured, payment_data, ); let total_capturable_amount = payment_data.payment_attempt.get_total_amount(); if Some(total_capturable_amount) == captured_amount.map(MinorUnit::new) || (captured_amount.is_some_and(|captured_amount| { MinorUnit::new(captured_amount) > total_capturable_amount })) { Ok(enums::AttemptStatus::Charged) } else if captured_amount.is_some_and(|captured_amount| { MinorUnit::new(captured_amount) < total_capturable_amount }) { Ok(enums::AttemptStatus::PartialCharged) } else { Ok(self.status) } } enums::AttemptStatus::Authorized => { let capturable_amount = types::Capturable::get_amount_capturable( &self.request, payment_data, amount_capturable, payment_data.payment_attempt.status, ); let total_capturable_amount = payment_data.payment_attempt.get_total_amount(); let is_overcapture_enabled = *payment_data .payment_attempt .is_overcapture_enabled .unwrap_or_default() .deref(); if Some(total_capturable_amount) == capturable_amount.map(MinorUnit::new) || (capturable_amount.is_some_and(|capturable_amount| { MinorUnit::new(capturable_amount) > total_capturable_amount }) && is_overcapture_enabled) { Ok(enums::AttemptStatus::Authorized) } else if capturable_amount.is_some_and(|capturable_amount| { MinorUnit::new(capturable_amount) < total_capturable_amount }) && payment_data .payment_intent .enable_partial_authorization .is_some_and(|val| val.is_true()) { Ok(enums::AttemptStatus::PartiallyAuthorized) } else if capturable_amount.is_some_and(|capturable_amount| { MinorUnit::new(capturable_amount) < total_capturable_amount }) && !payment_data .payment_intent .enable_partial_authorization .is_some_and(|val| val.is_true()) { Err(ApiErrorResponse::IntegrityCheckFailed { reason: "capturable_amount is less than the total attempt amount" .to_string(), field_names: "amount_capturable".to_string(), connector_transaction_id: payment_data .payment_attempt .connector_transaction_id .clone(), })? } else if capturable_amount.is_some_and(|capturable_amount| { MinorUnit::new(capturable_amount) > total_capturable_amount }) && !is_overcapture_enabled { Err(ApiErrorResponse::IntegrityCheckFailed { reason: "capturable_amount is greater than the total attempt amount" .to_string(), field_names: "amount_capturable".to_string(), connector_transaction_id: payment_data .payment_attempt .connector_transaction_id .clone(), })? } else { Ok(self.status) } } _ => Ok(self.status), } } } #[cfg(feature = "v2")] impl<Flow, Request, Response> PaymentResponseRouterData for types::RouterData<Flow, Request, Response> where Request: types::Capturable, { fn get_attempt_status_for_db_update<F>( &self, payment_data: &PaymentData<F>, amount_captured: Option<i64>, amount_capturable: Option<i64>, ) -> CustomResult<enums::AttemptStatus, ApiErrorResponse> where F: Clone, { match self.status { enums::AttemptStatus::Voided => { if payment_data.payment_intent.amount_captured > Some(MinorUnit::new(0)) { Ok(enums::AttemptStatus::PartialCharged) } else { Ok(self.status) } } enums::AttemptStatus::Charged => { let captured_amount = types::Capturable::get_captured_amount( &self.request, amount_captured, payment_data, ); let total_capturable_amount = payment_data.payment_attempt.get_total_amount(); if Some(total_capturable_amount) == captured_amount.map(MinorUnit::new) { Ok(enums::AttemptStatus::Charged) } else if captured_amount.is_some() { Ok(enums::AttemptStatus::PartialCharged) } else { Ok(self.status) } } enums::AttemptStatus::Authorized => { let capturable_amount = types::Capturable::get_amount_capturable( &self.request, payment_data, amount_capturable, payment_data.payment_attempt.status, ); if Some(payment_data.payment_attempt.get_total_amount()) == capturable_amount.map(MinorUnit::new) { Ok(enums::AttemptStatus::Authorized) } else if capturable_amount.is_some() { Ok(enums::AttemptStatus::PartiallyAuthorized) } else { Ok(self.status) } } _ => Ok(self.status), } } } pub const SELECTED_PAYMENT_METHOD: &str = "Selected payment method"; pub fn get_unimplemented_payment_method_error_message(connector: &str) -> String { format!("{SELECTED_PAYMENT_METHOD} through {connector}") } impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Response> { fn get_billing(&self) -> Result<&hyperswitch_domain_models::address::Address, Error> { self.address .get_payment_method_billing() .ok_or_else(missing_field_err("billing")) } fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error> { self.address .get_payment_method_billing() .and_then(|a| a.address.as_ref()) .and_then(|ad| ad.country) .ok_or_else(missing_field_err( "payment_method_data.billing.address.country", )) } fn get_billing_phone( &self, ) -> Result<&hyperswitch_domain_models::address::PhoneDetails, Error> { self.address .get_payment_method_billing() .and_then(|a| a.phone.as_ref()) .ok_or_else(missing_field_err("billing.phone")) } fn get_optional_billing(&self) -> Option<&hyperswitch_domain_models::address::Address> { self.address.get_payment_method_billing() } fn get_optional_shipping(&self) -> Option<&hyperswitch_domain_models::address::Address> { self.address.get_shipping() } fn get_optional_shipping_first_name(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.first_name) }) } fn get_optional_shipping_last_name(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.last_name) }) } fn get_optional_shipping_line1(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.line1) }) } fn get_optional_shipping_line2(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.line2) }) } fn get_optional_shipping_line3(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.line3) }) } fn get_optional_shipping_city(&self) -> Option<String> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.city) }) } fn get_optional_shipping_state(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.state) }) } fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.country) }) } fn get_optional_shipping_zip(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.zip) }) } fn get_optional_shipping_email(&self) -> Option<Email> { self.address .get_shipping() .and_then(|shipping_address| shipping_address.clone().email) } fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>> { self.address .get_shipping() .and_then(|shipping_address| shipping_address.clone().phone) .and_then(|phone_details| phone_details.get_number_with_country_code().ok()) } fn get_description(&self) -> Result<String, Error> { self.description .clone() .ok_or_else(missing_field_err("description")) } fn get_billing_address( &self, ) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error> { self.address .get_payment_method_billing() .as_ref() .and_then(|a| a.address.as_ref()) .ok_or_else(missing_field_err("billing.address")) } fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error> { self.connector_meta_data .clone() .ok_or_else(missing_field_err("connector_meta_data")) } fn get_session_token(&self) -> Result<String, Error> { self.session_token .clone() .ok_or_else(missing_field_err("session_token")) } fn get_billing_first_name(&self) -> Result<Secret<String>, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.first_name.clone()) }) .ok_or_else(missing_field_err( "payment_method_data.billing.address.first_name", )) } fn get_billing_full_name(&self) -> Result<Secret<String>, Error> { self.get_optional_billing() .and_then(|billing_details| billing_details.address.as_ref()) .and_then(|billing_address| billing_address.get_optional_full_name()) .ok_or_else(missing_field_err( "payment_method_data.billing.address.first_name", )) } fn get_billing_last_name(&self) -> Result<Secret<String>, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.last_name.clone()) }) .ok_or_else(missing_field_err( "payment_method_data.billing.address.last_name", )) } fn get_billing_line1(&self) -> Result<Secret<String>, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.line1.clone()) }) .ok_or_else(missing_field_err( "payment_method_data.billing.address.line1", )) } fn get_billing_city(&self) -> Result<String, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.city) }) .ok_or_else(missing_field_err( "payment_method_data.billing.address.city", )) } fn get_billing_email(&self) -> Result<Email, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| billing_address.email.clone()) .ok_or_else(missing_field_err("payment_method_data.billing.email")) } fn get_billing_phone_number(&self) -> Result<Secret<String>, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| billing_address.clone().phone) .map(|phone_details| phone_details.get_number_with_country_code()) .transpose()? .ok_or_else(missing_field_err("payment_method_data.billing.phone")) } fn get_optional_billing_line1(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.line1) }) } fn get_optional_billing_line2(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.line2) }) } fn get_optional_billing_city(&self) -> Option<String> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.city) }) } fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.country) }) } fn get_optional_billing_zip(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.zip) }) } fn get_optional_billing_state(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.state) }) } fn get_optional_billing_first_name(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.first_name) }) } fn get_optional_billing_last_name(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.last_name) }) } fn get_optional_billing_phone_number(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .phone .and_then(|phone_data| phone_data.number) }) } fn get_optional_billing_email(&self) -> Option<Email> { self.address .get_payment_method_billing() .and_then(|billing_address| billing_address.clone().email) } fn to_connector_meta<T>(&self) -> Result<T, Error> where T: serde::de::DeserializeOwned, { self.get_connector_meta()? .parse_value(std::any::type_name::<T>()) .change_context(errors::ConnectorError::NoConnectorMetaData) } fn is_three_ds(&self) -> bool { matches!(self.auth_type, enums::AuthenticationType::ThreeDs) } fn get_shipping_address( &self, ) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error> { self.address .get_shipping() .and_then(|a| a.address.as_ref()) .ok_or_else(missing_field_err("shipping.address")) } fn get_shipping_address_with_phone_number( &self, ) -> Result<&hyperswitch_domain_models::address::Address, Error> { self.address .get_shipping() .ok_or_else(missing_field_err("shipping")) } fn get_payment_method_token(&self) -> Result<types::PaymentMethodToken, Error> { self.payment_method_token .clone() .ok_or_else(missing_field_err("payment_method_token")) } fn get_customer_id(&self) -> Result<id_type::CustomerId, Error> { self.customer_id .to_owned() .ok_or_else(missing_field_err("customer_id")) } fn get_connector_customer_id(&self) -> Result<String, Error> { self.connector_customer .to_owned() .ok_or_else(missing_field_err("connector_customer_id")) } fn get_preprocessing_id(&self) -> Result<String, Error> { self.preprocessing_id .to_owned() .ok_or_else(missing_field_err("preprocessing_id")) } fn get_recurring_mandate_payment_data( &self, ) -> Result<types::RecurringMandatePaymentData, Error> { self.recurring_mandate_payment_data .to_owned() .ok_or_else(missing_field_err("recurring_mandate_payment_data")) } fn get_optional_billing_full_name(&self) -> Option<Secret<String>> { self.get_optional_billing() .and_then(|billing_details| billing_details.address.as_ref()) .and_then(|billing_address| billing_address.get_optional_full_name()) } #[cfg(feature = "payouts")] fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error> { self.payout_method_data .to_owned() .ok_or_else(missing_field_err("payout_method_data")) } #[cfg(feature = "payouts")] fn get_quote_id(&self) -> Result<String, Error> { self.quote_id .to_owned() .ok_or_else(missing_field_err("quote_id")) } } pub trait AddressData { fn get_email(&self) -> Result<Email, Error>; fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error>; fn get_optional_country(&self) -> Option<enums::CountryAlpha2>; fn get_optional_full_name(&self) -> Option<Secret<String>>; } impl AddressData for hyperswitch_domain_models::address::Address { fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error> { self.phone .clone() .map(|phone_details| phone_details.get_number_with_country_code()) .transpose()? .ok_or_else(missing_field_err("phone")) } fn get_optional_country(&self) -> Option<enums::CountryAlpha2> { self.address .as_ref() .and_then(|billing_details| billing_details.country) } fn get_optional_full_name(&self) -> Option<Secret<String>> { self.address .as_ref() .and_then(|billing_address| billing_address.get_optional_full_name()) } } pub trait PaymentsPreProcessingData { fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>; fn get_email(&self) -> Result<Email, Error>; fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>; fn get_currency(&self) -> Result<enums::Currency, Error>; fn get_amount(&self) -> Result<i64, Error>; fn get_minor_amount(&self) -> Result<MinorUnit, Error>; fn is_auto_capture(&self) -> Result<bool, Error>; fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; fn get_webhook_url(&self) -> Result<String, Error>; fn get_router_return_url(&self) -> Result<String, Error>; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_complete_authorize_url(&self) -> Result<String, Error>; fn connector_mandate_id(&self) -> Option<String>; } impl PaymentsPreProcessingData for types::PaymentsPreProcessingData { fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> { self.payment_method_type .to_owned() .ok_or_else(missing_field_err("payment_method_type")) } fn get_currency(&self) -> Result<enums::Currency, Error> { self.currency.ok_or_else(missing_field_err("currency")) } fn get_amount(&self) -> Result<i64, Error> { self.amount.ok_or_else(missing_field_err("amount")) } // New minor amount function for amount framework fn get_minor_amount(&self) -> Result<MinorUnit, Error> { self.minor_amount.ok_or_else(missing_field_err("amount")) } fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { Some(enums::CaptureMethod::Automatic) | None | Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true), Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { self.order_details .clone() .ok_or_else(missing_field_err("order_details")) } fn get_webhook_url(&self) -> Result<String, Error> { self.webhook_url .clone() .ok_or_else(missing_field_err("webhook_url")) } fn get_router_return_url(&self) -> Result<String, Error> { self.router_return_url .clone() .ok_or_else(missing_field_err("return_url")) } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_complete_authorize_url(&self) -> Result<String, Error> { self.complete_authorize_url .clone() .ok_or_else(missing_field_err("complete_authorize_url")) } fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error> { self.redirect_response .as_ref() .and_then(|res| res.payload.to_owned()) .ok_or( errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.payload", } .into(), ) } fn connector_mandate_id(&self) -> Option<String> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => { connector_mandate_ids.get_connector_mandate_id() } Some(payments::MandateReferenceId::NetworkMandateId(_)) | None | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None, }) } } pub trait PaymentsCaptureRequestData { fn is_multiple_capture(&self) -> bool; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_capture_method(&self) -> Option<enums::CaptureMethod>; } impl PaymentsCaptureRequestData for types::PaymentsCaptureData { fn is_multiple_capture(&self) -> bool { self.multiple_capture_data.is_some() } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_capture_method(&self) -> Option<enums::CaptureMethod> { self.capture_method.to_owned() } } pub trait SplitPaymentData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest>; } impl SplitPaymentData for types::PaymentsCaptureData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { None } } impl SplitPaymentData for types::PaymentsAuthorizeData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { self.split_payments.clone() } } impl SplitPaymentData for types::PaymentsSyncData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { self.split_payments.clone() } } impl SplitPaymentData for PaymentsCancelData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { None } } impl SplitPaymentData for types::SetupMandateRequestData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { None } } pub trait RevokeMandateRequestData { fn get_connector_mandate_id(&self) -> Result<String, Error>; } impl RevokeMandateRequestData for types::MandateRevokeRequestData { fn get_connector_mandate_id(&self) -> Result<String, Error> { self.connector_mandate_id .clone() .ok_or_else(missing_field_err("connector_mandate_id")) } } pub trait PaymentsSetupMandateRequestData { fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_email(&self) -> Result<Email, Error>; fn is_card(&self) -> bool; } impl PaymentsSetupMandateRequestData for types::SetupMandateRequestData { fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn is_card(&self) -> bool { matches!(self.payment_method_data, domain::PaymentMethodData::Card(_)) } } pub trait PaymentsAuthorizeRequestData { fn is_auto_capture(&self) -> Result<bool, Error>; fn get_email(&self) -> Result<Email, Error>; fn get_optional_email(&self) -> Option<Email>; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; fn get_card(&self) -> Result<domain::Card, Error>; fn connector_mandate_id(&self) -> Option<String>; fn get_optional_network_transaction_id(&self) -> Option<String>; fn is_mandate_payment(&self) -> bool; fn is_cit_mandate_payment(&self) -> bool; fn is_customer_initiated_mandate_payment(&self) -> bool; fn get_webhook_url(&self) -> Result<String, Error>; fn get_router_return_url(&self) -> Result<String, Error>; fn is_wallet(&self) -> bool; fn is_card(&self) -> bool; fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>; fn get_connector_mandate_id(&self) -> Result<String, Error>; fn get_complete_authorize_url(&self) -> Result<String, Error>; fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>>; fn get_original_amount(&self) -> i64; fn get_surcharge_amount(&self) -> Option<i64>; fn get_tax_on_surcharge_amount(&self) -> Option<i64>; fn get_total_surcharge_amount(&self) -> Option<i64>; fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue>; fn get_authentication_data(&self) -> Result<AuthenticationData, Error>; fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error>; } pub trait PaymentMethodTokenizationRequestData { fn get_browser_info(&self) -> Result<BrowserInformation, Error>; } impl PaymentMethodTokenizationRequestData for types::PaymentMethodTokenizationData { fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } } impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData { fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { Some(enums::CaptureMethod::Automatic) | None | Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true), Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn get_optional_email(&self) -> Option<Email> { self.email.clone() } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { self.order_details .clone() .ok_or_else(missing_field_err("order_details")) } fn get_card(&self) -> Result<domain::Card, Error> { match self.payment_method_data.clone() { domain::PaymentMethodData::Card(card) => Ok(card), _ => Err(missing_field_err("card")()), } } fn get_complete_authorize_url(&self) -> Result<String, Error> { self.complete_authorize_url .clone() .ok_or_else(missing_field_err("complete_authorize_url")) } fn connector_mandate_id(&self) -> Option<String> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => { connector_mandate_ids.get_connector_mandate_id() } Some(payments::MandateReferenceId::NetworkMandateId(_)) | None | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None, }) } fn get_optional_network_transaction_id(&self) -> Option<String> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => { Some(network_transaction_id.clone()) } Some(payments::MandateReferenceId::ConnectorMandateId(_)) | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) | None => None, }) } fn is_mandate_payment(&self) -> bool { ((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession)) || self .mandate_id .as_ref() .and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref()) .is_some() } fn is_cit_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession) } fn get_webhook_url(&self) -> Result<String, Error> { self.webhook_url .clone() .ok_or_else(missing_field_err("webhook_url")) } fn get_router_return_url(&self) -> Result<String, Error> { self.router_return_url .clone() .ok_or_else(missing_field_err("return_url")) } fn is_wallet(&self) -> bool { matches!( self.payment_method_data, domain::PaymentMethodData::Wallet(_) ) } fn is_card(&self) -> bool { matches!(self.payment_method_data, domain::PaymentMethodData::Card(_)) } fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> { self.payment_method_type .to_owned() .ok_or_else(missing_field_err("payment_method_type")) } fn get_connector_mandate_id(&self) -> Result<String, Error> { self.connector_mandate_id() .ok_or_else(missing_field_err("connector_mandate_id")) } fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>> { self.browser_info.clone().and_then(|browser_info| { browser_info .ip_address .map(|ip| Secret::new(ip.to_string())) }) } fn get_original_amount(&self) -> i64 { self.surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.original_amount.get_amount_as_i64()) .unwrap_or(self.amount) } fn get_surcharge_amount(&self) -> Option<i64> { self.surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.surcharge_amount.get_amount_as_i64()) } fn get_tax_on_surcharge_amount(&self) -> Option<i64> { self.surcharge_details.as_ref().map(|surcharge_details| { surcharge_details .tax_on_surcharge_amount .get_amount_as_i64() }) } fn get_total_surcharge_amount(&self) -> Option<i64> { self.surcharge_details.as_ref().map(|surcharge_details| { surcharge_details .get_total_surcharge_amount() .get_amount_as_i64() }) } fn is_customer_initiated_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession) } fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue> { self.metadata.clone().and_then(|meta_data| match meta_data { serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::Number(_) | serde_json::Value::String(_) | serde_json::Value::Array(_) => None, serde_json::Value::Object(_) => Some(meta_data.into()), }) } fn get_authentication_data(&self) -> Result<AuthenticationData, Error> { self.authentication_data .clone() .ok_or_else(missing_field_err("authentication_data")) } /// Attempts to retrieve the connector mandate reference ID as a `Result<String, Error>`. fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => { connector_mandate_ids.get_connector_mandate_request_reference_id() } Some(payments::MandateReferenceId::NetworkMandateId(_)) | None | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None, }) .ok_or_else(missing_field_err("connector_mandate_request_reference_id")) } } pub trait ConnectorCustomerData { fn get_email(&self) -> Result<Email, Error>; } impl ConnectorCustomerData for types::ConnectorCustomerData { fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } } pub trait BrowserInformationData { fn get_accept_header(&self) -> Result<String, Error>; fn get_language(&self) -> Result<String, Error>; fn get_screen_height(&self) -> Result<u32, Error>; fn get_screen_width(&self) -> Result<u32, Error>; fn get_color_depth(&self) -> Result<u8, Error>; fn get_user_agent(&self) -> Result<String, Error>; fn get_time_zone(&self) -> Result<i32, Error>; fn get_java_enabled(&self) -> Result<bool, Error>; fn get_java_script_enabled(&self) -> Result<bool, Error>; fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error>; } impl BrowserInformationData for BrowserInformation { fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error> { let ip_address = self .ip_address .ok_or_else(missing_field_err("browser_info.ip_address"))?; Ok(Secret::new(ip_address.to_string())) } fn get_accept_header(&self) -> Result<String, Error> { self.accept_header .clone() .ok_or_else(missing_field_err("browser_info.accept_header")) } fn get_language(&self) -> Result<String, Error> { self.language .clone() .ok_or_else(missing_field_err("browser_info.language")) } fn get_screen_height(&self) -> Result<u32, Error> { self.screen_height .ok_or_else(missing_field_err("browser_info.screen_height")) } fn get_screen_width(&self) -> Result<u32, Error> { self.screen_width .ok_or_else(missing_field_err("browser_info.screen_width")) } fn get_color_depth(&self) -> Result<u8, Error> { self.color_depth .ok_or_else(missing_field_err("browser_info.color_depth")) } fn get_user_agent(&self) -> Result<String, Error> { self.user_agent .clone() .ok_or_else(missing_field_err("browser_info.user_agent")) } fn get_time_zone(&self) -> Result<i32, Error> { self.time_zone .ok_or_else(missing_field_err("browser_info.time_zone")) } fn get_java_enabled(&self) -> Result<bool, Error> { self.java_enabled .ok_or_else(missing_field_err("browser_info.java_enabled")) } fn get_java_script_enabled(&self) -> Result<bool, Error> { self.java_script_enabled .ok_or_else(missing_field_err("browser_info.java_script_enabled")) } } pub trait PaymentsCompleteAuthorizeRequestData { fn is_auto_capture(&self) -> Result<bool, Error>; fn get_email(&self) -> Result<Email, Error>; fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>; fn get_complete_authorize_url(&self) -> Result<String, Error>; fn is_mandate_payment(&self) -> bool; fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error>; fn is_cit_mandate_payment(&self) -> bool; } impl PaymentsCompleteAuthorizeRequestData for types::CompleteAuthorizeData { fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { Some(enums::CaptureMethod::Automatic) | None | Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true), Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error> { self.redirect_response .as_ref() .and_then(|res| res.payload.to_owned()) .ok_or( errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.payload", } .into(), ) } fn get_complete_authorize_url(&self) -> Result<String, Error> { self.complete_authorize_url .clone() .ok_or_else(missing_field_err("complete_authorize_url")) } fn is_mandate_payment(&self) -> bool { ((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession)) || self .mandate_id .as_ref() .and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref()) .is_some() } fn is_cit_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession) } /// Attempts to retrieve the connector mandate reference ID as a `Result<String, Error>`. fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => { connector_mandate_ids.get_connector_mandate_request_reference_id() } Some(payments::MandateReferenceId::NetworkMandateId(_)) | None | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None, }) .ok_or_else(missing_field_err("connector_mandate_request_reference_id")) } } pub trait PaymentsSyncRequestData { fn is_auto_capture(&self) -> Result<bool, Error>; fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError>; } impl PaymentsSyncRequestData for types::PaymentsSyncData { fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { Some(enums::CaptureMethod::Automatic) | None | Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true), Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError> { match self.connector_transaction_id.clone() { ResponseId::ConnectorTransactionId(txn_id) => Ok(txn_id), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "connector_transaction_id", }) .attach_printable("Expected connector transaction ID not found") .change_context(errors::ConnectorError::MissingConnectorTransactionID)?, } } } pub trait PaymentsPostSessionTokensRequestData { fn is_auto_capture(&self) -> Result<bool, Error>; } impl PaymentsPostSessionTokensRequestData for types::PaymentsPostSessionTokensData { fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { Some(enums::CaptureMethod::Automatic) | None | Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true), Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } } pub trait PaymentsCancelRequestData { fn get_amount(&self) -> Result<i64, Error>; fn get_currency(&self) -> Result<enums::Currency, Error>; fn get_cancellation_reason(&self) -> Result<String, Error>; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; } impl PaymentsCancelRequestData for PaymentsCancelData { fn get_amount(&self) -> Result<i64, Error> { self.amount.ok_or_else(missing_field_err("amount")) } fn get_currency(&self) -> Result<enums::Currency, Error> { self.currency.ok_or_else(missing_field_err("currency")) } fn get_cancellation_reason(&self) -> Result<String, Error> { self.cancellation_reason .clone() .ok_or_else(missing_field_err("cancellation_reason")) } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } } pub trait RefundsRequestData { fn get_connector_refund_id(&self) -> Result<String, Error>; fn get_webhook_url(&self) -> Result<String, Error>; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_connector_metadata(&self) -> Result<serde_json::Value, Error>; } impl RefundsRequestData for types::RefundsData { #[track_caller] fn get_connector_refund_id(&self) -> Result<String, Error> { self.connector_refund_id .clone() .get_required_value("connector_refund_id") .change_context(errors::ConnectorError::MissingConnectorTransactionID) } fn get_webhook_url(&self) -> Result<String, Error> { self.webhook_url .clone() .ok_or_else(missing_field_err("webhook_url")) } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_connector_metadata(&self) -> Result<serde_json::Value, Error> { self.connector_metadata .clone() .ok_or_else(missing_field_err("connector_metadata")) } } #[cfg(feature = "payouts")] pub trait PayoutsData { fn get_transfer_id(&self) -> Result<String, Error>; fn get_customer_details(&self) -> Result<types::CustomerDetails, Error>; fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error>; #[cfg(feature = "payouts")] fn get_payout_type(&self) -> Result<storage_enums::PayoutType, Error>; } #[cfg(feature = "payouts")] impl PayoutsData for types::PayoutsData { fn get_transfer_id(&self) -> Result<String, Error> { self.connector_payout_id .clone() .ok_or_else(missing_field_err("transfer_id")) } fn get_customer_details(&self) -> Result<types::CustomerDetails, Error> { self.customer_details .clone() .ok_or_else(missing_field_err("customer_details")) } fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error> { self.vendor_details .clone() .ok_or_else(missing_field_err("vendor_details")) } #[cfg(feature = "payouts")] fn get_payout_type(&self) -> Result<storage_enums::PayoutType, Error> { self.payout_type .to_owned() .ok_or_else(missing_field_err("payout_type")) } } static CARD_REGEX: LazyLock<HashMap<CardIssuer, Result<Regex, regex::Error>>> = LazyLock::new( || { let mut map = HashMap::new(); // Reference: https://gist.github.com/michaelkeevildown/9096cd3aac9029c4e6e05588448a8841 // [#379]: Determine card issuer from card BIN number map.insert(CardIssuer::Master, Regex::new(r"^5[1-5][0-9]{14}$")); map.insert(CardIssuer::AmericanExpress, Regex::new(r"^3[47][0-9]{13}$")); map.insert(CardIssuer::Visa, Regex::new(r"^4[0-9]{12}(?:[0-9]{3})?$")); map.insert(CardIssuer::Discover, Regex::new(r"^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$")); map.insert( CardIssuer::Maestro, Regex::new(r"^(5018|5020|5038|5893|6304|6759|6761|6762|6763)[0-9]{8,15}$"), ); map.insert( CardIssuer::DinersClub, Regex::new(r"^3(?:0[0-5]|[68][0-9])[0-9]{11}$"), ); map.insert( CardIssuer::JCB, Regex::new(r"^(3(?:088|096|112|158|337|5(?:2[89]|[3-8][0-9]))\d{12})$"), ); map.insert(CardIssuer::CarteBlanche, Regex::new(r"^389[0-9]{11}$")); map }, ); #[derive(Debug, Copy, Clone, strum::Display, Eq, Hash, PartialEq)] pub enum CardIssuer { AmericanExpress, Master, Maestro, Visa, Discover, DinersClub, JCB, CarteBlanche, } pub trait CardData { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>; fn get_card_issuer(&self) -> Result<CardIssuer, Error>; fn get_card_expiry_month_year_2_digit_with_delimiter( &self, delimiter: String, ) -> Result<Secret<String>, errors::ConnectorError>; fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String>; fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String>; fn get_expiry_year_4_digit(&self) -> Secret<String>; fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError>; fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error>; fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error>; } #[cfg(feature = "payouts")] impl CardData for payouts::CardPayout { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let binding = self.expiry_year.clone(); let year = binding.peek(); Ok(Secret::new( year.get(year.len() - 2..) .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_string(), )) } fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.card_number.peek()) } fn get_card_expiry_month_year_2_digit_with_delimiter( &self, delimiter: String, ) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?; Ok(Secret::new(format!( "{}{}{}", self.expiry_month.peek(), delimiter, year.peek() ))) } fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", year.peek(), delimiter, self.expiry_month.peek() )) } fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", self.expiry_month.peek(), delimiter, year.peek() )) } fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.expiry_year.peek().clone(); if year.len() == 2 { year = format!("20{year}"); } Secret::new(year) } fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?.expose(); let month = self.expiry_month.clone().expose(); Ok(Secret::new(format!("{year}{month}"))) } fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> { self.expiry_month .peek() .clone() .parse::<i8>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> { self.expiry_year .peek() .clone() .parse::<i32>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } } impl CardData for hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let binding = self.card_exp_year.clone(); let year = binding.peek(); Ok(Secret::new( year.get(year.len() - 2..) .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_string(), )) } fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.card_number.peek()) } fn get_card_expiry_month_year_2_digit_with_delimiter( &self, delimiter: String, ) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?; Ok(Secret::new(format!( "{}{}{}", self.card_exp_month.peek(), delimiter, year.peek() ))) } fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", year.peek(), delimiter, self.card_exp_month.peek() )) } fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", self.card_exp_month.peek(), delimiter, year.peek() )) } fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.card_exp_year.peek().clone(); if year.len() == 2 { year = format!("20{year}"); } Secret::new(year) } fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?.expose(); let month = self.card_exp_month.clone().expose(); Ok(Secret::new(format!("{year}{month}"))) } fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> { self.card_exp_month .peek() .clone() .parse::<i8>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> { self.card_exp_year .peek() .clone() .parse::<i32>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } } impl CardData for domain::Card { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let binding = self.card_exp_year.clone(); let year = binding.peek(); Ok(Secret::new( year.get(year.len() - 2..) .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_string(), )) } fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.card_number.peek()) } fn get_card_expiry_month_year_2_digit_with_delimiter( &self, delimiter: String, ) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?; Ok(Secret::new(format!( "{}{}{}", self.card_exp_month.peek(), delimiter, year.peek() ))) } fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", year.peek(), delimiter, self.card_exp_month.peek() )) } fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", self.card_exp_month.peek(), delimiter, year.peek() )) } fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.card_exp_year.peek().clone(); if year.len() == 2 { year = format!("20{year}"); } Secret::new(year) } fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?.expose(); let month = self.card_exp_month.clone().expose(); Ok(Secret::new(format!("{year}{month}"))) } fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> { self.card_exp_month .peek() .clone() .parse::<i8>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> { self.card_exp_year .peek() .clone() .parse::<i32>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } } #[track_caller] fn get_card_issuer(card_number: &str) -> Result<CardIssuer, Error> { for (k, v) in CARD_REGEX.iter() { let regex: Regex = v .clone() .change_context(errors::ConnectorError::RequestEncodingFailed)?; if regex.is_match(card_number) { return Ok(*k); } } Err(error_stack::Report::new( errors::ConnectorError::NotImplemented("Card Type".into()), )) } pub trait WalletData { fn get_wallet_token(&self) -> Result<Secret<String>, Error>; fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error> where T: serde::de::DeserializeOwned; fn get_encoded_wallet_token(&self) -> Result<String, Error>; } impl WalletData for domain::WalletData { fn get_wallet_token(&self) -> Result<Secret<String>, Error> { match self { Self::GooglePay(data) => Ok(data.get_googlepay_encrypted_payment_data()?), Self::ApplePay(data) => Ok(data.get_applepay_decoded_payment_data()?), Self::PaypalSdk(data) => Ok(Secret::new(data.token.clone())), _ => Err(errors::ConnectorError::InvalidWallet.into()), } } fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error> where T: serde::de::DeserializeOwned, { serde_json::from_str::<T>(self.get_wallet_token()?.peek()) .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name }) } fn get_encoded_wallet_token(&self) -> Result<String, Error> { match self { Self::GooglePay(_) => { let json_token: serde_json::Value = self.get_wallet_token_as_json("Google Pay".to_owned())?; let token_as_vec = serde_json::to_vec(&json_token).change_context( errors::ConnectorError::InvalidWalletToken { wallet_name: "Google Pay".to_string(), }, )?; let encoded_token = consts::BASE64_ENGINE.encode(token_as_vec); Ok(encoded_token) } _ => Err( errors::ConnectorError::NotImplemented("SELECTED PAYMENT METHOD".to_owned()).into(), ), } } } pub trait ApplePay { fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error>; } impl ApplePay for domain::ApplePayWalletData { fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error> { let apple_pay_encrypted_data = self .payment_data .get_encrypted_apple_pay_payment_data_mandatory() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "Apple pay encrypted data", })?; let token = Secret::new( String::from_utf8( consts::BASE64_ENGINE .decode(apple_pay_encrypted_data) .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name: "Apple Pay".to_string(), })?, ) .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name: "Apple Pay".to_string(), })?, ); Ok(token) } } pub trait GooglePay { fn get_googlepay_encrypted_payment_data(&self) -> Result<Secret<String>, Error>; } impl GooglePay for domain::GooglePayWalletData { fn get_googlepay_encrypted_payment_data(&self) -> Result<Secret<String>, Error> { let encrypted_data = self .tokenization_data .get_encrypted_google_pay_payment_data_mandatory() .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name: "Google Pay".to_string(), })?; Ok(Secret::new(encrypted_data.token.clone())) } } pub trait CryptoData { fn get_pay_currency(&self) -> Result<String, Error>; } impl CryptoData for domain::CryptoData { fn get_pay_currency(&self) -> Result<String, Error> { self.pay_currency .clone() .ok_or_else(missing_field_err("crypto_data.pay_currency")) } } pub trait PhoneDetailsData { fn get_number(&self) -> Result<Secret<String>, Error>; fn get_country_code(&self) -> Result<String, Error>; fn get_number_with_country_code(&self) -> Result<Secret<String>, Error>; fn get_number_with_hash_country_code(&self) -> Result<Secret<String>, Error>; fn extract_country_code(&self) -> Result<String, Error>; } impl PhoneDetailsData for hyperswitch_domain_models::address::PhoneDetails { fn get_country_code(&self) -> Result<String, Error> { self.country_code .clone() .ok_or_else(missing_field_err("billing.phone.country_code")) } fn extract_country_code(&self) -> Result<String, Error> { self.get_country_code() .map(|cc| cc.trim_start_matches('+').to_string()) } fn get_number(&self) -> Result<Secret<String>, Error> { self.number .clone() .ok_or_else(missing_field_err("billing.phone.number")) } fn get_number_with_country_code(&self) -> Result<Secret<String>, Error> { let number = self.get_number()?; let country_code = self.get_country_code()?; Ok(Secret::new(format!("{}{}", country_code, number.peek()))) } fn get_number_with_hash_country_code(&self) -> Result<Secret<String>, Error> { let number = self.get_number()?; let country_code = self.get_country_code()?; let number_without_plus = country_code.trim_start_matches('+'); Ok(Secret::new(format!( "{}#{}", number_without_plus, number.peek() ))) } } pub trait AddressDetailsData { fn get_first_name(&self) -> Result<&Secret<String>, Error>; fn get_last_name(&self) -> Result<&Secret<String>, Error>; fn get_full_name(&self) -> Result<Secret<String>, Error>; fn get_line1(&self) -> Result<&Secret<String>, Error>; fn get_city(&self) -> Result<&String, Error>; fn get_line2(&self) -> Result<&Secret<String>, Error>; fn get_state(&self) -> Result<&Secret<String>, Error>; fn get_zip(&self) -> Result<&Secret<String>, Error>; fn get_country(&self) -> Result<&api_models::enums::CountryAlpha2, Error>; fn get_combined_address_line(&self) -> Result<Secret<String>, Error>; fn get_optional_line2(&self) -> Option<Secret<String>>; fn get_optional_country(&self) -> Option<api_models::enums::CountryAlpha2>; } impl AddressDetailsData for hyperswitch_domain_models::address::AddressDetails { fn get_first_name(&self) -> Result<&Secret<String>, Error> { self.first_name .as_ref() .ok_or_else(missing_field_err("address.first_name")) } fn get_last_name(&self) -> Result<&Secret<String>, Error> { self.last_name .as_ref() .ok_or_else(missing_field_err("address.last_name")) } fn get_full_name(&self) -> Result<Secret<String>, Error> { let first_name = self.get_first_name()?.peek().to_owned(); let last_name = self .get_last_name() .ok() .cloned() .unwrap_or(Secret::new("".to_string())); let last_name = last_name.peek(); let full_name = format!("{first_name} {last_name}").trim().to_string(); Ok(Secret::new(full_name)) } fn get_line1(&self) -> Result<&Secret<String>, Error> { self.line1 .as_ref() .ok_or_else(missing_field_err("address.line1")) } fn get_city(&self) -> Result<&String, Error> { self.city .as_ref() .ok_or_else(missing_field_err("address.city")) } fn get_state(&self) -> Result<&Secret<String>, Error> { self.state .as_ref() .ok_or_else(missing_field_err("address.state")) } fn get_line2(&self) -> Result<&Secret<String>, Error> { self.line2 .as_ref() .ok_or_else(missing_field_err("address.line2")) } fn get_zip(&self) -> Result<&Secret<String>, Error> { self.zip .as_ref() .ok_or_else(missing_field_err("address.zip")) } fn get_country(&self) -> Result<&api_models::enums::CountryAlpha2, Error> { self.country .as_ref() .ok_or_else(missing_field_err("address.country")) } fn get_combined_address_line(&self) -> Result<Secret<String>, Error> { Ok(Secret::new(format!( "{},{}", self.get_line1()?.peek(), self.get_line2()?.peek() ))) } fn get_optional_line2(&self) -> Option<Secret<String>> { self.line2.clone() } fn get_optional_country(&self) -> Option<api_models::enums::CountryAlpha2> { self.country } } pub trait MandateData { fn get_end_date(&self, format: date_time::DateFormat) -> Result<String, Error>; fn get_metadata(&self) -> Result<pii::SecretSerdeValue, Error>; } impl MandateData for payments::MandateAmountData { fn get_end_date(&self, format: date_time::DateFormat) -> Result<String, Error> { let date = self.end_date.ok_or_else(missing_field_err( "mandate_data.mandate_type.{multi_use|single_use}.end_date", ))?; date_time::format_date(date, format) .change_context(errors::ConnectorError::DateFormattingFailed) } fn get_metadata(&self) -> Result<pii::SecretSerdeValue, Error> { self.metadata.clone().ok_or_else(missing_field_err( "mandate_data.mandate_type.{multi_use|single_use}.metadata", )) } } pub trait RecurringMandateData { fn get_original_payment_amount(&self) -> Result<i64, Error>; fn get_original_payment_currency(&self) -> Result<enums::Currency, Error>; } impl RecurringMandateData for types::RecurringMandatePaymentData { fn get_original_payment_amount(&self) -> Result<i64, Error> { self.original_payment_authorized_amount .ok_or_else(missing_field_err("original_payment_authorized_amount")) } fn get_original_payment_currency(&self) -> Result<enums::Currency, Error> { self.original_payment_authorized_currency .ok_or_else(missing_field_err("original_payment_authorized_currency")) } } pub trait MandateReferenceData { fn get_connector_mandate_id(&self) -> Result<String, Error>; } impl MandateReferenceData for payments::ConnectorMandateReferenceId { fn get_connector_mandate_id(&self) -> Result<String, Error> { self.get_connector_mandate_id() .ok_or_else(missing_field_err("mandate_id")) } } pub fn get_header_key_value<'a>( key: &str, headers: &'a actix_web::http::header::HeaderMap, ) -> CustomResult<&'a str, errors::ConnectorError> { get_header_field(headers.get(key)) } fn get_header_field( field: Option<&http::HeaderValue>, ) -> CustomResult<&str, errors::ConnectorError> { field .map(|header_value| { header_value .to_str() .change_context(errors::ConnectorError::WebhookSignatureNotFound) }) .ok_or(report!( errors::ConnectorError::WebhookSourceVerificationFailed ))? } pub fn to_connector_meta<T>(connector_meta: Option<serde_json::Value>) -> Result<T, Error> where T: serde::de::DeserializeOwned, { let json = connector_meta.ok_or_else(missing_field_err("connector_meta_data"))?; json.parse_value(std::any::type_name::<T>()).switch() } pub fn to_connector_meta_from_secret<T>( connector_meta: Option<Secret<serde_json::Value>>, ) -> Result<T, Error> where T: serde::de::DeserializeOwned, { let connector_meta_secret = connector_meta.ok_or_else(missing_field_err("connector_meta_data"))?; let json = connector_meta_secret.expose(); json.parse_value(std::any::type_name::<T>()).switch() } impl ForeignTryFrom<String> for UsStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "UsStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => { let binding = value.as_str().to_lowercase(); let state = binding.as_str(); match state { "alabama" => Ok(Self::AL), "alaska" => Ok(Self::AK), "american samoa" => Ok(Self::AS), "arizona" => Ok(Self::AZ), "arkansas" => Ok(Self::AR), "california" => Ok(Self::CA), "colorado" => Ok(Self::CO), "connecticut" => Ok(Self::CT), "delaware" => Ok(Self::DE), "district of columbia" | "columbia" => Ok(Self::DC), "federated states of micronesia" | "micronesia" => Ok(Self::FM), "florida" => Ok(Self::FL), "georgia" => Ok(Self::GA), "guam" => Ok(Self::GU), "hawaii" => Ok(Self::HI), "idaho" => Ok(Self::ID), "illinois" => Ok(Self::IL), "indiana" => Ok(Self::IN), "iowa" => Ok(Self::IA), "kansas" => Ok(Self::KS), "kentucky" => Ok(Self::KY), "louisiana" => Ok(Self::LA), "maine" => Ok(Self::ME), "marshall islands" => Ok(Self::MH), "maryland" => Ok(Self::MD), "massachusetts" => Ok(Self::MA), "michigan" => Ok(Self::MI), "minnesota" => Ok(Self::MN), "mississippi" => Ok(Self::MS), "missouri" => Ok(Self::MO), "montana" => Ok(Self::MT), "nebraska" => Ok(Self::NE), "nevada" => Ok(Self::NV), "new hampshire" => Ok(Self::NH), "new jersey" => Ok(Self::NJ), "new mexico" => Ok(Self::NM), "new york" => Ok(Self::NY), "north carolina" => Ok(Self::NC), "north dakota" => Ok(Self::ND), "northern mariana islands" => Ok(Self::MP), "ohio" => Ok(Self::OH), "oklahoma" => Ok(Self::OK), "oregon" => Ok(Self::OR), "palau" => Ok(Self::PW), "pennsylvania" => Ok(Self::PA), "puerto rico" => Ok(Self::PR), "rhode island" => Ok(Self::RI), "south carolina" => Ok(Self::SC), "south dakota" => Ok(Self::SD), "tennessee" => Ok(Self::TN), "texas" => Ok(Self::TX), "utah" => Ok(Self::UT), "vermont" => Ok(Self::VT), "virgin islands" => Ok(Self::VI), "virginia" => Ok(Self::VA), "washington" => Ok(Self::WA), "west virginia" => Ok(Self::WV), "wisconsin" => Ok(Self::WI), "wyoming" => Ok(Self::WY), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), } } } } } impl ForeignTryFrom<String> for CanadaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "CanadaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => { let binding = value.as_str().to_lowercase(); let state = binding.as_str(); match state { "alberta" => Ok(Self::AB), "british columbia" => Ok(Self::BC), "manitoba" => Ok(Self::MB), "new brunswick" => Ok(Self::NB), "newfoundland and labrador" | "newfoundland & labrador" => Ok(Self::NL), "northwest territories" => Ok(Self::NT), "nova scotia" => Ok(Self::NS), "nunavut" => Ok(Self::NU), "ontario" => Ok(Self::ON), "prince edward island" => Ok(Self::PE), "quebec" => Ok(Self::QC), "saskatchewan" => Ok(Self::SK), "yukon" => Ok(Self::YT), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), } } } } } pub trait ConnectorErrorTypeMapping { fn get_connector_error_type( &self, _error_code: String, _error_message: String, ) -> ConnectorErrorType { ConnectorErrorType::UnknownError } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct ErrorCodeAndMessage { pub error_code: String, pub error_message: String, } #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)] //Priority of connector_error_type pub enum ConnectorErrorType { UserError = 2, BusinessError = 3, TechnicalError = 4, UnknownError = 1, } //Gets the list of error_code_and_message, sorts based on the priority of error_type and gives most prior error // This could be used in connectors where we get list of error_messages and have to choose one error_message pub fn get_error_code_error_message_based_on_priority( connector: impl ConnectorErrorTypeMapping, error_list: Vec<ErrorCodeAndMessage>, ) -> Option<ErrorCodeAndMessage> { let error_type_list = error_list .iter() .map(|error| { connector .get_connector_error_type(error.error_code.clone(), error.error_message.clone()) }) .collect::<Vec<ConnectorErrorType>>(); let mut error_zip_list = error_list .iter() .zip(error_type_list.iter()) .collect::<Vec<(&ErrorCodeAndMessage, &ConnectorErrorType)>>(); error_zip_list.sort_by_key(|&(_, error_type)| error_type); error_zip_list .first() .map(|&(error_code_message, _)| error_code_message) .cloned() } pub trait MultipleCaptureSyncResponse { fn get_connector_capture_id(&self) -> String; fn get_capture_attempt_status(&self) -> enums::AttemptStatus; fn is_capture_response(&self) -> bool; fn get_connector_reference_id(&self) -> Option<String> { None } fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>>; } #[cfg(feature = "frm")] pub trait FraudCheckSaleRequest { fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; } #[cfg(feature = "frm")] impl FraudCheckSaleRequest for fraud_check::FraudCheckSaleData { fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { self.order_details .clone() .ok_or_else(missing_field_err("order_details")) } } #[cfg(feature = "frm")] pub trait FraudCheckRecordReturnRequest { fn get_currency(&self) -> Result<storage_enums::Currency, Error>; } #[cfg(feature = "frm")] impl FraudCheckRecordReturnRequest for fraud_check::FraudCheckRecordReturnData { fn get_currency(&self) -> Result<storage_enums::Currency, Error> { self.currency.ok_or_else(missing_field_err("currency")) } } #[cfg(feature = "v1")] pub trait PaymentsAttemptData { fn get_browser_info(&self) -> Result<BrowserInformation, error_stack::Report<ApiErrorResponse>>; } #[cfg(feature = "v1")] impl PaymentsAttemptData for PaymentAttempt { fn get_browser_info( &self, ) -> Result<BrowserInformation, error_stack::Report<ApiErrorResponse>> { self.browser_info .clone() .ok_or(ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })? .parse_value::<BrowserInformation>("BrowserInformation") .change_context(ApiErrorResponse::InvalidDataValue { field_name: "browser_info", }) } } #[cfg(feature = "frm")] pub trait FrmTransactionRouterDataRequest { fn is_payment_successful(&self) -> Option<bool>; } #[cfg(feature = "frm")] impl FrmTransactionRouterDataRequest for fraud_check::FrmTransactionRouterData { fn is_payment_successful(&self) -> Option<bool> { match self.status { storage_enums::AttemptStatus::AuthenticationFailed | storage_enums::AttemptStatus::RouterDeclined | storage_enums::AttemptStatus::AuthorizationFailed | storage_enums::AttemptStatus::Voided | storage_enums::AttemptStatus::VoidedPostCharge | storage_enums::AttemptStatus::CaptureFailed | storage_enums::AttemptStatus::Failure | storage_enums::AttemptStatus::AutoRefunded | storage_enums::AttemptStatus::Expired => Some(false), storage_enums::AttemptStatus::AuthenticationSuccessful | storage_enums::AttemptStatus::PartialChargedAndChargeable | storage_enums::AttemptStatus::Authorized | storage_enums::AttemptStatus::Charged | storage_enums::AttemptStatus::PartiallyAuthorized => Some(true), storage_enums::AttemptStatus::Started | storage_enums::AttemptStatus::AuthenticationPending | storage_enums::AttemptStatus::Authorizing | storage_enums::AttemptStatus::CodInitiated | storage_enums::AttemptStatus::VoidInitiated | storage_enums::AttemptStatus::CaptureInitiated | storage_enums::AttemptStatus::VoidFailed | storage_enums::AttemptStatus::PartialCharged | storage_enums::AttemptStatus::Unresolved | storage_enums::AttemptStatus::Pending | storage_enums::AttemptStatus::PaymentMethodAwaited | storage_enums::AttemptStatus::ConfirmationAwaited | storage_enums::AttemptStatus::DeviceDataCollectionPending | storage_enums::AttemptStatus::IntegrityFailure => None, } } } pub fn is_payment_failure(status: enums::AttemptStatus) -> bool { match status { common_enums::AttemptStatus::AuthenticationFailed | common_enums::AttemptStatus::AuthorizationFailed | common_enums::AttemptStatus::CaptureFailed | common_enums::AttemptStatus::VoidFailed | common_enums::AttemptStatus::Failure | common_enums::AttemptStatus::Expired => true, common_enums::AttemptStatus::Started | common_enums::AttemptStatus::RouterDeclined | common_enums::AttemptStatus::AuthenticationPending | common_enums::AttemptStatus::AuthenticationSuccessful | common_enums::AttemptStatus::Authorized | common_enums::AttemptStatus::Charged | common_enums::AttemptStatus::Authorizing | common_enums::AttemptStatus::CodInitiated | common_enums::AttemptStatus::Voided | common_enums::AttemptStatus::VoidedPostCharge | common_enums::AttemptStatus::VoidInitiated | common_enums::AttemptStatus::CaptureInitiated | common_enums::AttemptStatus::AutoRefunded | common_enums::AttemptStatus::PartialCharged | common_enums::AttemptStatus::PartialChargedAndChargeable | common_enums::AttemptStatus::Unresolved | common_enums::AttemptStatus::Pending | common_enums::AttemptStatus::PaymentMethodAwaited | common_enums::AttemptStatus::ConfirmationAwaited | common_enums::AttemptStatus::DeviceDataCollectionPending | common_enums::AttemptStatus::IntegrityFailure | common_enums::AttemptStatus::PartiallyAuthorized => false, } } pub fn is_refund_failure(status: enums::RefundStatus) -> bool { match status { common_enums::RefundStatus::Failure | common_enums::RefundStatus::TransactionFailure => { true } common_enums::RefundStatus::ManualReview | common_enums::RefundStatus::Pending | common_enums::RefundStatus::Success => false, } } impl ForeignFrom<( Option<String>, Option<String>, Option<String>, u16, Option<enums::AttemptStatus>, Option<String>, )> for types::ErrorResponse { fn foreign_from( (code, message, reason, http_code, attempt_status, connector_transaction_id): ( Option<String>, Option<String>, Option<String>, u16, Option<enums::AttemptStatus>, Option<String>, ), ) -> Self { Self { code: code.unwrap_or(consts::NO_ERROR_CODE.to_string()), message: message .clone() .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), reason, status_code: http_code, attempt_status, connector_transaction_id, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, } } } pub fn get_card_details( payment_method_data: domain::PaymentMethodData, connector_name: &'static str, ) -> Result<domain::payments::Card, errors::ConnectorError> { match payment_method_data { domain::PaymentMethodData::Card(details) => Ok(details), _ => Err(errors::ConnectorError::NotSupported { message: SELECTED_PAYMENT_METHOD.to_string(), connector: connector_name, })?, } } #[cfg(test)] mod error_code_error_message_tests { #![allow(clippy::unwrap_used)] use super::*; struct TestConnector; impl ConnectorErrorTypeMapping for TestConnector { fn get_connector_error_type( &self, error_code: String, error_message: String, ) -> ConnectorErrorType { match (error_code.as_str(), error_message.as_str()) { ("01", "INVALID_MERCHANT") => ConnectorErrorType::BusinessError, ("03", "INVALID_CVV") => ConnectorErrorType::UserError, ("04", "04") => ConnectorErrorType::TechnicalError, _ => ConnectorErrorType::UnknownError, } } } #[test] fn test_get_error_code_error_message_based_on_priority() { let error_code_message_list_unknown = vec![ ErrorCodeAndMessage { error_code: "01".to_string(), error_message: "INVALID_MERCHANT".to_string(), }, ErrorCodeAndMessage { error_code: "05".to_string(), error_message: "05".to_string(), }, ErrorCodeAndMessage { error_code: "03".to_string(), error_message: "INVALID_CVV".to_string(), }, ErrorCodeAndMessage { error_code: "04".to_string(), error_message: "04".to_string(), }, ]; let error_code_message_list_user = vec![ ErrorCodeAndMessage { error_code: "01".to_string(), error_message: "INVALID_MERCHANT".to_string(), }, ErrorCodeAndMessage { error_code: "03".to_string(), error_message: "INVALID_CVV".to_string(), }, ]; let error_code_error_message_unknown = get_error_code_error_message_based_on_priority( TestConnector, error_code_message_list_unknown, ); let error_code_error_message_user = get_error_code_error_message_based_on_priority( TestConnector, error_code_message_list_user, ); let error_code_error_message_none = get_error_code_error_message_based_on_priority(TestConnector, vec![]); assert_eq!( error_code_error_message_unknown, Some(ErrorCodeAndMessage { error_code: "05".to_string(), error_message: "05".to_string(), }) ); assert_eq!( error_code_error_message_user, Some(ErrorCodeAndMessage { error_code: "03".to_string(), error_message: "INVALID_CVV".to_string(), }) ); assert_eq!(error_code_error_message_none, None); } } pub fn is_mandate_supported( selected_pmd: domain::payments::PaymentMethodData, payment_method_type: Option<types::storage::enums::PaymentMethodType>, mandate_implemented_pmds: HashSet<PaymentMethodDataType>, connector: &'static str, ) -> Result<(), Error> { if mandate_implemented_pmds.contains(&PaymentMethodDataType::from(selected_pmd.clone())) { Ok(()) } else { match payment_method_type { Some(pm_type) => Err(errors::ConnectorError::NotSupported { message: format!("{pm_type} mandate payment"), connector, } .into()), None => Err(errors::ConnectorError::NotSupported { message: " mandate payment".to_string(), connector, } .into()), } } } #[derive(Debug, strum::Display, Eq, PartialEq, Hash)] pub enum PaymentMethodDataType { Card, Knet, Benefit, MomoAtm, CardRedirect, AliPayQr, AliPayRedirect, AliPayHkRedirect, AmazonPay, AmazonPayRedirect, Paysera, Skrill, MomoRedirect, KakaoPayRedirect, GoPayRedirect, GcashRedirect, ApplePay, ApplePayRedirect, ApplePayThirdPartySdk, DanaRedirect, DuitNow, GooglePay, Bluecode, GooglePayRedirect, GooglePayThirdPartySdk, MbWayRedirect, MobilePayRedirect, PaypalRedirect, PaypalSdk, Paze, SamsungPay, TwintRedirect, VippsRedirect, TouchNGoRedirect, WeChatPayRedirect, WeChatPayQr, CashappQr, SwishQr, KlarnaRedirect, KlarnaSdk, AffirmRedirect, AfterpayClearpayRedirect, PayBrightRedirect, WalleyRedirect, AlmaRedirect, AtomeRedirect, BreadpayRedirect, FlexitiRedirect, BancontactCard, Bizum, Blik, Eft, Eps, Giropay, Ideal, Interac, LocalBankRedirect, OnlineBankingCzechRepublic, OnlineBankingFinland, OnlineBankingPoland, OnlineBankingSlovakia, OpenBankingUk, Przelewy24, Sofort, Trustly, OnlineBankingFpx, OnlineBankingThailand, AchBankDebit, SepaBankDebit, SepaGuarenteedDebit, BecsBankDebit, BacsBankDebit, AchBankTransfer, SepaBankTransfer, BacsBankTransfer, MultibancoBankTransfer, PermataBankTransfer, BcaBankTransfer, BniVaBankTransfer, BriVaBankTransfer, CimbVaBankTransfer, DanamonVaBankTransfer, MandiriVaBankTransfer, Pix, Pse, Crypto, MandatePayment, Reward, Upi, Boleto, Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart, Indomaret, Oxxo, SevenEleven, Lawson, MiniStop, FamilyMart, Seicomart, PayEasy, Givex, BhnCardNetwork, PaySafeCar, CardToken, LocalBankTransfer, Mifinity, Fps, PromptPay, VietQr, OpenBanking, NetworkToken, DirectCarrierBilling, InstantBankTransfer, InstantBankTransferFinland, InstantBankTransferPoland, RevolutPay, IndonesianBankTransfer, } impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType { fn from(pm_data: domain::payments::PaymentMethodData) -> Self { match pm_data { domain::payments::PaymentMethodData::Card(_) => Self::Card, domain::payments::PaymentMethodData::NetworkToken(_) => Self::NetworkToken, domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Self::Card, domain::payments::PaymentMethodData::CardRedirect(card_redirect_data) => { match card_redirect_data { domain::CardRedirectData::Knet {} => Self::Knet, domain::payments::CardRedirectData::Benefit {} => Self::Benefit, domain::payments::CardRedirectData::MomoAtm {} => Self::MomoAtm, domain::payments::CardRedirectData::CardRedirect {} => Self::CardRedirect, } } domain::payments::PaymentMethodData::Wallet(wallet_data) => match wallet_data { domain::payments::WalletData::AliPayQr(_) => Self::AliPayQr, domain::payments::WalletData::AliPayRedirect(_) => Self::AliPayRedirect, domain::payments::WalletData::AliPayHkRedirect(_) => Self::AliPayHkRedirect, domain::payments::WalletData::AmazonPay(_) => Self::AmazonPay, domain::payments::WalletData::AmazonPayRedirect(_) => Self::AmazonPayRedirect, domain::payments::WalletData::Paysera(_) => Self::Paysera, domain::payments::WalletData::Skrill(_) => Self::Skrill, domain::payments::WalletData::MomoRedirect(_) => Self::MomoRedirect, domain::payments::WalletData::KakaoPayRedirect(_) => Self::KakaoPayRedirect, domain::payments::WalletData::GoPayRedirect(_) => Self::GoPayRedirect, domain::payments::WalletData::GcashRedirect(_) => Self::GcashRedirect, domain::payments::WalletData::ApplePay(_) => Self::ApplePay, domain::payments::WalletData::ApplePayRedirect(_) => Self::ApplePayRedirect, domain::payments::WalletData::ApplePayThirdPartySdk(_) => { Self::ApplePayThirdPartySdk } domain::payments::WalletData::DanaRedirect {} => Self::DanaRedirect, domain::payments::WalletData::GooglePay(_) => Self::GooglePay, domain::payments::WalletData::BluecodeRedirect {} => Self::Bluecode, domain::payments::WalletData::GooglePayRedirect(_) => Self::GooglePayRedirect, domain::payments::WalletData::GooglePayThirdPartySdk(_) => { Self::GooglePayThirdPartySdk } domain::payments::WalletData::MbWayRedirect(_) => Self::MbWayRedirect, domain::payments::WalletData::MobilePayRedirect(_) => Self::MobilePayRedirect, domain::payments::WalletData::PaypalRedirect(_) => Self::PaypalRedirect, domain::payments::WalletData::PaypalSdk(_) => Self::PaypalSdk, domain::payments::WalletData::Paze(_) => Self::Paze, domain::payments::WalletData::SamsungPay(_) => Self::SamsungPay, domain::payments::WalletData::TwintRedirect {} => Self::TwintRedirect, domain::payments::WalletData::VippsRedirect {} => Self::VippsRedirect, domain::payments::WalletData::TouchNGoRedirect(_) => Self::TouchNGoRedirect, domain::payments::WalletData::WeChatPayRedirect(_) => Self::WeChatPayRedirect, domain::payments::WalletData::WeChatPayQr(_) => Self::WeChatPayQr, domain::payments::WalletData::CashappQr(_) => Self::CashappQr, domain::payments::WalletData::SwishQr(_) => Self::SwishQr, domain::payments::WalletData::Mifinity(_) => Self::Mifinity, domain::payments::WalletData::RevolutPay(_) => Self::RevolutPay, }, domain::payments::PaymentMethodData::PayLater(pay_later_data) => match pay_later_data { domain::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect, domain::payments::PayLaterData::KlarnaSdk { .. } => Self::KlarnaSdk, domain::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect, domain::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { Self::AfterpayClearpayRedirect } domain::payments::PayLaterData::PayBrightRedirect {} => Self::PayBrightRedirect, domain::payments::PayLaterData::WalleyRedirect {} => Self::WalleyRedirect, domain::payments::PayLaterData::AlmaRedirect {} => Self::AlmaRedirect, domain::payments::PayLaterData::FlexitiRedirect {} => Self::FlexitiRedirect, domain::payments::PayLaterData::AtomeRedirect {} => Self::AtomeRedirect, domain::payments::PayLaterData::BreadpayRedirect {} => Self::BreadpayRedirect, }, domain::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => { match bank_redirect_data { domain::payments::BankRedirectData::BancontactCard { .. } => { Self::BancontactCard } domain::payments::BankRedirectData::Bizum {} => Self::Bizum, domain::payments::BankRedirectData::Blik { .. } => Self::Blik, domain::payments::BankRedirectData::Eft { .. } => Self::Eft, domain::payments::BankRedirectData::Eps { .. } => Self::Eps, domain::payments::BankRedirectData::Giropay { .. } => Self::Giropay, domain::payments::BankRedirectData::Ideal { .. } => Self::Ideal, domain::payments::BankRedirectData::Interac { .. } => Self::Interac, domain::payments::BankRedirectData::OnlineBankingCzechRepublic { .. } => { Self::OnlineBankingCzechRepublic } domain::payments::BankRedirectData::OnlineBankingFinland { .. } => { Self::OnlineBankingFinland } domain::payments::BankRedirectData::OnlineBankingPoland { .. } => { Self::OnlineBankingPoland } domain::payments::BankRedirectData::OnlineBankingSlovakia { .. } => { Self::OnlineBankingSlovakia } domain::payments::BankRedirectData::OpenBankingUk { .. } => Self::OpenBankingUk, domain::payments::BankRedirectData::Przelewy24 { .. } => Self::Przelewy24, domain::payments::BankRedirectData::Sofort { .. } => Self::Sofort, domain::payments::BankRedirectData::Trustly { .. } => Self::Trustly, domain::payments::BankRedirectData::OnlineBankingFpx { .. } => { Self::OnlineBankingFpx } domain::payments::BankRedirectData::OnlineBankingThailand { .. } => { Self::OnlineBankingThailand } domain::payments::BankRedirectData::LocalBankRedirect { } => { Self::LocalBankRedirect } } } domain::payments::PaymentMethodData::BankDebit(bank_debit_data) => { match bank_debit_data { domain::payments::BankDebitData::AchBankDebit { .. } => Self::AchBankDebit, domain::payments::BankDebitData::SepaBankDebit { .. } => Self::SepaBankDebit, domain::payments::BankDebitData::SepaGuarenteedBankDebit { .. } => Self::SepaGuarenteedDebit, domain::payments::BankDebitData::BecsBankDebit { .. } => Self::BecsBankDebit, domain::payments::BankDebitData::BacsBankDebit { .. } => Self::BacsBankDebit, } } domain::payments::PaymentMethodData::BankTransfer(bank_transfer_data) => { match *bank_transfer_data { domain::payments::BankTransferData::AchBankTransfer { .. } => { Self::AchBankTransfer } domain::payments::BankTransferData::SepaBankTransfer { .. } => { Self::SepaBankTransfer } domain::payments::BankTransferData::BacsBankTransfer { .. } => { Self::BacsBankTransfer } domain::payments::BankTransferData::MultibancoBankTransfer { .. } => { Self::MultibancoBankTransfer } domain::payments::BankTransferData::PermataBankTransfer { .. } => { Self::PermataBankTransfer } domain::payments::BankTransferData::BcaBankTransfer { .. } => { Self::BcaBankTransfer } domain::payments::BankTransferData::BniVaBankTransfer { .. } => { Self::BniVaBankTransfer } domain::payments::BankTransferData::BriVaBankTransfer { .. } => { Self::BriVaBankTransfer } domain::payments::BankTransferData::CimbVaBankTransfer { .. } => { Self::CimbVaBankTransfer } domain::payments::BankTransferData::DanamonVaBankTransfer { .. } => { Self::DanamonVaBankTransfer } domain::payments::BankTransferData::MandiriVaBankTransfer { .. } => { Self::MandiriVaBankTransfer } domain::payments::BankTransferData::Pix { .. } => Self::Pix, domain::payments::BankTransferData::Pse {} => Self::Pse, domain::payments::BankTransferData::LocalBankTransfer { .. } => { Self::LocalBankTransfer } domain::payments::BankTransferData::InstantBankTransfer {} => { Self::InstantBankTransfer } domain::payments::BankTransferData::InstantBankTransferFinland {} => { Self::InstantBankTransferFinland } domain::payments::BankTransferData::InstantBankTransferPoland {} => { Self::InstantBankTransferPoland } domain::payments::BankTransferData::IndonesianBankTransfer { .. } => { Self::IndonesianBankTransfer } } } domain::payments::PaymentMethodData::Crypto(_) => Self::Crypto, domain::payments::PaymentMethodData::MandatePayment => Self::MandatePayment, domain::payments::PaymentMethodData::Reward => Self::Reward, domain::payments::PaymentMethodData::Upi(_) => Self::Upi, domain::payments::PaymentMethodData::Voucher(voucher_data) => match voucher_data { domain::payments::VoucherData::Boleto(_) => Self::Boleto, domain::payments::VoucherData::Efecty => Self::Efecty, domain::payments::VoucherData::PagoEfectivo => Self::PagoEfectivo, domain::payments::VoucherData::RedCompra => Self::RedCompra, domain::payments::VoucherData::RedPagos => Self::RedPagos, domain::payments::VoucherData::Alfamart(_) => Self::Alfamart, domain::payments::VoucherData::Indomaret(_) => Self::Indomaret, domain::payments::VoucherData::Oxxo => Self::Oxxo, domain::payments::VoucherData::SevenEleven(_) => Self::SevenEleven, domain::payments::VoucherData::Lawson(_) => Self::Lawson, domain::payments::VoucherData::MiniStop(_) => Self::MiniStop, domain::payments::VoucherData::FamilyMart(_) => Self::FamilyMart, domain::payments::VoucherData::Seicomart(_) => Self::Seicomart, domain::payments::VoucherData::PayEasy(_) => Self::PayEasy, }, domain::PaymentMethodData::RealTimePayment(real_time_payment_data) => match *real_time_payment_data{ hyperswitch_domain_models::payment_method_data::RealTimePaymentData::DuitNow { } => Self::DuitNow, hyperswitch_domain_models::payment_method_data::RealTimePaymentData::Fps { } => Self::Fps, hyperswitch_domain_models::payment_method_data::RealTimePaymentData::PromptPay { } => Self::PromptPay, hyperswitch_domain_models::payment_method_data::RealTimePaymentData::VietQr { } => Self::VietQr, }, domain::payments::PaymentMethodData::GiftCard(gift_card_data) => { match *gift_card_data { domain::payments::GiftCardData::Givex(_) => Self::Givex, domain::payments::GiftCardData::BhnCardNetwork(_)=>Self::BhnCardNetwork, domain::payments::GiftCardData::PaySafeCard {} => Self::PaySafeCar, } } domain::payments::PaymentMethodData::CardToken(_) => Self::CardToken, domain::payments::PaymentMethodData::OpenBanking(data) => match data { hyperswitch_domain_models::payment_method_data::OpenBankingData::OpenBankingPIS { } => Self::OpenBanking }, domain::payments::PaymentMethodData::MobilePayment(mobile_payment_data) => match mobile_payment_data { hyperswitch_domain_models::payment_method_data::MobilePaymentData::DirectCarrierBilling { .. } => Self::DirectCarrierBilling, }, } } } pub fn convert_amount<T>( amount_convertor: &dyn AmountConvertor<Output = T>, amount: MinorUnit, currency: enums::Currency, ) -> Result<T, error_stack::Report<errors::ConnectorError>> { amount_convertor .convert(amount, currency) .change_context(errors::ConnectorError::AmountConversionFailed) } pub fn convert_back_amount_to_minor_units<T>( amount_convertor: &dyn AmountConvertor<Output = T>, amount: T, currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>> { amount_convertor .convert_back(amount, currency) .change_context(errors::ConnectorError::AmountConversionFailed) } pub trait NetworkTokenData { fn get_card_issuer(&self) -> Result<CardIssuer, Error>; fn get_expiry_year_4_digit(&self) -> Secret<String>; fn get_network_token(&self) -> NetworkTokenNumber; fn get_network_token_expiry_month(&self) -> Secret<String>; fn get_network_token_expiry_year(&self) -> Secret<String>; fn get_cryptogram(&self) -> Option<Secret<String>>; } impl NetworkTokenData for domain::NetworkTokenData { #[cfg(feature = "v1")] fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.token_number.peek()) } #[cfg(feature = "v2")] fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.network_token.peek()) } #[cfg(feature = "v1")] fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.token_exp_year.peek().clone(); if year.len() == 2 { year = format!("20{year}"); } Secret::new(year) } #[cfg(feature = "v2")] fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.network_token_exp_year.peek().clone(); if year.len() == 2 { year = format!("20{year}"); } Secret::new(year) } #[cfg(feature = "v1")] fn get_network_token(&self) -> NetworkTokenNumber { self.token_number.clone() } #[cfg(feature = "v2")] fn get_network_token(&self) -> NetworkTokenNumber { self.network_token.clone() } #[cfg(feature = "v1")] fn get_network_token_expiry_month(&self) -> Secret<String> { self.token_exp_month.clone() } #[cfg(feature = "v2")] fn get_network_token_expiry_month(&self) -> Secret<String> { self.network_token_exp_month.clone() } #[cfg(feature = "v1")] fn get_network_token_expiry_year(&self) -> Secret<String> { self.token_exp_year.clone() } #[cfg(feature = "v2")] fn get_network_token_expiry_year(&self) -> Secret<String> { self.network_token_exp_year.clone() } #[cfg(feature = "v1")] fn get_cryptogram(&self) -> Option<Secret<String>> { self.token_cryptogram.clone() } #[cfg(feature = "v2")] fn get_cryptogram(&self) -> Option<Secret<String>> { self.cryptogram.clone() } } pub fn convert_uppercase<'de, D, T>(v: D) -> Result<T, D::Error> where D: serde::Deserializer<'de>, T: FromStr, <T as FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error, { use serde::de::Error; let output = <&str>::deserialize(v)?; output.to_uppercase().parse::<T>().map_err(D::Error::custom) }
crates/router/src/connector/utils.rs
router::src::connector::utils
25,998
true
// File: crates/router/src/db/dynamic_routing_stats.rs // Module: router::src::db::dynamic_routing_stats use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::MockDb; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, db::kafka_store::KafkaStore, types::storage, }; #[async_trait::async_trait] pub trait DynamicRoutingStatsInterface { async fn insert_dynamic_routing_stat_entry( &self, dynamic_routing_stat_new: storage::DynamicRoutingStatsNew, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError>; async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError>; async fn update_dynamic_routing_stats( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, data: storage::DynamicRoutingStatsUpdate, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError>; } #[async_trait::async_trait] impl DynamicRoutingStatsInterface for Store { #[instrument(skip_all)] async fn insert_dynamic_routing_stat_entry( &self, dynamic_routing_stat: storage::DynamicRoutingStatsNew, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; dynamic_routing_stat .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::DynamicRoutingStats::find_optional_by_attempt_id_merchant_id( &conn, attempt_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn update_dynamic_routing_stats( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, data: storage::DynamicRoutingStatsUpdate, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::DynamicRoutingStats::update(&conn, attempt_id, merchant_id, data) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl DynamicRoutingStatsInterface for MockDb { #[instrument(skip_all)] async fn insert_dynamic_routing_stat_entry( &self, _dynamic_routing_stat: storage::DynamicRoutingStatsNew, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( &self, _attempt_id: String, _merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_dynamic_routing_stats( &self, _attempt_id: String, _merchant_id: &common_utils::id_type::MerchantId, _data: storage::DynamicRoutingStatsUpdate, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[async_trait::async_trait] impl DynamicRoutingStatsInterface for KafkaStore { #[instrument(skip_all)] async fn insert_dynamic_routing_stat_entry( &self, dynamic_routing_stat: storage::DynamicRoutingStatsNew, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { self.diesel_store .insert_dynamic_routing_stat_entry(dynamic_routing_stat) .await } async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> { self.diesel_store .find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(attempt_id, merchant_id) .await } async fn update_dynamic_routing_stats( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, data: storage::DynamicRoutingStatsUpdate, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { self.diesel_store .update_dynamic_routing_stats(attempt_id, merchant_id, data) .await } }
crates/router/src/db/dynamic_routing_stats.rs
router::src::db::dynamic_routing_stats
1,105
true
// File: crates/router/src/db/dispute.rs // Module: router::src::db::dispute use std::collections::HashMap; use error_stack::report; use hyperswitch_domain_models::disputes; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage::{self, DisputeDbExt}, }; #[async_trait::async_trait] pub trait DisputeInterface { async fn insert_dispute( &self, dispute: storage::DisputeNew, ) -> CustomResult<storage::Dispute, errors::StorageError>; async fn find_by_merchant_id_payment_id_connector_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> CustomResult<Option<storage::Dispute>, errors::StorageError>; async fn find_dispute_by_merchant_id_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_id: &str, ) -> CustomResult<storage::Dispute, errors::StorageError>; async fn find_disputes_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_constraints: &disputes::DisputeListConstraints, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError>; async fn find_disputes_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError>; async fn update_dispute( &self, this: storage::Dispute, dispute: storage::DisputeUpdate, ) -> CustomResult<storage::Dispute, errors::StorageError>; async fn get_dispute_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::StorageError>; } #[async_trait::async_trait] impl DisputeInterface for Store { #[instrument(skip_all)] async fn insert_dispute( &self, dispute: storage::DisputeNew, ) -> CustomResult<storage::Dispute, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; dispute .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_by_merchant_id_payment_id_connector_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> CustomResult<Option<storage::Dispute>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::find_by_merchant_id_payment_id_connector_dispute_id( &conn, merchant_id, payment_id, connector_dispute_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_dispute_by_merchant_id_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_id: &str, ) -> CustomResult<storage::Dispute, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::find_by_merchant_id_dispute_id(&conn, merchant_id, dispute_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_disputes_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_constraints: &disputes::DisputeListConstraints, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::filter_by_constraints(&conn, merchant_id, dispute_constraints) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_disputes_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_dispute( &self, this: storage::Dispute, dispute: storage::DisputeUpdate, ) -> CustomResult<storage::Dispute, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update(&conn, dispute) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn get_dispute_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::get_dispute_status_with_count( &conn, merchant_id, profile_id_list, time_range, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl DisputeInterface for MockDb { async fn insert_dispute( &self, dispute: storage::DisputeNew, ) -> CustomResult<storage::Dispute, errors::StorageError> { let evidence = dispute.evidence.ok_or(errors::StorageError::MockDbError)?; let mut locked_disputes = self.disputes.lock().await; if locked_disputes .iter() .any(|d| d.dispute_id == dispute.dispute_id) { Err(errors::StorageError::MockDbError)?; } let now = common_utils::date_time::now(); let new_dispute = storage::Dispute { dispute_id: dispute.dispute_id, amount: dispute.amount, currency: dispute.currency, dispute_stage: dispute.dispute_stage, dispute_status: dispute.dispute_status, payment_id: dispute.payment_id, attempt_id: dispute.attempt_id, merchant_id: dispute.merchant_id, connector_status: dispute.connector_status, connector_dispute_id: dispute.connector_dispute_id, connector_reason: dispute.connector_reason, connector_reason_code: dispute.connector_reason_code, challenge_required_by: dispute.challenge_required_by, connector_created_at: dispute.connector_created_at, connector_updated_at: dispute.connector_updated_at, created_at: now, modified_at: now, connector: dispute.connector, profile_id: dispute.profile_id, evidence, merchant_connector_id: dispute.merchant_connector_id, dispute_amount: dispute.dispute_amount, organization_id: dispute.organization_id, dispute_currency: dispute.dispute_currency, }; locked_disputes.push(new_dispute.clone()); Ok(new_dispute) } async fn find_by_merchant_id_payment_id_connector_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> CustomResult<Option<storage::Dispute>, errors::StorageError> { Ok(self .disputes .lock() .await .iter() .find(|d| { d.merchant_id == *merchant_id && d.payment_id == *payment_id && d.connector_dispute_id == connector_dispute_id }) .cloned()) } async fn find_dispute_by_merchant_id_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_id: &str, ) -> CustomResult<storage::Dispute, errors::StorageError> { let locked_disputes = self.disputes.lock().await; locked_disputes .iter() .find(|d| d.merchant_id == *merchant_id && d.dispute_id == dispute_id) .cloned() .ok_or(errors::StorageError::ValueNotFound(format!("No dispute available for merchant_id = {merchant_id:?} and dispute_id = {dispute_id}")) .into()) } async fn find_disputes_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_constraints: &disputes::DisputeListConstraints, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { let locked_disputes = self.disputes.lock().await; let limit_usize = dispute_constraints .limit .unwrap_or(u32::MAX) .try_into() .unwrap_or(usize::MAX); let offset_usize = dispute_constraints .offset .unwrap_or(0) .try_into() .unwrap_or(usize::MIN); let filtered_disputes: Vec<storage::Dispute> = locked_disputes .iter() .filter(|dispute| { dispute.merchant_id == *merchant_id && dispute_constraints .dispute_id .as_ref() .is_none_or(|id| &dispute.dispute_id == id) && dispute_constraints .payment_id .as_ref() .is_none_or(|id| &dispute.payment_id == id) && dispute_constraints .profile_id .as_ref() .is_none_or(|profile_ids| { dispute .profile_id .as_ref() .is_none_or(|id| profile_ids.contains(id)) }) && dispute_constraints .dispute_status .as_ref() .is_none_or(|statuses| statuses.contains(&dispute.dispute_status)) && dispute_constraints .dispute_stage .as_ref() .is_none_or(|stages| stages.contains(&dispute.dispute_stage)) && dispute_constraints.reason.as_ref().is_none_or(|reason| { dispute .connector_reason .as_ref() .is_none_or(|d_reason| d_reason == reason) }) && dispute_constraints .connector .as_ref() .is_none_or(|connectors| { connectors .iter() .any(|connector| dispute.connector.as_str() == *connector) }) && dispute_constraints .merchant_connector_id .as_ref() .is_none_or(|id| dispute.merchant_connector_id.as_ref() == Some(id)) && dispute_constraints .currency .as_ref() .is_none_or(|currencies| { currencies.iter().any(|currency| { dispute .dispute_currency .map(|dispute_currency| &dispute_currency == currency) .unwrap_or(dispute.currency.as_str() == currency.to_string()) }) }) && dispute_constraints.time_range.as_ref().is_none_or(|range| { let dispute_time = dispute.created_at; dispute_time >= range.start_time && range .end_time .is_none_or(|end_time| dispute_time <= end_time) }) }) .skip(offset_usize) .take(limit_usize) .cloned() .collect(); Ok(filtered_disputes) } async fn find_disputes_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { let locked_disputes = self.disputes.lock().await; Ok(locked_disputes .iter() .filter(|d| d.merchant_id == *merchant_id && d.payment_id == *payment_id) .cloned() .collect()) } async fn update_dispute( &self, this: storage::Dispute, dispute: storage::DisputeUpdate, ) -> CustomResult<storage::Dispute, errors::StorageError> { let mut locked_disputes = self.disputes.lock().await; let dispute_to_update = locked_disputes .iter_mut() .find(|d| d.dispute_id == this.dispute_id) .ok_or(errors::StorageError::MockDbError)?; let now = common_utils::date_time::now(); match dispute { storage::DisputeUpdate::Update { dispute_stage, dispute_status, connector_status, connector_reason, connector_reason_code, challenge_required_by, connector_updated_at, } => { if connector_reason.is_some() { dispute_to_update.connector_reason = connector_reason; } if connector_reason_code.is_some() { dispute_to_update.connector_reason_code = connector_reason_code; } if challenge_required_by.is_some() { dispute_to_update.challenge_required_by = challenge_required_by; } if connector_updated_at.is_some() { dispute_to_update.connector_updated_at = connector_updated_at; } dispute_to_update.dispute_stage = dispute_stage; dispute_to_update.dispute_status = dispute_status; dispute_to_update.connector_status = connector_status; } storage::DisputeUpdate::StatusUpdate { dispute_status, connector_status, } => { if let Some(status) = connector_status { dispute_to_update.connector_status = status; } dispute_to_update.dispute_status = dispute_status; } storage::DisputeUpdate::EvidenceUpdate { evidence } => { dispute_to_update.evidence = evidence; } } dispute_to_update.modified_at = now; Ok(dispute_to_update.clone()) } async fn get_dispute_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> { let locked_disputes = self.disputes.lock().await; let filtered_disputes_data = locked_disputes .iter() .filter(|d| { d.merchant_id == *merchant_id && d.created_at >= time_range.start_time && time_range .end_time .as_ref() .is_none_or(|received_end_time| received_end_time >= &d.created_at) && profile_id_list .as_ref() .zip(d.profile_id.as_ref()) .is_none_or(|(received_profile_list, received_profile_id)| { received_profile_list.contains(received_profile_id) }) }) .cloned() .collect::<Vec<storage::Dispute>>(); Ok(filtered_disputes_data .into_iter() .fold( HashMap::new(), |mut acc: HashMap<common_enums::DisputeStatus, i64>, value| { acc.entry(value.dispute_status) .and_modify(|value| *value += 1) .or_insert(1); acc }, ) .into_iter() .collect::<Vec<(common_enums::DisputeStatus, i64)>>()) } } #[cfg(test)] mod tests { #![allow(clippy::expect_used, clippy::unwrap_used)] mod mockdb_dispute_interface { use std::borrow::Cow; use common_enums::enums::Currency; use common_utils::types::{AmountConvertor, MinorUnit, StringMinorUnitForConnector}; use diesel_models::{ dispute::DisputeNew, enums::{DisputeStage, DisputeStatus}, }; use hyperswitch_domain_models::disputes::DisputeListConstraints; use masking::Secret; use redis_interface::RedisSettings; use serde_json::Value; use time::macros::datetime; use crate::db::{dispute::DisputeInterface, MockDb}; pub struct DisputeNewIds { dispute_id: String, payment_id: common_utils::id_type::PaymentId, attempt_id: String, merchant_id: common_utils::id_type::MerchantId, connector_dispute_id: String, } fn create_dispute_new(dispute_ids: DisputeNewIds) -> DisputeNew { DisputeNew { dispute_id: dispute_ids.dispute_id, amount: StringMinorUnitForConnector::convert( &StringMinorUnitForConnector, MinorUnit::new(0), Currency::USD, ) .expect("Amount Conversion Error"), currency: "currency".into(), dispute_stage: DisputeStage::Dispute, dispute_status: DisputeStatus::DisputeOpened, payment_id: dispute_ids.payment_id, attempt_id: dispute_ids.attempt_id, merchant_id: dispute_ids.merchant_id, connector_status: "connector_status".into(), connector_dispute_id: dispute_ids.connector_dispute_id, connector_reason: Some("connector_reason".into()), connector_reason_code: Some("connector_reason_code".into()), challenge_required_by: Some(datetime!(2019-01-01 0:00)), connector_created_at: Some(datetime!(2019-01-02 0:00)), connector_updated_at: Some(datetime!(2019-01-03 0:00)), connector: "connector".into(), evidence: Some(Secret::from(Value::String("evidence".into()))), profile_id: Some(common_utils::generate_profile_id_of_default_length()), merchant_connector_id: None, dispute_amount: MinorUnit::new(1040), organization_id: common_utils::id_type::OrganizationId::default(), dispute_currency: Some(Currency::default()), } } #[tokio::test] async fn test_insert_dispute() { let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create a mock DB"); let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed( "payment_1", )) .unwrap(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let found_dispute = mockdb .disputes .lock() .await .iter() .find(|d| d.dispute_id == created_dispute.dispute_id) .cloned(); assert!(found_dispute.is_some()); assert_eq!(created_dispute, found_dispute.unwrap()); } #[tokio::test] async fn test_find_by_merchant_id_payment_id_connector_dispute_id() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed( "payment_1", )) .unwrap(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let _ = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_2".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed( "payment_1", )) .unwrap(), connector_dispute_id: "connector_dispute_2".into(), })) .await .unwrap(); let found_dispute = mockdb .find_by_merchant_id_payment_id_connector_dispute_id( &merchant_id, &common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")) .unwrap(), "connector_dispute_1", ) .await .unwrap(); assert!(found_dispute.is_some()); assert_eq!(created_dispute, found_dispute.unwrap()); } #[tokio::test] async fn test_find_dispute_by_merchant_id_dispute_id() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let _ = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_2".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let found_dispute = mockdb .find_dispute_by_merchant_id_dispute_id(&merchant_id, "dispute_1") .await .unwrap(); assert_eq!(created_dispute, found_dispute); } #[tokio::test] async fn test_find_disputes_by_merchant_id() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_2")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let _ = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_2".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let found_disputes = mockdb .find_disputes_by_constraints( &merchant_id, &DisputeListConstraints { dispute_id: None, payment_id: None, profile_id: None, connector: None, merchant_connector_id: None, currency: None, limit: None, offset: None, dispute_status: None, dispute_stage: None, reason: None, time_range: None, }, ) .await .unwrap(); assert_eq!(1, found_disputes.len()); assert_eq!(created_dispute, found_disputes.first().unwrap().clone()); } #[tokio::test] async fn test_find_disputes_by_merchant_id_payment_id() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let _ = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_2".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let found_disputes = mockdb .find_disputes_by_merchant_id_payment_id(&merchant_id, &payment_id) .await .unwrap(); assert_eq!(1, found_disputes.len()); assert_eq!(created_dispute, found_disputes.first().unwrap().clone()); } mod update_dispute { use std::borrow::Cow; use diesel_models::{ dispute::DisputeUpdate, enums::{DisputeStage, DisputeStatus}, }; use masking::Secret; use serde_json::Value; use time::macros::datetime; use crate::db::{ dispute::{ tests::mockdb_dispute_interface::{create_dispute_new, DisputeNewIds}, DisputeInterface, }, MockDb, }; #[tokio::test] async fn test_update_dispute_update() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let updated_dispute = mockdb .update_dispute( created_dispute.clone(), DisputeUpdate::Update { dispute_stage: DisputeStage::PreDispute, dispute_status: DisputeStatus::DisputeAccepted, connector_status: "updated_connector_status".into(), connector_reason: Some("updated_connector_reason".into()), connector_reason_code: Some("updated_connector_reason_code".into()), challenge_required_by: Some(datetime!(2019-01-10 0:00)), connector_updated_at: Some(datetime!(2019-01-11 0:00)), }, ) .await .unwrap(); assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id); assert_eq!(created_dispute.amount, updated_dispute.amount); assert_eq!(created_dispute.currency, updated_dispute.currency); assert_ne!(created_dispute.dispute_stage, updated_dispute.dispute_stage); assert_ne!( created_dispute.dispute_status, updated_dispute.dispute_status ); assert_eq!(created_dispute.payment_id, updated_dispute.payment_id); assert_eq!(created_dispute.attempt_id, updated_dispute.attempt_id); assert_eq!(created_dispute.merchant_id, updated_dispute.merchant_id); assert_ne!( created_dispute.connector_status, updated_dispute.connector_status ); assert_eq!( created_dispute.connector_dispute_id, updated_dispute.connector_dispute_id ); assert_ne!( created_dispute.connector_reason, updated_dispute.connector_reason ); assert_ne!( created_dispute.connector_reason_code, updated_dispute.connector_reason_code ); assert_ne!( created_dispute.challenge_required_by, updated_dispute.challenge_required_by ); assert_eq!( created_dispute.connector_created_at, updated_dispute.connector_created_at ); assert_ne!( created_dispute.connector_updated_at, updated_dispute.connector_updated_at ); assert_eq!(created_dispute.created_at, updated_dispute.created_at); assert_ne!(created_dispute.modified_at, updated_dispute.modified_at); assert_eq!(created_dispute.connector, updated_dispute.connector); assert_eq!(created_dispute.evidence, updated_dispute.evidence); } #[tokio::test] async fn test_update_dispute_update_status() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let updated_dispute = mockdb .update_dispute( created_dispute.clone(), DisputeUpdate::StatusUpdate { dispute_status: DisputeStatus::DisputeExpired, connector_status: Some("updated_connector_status".into()), }, ) .await .unwrap(); assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id); assert_eq!(created_dispute.amount, updated_dispute.amount); assert_eq!(created_dispute.currency, updated_dispute.currency); assert_eq!(created_dispute.dispute_stage, updated_dispute.dispute_stage); assert_ne!( created_dispute.dispute_status, updated_dispute.dispute_status ); assert_eq!(created_dispute.payment_id, updated_dispute.payment_id); assert_eq!(created_dispute.attempt_id, updated_dispute.attempt_id); assert_eq!(created_dispute.merchant_id, updated_dispute.merchant_id); assert_ne!( created_dispute.connector_status, updated_dispute.connector_status ); assert_eq!( created_dispute.connector_dispute_id, updated_dispute.connector_dispute_id ); assert_eq!( created_dispute.connector_reason, updated_dispute.connector_reason ); assert_eq!( created_dispute.connector_reason_code, updated_dispute.connector_reason_code ); assert_eq!( created_dispute.challenge_required_by, updated_dispute.challenge_required_by ); assert_eq!( created_dispute.connector_created_at, updated_dispute.connector_created_at ); assert_eq!( created_dispute.connector_updated_at, updated_dispute.connector_updated_at ); assert_eq!(created_dispute.created_at, updated_dispute.created_at); assert_ne!(created_dispute.modified_at, updated_dispute.modified_at); assert_eq!(created_dispute.connector, updated_dispute.connector); assert_eq!(created_dispute.evidence, updated_dispute.evidence); } #[tokio::test] async fn test_update_dispute_update_evidence() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let updated_dispute = mockdb .update_dispute( created_dispute.clone(), DisputeUpdate::EvidenceUpdate { evidence: Secret::from(Value::String("updated_evidence".into())), }, ) .await .unwrap(); assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id); assert_eq!(created_dispute.amount, updated_dispute.amount); assert_eq!(created_dispute.currency, updated_dispute.currency); assert_eq!(created_dispute.dispute_stage, updated_dispute.dispute_stage); assert_eq!( created_dispute.dispute_status, updated_dispute.dispute_status ); assert_eq!(created_dispute.payment_id, updated_dispute.payment_id); assert_eq!(created_dispute.attempt_id, updated_dispute.attempt_id); assert_eq!(created_dispute.merchant_id, updated_dispute.merchant_id); assert_eq!( created_dispute.connector_status, updated_dispute.connector_status ); assert_eq!( created_dispute.connector_dispute_id, updated_dispute.connector_dispute_id ); assert_eq!( created_dispute.connector_reason, updated_dispute.connector_reason ); assert_eq!( created_dispute.connector_reason_code, updated_dispute.connector_reason_code ); assert_eq!( created_dispute.challenge_required_by, updated_dispute.challenge_required_by ); assert_eq!( created_dispute.connector_created_at, updated_dispute.connector_created_at ); assert_eq!( created_dispute.connector_updated_at, updated_dispute.connector_updated_at ); assert_eq!(created_dispute.created_at, updated_dispute.created_at); assert_ne!(created_dispute.modified_at, updated_dispute.modified_at); assert_eq!(created_dispute.connector, updated_dispute.connector); assert_ne!(created_dispute.evidence, updated_dispute.evidence); } } } }
crates/router/src/db/dispute.rs
router::src::db::dispute
7,976
true
// File: crates/router/src/db/callback_mapper.rs // Module: router::src::db::callback_mapper use error_stack::report; use hyperswitch_domain_models::callback_mapper as domain; use router_env::{instrument, tracing}; use storage_impl::{DataModelExt, MockDb}; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait CallbackMapperInterface { async fn insert_call_back_mapper( &self, call_back_mapper: domain::CallbackMapper, ) -> CustomResult<domain::CallbackMapper, errors::StorageError>; async fn find_call_back_mapper_by_id( &self, id: &str, ) -> CustomResult<domain::CallbackMapper, errors::StorageError>; } #[async_trait::async_trait] impl CallbackMapperInterface for Store { #[instrument(skip_all)] async fn insert_call_back_mapper( &self, call_back_mapper: domain::CallbackMapper, ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; call_back_mapper .to_storage_model() .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) .map(domain::CallbackMapper::from_storage_model) } #[instrument(skip_all)] async fn find_call_back_mapper_by_id( &self, id: &str, ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::CallbackMapper::find_by_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) .map(domain::CallbackMapper::from_storage_model) } } #[async_trait::async_trait] impl CallbackMapperInterface for MockDb { #[instrument(skip_all)] async fn insert_call_back_mapper( &self, _call_back_mapper: domain::CallbackMapper, ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { Err(errors::StorageError::MockDbError)? } #[instrument(skip_all)] async fn find_call_back_mapper_by_id( &self, _id: &str, ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { Err(errors::StorageError::MockDbError)? } }
crates/router/src/db/callback_mapper.rs
router::src::db::callback_mapper
536
true
// File: crates/router/src/db/role.rs // Module: router::src::db::role use common_utils::id_type; use diesel_models::{ enums::{EntityType, RoleScope}, role as storage, }; use error_stack::report; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait RoleInterface { async fn insert_role( &self, role: storage::RoleNew, ) -> CustomResult<storage::Role, errors::StorageError>; async fn find_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError>; async fn find_role_by_role_id_in_lineage( &self, role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, profile_id: &id_type::ProfileId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError>; async fn find_by_role_id_org_id_tenant_id( &self, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError>; async fn update_role_by_role_id( &self, role_id: &str, role_update: storage::RoleUpdate, ) -> CustomResult<storage::Role, errors::StorageError>; async fn delete_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError>; //TODO: Remove once generic_list_roles_by_entity_type is stable async fn list_roles_for_org_by_parameters( &self, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, entity_type: Option<EntityType>, limit: Option<u32>, ) -> CustomResult<Vec<storage::Role>, errors::StorageError>; async fn generic_list_roles_by_entity_type( &self, payload: storage::ListRolesByEntityPayload, is_lineage_data_required: bool, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, ) -> CustomResult<Vec<storage::Role>, errors::StorageError>; } #[async_trait::async_trait] impl RoleInterface for Store { #[instrument(skip_all)] async fn insert_role( &self, role: storage::RoleNew, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; role.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Role::find_by_role_id(&conn, role_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_role_by_role_id_in_lineage( &self, role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, profile_id: &id_type::ProfileId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Role::find_by_role_id_in_lineage( &conn, role_id, merchant_id, org_id, profile_id, tenant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_by_role_id_org_id_tenant_id( &self, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Role::find_by_role_id_org_id_tenant_id(&conn, role_id, org_id, tenant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_role_by_role_id( &self, role_id: &str, role_update: storage::RoleUpdate, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Role::update_by_role_id(&conn, role_id, role_update) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Role::delete_by_role_id(&conn, role_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } //TODO: Remove once generic_list_roles_by_entity_type is stable #[instrument(skip_all)] async fn list_roles_for_org_by_parameters( &self, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, entity_type: Option<EntityType>, limit: Option<u32>, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Role::generic_roles_list_for_org( &conn, tenant_id.to_owned(), org_id.to_owned(), merchant_id.cloned(), entity_type, limit, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn generic_list_roles_by_entity_type( &self, payload: storage::ListRolesByEntityPayload, is_lineage_data_required: bool, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Role::generic_list_roles_by_entity_type( &conn, payload, is_lineage_data_required, tenant_id, org_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl RoleInterface for MockDb { async fn insert_role( &self, role: storage::RoleNew, ) -> CustomResult<storage::Role, errors::StorageError> { let mut roles = self.roles.lock().await; if roles .iter() .any(|role_inner| role_inner.role_id == role.role_id) { Err(errors::StorageError::DuplicateValue { entity: "role_id", key: None, })? } let role = storage::Role { role_name: role.role_name, role_id: role.role_id, merchant_id: role.merchant_id, org_id: role.org_id, groups: role.groups, scope: role.scope, entity_type: role.entity_type, created_by: role.created_by, created_at: role.created_at, last_modified_at: role.last_modified_at, last_modified_by: role.last_modified_by, profile_id: role.profile_id, tenant_id: role.tenant_id, }; roles.push(role.clone()); Ok(role) } async fn find_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { let roles = self.roles.lock().await; roles .iter() .find(|role| role.role_id == role_id) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No role available role_id = {role_id}" )) .into(), ) } async fn find_role_by_role_id_in_lineage( &self, role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, profile_id: &id_type::ProfileId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { let roles = self.roles.lock().await; roles .iter() .find(|role| { role.role_id == role_id && (role.tenant_id == *tenant_id) && role.org_id == *org_id && ((role.scope == RoleScope::Organization) || (role .merchant_id .as_ref() .is_some_and(|merchant_id_from_role| { merchant_id_from_role == merchant_id && role.scope == RoleScope::Merchant })) || (role .profile_id .as_ref() .is_some_and(|profile_id_from_role| { profile_id_from_role == profile_id && role.scope == RoleScope::Profile }))) }) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No role available in merchant scope for role_id = {role_id}, \ merchant_id = {merchant_id:?} and org_id = {org_id:?}" )) .into(), ) } async fn find_by_role_id_org_id_tenant_id( &self, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { let roles = self.roles.lock().await; roles .iter() .find(|role| { role.role_id == role_id && role.org_id == *org_id && role.tenant_id == *tenant_id }) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No role available in org scope for role_id = {role_id} and org_id = {org_id:?}" )) .into(), ) } async fn update_role_by_role_id( &self, role_id: &str, role_update: storage::RoleUpdate, ) -> CustomResult<storage::Role, errors::StorageError> { let mut roles = self.roles.lock().await; roles .iter_mut() .find(|role| role.role_id == role_id) .map(|role| { *role = match role_update { storage::RoleUpdate::UpdateDetails { groups, role_name, last_modified_at, last_modified_by, } => storage::Role { groups: groups.unwrap_or(role.groups.to_owned()), role_name: role_name.unwrap_or(role.role_name.to_owned()), last_modified_by, last_modified_at, ..role.to_owned() }, }; role.to_owned() }) .ok_or( errors::StorageError::ValueNotFound(format!( "No role available for role_id = {role_id}" )) .into(), ) } async fn delete_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { let mut roles = self.roles.lock().await; let role_index = roles .iter() .position(|role| role.role_id == role_id) .ok_or(errors::StorageError::ValueNotFound(format!( "No role available for role_id = {role_id}" )))?; Ok(roles.remove(role_index)) } //TODO: Remove once generic_list_roles_by_entity_type is stable #[instrument(skip_all)] async fn list_roles_for_org_by_parameters( &self, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, entity_type: Option<EntityType>, limit: Option<u32>, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { let roles = self.roles.lock().await; let limit_usize = limit.unwrap_or(u32::MAX).try_into().unwrap_or(usize::MAX); let roles_list: Vec<_> = roles .iter() .filter(|role| { let matches_merchant = merchant_id .zip(role.merchant_id.as_ref()) .map(|(merchant_id, role_merchant_id)| merchant_id == role_merchant_id) .unwrap_or(true); matches_merchant && role.org_id == *org_id && role.tenant_id == *tenant_id && Some(role.entity_type) == entity_type }) .take(limit_usize) .cloned() .collect(); Ok(roles_list) } #[instrument(skip_all)] async fn generic_list_roles_by_entity_type( &self, payload: storage::ListRolesByEntityPayload, is_lineage_data_required: bool, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { let roles = self.roles.lock().await; let roles_list: Vec<_> = roles .iter() .filter(|role| match &payload { storage::ListRolesByEntityPayload::Organization => { let entity_in_vec = if is_lineage_data_required { vec![ EntityType::Organization, EntityType::Merchant, EntityType::Profile, ] } else { vec![EntityType::Organization] }; role.tenant_id == tenant_id && role.org_id == org_id && entity_in_vec.contains(&role.entity_type) } storage::ListRolesByEntityPayload::Merchant(merchant_id) => { let entity_in_vec = if is_lineage_data_required { vec![EntityType::Merchant, EntityType::Profile] } else { vec![EntityType::Merchant] }; let matches_merchant = role .merchant_id .as_ref() .is_some_and(|merchant_id_from_role| merchant_id_from_role == merchant_id); role.tenant_id == tenant_id && role.org_id == org_id && (role.scope == RoleScope::Organization || matches_merchant) && entity_in_vec.contains(&role.entity_type) } storage::ListRolesByEntityPayload::Profile(merchant_id, profile_id) => { let entity_in_vec = [EntityType::Profile]; let matches_merchant = role.merchant_id .as_ref() .is_some_and(|merchant_id_from_role| { merchant_id_from_role == merchant_id && role.scope == RoleScope::Merchant }); let matches_profile = role.profile_id .as_ref() .is_some_and(|profile_id_from_role| { profile_id_from_role == profile_id && role.scope == RoleScope::Profile }); role.tenant_id == tenant_id && role.org_id == org_id && (role.scope == RoleScope::Organization || matches_merchant || matches_profile) && entity_in_vec.contains(&role.entity_type) } }) .cloned() .collect(); Ok(roles_list) } }
crates/router/src/db/role.rs
router::src::db::role
3,527
true
// File: crates/router/src/db/events.rs // Module: router::src::db::events use std::collections::HashSet; use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage, }, }; #[async_trait::async_trait] pub trait EventInterface where domain::Event: Conversion<DstType = storage::events::Event, NewDstType = storage::events::EventNew>, { async fn insert_event( &self, state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError>; async fn find_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError>; async fn find_event_by_merchant_id_idempotent_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, idempotent_event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError>; async fn list_initial_events_by_merchant_id_primary_object_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; #[allow(clippy::too_many_arguments)] async fn list_initial_events_by_merchant_id_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; async fn list_events_by_merchant_id_initial_attempt_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; async fn list_initial_events_by_profile_id_primary_object_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; #[allow(clippy::too_many_arguments)] async fn list_initial_events_by_profile_id_constraints( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; async fn update_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, event: domain::EventUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError>; async fn count_initial_events_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, ) -> CustomResult<i64, errors::StorageError>; } #[async_trait::async_trait] impl EventInterface for Store { #[instrument(skip_all)] async fn insert_event( &self, state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; event .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::find_by_merchant_id_event_id(&conn, merchant_id, event_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_event_by_merchant_id_idempotent_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, idempotent_event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::find_by_merchant_id_idempotent_event_id( &conn, merchant_id, idempotent_event_id, ) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn list_initial_events_by_merchant_id_primary_object_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_initial_attempts_by_merchant_id_primary_object_id( &conn, merchant_id, primary_object_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn list_initial_events_by_merchant_id_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_initial_attempts_by_merchant_id_constraints( &conn, merchant_id, created_after, created_before, limit, offset, event_types, is_delivered, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn list_events_by_merchant_id_initial_attempt_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_by_merchant_id_initial_attempt_id( &conn, merchant_id, initial_attempt_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn list_initial_events_by_profile_id_primary_object_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_initial_attempts_by_profile_id_primary_object_id( &conn, profile_id, primary_object_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn list_initial_events_by_profile_id_constraints( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_initial_attempts_by_profile_id_constraints( &conn, profile_id, created_after, created_before, limit, offset, event_types, is_delivered, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( merchant_key_store.merchant_id.clone(), ), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn update_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, event: domain::EventUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Event::update_by_merchant_id_event_id(&conn, merchant_id, event_id, event.into()) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn count_initial_events_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, ) -> CustomResult<i64, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::count_initial_attempts_by_constraints( &conn, merchant_id, profile_id, created_after, created_before, event_types, is_delivered, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl EventInterface for MockDb { async fn insert_event( &self, state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let mut locked_events = self.events.lock().await; let stored_event = Conversion::convert(event) .await .change_context(errors::StorageError::EncryptionError)?; locked_events.push(stored_event.clone()); stored_event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let locked_events = self.events.lock().await; locked_events .iter() .find(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.event_id == event_id }) .cloned() .async_map(|event| async { event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()? .ok_or( errors::StorageError::ValueNotFound(format!( "No event available with merchant_id = {merchant_id:?} and event_id = {event_id}" )) .into(), ) } async fn find_event_by_merchant_id_idempotent_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, idempotent_event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let locked_events = self.events.lock().await; locked_events .iter() .find(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.idempotent_event_id == Some(idempotent_event_id.to_string()) }) .cloned() .async_map(|event| async { event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()? .ok_or( errors::StorageError::ValueNotFound(format!( "No event available with merchant_id = {merchant_id:?} and idempotent_event_id = {idempotent_event_id}" )) .into(), ) } async fn list_initial_events_by_merchant_id_primary_object_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events = locked_events .iter() .filter(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.initial_attempt_id.as_ref() == Some(&event.event_id) && event.primary_object_id == primary_object_id }) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn list_initial_events_by_merchant_id_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events_iter = locked_events.iter().filter(|event| { let check = event.merchant_id == Some(merchant_id.to_owned()) && event.initial_attempt_id.as_ref() == Some(&event.event_id) && (event.created_at >= created_after) && (event.created_at <= created_before) && (event_types.is_empty() || event_types.contains(&event.event_type)) && (event.is_overall_delivery_successful == is_delivered); check }); let offset: usize = if let Some(offset) = offset { if offset < 0 { Err(errors::StorageError::MockDbError)?; } offset .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { 0 }; let limit: usize = if let Some(limit) = limit { if limit < 0 { Err(errors::StorageError::MockDbError)?; } limit .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { usize::MAX }; let events = events_iter .skip(offset) .take(limit) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn list_events_by_merchant_id_initial_attempt_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events = locked_events .iter() .filter(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.initial_attempt_id == Some(initial_attempt_id.to_owned()) }) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn list_initial_events_by_profile_id_primary_object_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events = locked_events .iter() .filter(|event| { event.business_profile_id == Some(profile_id.to_owned()) && event.initial_attempt_id.as_ref() == Some(&event.event_id) && event.primary_object_id == primary_object_id }) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn list_initial_events_by_profile_id_constraints( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events_iter = locked_events.iter().filter(|event| { let check = event.business_profile_id == Some(profile_id.to_owned()) && event.initial_attempt_id.as_ref() == Some(&event.event_id) && (event.created_at >= created_after) && (event.created_at <= created_before) && (event_types.is_empty() || event_types.contains(&event.event_type)) && (event.is_overall_delivery_successful == is_delivered); check }); let offset: usize = if let Some(offset) = offset { if offset < 0 { Err(errors::StorageError::MockDbError)?; } offset .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { 0 }; let limit: usize = if let Some(limit) = limit { if limit < 0 { Err(errors::StorageError::MockDbError)?; } limit .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { usize::MAX }; let events = events_iter .skip(offset) .take(limit) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn update_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, event: domain::EventUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let mut locked_events = self.events.lock().await; let event_to_update = locked_events .iter_mut() .find(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.event_id == event_id }) .ok_or(errors::StorageError::MockDbError)?; match event { domain::EventUpdate::UpdateResponse { is_webhook_notified, response, } => { event_to_update.is_webhook_notified = is_webhook_notified; event_to_update.response = response.map(Into::into); } domain::EventUpdate::OverallDeliveryStatusUpdate { is_overall_delivery_successful, } => { event_to_update.is_overall_delivery_successful = Some(is_overall_delivery_successful) } } event_to_update .clone() .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn count_initial_events_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, ) -> CustomResult<i64, errors::StorageError> { let locked_events = self.events.lock().await; let iter_events = locked_events.iter().filter(|event| { let check = event.initial_attempt_id.as_ref() == Some(&event.event_id) && (event.merchant_id == Some(merchant_id.to_owned())) && (event.business_profile_id == profile_id) && (event.created_at >= created_after) && (event.created_at <= created_before) && (event_types.is_empty() || event_types.contains(&event.event_type)) && (event.is_overall_delivery_successful == is_delivered); check }); let events = iter_events.cloned().collect::<Vec<_>>(); i64::try_from(events.len()) .change_context(errors::StorageError::MockDbError) .attach_printable("Failed to convert usize to i64") } } #[cfg(test)] mod tests { use std::sync::Arc; use api_models::webhooks as api_webhooks; use common_enums::IntentStatus; use common_utils::{ generate_organization_id_of_default_length, type_name, types::{keymanager::Identifier, MinorUnit}, }; use diesel_models::{ business_profile::WebhookDetails, enums::{self}, events::EventMetadata, }; use futures::future::join_all; use hyperswitch_domain_models::{ master_key::MasterKeyInterface, merchant_account::MerchantAccountSetter, }; use time::macros::datetime; use tokio::time::{timeout, Duration}; use crate::{ core::webhooks as webhooks_core, db::{events::EventInterface, merchant_key_store::MerchantKeyStoreInterface, MockDb}, routes::{ self, app::{settings::Settings, StorageImpl}, }, services, types::{ api, domain::{self, MerchantAccount}, }, }; #[allow(clippy::unwrap_used)] #[tokio::test] #[cfg(feature = "v1")] async fn test_mockdb_event_interface() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let event_id = "test_event_id"; let (tx, _) = tokio::sync::oneshot::channel(); let app_state = Box::pin(routes::AppState::with_storage( Settings::default(), StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = &Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant_1")) .unwrap(); let business_profile_id = common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("profile1")).unwrap(); let payment_id = "test_payment_id"; let key_manager_state = &state.into(); let master_key = mockdb.get_master_key(); mockdb .insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain::types::CryptoOperation::Encrypt( services::generate_aes256_key().unwrap().to_vec().into(), ), Identifier::Merchant(merchant_id.to_owned()), master_key, ) .await .and_then(|val| val.try_into_operation()) .unwrap(), created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await .unwrap(); let merchant_key_store = mockdb .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &master_key.to_vec().into(), ) .await .unwrap(); let event1 = mockdb .insert_event( key_manager_state, domain::Event { event_id: event_id.into(), event_type: enums::EventType::PaymentSucceeded, event_class: enums::EventClass::Payments, is_webhook_notified: false, primary_object_id: payment_id.into(), primary_object_type: enums::EventObjectType::PaymentDetails, created_at: common_utils::date_time::now(), merchant_id: Some(merchant_id.to_owned()), business_profile_id: Some(business_profile_id.to_owned()), primary_object_created_at: Some(common_utils::date_time::now()), idempotent_event_id: Some(event_id.into()), initial_attempt_id: Some(event_id.into()), request: None, response: None, delivery_attempt: Some(enums::WebhookDeliveryAttempt::InitialAttempt), metadata: Some(EventMetadata::Payment { payment_id: common_utils::id_type::PaymentId::try_from( std::borrow::Cow::Borrowed(payment_id), ) .unwrap(), }), is_overall_delivery_successful: Some(false), }, &merchant_key_store, ) .await .unwrap(); assert_eq!(event1.event_id, event_id); let updated_event = mockdb .update_event_by_merchant_id_event_id( key_manager_state, &merchant_id, event_id, domain::EventUpdate::UpdateResponse { is_webhook_notified: true, response: None, }, &merchant_key_store, ) .await .unwrap(); assert!(updated_event.is_webhook_notified); assert_eq!(updated_event.primary_object_id, payment_id); assert_eq!(updated_event.event_id, event_id); } #[allow(clippy::unwrap_used)] #[tokio::test] #[cfg(feature = "v2")] async fn test_mockdb_event_interface() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let event_id = "test_event_id"; let (tx, _) = tokio::sync::oneshot::channel(); let app_state = Box::pin(routes::AppState::with_storage( Settings::default(), StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = &Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant_1")) .unwrap(); let business_profile_id = common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("profile1")).unwrap(); let payment_id = "test_payment_id"; let key_manager_state = &state.into(); let master_key = mockdb.get_master_key(); mockdb .insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain::types::CryptoOperation::Encrypt( services::generate_aes256_key().unwrap().to_vec().into(), ), Identifier::Merchant(merchant_id.to_owned()), master_key, ) .await .and_then(|val| val.try_into_operation()) .unwrap(), created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await .unwrap(); let merchant_key_store = mockdb .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &master_key.to_vec().into(), ) .await .unwrap(); let event1 = mockdb .insert_event( key_manager_state, domain::Event { event_id: event_id.into(), event_type: enums::EventType::PaymentSucceeded, event_class: enums::EventClass::Payments, is_webhook_notified: false, primary_object_id: payment_id.into(), primary_object_type: enums::EventObjectType::PaymentDetails, created_at: common_utils::date_time::now(), merchant_id: Some(merchant_id.to_owned()), business_profile_id: Some(business_profile_id.to_owned()), primary_object_created_at: Some(common_utils::date_time::now()), idempotent_event_id: Some(event_id.into()), initial_attempt_id: Some(event_id.into()), request: None, response: None, delivery_attempt: Some(enums::WebhookDeliveryAttempt::InitialAttempt), metadata: Some(EventMetadata::Payment { payment_id: common_utils::id_type::GlobalPaymentId::try_from( std::borrow::Cow::Borrowed(payment_id), ) .unwrap(), }), is_overall_delivery_successful: Some(false), }, &merchant_key_store, ) .await .unwrap(); assert_eq!(event1.event_id, event_id); let updated_event = mockdb .update_event_by_merchant_id_event_id( key_manager_state, &merchant_id, event_id, domain::EventUpdate::UpdateResponse { is_webhook_notified: true, response: None, }, &merchant_key_store, ) .await .unwrap(); assert!(updated_event.is_webhook_notified); assert_eq!(updated_event.primary_object_id, payment_id); assert_eq!(updated_event.event_id, event_id); } #[cfg(feature = "v1")] #[allow(clippy::panic_in_result_fn)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn test_concurrent_webhook_insertion_with_redis_lock( ) -> Result<(), Box<dyn std::error::Error>> { // Test concurrent webhook insertion with a Redis lock to prevent race conditions let conf = Settings::new()?; let tx: tokio::sync::oneshot::Sender<()> = tokio::sync::oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let tenant_id = common_utils::id_type::TenantId::try_from_string("public".to_string())?; let state = Arc::new(app_state) .get_session_state(&tenant_id, None, || {}) .map_err(|_| "failed to get session state")?; let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("juspay_merchant"))?; let business_profile_id = common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("profile1"))?; let key_manager_state = &(&state).into(); let master_key = state.store.get_master_key(); let aes_key = services::generate_aes256_key()?; let merchant_key_store = state .store .insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain::types::CryptoOperation::Encrypt(aes_key.to_vec().into()), Identifier::Merchant(merchant_id.to_owned()), master_key, ) .await? .try_into_operation()?, created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await?; let merchant_account_to_insert = MerchantAccount::from(MerchantAccountSetter { merchant_id: merchant_id.clone(), merchant_name: None, merchant_details: None, return_url: None, webhook_details: Some(WebhookDetails { webhook_version: None, webhook_username: None, webhook_password: None, webhook_url: Some(masking::Secret::new( "https://example.com/webhooks".to_string(), )), payment_created_enabled: None, payment_succeeded_enabled: Some(true), payment_failed_enabled: None, payment_statuses_enabled: None, refund_statuses_enabled: None, payout_statuses_enabled: None, multiple_webhooks_list: None, }), sub_merchants_enabled: None, parent_merchant_id: None, enable_payment_response_hash: true, payment_response_hash_key: None, redirect_to_merchant_with_http_post: false, publishable_key: "pk_test_11DviC2G2fb3lAJoes1q3A2222233327".to_string(), locker_id: None, storage_scheme: enums::MerchantStorageScheme::PostgresOnly, metadata: None, routing_algorithm: None, primary_business_details: serde_json::json!({ "country": "US", "business": "default" }), intent_fulfillment_time: Some(1), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), frm_routing_algorithm: None, payout_routing_algorithm: None, organization_id: generate_organization_id_of_default_length(), is_recon_enabled: true, default_profile: None, recon_status: enums::ReconStatus::NotRequested, payment_link_config: None, pm_collect_link_config: None, is_platform_account: false, merchant_account_type: common_enums::MerchantAccountType::Standard, product_type: None, version: common_enums::ApiVersion::V1, }); let merchant_account = state .store .insert_merchant( key_manager_state, merchant_account_to_insert, &merchant_key_store, ) .await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account, merchant_key_store.clone(), ))); let merchant_id = merchant_id.clone(); // Clone merchant_id to avoid move let business_profile_to_insert = domain::Profile::from(domain::ProfileSetter { merchant_country_code: None, profile_id: business_profile_id.clone(), merchant_id: merchant_id.clone(), profile_name: "test_concurrent_profile".to_string(), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), return_url: None, enable_payment_response_hash: true, payment_response_hash_key: None, redirect_to_merchant_with_http_post: false, webhook_details: Some(WebhookDetails { webhook_version: None, webhook_username: None, webhook_password: None, webhook_url: Some(masking::Secret::new( "https://example.com/webhooks".to_string(), )), payment_created_enabled: None, payment_succeeded_enabled: Some(true), payment_failed_enabled: None, payment_statuses_enabled: None, refund_statuses_enabled: None, payout_statuses_enabled: None, multiple_webhooks_list: None, }), metadata: None, routing_algorithm: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, is_recon_enabled: false, applepay_verified_domains: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: None, extended_card_info_config: None, is_connector_agnostic_mit_enabled: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, tax_connector_id: None, is_tax_connector_enabled: false, dynamic_routing_algorithm: None, is_network_tokenization_enabled: false, is_auto_retries_enabled: false, max_auto_retries_enabled: None, always_request_extended_authorization: None, is_click_to_pay_enabled: false, authentication_product_ids: None, card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: false, force_3ds_challenge: false, is_debit_routing_enabled: false, merchant_business_country: None, is_iframe_redirection_enabled: None, is_pre_network_tokenization_enabled: false, merchant_category_code: None, dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, external_vault_details: domain::ExternalVaultDetails::Skip, billing_processor_id: None, is_l2_l3_enabled: false, }); let business_profile = state .store .insert_business_profile( key_manager_state, &merchant_key_store.clone(), business_profile_to_insert, ) .await?; // Same inputs for all threads let event_type = enums::EventType::PaymentSucceeded; let event_class = enums::EventClass::Payments; let primary_object_id = Arc::new("concurrent_payment_id".to_string()); let primary_object_type = enums::EventObjectType::PaymentDetails; let payment_id = common_utils::id_type::PaymentId::try_from(std::borrow::Cow::Borrowed( "pay_mbabizu24mvu3mela5njyhpit10", ))?; let primary_object_created_at = Some(common_utils::date_time::now()); let expected_response = api::PaymentsResponse { payment_id, status: IntentStatus::Succeeded, amount: MinorUnit::new(6540), amount_capturable: MinorUnit::new(0), amount_received: None, client_secret: None, created: None, currency: "USD".to_string(), customer_id: None, description: Some("Its my first payment request".to_string()), refunds: None, mandate_id: None, merchant_id, net_amount: MinorUnit::new(6540), connector: None, customer: None, disputes: None, attempts: None, captures: None, mandate_data: None, setup_future_usage: None, off_session: None, capture_on: None, capture_method: None, payment_method: None, payment_method_data: None, payment_token: None, shipping: None, billing: None, order_details: None, email: None, name: None, phone: None, return_url: None, authentication_type: None, statement_descriptor_name: None, statement_descriptor_suffix: None, next_action: None, cancellation_reason: None, error_code: None, error_message: None, unified_code: None, unified_message: None, payment_experience: None, payment_method_type: None, connector_label: None, business_country: None, business_label: None, business_sub_label: None, allowed_payment_method_types: None, ephemeral_key: None, manual_retry_allowed: None, connector_transaction_id: None, frm_message: None, metadata: None, connector_metadata: None, feature_metadata: None, reference_id: None, payment_link: None, profile_id: None, surcharge_details: None, attempt_count: 1, merchant_decision: None, merchant_connector_id: None, incremental_authorization_allowed: None, authorization_count: None, incremental_authorizations: None, external_authentication_details: None, external_3ds_authentication_attempted: None, expires_on: None, fingerprint: None, browser_info: None, payment_method_id: None, payment_method_status: None, updated: None, split_payments: None, frm_metadata: None, merchant_order_reference_id: None, capture_before: None, extended_authorization_applied: None, order_tax_amount: None, connector_mandate_id: None, shipping_cost: None, card_discovery: None, mit_category: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, issuer_error_code: None, issuer_error_message: None, is_iframe_redirection_enabled: None, whole_connector_response: None, payment_channel: None, network_transaction_id: None, enable_partial_authorization: None, is_overcapture_enabled: None, enable_overcapture: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, }; let content = api_webhooks::OutgoingWebhookContent::PaymentDetails(Box::new(expected_response)); // Run 10 concurrent webhook creations let mut handles = vec![]; for _ in 0..10 { let state_clone = state.clone(); let merchant_context_clone = merchant_context.clone(); let business_profile_clone = business_profile.clone(); let content_clone = content.clone(); let primary_object_id_clone = primary_object_id.clone(); let handle = tokio::spawn(async move { webhooks_core::create_event_and_trigger_outgoing_webhook( state_clone, merchant_context_clone, business_profile_clone, event_type, event_class, (*primary_object_id_clone).to_string(), primary_object_type, content_clone, primary_object_created_at, ) .await .map_err(|e| format!("create_event_and_trigger_outgoing_webhook failed: {e}")) }); handles.push(handle); } // Await all tasks // We give the whole batch 20 s; if they don't finish something is wrong. let results = timeout(Duration::from_secs(20), join_all(handles)) .await .map_err(|_| "tasks hung for >20 s – possible dead-lock / endless retry")?; for res in results { // Any task that panicked or returned Err will make the test fail here. let _ = res.map_err(|e| format!("task panicked: {e}"))?; } // Collect all initial-attempt events for this payment let events = state .store .list_initial_events_by_merchant_id_primary_object_id( key_manager_state, &business_profile.merchant_id, &primary_object_id.clone(), merchant_context.get_merchant_key_store(), ) .await?; assert_eq!( events.len(), 1, "Expected exactly 1 row in events table, found {}", events.len() ); Ok(()) } }
crates/router/src/db/events.rs
router::src::db::events
11,157
true
// File: crates/router/src/db/organization.rs // Module: router::src::db::organization use common_utils::{errors::CustomResult, id_type}; use diesel_models::{organization as storage, organization::OrganizationBridge}; use error_stack::report; use router_env::{instrument, tracing}; use crate::{connection, core::errors, services::Store}; #[async_trait::async_trait] pub trait OrganizationInterface { async fn insert_organization( &self, organization: storage::OrganizationNew, ) -> CustomResult<storage::Organization, errors::StorageError>; async fn find_organization_by_org_id( &self, org_id: &id_type::OrganizationId, ) -> CustomResult<storage::Organization, errors::StorageError>; async fn update_organization_by_org_id( &self, org_id: &id_type::OrganizationId, update: storage::OrganizationUpdate, ) -> CustomResult<storage::Organization, errors::StorageError>; } #[async_trait::async_trait] impl OrganizationInterface for Store { #[instrument(skip_all)] async fn insert_organization( &self, organization: storage::OrganizationNew, ) -> CustomResult<storage::Organization, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; organization .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_organization_by_org_id( &self, org_id: &id_type::OrganizationId, ) -> CustomResult<storage::Organization, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; storage::Organization::find_by_org_id(&conn, org_id.to_owned()) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_organization_by_org_id( &self, org_id: &id_type::OrganizationId, update: storage::OrganizationUpdate, ) -> CustomResult<storage::Organization, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; storage::Organization::update_by_org_id(&conn, org_id.to_owned(), update) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl OrganizationInterface for super::MockDb { async fn insert_organization( &self, organization: storage::OrganizationNew, ) -> CustomResult<storage::Organization, errors::StorageError> { let mut organizations = self.organizations.lock().await; if organizations .iter() .any(|org| org.get_organization_id() == organization.get_organization_id()) { Err(errors::StorageError::DuplicateValue { entity: "org_id", key: None, })? } let org = storage::Organization::new(organization); organizations.push(org.clone()); Ok(org) } async fn find_organization_by_org_id( &self, org_id: &id_type::OrganizationId, ) -> CustomResult<storage::Organization, errors::StorageError> { let organizations = self.organizations.lock().await; organizations .iter() .find(|org| org.get_organization_id() == *org_id) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No organization available for org_id = {org_id:?}", )) .into(), ) } async fn update_organization_by_org_id( &self, org_id: &id_type::OrganizationId, update: storage::OrganizationUpdate, ) -> CustomResult<storage::Organization, errors::StorageError> { let mut organizations = self.organizations.lock().await; organizations .iter_mut() .find(|org| org.get_organization_id() == *org_id) .map(|org| match &update { storage::OrganizationUpdate::Update { organization_name, organization_details, metadata, platform_merchant_id, } => { organization_name .as_ref() .map(|org_name| org.set_organization_name(org_name.to_owned())); organization_details.clone_into(&mut org.organization_details); metadata.clone_into(&mut org.metadata); platform_merchant_id.clone_into(&mut org.platform_merchant_id); org } }) .ok_or( errors::StorageError::ValueNotFound(format!( "No organization available for org_id = {org_id:?}", )) .into(), ) .cloned() } }
crates/router/src/db/organization.rs
router::src::db::organization
1,009
true
// File: crates/router/src/db/merchant_account.rs // Module: router::src::db::merchant_account pub use hyperswitch_domain_models::merchant_account::{self, MerchantAccountInterface};
crates/router/src/db/merchant_account.rs
router::src::db::merchant_account
40
true
// File: crates/router/src/db/fraud_check.rs // Module: router::src::db::fraud_check use diesel_models::fraud_check::{self as storage, FraudCheck, FraudCheckUpdate}; use error_stack::report; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait FraudCheckInterface { async fn insert_fraud_check_response( &self, new: storage::FraudCheckNew, ) -> CustomResult<FraudCheck, errors::StorageError>; async fn update_fraud_check_response_with_attempt_id( &self, this: FraudCheck, fraud_check: FraudCheckUpdate, ) -> CustomResult<FraudCheck, errors::StorageError>; async fn find_fraud_check_by_payment_id( &self, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<FraudCheck, errors::StorageError>; async fn find_fraud_check_by_payment_id_if_present( &self, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<Option<FraudCheck>, errors::StorageError>; } #[async_trait::async_trait] impl FraudCheckInterface for Store { #[instrument(skip_all)] async fn insert_fraud_check_response( &self, new: storage::FraudCheckNew, ) -> CustomResult<FraudCheck, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_fraud_check_response_with_attempt_id( &self, this: FraudCheck, fraud_check: FraudCheckUpdate, ) -> CustomResult<FraudCheck, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update_with_attempt_id(&conn, fraud_check) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_fraud_check_by_payment_id( &self, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<FraudCheck, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; FraudCheck::get_with_payment_id(&conn, payment_id, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_fraud_check_by_payment_id_if_present( &self, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<Option<FraudCheck>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; FraudCheck::get_with_payment_id_if_present(&conn, payment_id, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl FraudCheckInterface for MockDb { async fn insert_fraud_check_response( &self, _new: storage::FraudCheckNew, ) -> CustomResult<FraudCheck, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_fraud_check_response_with_attempt_id( &self, _this: FraudCheck, _fraud_check: FraudCheckUpdate, ) -> CustomResult<FraudCheck, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_fraud_check_by_payment_id( &self, _payment_id: common_utils::id_type::PaymentId, _merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<FraudCheck, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_fraud_check_by_payment_id_if_present( &self, _payment_id: common_utils::id_type::PaymentId, _merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<Option<FraudCheck>, errors::StorageError> { Err(errors::StorageError::MockDbError)? } }
crates/router/src/db/fraud_check.rs
router::src::db::fraud_check
1,003
true
// File: crates/router/src/db/merchant_connector_account.rs // Module: router::src::db::merchant_connector_account use common_utils::ext_traits::{ByteSliceExt, Encode}; use error_stack::ResultExt; pub use hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccountInterface; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::RedisConnInterface; use super::{MockDb, Store}; use crate::{ core::errors::{self, CustomResult}, types, }; #[async_trait::async_trait] pub trait ConnectorAccessToken { async fn get_access_token( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id_or_connector_name: &str, ) -> CustomResult<Option<types::AccessToken>, errors::StorageError>; async fn set_access_token( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id_or_connector_name: &str, access_token: types::AccessToken, ) -> CustomResult<(), errors::StorageError>; } #[async_trait::async_trait] impl ConnectorAccessToken for Store { #[instrument(skip_all)] async fn get_access_token( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id_or_connector_name: &str, ) -> CustomResult<Option<types::AccessToken>, errors::StorageError> { //TODO: Handle race condition // This function should acquire a global lock on some resource, if access token is already // being refreshed by other request then wait till it finishes and use the same access token let key = common_utils::access_token::create_access_token_key( merchant_id, merchant_connector_id_or_connector_name, ); let maybe_token = self .get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .get_key::<Option<Vec<u8>>>(&key.into()) .await .change_context(errors::StorageError::KVError) .attach_printable("DB error when getting access token")?; let access_token = maybe_token .map(|token| token.parse_struct::<types::AccessToken>("AccessToken")) .transpose() .change_context(errors::StorageError::DeserializationFailed)?; Ok(access_token) } #[instrument(skip_all)] async fn set_access_token( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id_or_connector_name: &str, access_token: types::AccessToken, ) -> CustomResult<(), errors::StorageError> { let key = common_utils::access_token::create_access_token_key( merchant_id, merchant_connector_id_or_connector_name, ); let serialized_access_token = access_token .encode_to_string_of_json() .change_context(errors::StorageError::SerializationFailed)?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .set_key_with_expiry(&key.into(), serialized_access_token, access_token.expires) .await .change_context(errors::StorageError::KVError) } } #[async_trait::async_trait] impl ConnectorAccessToken for MockDb { async fn get_access_token( &self, _merchant_id: &common_utils::id_type::MerchantId, _merchant_connector_id_or_connector_name: &str, ) -> CustomResult<Option<types::AccessToken>, errors::StorageError> { Ok(None) } async fn set_access_token( &self, _merchant_id: &common_utils::id_type::MerchantId, _merchant_connector_id_or_connector_name: &str, _access_token: types::AccessToken, ) -> CustomResult<(), errors::StorageError> { Ok(()) } } #[cfg(feature = "accounts_cache")] #[cfg(test)] mod merchant_connector_account_cache_tests { use std::sync::Arc; #[cfg(feature = "v1")] use api_models::enums::CountryAlpha2; use common_utils::{date_time, type_name, types::keymanager::Identifier}; use diesel_models::enums::ConnectorType; use error_stack::ResultExt; use hyperswitch_domain_models::master_key::MasterKeyInterface; use masking::PeekInterface; use storage_impl::redis::{ cache::{self, CacheKey, CacheKind, ACCOUNTS_CACHE}, kv_store::RedisConnInterface, pub_sub::PubSubInterface, }; use time::macros::datetime; use tokio::sync::oneshot; use crate::{ core::errors, db::{ merchant_connector_account::MerchantConnectorAccountInterface, merchant_key_store::MerchantKeyStoreInterface, MockDb, }, routes::{ self, app::{settings::Settings, StorageImpl}, }, services, types::{ domain::{self, behaviour::Conversion}, storage, }, }; #[allow(clippy::unwrap_used)] #[tokio::test] #[cfg(feature = "v1")] async fn test_connector_profile_id_cache() { let conf = Settings::new().unwrap(); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = &Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); #[allow(clippy::expect_used)] let db = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let redis_conn = db.get_redis_conn().unwrap(); let master_key = db.get_master_key(); redis_conn .subscribe("hyperswitch_invalidate") .await .unwrap(); let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("test_merchant")) .unwrap(); let connector_label = "stripe_USA"; let merchant_connector_id = "simple_merchant_connector_id"; let profile_id = common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("pro_max_ultra")) .unwrap(); let key_manager_state = &state.into(); db.insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain::types::CryptoOperation::Encrypt( services::generate_aes256_key().unwrap().to_vec().into(), ), Identifier::Merchant(merchant_id.clone()), master_key, ) .await .and_then(|val| val.try_into_operation()) .unwrap(), created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await .unwrap(); let merchant_key = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &master_key.to_vec().into(), ) .await .unwrap(); let mca = domain::MerchantConnectorAccount { merchant_id: merchant_id.to_owned(), connector_name: "stripe".to_string(), connector_account_details: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain::types::CryptoOperation::Encrypt(serde_json::Value::default().into()), Identifier::Merchant(merchant_key.merchant_id.clone()), merchant_key.key.get_inner().peek(), ) .await .and_then(|val| val.try_into_operation()) .unwrap(), test_mode: None, disabled: None, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId::wrap( merchant_connector_id.to_string(), ) .unwrap(), payment_methods_enabled: None, connector_type: ConnectorType::FinOperations, metadata: None, frm_configs: None, connector_label: Some(connector_label.to_string()), business_country: Some(CountryAlpha2::US), business_label: Some("cloth".to_string()), business_sub_label: None, created_at: date_time::now(), modified_at: date_time::now(), connector_webhook_details: None, profile_id: profile_id.to_owned(), applepay_verified_domains: None, pm_auth_config: None, status: common_enums::ConnectorStatus::Inactive, connector_wallets_details: Some( domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain::types::CryptoOperation::Encrypt(serde_json::Value::default().into()), Identifier::Merchant(merchant_key.merchant_id.clone()), merchant_key.key.get_inner().peek(), ) .await .and_then(|val| val.try_into_operation()) .unwrap(), ), additional_merchant_data: None, version: common_types::consts::API_VERSION, }; db.insert_merchant_connector_account(key_manager_state, mca.clone(), &merchant_key) .await .unwrap(); let find_call = || async { Conversion::convert( db.find_merchant_connector_account_by_profile_id_connector_name( key_manager_state, &profile_id, &mca.connector_name, &merchant_key, ) .await .unwrap(), ) .await .change_context(errors::StorageError::DecryptionError) }; let _: storage::MerchantConnectorAccount = cache::get_or_populate_in_memory( &db, &format!( "{}_{}", merchant_id.get_string_repr(), profile_id.get_string_repr(), ), find_call, &ACCOUNTS_CACHE, ) .await .unwrap(); let delete_call = || async { db.delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &merchant_id, &common_utils::id_type::MerchantConnectorAccountId::wrap( merchant_connector_id.to_string(), ) .unwrap(), ) .await }; cache::publish_and_redact( &db, CacheKind::Accounts( format!("{}_{}", merchant_id.get_string_repr(), connector_label).into(), ), delete_call, ) .await .unwrap(); assert!(ACCOUNTS_CACHE .get_val::<domain::MerchantConnectorAccount>(CacheKey { key: format!("{}_{}", merchant_id.get_string_repr(), connector_label), prefix: String::default(), },) .await .is_none()) } #[allow(clippy::unwrap_used)] #[tokio::test] #[cfg(feature = "v2")] async fn test_connector_profile_id_cache() { let conf = Settings::new().unwrap(); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = &Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); #[allow(clippy::expect_used)] let db = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let redis_conn = db.get_redis_conn().unwrap(); let master_key = db.get_master_key(); redis_conn .subscribe("hyperswitch_invalidate") .await .unwrap(); let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("test_merchant")) .unwrap(); let connector_label = "stripe_USA"; let id = common_utils::generate_merchant_connector_account_id_of_default_length(); let profile_id = common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("pro_max_ultra")) .unwrap(); let key_manager_state = &state.into(); db.insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain::types::CryptoOperation::Encrypt( services::generate_aes256_key().unwrap().to_vec().into(), ), Identifier::Merchant(merchant_id.clone()), master_key, ) .await .and_then(|val| val.try_into_operation()) .unwrap(), created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await .unwrap(); let merchant_key = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &master_key.to_vec().into(), ) .await .unwrap(); let mca = domain::MerchantConnectorAccount { id: id.clone(), merchant_id: merchant_id.clone(), connector_name: common_enums::connector_enums::Connector::Stripe, connector_account_details: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain::types::CryptoOperation::Encrypt(serde_json::Value::default().into()), Identifier::Merchant(merchant_key.merchant_id.clone()), merchant_key.key.get_inner().peek(), ) .await .and_then(|val| val.try_into_operation()) .unwrap(), disabled: None, payment_methods_enabled: None, connector_type: ConnectorType::FinOperations, metadata: None, frm_configs: None, connector_label: Some(connector_label.to_string()), created_at: date_time::now(), modified_at: date_time::now(), connector_webhook_details: None, profile_id: profile_id.to_owned(), applepay_verified_domains: None, pm_auth_config: None, status: common_enums::ConnectorStatus::Inactive, connector_wallets_details: Some( domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain::types::CryptoOperation::Encrypt(serde_json::Value::default().into()), Identifier::Merchant(merchant_key.merchant_id.clone()), merchant_key.key.get_inner().peek(), ) .await .and_then(|val| val.try_into_operation()) .unwrap(), ), additional_merchant_data: None, version: common_types::consts::API_VERSION, feature_metadata: None, }; db.insert_merchant_connector_account(key_manager_state, mca.clone(), &merchant_key) .await .unwrap(); let find_call = || async { #[cfg(feature = "v1")] let mca = db .find_merchant_connector_account_by_profile_id_connector_name( key_manager_state, profile_id, &mca.connector_name, &merchant_key, ) .await .unwrap(); #[cfg(feature = "v2")] let mca: domain::MerchantConnectorAccount = { todo!() }; Conversion::convert(mca) .await .change_context(errors::StorageError::DecryptionError) }; let _: storage::MerchantConnectorAccount = cache::get_or_populate_in_memory( &db, &format!( "{}_{}", merchant_id.clone().get_string_repr(), profile_id.get_string_repr() ), find_call, &ACCOUNTS_CACHE, ) .await .unwrap(); let delete_call = || async { db.delete_merchant_connector_account_by_id(&id).await }; cache::publish_and_redact( &db, CacheKind::Accounts( format!("{}_{}", merchant_id.get_string_repr(), connector_label).into(), ), delete_call, ) .await .unwrap(); assert!(ACCOUNTS_CACHE .get_val::<domain::MerchantConnectorAccount>(CacheKey { key: format!("{}_{}", merchant_id.get_string_repr(), connector_label), prefix: String::default(), },) .await .is_none()) } }
crates/router/src/db/merchant_connector_account.rs
router::src::db::merchant_connector_account
3,614
true
// File: crates/router/src/db/configs.rs // Module: router::src::db::configs pub use hyperswitch_domain_models::{ configs::{self, ConfigInterface}, errors::api_error_response, };
crates/router/src/db/configs.rs
router::src::db::configs
45
true
// File: crates/router/src/db/blocklist_fingerprint.rs // Module: router::src::db::blocklist_fingerprint use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::MockDb; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, db::kafka_store::KafkaStore, types::storage, }; #[async_trait::async_trait] pub trait BlocklistFingerprintInterface { async fn insert_blocklist_fingerprint_entry( &self, pm_fingerprint_new: storage::BlocklistFingerprintNew, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError>; async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError>; } #[async_trait::async_trait] impl BlocklistFingerprintInterface for Store { #[instrument(skip_all)] async fn insert_blocklist_fingerprint_entry( &self, pm_fingerprint_new: storage::BlocklistFingerprintNew, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; pm_fingerprint_new .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::BlocklistFingerprint::find_by_merchant_id_fingerprint_id( &conn, merchant_id, fingerprint_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl BlocklistFingerprintInterface for MockDb { async fn insert_blocklist_fingerprint_entry( &self, _pm_fingerprint_new: storage::BlocklistFingerprintNew, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _fingerprint_id: &str, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[async_trait::async_trait] impl BlocklistFingerprintInterface for KafkaStore { #[instrument(skip_all)] async fn insert_blocklist_fingerprint_entry( &self, pm_fingerprint_new: storage::BlocklistFingerprintNew, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { self.diesel_store .insert_blocklist_fingerprint_entry(pm_fingerprint_new) .await } #[instrument(skip_all)] async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { self.diesel_store .find_blocklist_fingerprint_by_merchant_id_fingerprint_id(merchant_id, fingerprint) .await } }
crates/router/src/db/blocklist_fingerprint.rs
router::src::db::blocklist_fingerprint
806
true
// File: crates/router/src/db/payment_method_session.rs // Module: router::src::db::payment_method_session #[cfg(feature = "v2")] use crate::core::errors::{self, CustomResult}; use crate::db::MockDb; #[cfg(feature = "v2")] #[async_trait::async_trait] pub trait PaymentMethodsSessionInterface { async fn insert_payment_methods_session( &self, state: &common_utils::types::keymanager::KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, validity: i64, ) -> CustomResult<(), errors::StorageError>; async fn update_payment_method_session( &self, state: &common_utils::types::keymanager::KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, id: &common_utils::id_type::GlobalPaymentMethodSessionId, payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum, current_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, ) -> CustomResult< hyperswitch_domain_models::payment_methods::PaymentMethodSession, errors::StorageError, >; async fn get_payment_methods_session( &self, state: &common_utils::types::keymanager::KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, id: &common_utils::id_type::GlobalPaymentMethodSessionId, ) -> CustomResult< hyperswitch_domain_models::payment_methods::PaymentMethodSession, errors::StorageError, >; } #[cfg(feature = "v1")] pub trait PaymentMethodsSessionInterface {} #[cfg(feature = "v1")] impl PaymentMethodsSessionInterface for crate::services::Store {} #[cfg(feature = "v2")] mod storage { use error_stack::ResultExt; use hyperswitch_domain_models::behaviour::{Conversion, ReverseConversion}; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::RedisConnInterface; use super::PaymentMethodsSessionInterface; use crate::{ core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] impl PaymentMethodsSessionInterface for Store { #[instrument(skip_all)] async fn insert_payment_methods_session( &self, _state: &common_utils::types::keymanager::KeyManagerState, _key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, validity_in_seconds: i64, ) -> CustomResult<(), errors::StorageError> { let redis_key = payment_methods_session.id.get_redis_key(); let db_model = payment_methods_session .construct_new() .await .change_context(errors::StorageError::EncryptionError)?; let redis_connection = self .get_redis_conn() .map_err(Into::<errors::StorageError>::into)?; redis_connection .serialize_and_set_key_with_expiry(&redis_key.into(), db_model, validity_in_seconds) .await .change_context(errors::StorageError::KVError) .attach_printable("Failed to insert payment methods session to redis") } #[instrument(skip_all)] async fn get_payment_methods_session( &self, state: &common_utils::types::keymanager::KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, id: &common_utils::id_type::GlobalPaymentMethodSessionId, ) -> CustomResult< hyperswitch_domain_models::payment_methods::PaymentMethodSession, errors::StorageError, > { let redis_key = id.get_redis_key(); let redis_connection = self .get_redis_conn() .map_err(Into::<errors::StorageError>::into)?; let db_model = redis_connection .get_and_deserialize_key::<diesel_models::payment_methods_session::PaymentMethodSession>(&redis_key.into(), "PaymentMethodSession") .await .change_context(errors::StorageError::KVError)?; let key_manager_identifier = common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ); db_model .convert(state, &key_store.key, key_manager_identifier) .await .change_context(errors::StorageError::DecryptionError) .attach_printable("Failed to decrypt payment methods session") } #[instrument(skip_all)] async fn update_payment_method_session( &self, state: &common_utils::types::keymanager::KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, session_id: &common_utils::id_type::GlobalPaymentMethodSessionId, update_request: hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum, current_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, ) -> CustomResult< hyperswitch_domain_models::payment_methods::PaymentMethodSession, errors::StorageError, > { let redis_key = session_id.get_redis_key(); let internal_obj = hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateInternal::from(update_request); let update_state = current_session.apply_changeset(internal_obj); let db_model = update_state .construct_new() .await .change_context(errors::StorageError::EncryptionError)?; let redis_connection = self .get_redis_conn() .map_err(Into::<errors::StorageError>::into)?; redis_connection .serialize_and_set_key_without_modifying_ttl(&redis_key.into(), db_model.clone()) .await .change_context(errors::StorageError::KVError) .attach_printable("Failed to insert payment methods session to redis"); let key_manager_identifier = common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ); db_model .convert(state, &key_store.key, key_manager_identifier) .await .change_context(errors::StorageError::DecryptionError) .attach_printable("Failed to decrypt payment methods session") } } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl PaymentMethodsSessionInterface for MockDb { async fn insert_payment_methods_session( &self, state: &common_utils::types::keymanager::KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, validity_in_seconds: i64, ) -> CustomResult<(), errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_payment_method_session( &self, state: &common_utils::types::keymanager::KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, id: &common_utils::id_type::GlobalPaymentMethodSessionId, payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum, current_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, ) -> CustomResult< hyperswitch_domain_models::payment_methods::PaymentMethodSession, errors::StorageError, > { Err(errors::StorageError::MockDbError)? } #[cfg(feature = "v2")] async fn get_payment_methods_session( &self, state: &common_utils::types::keymanager::KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, id: &common_utils::id_type::GlobalPaymentMethodSessionId, ) -> CustomResult< hyperswitch_domain_models::payment_methods::PaymentMethodSession, errors::StorageError, > { Err(errors::StorageError::MockDbError)? } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl PaymentMethodsSessionInterface for MockDb {}
crates/router/src/db/payment_method_session.rs
router::src::db::payment_method_session
1,768
true
// File: crates/router/src/db/routing_algorithm.rs // Module: router::src::db::routing_algorithm use diesel_models::routing_algorithm as routing_storage; use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::mock_db::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; type StorageResult<T> = CustomResult<T, errors::StorageError>; #[async_trait::async_trait] pub trait RoutingAlgorithmInterface { async fn insert_routing_algorithm( &self, routing_algorithm: routing_storage::RoutingAlgorithm, ) -> StorageResult<routing_storage::RoutingAlgorithm>; async fn find_routing_algorithm_by_profile_id_algorithm_id( &self, profile_id: &common_utils::id_type::ProfileId, algorithm_id: &common_utils::id_type::RoutingId, ) -> StorageResult<routing_storage::RoutingAlgorithm>; async fn find_routing_algorithm_by_algorithm_id_merchant_id( &self, algorithm_id: &common_utils::id_type::RoutingId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<routing_storage::RoutingAlgorithm>; async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id( &self, algorithm_id: &common_utils::id_type::RoutingId, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<routing_storage::RoutingProfileMetadata>; async fn list_routing_algorithm_metadata_by_profile_id( &self, profile_id: &common_utils::id_type::ProfileId, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>>; async fn list_routing_algorithm_metadata_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>>; async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type( &self, merchant_id: &common_utils::id_type::MerchantId, transaction_type: &common_enums::TransactionType, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>>; } #[async_trait::async_trait] impl RoutingAlgorithmInterface for Store { #[instrument(skip_all)] async fn insert_routing_algorithm( &self, routing_algorithm: routing_storage::RoutingAlgorithm, ) -> StorageResult<routing_storage::RoutingAlgorithm> { let conn = connection::pg_connection_write(self).await?; routing_algorithm .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_routing_algorithm_by_profile_id_algorithm_id( &self, profile_id: &common_utils::id_type::ProfileId, algorithm_id: &common_utils::id_type::RoutingId, ) -> StorageResult<routing_storage::RoutingAlgorithm> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::find_by_algorithm_id_profile_id( &conn, algorithm_id, profile_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_routing_algorithm_by_algorithm_id_merchant_id( &self, algorithm_id: &common_utils::id_type::RoutingId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<routing_storage::RoutingAlgorithm> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::find_by_algorithm_id_merchant_id( &conn, algorithm_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id( &self, algorithm_id: &common_utils::id_type::RoutingId, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<routing_storage::RoutingProfileMetadata> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::find_metadata_by_algorithm_id_profile_id( &conn, algorithm_id, profile_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_routing_algorithm_metadata_by_profile_id( &self, profile_id: &common_utils::id_type::ProfileId, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::list_metadata_by_profile_id( &conn, profile_id, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_routing_algorithm_metadata_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::list_metadata_by_merchant_id( &conn, merchant_id, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type( &self, merchant_id: &common_utils::id_type::MerchantId, transaction_type: &common_enums::TransactionType, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::list_metadata_by_merchant_id_transaction_type( &conn, merchant_id, transaction_type, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl RoutingAlgorithmInterface for MockDb { async fn insert_routing_algorithm( &self, _routing_algorithm: routing_storage::RoutingAlgorithm, ) -> StorageResult<routing_storage::RoutingAlgorithm> { Err(errors::StorageError::MockDbError)? } async fn find_routing_algorithm_by_profile_id_algorithm_id( &self, _profile_id: &common_utils::id_type::ProfileId, _algorithm_id: &common_utils::id_type::RoutingId, ) -> StorageResult<routing_storage::RoutingAlgorithm> { Err(errors::StorageError::MockDbError)? } async fn find_routing_algorithm_by_algorithm_id_merchant_id( &self, _algorithm_id: &common_utils::id_type::RoutingId, _merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<routing_storage::RoutingAlgorithm> { Err(errors::StorageError::MockDbError)? } async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id( &self, _algorithm_id: &common_utils::id_type::RoutingId, _profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<routing_storage::RoutingProfileMetadata> { Err(errors::StorageError::MockDbError)? } async fn list_routing_algorithm_metadata_by_profile_id( &self, _profile_id: &common_utils::id_type::ProfileId, _limit: i64, _offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { Err(errors::StorageError::MockDbError)? } async fn list_routing_algorithm_metadata_by_merchant_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _limit: i64, _offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { Err(errors::StorageError::MockDbError)? } async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type( &self, _merchant_id: &common_utils::id_type::MerchantId, _transaction_type: &common_enums::TransactionType, _limit: i64, _offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { Err(errors::StorageError::MockDbError)? } }
crates/router/src/db/routing_algorithm.rs
router::src::db::routing_algorithm
1,913
true
// File: crates/router/src/db/address.rs // Module: router::src::db::address use common_utils::{id_type, types::keymanager::KeyManagerState}; use diesel_models::{address::AddressUpdateInternal, enums::MerchantStorageScheme}; use error_stack::ResultExt; use super::MockDb; use crate::{ core::errors::{self, CustomResult}, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage as storage_types, }, }; #[async_trait::async_trait] pub trait AddressInterface where domain::Address: Conversion<DstType = storage_types::Address, NewDstType = storage_types::AddressNew>, { async fn update_address( &self, state: &KeyManagerState, address_id: String, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError>; async fn update_address_for_payments( &self, state: &KeyManagerState, this: domain::PaymentAddress, address: domain::AddressUpdate, payment_id: id_type::PaymentId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError>; async fn find_address_by_address_id( &self, state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError>; async fn insert_address_for_payments( &self, state: &KeyManagerState, payment_id: &id_type::PaymentId, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError>; async fn insert_address_for_customers( &self, state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError>; async fn find_address_by_merchant_id_payment_id_address_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, address_id: &str, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError>; async fn update_address_by_merchant_id_customer_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Address>, errors::StorageError>; } #[cfg(not(feature = "kv_store"))] mod storage { use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::AddressInterface; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage::{self as storage_types, enums::MerchantStorageScheme}, }, }; #[async_trait::async_trait] impl AddressInterface for Store { #[instrument(skip_all)] async fn find_address_by_address_id( &self, state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Address::find_by_address_id(&conn, address_id) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn find_address_by_merchant_id_payment_id_address_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, address_id: &str, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Address::find_by_merchant_id_payment_id_address_id( &conn, merchant_id, payment_id, address_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn update_address( &self, state: &KeyManagerState, address_id: String, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Address::update_by_address_id(&conn, address_id, address.into()) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn update_address_for_payments( &self, state: &KeyManagerState, this: domain::PaymentAddress, address_update: domain::AddressUpdate, _payment_id: id_type::PaymentId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let address = Conversion::convert(this) .await .change_context(errors::StorageError::EncryptionError)?; address .update(&conn, address_update.into()) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn insert_address_for_payments( &self, state: &KeyManagerState, _payment_id: &id_type::PaymentId, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; address .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn insert_address_for_customers( &self, state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; address .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn update_address_by_merchant_id_customer_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Address>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Address::update_by_merchant_id_customer_id( &conn, customer_id, merchant_id, address.into(), ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|addresses| async { let mut output = Vec::with_capacity(addresses.len()); for address in addresses.into_iter() { output.push( address .convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) }) .await } } } #[cfg(feature = "kv_store")] mod storage { use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use diesel_models::{enums::MerchantStorageScheme, AddressUpdateInternal}; use error_stack::{report, ResultExt}; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::{ decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey, }; use super::AddressInterface; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage::{self as storage_types, kv}, }, utils::db_utils, }; #[async_trait::async_trait] impl AddressInterface for Store { #[instrument(skip_all)] async fn find_address_by_address_id( &self, state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Address::find_by_address_id(&conn, address_id) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn find_address_by_merchant_id_payment_id_address_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, address_id: &str, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Address::find_by_merchant_id_payment_id_address_id( &conn, merchant_id, payment_id, address_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Address>( self, storage_scheme, Op::Find, )) .await; let address = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPaymentId { merchant_id, payment_id, }; let field = format!("add_{address_id}"); Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Address>::HGet(&field), key, )) .await? .try_into_hget() }, database_call, )) .await } }?; address .convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn update_address( &self, state: &KeyManagerState, address_id: String, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Address::update_by_address_id(&conn, address_id, address.into()) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn update_address_for_payments( &self, state: &KeyManagerState, this: domain::PaymentAddress, address_update: domain::AddressUpdate, payment_id: id_type::PaymentId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let address = Conversion::convert(this) .await .change_context(errors::StorageError::EncryptionError)?; let merchant_id = address.merchant_id.clone(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, }; let field = format!("add_{}", address.address_id); let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Address>( self, storage_scheme, Op::Update(key.clone(), &field, Some(address.updated_by.as_str())), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { address .update(&conn, address_update.into()) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } MerchantStorageScheme::RedisKv => { let updated_address = AddressUpdateInternal::from(address_update.clone()) .create_address(address.clone()); let redis_value = serde_json::to_string(&updated_address) .change_context(errors::StorageError::KVError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::AddressUpdate(Box::new( kv::AddressUpdateMems { orig: address, update_data: address_update.into(), }, ))), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::Hset::<storage_types::Address>( (&field, redis_value), redis_entry, ), key, )) .await .change_context(errors::StorageError::KVError)? .try_into_hset() .change_context(errors::StorageError::KVError)?; updated_address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } } } #[instrument(skip_all)] async fn insert_address_for_payments( &self, state: &KeyManagerState, payment_id: &id_type::PaymentId, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { let address_new = address .clone() .construct_new() .await .change_context(errors::StorageError::EncryptionError)?; let merchant_id = address_new.merchant_id.clone(); let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Address>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { let conn = connection::pg_connection_write(self).await?; address_new .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id, }; let field = format!("add_{}", &address_new.address_id); let created_address = diesel_models::Address { address_id: address_new.address_id.clone(), city: address_new.city.clone(), country: address_new.country, line1: address_new.line1.clone(), line2: address_new.line2.clone(), line3: address_new.line3.clone(), state: address_new.state.clone(), zip: address_new.zip.clone(), first_name: address_new.first_name.clone(), last_name: address_new.last_name.clone(), phone_number: address_new.phone_number.clone(), country_code: address_new.country_code.clone(), created_at: address_new.created_at, modified_at: address_new.modified_at, customer_id: address_new.customer_id.clone(), merchant_id: address_new.merchant_id.clone(), payment_id: address_new.payment_id.clone(), updated_by: storage_scheme.to_string(), email: address_new.email.clone(), origin_zip: address_new.origin_zip.clone(), }; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::Address(Box::new(address_new))), }, }; match Box::pin(kv_wrapper::<diesel_models::Address, _, _>( self, KvOperation::HSetNx::<diesel_models::Address>( &field, &created_address, redis_entry, ), key, )) .await .change_context(errors::StorageError::KVError)? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "address", key: Some(created_address.address_id), } .into()), Ok(HsetnxReply::KeySet) => Ok(created_address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } } } #[instrument(skip_all)] async fn insert_address_for_customers( &self, state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; address .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn update_address_by_merchant_id_customer_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Address>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Address::update_by_merchant_id_customer_id( &conn, customer_id, merchant_id, address.into(), ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|addresses| async { let mut output = Vec::with_capacity(addresses.len()); for address in addresses.into_iter() { output.push( address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) }) .await } } } #[async_trait::async_trait] impl AddressInterface for MockDb { async fn find_address_by_address_id( &self, state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { match self .addresses .lock() .await .iter() .find(|address| address.address_id == address_id) { Some(address) => address .clone() .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError), None => { return Err( errors::StorageError::ValueNotFound("address not found".to_string()).into(), ) } } } async fn find_address_by_merchant_id_payment_id_address_id( &self, state: &KeyManagerState, _merchant_id: &id_type::MerchantId, _payment_id: &id_type::PaymentId, address_id: &str, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { match self .addresses .lock() .await .iter() .find(|address| address.address_id == address_id) { Some(address) => address .clone() .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError), None => { return Err( errors::StorageError::ValueNotFound("address not found".to_string()).into(), ) } } } async fn update_address( &self, state: &KeyManagerState, address_id: String, address_update: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { let updated_addr = self .addresses .lock() .await .iter_mut() .find(|address| address.address_id == address_id) .map(|a| { let address_updated = AddressUpdateInternal::from(address_update).create_address(a.clone()); *a = address_updated.clone(); address_updated }); match updated_addr { Some(address_updated) => address_updated .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError), None => Err(errors::StorageError::ValueNotFound( "cannot find address to update".to_string(), ) .into()), } } async fn update_address_for_payments( &self, state: &KeyManagerState, this: domain::PaymentAddress, address_update: domain::AddressUpdate, _payment_id: id_type::PaymentId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { let updated_addr = self .addresses .lock() .await .iter_mut() .find(|address| address.address_id == this.address.address_id) .map(|a| { let address_updated = AddressUpdateInternal::from(address_update).create_address(a.clone()); *a = address_updated.clone(); address_updated }); match updated_addr { Some(address_updated) => address_updated .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError), None => Err(errors::StorageError::ValueNotFound( "cannot find address to update".to_string(), ) .into()), } } async fn insert_address_for_payments( &self, state: &KeyManagerState, _payment_id: &id_type::PaymentId, address_new: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { let mut addresses = self.addresses.lock().await; let address = Conversion::convert(address_new) .await .change_context(errors::StorageError::EncryptionError)?; addresses.push(address.clone()); address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn insert_address_for_customers( &self, state: &KeyManagerState, address_new: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { let mut addresses = self.addresses.lock().await; let address = Conversion::convert(address_new) .await .change_context(errors::StorageError::EncryptionError)?; addresses.push(address.clone()); address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn update_address_by_merchant_id_customer_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, address_update: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Address>, errors::StorageError> { let updated_addr = self .addresses .lock() .await .iter_mut() .find(|address| { address.customer_id.as_ref() == Some(customer_id) && address.merchant_id == *merchant_id }) .map(|a| { let address_updated = AddressUpdateInternal::from(address_update).create_address(a.clone()); *a = address_updated.clone(); address_updated }); match updated_addr { Some(address) => { let address: domain::Address = address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; Ok(vec![address]) } None => { Err(errors::StorageError::ValueNotFound("address not found".to_string()).into()) } } } }
crates/router/src/db/address.rs
router::src::db::address
6,516
true
// File: crates/router/src/db/blocklist_lookup.rs // Module: router::src::db::blocklist_lookup use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::MockDb; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, db::kafka_store::KafkaStore, types::storage, }; #[async_trait::async_trait] pub trait BlocklistLookupInterface { async fn insert_blocklist_lookup_entry( &self, blocklist_lookup_new: storage::BlocklistLookupNew, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError>; async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError>; async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError>; } #[async_trait::async_trait] impl BlocklistLookupInterface for Store { #[instrument(skip_all)] async fn insert_blocklist_lookup_entry( &self, blocklist_lookup_entry: storage::BlocklistLookupNew, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; blocklist_lookup_entry .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::BlocklistLookup::find_by_merchant_id_fingerprint(&conn, merchant_id, fingerprint) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::BlocklistLookup::delete_by_merchant_id_fingerprint(&conn, merchant_id, fingerprint) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl BlocklistLookupInterface for MockDb { #[instrument(skip_all)] async fn insert_blocklist_lookup_entry( &self, _blocklist_lookup_entry: storage::BlocklistLookupNew, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, _merchant_id: &common_utils::id_type::MerchantId, _fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, _merchant_id: &common_utils::id_type::MerchantId, _fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[async_trait::async_trait] impl BlocklistLookupInterface for KafkaStore { #[instrument(skip_all)] async fn insert_blocklist_lookup_entry( &self, blocklist_lookup_entry: storage::BlocklistLookupNew, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { self.diesel_store .insert_blocklist_lookup_entry(blocklist_lookup_entry) .await } #[instrument(skip_all)] async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { self.diesel_store .find_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, fingerprint) .await } #[instrument(skip_all)] async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { self.diesel_store .delete_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, fingerprint) .await } }
crates/router/src/db/blocklist_lookup.rs
router::src::db::blocklist_lookup
1,116
true
// File: crates/router/src/db/blocklist.rs // Module: router::src::db::blocklist use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::MockDb; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, db::kafka_store::KafkaStore, types::storage, }; #[async_trait::async_trait] pub trait BlocklistInterface { async fn insert_blocklist_entry( &self, pm_blocklist_new: storage::BlocklistNew, ) -> CustomResult<storage::Blocklist, errors::StorageError>; async fn find_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError>; async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError>; async fn list_blocklist_entries_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>; async fn list_blocklist_entries_by_merchant_id_data_kind( &self, merchant_id: &common_utils::id_type::MerchantId, data_kind: common_enums::BlocklistDataKind, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>; } #[async_trait::async_trait] impl BlocklistInterface for Store { #[instrument(skip_all)] async fn insert_blocklist_entry( &self, pm_blocklist: storage::BlocklistNew, ) -> CustomResult<storage::Blocklist, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; pm_blocklist .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Blocklist::find_by_merchant_id_fingerprint_id(&conn, merchant_id, fingerprint_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_blocklist_entries_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Blocklist::list_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_blocklist_entries_by_merchant_id_data_kind( &self, merchant_id: &common_utils::id_type::MerchantId, data_kind: common_enums::BlocklistDataKind, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Blocklist::list_by_merchant_id_data_kind( &conn, merchant_id, data_kind, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Blocklist::delete_by_merchant_id_fingerprint_id(&conn, merchant_id, fingerprint_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl BlocklistInterface for MockDb { #[instrument(skip_all)] async fn insert_blocklist_entry( &self, _pm_blocklist: storage::BlocklistNew, ) -> CustomResult<storage::Blocklist, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_blocklist_entry_by_merchant_id_fingerprint_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn list_blocklist_entries_by_merchant_id( &self, _merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn list_blocklist_entries_by_merchant_id_data_kind( &self, _merchant_id: &common_utils::id_type::MerchantId, _data_kind: common_enums::BlocklistDataKind, _limit: i64, _offset: i64, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[async_trait::async_trait] impl BlocklistInterface for KafkaStore { #[instrument(skip_all)] async fn insert_blocklist_entry( &self, pm_blocklist: storage::BlocklistNew, ) -> CustomResult<storage::Blocklist, errors::StorageError> { self.diesel_store.insert_blocklist_entry(pm_blocklist).await } #[instrument(skip_all)] async fn find_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { self.diesel_store .find_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, fingerprint) .await } #[instrument(skip_all)] async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { self.diesel_store .delete_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, fingerprint) .await } #[instrument(skip_all)] async fn list_blocklist_entries_by_merchant_id_data_kind( &self, merchant_id: &common_utils::id_type::MerchantId, data_kind: common_enums::BlocklistDataKind, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { self.diesel_store .list_blocklist_entries_by_merchant_id_data_kind(merchant_id, data_kind, limit, offset) .await } #[instrument(skip_all)] async fn list_blocklist_entries_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { self.diesel_store .list_blocklist_entries_by_merchant_id(merchant_id) .await } }
crates/router/src/db/blocklist.rs
router::src::db::blocklist
1,824
true
// File: crates/router/src/db/user.rs // Module: router::src::db::user use diesel_models::user as storage; use error_stack::report; use masking::Secret; use router_env::{instrument, tracing}; use super::{domain, MockDb}; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; pub mod sample_data; pub mod theme; #[async_trait::async_trait] pub trait UserInterface { async fn insert_user( &self, user_data: storage::UserNew, ) -> CustomResult<storage::User, errors::StorageError>; async fn find_user_by_email( &self, user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError>; async fn find_user_by_id( &self, user_id: &str, ) -> CustomResult<storage::User, errors::StorageError>; async fn update_user_by_user_id( &self, user_id: &str, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError>; async fn update_user_by_email( &self, user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError>; async fn delete_user_by_user_id( &self, user_id: &str, ) -> CustomResult<bool, errors::StorageError>; async fn find_users_by_user_ids( &self, user_ids: Vec<String>, ) -> CustomResult<Vec<storage::User>, errors::StorageError>; } #[async_trait::async_trait] impl UserInterface for Store { #[instrument(skip_all)] async fn insert_user( &self, user_data: storage::UserNew, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; user_data .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_user_by_email( &self, user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::User::find_by_user_email(&conn, user_email.get_inner()) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_user_by_id( &self, user_id: &str, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::User::find_by_user_id(&conn, user_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_user_by_user_id( &self, user_id: &str, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::User::update_by_user_id(&conn, user_id, user) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_user_by_email( &self, user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::User::update_by_user_email(&conn, user_email.get_inner(), user) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_user_by_user_id( &self, user_id: &str, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::User::delete_by_user_id(&conn, user_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_users_by_user_ids( &self, user_ids: Vec<String>, ) -> CustomResult<Vec<storage::User>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::User::find_users_by_user_ids(&conn, user_ids) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl UserInterface for MockDb { async fn insert_user( &self, user_data: storage::UserNew, ) -> CustomResult<storage::User, errors::StorageError> { let mut users = self.users.lock().await; if users .iter() .any(|user| user.email == user_data.email || user.user_id == user_data.user_id) { Err(errors::StorageError::DuplicateValue { entity: "email or user_id", key: None, })? } let time_now = common_utils::date_time::now(); let user = storage::User { user_id: user_data.user_id, email: user_data.email, name: user_data.name, password: user_data.password, is_verified: user_data.is_verified, created_at: user_data.created_at.unwrap_or(time_now), last_modified_at: user_data.created_at.unwrap_or(time_now), totp_status: user_data.totp_status, totp_secret: user_data.totp_secret, totp_recovery_codes: user_data.totp_recovery_codes, last_password_modified_at: user_data.last_password_modified_at, lineage_context: user_data.lineage_context, }; users.push(user.clone()); Ok(user) } async fn find_user_by_email( &self, user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { let users = self.users.lock().await; users .iter() .find(|user| user.email.eq(user_email.get_inner())) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No user available for email = {user_email:?}" )) .into(), ) } async fn find_user_by_id( &self, user_id: &str, ) -> CustomResult<storage::User, errors::StorageError> { let users = self.users.lock().await; users .iter() .find(|user| user.user_id == user_id) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No user available for user_id = {user_id}" )) .into(), ) } async fn update_user_by_user_id( &self, user_id: &str, update_user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let mut users = self.users.lock().await; let last_modified_at = common_utils::date_time::now(); users .iter_mut() .find(|user| user.user_id == user_id) .map(|user| { *user = match &update_user { storage::UserUpdate::VerifyUser => storage::User { last_modified_at, is_verified: true, ..user.to_owned() }, storage::UserUpdate::AccountUpdate { name, is_verified } => storage::User { name: name.clone().map(Secret::new).unwrap_or(user.name.clone()), last_modified_at, is_verified: is_verified.unwrap_or(user.is_verified), ..user.to_owned() }, storage::UserUpdate::TotpUpdate { totp_status, totp_secret, totp_recovery_codes, } => storage::User { last_modified_at, totp_status: totp_status.unwrap_or(user.totp_status), totp_secret: totp_secret.clone().or(user.totp_secret.clone()), totp_recovery_codes: totp_recovery_codes .clone() .or(user.totp_recovery_codes.clone()), ..user.to_owned() }, storage::UserUpdate::PasswordUpdate { password } => storage::User { password: Some(password.clone()), last_password_modified_at: Some(common_utils::date_time::now()), ..user.to_owned() }, storage::UserUpdate::LineageContextUpdate { lineage_context } => { storage::User { last_modified_at, lineage_context: Some(lineage_context.clone()), ..user.to_owned() } } }; user.to_owned() }) .ok_or( errors::StorageError::ValueNotFound(format!( "No user available for user_id = {user_id}" )) .into(), ) } async fn update_user_by_email( &self, user_email: &domain::UserEmail, update_user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let mut users = self.users.lock().await; let last_modified_at = common_utils::date_time::now(); users .iter_mut() .find(|user| user.email.eq(user_email.get_inner())) .map(|user| { *user = match &update_user { storage::UserUpdate::VerifyUser => storage::User { last_modified_at, is_verified: true, ..user.to_owned() }, storage::UserUpdate::AccountUpdate { name, is_verified } => storage::User { name: name.clone().map(Secret::new).unwrap_or(user.name.clone()), last_modified_at, is_verified: is_verified.unwrap_or(user.is_verified), ..user.to_owned() }, storage::UserUpdate::TotpUpdate { totp_status, totp_secret, totp_recovery_codes, } => storage::User { last_modified_at, totp_status: totp_status.unwrap_or(user.totp_status), totp_secret: totp_secret.clone().or(user.totp_secret.clone()), totp_recovery_codes: totp_recovery_codes .clone() .or(user.totp_recovery_codes.clone()), ..user.to_owned() }, storage::UserUpdate::PasswordUpdate { password } => storage::User { password: Some(password.clone()), last_password_modified_at: Some(common_utils::date_time::now()), ..user.to_owned() }, storage::UserUpdate::LineageContextUpdate { lineage_context } => { storage::User { last_modified_at, lineage_context: Some(lineage_context.clone()), ..user.to_owned() } } }; user.to_owned() }) .ok_or( errors::StorageError::ValueNotFound(format!( "No user available for user_email = {user_email:?}" )) .into(), ) } async fn delete_user_by_user_id( &self, user_id: &str, ) -> CustomResult<bool, errors::StorageError> { let mut users = self.users.lock().await; let user_index = users .iter() .position(|user| user.user_id == user_id) .ok_or(errors::StorageError::ValueNotFound(format!( "No user available for user_id = {user_id}" )))?; users.remove(user_index); Ok(true) } async fn find_users_by_user_ids( &self, _user_ids: Vec<String>, ) -> CustomResult<Vec<storage::User>, errors::StorageError> { Err(errors::StorageError::MockDbError)? } }
crates/router/src/db/user.rs
router::src::db::user
2,591
true
// File: crates/router/src/db/user_role.rs // Module: router::src::db::user_role use common_utils::id_type; use diesel_models::{ enums::{self, UserStatus}, user_role as storage, }; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; pub struct ListUserRolesByOrgIdPayload<'a> { pub user_id: Option<&'a String>, pub tenant_id: &'a id_type::TenantId, pub org_id: &'a id_type::OrganizationId, pub merchant_id: Option<&'a id_type::MerchantId>, pub profile_id: Option<&'a id_type::ProfileId>, pub version: Option<enums::UserRoleVersion>, pub limit: Option<u32>, } pub struct ListUserRolesByUserIdPayload<'a> { pub user_id: &'a str, pub tenant_id: &'a id_type::TenantId, pub org_id: Option<&'a id_type::OrganizationId>, pub merchant_id: Option<&'a id_type::MerchantId>, pub profile_id: Option<&'a id_type::ProfileId>, pub entity_id: Option<&'a String>, pub version: Option<enums::UserRoleVersion>, pub status: Option<UserStatus>, pub limit: Option<u32>, } #[async_trait::async_trait] pub trait UserRoleInterface { async fn insert_user_role( &self, user_role: storage::UserRoleNew, ) -> CustomResult<storage::UserRole, errors::StorageError>; async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; #[allow(clippy::too_many_arguments)] async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, update: storage::UserRoleUpdate, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; async fn delete_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; async fn list_user_roles_by_user_id<'a>( &self, payload: ListUserRolesByUserIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; async fn list_user_roles_by_user_id_across_tenants( &self, user_id: &str, limit: Option<u32>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; async fn list_user_roles_by_org_id<'a>( &self, payload: ListUserRolesByOrgIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; } #[async_trait::async_trait] impl UserRoleInterface for Store { #[instrument(skip_all)] async fn insert_user_role( &self, user_role: storage::UserRoleNew, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; user_role .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserRole::find_by_user_id_tenant_id_org_id_merchant_id_profile_id( &conn, user_id.to_owned(), tenant_id.to_owned(), org_id.to_owned(), merchant_id.to_owned(), profile_id.to_owned(), version, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, update: storage::UserRoleUpdate, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::UserRole::update_by_user_id_tenant_id_org_id_merchant_id_profile_id( &conn, user_id.to_owned(), tenant_id.to_owned(), org_id.to_owned(), merchant_id.cloned(), profile_id.cloned(), update, version, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::UserRole::delete_by_user_id_tenant_id_org_id_merchant_id_profile_id( &conn, user_id.to_owned(), tenant_id.to_owned(), org_id.to_owned(), merchant_id.to_owned(), profile_id.to_owned(), version, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn list_user_roles_by_user_id<'a>( &self, payload: ListUserRolesByUserIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserRole::generic_user_roles_list_for_user( &conn, payload.user_id.to_owned(), payload.tenant_id.to_owned(), payload.org_id.cloned(), payload.merchant_id.cloned(), payload.profile_id.cloned(), payload.entity_id.cloned(), payload.status, payload.version, payload.limit, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn list_user_roles_by_user_id_across_tenants( &self, user_id: &str, limit: Option<u32>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserRole::list_user_roles_by_user_id_across_tenants( &conn, user_id.to_owned(), limit, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn list_user_roles_by_org_id<'a>( &self, payload: ListUserRolesByOrgIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserRole::generic_user_roles_list_for_org_and_extra( &conn, payload.user_id.cloned(), payload.tenant_id.to_owned(), payload.org_id.to_owned(), payload.merchant_id.cloned(), payload.profile_id.cloned(), payload.version, payload.limit, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl UserRoleInterface for MockDb { async fn insert_user_role( &self, user_role: storage::UserRoleNew, ) -> CustomResult<storage::UserRole, errors::StorageError> { let mut db_user_roles = self.user_roles.lock().await; if db_user_roles .iter() .any(|user_role_inner| user_role_inner.user_id == user_role.user_id) { Err(errors::StorageError::DuplicateValue { entity: "user_id", key: None, })? } let user_role = storage::UserRole { id: i32::try_from(db_user_roles.len()) .change_context(errors::StorageError::MockDbError)?, user_id: user_role.user_id, merchant_id: user_role.merchant_id, role_id: user_role.role_id, status: user_role.status, created_by: user_role.created_by, created_at: user_role.created_at, last_modified: user_role.last_modified, last_modified_by: user_role.last_modified_by, org_id: user_role.org_id, profile_id: None, entity_id: None, entity_type: None, version: enums::UserRoleVersion::V1, tenant_id: user_role.tenant_id, }; db_user_roles.push(user_role.clone()); Ok(user_role) } async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let user_roles = self.user_roles.lock().await; for user_role in user_roles.iter() { let tenant_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.is_none() && user_role.merchant_id.is_none() && user_role.profile_id.is_none(); let org_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.is_none() && user_role.profile_id.is_none(); let merchant_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == Some(merchant_id) && user_role.profile_id.is_none(); let profile_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == Some(merchant_id) && user_role.profile_id.as_ref() == Some(profile_id); // Check if any condition matches and the version matches if user_role.user_id == user_id && (tenant_level_check || org_level_check || merchant_level_check || profile_level_check) && user_role.version == version { return Ok(user_role.clone()); } } Err(errors::StorageError::ValueNotFound(format!( "No user role available for user_id = {user_id} in the current token hierarchy", )) .into()) } async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, update: storage::UserRoleUpdate, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let mut user_roles = self.user_roles.lock().await; for user_role in user_roles.iter_mut() { let tenant_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.is_none() && user_role.merchant_id.is_none() && user_role.profile_id.is_none(); let org_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.is_none() && user_role.profile_id.is_none(); let merchant_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == merchant_id && user_role.profile_id.is_none(); let profile_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == merchant_id && user_role.profile_id.as_ref() == profile_id; // Check if any condition matches and the version matches if user_role.user_id == user_id && (tenant_level_check || org_level_check || merchant_level_check || profile_level_check) && user_role.version == version { match &update { storage::UserRoleUpdate::UpdateRole { role_id, modified_by, } => { user_role.role_id = role_id.to_string(); user_role.last_modified_by = modified_by.to_string(); } storage::UserRoleUpdate::UpdateStatus { status, modified_by, } => { user_role.status = *status; user_role.last_modified_by = modified_by.to_string(); } } return Ok(user_role.clone()); } } Err( errors::StorageError::ValueNotFound("Cannot find user role to update".to_string()) .into(), ) } async fn delete_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let mut user_roles = self.user_roles.lock().await; // Find the position of the user role to delete let index = user_roles.iter().position(|role| { let tenant_level_check = role.tenant_id == *tenant_id && role.org_id.is_none() && role.merchant_id.is_none() && role.profile_id.is_none(); let org_level_check = role.tenant_id == *tenant_id && role.org_id.as_ref() == Some(org_id) && role.merchant_id.is_none() && role.profile_id.is_none(); let merchant_level_check = role.tenant_id == *tenant_id && role.org_id.as_ref() == Some(org_id) && role.merchant_id.as_ref() == Some(merchant_id) && role.profile_id.is_none(); let profile_level_check = role.tenant_id == *tenant_id && role.org_id.as_ref() == Some(org_id) && role.merchant_id.as_ref() == Some(merchant_id) && role.profile_id.as_ref() == Some(profile_id); // Check if the user role matches the conditions and the version matches role.user_id == user_id && (tenant_level_check || org_level_check || merchant_level_check || profile_level_check) && role.version == version }); // Remove and return the user role if found match index { Some(idx) => Ok(user_roles.remove(idx)), None => Err(errors::StorageError::ValueNotFound( "Cannot find user role to delete".to_string(), ) .into()), } } async fn list_user_roles_by_user_id<'a>( &self, payload: ListUserRolesByUserIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let user_roles = self.user_roles.lock().await; let mut filtered_roles: Vec<_> = user_roles .iter() .filter_map(|role| { let mut filter_condition = role.user_id == payload.user_id; role.org_id .as_ref() .zip(payload.org_id) .inspect(|(role_org_id, org_id)| { filter_condition = filter_condition && role_org_id == org_id }); role.merchant_id.as_ref().zip(payload.merchant_id).inspect( |(role_merchant_id, merchant_id)| { filter_condition = filter_condition && role_merchant_id == merchant_id }, ); role.profile_id.as_ref().zip(payload.profile_id).inspect( |(role_profile_id, profile_id)| { filter_condition = filter_condition && role_profile_id == profile_id }, ); role.entity_id.as_ref().zip(payload.entity_id).inspect( |(role_entity_id, entity_id)| { filter_condition = filter_condition && role_entity_id == entity_id }, ); payload .version .inspect(|ver| filter_condition = filter_condition && ver == &role.version); payload.status.inspect(|status| { filter_condition = filter_condition && status == &role.status }); filter_condition.then(|| role.to_owned()) }) .collect(); if let Some(Ok(limit)) = payload.limit.map(|val| val.try_into()) { filtered_roles = filtered_roles.into_iter().take(limit).collect(); } Ok(filtered_roles) } async fn list_user_roles_by_user_id_across_tenants( &self, user_id: &str, limit: Option<u32>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let user_roles = self.user_roles.lock().await; let filtered_roles: Vec<_> = user_roles .iter() .filter(|role| role.user_id == user_id) .cloned() .collect(); if let Some(Ok(limit)) = limit.map(|val| val.try_into()) { return Ok(filtered_roles.into_iter().take(limit).collect()); } Ok(filtered_roles) } async fn list_user_roles_by_org_id<'a>( &self, payload: ListUserRolesByOrgIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let user_roles = self.user_roles.lock().await; let mut filtered_roles = Vec::new(); for role in user_roles.iter() { let role_org_id = role .org_id .as_ref() .ok_or(report!(errors::StorageError::MockDbError))?; let mut filter_condition = role_org_id == payload.org_id; if let Some(user_id) = payload.user_id { filter_condition = filter_condition && user_id == &role.user_id } role.merchant_id.as_ref().zip(payload.merchant_id).inspect( |(role_merchant_id, merchant_id)| { filter_condition = filter_condition && role_merchant_id == merchant_id }, ); role.profile_id.as_ref().zip(payload.profile_id).inspect( |(role_profile_id, profile_id)| { filter_condition = filter_condition && role_profile_id == profile_id }, ); payload .version .inspect(|ver| filter_condition = filter_condition && ver == &role.version); if filter_condition { filtered_roles.push(role.clone()) } } Ok(filtered_roles) } }
crates/router/src/db/user_role.rs
router::src::db::user_role
4,409
true
// File: crates/router/src/db/locker_mock_up.rs // Module: router::src::db::locker_mock_up use error_stack::report; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait LockerMockUpInterface { async fn find_locker_by_card_id( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError>; async fn insert_locker_mock_up( &self, new: storage::LockerMockUpNew, ) -> CustomResult<storage::LockerMockUp, errors::StorageError>; async fn delete_locker_mock_up( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError>; } #[async_trait::async_trait] impl LockerMockUpInterface for Store { #[instrument(skip_all)] async fn find_locker_by_card_id( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::LockerMockUp::find_by_card_id(&conn, card_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_locker_mock_up( &self, new: storage::LockerMockUpNew, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_locker_mock_up( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::LockerMockUp::delete_by_card_id(&conn, card_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl LockerMockUpInterface for MockDb { async fn find_locker_by_card_id( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { self.lockers .lock() .await .iter() .find(|l| l.card_id == card_id) .cloned() .ok_or(errors::StorageError::MockDbError.into()) } async fn insert_locker_mock_up( &self, new: storage::LockerMockUpNew, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let mut locked_lockers = self.lockers.lock().await; if locked_lockers.iter().any(|l| l.card_id == new.card_id) { Err(errors::StorageError::MockDbError)?; } let created_locker = storage::LockerMockUp { card_id: new.card_id, external_id: new.external_id, card_fingerprint: new.card_fingerprint, card_global_fingerprint: new.card_global_fingerprint, merchant_id: new.merchant_id, card_number: new.card_number, card_exp_year: new.card_exp_year, card_exp_month: new.card_exp_month, name_on_card: new.name_on_card, nickname: None, customer_id: new.customer_id, duplicate: None, card_cvc: new.card_cvc, payment_method_id: new.payment_method_id, enc_card_data: new.enc_card_data, }; locked_lockers.push(created_locker.clone()); Ok(created_locker) } async fn delete_locker_mock_up( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let mut locked_lockers = self.lockers.lock().await; let position = locked_lockers .iter() .position(|l| l.card_id == card_id) .ok_or(errors::StorageError::MockDbError)?; Ok(locked_lockers.remove(position)) } } #[cfg(test)] mod tests { #[allow(clippy::unwrap_used)] mod mockdb_locker_mock_up_interface { use common_utils::{generate_customer_id_of_default_length, id_type}; use crate::{ db::{locker_mock_up::LockerMockUpInterface, MockDb}, types::storage, }; pub struct LockerMockUpIds { card_id: String, external_id: String, merchant_id: id_type::MerchantId, customer_id: id_type::CustomerId, } fn create_locker_mock_up_new(locker_ids: LockerMockUpIds) -> storage::LockerMockUpNew { storage::LockerMockUpNew { card_id: locker_ids.card_id, external_id: locker_ids.external_id, card_fingerprint: "card_fingerprint".into(), card_global_fingerprint: "card_global_fingerprint".into(), merchant_id: locker_ids.merchant_id, card_number: "1234123412341234".into(), card_exp_year: "2023".into(), card_exp_month: "06".into(), name_on_card: Some("name_on_card".into()), card_cvc: Some("123".into()), payment_method_id: Some("payment_method_id".into()), customer_id: Some(locker_ids.customer_id), nickname: Some("card_holder_nickname".into()), enc_card_data: Some("enc_card_data".into()), } } #[tokio::test] async fn find_locker_by_card_id() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_locker = mockdb .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { card_id: "card_1".into(), external_id: "external_1".into(), merchant_id: id_type::MerchantId::default(), customer_id: generate_customer_id_of_default_length(), })) .await .unwrap(); let _ = mockdb .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { card_id: "card_2".into(), external_id: "external_1".into(), merchant_id: id_type::MerchantId::default(), customer_id: generate_customer_id_of_default_length(), })) .await; let found_locker = mockdb.find_locker_by_card_id("card_1").await.unwrap(); assert_eq!(created_locker, found_locker) } #[tokio::test] async fn insert_locker_mock_up() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_locker = mockdb .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { card_id: "card_1".into(), external_id: "external_1".into(), merchant_id: id_type::MerchantId::default(), customer_id: generate_customer_id_of_default_length(), })) .await .unwrap(); let found_locker = mockdb .lockers .lock() .await .iter() .find(|l| l.card_id == "card_1") .cloned(); assert!(found_locker.is_some()); assert_eq!(created_locker, found_locker.unwrap()) } #[tokio::test] async fn delete_locker_mock_up() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_locker = mockdb .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { card_id: "card_1".into(), external_id: "external_1".into(), merchant_id: id_type::MerchantId::default(), customer_id: generate_customer_id_of_default_length(), })) .await .unwrap(); let deleted_locker = mockdb.delete_locker_mock_up("card_1").await.unwrap(); assert_eq!(created_locker, deleted_locker); let exist = mockdb .lockers .lock() .await .iter() .any(|l| l.card_id == "card_1"); assert!(!exist) } } }
crates/router/src/db/locker_mock_up.rs
router::src::db::locker_mock_up
1,973
true
// File: crates/router/src/db/refund.rs // Module: router::src::db::refund #[cfg(feature = "olap")] use std::collections::{HashMap, HashSet}; #[cfg(feature = "olap")] use common_utils::types::{ConnectorTransactionIdTrait, MinorUnit}; use diesel_models::{errors::DatabaseError, refund as diesel_refund}; use hyperswitch_domain_models::refunds; use super::MockDb; use crate::{ core::errors::{self, CustomResult}, types::storage::enums, }; #[cfg(feature = "olap")] const MAX_LIMIT: usize = 100; #[async_trait::async_trait] pub trait RefundInterface { #[cfg(feature = "v1")] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError>; #[cfg(feature = "v1")] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError>; #[cfg(feature = "v1")] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &common_utils::id_type::MerchantId, refund_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError>; #[cfg(feature = "v1")] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &common_utils::id_type::MerchantId, connector_refund_id: &str, connector: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError>; async fn update_refund( &self, this: diesel_refund::Refund, refund: diesel_refund::RefundUpdate, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError>; async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_transaction_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError>; #[cfg(feature = "v2")] async fn find_refund_by_id( &self, id: &common_utils::id_type::GlobalRefundId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError>; async fn insert_refund( &self, new: diesel_refund::RefundNew, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError>; #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError>; #[cfg(all(feature = "v2", feature = "olap"))] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: refunds::RefundListConstraints, storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError>; #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_refund_by_meta_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &common_utils::types::TimeRange, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError>; #[cfg(all(feature = "v1", feature = "olap"))] async fn get_refund_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, constraints: &common_utils::types::TimeRange, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError>; #[cfg(all(feature = "v1", feature = "olap"))] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError>; #[cfg(all(feature = "v2", feature = "olap"))] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: refunds::RefundListConstraints, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError>; } #[cfg(not(feature = "kv_store"))] mod storage { use error_stack::report; use hyperswitch_domain_models::refunds; use router_env::{instrument, tracing}; use super::RefundInterface; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, types::storage::{self as storage_types, enums}, }; #[async_trait::async_trait] impl RefundInterface for Store { #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_internal_reference_id_merchant_id( &conn, internal_reference_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_refund( &self, new: diesel_refund::RefundNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_transaction_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_merchant_id_connector_transaction_id( &conn, merchant_id, connector_transaction_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v2")] async fn find_refund_by_id( &self, id: &common_utils::id_type::GlobalRefundId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_global_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_refund( &self, this: diesel_refund::Refund, refund: diesel_refund::RefundUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update(&conn, refund) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_refund( &self, this: diesel_refund::Refund, refund: diesel_refund::RefundUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update_with_id(&conn, refund) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &common_utils::id_type::MerchantId, refund_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_merchant_id_refund_id(&conn, merchant_id, refund_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &common_utils::id_type::MerchantId, connector_refund_id: &str, connector: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_merchant_id_connector_refund_id_connector( &conn, merchant_id, connector_refund_id, connector, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints( &conn, merchant_id, refund_details, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints( &conn, merchant_id, refund_details, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_refund_by_meta_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &api_models::payments::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_meta_constraints( &conn, merchant_id, refund_details, ) .await .map_err(|error|report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_refund_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &api_models::payments::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id,profile_id_list, time_range) .await .map_err(|error|report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refunds_count( &conn, merchant_id, refund_details, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refunds_count( &conn, merchant_id, refund_details, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } } #[cfg(feature = "kv_store")] mod storage { use common_utils::{ ext_traits::Encode, fallback_reverse_lookup_not_found, types::ConnectorTransactionIdTrait, }; use diesel_models::refund as diesel_refund; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::refunds; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::{ decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey, }; use super::RefundInterface; use crate::{ connection, core::errors::{self, utils::RedisErrorExt, CustomResult}, db::reverse_lookup::ReverseLookupInterface, services::Store, types::storage::{self as storage_types, enums, kv}, utils::db_utils, }; #[async_trait::async_trait] impl RefundInterface for Store { #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_internal_reference_id_merchant_id( &conn, internal_reference_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let lookup_id = format!( "ref_inter_ref_{}_{internal_reference_id}", merchant_id.get_string_repr() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_refund::Refund>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, database_call, )) .await } } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn insert_refund( &self, new: diesel_refund::RefundNew, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } enums::MerchantStorageScheme::RedisKv => { let merchant_id = new.merchant_id.clone(); let payment_id = new.payment_id.clone(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, }; let key_str = key.to_string(); // TODO: need to add an application generated payment attempt id to distinguish between multiple attempts for the same payment id // Check for database presence as well Maybe use a read replica here ? let created_refund = diesel_refund::Refund { refund_id: new.refund_id.clone(), merchant_id: new.merchant_id.clone(), attempt_id: new.attempt_id.clone(), internal_reference_id: new.internal_reference_id.clone(), payment_id: new.payment_id.clone(), connector_transaction_id: new.connector_transaction_id.clone(), connector: new.connector.clone(), connector_refund_id: new.connector_refund_id.clone(), external_reference_id: new.external_reference_id.clone(), refund_type: new.refund_type, total_amount: new.total_amount, currency: new.currency, refund_amount: new.refund_amount, refund_status: new.refund_status, sent_to_gateway: new.sent_to_gateway, refund_error_message: None, refund_error_code: None, metadata: new.metadata.clone(), refund_arn: new.refund_arn.clone(), created_at: new.created_at, modified_at: new.created_at, description: new.description.clone(), refund_reason: new.refund_reason.clone(), profile_id: new.profile_id.clone(), updated_by: new.updated_by.clone(), merchant_connector_id: new.merchant_connector_id.clone(), charges: new.charges.clone(), split_refunds: new.split_refunds.clone(), organization_id: new.organization_id.clone(), unified_code: None, unified_message: None, processor_refund_data: new.processor_refund_data.clone(), processor_transaction_data: new.processor_transaction_data.clone(), issuer_error_code: None, issuer_error_message: None, // Below fields are deprecated. Please add any new fields above this line. connector_refund_data: None, connector_transaction_data: None, }; let field = format!( "pa_{}_ref_{}", &created_refund.attempt_id, &created_refund.refund_id ); let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::Refund(new)), }, }; let mut reverse_lookups = vec![ storage_types::ReverseLookupNew { sk_id: field.clone(), lookup_id: format!( "ref_ref_id_{}_{}", created_refund.merchant_id.get_string_repr(), created_refund.refund_id ), pk_id: key_str.clone(), source: "refund".to_string(), updated_by: storage_scheme.to_string(), }, // [#492]: A discussion is required on whether this is required? storage_types::ReverseLookupNew { sk_id: field.clone(), lookup_id: format!( "ref_inter_ref_{}_{}", created_refund.merchant_id.get_string_repr(), created_refund.internal_reference_id ), pk_id: key_str.clone(), source: "refund".to_string(), updated_by: storage_scheme.to_string(), }, ]; if let Some(connector_refund_id) = created_refund.to_owned().get_optional_connector_refund_id() { reverse_lookups.push(storage_types::ReverseLookupNew { sk_id: field.clone(), lookup_id: format!( "ref_connector_{}_{}_{}", created_refund.merchant_id.get_string_repr(), connector_refund_id, created_refund.connector ), pk_id: key_str.clone(), source: "refund".to_string(), updated_by: storage_scheme.to_string(), }) }; let rev_look = reverse_lookups .into_iter() .map(|rev| self.insert_reverse_lookup(rev, storage_scheme)); futures::future::try_join_all(rev_look).await?; match Box::pin(kv_wrapper::<diesel_refund::Refund, _, _>( self, KvOperation::<diesel_refund::Refund>::HSetNx( &field, &created_refund, redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "refund", key: Some(created_refund.refund_id), } .into()), Ok(HsetnxReply::KeySet) => Ok(created_refund), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn insert_refund( &self, new: diesel_refund::RefundNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_transaction_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_merchant_id_connector_transaction_id( &conn, merchant_id, connector_transaction_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let lookup_id = format!( "pa_conn_trans_{}_{connector_transaction_id}", merchant_id.get_string_repr() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; let pattern = db_utils::generate_hscan_pattern_for_refund(&lookup.sk_id); Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_refund::Refund>::Scan(&pattern), key, )) .await? .try_into_scan() }, database_call, )) .await } } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_transaction_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_merchant_id_connector_transaction_id( &conn, merchant_id, connector_transaction_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_refund( &self, this: diesel_refund::Refund, refund: diesel_refund::RefundUpdate, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let merchant_id = this.merchant_id.clone(); let payment_id = this.payment_id.clone(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, }; let field = format!("pa_{}_ref_{}", &this.attempt_id, &this.refund_id); let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>( self, storage_scheme, Op::Update(key.clone(), &field, Some(&this.updated_by)), )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => { let conn = connection::pg_connection_write(self).await?; this.update(&conn, refund) .await .map_err(|error| report!(errors::StorageError::from(error))) } enums::MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let updated_refund = refund.clone().apply_changeset(this.clone()); let redis_value = updated_refund .encode_to_string_of_json() .change_context(errors::StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::RefundUpdate(Box::new( kv::RefundUpdateMems { orig: this, update_data: refund, }, ))), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::Hset::<diesel_refund::Refund>( (&field, redis_value), redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(updated_refund) } } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_refund( &self, this: diesel_refund::Refund, refund: diesel_refund::RefundUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update_with_id(&conn, refund) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &common_utils::id_type::MerchantId, refund_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_merchant_id_refund_id(&conn, merchant_id, refund_id) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let lookup_id = format!("ref_ref_id_{}_{refund_id}", merchant_id.get_string_repr()); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_refund::Refund>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, database_call, )) .await } } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &common_utils::id_type::MerchantId, connector_refund_id: &str, connector: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_merchant_id_connector_refund_id_connector( &conn, merchant_id, connector_refund_id, connector, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let lookup_id = format!( "ref_connector_{}_{connector_refund_id}_{connector}", merchant_id.get_string_repr() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_refund::Refund>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, database_call, )) .await } } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_payment_id_merchant_id( &conn, payment_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPaymentId { merchant_id, payment_id, }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_refund::Refund>::Scan("pa_*_ref_*"), key, )) .await? .try_into_scan() }, database_call, )) .await } } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_refund_by_id( &self, id: &common_utils::id_type::GlobalRefundId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_global_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints( &conn, merchant_id, refund_details, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints( &conn, merchant_id, refund_details, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_refund_by_meta_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_meta_constraints(&conn, merchant_id, refund_details) .await .map_err(|error|report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_refund_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, constraints: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id,profile_id_list, constraints) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refunds_count( &conn, merchant_id, refund_details, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refunds_count( &conn, merchant_id, refund_details, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } } #[async_trait::async_trait] impl RefundInterface for MockDb { #[cfg(feature = "v1")] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let refunds = self.refunds.lock().await; refunds .iter() .find(|refund| { refund.merchant_id == *merchant_id && refund.internal_reference_id == internal_reference_id }) .cloned() .ok_or_else(|| { errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() }) } #[cfg(feature = "v1")] async fn insert_refund( &self, new: diesel_refund::RefundNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let mut refunds = self.refunds.lock().await; let current_time = common_utils::date_time::now(); let refund = diesel_refund::Refund { internal_reference_id: new.internal_reference_id, refund_id: new.refund_id, payment_id: new.payment_id, merchant_id: new.merchant_id, attempt_id: new.attempt_id, connector_transaction_id: new.connector_transaction_id, connector: new.connector, connector_refund_id: new.connector_refund_id, external_reference_id: new.external_reference_id, refund_type: new.refund_type, total_amount: new.total_amount, currency: new.currency, refund_amount: new.refund_amount, refund_status: new.refund_status, sent_to_gateway: new.sent_to_gateway, refund_error_message: None, refund_error_code: None, metadata: new.metadata, refund_arn: new.refund_arn.clone(), created_at: new.created_at, modified_at: current_time, description: new.description, refund_reason: new.refund_reason.clone(), profile_id: new.profile_id, updated_by: new.updated_by, merchant_connector_id: new.merchant_connector_id, charges: new.charges, split_refunds: new.split_refunds, organization_id: new.organization_id, unified_code: None, unified_message: None, processor_refund_data: new.processor_refund_data.clone(), processor_transaction_data: new.processor_transaction_data.clone(), issuer_error_code: None, issuer_error_message: None, // Below fields are deprecated. Please add any new fields above this line. connector_refund_data: None, connector_transaction_data: None, }; refunds.push(refund.clone()); Ok(refund) } #[cfg(feature = "v2")] async fn insert_refund( &self, new: diesel_refund::RefundNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let mut refunds = self.refunds.lock().await; let current_time = common_utils::date_time::now(); let refund = diesel_refund::Refund { id: new.id, merchant_reference_id: new.merchant_reference_id, payment_id: new.payment_id, merchant_id: new.merchant_id, attempt_id: new.attempt_id, connector_transaction_id: new.connector_transaction_id, connector: new.connector, connector_refund_id: new.connector_refund_id, external_reference_id: new.external_reference_id, refund_type: new.refund_type, total_amount: new.total_amount, currency: new.currency, refund_amount: new.refund_amount, refund_status: new.refund_status, sent_to_gateway: new.sent_to_gateway, refund_error_message: None, refund_error_code: None, metadata: new.metadata, refund_arn: new.refund_arn.clone(), created_at: new.created_at, modified_at: current_time, description: new.description, refund_reason: new.refund_reason.clone(), profile_id: new.profile_id, updated_by: new.updated_by, connector_id: new.connector_id, charges: new.charges, split_refunds: new.split_refunds, organization_id: new.organization_id, unified_code: None, unified_message: None, processor_refund_data: new.processor_refund_data.clone(), processor_transaction_data: new.processor_transaction_data.clone(), }; refunds.push(refund.clone()); Ok(refund) } async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_transaction_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { let refunds = self.refunds.lock().await; Ok(refunds .iter() .take_while(|refund| { refund.merchant_id == *merchant_id && refund.get_connector_transaction_id() == connector_transaction_id }) .cloned() .collect::<Vec<_>>()) } #[cfg(feature = "v1")] async fn update_refund( &self, this: diesel_refund::Refund, refund: diesel_refund::RefundUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { self.refunds .lock() .await .iter_mut() .find(|refund| this.refund_id == refund.refund_id) .map(|r| { let refund_updated = diesel_refund::RefundUpdateInternal::from(refund).create_refund(r.clone()); *r = refund_updated.clone(); refund_updated }) .ok_or_else(|| { errors::StorageError::ValueNotFound("cannot find refund to update".to_string()) .into() }) } #[cfg(feature = "v2")] async fn update_refund( &self, this: diesel_refund::Refund, refund: diesel_refund::RefundUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { self.refunds .lock() .await .iter_mut() .find(|refund| this.merchant_reference_id == refund.merchant_reference_id) .map(|r| { let refund_updated = diesel_refund::RefundUpdateInternal::from(refund).create_refund(r.clone()); *r = refund_updated.clone(); refund_updated }) .ok_or_else(|| { errors::StorageError::ValueNotFound("cannot find refund to update".to_string()) .into() }) } #[cfg(feature = "v1")] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &common_utils::id_type::MerchantId, refund_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let refunds = self.refunds.lock().await; refunds .iter() .find(|refund| refund.merchant_id == *merchant_id && refund.refund_id == refund_id) .cloned() .ok_or_else(|| { errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() }) } #[cfg(feature = "v1")] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &common_utils::id_type::MerchantId, connector_refund_id: &str, connector: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let refunds = self.refunds.lock().await; refunds .iter() .find(|refund| { refund.merchant_id == *merchant_id && refund .get_optional_connector_refund_id() .map(|refund_id| refund_id.as_str()) == Some(connector_refund_id) && refund.connector == connector }) .cloned() .ok_or_else(|| { errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() }) } #[cfg(feature = "v1")] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { let refunds = self.refunds.lock().await; Ok(refunds .iter() .filter(|refund| refund.merchant_id == *merchant_id && refund.payment_id == *payment_id) .cloned() .collect::<Vec<_>>()) } #[cfg(feature = "v2")] async fn find_refund_by_id( &self, id: &common_utils::id_type::GlobalRefundId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let refunds = self.refunds.lock().await; refunds .iter() .find(|refund| refund.id == *id) .cloned() .ok_or_else(|| { errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() }) } #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { let mut unique_connectors = HashSet::new(); let mut unique_merchant_connector_ids = HashSet::new(); let mut unique_currencies = HashSet::new(); let mut unique_statuses = HashSet::new(); let mut unique_profile_ids = HashSet::new(); // Fill the hash sets with data from refund_details if let Some(connectors) = &refund_details.connector { connectors.iter().for_each(|connector| { unique_connectors.insert(connector); }); } if let Some(merchant_connector_ids) = &refund_details.merchant_connector_id { merchant_connector_ids .iter() .for_each(|unique_merchant_connector_id| { unique_merchant_connector_ids.insert(unique_merchant_connector_id); }); } if let Some(currencies) = &refund_details.currency { currencies.iter().for_each(|currency| { unique_currencies.insert(currency); }); } if let Some(refund_statuses) = &refund_details.refund_status { refund_statuses.iter().for_each(|refund_status| { unique_statuses.insert(refund_status); }); } if let Some(profile_id_list) = &refund_details.profile_id { unique_profile_ids = profile_id_list.iter().collect(); } let refunds = self.refunds.lock().await; let filtered_refunds = refunds .iter() .filter(|refund| refund.merchant_id == *merchant_id) .filter(|refund| { refund_details .payment_id .clone() .is_none_or(|id| id == refund.payment_id) }) .filter(|refund| { refund_details .refund_id .clone() .is_none_or(|id| id == refund.refund_id) }) .filter(|refund| { refund.profile_id.as_ref().is_some_and(|profile_id| { unique_profile_ids.is_empty() || unique_profile_ids.contains(profile_id) }) }) .filter(|refund| { refund.created_at >= refund_details.time_range.map_or( common_utils::date_time::now() - time::Duration::days(60), |range| range.start_time, ) && refund.created_at <= refund_details .time_range .map_or(common_utils::date_time::now(), |range| { range.end_time.unwrap_or_else(common_utils::date_time::now) }) }) .filter(|refund| { refund_details.amount_filter.as_ref().is_none_or(|amount| { refund.refund_amount >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) && refund.refund_amount <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) }) }) .filter(|refund| { unique_connectors.is_empty() || unique_connectors.contains(&refund.connector) }) .filter(|refund| { unique_merchant_connector_ids.is_empty() || refund .merchant_connector_id .as_ref() .is_some_and(|id| unique_merchant_connector_ids.contains(id)) }) .filter(|refund| { unique_currencies.is_empty() || unique_currencies.contains(&refund.currency) }) .filter(|refund| { unique_statuses.is_empty() || unique_statuses.contains(&refund.refund_status) }) .skip(usize::try_from(offset).unwrap_or_default()) .take(usize::try_from(limit).unwrap_or(MAX_LIMIT)) .cloned() .collect::<Vec<_>>(); Ok(filtered_refunds) } #[cfg(all(feature = "v2", feature = "olap"))] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { let mut unique_connectors = HashSet::new(); let mut unique_connector_ids = HashSet::new(); let mut unique_currencies = HashSet::new(); let mut unique_statuses = HashSet::new(); // Fill the hash sets with data from refund_details if let Some(connectors) = &refund_details.connector { connectors.iter().for_each(|connector| { unique_connectors.insert(connector); }); } if let Some(connector_id_list) = &refund_details.connector_id_list { connector_id_list.iter().for_each(|unique_connector_id| { unique_connector_ids.insert(unique_connector_id); }); } if let Some(currencies) = &refund_details.currency { currencies.iter().for_each(|currency| { unique_currencies.insert(currency); }); } if let Some(refund_statuses) = &refund_details.refund_status { refund_statuses.iter().for_each(|refund_status| { unique_statuses.insert(refund_status); }); } let refunds = self.refunds.lock().await; let filtered_refunds = refunds .iter() .filter(|refund| refund.merchant_id == *merchant_id) .filter(|refund| { refund_details .payment_id .clone() .is_none_or(|id| id == refund.payment_id) }) .filter(|refund| { refund_details .refund_id .clone() .is_none_or(|id| id == refund.id) }) .filter(|refund| { refund .profile_id .as_ref() .is_some_and(|profile_id| profile_id == &refund_details.profile_id) }) .filter(|refund| { refund.created_at >= refund_details.time_range.map_or( common_utils::date_time::now() - time::Duration::days(60), |range| range.start_time, ) && refund.created_at <= refund_details .time_range .map_or(common_utils::date_time::now(), |range| { range.end_time.unwrap_or_else(common_utils::date_time::now) }) }) .filter(|refund| { refund_details.amount_filter.as_ref().is_none_or(|amount| { refund.refund_amount >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) && refund.refund_amount <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) }) }) .filter(|refund| { unique_connectors.is_empty() || unique_connectors.contains(&refund.connector) }) .filter(|refund| { unique_connector_ids.is_empty() || refund .connector_id .as_ref() .is_some_and(|id| unique_connector_ids.contains(id)) }) .filter(|refund| { unique_currencies.is_empty() || unique_currencies.contains(&refund.currency) }) .filter(|refund| { unique_statuses.is_empty() || unique_statuses.contains(&refund.refund_status) }) .skip(usize::try_from(offset).unwrap_or_default()) .take(usize::try_from(limit).unwrap_or(MAX_LIMIT)) .cloned() .collect::<Vec<_>>(); Ok(filtered_refunds) } #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_refund_by_meta_constraints( &self, _merchant_id: &common_utils::id_type::MerchantId, refund_details: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> { let refunds = self.refunds.lock().await; let start_time = refund_details.start_time; let end_time = refund_details .end_time .unwrap_or_else(common_utils::date_time::now); let filtered_refunds = refunds .iter() .filter(|refund| refund.created_at >= start_time && refund.created_at <= end_time) .cloned() .collect::<Vec<diesel_models::refund::Refund>>(); let mut refund_meta_data = api_models::refunds::RefundListMetaData { connector: vec![], currency: vec![], refund_status: vec![], }; let mut unique_connectors = HashSet::new(); let mut unique_currencies = HashSet::new(); let mut unique_statuses = HashSet::new(); for refund in filtered_refunds.into_iter() { unique_connectors.insert(refund.connector); let currency: api_models::enums::Currency = refund.currency; unique_currencies.insert(currency); let status: api_models::enums::RefundStatus = refund.refund_status; unique_statuses.insert(status); } refund_meta_data.connector = unique_connectors.into_iter().collect(); refund_meta_data.currency = unique_currencies.into_iter().collect(); refund_meta_data.refund_status = unique_statuses.into_iter().collect(); Ok(refund_meta_data) } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_refund_status_with_count( &self, _merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(api_models::enums::RefundStatus, i64)>, errors::StorageError> { let refunds = self.refunds.lock().await; let start_time = time_range.start_time; let end_time = time_range .end_time .unwrap_or_else(common_utils::date_time::now); let filtered_refunds = refunds .iter() .filter(|refund| { refund.created_at >= start_time && refund.created_at <= end_time && profile_id_list .as_ref() .zip(refund.profile_id.as_ref()) .map(|(received_profile_list, received_profile_id)| { received_profile_list.contains(received_profile_id) }) .unwrap_or(true) }) .cloned() .collect::<Vec<diesel_models::refund::Refund>>(); let mut refund_status_counts: HashMap<api_models::enums::RefundStatus, i64> = HashMap::new(); for refund in filtered_refunds { *refund_status_counts .entry(refund.refund_status) .or_insert(0) += 1; } let result: Vec<(api_models::enums::RefundStatus, i64)> = refund_status_counts.into_iter().collect(); Ok(result) } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let mut unique_connectors = HashSet::new(); let mut unique_merchant_connector_ids = HashSet::new(); let mut unique_currencies = HashSet::new(); let mut unique_statuses = HashSet::new(); let mut unique_profile_ids = HashSet::new(); // Fill the hash sets with data from refund_details if let Some(connectors) = &refund_details.connector { connectors.iter().for_each(|connector| { unique_connectors.insert(connector); }); } if let Some(merchant_connector_ids) = &refund_details.merchant_connector_id { merchant_connector_ids .iter() .for_each(|unique_merchant_connector_id| { unique_merchant_connector_ids.insert(unique_merchant_connector_id); }); } if let Some(currencies) = &refund_details.currency { currencies.iter().for_each(|currency| { unique_currencies.insert(currency); }); } if let Some(refund_statuses) = &refund_details.refund_status { refund_statuses.iter().for_each(|refund_status| { unique_statuses.insert(refund_status); }); } if let Some(profile_id_list) = &refund_details.profile_id { unique_profile_ids = profile_id_list.iter().collect(); } let refunds = self.refunds.lock().await; let filtered_refunds = refunds .iter() .filter(|refund| refund.merchant_id == *merchant_id) .filter(|refund| { refund_details .payment_id .clone() .is_none_or(|id| id == refund.payment_id) }) .filter(|refund| { refund_details .refund_id .clone() .is_none_or(|id| id == refund.refund_id) }) .filter(|refund| { refund.profile_id.as_ref().is_some_and(|profile_id| { unique_profile_ids.is_empty() || unique_profile_ids.contains(profile_id) }) }) .filter(|refund| { refund.created_at >= refund_details.time_range.map_or( common_utils::date_time::now() - time::Duration::days(60), |range| range.start_time, ) && refund.created_at <= refund_details .time_range .map_or(common_utils::date_time::now(), |range| { range.end_time.unwrap_or_else(common_utils::date_time::now) }) }) .filter(|refund| { refund_details.amount_filter.as_ref().is_none_or(|amount| { refund.refund_amount >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) && refund.refund_amount <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) }) }) .filter(|refund| { unique_connectors.is_empty() || unique_connectors.contains(&refund.connector) }) .filter(|refund| { unique_merchant_connector_ids.is_empty() || refund .merchant_connector_id .as_ref() .is_some_and(|id| unique_merchant_connector_ids.contains(id)) }) .filter(|refund| { unique_currencies.is_empty() || unique_currencies.contains(&refund.currency) }) .filter(|refund| { unique_statuses.is_empty() || unique_statuses.contains(&refund.refund_status) }) .cloned() .collect::<Vec<_>>(); let filtered_refunds_count = filtered_refunds.len().try_into().unwrap_or_default(); Ok(filtered_refunds_count) } #[cfg(all(feature = "v2", feature = "olap"))] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let mut unique_connectors = HashSet::new(); let mut unique_connector_ids = HashSet::new(); let mut unique_currencies = HashSet::new(); let mut unique_statuses = HashSet::new(); // Fill the hash sets with data from refund_details if let Some(connectors) = &refund_details.connector { connectors.iter().for_each(|connector| { unique_connectors.insert(connector); }); } if let Some(connector_id_list) = &refund_details.connector_id_list { connector_id_list.iter().for_each(|unique_connector_id| { unique_connector_ids.insert(unique_connector_id); }); } if let Some(currencies) = &refund_details.currency { currencies.iter().for_each(|currency| { unique_currencies.insert(currency); }); } if let Some(refund_statuses) = &refund_details.refund_status { refund_statuses.iter().for_each(|refund_status| { unique_statuses.insert(refund_status); }); } let refunds = self.refunds.lock().await; let filtered_refunds = refunds .iter() .filter(|refund| refund.merchant_id == *merchant_id) .filter(|refund| { refund_details .payment_id .clone() .is_none_or(|id| id == refund.payment_id) }) .filter(|refund| { refund_details .refund_id .clone() .is_none_or(|id| id == refund.id) }) .filter(|refund| { refund .profile_id .as_ref() .is_some_and(|profile_id| profile_id == &refund_details.profile_id) }) .filter(|refund| { refund.created_at >= refund_details.time_range.map_or( common_utils::date_time::now() - time::Duration::days(60), |range| range.start_time, ) && refund.created_at <= refund_details .time_range .map_or(common_utils::date_time::now(), |range| { range.end_time.unwrap_or_else(common_utils::date_time::now) }) }) .filter(|refund| { refund_details.amount_filter.as_ref().is_none_or(|amount| { refund.refund_amount >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) && refund.refund_amount <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) }) }) .filter(|refund| { unique_connectors.is_empty() || unique_connectors.contains(&refund.connector) }) .filter(|refund| { unique_connector_ids.is_empty() || refund .connector_id .as_ref() .is_some_and(|id| unique_connector_ids.contains(id)) }) .filter(|refund| { unique_currencies.is_empty() || unique_currencies.contains(&refund.currency) }) .filter(|refund| { unique_statuses.is_empty() || unique_statuses.contains(&refund.refund_status) }) .cloned() .collect::<Vec<_>>(); let filtered_refunds_count = filtered_refunds.len().try_into().unwrap_or_default(); Ok(filtered_refunds_count) } }
crates/router/src/db/refund.rs
router::src::db::refund
15,268
true
// File: crates/router/src/db/business_profile.rs // Module: router::src::db::business_profile pub use hyperswitch_domain_models::{ business_profile::{self, ProfileInterface}, errors::api_error_response, };
crates/router/src/db/business_profile.rs
router::src::db::business_profile
47
true
// File: crates/router/src/db/payment_link.rs // Module: router::src::db::payment_link use error_stack::report; use router_env::{instrument, tracing}; use crate::{ connection, core::errors::{self, CustomResult}, db::MockDb, services::Store, types::storage::{self, PaymentLinkDbExt}, }; #[async_trait::async_trait] pub trait PaymentLinkInterface { async fn find_payment_link_by_payment_link_id( &self, payment_link_id: &str, ) -> CustomResult<storage::PaymentLink, errors::StorageError>; async fn insert_payment_link( &self, _payment_link: storage::PaymentLinkNew, ) -> CustomResult<storage::PaymentLink, errors::StorageError>; async fn list_payment_link_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_link_constraints: api_models::payments::PaymentLinkListConstraints, ) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError>; } #[async_trait::async_trait] impl PaymentLinkInterface for Store { #[instrument(skip_all)] async fn find_payment_link_by_payment_link_id( &self, payment_link_id: &str, ) -> CustomResult<storage::PaymentLink, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::PaymentLink::find_link_by_payment_link_id(&conn, payment_link_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_payment_link( &self, payment_link_config: storage::PaymentLinkNew, ) -> CustomResult<storage::PaymentLink, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; payment_link_config .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_payment_link_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_link_constraints: api_models::payments::PaymentLinkListConstraints, ) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::PaymentLink::filter_by_constraints(&conn, merchant_id, payment_link_constraints) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl PaymentLinkInterface for MockDb { async fn insert_payment_link( &self, _payment_link: storage::PaymentLinkNew, ) -> CustomResult<storage::PaymentLink, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn find_payment_link_by_payment_link_id( &self, _payment_link_id: &str, ) -> CustomResult<storage::PaymentLink, errors::StorageError> { // TODO: Implement function for `MockDb`x Err(errors::StorageError::MockDbError)? } async fn list_payment_link_by_merchant_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _payment_link_constraints: api_models::payments::PaymentLinkListConstraints, ) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> { // TODO: Implement function for `MockDb`x Err(errors::StorageError::MockDbError)? } }
crates/router/src/db/payment_link.rs
router::src::db::payment_link
796
true
// File: crates/router/src/db/generic_link.rs // Module: router::src::db::generic_link use error_stack::report; use router_env::{instrument, tracing}; use crate::{ connection, core::errors::{self, CustomResult}, db::MockDb, services::Store, types::storage, }; #[async_trait::async_trait] pub trait GenericLinkInterface { async fn find_generic_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::GenericLinkState, errors::StorageError>; async fn find_pm_collect_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError>; async fn find_payout_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::PayoutLink, errors::StorageError>; async fn insert_generic_link( &self, _generic_link: storage::GenericLinkNew, ) -> CustomResult<storage::GenericLinkState, errors::StorageError>; async fn insert_pm_collect_link( &self, _pm_collect_link: storage::GenericLinkNew, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError>; async fn insert_payout_link( &self, _payout_link: storage::GenericLinkNew, ) -> CustomResult<storage::PayoutLink, errors::StorageError>; async fn update_payout_link( &self, payout_link: storage::PayoutLink, payout_link_update: storage::PayoutLinkUpdate, ) -> CustomResult<storage::PayoutLink, errors::StorageError>; } #[async_trait::async_trait] impl GenericLinkInterface for Store { #[instrument(skip_all)] async fn find_generic_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::GenericLinkState, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::GenericLink::find_generic_link_by_link_id(&conn, link_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_pm_collect_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::GenericLink::find_pm_collect_link_by_link_id(&conn, link_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_payout_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::GenericLink::find_payout_link_by_link_id(&conn, link_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_generic_link( &self, generic_link: storage::GenericLinkNew, ) -> CustomResult<storage::GenericLinkState, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; generic_link .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_pm_collect_link( &self, pm_collect_link: storage::GenericLinkNew, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; pm_collect_link .insert_pm_collect_link(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_payout_link( &self, pm_collect_link: storage::GenericLinkNew, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; pm_collect_link .insert_payout_link(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_payout_link( &self, payout_link: storage::PayoutLink, payout_link_update: storage::PayoutLinkUpdate, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; payout_link .update_payout_link(&conn, payout_link_update) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl GenericLinkInterface for MockDb { async fn find_generic_link_by_link_id( &self, _generic_link_id: &str, ) -> CustomResult<storage::GenericLinkState, errors::StorageError> { // TODO: Implement function for `MockDb`x Err(errors::StorageError::MockDbError)? } async fn find_pm_collect_link_by_link_id( &self, _generic_link_id: &str, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> { // TODO: Implement function for `MockDb`x Err(errors::StorageError::MockDbError)? } async fn find_payout_link_by_link_id( &self, _generic_link_id: &str, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { // TODO: Implement function for `MockDb`x Err(errors::StorageError::MockDbError)? } async fn insert_generic_link( &self, _generic_link: storage::GenericLinkNew, ) -> CustomResult<storage::GenericLinkState, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn insert_pm_collect_link( &self, _pm_collect_link: storage::GenericLinkNew, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn insert_payout_link( &self, _pm_collect_link: storage::GenericLinkNew, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn update_payout_link( &self, _payout_link: storage::PayoutLink, _payout_link_update: storage::PayoutLinkUpdate, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } }
crates/router/src/db/generic_link.rs
router::src::db::generic_link
1,586
true
// File: crates/router/src/db/unified_translations.rs // Module: router::src::db::unified_translations use diesel_models::unified_translations as storage; use error_stack::report; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait UnifiedTranslationsInterface { async fn add_unfied_translation( &self, translation: storage::UnifiedTranslationsNew, ) -> CustomResult<storage::UnifiedTranslations, errors::StorageError>; async fn update_translation( &self, unified_code: String, unified_message: String, locale: String, data: storage::UnifiedTranslationsUpdate, ) -> CustomResult<storage::UnifiedTranslations, errors::StorageError>; async fn find_translation( &self, unified_code: String, unified_message: String, locale: String, ) -> CustomResult<String, errors::StorageError>; async fn delete_translation( &self, unified_code: String, unified_message: String, locale: String, ) -> CustomResult<bool, errors::StorageError>; } #[async_trait::async_trait] impl UnifiedTranslationsInterface for Store { async fn add_unfied_translation( &self, translation: storage::UnifiedTranslationsNew, ) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; translation .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn update_translation( &self, unified_code: String, unified_message: String, locale: String, data: storage::UnifiedTranslationsUpdate, ) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::UnifiedTranslations::update_by_unified_code_unified_message_locale( &conn, unified_code, unified_message, locale, data, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_translation( &self, unified_code: String, unified_message: String, locale: String, ) -> CustomResult<String, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let translations = storage::UnifiedTranslations::find_by_unified_code_unified_message_locale( &conn, unified_code, unified_message, locale, ) .await .map_err(|error| report!(errors::StorageError::from(error)))?; Ok(translations.translation) } async fn delete_translation( &self, unified_code: String, unified_message: String, locale: String, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::UnifiedTranslations::delete_by_unified_code_unified_message_locale( &conn, unified_code, unified_message, locale, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl UnifiedTranslationsInterface for MockDb { async fn add_unfied_translation( &self, _translation: storage::UnifiedTranslationsNew, ) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_translation( &self, _unified_code: String, _unified_message: String, _locale: String, ) -> CustomResult<String, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_translation( &self, _unified_code: String, _unified_message: String, _locale: String, _data: storage::UnifiedTranslationsUpdate, ) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn delete_translation( &self, _unified_code: String, _unified_message: String, _locale: String, ) -> CustomResult<bool, errors::StorageError> { Err(errors::StorageError::MockDbError)? } }
crates/router/src/db/unified_translations.rs
router::src::db::unified_translations
964
true
// File: crates/router/src/db/api_keys.rs // Module: router::src::db::api_keys use error_stack::report; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] use storage_impl::redis::cache::{self, CacheKind, ACCOUNTS_CACHE}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait ApiKeyInterface { async fn insert_api_key( &self, api_key: storage::ApiKeyNew, ) -> CustomResult<storage::ApiKey, errors::StorageError>; async fn update_api_key( &self, merchant_id: common_utils::id_type::MerchantId, key_id: common_utils::id_type::ApiKeyId, api_key: storage::ApiKeyUpdate, ) -> CustomResult<storage::ApiKey, errors::StorageError>; async fn revoke_api_key( &self, merchant_id: &common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<bool, errors::StorageError>; async fn find_api_key_by_merchant_id_key_id_optional( &self, merchant_id: &common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError>; async fn find_api_key_by_hash_optional( &self, hashed_api_key: storage::HashedApiKey, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError>; async fn list_api_keys_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, limit: Option<i64>, offset: Option<i64>, ) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError>; } #[async_trait::async_trait] impl ApiKeyInterface for Store { #[instrument(skip_all)] async fn insert_api_key( &self, api_key: storage::ApiKeyNew, ) -> CustomResult<storage::ApiKey, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; api_key .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_api_key( &self, merchant_id: common_utils::id_type::MerchantId, key_id: common_utils::id_type::ApiKeyId, api_key: storage::ApiKeyUpdate, ) -> CustomResult<storage::ApiKey, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let _merchant_id = merchant_id.clone(); let _key_id = key_id.clone(); let update_call = || async { storage::ApiKey::update_by_merchant_id_key_id(&conn, merchant_id, key_id, api_key) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { update_call().await } #[cfg(feature = "accounts_cache")] { use error_stack::report; // We need to fetch api_key here because the key that's saved in cache in HashedApiKey. // Used function from storage model to reuse the connection that made here instead of // creating new. let api_key = storage::ApiKey::find_optional_by_merchant_id_key_id( &conn, &_merchant_id, &_key_id, ) .await .map_err(|error| report!(errors::StorageError::from(error)))? .ok_or(report!(errors::StorageError::ValueNotFound(format!( "ApiKey of {} not found", _key_id.get_string_repr() ))))?; cache::publish_and_redact( self, CacheKind::Accounts(api_key.hashed_api_key.into_inner().into()), update_call, ) .await } } #[instrument(skip_all)] async fn revoke_api_key( &self, merchant_id: &common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let delete_call = || async { storage::ApiKey::revoke_by_merchant_id_key_id(&conn, merchant_id, key_id) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { delete_call().await } #[cfg(feature = "accounts_cache")] { use error_stack::report; // We need to fetch api_key here because the key that's saved in cache in HashedApiKey. // Used function from storage model to reuse the connection that made here instead of // creating new. let api_key = storage::ApiKey::find_optional_by_merchant_id_key_id(&conn, merchant_id, key_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? .ok_or(report!(errors::StorageError::ValueNotFound(format!( "ApiKey of {} not found", key_id.get_string_repr() ))))?; cache::publish_and_redact( self, CacheKind::Accounts(api_key.hashed_api_key.into_inner().into()), delete_call, ) .await } } #[instrument(skip_all)] async fn find_api_key_by_merchant_id_key_id_optional( &self, merchant_id: &common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::ApiKey::find_optional_by_merchant_id_key_id(&conn, merchant_id, key_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_api_key_by_hash_optional( &self, hashed_api_key: storage::HashedApiKey, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { let _hashed_api_key = hashed_api_key.clone(); let find_call = || async { let conn = connection::pg_connection_read(self).await?; storage::ApiKey::find_optional_by_hashed_api_key(&conn, hashed_api_key) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call().await } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, &_hashed_api_key.into_inner(), find_call, &ACCOUNTS_CACHE, ) .await } } #[instrument(skip_all)] async fn list_api_keys_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, limit: Option<i64>, offset: Option<i64>, ) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::ApiKey::find_by_merchant_id(&conn, merchant_id, limit, offset) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl ApiKeyInterface for MockDb { async fn insert_api_key( &self, api_key: storage::ApiKeyNew, ) -> CustomResult<storage::ApiKey, errors::StorageError> { let mut locked_api_keys = self.api_keys.lock().await; // don't allow duplicate key_ids, a those would be a unique constraint violation in the // real db as it is used as the primary key if locked_api_keys.iter().any(|k| k.key_id == api_key.key_id) { Err(errors::StorageError::MockDbError)?; } let stored_key = storage::ApiKey { key_id: api_key.key_id, merchant_id: api_key.merchant_id, name: api_key.name, description: api_key.description, hashed_api_key: api_key.hashed_api_key, prefix: api_key.prefix, created_at: api_key.created_at, expires_at: api_key.expires_at, last_used: api_key.last_used, }; locked_api_keys.push(stored_key.clone()); Ok(stored_key) } async fn update_api_key( &self, merchant_id: common_utils::id_type::MerchantId, key_id: common_utils::id_type::ApiKeyId, api_key: storage::ApiKeyUpdate, ) -> CustomResult<storage::ApiKey, errors::StorageError> { let mut locked_api_keys = self.api_keys.lock().await; // find a key with the given merchant_id and key_id and update, otherwise return an error let key_to_update = locked_api_keys .iter_mut() .find(|k| k.merchant_id == merchant_id && k.key_id == key_id) .ok_or(errors::StorageError::MockDbError)?; match api_key { storage::ApiKeyUpdate::Update { name, description, expires_at, last_used, } => { if let Some(name) = name { key_to_update.name = name; } // only update these fields if the value was Some(_) if description.is_some() { key_to_update.description = description; } if let Some(expires_at) = expires_at { key_to_update.expires_at = expires_at; } if last_used.is_some() { key_to_update.last_used = last_used } } storage::ApiKeyUpdate::LastUsedUpdate { last_used } => { key_to_update.last_used = Some(last_used); } } Ok(key_to_update.clone()) } async fn revoke_api_key( &self, merchant_id: &common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<bool, errors::StorageError> { let mut locked_api_keys = self.api_keys.lock().await; // find the key to remove, if it exists if let Some(pos) = locked_api_keys .iter() .position(|k| k.merchant_id == *merchant_id && k.key_id == *key_id) { // use `remove` instead of `swap_remove` so we have a consistent order, which might // matter to someone using limit/offset in `list_api_keys_by_merchant_id` locked_api_keys.remove(pos); Ok(true) } else { Ok(false) } } async fn find_api_key_by_merchant_id_key_id_optional( &self, merchant_id: &common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { Ok(self .api_keys .lock() .await .iter() .find(|k| k.merchant_id == *merchant_id && k.key_id == *key_id) .cloned()) } async fn find_api_key_by_hash_optional( &self, hashed_api_key: storage::HashedApiKey, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { Ok(self .api_keys .lock() .await .iter() .find(|k| k.hashed_api_key == hashed_api_key) .cloned()) } async fn list_api_keys_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, limit: Option<i64>, offset: Option<i64>, ) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> { // mimic the SQL limit/offset behavior let offset: usize = if let Some(offset) = offset { if offset < 0 { Err(errors::StorageError::MockDbError)?; } offset .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { 0 }; let limit: usize = if let Some(limit) = limit { if limit < 0 { Err(errors::StorageError::MockDbError)?; } limit .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { usize::MAX }; let keys_for_merchant_id: Vec<storage::ApiKey> = self .api_keys .lock() .await .iter() .filter(|k| k.merchant_id == *merchant_id) .skip(offset) .take(limit) .cloned() .collect(); Ok(keys_for_merchant_id) } } #[cfg(test)] mod tests { use std::borrow::Cow; use storage_impl::redis::{ cache::{self, CacheKey, CacheKind, ACCOUNTS_CACHE}, kv_store::RedisConnInterface, pub_sub::PubSubInterface, }; use time::macros::datetime; use crate::{ db::{api_keys::ApiKeyInterface, MockDb}, types::storage, }; #[allow(clippy::unwrap_used)] #[tokio::test] async fn test_mockdb_api_key_interface() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant1")).unwrap(); let key_id1 = common_utils::id_type::ApiKeyId::try_from(Cow::from("key_id1")).unwrap(); let key_id2 = common_utils::id_type::ApiKeyId::try_from(Cow::from("key_id2")).unwrap(); let non_existent_key_id = common_utils::id_type::ApiKeyId::try_from(Cow::from("does_not_exist")).unwrap(); let key1 = mockdb .insert_api_key(storage::ApiKeyNew { key_id: key_id1.clone(), merchant_id: merchant_id.clone(), name: "Key 1".into(), description: None, hashed_api_key: "hashed_key1".to_string().into(), prefix: "abc".into(), created_at: datetime!(2023-02-01 0:00), expires_at: Some(datetime!(2023-03-01 0:00)), last_used: None, }) .await .unwrap(); mockdb .insert_api_key(storage::ApiKeyNew { key_id: key_id2.clone(), merchant_id: merchant_id.clone(), name: "Key 2".into(), description: None, hashed_api_key: "hashed_key2".to_string().into(), prefix: "abc".into(), created_at: datetime!(2023-03-01 0:00), expires_at: None, last_used: None, }) .await .unwrap(); let found_key1 = mockdb .find_api_key_by_merchant_id_key_id_optional(&merchant_id, &key_id1) .await .unwrap() .unwrap(); assert_eq!(found_key1.key_id, key1.key_id); assert!(mockdb .find_api_key_by_merchant_id_key_id_optional(&merchant_id, &non_existent_key_id) .await .unwrap() .is_none()); mockdb .update_api_key( merchant_id.clone(), key_id1.clone(), storage::ApiKeyUpdate::LastUsedUpdate { last_used: datetime!(2023-02-04 1:11), }, ) .await .unwrap(); let updated_key1 = mockdb .find_api_key_by_merchant_id_key_id_optional(&merchant_id, &key_id1) .await .unwrap() .unwrap(); assert_eq!(updated_key1.last_used, Some(datetime!(2023-02-04 1:11))); assert_eq!( mockdb .list_api_keys_by_merchant_id(&merchant_id, None, None) .await .unwrap() .len(), 2 ); mockdb.revoke_api_key(&merchant_id, &key_id1).await.unwrap(); assert_eq!( mockdb .list_api_keys_by_merchant_id(&merchant_id, None, None) .await .unwrap() .len(), 1 ); } #[allow(clippy::unwrap_used)] #[tokio::test] async fn test_api_keys_cache() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("test_merchant")).unwrap(); #[allow(clippy::expect_used)] let db = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let redis_conn = db.get_redis_conn().unwrap(); redis_conn .subscribe("hyperswitch_invalidate") .await .unwrap(); let test_key = common_utils::id_type::ApiKeyId::try_from(Cow::from("test_ey")).unwrap(); let api = storage::ApiKeyNew { key_id: test_key.clone(), merchant_id: merchant_id.clone(), name: "My test key".into(), description: None, hashed_api_key: "a_hashed_key".to_string().into(), prefix: "pre".into(), created_at: datetime!(2023-06-01 0:00), expires_at: None, last_used: None, }; let api = db.insert_api_key(api).await.unwrap(); let hashed_api_key = api.hashed_api_key.clone(); let find_call = || async { db.find_api_key_by_hash_optional(hashed_api_key.clone()) .await }; let _: Option<storage::ApiKey> = cache::get_or_populate_in_memory( &db, &format!( "{}_{}", merchant_id.get_string_repr(), hashed_api_key.clone().into_inner() ), find_call, &ACCOUNTS_CACHE, ) .await .unwrap(); let delete_call = || async { db.revoke_api_key(&merchant_id, &api.key_id).await }; cache::publish_and_redact( &db, CacheKind::Accounts( format!( "{}_{}", merchant_id.get_string_repr(), hashed_api_key.clone().into_inner() ) .into(), ), delete_call, ) .await .unwrap(); assert!(ACCOUNTS_CACHE .get_val::<storage::ApiKey>(CacheKey { key: format!( "{}_{}", merchant_id.get_string_repr(), hashed_api_key.into_inner() ), prefix: String::default(), },) .await .is_none()) } }
crates/router/src/db/api_keys.rs
router::src::db::api_keys
4,278
true
// File: crates/router/src/db/dashboard_metadata.rs // Module: router::src::db::dashboard_metadata use common_utils::id_type; use diesel_models::{enums, user::dashboard_metadata as storage}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use storage_impl::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait DashboardMetadataInterface { async fn insert_metadata( &self, metadata: storage::DashboardMetadataNew, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError>; async fn update_metadata( &self, user_id: Option<String>, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_key: enums::DashboardMetadata, dashboard_metadata_update: storage::DashboardMetadataUpdate, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError>; async fn find_user_scoped_dashboard_metadata( &self, user_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>; async fn find_merchant_scoped_dashboard_metadata( &self, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>; async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( &self, user_id: &str, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError>; async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &self, user_id: &str, merchant_id: &id_type::MerchantId, data_key: enums::DashboardMetadata, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError>; } #[async_trait::async_trait] impl DashboardMetadataInterface for Store { #[instrument(skip_all)] async fn insert_metadata( &self, metadata: storage::DashboardMetadataNew, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; metadata .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_metadata( &self, user_id: Option<String>, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_key: enums::DashboardMetadata, dashboard_metadata_update: storage::DashboardMetadataUpdate, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; storage::DashboardMetadata::update( &conn, user_id, merchant_id, org_id, data_key, dashboard_metadata_update, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_user_scoped_dashboard_metadata( &self, user_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; storage::DashboardMetadata::find_user_scoped_dashboard_metadata( &conn, user_id.to_owned(), merchant_id.to_owned(), org_id.to_owned(), data_keys, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_merchant_scoped_dashboard_metadata( &self, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; storage::DashboardMetadata::find_merchant_scoped_dashboard_metadata( &conn, merchant_id.to_owned(), org_id.to_owned(), data_keys, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( &self, user_id: &str, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; storage::DashboardMetadata::delete_all_user_scoped_dashboard_metadata_by_merchant_id( &conn, user_id.to_owned(), merchant_id.to_owned(), ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &self, user_id: &str, merchant_id: &id_type::MerchantId, data_key: enums::DashboardMetadata, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; storage::DashboardMetadata::delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &conn, user_id.to_owned(), merchant_id.to_owned(), data_key, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl DashboardMetadataInterface for MockDb { async fn insert_metadata( &self, metadata: storage::DashboardMetadataNew, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let mut dashboard_metadata = self.dashboard_metadata.lock().await; if dashboard_metadata.iter().any(|metadata_inner| { metadata_inner.user_id == metadata.user_id && metadata_inner.merchant_id == metadata.merchant_id && metadata_inner.org_id == metadata.org_id && metadata_inner.data_key == metadata.data_key }) { Err(errors::StorageError::DuplicateValue { entity: "user_id, merchant_id, org_id and data_key", key: None, })? } let metadata_new = storage::DashboardMetadata { id: i32::try_from(dashboard_metadata.len()) .change_context(errors::StorageError::MockDbError)?, user_id: metadata.user_id, merchant_id: metadata.merchant_id, org_id: metadata.org_id, data_key: metadata.data_key, data_value: metadata.data_value, created_by: metadata.created_by, created_at: metadata.created_at, last_modified_by: metadata.last_modified_by, last_modified_at: metadata.last_modified_at, }; dashboard_metadata.push(metadata_new.clone()); Ok(metadata_new) } async fn update_metadata( &self, user_id: Option<String>, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_key: enums::DashboardMetadata, dashboard_metadata_update: storage::DashboardMetadataUpdate, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let mut dashboard_metadata = self.dashboard_metadata.lock().await; let dashboard_metadata_to_update = dashboard_metadata .iter_mut() .find(|metadata| { metadata.user_id == user_id && metadata.merchant_id == merchant_id && metadata.org_id == org_id && metadata.data_key == data_key }) .ok_or(errors::StorageError::MockDbError)?; match dashboard_metadata_update { storage::DashboardMetadataUpdate::UpdateData { data_key, data_value, last_modified_by, } => { dashboard_metadata_to_update.data_key = data_key; dashboard_metadata_to_update.data_value = data_value; dashboard_metadata_to_update.last_modified_by = last_modified_by; dashboard_metadata_to_update.last_modified_at = common_utils::date_time::now(); } } Ok(dashboard_metadata_to_update.clone()) } async fn find_user_scoped_dashboard_metadata( &self, user_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { let dashboard_metadata = self.dashboard_metadata.lock().await; let query_result = dashboard_metadata .iter() .filter(|metadata_inner| { metadata_inner .user_id .clone() .map(|user_id_inner| user_id_inner == user_id) .unwrap_or(false) && metadata_inner.merchant_id == *merchant_id && metadata_inner.org_id == *org_id && data_keys.contains(&metadata_inner.data_key) }) .cloned() .collect::<Vec<storage::DashboardMetadata>>(); if query_result.is_empty() { return Err(errors::StorageError::ValueNotFound(format!( "No dashboard_metadata available for user_id = {user_id},\ merchant_id = {merchant_id:?}, org_id = {org_id:?} and data_keys = {data_keys:?}", )) .into()); } Ok(query_result) } async fn find_merchant_scoped_dashboard_metadata( &self, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { let dashboard_metadata = self.dashboard_metadata.lock().await; let query_result = dashboard_metadata .iter() .filter(|metadata_inner| { metadata_inner.merchant_id == *merchant_id && metadata_inner.org_id == *org_id && data_keys.contains(&metadata_inner.data_key) }) .cloned() .collect::<Vec<storage::DashboardMetadata>>(); if query_result.is_empty() { return Err(errors::StorageError::ValueNotFound(format!( "No dashboard_metadata available for merchant_id = {merchant_id:?},\ org_id = {org_id:?} and data_keyss = {data_keys:?}", )) .into()); } Ok(query_result) } async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( &self, user_id: &str, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let mut dashboard_metadata = self.dashboard_metadata.lock().await; let initial_len = dashboard_metadata.len(); dashboard_metadata.retain(|metadata_inner| { !(metadata_inner .user_id .clone() .map(|user_id_inner| user_id_inner == user_id) .unwrap_or(false) && metadata_inner.merchant_id == *merchant_id) }); if dashboard_metadata.len() == initial_len { return Err(errors::StorageError::ValueNotFound(format!( "No user available for user_id = {user_id} and merchant id = {merchant_id:?}" )) .into()); } Ok(true) } async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &self, user_id: &str, merchant_id: &id_type::MerchantId, data_key: enums::DashboardMetadata, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let mut dashboard_metadata = self.dashboard_metadata.lock().await; let index_to_remove = dashboard_metadata .iter() .position(|metadata_inner| { metadata_inner.user_id.as_deref() == Some(user_id) && metadata_inner.merchant_id == *merchant_id && metadata_inner.data_key == data_key }) .ok_or(errors::StorageError::ValueNotFound( "No data found".to_string(), ))?; let deleted_value = dashboard_metadata.swap_remove(index_to_remove); Ok(deleted_value) } }
crates/router/src/db/dashboard_metadata.rs
router::src::db::dashboard_metadata
2,700
true
// File: crates/router/src/db/customers.rs // Module: router::src::db::customers pub use hyperswitch_domain_models::customer::{CustomerInterface, CustomerListConstraints};
crates/router/src/db/customers.rs
router::src::db::customers
38
true
// File: crates/router/src/db/gsm.rs // Module: router::src::db::gsm use diesel_models::gsm as storage; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait GsmInterface { async fn add_gsm_rule( &self, rule: hyperswitch_domain_models::gsm::GatewayStatusMap, ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError>; async fn find_gsm_decision( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<String, errors::StorageError>; async fn find_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError>; async fn update_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, data: hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate, ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError>; async fn delete_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<bool, errors::StorageError>; } #[async_trait::async_trait] impl GsmInterface for Store { #[instrument(skip_all)] async fn add_gsm_rule( &self, rule: hyperswitch_domain_models::gsm::GatewayStatusMap, ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let gsm_db_record = diesel_models::gsm::GatewayStatusMappingNew::try_from(rule) .change_context(errors::StorageError::SerializationFailed) .attach_printable("Failed to convert gsm domain models to diesel models")? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))?; hyperswitch_domain_models::gsm::GatewayStatusMap::try_from(gsm_db_record) .change_context(errors::StorageError::DeserializationFailed) .attach_printable("Failed to convert gsm diesel models to domain models") } #[instrument(skip_all)] async fn find_gsm_decision( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<String, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::GatewayStatusMap::retrieve_decision( &conn, connector, flow, sub_flow, code, message, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let gsm_db_record = storage::GatewayStatusMap::find(&conn, connector, flow, sub_flow, code, message) .await .map_err(|error| report!(errors::StorageError::from(error)))?; hyperswitch_domain_models::gsm::GatewayStatusMap::try_from(gsm_db_record) .change_context(errors::StorageError::DeserializationFailed) .attach_printable("Failed to convert gsm diesel models to domain models") } #[instrument(skip_all)] async fn update_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, data: hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate, ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let gsm_update_data = diesel_models::gsm::GatewayStatusMappingUpdate::try_from(data) .change_context(errors::StorageError::SerializationFailed)?; let gsm_db_record = storage::GatewayStatusMap::update( &conn, connector, flow, sub_flow, code, message, gsm_update_data, ) .await .map_err(|error| report!(errors::StorageError::from(error)))?; hyperswitch_domain_models::gsm::GatewayStatusMap::try_from(gsm_db_record) .change_context(errors::StorageError::DeserializationFailed) .attach_printable("Failed to convert gsm diesel models to domain models") } #[instrument(skip_all)] async fn delete_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::GatewayStatusMap::delete(&conn, connector, flow, sub_flow, code, message) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl GsmInterface for MockDb { async fn add_gsm_rule( &self, _rule: hyperswitch_domain_models::gsm::GatewayStatusMap, ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_gsm_decision( &self, _connector: String, _flow: String, _sub_flow: String, _code: String, _message: String, ) -> CustomResult<String, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_gsm_rule( &self, _connector: String, _flow: String, _sub_flow: String, _code: String, _message: String, ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_gsm_rule( &self, _connector: String, _flow: String, _sub_flow: String, _code: String, _message: String, _data: hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate, ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn delete_gsm_rule( &self, _connector: String, _flow: String, _sub_flow: String, _code: String, _message: String, ) -> CustomResult<bool, errors::StorageError> { Err(errors::StorageError::MockDbError)? } }
crates/router/src/db/gsm.rs
router::src::db::gsm
1,668
true
// File: crates/router/src/db/hyperswitch_ai_interaction.rs // Module: router::src::db::hyperswitch_ai_interaction use diesel_models::hyperswitch_ai_interaction as storage; use error_stack::report; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait HyperswitchAiInteractionInterface { async fn insert_hyperswitch_ai_interaction( &self, hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew, ) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError>; async fn list_hyperswitch_ai_interactions( &self, merchant_id: Option<common_utils::id_type::MerchantId>, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError>; } #[async_trait::async_trait] impl HyperswitchAiInteractionInterface for Store { #[instrument(skip_all)] async fn insert_hyperswitch_ai_interaction( &self, hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew, ) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; hyperswitch_ai_interaction .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_hyperswitch_ai_interactions( &self, merchant_id: Option<common_utils::id_type::MerchantId>, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::HyperswitchAiInteraction::filter_by_optional_merchant_id( &conn, merchant_id.as_ref(), limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl HyperswitchAiInteractionInterface for MockDb { async fn insert_hyperswitch_ai_interaction( &self, hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew, ) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError> { let mut hyperswitch_ai_interactions = self.hyperswitch_ai_interactions.lock().await; let hyperswitch_ai_interaction = storage::HyperswitchAiInteraction { id: hyperswitch_ai_interaction.id, session_id: hyperswitch_ai_interaction.session_id, user_id: hyperswitch_ai_interaction.user_id, merchant_id: hyperswitch_ai_interaction.merchant_id, profile_id: hyperswitch_ai_interaction.profile_id, org_id: hyperswitch_ai_interaction.org_id, role_id: hyperswitch_ai_interaction.role_id, user_query: hyperswitch_ai_interaction.user_query, response: hyperswitch_ai_interaction.response, database_query: hyperswitch_ai_interaction.database_query, interaction_status: hyperswitch_ai_interaction.interaction_status, created_at: hyperswitch_ai_interaction.created_at, }; hyperswitch_ai_interactions.push(hyperswitch_ai_interaction.clone()); Ok(hyperswitch_ai_interaction) } async fn list_hyperswitch_ai_interactions( &self, merchant_id: Option<common_utils::id_type::MerchantId>, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError> { let hyperswitch_ai_interactions = self.hyperswitch_ai_interactions.lock().await; let offset_usize = offset.try_into().unwrap_or_else(|_| { common_utils::consts::DEFAULT_LIST_OFFSET .try_into() .unwrap_or(usize::MIN) }); let limit_usize = limit.try_into().unwrap_or_else(|_| { common_utils::consts::DEFAULT_LIST_LIMIT .try_into() .unwrap_or(usize::MAX) }); let filtered_interactions: Vec<storage::HyperswitchAiInteraction> = hyperswitch_ai_interactions .iter() .filter( |interaction| match (merchant_id.as_ref(), &interaction.merchant_id) { (Some(merchant_id), Some(interaction_merchant_id)) => { interaction_merchant_id == &merchant_id.get_string_repr().to_owned() } (None, _) => true, _ => false, }, ) .skip(offset_usize) .take(limit_usize) .cloned() .collect(); Ok(filtered_interactions) } }
crates/router/src/db/hyperswitch_ai_interaction.rs
router::src::db::hyperswitch_ai_interaction
1,056
true
// File: crates/router/src/db/authentication.rs // Module: router::src::db::authentication use diesel_models::authentication::AuthenticationUpdateInternal; use error_stack::report; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait AuthenticationInterface { async fn insert_authentication( &self, authentication: storage::AuthenticationNew, ) -> CustomResult<storage::Authentication, errors::StorageError>; async fn find_authentication_by_merchant_id_authentication_id( &self, merchant_id: &common_utils::id_type::MerchantId, authentication_id: &common_utils::id_type::AuthenticationId, ) -> CustomResult<storage::Authentication, errors::StorageError>; async fn find_authentication_by_merchant_id_connector_authentication_id( &self, merchant_id: common_utils::id_type::MerchantId, connector_authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError>; async fn update_authentication_by_merchant_id_authentication_id( &self, previous_state: storage::Authentication, authentication_update: storage::AuthenticationUpdate, ) -> CustomResult<storage::Authentication, errors::StorageError>; } #[async_trait::async_trait] impl AuthenticationInterface for Store { #[instrument(skip_all)] async fn insert_authentication( &self, authentication: storage::AuthenticationNew, ) -> CustomResult<storage::Authentication, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; authentication .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_authentication_by_merchant_id_authentication_id( &self, merchant_id: &common_utils::id_type::MerchantId, authentication_id: &common_utils::id_type::AuthenticationId, ) -> CustomResult<storage::Authentication, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Authentication::find_by_merchant_id_authentication_id( &conn, merchant_id, authentication_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_authentication_by_merchant_id_connector_authentication_id( &self, merchant_id: common_utils::id_type::MerchantId, connector_authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Authentication::find_authentication_by_merchant_id_connector_authentication_id( &conn, &merchant_id, &connector_authentication_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_authentication_by_merchant_id_authentication_id( &self, previous_state: storage::Authentication, authentication_update: storage::AuthenticationUpdate, ) -> CustomResult<storage::Authentication, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Authentication::update_by_merchant_id_authentication_id( &conn, previous_state.merchant_id, previous_state.authentication_id, authentication_update, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl AuthenticationInterface for MockDb { async fn insert_authentication( &self, authentication: storage::AuthenticationNew, ) -> CustomResult<storage::Authentication, errors::StorageError> { let mut authentications = self.authentications.lock().await; if authentications.iter().any(|authentication_inner| { authentication_inner.authentication_id == authentication.authentication_id }) { Err(errors::StorageError::DuplicateValue { entity: "authentication_id", key: Some( authentication .authentication_id .get_string_repr() .to_string(), ), })? } let authentication = storage::Authentication { created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), authentication_id: authentication.authentication_id, merchant_id: authentication.merchant_id, authentication_status: authentication.authentication_status, authentication_connector: authentication.authentication_connector, connector_authentication_id: authentication.connector_authentication_id, authentication_data: None, payment_method_id: authentication.payment_method_id, authentication_type: authentication.authentication_type, authentication_lifecycle_status: authentication.authentication_lifecycle_status, error_code: authentication.error_code, error_message: authentication.error_message, connector_metadata: authentication.connector_metadata, maximum_supported_version: authentication.maximum_supported_version, threeds_server_transaction_id: authentication.threeds_server_transaction_id, cavv: authentication.cavv, authentication_flow_type: authentication.authentication_flow_type, message_version: authentication.message_version, eci: authentication.eci, trans_status: authentication.trans_status, acquirer_bin: authentication.acquirer_bin, acquirer_merchant_id: authentication.acquirer_merchant_id, three_ds_method_data: authentication.three_ds_method_data, three_ds_method_url: authentication.three_ds_method_url, acs_url: authentication.acs_url, challenge_request: authentication.challenge_request, challenge_request_key: authentication.challenge_request_key, acs_reference_number: authentication.acs_reference_number, acs_trans_id: authentication.acs_trans_id, acs_signed_content: authentication.acs_signed_content, profile_id: authentication.profile_id, payment_id: authentication.payment_id, merchant_connector_id: authentication.merchant_connector_id, ds_trans_id: authentication.ds_trans_id, directory_server_id: authentication.directory_server_id, acquirer_country_code: authentication.acquirer_country_code, service_details: authentication.service_details, organization_id: authentication.organization_id, authentication_client_secret: authentication.authentication_client_secret, force_3ds_challenge: authentication.force_3ds_challenge, psd2_sca_exemption_type: authentication.psd2_sca_exemption_type, return_url: authentication.return_url, amount: authentication.amount, currency: authentication.currency, billing_address: authentication.billing_address, shipping_address: authentication.shipping_address, browser_info: authentication.browser_info, email: authentication.email, profile_acquirer_id: authentication.profile_acquirer_id, challenge_code: authentication.challenge_code, challenge_cancel: authentication.challenge_cancel, challenge_code_reason: authentication.challenge_code_reason, message_extension: authentication.message_extension, }; authentications.push(authentication.clone()); Ok(authentication) } async fn find_authentication_by_merchant_id_authentication_id( &self, merchant_id: &common_utils::id_type::MerchantId, authentication_id: &common_utils::id_type::AuthenticationId, ) -> CustomResult<storage::Authentication, errors::StorageError> { let authentications = self.authentications.lock().await; authentications .iter() .find(|a| a.merchant_id == *merchant_id && a.authentication_id == *authentication_id) .ok_or( errors::StorageError::ValueNotFound(format!( "cannot find authentication for authentication_id = {authentication_id:?} and merchant_id = {merchant_id:?}" )).into(), ).cloned() } async fn find_authentication_by_merchant_id_connector_authentication_id( &self, _merchant_id: common_utils::id_type::MerchantId, _connector_authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_authentication_by_merchant_id_authentication_id( &self, previous_state: storage::Authentication, authentication_update: storage::AuthenticationUpdate, ) -> CustomResult<storage::Authentication, errors::StorageError> { let mut authentications = self.authentications.lock().await; let authentication_id = previous_state.authentication_id.clone(); let merchant_id = previous_state.merchant_id.clone(); authentications .iter_mut() .find(|authentication| authentication.authentication_id == authentication_id && authentication.merchant_id == merchant_id) .map(|authentication| { let authentication_update_internal = AuthenticationUpdateInternal::from(authentication_update); let updated_authentication = authentication_update_internal.apply_changeset(previous_state); *authentication = updated_authentication.clone(); updated_authentication }) .ok_or( errors::StorageError::ValueNotFound(format!( "cannot find authentication for authentication_id = {authentication_id:?} and merchant_id = {merchant_id:?}" )) .into(), ) } }
crates/router/src/db/authentication.rs
router::src::db::authentication
1,886
true
// File: crates/router/src/db/merchant_key_store.rs // Module: router::src::db::merchant_key_store pub use hyperswitch_domain_models::merchant_key_store::{self, MerchantKeyStoreInterface}; #[cfg(test)] mod tests { use std::{borrow::Cow, sync::Arc}; use common_utils::{type_name, types::keymanager::Identifier}; use hyperswitch_domain_models::master_key::MasterKeyInterface; use time::macros::datetime; use tokio::sync::oneshot; use crate::{ db::{merchant_key_store::MerchantKeyStoreInterface, MockDb}, routes::{ self, app::{settings::Settings, StorageImpl}, }, services, types::domain, }; #[allow(clippy::unwrap_used, clippy::expect_used)] #[tokio::test] async fn test_mock_db_merchant_key_store_interface() { let conf = Settings::new().expect("invalid settings"); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = &Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); #[allow(clippy::expect_used)] let mock_db = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create mock DB"); let master_key = mock_db.get_master_key(); let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant1")).unwrap(); let identifier = Identifier::Merchant(merchant_id.clone()); let key_manager_state = &state.into(); let merchant_key1 = mock_db .insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain::types::CryptoOperation::Encrypt( services::generate_aes256_key().unwrap().to_vec().into(), ), identifier.clone(), master_key, ) .await .and_then(|val| val.try_into_operation()) .unwrap(), created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await .unwrap(); let found_merchant_key1 = mock_db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &master_key.to_vec().into(), ) .await .unwrap(); assert_eq!(found_merchant_key1.merchant_id, merchant_key1.merchant_id); assert_eq!(found_merchant_key1.key, merchant_key1.key); let insert_duplicate_merchant_key1_result = mock_db .insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain::types::CryptoOperation::Encrypt( services::generate_aes256_key().unwrap().to_vec().into(), ), identifier.clone(), master_key, ) .await .and_then(|val| val.try_into_operation()) .unwrap(), created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await; assert!(insert_duplicate_merchant_key1_result.is_err()); let non_existent_merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("non_existent")).unwrap(); let find_non_existent_merchant_key_result = mock_db .get_merchant_key_store_by_merchant_id( key_manager_state, &non_existent_merchant_id, &master_key.to_vec().into(), ) .await; assert!(find_non_existent_merchant_key_result.is_err()); let find_merchant_key_with_incorrect_master_key_result = mock_db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &vec![0; 32].into(), ) .await; assert!(find_merchant_key_with_incorrect_master_key_result.is_err()); } }
crates/router/src/db/merchant_key_store.rs
router::src::db::merchant_key_store
1,026
true
// File: crates/router/src/db/health_check.rs // Module: router::src::db::health_check use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; use diesel_models::ConfigNew; use error_stack::ResultExt; use router_env::{instrument, logger, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait HealthCheckDbInterface { async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError>; } #[async_trait::async_trait] impl HealthCheckDbInterface for Store { #[instrument(skip_all)] async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> { let conn = connection::pg_connection_write(self) .await .change_context(errors::HealthCheckDBError::DBError)?; conn.transaction_async(|conn| async move { let query = diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("1 + 1")); let _x: i32 = query.get_result_async(&conn).await.map_err(|err| { logger::error!(read_err=?err,"Error while reading element in the database"); errors::HealthCheckDBError::DBReadError })?; logger::debug!("Database read was successful"); let config = ConfigNew { key: "test_key".to_string(), config: "test_value".to_string(), }; config.insert(&conn).await.map_err(|err| { logger::error!(write_err=?err,"Error while writing to database"); errors::HealthCheckDBError::DBWriteError })?; logger::debug!("Database write was successful"); storage::Config::delete_by_key(&conn, "test_key") .await .map_err(|err| { logger::error!(delete_err=?err,"Error while deleting element in the database"); errors::HealthCheckDBError::DBDeleteError })?; logger::debug!("Database delete was successful"); Ok::<_, errors::HealthCheckDBError>(()) }) .await?; Ok(()) } } #[async_trait::async_trait] impl HealthCheckDbInterface for MockDb { async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> { Ok(()) } }
crates/router/src/db/health_check.rs
router::src::db::health_check
523
true
// File: crates/router/src/db/kafka_store.rs // Module: router::src::db::kafka_store use std::{collections::HashSet, sync::Arc}; use ::payment_methods::state::PaymentMethodsStorageInterface; use common_enums::enums::MerchantStorageScheme; use common_utils::{ errors::CustomResult, id_type, types::{keymanager::KeyManagerState, user::ThemeLineage, TenantConfig}, }; #[cfg(feature = "v2")] use diesel_models::ephemeral_key::{ClientSecretType, ClientSecretTypeNew}; use diesel_models::{ enums::{self, ProcessTrackerStatus}, ephemeral_key::{EphemeralKey, EphemeralKeyNew}, refund as diesel_refund, reverse_lookup::{ReverseLookup, ReverseLookupNew}, user_role as user_storage, }; #[cfg(feature = "payouts")] use hyperswitch_domain_models::payouts::{ payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface, }; use hyperswitch_domain_models::{ cards_info::CardsInfoInterface, disputes, invoice::{Invoice as DomainInvoice, InvoiceInterface, InvoiceUpdate as DomainInvoiceUpdate}, payment_methods::PaymentMethodInterface, payments::{payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface}, refunds, subscription::{ Subscription as DomainSubscription, SubscriptionInterface, SubscriptionUpdate as DomainSubscriptionUpdate, }, }; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; use masking::Secret; use redis_interface::{errors::RedisError, RedisConnectionPool, RedisEntryId}; use router_env::{instrument, logger, tracing}; use scheduler::{ db::{process_tracker::ProcessTrackerInterface, queue::QueueInterface}, SchedulerInterface, }; use serde::Serialize; use storage_impl::redis::kv_store::RedisConnInterface; use time::PrimitiveDateTime; use super::{ dashboard_metadata::DashboardMetadataInterface, ephemeral_key::ClientSecretInterface, hyperswitch_ai_interaction::HyperswitchAiInteractionInterface, role::RoleInterface, user::{sample_data::BatchSampleDataInterface, theme::ThemeInterface, UserInterface}, user_authentication_method::UserAuthenticationMethodInterface, user_key_store::UserKeyStoreInterface, user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload, UserRoleInterface}, }; #[cfg(feature = "payouts")] use crate::services::kafka::payout::KafkaPayout; use crate::{ core::errors::{self, ProcessTrackerError}, db::{ self, address::AddressInterface, api_keys::ApiKeyInterface, authentication::AuthenticationInterface, authorization::AuthorizationInterface, business_profile::ProfileInterface, callback_mapper::CallbackMapperInterface, capture::CaptureInterface, configs::ConfigInterface, customers::CustomerInterface, dispute::DisputeInterface, ephemeral_key::EphemeralKeyInterface, events::EventInterface, file::FileMetadataInterface, generic_link::GenericLinkInterface, gsm::GsmInterface, health_check::HealthCheckDbInterface, locker_mock_up::LockerMockUpInterface, mandate::MandateInterface, merchant_account::MerchantAccountInterface, merchant_connector_account::{ConnectorAccessToken, MerchantConnectorAccountInterface}, merchant_key_store::MerchantKeyStoreInterface, payment_link::PaymentLinkInterface, refund::RefundInterface, reverse_lookup::ReverseLookupInterface, routing_algorithm::RoutingAlgorithmInterface, tokenization::TokenizationInterface, unified_translations::UnifiedTranslationsInterface, AccountsStorageInterface, CommonStorageInterface, GlobalStorageInterface, MasterKeyInterface, StorageInterface, }, services::{kafka::KafkaProducer, Store}, types::{domain, storage, AccessToken}, }; #[derive(Debug, Clone, Serialize)] pub struct TenantID(pub String); #[derive(Clone)] pub struct KafkaStore { pub kafka_producer: KafkaProducer, pub diesel_store: Store, pub tenant_id: TenantID, } impl KafkaStore { pub async fn new( store: Store, mut kafka_producer: KafkaProducer, tenant_id: TenantID, tenant_config: &dyn TenantConfig, ) -> Self { kafka_producer.set_tenancy(tenant_config); Self { kafka_producer, diesel_store: store, tenant_id, } } } #[async_trait::async_trait] impl AddressInterface for KafkaStore { async fn find_address_by_address_id( &self, state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { self.diesel_store .find_address_by_address_id(state, address_id, key_store) .await } async fn update_address( &self, state: &KeyManagerState, address_id: String, address: storage::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { self.diesel_store .update_address(state, address_id, address, key_store) .await } async fn update_address_for_payments( &self, state: &KeyManagerState, this: domain::PaymentAddress, address: domain::AddressUpdate, payment_id: id_type::PaymentId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { self.diesel_store .update_address_for_payments( state, this, address, payment_id, key_store, storage_scheme, ) .await } async fn insert_address_for_payments( &self, state: &KeyManagerState, payment_id: &id_type::PaymentId, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { self.diesel_store .insert_address_for_payments(state, payment_id, address, key_store, storage_scheme) .await } async fn find_address_by_merchant_id_payment_id_address_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, address_id: &str, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { self.diesel_store .find_address_by_merchant_id_payment_id_address_id( state, merchant_id, payment_id, address_id, key_store, storage_scheme, ) .await } async fn insert_address_for_customers( &self, state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { self.diesel_store .insert_address_for_customers(state, address, key_store) .await } async fn update_address_by_merchant_id_customer_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, address: storage::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Address>, errors::StorageError> { self.diesel_store .update_address_by_merchant_id_customer_id( state, customer_id, merchant_id, address, key_store, ) .await } } #[async_trait::async_trait] impl ApiKeyInterface for KafkaStore { async fn insert_api_key( &self, api_key: storage::ApiKeyNew, ) -> CustomResult<storage::ApiKey, errors::StorageError> { self.diesel_store.insert_api_key(api_key).await } async fn update_api_key( &self, merchant_id: id_type::MerchantId, key_id: id_type::ApiKeyId, api_key: storage::ApiKeyUpdate, ) -> CustomResult<storage::ApiKey, errors::StorageError> { self.diesel_store .update_api_key(merchant_id, key_id, api_key) .await } async fn revoke_api_key( &self, merchant_id: &id_type::MerchantId, key_id: &id_type::ApiKeyId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store.revoke_api_key(merchant_id, key_id).await } async fn find_api_key_by_merchant_id_key_id_optional( &self, merchant_id: &id_type::MerchantId, key_id: &id_type::ApiKeyId, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { self.diesel_store .find_api_key_by_merchant_id_key_id_optional(merchant_id, key_id) .await } async fn find_api_key_by_hash_optional( &self, hashed_api_key: storage::HashedApiKey, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { self.diesel_store .find_api_key_by_hash_optional(hashed_api_key) .await } async fn list_api_keys_by_merchant_id( &self, merchant_id: &id_type::MerchantId, limit: Option<i64>, offset: Option<i64>, ) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> { self.diesel_store .list_api_keys_by_merchant_id(merchant_id, limit, offset) .await } } #[async_trait::async_trait] impl CardsInfoInterface for KafkaStore { type Error = errors::StorageError; async fn get_card_info( &self, card_iin: &str, ) -> CustomResult<Option<storage::CardInfo>, errors::StorageError> { self.diesel_store.get_card_info(card_iin).await } async fn add_card_info( &self, data: storage::CardInfo, ) -> CustomResult<storage::CardInfo, errors::StorageError> { self.diesel_store.add_card_info(data).await } async fn update_card_info( &self, card_iin: String, data: storage::UpdateCardInfo, ) -> CustomResult<storage::CardInfo, errors::StorageError> { self.diesel_store.update_card_info(card_iin, data).await } } #[async_trait::async_trait] impl ConfigInterface for KafkaStore { type Error = errors::StorageError; async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, errors::StorageError> { self.diesel_store.insert_config(config).await } async fn find_config_by_key( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { self.diesel_store.find_config_by_key(key).await } async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { self.diesel_store.find_config_by_key_from_db(key).await } async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError> { self.diesel_store .update_config_in_database(key, config_update) .await } async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError> { self.diesel_store .update_config_by_key(key, config_update) .await } async fn delete_config_by_key( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { self.diesel_store.delete_config_by_key(key).await } async fn find_config_by_key_unwrap_or( &self, key: &str, default_config: Option<String>, ) -> CustomResult<storage::Config, errors::StorageError> { self.diesel_store .find_config_by_key_unwrap_or(key, default_config) .await } } #[async_trait::async_trait] impl CustomerInterface for KafkaStore { type Error = errors::StorageError; #[cfg(feature = "v1")] async fn delete_customer_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_customer_by_customer_id_merchant_id(customer_id, merchant_id) .await } #[cfg(feature = "v1")] async fn find_customer_optional_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, errors::StorageError> { self.diesel_store .find_customer_optional_by_customer_id_merchant_id( state, customer_id, merchant_id, key_store, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, errors::StorageError> { self.diesel_store .find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( state, customer_id, merchant_id, key_store, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_optional_by_merchant_id_merchant_reference_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, errors::StorageError> { self.diesel_store .find_optional_by_merchant_id_merchant_reference_id( state, customer_id, merchant_id, key_store, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn update_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, customer: domain::Customer, customer_update: storage::CustomerUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store .update_customer_by_customer_id_merchant_id( state, customer_id, merchant_id, customer, customer_update, key_store, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn update_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, customer: domain::Customer, customer_update: storage::CustomerUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store .update_customer_by_global_id( state, id, customer, customer_update, key_store, storage_scheme, ) .await } async fn list_customers_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, constraints: super::customers::CustomerListConstraints, ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> { self.diesel_store .list_customers_by_merchant_id(state, merchant_id, key_store, constraints) .await } async fn list_customers_by_merchant_id_with_count( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, constraints: super::customers::CustomerListConstraints, ) -> CustomResult<(Vec<domain::Customer>, usize), errors::StorageError> { self.diesel_store .list_customers_by_merchant_id_with_count(state, merchant_id, key_store, constraints) .await } #[cfg(feature = "v1")] async fn find_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store .find_customer_by_customer_id_merchant_id( state, customer_id, merchant_id, key_store, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_customer_by_merchant_reference_id_merchant_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store .find_customer_by_merchant_reference_id_merchant_id( state, merchant_reference_id, merchant_id, key_store, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store .find_customer_by_global_id(state, id, key_store, storage_scheme) .await } async fn insert_customer( &self, customer_data: domain::Customer, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store .insert_customer(customer_data, state, key_store, storage_scheme) .await } } #[async_trait::async_trait] impl DisputeInterface for KafkaStore { async fn insert_dispute( &self, dispute_new: storage::DisputeNew, ) -> CustomResult<storage::Dispute, errors::StorageError> { let dispute = self.diesel_store.insert_dispute(dispute_new).await?; if let Err(er) = self .kafka_producer .log_dispute(&dispute, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to add analytics entry for Dispute {dispute:?}", error_message=?er); }; Ok(dispute) } async fn find_by_merchant_id_payment_id_connector_dispute_id( &self, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, connector_dispute_id: &str, ) -> CustomResult<Option<storage::Dispute>, errors::StorageError> { self.diesel_store .find_by_merchant_id_payment_id_connector_dispute_id( merchant_id, payment_id, connector_dispute_id, ) .await } async fn find_dispute_by_merchant_id_dispute_id( &self, merchant_id: &id_type::MerchantId, dispute_id: &str, ) -> CustomResult<storage::Dispute, errors::StorageError> { self.diesel_store .find_dispute_by_merchant_id_dispute_id(merchant_id, dispute_id) .await } async fn find_disputes_by_constraints( &self, merchant_id: &id_type::MerchantId, dispute_constraints: &disputes::DisputeListConstraints, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { self.diesel_store .find_disputes_by_constraints(merchant_id, dispute_constraints) .await } async fn update_dispute( &self, this: storage::Dispute, dispute: storage::DisputeUpdate, ) -> CustomResult<storage::Dispute, errors::StorageError> { let dispute_new = self .diesel_store .update_dispute(this.clone(), dispute) .await?; if let Err(er) = self .kafka_producer .log_dispute(&dispute_new, Some(this), self.tenant_id.clone()) .await { logger::error!(message="Failed to add analytics entry for Dispute {dispute_new:?}", error_message=?er); }; Ok(dispute_new) } async fn find_disputes_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { self.diesel_store .find_disputes_by_merchant_id_payment_id(merchant_id, payment_id) .await } async fn get_dispute_status_with_count( &self, merchant_id: &id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> { self.diesel_store .get_dispute_status_with_count(merchant_id, profile_id_list, time_range) .await } } #[async_trait::async_trait] impl EphemeralKeyInterface for KafkaStore { #[cfg(feature = "v1")] async fn create_ephemeral_key( &self, ek: EphemeralKeyNew, validity: i64, ) -> CustomResult<EphemeralKey, errors::StorageError> { self.diesel_store.create_ephemeral_key(ek, validity).await } #[cfg(feature = "v1")] async fn get_ephemeral_key( &self, key: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { self.diesel_store.get_ephemeral_key(key).await } #[cfg(feature = "v1")] async fn delete_ephemeral_key( &self, id: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { self.diesel_store.delete_ephemeral_key(id).await } } #[async_trait::async_trait] impl ClientSecretInterface for KafkaStore { #[cfg(feature = "v2")] async fn create_client_secret( &self, ek: ClientSecretTypeNew, validity: i64, ) -> CustomResult<ClientSecretType, errors::StorageError> { self.diesel_store.create_client_secret(ek, validity).await } #[cfg(feature = "v2")] async fn get_client_secret( &self, key: &str, ) -> CustomResult<ClientSecretType, errors::StorageError> { self.diesel_store.get_client_secret(key).await } #[cfg(feature = "v2")] async fn delete_client_secret( &self, id: &str, ) -> CustomResult<ClientSecretType, errors::StorageError> { self.diesel_store.delete_client_secret(id).await } } #[async_trait::async_trait] impl EventInterface for KafkaStore { async fn insert_event( &self, state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { self.diesel_store .insert_event(state, event, merchant_key_store) .await } async fn find_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { self.diesel_store .find_event_by_merchant_id_event_id(state, merchant_id, event_id, merchant_key_store) .await } async fn find_event_by_merchant_id_idempotent_event_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, idempotent_event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { self.diesel_store .find_event_by_merchant_id_idempotent_event_id( state, merchant_id, idempotent_event_id, merchant_key_store, ) .await } async fn list_initial_events_by_merchant_id_primary_object_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_initial_events_by_merchant_id_primary_object_id( state, merchant_id, primary_object_id, merchant_key_store, ) .await } async fn list_initial_events_by_merchant_id_constraints( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, created_after: PrimitiveDateTime, created_before: PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_initial_events_by_merchant_id_constraints( state, merchant_id, created_after, created_before, limit, offset, event_types, is_delivered, merchant_key_store, ) .await } async fn list_events_by_merchant_id_initial_attempt_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_events_by_merchant_id_initial_attempt_id( state, merchant_id, initial_attempt_id, merchant_key_store, ) .await } async fn list_initial_events_by_profile_id_primary_object_id( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_initial_events_by_profile_id_primary_object_id( state, profile_id, primary_object_id, merchant_key_store, ) .await } async fn list_initial_events_by_profile_id_constraints( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, created_after: PrimitiveDateTime, created_before: PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_initial_events_by_profile_id_constraints( state, profile_id, created_after, created_before, limit, offset, event_types, is_delivered, merchant_key_store, ) .await } async fn update_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, event_id: &str, event: domain::EventUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { self.diesel_store .update_event_by_merchant_id_event_id( state, merchant_id, event_id, event, merchant_key_store, ) .await } async fn count_initial_events_by_constraints( &self, merchant_id: &id_type::MerchantId, profile_id: Option<id_type::ProfileId>, created_after: PrimitiveDateTime, created_before: PrimitiveDateTime, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .count_initial_events_by_constraints( merchant_id, profile_id, created_after, created_before, event_types, is_delivered, ) .await } } #[async_trait::async_trait] impl LockerMockUpInterface for KafkaStore { async fn find_locker_by_card_id( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { self.diesel_store.find_locker_by_card_id(card_id).await } async fn insert_locker_mock_up( &self, new: storage::LockerMockUpNew, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { self.diesel_store.insert_locker_mock_up(new).await } async fn delete_locker_mock_up( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { self.diesel_store.delete_locker_mock_up(card_id).await } } #[async_trait::async_trait] impl MandateInterface for KafkaStore { async fn find_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Mandate, errors::StorageError> { self.diesel_store .find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id, storage_scheme) .await } async fn find_mandate_by_merchant_id_connector_mandate_id( &self, merchant_id: &id_type::MerchantId, connector_mandate_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Mandate, errors::StorageError> { self.diesel_store .find_mandate_by_merchant_id_connector_mandate_id( merchant_id, connector_mandate_id, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_mandate_by_global_customer_id( &self, id: &id_type::GlobalCustomerId, ) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> { self.diesel_store .find_mandate_by_global_customer_id(id) .await } async fn find_mandate_by_merchant_id_customer_id( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, ) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> { self.diesel_store .find_mandate_by_merchant_id_customer_id(merchant_id, customer_id) .await } async fn update_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, mandate_update: storage::MandateUpdate, mandate: storage::Mandate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Mandate, errors::StorageError> { self.diesel_store .update_mandate_by_merchant_id_mandate_id( merchant_id, mandate_id, mandate_update, mandate, storage_scheme, ) .await } async fn find_mandates_by_merchant_id( &self, merchant_id: &id_type::MerchantId, mandate_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> { self.diesel_store .find_mandates_by_merchant_id(merchant_id, mandate_constraints) .await } async fn insert_mandate( &self, mandate: storage::MandateNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Mandate, errors::StorageError> { self.diesel_store .insert_mandate(mandate, storage_scheme) .await } } #[async_trait::async_trait] impl PaymentLinkInterface for KafkaStore { async fn find_payment_link_by_payment_link_id( &self, payment_link_id: &str, ) -> CustomResult<storage::PaymentLink, errors::StorageError> { self.diesel_store .find_payment_link_by_payment_link_id(payment_link_id) .await } async fn insert_payment_link( &self, payment_link_object: storage::PaymentLinkNew, ) -> CustomResult<storage::PaymentLink, errors::StorageError> { self.diesel_store .insert_payment_link(payment_link_object) .await } async fn list_payment_link_by_merchant_id( &self, merchant_id: &id_type::MerchantId, payment_link_constraints: api_models::payments::PaymentLinkListConstraints, ) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> { self.diesel_store .list_payment_link_by_merchant_id(merchant_id, payment_link_constraints) .await } } #[async_trait::async_trait] impl MerchantAccountInterface for KafkaStore { type Error = errors::StorageError; async fn insert_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store .insert_merchant(state, merchant_account, key_store) .await } async fn find_merchant_account_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store .find_merchant_account_by_merchant_id(state, merchant_id, key_store) .await } async fn update_merchant( &self, state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: storage::MerchantAccountUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store .update_merchant(state, this, merchant_account, key_store) .await } async fn update_specific_fields_in_merchant( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, merchant_account: storage::MerchantAccountUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store .update_specific_fields_in_merchant(state, merchant_id, merchant_account, key_store) .await } async fn update_all_merchant_account( &self, merchant_account: storage::MerchantAccountUpdate, ) -> CustomResult<usize, errors::StorageError> { self.diesel_store .update_all_merchant_account(merchant_account) .await } async fn find_merchant_account_by_publishable_key( &self, state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, domain::MerchantKeyStore), errors::StorageError> { self.diesel_store .find_merchant_account_by_publishable_key(state, publishable_key) .await } #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, state: &KeyManagerState, organization_id: &id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { self.diesel_store .list_merchant_accounts_by_organization_id(state, organization_id) .await } async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_merchant_account_by_merchant_id(merchant_id) .await } #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, state: &KeyManagerState, merchant_ids: Vec<id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { self.diesel_store .list_multiple_merchant_accounts(state, merchant_ids) .await } #[cfg(feature = "olap")] async fn list_merchant_and_org_ids( &self, state: &KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult<Vec<(id_type::MerchantId, id_type::OrganizationId)>, errors::StorageError> { self.diesel_store .list_merchant_and_org_ids(state, limit, offset) .await } } #[async_trait::async_trait] impl ConnectorAccessToken for KafkaStore { async fn get_access_token( &self, merchant_id: &id_type::MerchantId, merchant_connector_id: &str, ) -> CustomResult<Option<AccessToken>, errors::StorageError> { self.diesel_store .get_access_token(merchant_id, merchant_connector_id) .await } async fn set_access_token( &self, merchant_id: &id_type::MerchantId, merchant_connector_id: &str, access_token: AccessToken, ) -> CustomResult<(), errors::StorageError> { self.diesel_store .set_access_token(merchant_id, merchant_connector_id, access_token) .await } } #[async_trait::async_trait] impl FileMetadataInterface for KafkaStore { async fn insert_file_metadata( &self, file: storage::FileMetadataNew, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { self.diesel_store.insert_file_metadata(file).await } async fn find_file_metadata_by_merchant_id_file_id( &self, merchant_id: &id_type::MerchantId, file_id: &str, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { self.diesel_store .find_file_metadata_by_merchant_id_file_id(merchant_id, file_id) .await } async fn delete_file_metadata_by_merchant_id_file_id( &self, merchant_id: &id_type::MerchantId, file_id: &str, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_file_metadata_by_merchant_id_file_id(merchant_id, file_id) .await } async fn update_file_metadata( &self, this: storage::FileMetadata, file_metadata: storage::FileMetadataUpdate, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { self.diesel_store .update_file_metadata(this, file_metadata) .await } } #[async_trait::async_trait] impl MerchantConnectorAccountInterface for KafkaStore { type Error = errors::StorageError; async fn update_multiple_merchant_connector_accounts( &self, merchant_connector_accounts: Vec<( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), errors::StorageError> { self.diesel_store .update_multiple_merchant_connector_accounts(merchant_connector_accounts) .await } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, connector: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_merchant_id_connector_label( state, merchant_id, connector, key_store, ) .await } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_merchant_id_connector_name( state, merchant_id, connector_name, key_store, ) .await } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_profile_id_connector_name( state, profile_id, connector_name, key_store, ) .await } async fn list_enabled_connector_accounts_by_profile_id( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, key_store: &domain::MerchantKeyStore, connector_type: common_enums::ConnectorType, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { self.diesel_store .list_enabled_connector_accounts_by_profile_id( state, profile_id, key_store, connector_type, ) .await } async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .insert_merchant_connector_account(state, t, key_store) .await } #[cfg(feature = "v1")] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, merchant_connector_id: &id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( state, merchant_id, merchant_connector_id, key_store, ) .await } #[cfg(feature = "v2")] async fn find_merchant_connector_account_by_id( &self, state: &KeyManagerState, id: &id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_id(state, id, key_store) .await } async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, get_disabled: bool, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccounts, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_merchant_id_and_disabled_list( state, merchant_id, get_disabled, key_store, ) .await } #[cfg(all(feature = "olap", feature = "v2"))] async fn list_connector_account_by_profile_id( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { self.diesel_store .list_connector_account_by_profile_id(state, profile_id, key_store) .await } async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .update_merchant_connector_account(state, this, merchant_connector_account, key_store) .await } #[cfg(feature = "v1")] async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &id_type::MerchantId, merchant_connector_id: &id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_merchant_connector_account_by_merchant_id_merchant_connector_id( merchant_id, merchant_connector_id, ) .await } #[cfg(feature = "v2")] async fn delete_merchant_connector_account_by_id( &self, id: &id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_merchant_connector_account_by_id(id) .await } } #[async_trait::async_trait] impl QueueInterface for KafkaStore { async fn fetch_consumer_tasks( &self, stream_name: &str, group_name: &str, consumer_name: &str, ) -> CustomResult<Vec<storage::ProcessTracker>, ProcessTrackerError> { self.diesel_store .fetch_consumer_tasks(stream_name, group_name, consumer_name) .await } async fn consumer_group_create( &self, stream: &str, group: &str, id: &RedisEntryId, ) -> CustomResult<(), RedisError> { self.diesel_store .consumer_group_create(stream, group, id) .await } async fn acquire_pt_lock( &self, tag: &str, lock_key: &str, lock_val: &str, ttl: i64, ) -> CustomResult<bool, RedisError> { self.diesel_store .acquire_pt_lock(tag, lock_key, lock_val, ttl) .await } async fn release_pt_lock(&self, tag: &str, lock_key: &str) -> CustomResult<bool, RedisError> { self.diesel_store.release_pt_lock(tag, lock_key).await } async fn stream_append_entry( &self, stream: &str, entry_id: &RedisEntryId, fields: Vec<(&str, String)>, ) -> CustomResult<(), RedisError> { self.diesel_store .stream_append_entry(stream, entry_id, fields) .await } async fn get_key(&self, key: &str) -> CustomResult<Vec<u8>, RedisError> { self.diesel_store.get_key(key).await } } #[async_trait::async_trait] impl PaymentAttemptInterface for KafkaStore { type Error = errors::StorageError; #[cfg(feature = "v1")] async fn insert_payment_attempt( &self, payment_attempt: storage::PaymentAttemptNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { let attempt = self .diesel_store .insert_payment_attempt(payment_attempt, storage_scheme) .await?; if let Err(er) = self .kafka_producer .log_payment_attempt(&attempt, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) } Ok(attempt) } #[cfg(feature = "v2")] async fn insert_payment_attempt( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, payment_attempt: storage::PaymentAttempt, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { let attempt = self .diesel_store .insert_payment_attempt( key_manager_state, merchant_key_store, payment_attempt, storage_scheme, ) .await?; if let Err(er) = self .kafka_producer .log_payment_attempt(&attempt, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) } Ok(attempt) } #[cfg(feature = "v1")] async fn update_payment_attempt_with_attempt_id( &self, this: storage::PaymentAttempt, payment_attempt: storage::PaymentAttemptUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { let mut attempt = self .diesel_store .update_payment_attempt_with_attempt_id( this.clone(), payment_attempt.clone(), storage_scheme, ) .await?; let debit_routing_savings = payment_attempt.get_debit_routing_savings(); attempt.set_debit_routing_savings(debit_routing_savings); if let Err(er) = self .kafka_producer .log_payment_attempt(&attempt, Some(this), self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) } Ok(attempt) } #[cfg(feature = "v2")] async fn update_payment_attempt( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, this: storage::PaymentAttempt, payment_attempt: storage::PaymentAttemptUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { let attempt = self .diesel_store .update_payment_attempt( key_manager_state, merchant_key_store, this.clone(), payment_attempt, storage_scheme, ) .await?; if let Err(er) = self .kafka_producer .log_payment_attempt(&attempt, Some(this), self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) } Ok(attempt) } #[cfg(feature = "v1")] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( connector_transaction_id, payment_id, merchant_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, merchant_id: &id_type::MerchantId, connector_txn_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, connector_txn_id, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_attempt_by_profile_id_connector_transaction_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &id_type::ProfileId, connector_transaction_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_profile_id_connector_transaction_id( key_manager_state, merchant_key_store, profile_id, connector_transaction_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, attempt_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( payment_id, merchant_id, attempt_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, attempt_id: &str, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_attempt_id_merchant_id(attempt_id, merchant_id, storage_scheme) .await } #[cfg(feature = "v2")] async fn find_payment_attempt_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, attempt_id: &id_type::GlobalAttemptId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_id( key_manager_state, merchant_key_store, attempt_id, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_attempts_by_payment_intent_id( &self, key_manager_state: &KeyManagerState, payment_id: &id_type::GlobalPaymentId, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<storage::PaymentAttempt>, errors::StorageError> { self.diesel_store .find_payment_attempts_by_payment_intent_id( key_manager_state, payment_id, merchant_key_store, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( payment_id, merchant_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( payment_id, merchant_id, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, payment_id: &id_type::GlobalPaymentId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( key_manager_state, merchant_key_store, payment_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, preprocessing_id: &str, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_preprocessing_id_merchant_id( preprocessing_id, merchant_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn get_filters_for_payments( &self, pi: &[hyperswitch_domain_models::payments::PaymentIntent], merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult< hyperswitch_domain_models::payments::payment_attempt::PaymentListFilters, errors::StorageError, > { self.diesel_store .get_filters_for_payments(pi, merchant_id, storage_scheme) .await } #[cfg(feature = "v1")] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<api_models::enums::Connector>>, payment_method: Option<Vec<common_enums::PaymentMethod>>, payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<common_enums::CardNetwork>>, card_discovery: Option<Vec<common_enums::CardDiscovery>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .get_total_count_of_filtered_payment_attempts( merchant_id, active_attempt_ids, connector, payment_method, payment_method_type, authentication_type, merchant_connector_id, card_network, card_discovery, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<api_models::enums::Connector>>, payment_method_type: Option<Vec<common_enums::PaymentMethod>>, payment_method_subtype: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<common_enums::CardNetwork>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .get_total_count_of_filtered_payment_attempts( merchant_id, active_attempt_ids, connector, payment_method_type, payment_method_subtype, authentication_type, merchant_connector_id, card_network, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_attempts_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::PaymentAttempt>, errors::StorageError> { self.diesel_store .find_attempts_by_merchant_id_payment_id(merchant_id, payment_id, storage_scheme) .await } } #[async_trait::async_trait] impl PaymentIntentInterface for KafkaStore { type Error = errors::StorageError; async fn update_payment_intent( &self, state: &KeyManagerState, this: storage::PaymentIntent, payment_intent: storage::PaymentIntentUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentIntent, errors::StorageError> { let intent = self .diesel_store .update_payment_intent( state, this.clone(), payment_intent.clone(), key_store, storage_scheme, ) .await?; if let Err(er) = self .kafka_producer .log_payment_intent( &intent, Some(this), self.tenant_id.clone(), state.add_confirm_value_in_infra_values(payment_intent.is_confirm_operation()), ) .await { logger::error!(message="Failed to add analytics entry for Payment Intent {intent:?}", error_message=?er); }; Ok(intent) } async fn insert_payment_intent( &self, state: &KeyManagerState, new: storage::PaymentIntent, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentIntent, errors::StorageError> { logger::debug!("Inserting PaymentIntent Via KafkaStore"); let intent = self .diesel_store .insert_payment_intent(state, new, key_store, storage_scheme) .await?; if let Err(er) = self .kafka_producer .log_payment_intent( &intent, None, self.tenant_id.clone(), state.infra_values.clone(), ) .await { logger::error!(message="Failed to add analytics entry for Payment Intent {intent:?}", error_message=?er); }; Ok(intent) } #[cfg(feature = "v1")] async fn find_payment_intent_by_payment_id_merchant_id( &self, state: &KeyManagerState, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentIntent, errors::StorageError> { self.diesel_store .find_payment_intent_by_payment_id_merchant_id( state, payment_id, merchant_id, key_store, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_intent_by_id( &self, state: &KeyManagerState, payment_id: &id_type::GlobalPaymentId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentIntent, errors::StorageError> { self.diesel_store .find_payment_intent_by_id(state, payment_id, key_store, storage_scheme) .await } #[cfg(all(feature = "olap", feature = "v1"))] async fn filter_payment_intent_by_constraints( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::PaymentIntent>, errors::StorageError> { self.diesel_store .filter_payment_intent_by_constraints( state, merchant_id, filters, key_store, storage_scheme, ) .await } #[cfg(all(feature = "olap", feature = "v1"))] async fn filter_payment_intents_by_time_range_constraints( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, time_range: &common_utils::types::TimeRange, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::PaymentIntent>, errors::StorageError> { self.diesel_store .filter_payment_intents_by_time_range_constraints( state, merchant_id, time_range, key_store, storage_scheme, ) .await } #[cfg(feature = "olap")] async fn get_intent_status_with_count( &self, merchant_id: &id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::StorageError> { self.diesel_store .get_intent_status_with_count(merchant_id, profile_id_list, time_range) .await } #[cfg(all(feature = "olap", feature = "v1"))] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult< Vec<( hyperswitch_domain_models::payments::PaymentIntent, hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, )>, errors::StorageError, > { self.diesel_store .get_filtered_payment_intents_attempt( state, merchant_id, constraints, key_store, storage_scheme, ) .await } #[cfg(all(feature = "olap", feature = "v2"))] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult< Vec<( hyperswitch_domain_models::payments::PaymentIntent, Option<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>, )>, errors::StorageError, > { self.diesel_store .get_filtered_payment_intents_attempt( state, merchant_id, constraints, key_store, storage_scheme, ) .await } #[cfg(all(feature = "olap", feature = "v1"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &id_type::MerchantId, constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<String>, errors::StorageError> { self.diesel_store .get_filtered_active_attempt_ids_for_total_count( merchant_id, constraints, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_intent_by_merchant_reference_id_profile_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::PaymentReferenceId, profile_id: &id_type::ProfileId, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: &MerchantStorageScheme, ) -> error_stack::Result<hyperswitch_domain_models::payments::PaymentIntent, errors::StorageError> { self.diesel_store .find_payment_intent_by_merchant_reference_id_profile_id( state, merchant_reference_id, profile_id, merchant_key_store, storage_scheme, ) .await } #[cfg(all(feature = "olap", feature = "v2"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &id_type::MerchantId, constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<Option<String>>, errors::StorageError> { self.diesel_store .get_filtered_active_attempt_ids_for_total_count( merchant_id, constraints, storage_scheme, ) .await } } #[async_trait::async_trait] impl PaymentMethodInterface for KafkaStore { type Error = errors::StorageError; #[cfg(feature = "v1")] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, payment_method_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .find_payment_method(state, key_store, payment_method_id, storage_scheme) .await } #[cfg(feature = "v2")] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .find_payment_method(state, key_store, payment_method_id, storage_scheme) .await } #[cfg(feature = "v1")] async fn find_payment_method_by_customer_id_merchant_id_list( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, limit: Option<i64>, ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> { self.diesel_store .find_payment_method_by_customer_id_merchant_id_list( state, key_store, customer_id, merchant_id, limit, ) .await } #[cfg(feature = "v2")] async fn find_payment_method_list_by_global_customer_id( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, id: &id_type::GlobalCustomerId, limit: Option<i64>, ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> { self.diesel_store .find_payment_method_list_by_global_customer_id(state, key_store, id, limit) .await } #[cfg(feature = "v1")] async fn find_payment_method_by_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> { self.diesel_store .find_payment_method_by_customer_id_merchant_id_status( state, key_store, customer_id, merchant_id, status, limit, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> { self.diesel_store .find_payment_method_by_global_customer_id_merchant_id_status( state, key_store, customer_id, merchant_id, status, limit, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn get_payment_method_count_by_customer_id_merchant_id_status( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .get_payment_method_count_by_customer_id_merchant_id_status( customer_id, merchant_id, status, ) .await } async fn get_payment_method_count_by_merchant_id_status( &self, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .get_payment_method_count_by_merchant_id_status(merchant_id, status) .await } #[cfg(feature = "v1")] async fn find_payment_method_by_locker_id( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, locker_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .find_payment_method_by_locker_id(state, key_store, locker_id, storage_scheme) .await } async fn insert_payment_method( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, m: domain::PaymentMethod, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .insert_payment_method(state, key_store, m, storage_scheme) .await } async fn update_payment_method( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, payment_method: domain::PaymentMethod, payment_method_update: storage::PaymentMethodUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .update_payment_method( state, key_store, payment_method, payment_method_update, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn delete_payment_method_by_merchant_id_payment_method_id( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_id: &str, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .delete_payment_method_by_merchant_id_payment_method_id( state, key_store, merchant_id, payment_method_id, ) .await } #[cfg(feature = "v2")] async fn delete_payment_method( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, payment_method: domain::PaymentMethod, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .delete_payment_method(state, key_store, payment_method) .await } #[cfg(feature = "v2")] async fn find_payment_method_by_fingerprint_id( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, fingerprint_id: &str, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .find_payment_method_by_fingerprint_id(state, key_store, fingerprint_id) .await } } #[cfg(not(feature = "payouts"))] impl PayoutAttemptInterface for KafkaStore {} #[cfg(feature = "payouts")] #[async_trait::async_trait] impl PayoutAttemptInterface for KafkaStore { type Error = errors::StorageError; async fn find_payout_attempt_by_merchant_id_merchant_order_reference_id( &self, merchant_id: &id_type::MerchantId, merchant_order_reference_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> { self.diesel_store .find_payout_attempt_by_merchant_id_merchant_order_reference_id( merchant_id, merchant_order_reference_id, storage_scheme, ) .await } async fn find_payout_attempt_by_merchant_id_payout_attempt_id( &self, merchant_id: &id_type::MerchantId, payout_attempt_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> { self.diesel_store .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, payout_attempt_id, storage_scheme, ) .await } async fn find_payout_attempt_by_merchant_id_connector_payout_id( &self, merchant_id: &id_type::MerchantId, connector_payout_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> { self.diesel_store .find_payout_attempt_by_merchant_id_connector_payout_id( merchant_id, connector_payout_id, storage_scheme, ) .await } async fn update_payout_attempt( &self, this: &storage::PayoutAttempt, payout_attempt_update: storage::PayoutAttemptUpdate, payouts: &storage::Payouts, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> { let updated_payout_attempt = self .diesel_store .update_payout_attempt(this, payout_attempt_update, payouts, storage_scheme) .await?; if let Err(err) = self .kafka_producer .log_payout( &KafkaPayout::from_storage(payouts, &updated_payout_attempt), Some(KafkaPayout::from_storage(payouts, this)), self.tenant_id.clone(), ) .await { logger::error!(message="Failed to update analytics entry for Payouts {payouts:?}\n{updated_payout_attempt:?}", error_message=?err); }; Ok(updated_payout_attempt) } async fn insert_payout_attempt( &self, payout_attempt: storage::PayoutAttemptNew, payouts: &storage::Payouts, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> { let payout_attempt_new = self .diesel_store .insert_payout_attempt(payout_attempt, payouts, storage_scheme) .await?; if let Err(err) = self .kafka_producer .log_payout( &KafkaPayout::from_storage(payouts, &payout_attempt_new), None, self.tenant_id.clone(), ) .await { logger::error!(message="Failed to add analytics entry for Payouts {payouts:?}\n{payout_attempt_new:?}", error_message=?err); }; Ok(payout_attempt_new) } async fn get_filters_for_payouts( &self, payouts: &[hyperswitch_domain_models::payouts::payouts::Payouts], merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult< hyperswitch_domain_models::payouts::payout_attempt::PayoutListFilters, errors::StorageError, > { self.diesel_store .get_filters_for_payouts(payouts, merchant_id, storage_scheme) .await } } #[cfg(not(feature = "payouts"))] impl PayoutsInterface for KafkaStore {} #[cfg(feature = "payouts")] #[async_trait::async_trait] impl PayoutsInterface for KafkaStore { type Error = errors::StorageError; async fn find_payout_by_merchant_id_payout_id( &self, merchant_id: &id_type::MerchantId, payout_id: &id_type::PayoutId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Payouts, errors::StorageError> { self.diesel_store .find_payout_by_merchant_id_payout_id(merchant_id, payout_id, storage_scheme) .await } async fn update_payout( &self, this: &storage::Payouts, payout_update: storage::PayoutsUpdate, payout_attempt: &storage::PayoutAttempt, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Payouts, errors::StorageError> { let payout = self .diesel_store .update_payout(this, payout_update, payout_attempt, storage_scheme) .await?; if let Err(err) = self .kafka_producer .log_payout( &KafkaPayout::from_storage(&payout, payout_attempt), Some(KafkaPayout::from_storage(this, payout_attempt)), self.tenant_id.clone(), ) .await { logger::error!(message="Failed to update analytics entry for Payouts {payout:?}\n{payout_attempt:?}", error_message=?err); }; Ok(payout) } async fn insert_payout( &self, payout: storage::PayoutsNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Payouts, errors::StorageError> { self.diesel_store .insert_payout(payout, storage_scheme) .await } async fn find_optional_payout_by_merchant_id_payout_id( &self, merchant_id: &id_type::MerchantId, payout_id: &id_type::PayoutId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<storage::Payouts>, errors::StorageError> { self.diesel_store .find_optional_payout_by_merchant_id_payout_id(merchant_id, payout_id, storage_scheme) .await } #[cfg(feature = "olap")] async fn filter_payouts_by_constraints( &self, merchant_id: &id_type::MerchantId, filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::Payouts>, errors::StorageError> { self.diesel_store .filter_payouts_by_constraints(merchant_id, filters, storage_scheme) .await } #[cfg(feature = "olap")] async fn filter_payouts_and_attempts( &self, merchant_id: &id_type::MerchantId, filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> CustomResult< Vec<( storage::Payouts, storage::PayoutAttempt, Option<diesel_models::Customer>, Option<diesel_models::Address>, )>, errors::StorageError, > { self.diesel_store .filter_payouts_and_attempts(merchant_id, filters, storage_scheme) .await } #[cfg(feature = "olap")] async fn filter_payouts_by_time_range_constraints( &self, merchant_id: &id_type::MerchantId, time_range: &common_utils::types::TimeRange, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::Payouts>, errors::StorageError> { self.diesel_store .filter_payouts_by_time_range_constraints(merchant_id, time_range, storage_scheme) .await } #[cfg(feature = "olap")] async fn get_total_count_of_filtered_payouts( &self, merchant_id: &id_type::MerchantId, active_payout_ids: &[id_type::PayoutId], connector: Option<Vec<api_models::enums::PayoutConnectors>>, currency: Option<Vec<enums::Currency>>, status: Option<Vec<enums::PayoutStatus>>, payout_method: Option<Vec<enums::PayoutType>>, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .get_total_count_of_filtered_payouts( merchant_id, active_payout_ids, connector, currency, status, payout_method, ) .await } #[cfg(feature = "olap")] async fn filter_active_payout_ids_by_constraints( &self, merchant_id: &id_type::MerchantId, constraints: &hyperswitch_domain_models::payouts::PayoutFetchConstraints, ) -> CustomResult<Vec<id_type::PayoutId>, errors::StorageError> { self.diesel_store .filter_active_payout_ids_by_constraints(merchant_id, constraints) .await } } #[async_trait::async_trait] impl ProcessTrackerInterface for KafkaStore { async fn reinitialize_limbo_processes( &self, ids: Vec<String>, schedule_time: PrimitiveDateTime, ) -> CustomResult<usize, errors::StorageError> { self.diesel_store .reinitialize_limbo_processes(ids, schedule_time) .await } async fn find_process_by_id( &self, id: &str, ) -> CustomResult<Option<storage::ProcessTracker>, errors::StorageError> { self.diesel_store.find_process_by_id(id).await } async fn update_process( &self, this: storage::ProcessTracker, process: storage::ProcessTrackerUpdate, ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { self.diesel_store.update_process(this, process).await } async fn process_tracker_update_process_status_by_ids( &self, task_ids: Vec<String>, task_update: storage::ProcessTrackerUpdate, ) -> CustomResult<usize, errors::StorageError> { self.diesel_store .process_tracker_update_process_status_by_ids(task_ids, task_update) .await } async fn insert_process( &self, new: storage::ProcessTrackerNew, ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { self.diesel_store.insert_process(new).await } async fn reset_process( &self, this: storage::ProcessTracker, schedule_time: PrimitiveDateTime, ) -> CustomResult<(), errors::StorageError> { self.diesel_store.reset_process(this, schedule_time).await } async fn retry_process( &self, this: storage::ProcessTracker, schedule_time: PrimitiveDateTime, ) -> CustomResult<(), errors::StorageError> { self.diesel_store.retry_process(this, schedule_time).await } async fn finish_process_with_business_status( &self, this: storage::ProcessTracker, business_status: &'static str, ) -> CustomResult<(), errors::StorageError> { self.diesel_store .finish_process_with_business_status(this, business_status) .await } async fn find_processes_by_time_status( &self, time_lower_limit: PrimitiveDateTime, time_upper_limit: PrimitiveDateTime, status: ProcessTrackerStatus, limit: Option<i64>, ) -> CustomResult<Vec<storage::ProcessTracker>, errors::StorageError> { self.diesel_store .find_processes_by_time_status(time_lower_limit, time_upper_limit, status, limit) .await } } #[async_trait::async_trait] impl CaptureInterface for KafkaStore { async fn insert_capture( &self, capture: storage::CaptureNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Capture, errors::StorageError> { self.diesel_store .insert_capture(capture, storage_scheme) .await } async fn update_capture_with_capture_id( &self, this: storage::Capture, capture: storage::CaptureUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Capture, errors::StorageError> { self.diesel_store .update_capture_with_capture_id(this, capture, storage_scheme) .await } async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &self, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, authorized_attempt_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::Capture>, errors::StorageError> { self.diesel_store .find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( merchant_id, payment_id, authorized_attempt_id, storage_scheme, ) .await } } #[async_trait::async_trait] impl RefundInterface for KafkaStore { #[cfg(feature = "v1")] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { self.diesel_store .find_refund_by_internal_reference_id_merchant_id( internal_reference_id, merchant_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { self.diesel_store .find_refund_by_payment_id_merchant_id(payment_id, merchant_id, storage_scheme) .await } #[cfg(feature = "v1")] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &id_type::MerchantId, refund_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { self.diesel_store .find_refund_by_merchant_id_refund_id(merchant_id, refund_id, storage_scheme) .await } #[cfg(feature = "v1")] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &id_type::MerchantId, connector_refund_id: &str, connector: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { self.diesel_store .find_refund_by_merchant_id_connector_refund_id_connector( merchant_id, connector_refund_id, connector, storage_scheme, ) .await } async fn update_refund( &self, this: diesel_refund::Refund, refund: diesel_refund::RefundUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let refund = self .diesel_store .update_refund(this.clone(), refund, storage_scheme) .await?; if let Err(er) = self .kafka_producer .log_refund(&refund, Some(this), self.tenant_id.clone()) .await { logger::error!(message="Failed to insert analytics event for Refund Update {refund?}", error_message=?er); } Ok(refund) } async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &id_type::MerchantId, connector_transaction_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { self.diesel_store .find_refund_by_merchant_id_connector_transaction_id( merchant_id, connector_transaction_id, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_refund_by_id( &self, id: &id_type::GlobalRefundId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { self.diesel_store .find_refund_by_id(id, storage_scheme) .await } async fn insert_refund( &self, new: diesel_refund::RefundNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let refund = self.diesel_store.insert_refund(new, storage_scheme).await?; if let Err(er) = self .kafka_producer .log_refund(&refund, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to insert analytics event for Refund Create {refund?}", error_message=?er); } Ok(refund) } #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_refund_by_constraints( &self, merchant_id: &id_type::MerchantId, refund_details: &refunds::RefundListConstraints, storage_scheme: MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { self.diesel_store .filter_refund_by_constraints( merchant_id, refund_details, storage_scheme, limit, offset, ) .await } #[cfg(feature = "v2")] async fn filter_refund_by_constraints( &self, merchant_id: &id_type::MerchantId, refund_details: refunds::RefundListConstraints, storage_scheme: MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { self.diesel_store .filter_refund_by_constraints( merchant_id, refund_details, storage_scheme, limit, offset, ) .await } #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_refund_by_meta_constraints( &self, merchant_id: &id_type::MerchantId, refund_details: &common_utils::types::TimeRange, storage_scheme: MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> { self.diesel_store .filter_refund_by_meta_constraints(merchant_id, refund_details, storage_scheme) .await } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_refund_status_with_count( &self, merchant_id: &id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, constraints: &common_utils::types::TimeRange, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> { self.diesel_store .get_refund_status_with_count(merchant_id, profile_id_list, constraints, storage_scheme) .await } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_total_count_of_refunds( &self, merchant_id: &id_type::MerchantId, refund_details: &refunds::RefundListConstraints, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .get_total_count_of_refunds(merchant_id, refund_details, storage_scheme) .await } #[cfg(feature = "v2")] async fn get_total_count_of_refunds( &self, merchant_id: &id_type::MerchantId, refund_details: refunds::RefundListConstraints, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .get_total_count_of_refunds(merchant_id, refund_details, storage_scheme) .await } } #[async_trait::async_trait] impl MerchantKeyStoreInterface for KafkaStore { type Error = errors::StorageError; async fn insert_merchant_key_store( &self, state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { self.diesel_store .insert_merchant_key_store(state, merchant_key_store, key) .await } async fn get_merchant_key_store_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { self.diesel_store .get_merchant_key_store_by_merchant_id(state, merchant_id, key) .await } async fn delete_merchant_key_store_by_merchant_id( &self, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_merchant_key_store_by_merchant_id(merchant_id) .await } #[cfg(feature = "olap")] async fn list_multiple_key_stores( &self, state: &KeyManagerState, merchant_ids: Vec<id_type::MerchantId>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { self.diesel_store .list_multiple_key_stores(state, merchant_ids, key) .await } async fn get_all_key_stores( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { self.diesel_store .get_all_key_stores(state, key, from, to) .await } } #[async_trait::async_trait] impl ProfileInterface for KafkaStore { type Error = errors::StorageError; async fn insert_business_profile( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, business_profile: domain::Profile, ) -> CustomResult<domain::Profile, errors::StorageError> { self.diesel_store .insert_business_profile(key_manager_state, merchant_key_store, business_profile) .await } async fn find_business_profile_by_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &id_type::ProfileId, ) -> CustomResult<domain::Profile, errors::StorageError> { self.diesel_store .find_business_profile_by_profile_id(key_manager_state, merchant_key_store, profile_id) .await } async fn find_business_profile_by_merchant_id_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, ) -> CustomResult<domain::Profile, errors::StorageError> { self.diesel_store .find_business_profile_by_merchant_id_profile_id( key_manager_state, merchant_key_store, merchant_id, profile_id, ) .await } async fn update_profile_by_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, current_state: domain::Profile, business_profile_update: domain::ProfileUpdate, ) -> CustomResult<domain::Profile, errors::StorageError> { self.diesel_store .update_profile_by_profile_id( key_manager_state, merchant_key_store, current_state, business_profile_update, ) .await } async fn delete_profile_by_profile_id_merchant_id( &self, profile_id: &id_type::ProfileId, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_profile_by_profile_id_merchant_id(profile_id, merchant_id) .await } async fn list_profile_by_merchant_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, ) -> CustomResult<Vec<domain::Profile>, errors::StorageError> { self.diesel_store .list_profile_by_merchant_id(key_manager_state, merchant_key_store, merchant_id) .await } async fn find_business_profile_by_profile_name_merchant_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_name: &str, merchant_id: &id_type::MerchantId, ) -> CustomResult<domain::Profile, errors::StorageError> { self.diesel_store .find_business_profile_by_profile_name_merchant_id( key_manager_state, merchant_key_store, profile_name, merchant_id, ) .await } } #[async_trait::async_trait] impl ReverseLookupInterface for KafkaStore { async fn insert_reverse_lookup( &self, new: ReverseLookupNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { self.diesel_store .insert_reverse_lookup(new, storage_scheme) .await } async fn get_lookup_by_lookup_id( &self, id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { self.diesel_store .get_lookup_by_lookup_id(id, storage_scheme) .await } } #[async_trait::async_trait] impl RoutingAlgorithmInterface for KafkaStore { async fn insert_routing_algorithm( &self, routing_algorithm: storage::RoutingAlgorithm, ) -> CustomResult<storage::RoutingAlgorithm, errors::StorageError> { self.diesel_store .insert_routing_algorithm(routing_algorithm) .await } async fn find_routing_algorithm_by_profile_id_algorithm_id( &self, profile_id: &id_type::ProfileId, algorithm_id: &id_type::RoutingId, ) -> CustomResult<storage::RoutingAlgorithm, errors::StorageError> { self.diesel_store .find_routing_algorithm_by_profile_id_algorithm_id(profile_id, algorithm_id) .await } async fn find_routing_algorithm_by_algorithm_id_merchant_id( &self, algorithm_id: &id_type::RoutingId, merchant_id: &id_type::MerchantId, ) -> CustomResult<storage::RoutingAlgorithm, errors::StorageError> { self.diesel_store .find_routing_algorithm_by_algorithm_id_merchant_id(algorithm_id, merchant_id) .await } async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id( &self, algorithm_id: &id_type::RoutingId, profile_id: &id_type::ProfileId, ) -> CustomResult<storage::RoutingProfileMetadata, errors::StorageError> { self.diesel_store .find_routing_algorithm_metadata_by_algorithm_id_profile_id(algorithm_id, profile_id) .await } async fn list_routing_algorithm_metadata_by_profile_id( &self, profile_id: &id_type::ProfileId, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::RoutingProfileMetadata>, errors::StorageError> { self.diesel_store .list_routing_algorithm_metadata_by_profile_id(profile_id, limit, offset) .await } async fn list_routing_algorithm_metadata_by_merchant_id( &self, merchant_id: &id_type::MerchantId, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::RoutingProfileMetadata>, errors::StorageError> { self.diesel_store .list_routing_algorithm_metadata_by_merchant_id(merchant_id, limit, offset) .await } async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type( &self, merchant_id: &id_type::MerchantId, transaction_type: &enums::TransactionType, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::RoutingProfileMetadata>, errors::StorageError> { self.diesel_store .list_routing_algorithm_metadata_by_merchant_id_transaction_type( merchant_id, transaction_type, limit, offset, ) .await } } #[async_trait::async_trait] impl GsmInterface for KafkaStore { async fn add_gsm_rule( &self, rule: hyperswitch_domain_models::gsm::GatewayStatusMap, ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { self.diesel_store.add_gsm_rule(rule).await } async fn find_gsm_decision( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<String, errors::StorageError> { self.diesel_store .find_gsm_decision(connector, flow, sub_flow, code, message) .await } async fn find_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { self.diesel_store .find_gsm_rule(connector, flow, sub_flow, code, message) .await } async fn update_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, data: hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate, ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { self.diesel_store .update_gsm_rule(connector, flow, sub_flow, code, message, data) .await } async fn delete_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_gsm_rule(connector, flow, sub_flow, code, message) .await } } #[async_trait::async_trait] impl UnifiedTranslationsInterface for KafkaStore { async fn add_unfied_translation( &self, translation: storage::UnifiedTranslationsNew, ) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> { self.diesel_store.add_unfied_translation(translation).await } async fn find_translation( &self, unified_code: String, unified_message: String, locale: String, ) -> CustomResult<String, errors::StorageError> { self.diesel_store .find_translation(unified_code, unified_message, locale) .await } async fn update_translation( &self, unified_code: String, unified_message: String, locale: String, data: storage::UnifiedTranslationsUpdate, ) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> { self.diesel_store .update_translation(unified_code, unified_message, locale, data) .await } async fn delete_translation( &self, unified_code: String, unified_message: String, locale: String, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_translation(unified_code, unified_message, locale) .await } } #[async_trait::async_trait] impl StorageInterface for KafkaStore { fn get_scheduler_db(&self) -> Box<dyn SchedulerInterface> { Box::new(self.clone()) } fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface> { Box::new(self.clone()) } fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } fn get_subscription_store( &self, ) -> Box<dyn subscriptions::state::SubscriptionStorageInterface> { Box::new(self.clone()) } } impl GlobalStorageInterface for KafkaStore { fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } } impl AccountsStorageInterface for KafkaStore {} impl PaymentMethodsStorageInterface for KafkaStore {} impl subscriptions::state::SubscriptionStorageInterface for KafkaStore {} impl CommonStorageInterface for KafkaStore { fn get_storage_interface(&self) -> Box<dyn StorageInterface> { Box::new(self.clone()) } fn get_global_storage_interface(&self) -> Box<dyn GlobalStorageInterface> { Box::new(self.clone()) } fn get_accounts_storage_interface(&self) -> Box<dyn AccountsStorageInterface> { Box::new(self.clone()) } } #[async_trait::async_trait] impl SchedulerInterface for KafkaStore {} impl MasterKeyInterface for KafkaStore { fn get_master_key(&self) -> &[u8] { self.diesel_store.get_master_key() } } #[async_trait::async_trait] impl UserInterface for KafkaStore { async fn insert_user( &self, user_data: storage::UserNew, ) -> CustomResult<storage::User, errors::StorageError> { self.diesel_store.insert_user(user_data).await } async fn find_user_by_email( &self, user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { self.diesel_store.find_user_by_email(user_email).await } async fn find_user_by_id( &self, user_id: &str, ) -> CustomResult<storage::User, errors::StorageError> { self.diesel_store.find_user_by_id(user_id).await } async fn update_user_by_user_id( &self, user_id: &str, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { self.diesel_store .update_user_by_user_id(user_id, user) .await } async fn update_user_by_email( &self, user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { self.diesel_store .update_user_by_email(user_email, user) .await } async fn delete_user_by_user_id( &self, user_id: &str, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store.delete_user_by_user_id(user_id).await } async fn find_users_by_user_ids( &self, user_ids: Vec<String>, ) -> CustomResult<Vec<storage::User>, errors::StorageError> { self.diesel_store.find_users_by_user_ids(user_ids).await } } impl RedisConnInterface for KafkaStore { fn get_redis_conn(&self) -> CustomResult<Arc<RedisConnectionPool>, RedisError> { self.diesel_store.get_redis_conn() } } #[async_trait::async_trait] impl UserRoleInterface for KafkaStore { async fn insert_user_role( &self, user_role: storage::UserRoleNew, ) -> CustomResult<user_storage::UserRole, errors::StorageError> { self.diesel_store.insert_user_role(user_role).await } async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { self.diesel_store .find_user_role_by_user_id_and_lineage( user_id, tenant_id, org_id, merchant_id, profile_id, version, ) .await } async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, update: user_storage::UserRoleUpdate, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { self.diesel_store .update_user_role_by_user_id_and_lineage( user_id, tenant_id, org_id, merchant_id, profile_id, update, version, ) .await } async fn delete_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { self.diesel_store .delete_user_role_by_user_id_and_lineage( user_id, tenant_id, org_id, merchant_id, profile_id, version, ) .await } async fn list_user_roles_by_user_id<'a>( &self, payload: ListUserRolesByUserIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { self.diesel_store.list_user_roles_by_user_id(payload).await } async fn list_user_roles_by_user_id_across_tenants( &self, user_id: &str, limit: Option<u32>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { self.diesel_store .list_user_roles_by_user_id_across_tenants(user_id, limit) .await } async fn list_user_roles_by_org_id<'a>( &self, payload: ListUserRolesByOrgIdPayload<'a>, ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> { self.diesel_store.list_user_roles_by_org_id(payload).await } } #[async_trait::async_trait] impl DashboardMetadataInterface for KafkaStore { async fn insert_metadata( &self, metadata: storage::DashboardMetadataNew, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { self.diesel_store.insert_metadata(metadata).await } async fn update_metadata( &self, user_id: Option<String>, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_key: enums::DashboardMetadata, dashboard_metadata_update: storage::DashboardMetadataUpdate, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { self.diesel_store .update_metadata( user_id, merchant_id, org_id, data_key, dashboard_metadata_update, ) .await } async fn find_user_scoped_dashboard_metadata( &self, user_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { self.diesel_store .find_user_scoped_dashboard_metadata(user_id, merchant_id, org_id, data_keys) .await } async fn find_merchant_scoped_dashboard_metadata( &self, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { self.diesel_store .find_merchant_scoped_dashboard_metadata(merchant_id, org_id, data_keys) .await } async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( &self, user_id: &str, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_all_user_scoped_dashboard_metadata_by_merchant_id(user_id, merchant_id) .await } async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &self, user_id: &str, merchant_id: &id_type::MerchantId, data_key: enums::DashboardMetadata, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { self.diesel_store .delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( user_id, merchant_id, data_key, ) .await } } #[async_trait::async_trait] impl BatchSampleDataInterface for KafkaStore { #[cfg(feature = "v1")] async fn insert_payment_intents_batch_for_sample_data( &self, state: &KeyManagerState, batch: Vec<hyperswitch_domain_models::payments::PaymentIntent>, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, ) -> CustomResult< Vec<hyperswitch_domain_models::payments::PaymentIntent>, storage_impl::errors::StorageError, > { let payment_intents_list = self .diesel_store .insert_payment_intents_batch_for_sample_data(state, batch, key_store) .await?; for payment_intent in payment_intents_list.iter() { let _ = self .kafka_producer .log_payment_intent( payment_intent, None, self.tenant_id.clone(), state.infra_values.clone(), ) .await; } Ok(payment_intents_list) } #[cfg(feature = "v1")] async fn insert_payment_attempts_batch_for_sample_data( &self, batch: Vec<diesel_models::user::sample_data::PaymentAttemptBatchNew>, ) -> CustomResult< Vec<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>, storage_impl::errors::StorageError, > { let payment_attempts_list = self .diesel_store .insert_payment_attempts_batch_for_sample_data(batch) .await?; for payment_attempt in payment_attempts_list.iter() { let _ = self .kafka_producer .log_payment_attempt(payment_attempt, None, self.tenant_id.clone()) .await; } Ok(payment_attempts_list) } #[cfg(feature = "v1")] async fn insert_refunds_batch_for_sample_data( &self, batch: Vec<diesel_models::RefundNew>, ) -> CustomResult<Vec<diesel_models::Refund>, storage_impl::errors::StorageError> { let refunds_list = self .diesel_store .insert_refunds_batch_for_sample_data(batch) .await?; for refund in refunds_list.iter() { let _ = self .kafka_producer .log_refund(refund, None, self.tenant_id.clone()) .await; } Ok(refunds_list) } #[cfg(feature = "v1")] async fn insert_disputes_batch_for_sample_data( &self, batch: Vec<diesel_models::DisputeNew>, ) -> CustomResult<Vec<diesel_models::Dispute>, storage_impl::errors::StorageError> { let disputes_list = self .diesel_store .insert_disputes_batch_for_sample_data(batch) .await?; for dispute in disputes_list.iter() { let _ = self .kafka_producer .log_dispute(dispute, None, self.tenant_id.clone()) .await; } Ok(disputes_list) } #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, ) -> CustomResult< Vec<hyperswitch_domain_models::payments::PaymentIntent>, storage_impl::errors::StorageError, > { let payment_intents_list = self .diesel_store .delete_payment_intents_for_sample_data(state, merchant_id, key_store) .await?; for payment_intent in payment_intents_list.iter() { let _ = self .kafka_producer .log_payment_intent_delete( payment_intent, self.tenant_id.clone(), state.infra_values.clone(), ) .await; } Ok(payment_intents_list) } #[cfg(feature = "v1")] async fn delete_payment_attempts_for_sample_data( &self, merchant_id: &id_type::MerchantId, ) -> CustomResult< Vec<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>, storage_impl::errors::StorageError, > { let payment_attempts_list = self .diesel_store .delete_payment_attempts_for_sample_data(merchant_id) .await?; for payment_attempt in payment_attempts_list.iter() { let _ = self .kafka_producer .log_payment_attempt_delete(payment_attempt, self.tenant_id.clone()) .await; } Ok(payment_attempts_list) } #[cfg(feature = "v1")] async fn delete_refunds_for_sample_data( &self, merchant_id: &id_type::MerchantId, ) -> CustomResult<Vec<diesel_models::Refund>, storage_impl::errors::StorageError> { let refunds_list = self .diesel_store .delete_refunds_for_sample_data(merchant_id) .await?; for refund in refunds_list.iter() { let _ = self .kafka_producer .log_refund_delete(refund, self.tenant_id.clone()) .await; } Ok(refunds_list) } #[cfg(feature = "v1")] async fn delete_disputes_for_sample_data( &self, merchant_id: &id_type::MerchantId, ) -> CustomResult<Vec<diesel_models::Dispute>, storage_impl::errors::StorageError> { let disputes_list = self .diesel_store .delete_disputes_for_sample_data(merchant_id) .await?; for dispute in disputes_list.iter() { let _ = self .kafka_producer .log_dispute_delete(dispute, self.tenant_id.clone()) .await; } Ok(disputes_list) } } #[async_trait::async_trait] impl AuthorizationInterface for KafkaStore { async fn insert_authorization( &self, authorization: storage::AuthorizationNew, ) -> CustomResult<storage::Authorization, errors::StorageError> { self.diesel_store.insert_authorization(authorization).await } async fn find_all_authorizations_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, ) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> { self.diesel_store .find_all_authorizations_by_merchant_id_payment_id(merchant_id, payment_id) .await } async fn update_authorization_by_merchant_id_authorization_id( &self, merchant_id: id_type::MerchantId, authorization_id: String, authorization: storage::AuthorizationUpdate, ) -> CustomResult<storage::Authorization, errors::StorageError> { self.diesel_store .update_authorization_by_merchant_id_authorization_id( merchant_id, authorization_id, authorization, ) .await } } #[async_trait::async_trait] impl AuthenticationInterface for KafkaStore { async fn insert_authentication( &self, authentication: storage::AuthenticationNew, ) -> CustomResult<storage::Authentication, errors::StorageError> { let auth = self .diesel_store .insert_authentication(authentication) .await?; if let Err(er) = self .kafka_producer .log_authentication(&auth, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for authentication {auth:?}", error_message=?er) } Ok(auth) } async fn find_authentication_by_merchant_id_authentication_id( &self, merchant_id: &id_type::MerchantId, authentication_id: &id_type::AuthenticationId, ) -> CustomResult<storage::Authentication, errors::StorageError> { self.diesel_store .find_authentication_by_merchant_id_authentication_id(merchant_id, authentication_id) .await } async fn find_authentication_by_merchant_id_connector_authentication_id( &self, merchant_id: id_type::MerchantId, connector_authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError> { self.diesel_store .find_authentication_by_merchant_id_connector_authentication_id( merchant_id, connector_authentication_id, ) .await } async fn update_authentication_by_merchant_id_authentication_id( &self, previous_state: storage::Authentication, authentication_update: storage::AuthenticationUpdate, ) -> CustomResult<storage::Authentication, errors::StorageError> { let auth = self .diesel_store .update_authentication_by_merchant_id_authentication_id( previous_state.clone(), authentication_update, ) .await?; if let Err(er) = self .kafka_producer .log_authentication(&auth, Some(previous_state.clone()), self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for authentication {auth:?}", error_message=?er) } Ok(auth) } } #[async_trait::async_trait] impl HealthCheckDbInterface for KafkaStore { async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> { self.diesel_store.health_check_db().await } } #[async_trait::async_trait] impl RoleInterface for KafkaStore { async fn insert_role( &self, role: storage::RoleNew, ) -> CustomResult<storage::Role, errors::StorageError> { self.diesel_store.insert_role(role).await } async fn find_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { self.diesel_store.find_role_by_role_id(role_id).await } async fn find_role_by_role_id_in_lineage( &self, role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, profile_id: &id_type::ProfileId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { self.diesel_store .find_role_by_role_id_in_lineage(role_id, merchant_id, org_id, profile_id, tenant_id) .await } async fn find_by_role_id_org_id_tenant_id( &self, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { self.diesel_store .find_by_role_id_org_id_tenant_id(role_id, org_id, tenant_id) .await } async fn update_role_by_role_id( &self, role_id: &str, role_update: storage::RoleUpdate, ) -> CustomResult<storage::Role, errors::StorageError> { self.diesel_store .update_role_by_role_id(role_id, role_update) .await } async fn delete_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { self.diesel_store.delete_role_by_role_id(role_id).await } //TODO: Remove once generic_list_roles_by_entity_type is stable async fn list_roles_for_org_by_parameters( &self, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, entity_type: Option<enums::EntityType>, limit: Option<u32>, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { self.diesel_store .list_roles_for_org_by_parameters(tenant_id, org_id, merchant_id, entity_type, limit) .await } async fn generic_list_roles_by_entity_type( &self, payload: diesel_models::role::ListRolesByEntityPayload, is_lineage_data_required: bool, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { self.diesel_store .generic_list_roles_by_entity_type(payload, is_lineage_data_required, tenant_id, org_id) .await } } #[async_trait::async_trait] impl GenericLinkInterface for KafkaStore { async fn find_generic_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::GenericLinkState, errors::StorageError> { self.diesel_store .find_generic_link_by_link_id(link_id) .await } async fn find_pm_collect_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> { self.diesel_store .find_pm_collect_link_by_link_id(link_id) .await } async fn find_payout_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { self.diesel_store.find_payout_link_by_link_id(link_id).await } async fn insert_generic_link( &self, generic_link: storage::GenericLinkNew, ) -> CustomResult<storage::GenericLinkState, errors::StorageError> { self.diesel_store.insert_generic_link(generic_link).await } async fn insert_pm_collect_link( &self, pm_collect_link: storage::GenericLinkNew, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> { self.diesel_store .insert_pm_collect_link(pm_collect_link) .await } async fn insert_payout_link( &self, pm_collect_link: storage::GenericLinkNew, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { self.diesel_store.insert_payout_link(pm_collect_link).await } async fn update_payout_link( &self, payout_link: storage::PayoutLink, payout_link_update: storage::PayoutLinkUpdate, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { self.diesel_store .update_payout_link(payout_link, payout_link_update) .await } } #[async_trait::async_trait] impl UserKeyStoreInterface for KafkaStore { async fn insert_user_key_store( &self, state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { self.diesel_store .insert_user_key_store(state, user_key_store, key) .await } async fn get_user_key_store_by_user_id( &self, state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { self.diesel_store .get_user_key_store_by_user_id(state, user_id, key) .await } async fn get_all_user_key_store( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, limit: u32, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { self.diesel_store .get_all_user_key_store(state, key, from, limit) .await } } #[async_trait::async_trait] impl UserAuthenticationMethodInterface for KafkaStore { async fn insert_user_authentication_method( &self, user_authentication_method: storage::UserAuthenticationMethodNew, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { self.diesel_store .insert_user_authentication_method(user_authentication_method) .await } async fn get_user_authentication_method_by_id( &self, id: &str, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { self.diesel_store .get_user_authentication_method_by_id(id) .await } async fn list_user_authentication_methods_for_auth_id( &self, auth_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { self.diesel_store .list_user_authentication_methods_for_auth_id(auth_id) .await } async fn list_user_authentication_methods_for_owner_id( &self, owner_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { self.diesel_store .list_user_authentication_methods_for_owner_id(owner_id) .await } async fn update_user_authentication_method( &self, id: &str, user_authentication_method_update: storage::UserAuthenticationMethodUpdate, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { self.diesel_store .update_user_authentication_method(id, user_authentication_method_update) .await } async fn list_user_authentication_methods_for_email_domain( &self, email_domain: &str, ) -> CustomResult< Vec<diesel_models::user_authentication_method::UserAuthenticationMethod>, errors::StorageError, > { self.diesel_store .list_user_authentication_methods_for_email_domain(email_domain) .await } } #[async_trait::async_trait] impl HyperswitchAiInteractionInterface for KafkaStore { async fn insert_hyperswitch_ai_interaction( &self, hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew, ) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError> { self.diesel_store .insert_hyperswitch_ai_interaction(hyperswitch_ai_interaction) .await } async fn list_hyperswitch_ai_interactions( &self, merchant_id: Option<id_type::MerchantId>, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError> { self.diesel_store .list_hyperswitch_ai_interactions(merchant_id, limit, offset) .await } } #[async_trait::async_trait] impl ThemeInterface for KafkaStore { async fn insert_theme( &self, theme: storage::theme::ThemeNew, ) -> CustomResult<storage::theme::Theme, errors::StorageError> { self.diesel_store.insert_theme(theme).await } async fn find_theme_by_theme_id( &self, theme_id: String, ) -> CustomResult<storage::theme::Theme, errors::StorageError> { self.diesel_store.find_theme_by_theme_id(theme_id).await } async fn find_most_specific_theme_in_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<diesel_models::user::theme::Theme, errors::StorageError> { self.diesel_store .find_most_specific_theme_in_lineage(lineage) .await } async fn find_theme_by_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::theme::Theme, errors::StorageError> { self.diesel_store.find_theme_by_lineage(lineage).await } async fn update_theme_by_theme_id( &self, theme_id: String, theme_update: diesel_models::user::theme::ThemeUpdate, ) -> CustomResult<diesel_models::user::theme::Theme, errors::StorageError> { self.diesel_store .update_theme_by_theme_id(theme_id, theme_update) .await } async fn delete_theme_by_theme_id( &self, theme_id: String, ) -> CustomResult<storage::theme::Theme, errors::StorageError> { self.diesel_store.delete_theme_by_theme_id(theme_id).await } async fn list_themes_at_and_under_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<Vec<storage::theme::Theme>, errors::StorageError> { self.diesel_store .list_themes_at_and_under_lineage(lineage) .await } } #[async_trait::async_trait] #[cfg(feature = "v2")] impl db::payment_method_session::PaymentMethodsSessionInterface for KafkaStore { async fn insert_payment_methods_session( &self, state: &KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, validity: i64, ) -> CustomResult<(), errors::StorageError> { self.diesel_store .insert_payment_methods_session(state, key_store, payment_methods_session, validity) .await } async fn get_payment_methods_session( &self, state: &KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, id: &id_type::GlobalPaymentMethodSessionId, ) -> CustomResult< hyperswitch_domain_models::payment_methods::PaymentMethodSession, errors::StorageError, > { self.diesel_store .get_payment_methods_session(state, key_store, id) .await } async fn update_payment_method_session( &self, state: &KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, id: &id_type::GlobalPaymentMethodSessionId, payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum, current_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, ) -> CustomResult< hyperswitch_domain_models::payment_methods::PaymentMethodSession, errors::StorageError, > { self.diesel_store .update_payment_method_session( state, key_store, id, payment_methods_session, current_session, ) .await } } #[async_trait::async_trait] #[cfg(feature = "v1")] impl db::payment_method_session::PaymentMethodsSessionInterface for KafkaStore {} #[async_trait::async_trait] impl CallbackMapperInterface for KafkaStore { #[instrument(skip_all)] async fn insert_call_back_mapper( &self, call_back_mapper: domain::CallbackMapper, ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { self.diesel_store .insert_call_back_mapper(call_back_mapper) .await } #[instrument(skip_all)] async fn find_call_back_mapper_by_id( &self, id: &str, ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { self.diesel_store.find_call_back_mapper_by_id(id).await } } #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[async_trait::async_trait] impl TokenizationInterface for KafkaStore { async fn insert_tokenization( &self, tokenization: hyperswitch_domain_models::tokenization::Tokenization, merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { self.diesel_store .insert_tokenization(tokenization, merchant_key_store, key_manager_state) .await } async fn get_entity_id_vault_id_by_token_id( &self, token: &id_type::GlobalTokenId, merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { self.diesel_store .get_entity_id_vault_id_by_token_id(token, merchant_key_store, key_manager_state) .await } async fn update_tokenization_record( &self, tokenization: hyperswitch_domain_models::tokenization::Tokenization, tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate, merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { self.diesel_store .update_tokenization_record( tokenization, tokenization_update, merchant_key_store, key_manager_state, ) .await } } #[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] impl TokenizationInterface for KafkaStore {} #[async_trait::async_trait] impl InvoiceInterface for KafkaStore { type Error = errors::StorageError; #[instrument(skip_all)] async fn insert_invoice_entry( &self, state: &KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, invoice_new: DomainInvoice, ) -> CustomResult<DomainInvoice, errors::StorageError> { self.diesel_store .insert_invoice_entry(state, key_store, invoice_new) .await } #[instrument(skip_all)] async fn find_invoice_by_invoice_id( &self, state: &KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, invoice_id: String, ) -> CustomResult<DomainInvoice, errors::StorageError> { self.diesel_store .find_invoice_by_invoice_id(state, key_store, invoice_id) .await } #[instrument(skip_all)] async fn update_invoice_entry( &self, state: &KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, invoice_id: String, data: DomainInvoiceUpdate, ) -> CustomResult<DomainInvoice, errors::StorageError> { self.diesel_store .update_invoice_entry(state, key_store, invoice_id, data) .await } #[instrument(skip_all)] async fn get_latest_invoice_for_subscription( &self, state: &KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, subscription_id: String, ) -> CustomResult<DomainInvoice, errors::StorageError> { self.diesel_store .get_latest_invoice_for_subscription(state, key_store, subscription_id) .await } #[instrument(skip_all)] async fn find_invoice_by_subscription_id_connector_invoice_id( &self, state: &KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, subscription_id: String, connector_invoice_id: id_type::InvoiceId, ) -> CustomResult<Option<DomainInvoice>, errors::StorageError> { self.diesel_store .find_invoice_by_subscription_id_connector_invoice_id( state, key_store, subscription_id, connector_invoice_id, ) .await } } #[async_trait::async_trait] impl SubscriptionInterface for KafkaStore { type Error = errors::StorageError; #[instrument(skip_all)] async fn insert_subscription_entry( &self, state: &KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, subscription_new: DomainSubscription, ) -> CustomResult<DomainSubscription, errors::StorageError> { self.diesel_store .insert_subscription_entry(state, key_store, subscription_new) .await } #[instrument(skip_all)] async fn find_by_merchant_id_subscription_id( &self, state: &KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, merchant_id: &id_type::MerchantId, subscription_id: String, ) -> CustomResult<DomainSubscription, errors::StorageError> { self.diesel_store .find_by_merchant_id_subscription_id(state, key_store, merchant_id, subscription_id) .await } #[instrument(skip_all)] async fn update_subscription_entry( &self, state: &KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, merchant_id: &id_type::MerchantId, subscription_id: String, data: DomainSubscriptionUpdate, ) -> CustomResult<DomainSubscription, errors::StorageError> { self.diesel_store .update_subscription_entry(state, key_store, merchant_id, subscription_id, data) .await } }
crates/router/src/db/kafka_store.rs
router::src::db::kafka_store
32,969
true
// File: crates/router/src/db/user_key_store.rs // Module: router::src::db::user_key_store use common_utils::{ errors::CustomResult, types::keymanager::{self, KeyManagerState}, }; use error_stack::{report, ResultExt}; use masking::Secret; use router_env::{instrument, tracing}; use storage_impl::MockDb; use crate::{ connection, core::errors, services::Store, types::domain::{ self, behaviour::{Conversion, ReverseConversion}, }, }; #[async_trait::async_trait] pub trait UserKeyStoreInterface { async fn insert_user_key_store( &self, state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError>; async fn get_user_key_store_by_user_id( &self, state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError>; async fn get_all_user_key_store( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, limit: u32, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError>; } #[async_trait::async_trait] impl UserKeyStoreInterface for Store { #[instrument(skip_all)] async fn insert_user_key_store( &self, state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let user_id = user_key_store.user_id.clone(); user_key_store .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert(state, key, keymanager::Identifier::User(user_id)) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn get_user_key_store_by_user_id( &self, state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_models::user_key_store::UserKeyStore::find_by_user_id(&conn, user_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert(state, key, keymanager::Identifier::User(user_id.to_owned())) .await .change_context(errors::StorageError::DecryptionError) } async fn get_all_user_key_store( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, limit: u32, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let key_stores = diesel_models::user_key_store::UserKeyStore::get_all_user_key_stores( &conn, from, limit, ) .await .map_err(|err| report!(errors::StorageError::from(err)))?; futures::future::try_join_all(key_stores.into_iter().map(|key_store| async { let user_id = key_store.user_id.clone(); key_store .convert(state, key, keymanager::Identifier::User(user_id)) .await .change_context(errors::StorageError::DecryptionError) })) .await } } #[async_trait::async_trait] impl UserKeyStoreInterface for MockDb { #[instrument(skip_all)] async fn insert_user_key_store( &self, state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { let mut locked_user_key_store = self.user_key_store.lock().await; if locked_user_key_store .iter() .any(|user_key| user_key.user_id == user_key_store.user_id) { Err(errors::StorageError::DuplicateValue { entity: "user_key_store", key: Some(user_key_store.user_id.clone()), })?; } let user_key_store = Conversion::convert(user_key_store) .await .change_context(errors::StorageError::MockDbError)?; locked_user_key_store.push(user_key_store.clone()); let user_id = user_key_store.user_id.clone(); user_key_store .convert(state, key, keymanager::Identifier::User(user_id)) .await .change_context(errors::StorageError::DecryptionError) } async fn get_all_user_key_store( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, _from: u32, _limit: u32, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { let user_key_store = self.user_key_store.lock().await; futures::future::try_join_all(user_key_store.iter().map(|user_key| async { let user_id = user_key.user_id.clone(); user_key .to_owned() .convert(state, key, keymanager::Identifier::User(user_id)) .await .change_context(errors::StorageError::DecryptionError) })) .await } #[instrument(skip_all)] async fn get_user_key_store_by_user_id( &self, state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { self.user_key_store .lock() .await .iter() .find(|user_key_store| user_key_store.user_id == user_id) .cloned() .ok_or(errors::StorageError::ValueNotFound(format!( "No user_key_store is found for user_id={user_id}", )))? .convert(state, key, keymanager::Identifier::User(user_id.to_owned())) .await .change_context(errors::StorageError::DecryptionError) } }
crates/router/src/db/user_key_store.rs
router::src::db::user_key_store
1,448
true
// File: crates/router/src/db/ephemeral_key.rs // Module: router::src::db::ephemeral_key #[cfg(feature = "v2")] use common_utils::id_type; use time::ext::NumericalDuration; #[cfg(feature = "v2")] use crate::types::storage::ephemeral_key::{ClientSecretType, ClientSecretTypeNew}; use crate::{ core::errors::{self, CustomResult}, db::MockDb, types::storage::ephemeral_key::{EphemeralKey, EphemeralKeyNew}, }; #[async_trait::async_trait] pub trait EphemeralKeyInterface { #[cfg(feature = "v1")] async fn create_ephemeral_key( &self, _ek: EphemeralKeyNew, _validity: i64, ) -> CustomResult<EphemeralKey, errors::StorageError>; #[cfg(feature = "v1")] async fn get_ephemeral_key( &self, _key: &str, ) -> CustomResult<EphemeralKey, errors::StorageError>; #[cfg(feature = "v1")] async fn delete_ephemeral_key( &self, _id: &str, ) -> CustomResult<EphemeralKey, errors::StorageError>; } #[async_trait::async_trait] pub trait ClientSecretInterface { #[cfg(feature = "v2")] async fn create_client_secret( &self, _ek: ClientSecretTypeNew, _validity: i64, ) -> CustomResult<ClientSecretType, errors::StorageError>; #[cfg(feature = "v2")] async fn get_client_secret( &self, _key: &str, ) -> CustomResult<ClientSecretType, errors::StorageError>; #[cfg(feature = "v2")] async fn delete_client_secret( &self, _id: &str, ) -> CustomResult<ClientSecretType, errors::StorageError>; } mod storage { use common_utils::date_time; #[cfg(feature = "v2")] use common_utils::id_type; use error_stack::ResultExt; #[cfg(feature = "v2")] use masking::PeekInterface; #[cfg(feature = "v2")] use redis_interface::errors::RedisError; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::RedisConnInterface; use time::ext::NumericalDuration; use super::{ClientSecretInterface, EphemeralKeyInterface}; #[cfg(feature = "v2")] use crate::types::storage::ephemeral_key::{ClientSecretType, ClientSecretTypeNew}; use crate::{ core::errors::{self, CustomResult}, services::Store, types::storage::ephemeral_key::{EphemeralKey, EphemeralKeyNew}, }; #[async_trait::async_trait] impl EphemeralKeyInterface for Store { #[cfg(feature = "v1")] #[instrument(skip_all)] async fn create_ephemeral_key( &self, new: EphemeralKeyNew, validity: i64, ) -> CustomResult<EphemeralKey, errors::StorageError> { let secret_key = format!("epkey_{}", &new.secret); let id_key = format!("epkey_{}", &new.id); let created_at = date_time::now(); let expires = created_at.saturating_add(validity.hours()); let created_ek = EphemeralKey { id: new.id, created_at: created_at.assume_utc().unix_timestamp(), expires: expires.assume_utc().unix_timestamp(), customer_id: new.customer_id, merchant_id: new.merchant_id, secret: new.secret, }; match self .get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .serialize_and_set_multiple_hash_field_if_not_exist( &[ (&secret_key.as_str().into(), &created_ek), (&id_key.as_str().into(), &created_ek), ], "ephkey", None, ) .await { Ok(v) if v.contains(&HsetnxReply::KeyNotSet) => { Err(errors::StorageError::DuplicateValue { entity: "ephemeral key", key: None, } .into()) } Ok(_) => { let expire_at = expires.assume_utc().unix_timestamp(); self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .set_expire_at(&secret_key.into(), expire_at) .await .change_context(errors::StorageError::KVError)?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .set_expire_at(&id_key.into(), expire_at) .await .change_context(errors::StorageError::KVError)?; Ok(created_ek) } Err(er) => Err(er).change_context(errors::StorageError::KVError), } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn get_ephemeral_key( &self, key: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { let key = format!("epkey_{key}"); self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .get_hash_field_and_deserialize(&key.into(), "ephkey", "EphemeralKey") .await .change_context(errors::StorageError::KVError) } #[cfg(feature = "v1")] async fn delete_ephemeral_key( &self, id: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { let ek = self.get_ephemeral_key(id).await?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .delete_key(&format!("epkey_{}", &ek.id).into()) .await .change_context(errors::StorageError::KVError)?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .delete_key(&format!("epkey_{}", &ek.secret).into()) .await .change_context(errors::StorageError::KVError)?; Ok(ek) } } #[async_trait::async_trait] impl ClientSecretInterface for Store { #[cfg(feature = "v2")] #[instrument(skip_all)] async fn create_client_secret( &self, new: ClientSecretTypeNew, validity: i64, ) -> CustomResult<ClientSecretType, errors::StorageError> { let created_at = date_time::now(); let expires = created_at.saturating_add(validity.hours()); let id_key = new.id.generate_redis_key(); let created_client_secret = ClientSecretType { id: new.id, created_at, expires, merchant_id: new.merchant_id, secret: new.secret, resource_id: new.resource_id, }; let secret_key = created_client_secret.generate_secret_key(); match self .get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .serialize_and_set_multiple_hash_field_if_not_exist( &[ (&secret_key.as_str().into(), &created_client_secret), (&id_key.as_str().into(), &created_client_secret), ], "csh", None, ) .await { Ok(v) if v.contains(&HsetnxReply::KeyNotSet) => { Err(errors::StorageError::DuplicateValue { entity: "ephemeral key", key: None, } .into()) } Ok(_) => { let expire_at = expires.assume_utc().unix_timestamp(); self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .set_expire_at(&secret_key.into(), expire_at) .await .change_context(errors::StorageError::KVError)?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .set_expire_at(&id_key.into(), expire_at) .await .change_context(errors::StorageError::KVError)?; Ok(created_client_secret) } Err(er) => Err(er).change_context(errors::StorageError::KVError), } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn get_client_secret( &self, key: &str, ) -> CustomResult<ClientSecretType, errors::StorageError> { let key = format!("cs_{key}"); self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .get_hash_field_and_deserialize(&key.into(), "csh", "ClientSecretType") .await .change_context(errors::StorageError::KVError) } #[cfg(feature = "v2")] async fn delete_client_secret( &self, id: &str, ) -> CustomResult<ClientSecretType, errors::StorageError> { let client_secret = self.get_client_secret(id).await?; let redis_id_key = client_secret.id.generate_redis_key(); let secret_key = client_secret.generate_secret_key(); self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .delete_key(&redis_id_key.as_str().into()) .await .map_err(|err| match err.current_context() { RedisError::NotFound => { err.change_context(errors::StorageError::ValueNotFound(redis_id_key)) } _ => err.change_context(errors::StorageError::KVError), })?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .delete_key(&secret_key.as_str().into()) .await .map_err(|err| match err.current_context() { RedisError::NotFound => { err.change_context(errors::StorageError::ValueNotFound(secret_key)) } _ => err.change_context(errors::StorageError::KVError), })?; Ok(client_secret) } } } #[async_trait::async_trait] impl EphemeralKeyInterface for MockDb { #[cfg(feature = "v1")] async fn create_ephemeral_key( &self, ek: EphemeralKeyNew, validity: i64, ) -> CustomResult<EphemeralKey, errors::StorageError> { let mut ephemeral_keys = self.ephemeral_keys.lock().await; let created_at = common_utils::date_time::now(); let expires = created_at.saturating_add(validity.hours()); let ephemeral_key = EphemeralKey { id: ek.id, merchant_id: ek.merchant_id, customer_id: ek.customer_id, created_at: created_at.assume_utc().unix_timestamp(), expires: expires.assume_utc().unix_timestamp(), secret: ek.secret, }; ephemeral_keys.push(ephemeral_key.clone()); Ok(ephemeral_key) } #[cfg(feature = "v1")] async fn get_ephemeral_key( &self, key: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { match self .ephemeral_keys .lock() .await .iter() .find(|ephemeral_key| ephemeral_key.secret.eq(key)) { Some(ephemeral_key) => Ok(ephemeral_key.clone()), None => Err( errors::StorageError::ValueNotFound("ephemeral key not found".to_string()).into(), ), } } #[cfg(feature = "v1")] async fn delete_ephemeral_key( &self, id: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { let mut ephemeral_keys = self.ephemeral_keys.lock().await; if let Some(pos) = ephemeral_keys.iter().position(|x| (*x.id).eq(id)) { let ek = ephemeral_keys.remove(pos); Ok(ek) } else { return Err( errors::StorageError::ValueNotFound("ephemeral key not found".to_string()).into(), ); } } } #[async_trait::async_trait] impl ClientSecretInterface for MockDb { #[cfg(feature = "v2")] async fn create_client_secret( &self, new: ClientSecretTypeNew, validity: i64, ) -> CustomResult<ClientSecretType, errors::StorageError> { todo!() } #[cfg(feature = "v2")] async fn get_client_secret( &self, key: &str, ) -> CustomResult<ClientSecretType, errors::StorageError> { todo!() } #[cfg(feature = "v2")] async fn delete_client_secret( &self, id: &str, ) -> CustomResult<ClientSecretType, errors::StorageError> { todo!() } }
crates/router/src/db/ephemeral_key.rs
router::src::db::ephemeral_key
2,878
true
// File: crates/router/src/db/reverse_lookup.rs // Module: router::src::db::reverse_lookup use super::{MockDb, Store}; use crate::{ errors::{self, CustomResult}, types::storage::{ enums, reverse_lookup::{ReverseLookup, ReverseLookupNew}, }, }; #[async_trait::async_trait] pub trait ReverseLookupInterface { async fn insert_reverse_lookup( &self, _new: ReverseLookupNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError>; async fn get_lookup_by_lookup_id( &self, _id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError>; } #[cfg(not(feature = "kv_store"))] mod storage { use error_stack::report; use router_env::{instrument, tracing}; use super::{ReverseLookupInterface, Store}; use crate::{ connection, errors::{self, CustomResult}, types::storage::{ enums, reverse_lookup::{ReverseLookup, ReverseLookupNew}, }, }; #[async_trait::async_trait] impl ReverseLookupInterface for Store { #[instrument(skip_all)] async fn insert_reverse_lookup( &self, new: ReverseLookupNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn get_lookup_by_lookup_id( &self, id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; ReverseLookup::find_by_lookup_id(id, &conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } } } #[cfg(feature = "kv_store")] mod storage { use error_stack::{report, ResultExt}; use redis_interface::SetnxReply; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::{ decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey, }; use super::{ReverseLookupInterface, Store}; use crate::{ connection, core::errors::utils::RedisErrorExt, errors::{self, CustomResult}, types::storage::{ enums, kv, reverse_lookup::{ReverseLookup, ReverseLookupNew}, }, utils::db_utils, }; #[async_trait::async_trait] impl ReverseLookupInterface for Store { #[instrument(skip_all)] async fn insert_reverse_lookup( &self, new: ReverseLookupNew, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, ReverseLookup>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } enums::MerchantStorageScheme::RedisKv => { let created_rev_lookup = ReverseLookup { lookup_id: new.lookup_id.clone(), sk_id: new.sk_id.clone(), pk_id: new.pk_id.clone(), source: new.source.clone(), updated_by: storage_scheme.to_string(), }; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::ReverseLookUp(new)), }, }; match Box::pin(kv_wrapper::<ReverseLookup, _, _>( self, KvOperation::SetNx(&created_rev_lookup, redis_entry), PartitionKey::CombinationKey { combination: &format!( "reverse_lookup_{}", &created_rev_lookup.lookup_id ), }, )) .await .map_err(|err| err.to_redis_failed_response(&created_rev_lookup.lookup_id))? .try_into_setnx() { Ok(SetnxReply::KeySet) => Ok(created_rev_lookup), Ok(SetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "reverse_lookup", key: Some(created_rev_lookup.lookup_id.clone()), } .into()), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } } } #[instrument(skip_all)] async fn get_lookup_by_lookup_id( &self, id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; ReverseLookup::find_by_lookup_id(id, &conn) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, ReverseLookup>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let redis_fut = async { Box::pin(kv_wrapper( self, KvOperation::<ReverseLookup>::Get, PartitionKey::CombinationKey { combination: &format!("reverse_lookup_{id}"), }, )) .await? .try_into_get() }; Box::pin(db_utils::try_redis_get_else_try_database_get( redis_fut, database_call, )) .await } } } } } #[async_trait::async_trait] impl ReverseLookupInterface for MockDb { async fn insert_reverse_lookup( &self, new: ReverseLookupNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let reverse_lookup_insert = ReverseLookup::from(new); self.reverse_lookups .lock() .await .push(reverse_lookup_insert.clone()); Ok(reverse_lookup_insert) } async fn get_lookup_by_lookup_id( &self, lookup_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { self.reverse_lookups .lock() .await .iter() .find(|reverse_lookup| reverse_lookup.lookup_id == lookup_id) .ok_or( errors::StorageError::ValueNotFound(format!( "No reverse lookup found for lookup_id = {lookup_id}", )) .into(), ) .cloned() } }
crates/router/src/db/reverse_lookup.rs
router::src::db::reverse_lookup
1,542
true
// File: crates/router/src/db/relay.rs // Module: router::src::db::relay use common_utils::types::keymanager::KeyManagerState; use diesel_models; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::behaviour::{Conversion, ReverseConversion}; use storage_impl::MockDb; use super::domain; use crate::{ connection, core::errors::{self, CustomResult}, db::kafka_store::KafkaStore, services::Store, }; #[async_trait::async_trait] pub trait RelayInterface { async fn insert_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, new: hyperswitch_domain_models::relay::Relay, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>; async fn update_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, current_state: hyperswitch_domain_models::relay::Relay, relay_update: hyperswitch_domain_models::relay::RelayUpdate, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>; async fn find_relay_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, relay_id: &common_utils::id_type::RelayId, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>; async fn find_relay_by_profile_id_connector_reference_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, connector_reference_id: &str, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>; } #[async_trait::async_trait] impl RelayInterface for Store { async fn insert_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, new: hyperswitch_domain_models::relay::Relay, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn update_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, current_state: hyperswitch_domain_models::relay::Relay, relay_update: hyperswitch_domain_models::relay::RelayUpdate, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; Conversion::convert(current_state) .await .change_context(errors::StorageError::EncryptionError)? .update( &conn, diesel_models::relay::RelayUpdateInternal::from(relay_update), ) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_relay_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, relay_id: &common_utils::id_type::RelayId, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_models::relay::Relay::find_by_id(&conn, relay_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_relay_by_profile_id_connector_reference_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, connector_reference_id: &str, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_models::relay::Relay::find_by_profile_id_connector_reference_id( &conn, profile_id, connector_reference_id, ) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } } #[async_trait::async_trait] impl RelayInterface for MockDb { async fn insert_relay( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &domain::MerchantKeyStore, _new: hyperswitch_domain_models::relay::Relay, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_relay( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &domain::MerchantKeyStore, _current_state: hyperswitch_domain_models::relay::Relay, _relay_update: hyperswitch_domain_models::relay::RelayUpdate, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_relay_by_id( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &domain::MerchantKeyStore, _relay_id: &common_utils::id_type::RelayId, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_relay_by_profile_id_connector_reference_id( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &domain::MerchantKeyStore, _profile_id: &common_utils::id_type::ProfileId, _connector_reference_id: &str, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[async_trait::async_trait] impl RelayInterface for KafkaStore { async fn insert_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, new: hyperswitch_domain_models::relay::Relay, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { self.diesel_store .insert_relay(key_manager_state, merchant_key_store, new) .await } async fn update_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, current_state: hyperswitch_domain_models::relay::Relay, relay_update: hyperswitch_domain_models::relay::RelayUpdate, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { self.diesel_store .update_relay( key_manager_state, merchant_key_store, current_state, relay_update, ) .await } async fn find_relay_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, relay_id: &common_utils::id_type::RelayId, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { self.diesel_store .find_relay_by_id(key_manager_state, merchant_key_store, relay_id) .await } async fn find_relay_by_profile_id_connector_reference_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, connector_reference_id: &str, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { self.diesel_store .find_relay_by_profile_id_connector_reference_id( key_manager_state, merchant_key_store, profile_id, connector_reference_id, ) .await } }
crates/router/src/db/relay.rs
router::src::db::relay
2,072
true
// File: crates/router/src/db/mandate.rs // Module: router::src::db::mandate use common_utils::id_type; use super::MockDb; use crate::{ core::errors::{self, CustomResult}, types::storage::{self as storage_types, enums::MerchantStorageScheme}, }; #[async_trait::async_trait] pub trait MandateInterface { async fn find_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError>; async fn find_mandate_by_merchant_id_connector_mandate_id( &self, merchant_id: &id_type::MerchantId, connector_mandate_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError>; async fn find_mandate_by_merchant_id_customer_id( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError>; // Fix this function once we move to mandate v2 #[cfg(feature = "v2")] async fn find_mandate_by_global_customer_id( &self, id: &id_type::GlobalCustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError>; async fn update_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, mandate_update: storage_types::MandateUpdate, mandate: storage_types::Mandate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError>; async fn find_mandates_by_merchant_id( &self, merchant_id: &id_type::MerchantId, mandate_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError>; async fn insert_mandate( &self, mandate: storage_types::MandateNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError>; } #[cfg(feature = "kv_store")] mod storage { use common_utils::{fallback_reverse_lookup_not_found, id_type}; use diesel_models::kv; use error_stack::{report, ResultExt}; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::{ decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey, }; use super::MandateInterface; use crate::{ connection, core::errors::{self, utils::RedisErrorExt, CustomResult}, db::reverse_lookup::ReverseLookupInterface, services::Store, types::storage::{self as storage_types, enums::MerchantStorageScheme, MandateDbExt}, utils::db_utils, }; #[async_trait::async_trait] impl MandateInterface for Store { #[instrument(skip_all)] async fn find_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Mandate::find_by_merchant_id_mandate_id( &conn, merchant_id, mandate_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdMandateId { merchant_id, mandate_id, }; let field = format!("mandate_{mandate_id}"); Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Mandate>::HGet(&field), key, )) .await? .try_into_hget() }, database_call, )) .await } } } #[instrument(skip_all)] async fn find_mandate_by_merchant_id_connector_mandate_id( &self, merchant_id: &id_type::MerchantId, connector_mandate_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Mandate::find_by_merchant_id_connector_mandate_id( &conn, merchant_id, connector_mandate_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let lookup_id = format!( "mid_{}_conn_mandate_{}", merchant_id.get_string_repr(), connector_mandate_id ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Mandate>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, database_call, )) .await } } } #[instrument(skip_all)] async fn find_mandate_by_merchant_id_customer_id( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_merchant_id_customer_id(&conn, merchant_id, customer_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_mandate_by_global_customer_id( &self, id: &id_type::GlobalCustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_global_customer_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, mandate_update: storage_types::MandateUpdate, mandate: storage_types::Mandate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let key = PartitionKey::MerchantIdMandateId { merchant_id, mandate_id, }; let field = format!("mandate_{mandate_id}"); let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>( self, storage_scheme, Op::Update(key.clone(), &field, mandate.updated_by.as_deref()), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { storage_types::Mandate::update_by_merchant_id_mandate_id( &conn, merchant_id, mandate_id, mandate_update.convert_to_mandate_update(storage_scheme), ) .await .map_err(|error| report!(errors::StorageError::from(error))) } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); if let diesel_models::MandateUpdate::ConnectorMandateIdUpdate { connector_mandate_id: Some(val), .. } = &mandate_update { let rev_lookup = diesel_models::ReverseLookupNew { sk_id: field.clone(), pk_id: key_str.clone(), lookup_id: format!( "mid_{}_conn_mandate_{}", merchant_id.get_string_repr(), val ), source: "mandate".to_string(), updated_by: storage_scheme.to_string(), }; self.insert_reverse_lookup(rev_lookup, storage_scheme) .await?; } let m_update = mandate_update.convert_to_mandate_update(storage_scheme); let updated_mandate = m_update.clone().apply_changeset(mandate.clone()); let redis_value = serde_json::to_string(&updated_mandate) .change_context(errors::StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::MandateUpdate( kv::MandateUpdateMems { orig: mandate, update_data: m_update, }, )), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<diesel_models::Mandate>::Hset( (&field, redis_value), redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(updated_mandate) } } } #[instrument(skip_all)] async fn find_mandates_by_merchant_id( &self, merchant_id: &id_type::MerchantId, mandate_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::filter_by_constraints(&conn, merchant_id, mandate_constraints) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_mandate( &self, mut mandate: storage_types::MandateNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>( self, storage_scheme, Op::Insert, )) .await; mandate.update_storage_scheme(storage_scheme); match storage_scheme { MerchantStorageScheme::PostgresOnly => mandate .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))), MerchantStorageScheme::RedisKv => { let mandate_id = mandate.mandate_id.clone(); let merchant_id = &mandate.merchant_id.to_owned(); let connector_mandate_id = mandate.connector_mandate_id.clone(); let key = PartitionKey::MerchantIdMandateId { merchant_id, mandate_id: mandate_id.as_str(), }; let key_str = key.to_string(); let field = format!("mandate_{mandate_id}"); let storage_mandate = storage_types::Mandate::from(&mandate); let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::Mandate(mandate)), }, }; if let Some(connector_val) = connector_mandate_id { let lookup_id = format!( "mid_{}_conn_mandate_{}", merchant_id.get_string_repr(), connector_val ); let reverse_lookup_entry = diesel_models::ReverseLookupNew { sk_id: field.clone(), pk_id: key_str.clone(), lookup_id, source: "mandate".to_string(), updated_by: storage_scheme.to_string(), }; self.insert_reverse_lookup(reverse_lookup_entry, storage_scheme) .await?; } match Box::pin(kv_wrapper::<diesel_models::Mandate, _, _>( self, KvOperation::<diesel_models::Mandate>::HSetNx( &field, &storage_mandate, redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "mandate", key: Some(storage_mandate.mandate_id), } .into()), Ok(HsetnxReply::KeySet) => Ok(storage_mandate), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } } } } } #[cfg(not(feature = "kv_store"))] mod storage { use common_utils::id_type; use error_stack::report; use router_env::{instrument, tracing}; use super::MandateInterface; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, types::storage::{self as storage_types, enums::MerchantStorageScheme, MandateDbExt}, }; #[async_trait::async_trait] impl MandateInterface for Store { #[instrument(skip_all)] async fn find_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_merchant_id_mandate_id(&conn, merchant_id, mandate_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_mandate_by_merchant_id_connector_mandate_id( &self, merchant_id: &id_type::MerchantId, connector_mandate_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_merchant_id_connector_mandate_id( &conn, merchant_id, connector_mandate_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_mandate_by_merchant_id_customer_id( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_merchant_id_customer_id(&conn, merchant_id, customer_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } // Need to fix this once we start moving to mandate v2 #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_mandate_by_global_customer_id( &self, customer_id: &id_type::GlobalCustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_global_id(&conn, customer_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, mandate_update: storage_types::MandateUpdate, _mandate: storage_types::Mandate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Mandate::update_by_merchant_id_mandate_id( &conn, merchant_id, mandate_id, storage_types::MandateUpdateInternal::from(mandate_update), ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_mandates_by_merchant_id( &self, merchant_id: &id_type::MerchantId, mandate_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::filter_by_constraints(&conn, merchant_id, mandate_constraints) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_mandate( &self, mandate: storage_types::MandateNew, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; mandate .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } } } #[async_trait::async_trait] impl MandateInterface for MockDb { async fn find_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { self.mandates .lock() .await .iter() .find(|mandate| mandate.merchant_id == *merchant_id && mandate.mandate_id == mandate_id) .cloned() .ok_or_else(|| errors::StorageError::ValueNotFound("mandate not found".to_string())) .map_err(|err| err.into()) } async fn find_mandate_by_merchant_id_connector_mandate_id( &self, merchant_id: &id_type::MerchantId, connector_mandate_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { self.mandates .lock() .await .iter() .find(|mandate| { mandate.merchant_id == *merchant_id && mandate.connector_mandate_id == Some(connector_mandate_id.to_string()) }) .cloned() .ok_or_else(|| errors::StorageError::ValueNotFound("mandate not found".to_string())) .map_err(|err| err.into()) } async fn find_mandate_by_merchant_id_customer_id( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { return Ok(self .mandates .lock() .await .iter() .filter(|mandate| { mandate.merchant_id == *merchant_id && &mandate.customer_id == customer_id }) .cloned() .collect()); } // Need to fix this once we move to v2 mandate #[cfg(feature = "v2")] async fn find_mandate_by_global_customer_id( &self, id: &id_type::GlobalCustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { todo!() } async fn update_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, mandate_update: storage_types::MandateUpdate, _mandate: storage_types::Mandate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let mut mandates = self.mandates.lock().await; match mandates .iter_mut() .find(|mandate| mandate.merchant_id == *merchant_id && mandate.mandate_id == mandate_id) { Some(mandate) => { let m_update = diesel_models::MandateUpdateInternal::from(mandate_update); let updated_mandate = m_update.clone().apply_changeset(mandate.clone()); Ok(updated_mandate) } None => { Err(errors::StorageError::ValueNotFound("mandate not found".to_string()).into()) } } } async fn find_mandates_by_merchant_id( &self, merchant_id: &id_type::MerchantId, mandate_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let mandates = self.mandates.lock().await; let mandates_iter = mandates.iter().filter(|mandate| { let mut checker = mandate.merchant_id == *merchant_id; if let Some(created_time) = mandate_constraints.created_time { checker &= mandate.created_at == created_time; } if let Some(created_time_lt) = mandate_constraints.created_time_lt { checker &= mandate.created_at < created_time_lt; } if let Some(created_time_gt) = mandate_constraints.created_time_gt { checker &= mandate.created_at > created_time_gt; } if let Some(created_time_lte) = mandate_constraints.created_time_lte { checker &= mandate.created_at <= created_time_lte; } if let Some(created_time_gte) = mandate_constraints.created_time_gte { checker &= mandate.created_at >= created_time_gte; } if let Some(connector) = &mandate_constraints.connector { checker &= mandate.connector == *connector; } if let Some(mandate_status) = mandate_constraints.mandate_status { checker &= mandate.mandate_status == mandate_status; } checker }); #[allow(clippy::as_conversions)] let offset = (if mandate_constraints.offset.unwrap_or(0) < 0 { 0 } else { mandate_constraints.offset.unwrap_or(0) }) as usize; let mandates: Vec<storage_types::Mandate> = if let Some(limit) = mandate_constraints.limit { #[allow(clippy::as_conversions)] mandates_iter .skip(offset) .take((if limit < 0 { 0 } else { limit }) as usize) .cloned() .collect() } else { mandates_iter.skip(offset).cloned().collect() }; Ok(mandates) } async fn insert_mandate( &self, mandate_new: storage_types::MandateNew, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let mut mandates = self.mandates.lock().await; let customer_user_agent_extended = mandate_new.get_customer_user_agent_extended(); let mandate = storage_types::Mandate { mandate_id: mandate_new.mandate_id.clone(), customer_id: mandate_new.customer_id, merchant_id: mandate_new.merchant_id, original_payment_id: mandate_new.original_payment_id, payment_method_id: mandate_new.payment_method_id, mandate_status: mandate_new.mandate_status, mandate_type: mandate_new.mandate_type, customer_accepted_at: mandate_new.customer_accepted_at, customer_ip_address: mandate_new.customer_ip_address, customer_user_agent: None, network_transaction_id: mandate_new.network_transaction_id, previous_attempt_id: mandate_new.previous_attempt_id, created_at: mandate_new .created_at .unwrap_or_else(common_utils::date_time::now), mandate_amount: mandate_new.mandate_amount, mandate_currency: mandate_new.mandate_currency, amount_captured: mandate_new.amount_captured, connector: mandate_new.connector, connector_mandate_id: mandate_new.connector_mandate_id, start_date: mandate_new.start_date, end_date: mandate_new.end_date, metadata: mandate_new.metadata, connector_mandate_ids: mandate_new.connector_mandate_ids, merchant_connector_id: mandate_new.merchant_connector_id, updated_by: mandate_new.updated_by, customer_user_agent_extended, }; mandates.push(mandate.clone()); Ok(mandate) } }
crates/router/src/db/mandate.rs
router::src::db::mandate
5,738
true
// File: crates/router/src/db/capture.rs // Module: router::src::db::capture use router_env::{instrument, tracing}; use super::MockDb; use crate::{ core::errors::{self, CustomResult}, types::storage::{self as types, enums}, }; #[async_trait::async_trait] pub trait CaptureInterface { async fn insert_capture( &self, capture: types::CaptureNew, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<types::Capture, errors::StorageError>; async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, authorized_attempt_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<types::Capture>, errors::StorageError>; async fn update_capture_with_capture_id( &self, this: types::Capture, capture: types::CaptureUpdate, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<types::Capture, errors::StorageError>; } #[cfg(feature = "kv_store")] mod storage { use error_stack::report; use router_env::{instrument, tracing}; use super::CaptureInterface; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, types::storage::{capture::*, enums}, }; #[async_trait::async_trait] impl CaptureInterface for Store { #[instrument(skip_all)] async fn insert_capture( &self, capture: CaptureNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Capture, errors::StorageError> { let db_call = || async { let conn = connection::pg_connection_write(self).await?; capture .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) }; db_call().await } #[instrument(skip_all)] async fn update_capture_with_capture_id( &self, this: Capture, capture: CaptureUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Capture, errors::StorageError> { let db_call = || async { let conn = connection::pg_connection_write(self).await?; this.update_with_capture_id(&conn, capture) .await .map_err(|error| report!(errors::StorageError::from(error))) }; db_call().await } #[instrument(skip_all)] async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, authorized_attempt_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<Capture>, errors::StorageError> { let db_call = || async { let conn = connection::pg_connection_read(self).await?; Capture::find_all_by_merchant_id_payment_id_authorized_attempt_id( merchant_id, payment_id, authorized_attempt_id, &conn, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; db_call().await } } } #[cfg(not(feature = "kv_store"))] mod storage { use error_stack::report; use router_env::{instrument, tracing}; use super::CaptureInterface; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, types::storage::{capture::*, enums}, }; #[async_trait::async_trait] impl CaptureInterface for Store { #[instrument(skip_all)] async fn insert_capture( &self, capture: CaptureNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Capture, errors::StorageError> { let db_call = || async { let conn = connection::pg_connection_write(self).await?; capture .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) }; db_call().await } #[instrument(skip_all)] async fn update_capture_with_capture_id( &self, this: Capture, capture: CaptureUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Capture, errors::StorageError> { let db_call = || async { let conn = connection::pg_connection_write(self).await?; this.update_with_capture_id(&conn, capture) .await .map_err(|error| report!(errors::StorageError::from(error))) }; db_call().await } #[instrument(skip_all)] async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, authorized_attempt_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<Capture>, errors::StorageError> { let db_call = || async { let conn = connection::pg_connection_read(self).await?; Capture::find_all_by_merchant_id_payment_id_authorized_attempt_id( merchant_id, payment_id, authorized_attempt_id, &conn, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; db_call().await } } } #[async_trait::async_trait] impl CaptureInterface for MockDb { async fn insert_capture( &self, capture: types::CaptureNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<types::Capture, errors::StorageError> { let mut captures = self.captures.lock().await; let capture = types::Capture { capture_id: capture.capture_id, payment_id: capture.payment_id, merchant_id: capture.merchant_id, status: capture.status, amount: capture.amount, currency: capture.currency, connector: capture.connector, error_message: capture.error_message, error_code: capture.error_code, error_reason: capture.error_reason, tax_amount: capture.tax_amount, created_at: capture.created_at, modified_at: capture.modified_at, authorized_attempt_id: capture.authorized_attempt_id, capture_sequence: capture.capture_sequence, connector_capture_id: capture.connector_capture_id, connector_response_reference_id: capture.connector_response_reference_id, processor_capture_data: capture.processor_capture_data, // Below fields are deprecated. Please add any new fields above this line. connector_capture_data: None, }; captures.push(capture.clone()); Ok(capture) } #[instrument(skip_all)] async fn update_capture_with_capture_id( &self, _this: types::Capture, _capture: types::CaptureUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<types::Capture, errors::StorageError> { //Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _payment_id: &common_utils::id_type::PaymentId, _authorized_attempt_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<types::Capture>, errors::StorageError> { //Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } }
crates/router/src/db/capture.rs
router::src::db::capture
1,702
true
// File: crates/router/src/db/authorization.rs // Module: router::src::db::authorization use diesel_models::authorization::AuthorizationUpdateInternal; use error_stack::report; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait AuthorizationInterface { async fn insert_authorization( &self, authorization: storage::AuthorizationNew, ) -> CustomResult<storage::Authorization, errors::StorageError>; async fn find_all_authorizations_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Authorization>, errors::StorageError>; async fn update_authorization_by_merchant_id_authorization_id( &self, merchant_id: common_utils::id_type::MerchantId, authorization_id: String, authorization: storage::AuthorizationUpdate, ) -> CustomResult<storage::Authorization, errors::StorageError>; } #[async_trait::async_trait] impl AuthorizationInterface for Store { #[instrument(skip_all)] async fn insert_authorization( &self, authorization: storage::AuthorizationNew, ) -> CustomResult<storage::Authorization, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; authorization .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_all_authorizations_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Authorization::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_authorization_by_merchant_id_authorization_id( &self, merchant_id: common_utils::id_type::MerchantId, authorization_id: String, authorization: storage::AuthorizationUpdate, ) -> CustomResult<storage::Authorization, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Authorization::update_by_merchant_id_authorization_id( &conn, merchant_id, authorization_id, authorization, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl AuthorizationInterface for MockDb { async fn insert_authorization( &self, authorization: storage::AuthorizationNew, ) -> CustomResult<storage::Authorization, errors::StorageError> { let mut authorizations = self.authorizations.lock().await; if authorizations.iter().any(|authorization_inner| { authorization_inner.authorization_id == authorization.authorization_id }) { Err(errors::StorageError::DuplicateValue { entity: "authorization_id", key: None, })? } let authorization = storage::Authorization { authorization_id: authorization.authorization_id, merchant_id: authorization.merchant_id, payment_id: authorization.payment_id, amount: authorization.amount, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), status: authorization.status, error_code: authorization.error_code, error_message: authorization.error_message, connector_authorization_id: authorization.connector_authorization_id, previously_authorized_amount: authorization.previously_authorized_amount, }; authorizations.push(authorization.clone()); Ok(authorization) } async fn find_all_authorizations_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> { let authorizations = self.authorizations.lock().await; let authorizations_found: Vec<storage::Authorization> = authorizations .iter() .filter(|a| a.merchant_id == *merchant_id && a.payment_id == *payment_id) .cloned() .collect(); Ok(authorizations_found) } async fn update_authorization_by_merchant_id_authorization_id( &self, merchant_id: common_utils::id_type::MerchantId, authorization_id: String, authorization_update: storage::AuthorizationUpdate, ) -> CustomResult<storage::Authorization, errors::StorageError> { let mut authorizations = self.authorizations.lock().await; authorizations .iter_mut() .find(|authorization| authorization.authorization_id == authorization_id && authorization.merchant_id == merchant_id) .map(|authorization| { let authorization_updated = AuthorizationUpdateInternal::from(authorization_update) .create_authorization(authorization.clone()); *authorization = authorization_updated.clone(); authorization_updated }) .ok_or( errors::StorageError::ValueNotFound(format!( "cannot find authorization for authorization_id = {authorization_id} and merchant_id = {merchant_id:?}" )) .into(), ) } }
crates/router/src/db/authorization.rs
router::src::db::authorization
1,179
true
// File: crates/router/src/db/user_authentication_method.rs // Module: router::src::db::user_authentication_method use diesel_models::user_authentication_method as storage; use error_stack::report; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait UserAuthenticationMethodInterface { async fn insert_user_authentication_method( &self, user_authentication_method: storage::UserAuthenticationMethodNew, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>; async fn get_user_authentication_method_by_id( &self, id: &str, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>; async fn list_user_authentication_methods_for_auth_id( &self, auth_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError>; async fn list_user_authentication_methods_for_owner_id( &self, owner_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError>; async fn update_user_authentication_method( &self, id: &str, user_authentication_method_update: storage::UserAuthenticationMethodUpdate, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>; async fn list_user_authentication_methods_for_email_domain( &self, email_domain: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError>; } #[async_trait::async_trait] impl UserAuthenticationMethodInterface for Store { #[instrument(skip_all)] async fn insert_user_authentication_method( &self, user_authentication_method: storage::UserAuthenticationMethodNew, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; user_authentication_method .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn get_user_authentication_method_by_id( &self, id: &str, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserAuthenticationMethod::get_user_authentication_method_by_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_user_authentication_methods_for_auth_id( &self, auth_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserAuthenticationMethod::list_user_authentication_methods_for_auth_id( &conn, auth_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_user_authentication_methods_for_owner_id( &self, owner_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserAuthenticationMethod::list_user_authentication_methods_for_owner_id( &conn, owner_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_user_authentication_method( &self, id: &str, user_authentication_method_update: storage::UserAuthenticationMethodUpdate, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::UserAuthenticationMethod::update_user_authentication_method( &conn, id, user_authentication_method_update, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_user_authentication_methods_for_email_domain( &self, email_domain: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserAuthenticationMethod::list_user_authentication_methods_for_email_domain( &conn, email_domain, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl UserAuthenticationMethodInterface for MockDb { async fn insert_user_authentication_method( &self, user_authentication_method: storage::UserAuthenticationMethodNew, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let mut user_authentication_methods = self.user_authentication_methods.lock().await; let existing_auth_id = user_authentication_methods .iter() .find(|uam| uam.owner_id == user_authentication_method.owner_id) .map(|uam| uam.auth_id.clone()); let auth_id = existing_auth_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); let user_authentication_method = storage::UserAuthenticationMethod { id: uuid::Uuid::new_v4().to_string(), auth_id, owner_id: user_authentication_method.auth_id, owner_type: user_authentication_method.owner_type, auth_type: user_authentication_method.auth_type, public_config: user_authentication_method.public_config, private_config: user_authentication_method.private_config, allow_signup: user_authentication_method.allow_signup, created_at: user_authentication_method.created_at, last_modified_at: user_authentication_method.last_modified_at, email_domain: user_authentication_method.email_domain, }; user_authentication_methods.push(user_authentication_method.clone()); Ok(user_authentication_method) } #[instrument(skip_all)] async fn get_user_authentication_method_by_id( &self, id: &str, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let user_authentication_methods = self.user_authentication_methods.lock().await; let user_authentication_method = user_authentication_methods .iter() .find(|&auth_method_inner| auth_method_inner.id == id); if let Some(user_authentication_method) = user_authentication_method { Ok(user_authentication_method.to_owned()) } else { return Err(errors::StorageError::ValueNotFound(format!( "No user authentication method found for id = {id}", )) .into()); } } async fn list_user_authentication_methods_for_auth_id( &self, auth_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let user_authentication_methods = self.user_authentication_methods.lock().await; let user_authentication_methods_list: Vec<_> = user_authentication_methods .iter() .filter(|auth_method_inner| auth_method_inner.auth_id == auth_id) .cloned() .collect(); if user_authentication_methods_list.is_empty() { return Err(errors::StorageError::ValueNotFound(format!( "No user authentication method found for auth_id = {auth_id}", )) .into()); } Ok(user_authentication_methods_list) } async fn list_user_authentication_methods_for_owner_id( &self, owner_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let user_authentication_methods = self.user_authentication_methods.lock().await; let user_authentication_methods_list: Vec<_> = user_authentication_methods .iter() .filter(|auth_method_inner| auth_method_inner.owner_id == owner_id) .cloned() .collect(); if user_authentication_methods_list.is_empty() { return Err(errors::StorageError::ValueNotFound(format!( "No user authentication method found for owner_id = {owner_id}", )) .into()); } Ok(user_authentication_methods_list) } async fn update_user_authentication_method( &self, id: &str, user_authentication_method_update: storage::UserAuthenticationMethodUpdate, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let mut user_authentication_methods = self.user_authentication_methods.lock().await; user_authentication_methods .iter_mut() .find(|auth_method_inner| auth_method_inner.id == id) .map(|auth_method_inner| { *auth_method_inner = match user_authentication_method_update { storage::UserAuthenticationMethodUpdate::UpdateConfig { private_config, public_config, } => storage::UserAuthenticationMethod { private_config, public_config, last_modified_at: common_utils::date_time::now(), ..auth_method_inner.to_owned() }, storage::UserAuthenticationMethodUpdate::EmailDomain { email_domain } => { storage::UserAuthenticationMethod { email_domain: email_domain.to_owned(), last_modified_at: common_utils::date_time::now(), ..auth_method_inner.to_owned() } } }; auth_method_inner.to_owned() }) .ok_or( errors::StorageError::ValueNotFound(format!( "No authentication method available for the id = {id}" )) .into(), ) } #[instrument(skip_all)] async fn list_user_authentication_methods_for_email_domain( &self, email_domain: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let user_authentication_methods = self.user_authentication_methods.lock().await; let user_authentication_methods_list: Vec<_> = user_authentication_methods .iter() .filter(|auth_method_inner| auth_method_inner.email_domain == email_domain) .cloned() .collect(); Ok(user_authentication_methods_list) } }
crates/router/src/db/user_authentication_method.rs
router::src::db::user_authentication_method
2,117
true
// File: crates/router/src/db/file.rs // Module: router::src::db::file use error_stack::report; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait FileMetadataInterface { async fn insert_file_metadata( &self, file: storage::FileMetadataNew, ) -> CustomResult<storage::FileMetadata, errors::StorageError>; async fn find_file_metadata_by_merchant_id_file_id( &self, merchant_id: &common_utils::id_type::MerchantId, file_id: &str, ) -> CustomResult<storage::FileMetadata, errors::StorageError>; async fn delete_file_metadata_by_merchant_id_file_id( &self, merchant_id: &common_utils::id_type::MerchantId, file_id: &str, ) -> CustomResult<bool, errors::StorageError>; async fn update_file_metadata( &self, this: storage::FileMetadata, file_metadata: storage::FileMetadataUpdate, ) -> CustomResult<storage::FileMetadata, errors::StorageError>; } #[async_trait::async_trait] impl FileMetadataInterface for Store { #[instrument(skip_all)] async fn insert_file_metadata( &self, file: storage::FileMetadataNew, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; file.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_file_metadata_by_merchant_id_file_id( &self, merchant_id: &common_utils::id_type::MerchantId, file_id: &str, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::FileMetadata::find_by_merchant_id_file_id(&conn, merchant_id, file_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_file_metadata_by_merchant_id_file_id( &self, merchant_id: &common_utils::id_type::MerchantId, file_id: &str, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::FileMetadata::delete_by_merchant_id_file_id(&conn, merchant_id, file_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_file_metadata( &self, this: storage::FileMetadata, file_metadata: storage::FileMetadataUpdate, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update(&conn, file_metadata) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl FileMetadataInterface for MockDb { async fn insert_file_metadata( &self, _file: storage::FileMetadataNew, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn find_file_metadata_by_merchant_id_file_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _file_id: &str, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn delete_file_metadata_by_merchant_id_file_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _file_id: &str, ) -> CustomResult<bool, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn update_file_metadata( &self, _this: storage::FileMetadata, _file_metadata: storage::FileMetadataUpdate, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } }
crates/router/src/db/file.rs
router::src::db::file
1,003
true
// File: crates/router/src/db/user/theme.rs // Module: router::src::db::user::theme use common_utils::types::user::ThemeLineage; use diesel_models::user::theme::{self as storage, ThemeUpdate}; use error_stack::report; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait ThemeInterface { async fn insert_theme( &self, theme: storage::ThemeNew, ) -> CustomResult<storage::Theme, errors::StorageError>; async fn find_theme_by_theme_id( &self, theme_id: String, ) -> CustomResult<storage::Theme, errors::StorageError>; async fn find_most_specific_theme_in_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError>; async fn find_theme_by_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError>; async fn update_theme_by_theme_id( &self, theme_id: String, theme_update: ThemeUpdate, ) -> CustomResult<storage::Theme, errors::StorageError>; async fn delete_theme_by_theme_id( &self, theme_id: String, ) -> CustomResult<storage::Theme, errors::StorageError>; async fn list_themes_at_and_under_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<Vec<storage::Theme>, errors::StorageError>; } #[async_trait::async_trait] impl ThemeInterface for Store { async fn insert_theme( &self, theme: storage::ThemeNew, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; theme .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_theme_by_theme_id( &self, theme_id: String, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Theme::find_by_theme_id(&conn, theme_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_most_specific_theme_in_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Theme::find_most_specific_theme_in_lineage(&conn, lineage) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_theme_by_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Theme::find_by_lineage(&conn, lineage) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn update_theme_by_theme_id( &self, theme_id: String, theme_update: ThemeUpdate, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Theme::update_by_theme_id(&conn, theme_id, theme_update) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn delete_theme_by_theme_id( &self, theme_id: String, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Theme::delete_by_theme_id(&conn, theme_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn list_themes_at_and_under_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<Vec<storage::Theme>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Theme::find_all_by_lineage_hierarchy(&conn, lineage) .await .map_err(|error| report!(errors::StorageError::from(error))) } } fn check_theme_with_lineage(theme: &storage::Theme, lineage: &ThemeLineage) -> bool { match lineage { ThemeLineage::Tenant { tenant_id } => { &theme.tenant_id == tenant_id && theme.org_id.is_none() && theme.merchant_id.is_none() && theme.profile_id.is_none() } ThemeLineage::Organization { tenant_id, org_id } => { &theme.tenant_id == tenant_id && theme .org_id .as_ref() .is_some_and(|org_id_inner| org_id_inner == org_id) && theme.merchant_id.is_none() && theme.profile_id.is_none() } ThemeLineage::Merchant { tenant_id, org_id, merchant_id, } => { &theme.tenant_id == tenant_id && theme .org_id .as_ref() .is_some_and(|org_id_inner| org_id_inner == org_id) && theme .merchant_id .as_ref() .is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id) && theme.profile_id.is_none() } ThemeLineage::Profile { tenant_id, org_id, merchant_id, profile_id, } => { &theme.tenant_id == tenant_id && theme .org_id .as_ref() .is_some_and(|org_id_inner| org_id_inner == org_id) && theme .merchant_id .as_ref() .is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id) && theme .profile_id .as_ref() .is_some_and(|profile_id_inner| profile_id_inner == profile_id) } } } fn check_theme_belongs_to_lineage_hierarchy( theme: &storage::Theme, lineage: &ThemeLineage, ) -> bool { match lineage { ThemeLineage::Tenant { tenant_id } => &theme.tenant_id == tenant_id, ThemeLineage::Organization { tenant_id, org_id } => { &theme.tenant_id == tenant_id && theme .org_id .as_ref() .is_some_and(|org_id_inner| org_id_inner == org_id) } ThemeLineage::Merchant { tenant_id, org_id, merchant_id, } => { &theme.tenant_id == tenant_id && theme .org_id .as_ref() .is_some_and(|org_id_inner| org_id_inner == org_id) && theme .merchant_id .as_ref() .is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id) } ThemeLineage::Profile { tenant_id, org_id, merchant_id, profile_id, } => { &theme.tenant_id == tenant_id && theme .org_id .as_ref() .is_some_and(|org_id_inner| org_id_inner == org_id) && theme .merchant_id .as_ref() .is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id) && theme .profile_id .as_ref() .is_some_and(|profile_id_inner| profile_id_inner == profile_id) } } } #[async_trait::async_trait] impl ThemeInterface for MockDb { async fn insert_theme( &self, new_theme: storage::ThemeNew, ) -> CustomResult<storage::Theme, errors::StorageError> { let mut themes = self.themes.lock().await; for theme in themes.iter() { if new_theme.theme_id == theme.theme_id { return Err(errors::StorageError::DuplicateValue { entity: "theme_id", key: None, } .into()); } if new_theme.tenant_id == theme.tenant_id && new_theme.org_id == theme.org_id && new_theme.merchant_id == theme.merchant_id && new_theme.profile_id == theme.profile_id { return Err(errors::StorageError::DuplicateValue { entity: "lineage", key: None, } .into()); } } let theme = storage::Theme { theme_id: new_theme.theme_id, tenant_id: new_theme.tenant_id, org_id: new_theme.org_id, merchant_id: new_theme.merchant_id, profile_id: new_theme.profile_id, created_at: new_theme.created_at, last_modified_at: new_theme.last_modified_at, entity_type: new_theme.entity_type, theme_name: new_theme.theme_name, email_primary_color: new_theme.email_primary_color, email_foreground_color: new_theme.email_foreground_color, email_background_color: new_theme.email_background_color, email_entity_name: new_theme.email_entity_name, email_entity_logo_url: new_theme.email_entity_logo_url, }; themes.push(theme.clone()); Ok(theme) } async fn find_theme_by_theme_id( &self, theme_id: String, ) -> CustomResult<storage::Theme, errors::StorageError> { let themes = self.themes.lock().await; themes .iter() .find(|theme| theme.theme_id == theme_id) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!("Theme with id {theme_id} not found")) .into(), ) } async fn find_most_specific_theme_in_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let themes = self.themes.lock().await; let lineages = lineage.get_same_and_higher_lineages(); themes .iter() .filter(|theme| { lineages .iter() .any(|lineage| check_theme_with_lineage(theme, lineage)) }) .min_by_key(|theme| theme.entity_type) .ok_or( errors::StorageError::ValueNotFound("No theme found in lineage".to_string()).into(), ) .cloned() } async fn find_theme_by_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let themes = self.themes.lock().await; themes .iter() .find(|theme| check_theme_with_lineage(theme, &lineage)) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "Theme with lineage {lineage:?} not found", )) .into(), ) } async fn update_theme_by_theme_id( &self, theme_id: String, theme_update: ThemeUpdate, ) -> CustomResult<storage::Theme, errors::StorageError> { let mut themes = self.themes.lock().await; themes .iter_mut() .find(|theme| theme.theme_id == theme_id) .map(|theme| { match theme_update { ThemeUpdate::EmailConfig { email_config } => { theme.email_primary_color = email_config.primary_color; theme.email_foreground_color = email_config.foreground_color; theme.email_background_color = email_config.background_color; theme.email_entity_name = email_config.entity_name; theme.email_entity_logo_url = email_config.entity_logo_url; } } theme.clone() }) .ok_or_else(|| { report!(errors::StorageError::ValueNotFound(format!( "Theme with id {theme_id} not found", ))) }) } async fn delete_theme_by_theme_id( &self, theme_id: String, ) -> CustomResult<storage::Theme, errors::StorageError> { let mut themes = self.themes.lock().await; let index = themes .iter() .position(|theme| theme.theme_id == theme_id) .ok_or(errors::StorageError::ValueNotFound(format!( "Theme with id {theme_id} not found" )))?; let theme = themes.remove(index); Ok(theme) } async fn list_themes_at_and_under_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<Vec<storage::Theme>, errors::StorageError> { let themes = self.themes.lock().await; let matching_themes: Vec<storage::Theme> = themes .iter() .filter(|theme| check_theme_belongs_to_lineage_hierarchy(theme, &lineage)) .cloned() .collect(); Ok(matching_themes) } }
crates/router/src/db/user/theme.rs
router::src::db::user::theme
2,870
true
// File: crates/router/src/db/user/sample_data.rs // Module: router::src::db::user::sample_data use common_utils::types::keymanager::KeyManagerState; #[cfg(feature = "v1")] use diesel_models::user::sample_data::PaymentAttemptBatchNew; use diesel_models::{ dispute::{Dispute, DisputeNew}, errors::DatabaseError, query::user::sample_data as sample_data_queries, refund::{Refund, RefundNew}, }; use error_stack::{Report, ResultExt}; use futures::{future::try_join_all, FutureExt}; use hyperswitch_domain_models::{ behaviour::Conversion, merchant_key_store::MerchantKeyStore, payments::{payment_attempt::PaymentAttempt, PaymentIntent}, }; use storage_impl::{errors::StorageError, DataModelExt}; use crate::{connection::pg_connection_write, core::errors::CustomResult, services::Store}; #[async_trait::async_trait] pub trait BatchSampleDataInterface { #[cfg(feature = "v1")] async fn insert_payment_intents_batch_for_sample_data( &self, state: &KeyManagerState, batch: Vec<PaymentIntent>, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError>; #[cfg(feature = "v1")] async fn insert_payment_attempts_batch_for_sample_data( &self, batch: Vec<PaymentAttemptBatchNew>, ) -> CustomResult<Vec<PaymentAttempt>, StorageError>; #[cfg(feature = "v1")] async fn insert_refunds_batch_for_sample_data( &self, batch: Vec<RefundNew>, ) -> CustomResult<Vec<Refund>, StorageError>; #[cfg(feature = "v1")] async fn insert_disputes_batch_for_sample_data( &self, batch: Vec<DisputeNew>, ) -> CustomResult<Vec<Dispute>, StorageError>; #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError>; #[cfg(feature = "v1")] async fn delete_payment_attempts_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<PaymentAttempt>, StorageError>; #[cfg(feature = "v1")] async fn delete_refunds_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Refund>, StorageError>; #[cfg(feature = "v1")] async fn delete_disputes_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Dispute>, StorageError>; } #[async_trait::async_trait] impl BatchSampleDataInterface for Store { #[cfg(feature = "v1")] async fn insert_payment_intents_batch_for_sample_data( &self, state: &KeyManagerState, batch: Vec<PaymentIntent>, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; let new_intents = try_join_all(batch.into_iter().map(|payment_intent| async { payment_intent .construct_new() .await .change_context(StorageError::EncryptionError) })) .await?; sample_data_queries::insert_payment_intents(&conn, new_intents) .await .map_err(diesel_error_to_data_error) .map(|v| { try_join_all(v.into_iter().map(|payment_intent| { PaymentIntent::convert_back( state, payment_intent, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) })? .await } #[cfg(feature = "v1")] async fn insert_payment_attempts_batch_for_sample_data( &self, batch: Vec<PaymentAttemptBatchNew>, ) -> CustomResult<Vec<PaymentAttempt>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::insert_payment_attempts(&conn, batch) .await .map_err(diesel_error_to_data_error) .map(|res| { res.into_iter() .map(PaymentAttempt::from_storage_model) .collect() }) } #[cfg(feature = "v1")] async fn insert_refunds_batch_for_sample_data( &self, batch: Vec<RefundNew>, ) -> CustomResult<Vec<Refund>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::insert_refunds(&conn, batch) .await .map_err(diesel_error_to_data_error) } #[cfg(feature = "v1")] async fn insert_disputes_batch_for_sample_data( &self, batch: Vec<DisputeNew>, ) -> CustomResult<Vec<Dispute>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::insert_disputes(&conn, batch) .await .map_err(diesel_error_to_data_error) } #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::delete_payment_intents(&conn, merchant_id) .await .map_err(diesel_error_to_data_error) .map(|v| { try_join_all(v.into_iter().map(|payment_intent| { PaymentIntent::convert_back( state, payment_intent, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) })? .await } #[cfg(feature = "v1")] async fn delete_payment_attempts_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<PaymentAttempt>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::delete_payment_attempts(&conn, merchant_id) .await .map_err(diesel_error_to_data_error) .map(|res| { res.into_iter() .map(PaymentAttempt::from_storage_model) .collect() }) } #[cfg(feature = "v1")] async fn delete_refunds_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Refund>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::delete_refunds(&conn, merchant_id) .await .map_err(diesel_error_to_data_error) } #[cfg(feature = "v1")] async fn delete_disputes_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Dispute>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::delete_disputes(&conn, merchant_id) .await .map_err(diesel_error_to_data_error) } } #[async_trait::async_trait] impl BatchSampleDataInterface for storage_impl::MockDb { #[cfg(feature = "v1")] async fn insert_payment_intents_batch_for_sample_data( &self, _state: &KeyManagerState, _batch: Vec<PaymentIntent>, _key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn insert_payment_attempts_batch_for_sample_data( &self, _batch: Vec<PaymentAttemptBatchNew>, ) -> CustomResult<Vec<PaymentAttempt>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn insert_refunds_batch_for_sample_data( &self, _batch: Vec<RefundNew>, ) -> CustomResult<Vec<Refund>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn insert_disputes_batch_for_sample_data( &self, _batch: Vec<DisputeNew>, ) -> CustomResult<Vec<Dispute>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, _state: &KeyManagerState, _merchant_id: &common_utils::id_type::MerchantId, _key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn delete_payment_attempts_for_sample_data( &self, _merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<PaymentAttempt>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn delete_refunds_for_sample_data( &self, _merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Refund>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn delete_disputes_for_sample_data( &self, _merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Dispute>, StorageError> { Err(StorageError::MockDbError)? } } // TODO: This error conversion is re-used from storage_impl and is not DRY when it should be // Ideally the impl's here should be defined in that crate avoiding this re-definition fn diesel_error_to_data_error(diesel_error: Report<DatabaseError>) -> Report<StorageError> { let new_err = match diesel_error.current_context() { DatabaseError::DatabaseConnectionError => StorageError::DatabaseConnectionError, DatabaseError::NotFound => StorageError::ValueNotFound("Value not found".to_string()), DatabaseError::UniqueViolation => StorageError::DuplicateValue { entity: "entity ", key: None, }, err => StorageError::DatabaseError(error_stack::report!(*err)), }; diesel_error.change_context(new_err) }
crates/router/src/db/user/sample_data.rs
router::src::db::user::sample_data
2,514
true
// File: crates/router/src/events/outgoing_webhook_logs.rs // Module: router::src::events::outgoing_webhook_logs use api_models::{enums::EventType as OutgoingWebhookEventType, webhooks::OutgoingWebhookContent}; use common_enums::WebhookDeliveryAttempt; use serde::Serialize; use serde_json::Value; use time::OffsetDateTime; use super::EventType; use crate::services::kafka::KafkaMessage; #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub struct OutgoingWebhookEvent { tenant_id: common_utils::id_type::TenantId, merchant_id: common_utils::id_type::MerchantId, event_id: String, event_type: OutgoingWebhookEventType, #[serde(flatten)] content: Option<OutgoingWebhookEventContent>, is_error: bool, error: Option<Value>, created_at_timestamp: i128, initial_attempt_id: Option<String>, status_code: Option<u16>, delivery_attempt: Option<WebhookDeliveryAttempt>, } #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(tag = "outgoing_webhook_event_type", rename_all = "snake_case")] pub enum OutgoingWebhookEventContent { #[cfg(feature = "v1")] Payment { payment_id: common_utils::id_type::PaymentId, content: Value, }, #[cfg(feature = "v2")] Payment { payment_id: common_utils::id_type::GlobalPaymentId, content: Value, }, Payout { payout_id: common_utils::id_type::PayoutId, content: Value, }, #[cfg(feature = "v1")] Refund { payment_id: common_utils::id_type::PaymentId, refund_id: String, content: Value, }, #[cfg(feature = "v2")] Refund { payment_id: common_utils::id_type::GlobalPaymentId, refund_id: common_utils::id_type::GlobalRefundId, content: Value, }, #[cfg(feature = "v1")] Dispute { payment_id: common_utils::id_type::PaymentId, attempt_id: String, dispute_id: String, content: Value, }, #[cfg(feature = "v2")] Dispute { payment_id: common_utils::id_type::GlobalPaymentId, attempt_id: String, dispute_id: String, content: Value, }, Mandate { payment_method_id: String, mandate_id: String, content: Value, }, } pub trait OutgoingWebhookEventMetric { fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent>; } #[cfg(feature = "v1")] impl OutgoingWebhookEventMetric for OutgoingWebhookContent { fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent> { match self { Self::PaymentDetails(payment_payload) => Some(OutgoingWebhookEventContent::Payment { payment_id: payment_payload.payment_id.clone(), content: masking::masked_serialize(&payment_payload) .unwrap_or(serde_json::json!({"error":"failed to serialize"})), }), Self::RefundDetails(refund_payload) => Some(OutgoingWebhookEventContent::Refund { payment_id: refund_payload.payment_id.clone(), refund_id: refund_payload.get_refund_id_as_string(), content: masking::masked_serialize(&refund_payload) .unwrap_or(serde_json::json!({"error":"failed to serialize"})), }), Self::DisputeDetails(dispute_payload) => Some(OutgoingWebhookEventContent::Dispute { payment_id: dispute_payload.payment_id.clone(), attempt_id: dispute_payload.attempt_id.clone(), dispute_id: dispute_payload.dispute_id.clone(), content: masking::masked_serialize(&dispute_payload) .unwrap_or(serde_json::json!({"error":"failed to serialize"})), }), Self::MandateDetails(mandate_payload) => Some(OutgoingWebhookEventContent::Mandate { payment_method_id: mandate_payload.payment_method_id.clone(), mandate_id: mandate_payload.mandate_id.clone(), content: masking::masked_serialize(&mandate_payload) .unwrap_or(serde_json::json!({"error":"failed to serialize"})), }), #[cfg(feature = "payouts")] Self::PayoutDetails(payout_payload) => Some(OutgoingWebhookEventContent::Payout { payout_id: payout_payload.payout_id.clone(), content: masking::masked_serialize(&payout_payload) .unwrap_or(serde_json::json!({"error":"failed to serialize"})), }), } } } #[cfg(feature = "v2")] impl OutgoingWebhookEventMetric for OutgoingWebhookContent { fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent> { match self { Self::PaymentDetails(payment_payload) => Some(OutgoingWebhookEventContent::Payment { payment_id: payment_payload.id.clone(), content: masking::masked_serialize(&payment_payload) .unwrap_or(serde_json::json!({"error":"failed to serialize"})), }), Self::RefundDetails(refund_payload) => Some(OutgoingWebhookEventContent::Refund { payment_id: refund_payload.payment_id.clone(), refund_id: refund_payload.id.clone(), content: masking::masked_serialize(&refund_payload) .unwrap_or(serde_json::json!({"error":"failed to serialize"})), }), Self::DisputeDetails(dispute_payload) => { //TODO: add support for dispute outgoing webhook todo!() } Self::MandateDetails(mandate_payload) => Some(OutgoingWebhookEventContent::Mandate { payment_method_id: mandate_payload.payment_method_id.clone(), mandate_id: mandate_payload.mandate_id.clone(), content: masking::masked_serialize(&mandate_payload) .unwrap_or(serde_json::json!({"error":"failed to serialize"})), }), #[cfg(feature = "payouts")] Self::PayoutDetails(payout_payload) => Some(OutgoingWebhookEventContent::Payout { payout_id: payout_payload.payout_id.clone(), content: masking::masked_serialize(&payout_payload) .unwrap_or(serde_json::json!({"error":"failed to serialize"})), }), } } } impl OutgoingWebhookEvent { #[allow(clippy::too_many_arguments)] pub fn new( tenant_id: common_utils::id_type::TenantId, merchant_id: common_utils::id_type::MerchantId, event_id: String, event_type: OutgoingWebhookEventType, content: Option<OutgoingWebhookEventContent>, error: Option<Value>, initial_attempt_id: Option<String>, status_code: Option<u16>, delivery_attempt: Option<WebhookDeliveryAttempt>, ) -> Self { Self { tenant_id, merchant_id, event_id, event_type, content, is_error: error.is_some(), error, created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000, initial_attempt_id, status_code, delivery_attempt, } } } impl KafkaMessage for OutgoingWebhookEvent { fn event_type(&self) -> EventType { EventType::OutgoingWebhookLogs } fn key(&self) -> String { self.event_id.clone() } }
crates/router/src/events/outgoing_webhook_logs.rs
router::src::events::outgoing_webhook_logs
1,652
true
// File: crates/router/src/events/api_logs.rs // Module: router::src::events::api_logs use actix_web::HttpRequest; pub use common_utils::events::{ApiEventMetric, ApiEventsType}; use common_utils::impl_api_event_type; use router_env::{tracing_actix_web::RequestId, types::FlowMetric}; use serde::Serialize; use time::OffsetDateTime; use super::EventType; #[cfg(feature = "dummy_connector")] use crate::routes::dummy_connector::types::{ DummyConnectorPaymentCompleteRequest, DummyConnectorPaymentConfirmRequest, DummyConnectorPaymentRequest, DummyConnectorPaymentResponse, DummyConnectorPaymentRetrieveRequest, DummyConnectorRefundRequest, DummyConnectorRefundResponse, DummyConnectorRefundRetrieveRequest, }; use crate::{ core::payments::PaymentsRedirectResponseData, services::{authentication::AuthenticationType, kafka::KafkaMessage}, types::api::{ AttachEvidenceRequest, Config, ConfigUpdate, CreateFileRequest, DisputeFetchQueryData, DisputeId, FileId, FileRetrieveRequest, PollId, }, }; #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub struct ApiEvent { tenant_id: common_utils::id_type::TenantId, merchant_id: Option<common_utils::id_type::MerchantId>, api_flow: String, created_at_timestamp: i128, request_id: String, latency: u128, status_code: i64, #[serde(flatten)] auth_type: AuthenticationType, request: String, user_agent: Option<String>, ip_addr: Option<String>, url_path: String, response: Option<String>, error: Option<serde_json::Value>, #[serde(flatten)] event_type: ApiEventsType, hs_latency: Option<u128>, http_method: String, #[serde(flatten)] infra_components: Option<serde_json::Value>, } impl ApiEvent { #[allow(clippy::too_many_arguments)] pub fn new( tenant_id: common_utils::id_type::TenantId, merchant_id: Option<common_utils::id_type::MerchantId>, api_flow: &impl FlowMetric, request_id: &RequestId, latency: u128, status_code: i64, request: serde_json::Value, response: Option<serde_json::Value>, hs_latency: Option<u128>, auth_type: AuthenticationType, error: Option<serde_json::Value>, event_type: ApiEventsType, http_req: &HttpRequest, http_method: &http::Method, infra_components: Option<serde_json::Value>, ) -> Self { Self { tenant_id, merchant_id, api_flow: api_flow.to_string(), created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000, request_id: request_id.as_hyphenated().to_string(), latency, status_code, request: request.to_string(), response: response.map(|resp| resp.to_string()), auth_type, error, ip_addr: http_req .connection_info() .realip_remote_addr() .map(ToOwned::to_owned), user_agent: http_req .headers() .get("user-agent") .and_then(|user_agent_value| user_agent_value.to_str().ok().map(ToOwned::to_owned)), url_path: http_req.path().to_string(), event_type, hs_latency, http_method: http_method.to_string(), infra_components, } } } impl KafkaMessage for ApiEvent { fn event_type(&self) -> EventType { EventType::ApiLogs } fn key(&self) -> String { self.request_id.clone() } } impl_api_event_type!( Miscellaneous, ( Config, CreateFileRequest, FileId, FileRetrieveRequest, AttachEvidenceRequest, DisputeFetchQueryData, ConfigUpdate ) ); #[cfg(feature = "dummy_connector")] impl_api_event_type!( Miscellaneous, ( DummyConnectorPaymentCompleteRequest, DummyConnectorPaymentRequest, DummyConnectorPaymentResponse, DummyConnectorPaymentRetrieveRequest, DummyConnectorPaymentConfirmRequest, DummyConnectorRefundRetrieveRequest, DummyConnectorRefundResponse, DummyConnectorRefundRequest ) ); #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsRedirectResponseData { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentRedirectionResponse { connector: self.connector.clone(), payment_id: match &self.resource_id { api_models::payments::PaymentIdType::PaymentIntentId(id) => Some(id.clone()), _ => None, }, }) } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentsRedirectResponseData { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentRedirectionResponse { payment_id: self.payment_id.clone(), }) } } impl ApiEventMetric for DisputeId { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Dispute { dispute_id: self.dispute_id.clone(), }) } } impl ApiEventMetric for PollId { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Poll { poll_id: self.poll_id.clone(), }) } }
crates/router/src/events/api_logs.rs
router::src::events::api_logs
1,207
true
// File: crates/router/src/events/audit_events.rs // Module: router::src::events::audit_events use api_models::payments::Amount; use common_utils::types::MinorUnit; use diesel_models::fraud_check::FraudCheck; use events::{Event, EventInfo}; use serde::Serialize; use time::PrimitiveDateTime; #[derive(Debug, Clone, Serialize)] #[serde(tag = "event_type")] pub enum AuditEventType { Error { error_message: String, }, PaymentCreated, ConnectorDecided, ConnectorCalled, RefundCreated, RefundSuccess, RefundFail, PaymentConfirm { client_src: Option<String>, client_ver: Option<String>, frm_message: Box<Option<FraudCheck>>, }, PaymentCancelled { cancellation_reason: Option<String>, }, PaymentCapture { capture_amount: Option<MinorUnit>, multiple_capture_count: Option<i16>, }, PaymentUpdate { amount: Amount, }, PaymentApprove, PaymentCreate, PaymentStatus, PaymentCompleteAuthorize, PaymentReject { error_code: Option<String>, error_message: Option<String>, }, } #[derive(Debug, Clone, Serialize)] pub struct AuditEvent { #[serde(flatten)] event_type: AuditEventType, #[serde(with = "common_utils::custom_serde::iso8601")] created_at: PrimitiveDateTime, } impl AuditEvent { pub fn new(event_type: AuditEventType) -> Self { Self { event_type, created_at: common_utils::date_time::now(), } } } impl Event for AuditEvent { type EventType = super::EventType; fn timestamp(&self) -> PrimitiveDateTime { self.created_at } fn identifier(&self) -> String { let event_type = match &self.event_type { AuditEventType::Error { .. } => "error", AuditEventType::PaymentCreated => "payment_created", AuditEventType::PaymentConfirm { .. } => "payment_confirm", AuditEventType::ConnectorDecided => "connector_decided", AuditEventType::ConnectorCalled => "connector_called", AuditEventType::PaymentCapture { .. } => "payment_capture", AuditEventType::RefundCreated => "refund_created", AuditEventType::RefundSuccess => "refund_success", AuditEventType::RefundFail => "refund_fail", AuditEventType::PaymentCancelled { .. } => "payment_cancelled", AuditEventType::PaymentUpdate { .. } => "payment_update", AuditEventType::PaymentApprove => "payment_approve", AuditEventType::PaymentCreate => "payment_create", AuditEventType::PaymentStatus => "payment_status", AuditEventType::PaymentCompleteAuthorize => "payment_complete_authorize", AuditEventType::PaymentReject { .. } => "payment_rejected", }; format!( "{event_type}-{}", self.timestamp().assume_utc().unix_timestamp_nanos() ) } fn class(&self) -> Self::EventType { super::EventType::AuditEvent } } impl EventInfo for AuditEvent { type Data = Self; fn data(&self) -> error_stack::Result<Self::Data, events::EventsError> { Ok(self.clone()) } fn key(&self) -> String { "event".to_string() } }
crates/router/src/events/audit_events.rs
router::src::events::audit_events
709
true
// File: crates/router/src/events/routing_api_logs.rs // Module: router::src::events::routing_api_logs pub use hyperswitch_interfaces::events::routing_api_logs::RoutingEvent; use super::EventType; use crate::services::kafka::KafkaMessage; impl KafkaMessage for RoutingEvent { fn event_type(&self) -> EventType { EventType::RoutingApiLogs } fn key(&self) -> String { format!( "{}-{}-{}", self.get_merchant_id(), self.get_profile_id(), self.get_payment_id() ) } }
crates/router/src/events/routing_api_logs.rs
router::src::events::routing_api_logs
127
true
// File: crates/router/src/events/connector_api_logs.rs // Module: router::src::events::connector_api_logs pub use hyperswitch_interfaces::events::connector_api_logs::ConnectorEvent; use super::EventType; use crate::services::kafka::KafkaMessage; impl KafkaMessage for ConnectorEvent { fn event_type(&self) -> EventType { EventType::ConnectorApiLogs } fn key(&self) -> String { self.request_id.clone() } }
crates/router/src/events/connector_api_logs.rs
router::src::events::connector_api_logs
102
true
// File: crates/router/src/events/event_logger.rs // Module: router::src::events::event_logger use std::collections::HashMap; use events::{EventsError, Message, MessagingInterface}; use masking::ErasedMaskSerialize; use time::PrimitiveDateTime; use super::EventType; use crate::services::{kafka::KafkaMessage, logger}; #[derive(Clone, Debug, Default)] pub struct EventLogger {} impl EventLogger { #[track_caller] pub(super) fn log_event<T: KafkaMessage>(&self, event: &T) { logger::info!(event = ?event.masked_serialize().unwrap_or_else(|e| serde_json::json!({"error": e.to_string()})), event_type =? event.event_type(), event_id =? event.key(), log_type =? "event"); } } impl MessagingInterface for EventLogger { type MessageClass = EventType; fn send_message<T>( &self, data: T, metadata: HashMap<String, String>, _timestamp: PrimitiveDateTime, ) -> error_stack::Result<(), EventsError> where T: Message<Class = Self::MessageClass> + ErasedMaskSerialize, { logger::info!(event =? data.masked_serialize().unwrap_or_else(|e| serde_json::json!({"error": e.to_string()})), event_type =? data.get_message_class(), event_id =? data.identifier(), log_type =? "event", metadata = ?metadata); Ok(()) } }
crates/router/src/events/event_logger.rs
router::src::events::event_logger
317
true
// File: crates/router/src/routes/tokenization.rs // Module: router::src::routes::tokenization #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use std::sync::Arc; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use actix_web::{web, HttpRequest, HttpResponse}; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use api_models; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use common_utils::{ ext_traits::{BytesExt, Encode}, id_type, }; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use error_stack::ResultExt; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use hyperswitch_domain_models; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use masking::Secret; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use router_env::{instrument, logger, tracing, Flow}; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use serde::Serialize; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use crate::{ core::{ api_locking, errors::{self, RouterResult}, tokenization, }, headers::X_CUSTOMER_ID, routes::{app::StorageInterface, AppState, SessionState}, services::{self, api as api_service, authentication as auth}, types::{api, domain, payment_methods as pm_types}, }; #[instrument(skip_all, fields(flow = ?Flow::TokenizationCreate))] #[cfg(all(feature = "v2", feature = "tokenization_v2"))] pub async fn create_token_vault_api( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_models::tokenization::GenericTokenizationRequest>, ) -> HttpResponse { let flow = Flow::TokenizationCreate; let payload = json_payload.into_inner(); let customer_id = payload.customer_id.clone(); Box::pin(api_service::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, request, _| async move { tokenization::create_vault_token_core( state, &auth.merchant_account, &auth.key_store, request, ) .await }, auth::api_or_client_auth( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Customer( customer_id, )), req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::TokenizationDelete))] #[cfg(all(feature = "v2", feature = "tokenization_v2"))] pub async fn delete_tokenized_data_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalTokenId>, json_payload: web::Json<api_models::tokenization::DeleteTokenDataRequest>, ) -> HttpResponse { let flow = Flow::TokenizationDelete; let payload = json_payload.into_inner(); let session_id = payload.session_id.clone(); let token_id = path.into_inner(); Box::pin(api_service::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); tokenization::delete_tokenized_data_core(state, merchant_context, &token_id, req) }, auth::api_or_client_auth( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::V2ClientAuth( common_utils::types::authentication::ResourceId::PaymentMethodSession(session_id), ), req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/tokenization.rs
router::src::routes::tokenization
926
true
// File: crates/router/src/routes/cache.rs // Module: router::src::routes::cache use actix_web::{web, HttpRequest, Responder}; use router_env::{instrument, tracing, Flow}; use super::AppState; use crate::{ core::{api_locking, cache}, services::{api, authentication as auth}, }; #[instrument(skip_all)] pub async fn invalidate( state: web::Data<AppState>, req: HttpRequest, key: web::Path<String>, ) -> impl Responder { let flow = Flow::CacheInvalidate; let key = key.into_inner().to_owned(); api::server_wrap( flow, state, &req, &key, |state, _, key, _| cache::invalidate(state, key), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, ) .await }
crates/router/src/routes/cache.rs
router::src::routes::cache
191
true
// File: crates/router/src/routes/locker_migration.rs // Module: router::src::routes::locker_migration use actix_web::{web, HttpRequest, HttpResponse}; use router_env::Flow; use super::AppState; use crate::{ core::{api_locking, locker_migration}, services::{api, authentication as auth}, }; pub async fn rust_locker_migration( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, ) -> HttpResponse { let flow = Flow::RustLockerMigration; let merchant_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, &merchant_id, |state, _, _, _| locker_migration::rust_locker_migration(state, &merchant_id), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/locker_migration.rs
router::src::routes::locker_migration
202
true
// File: crates/router/src/routes/payment_methods.rs // Module: router::src::routes::payment_methods use ::payment_methods::{ controller::PaymentMethodsController, core::{migration, migration::payment_methods::migrate_payment_method}, }; #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] use actix_multipart::form::MultipartForm; use actix_web::{web, HttpRequest, HttpResponse}; use common_utils::{errors::CustomResult, id_type, transformers::ForeignFrom}; use diesel_models::enums::IntentStatus; use error_stack::ResultExt; use hyperswitch_domain_models::{ bulk_tokenization::CardNetworkTokenizeRequest, merchant_key_store::MerchantKeyStore, payment_methods::PaymentMethodCustomerMigrate, transformers::ForeignTryFrom, }; use router_env::{instrument, logger, tracing, Flow}; use super::app::{AppState, SessionState}; #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] use crate::core::{customers, payment_methods::tokenize}; use crate::{ core::{ api_locking, errors::{self, utils::StorageErrorExt}, payment_methods::{self as payment_methods_routes, cards, migration as update_migration}, }, services::{self, api, authentication as auth, authorization::permissions::Permission}, types::{ api::payment_methods::{self, PaymentMethodId}, domain, storage::payment_method::PaymentTokenData, }, }; #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))] pub async fn create_payment_method_api( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payment_methods::PaymentMethodCreate>, ) -> HttpResponse { let flow = Flow::PaymentMethodsCreate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(cards::get_client_secret_or_add_payment_method( &state, req, &merchant_context, )) .await }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))] pub async fn create_payment_method_api( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payment_methods::PaymentMethodCreate>, ) -> HttpResponse { let flow = Flow::PaymentMethodsCreate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, req_state| async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(payment_methods_routes::create_payment_method( &state, &req_state, req, &merchant_context, &auth.profile, )) .await }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))] pub async fn create_payment_method_intent_api( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payment_methods::PaymentMethodIntentCreate>, ) -> HttpResponse { let flow = Flow::PaymentMethodsCreate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(payment_methods_routes::payment_method_intent_create( &state, req, &merchant_context, )) .await }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } /// This struct is used internally only #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentMethodIntentConfirmInternal { pub id: id_type::GlobalPaymentMethodId, pub request: payment_methods::PaymentMethodIntentConfirm, } #[cfg(feature = "v2")] impl From<PaymentMethodIntentConfirmInternal> for payment_methods::PaymentMethodIntentConfirm { fn from(item: PaymentMethodIntentConfirmInternal) -> Self { item.request } } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for PaymentMethodIntentConfirmInternal { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::PaymentMethod { payment_method_id: self.id.clone(), payment_method_type: Some(self.request.payment_method_type), payment_method_subtype: Some(self.request.payment_method_subtype), }) } } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))] pub async fn payment_method_update_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodId>, json_payload: web::Json<payment_methods::PaymentMethodUpdate>, ) -> HttpResponse { let flow = Flow::PaymentMethodsUpdate; let payment_method_id = path.into_inner(); let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::update_payment_method( state, merchant_context, auth.profile, req, &payment_method_id, ) }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsRetrieve))] pub async fn payment_method_retrieve_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::PaymentMethodsRetrieve; let payload = web::Json(PaymentMethodId { payment_method_id: path.into_inner(), }) .into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, pm, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::retrieve_payment_method(state, pm, merchant_context) }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsDelete))] pub async fn payment_method_delete_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::PaymentMethodsDelete; let payload = web::Json(PaymentMethodId { payment_method_id: path.into_inner(), }) .into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, pm, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::delete_payment_method(state, pm, merchant_context, auth.profile) }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))] pub async fn migrate_payment_method_api( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payment_methods::PaymentMethodMigrate>, ) -> HttpResponse { let flow = Flow::PaymentMethodsMigrate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, _, req, _| async move { let merchant_id = req.merchant_id.clone(); let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account, key_store), )); Box::pin(migrate_payment_method( &(&state).into(), req, &merchant_id, &merchant_context, &cards::PmCards { state: &state, merchant_context: &merchant_context, }, )) .await }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } async fn get_merchant_account( state: &SessionState, merchant_id: &id_type::MerchantId, ) -> CustomResult<(MerchantKeyStore, domain::MerchantAccount), errors::ApiErrorResponse> { let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = state .store .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; Ok((key_store, merchant_account)) } #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))] pub async fn migrate_payment_methods( state: web::Data<AppState>, req: HttpRequest, MultipartForm(form): MultipartForm<migration::PaymentMethodsMigrateForm>, ) -> HttpResponse { let flow = Flow::PaymentMethodsMigrate; let (merchant_id, records, merchant_connector_ids) = match form.validate_and_get_payment_method_records() { Ok((merchant_id, records, merchant_connector_ids)) => { (merchant_id, records, merchant_connector_ids) } Err(e) => return api::log_and_return_error_response(e.into()), }; Box::pin(api::server_wrap( flow, state, &req, records, |state, _, req, _| { let merchant_id = merchant_id.clone(); let merchant_connector_ids = merchant_connector_ids.clone(); async move { let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; // Create customers if they are not already present let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account.clone(), key_store.clone()), )); let mut mca_cache = std::collections::HashMap::new(); let customers = Vec::<PaymentMethodCustomerMigrate>::foreign_try_from(( &req, merchant_id.clone(), )) .map_err(|e| errors::ApiErrorResponse::InvalidRequestData { message: e.to_string(), })?; for record in &customers { if let Some(connector_customer_details) = &record.connector_customer_details { for connector_customer in connector_customer_details { if !mca_cache.contains_key(&connector_customer.merchant_connector_id) { let mca = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( &(&state).into(), &merchant_id, &connector_customer.merchant_connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_customer.merchant_connector_id.get_string_repr().to_string(), }, )?; mca_cache .insert(connector_customer.merchant_connector_id.clone(), mca); } } } } customers::migrate_customers(state.clone(), customers, merchant_context.clone()) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let controller = cards::PmCards { state: &state, merchant_context: &merchant_context, }; Box::pin(migration::migrate_payment_methods( &(&state).into(), req, &merchant_id, &merchant_context, merchant_connector_ids, &controller, )) .await } }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsBatchUpdate))] pub async fn update_payment_methods( state: web::Data<AppState>, req: HttpRequest, MultipartForm(form): MultipartForm<update_migration::PaymentMethodsUpdateForm>, ) -> HttpResponse { let flow = Flow::PaymentMethodsBatchUpdate; let (merchant_id, records) = match form.validate_and_get_payment_method_records() { Ok((merchant_id, records)) => (merchant_id, records), Err(e) => return api::log_and_return_error_response(e.into()), }; Box::pin(api::server_wrap( flow, state, &req, records, |state, _, req, _| { let merchant_id = merchant_id.clone(); async move { let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account.clone(), key_store.clone()), )); Box::pin(update_migration::update_payment_methods( &state, req, &merchant_id, &merchant_context, )) .await } }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSave))] pub async fn save_payment_method_api( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payment_methods::PaymentMethodCreate>, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::PaymentMethodSave; let payload = json_payload.into_inner(); let pm_id = path.into_inner(); let api_auth = auth::ApiKeyAuth::default(); let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok((auth, _auth_flow)) => (auth, _auth_flow), Err(e) => return api::log_and_return_error_response(e), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(cards::add_payment_method_data( state, req, merchant_context, pm_id.clone(), )) }, &*auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))] pub async fn list_payment_method_api( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Query<payment_methods::PaymentMethodListRequest>, ) -> HttpResponse { let flow = Flow::PaymentMethodsList; let payload = json_payload.into_inner(); let api_auth = auth::ApiKeyAuth::default(); let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok((auth, _auth_flow)) => (auth, _auth_flow), Err(e) => return api::log_and_return_error_response(e), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { // TODO (#7195): Fill platform_merchant_account in the client secret auth and pass it here. let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); cards::list_payment_methods(state, merchant_context, req) }, &*auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// List payment methods for a Customer /// /// To filter and list the applicable payment methods for a particular Customer ID #[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))] pub async fn list_customer_payment_method_api( state: web::Data<AppState>, customer_id: web::Path<(id_type::CustomerId,)>, req: HttpRequest, query_payload: web::Query<payment_methods::PaymentMethodListRequest>, ) -> HttpResponse { let flow = Flow::CustomerPaymentMethodsList; let payload = query_payload.into_inner(); let customer_id = customer_id.into_inner().0; let api_auth = auth::ApiKeyAuth::default(); let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); cards::do_list_customer_pm_fetch_customer_if_not_passed( state, merchant_context, Some(req), Some(&customer_id), None, ) }, &*ephemeral_auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// List payment methods for a Customer /// /// To filter and list the applicable payment methods for a particular Customer ID #[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))] pub async fn list_customer_payment_method_api_client( state: web::Data<AppState>, req: HttpRequest, query_payload: web::Query<payment_methods::PaymentMethodListRequest>, ) -> HttpResponse { let flow = Flow::CustomerPaymentMethodsList; let payload = query_payload.into_inner(); let api_key = auth::get_api_key(req.headers()).ok(); let api_auth = auth::ApiKeyAuth::default(); let (auth, _, is_ephemeral_auth) = match auth::get_ephemeral_or_other_auth(req.headers(), false, Some(&payload), api_auth) .await { Ok((auth, _auth_flow, is_ephemeral_auth)) => (auth, _auth_flow, is_ephemeral_auth), Err(e) => return api::log_and_return_error_response(e), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); cards::do_list_customer_pm_fetch_customer_if_not_passed( state, merchant_context, Some(req), None, is_ephemeral_auth.then_some(api_key).flatten(), ) }, &*auth, api_locking::LockAction::NotApplicable, )) .await } /// Generate a form link for collecting payment methods for a customer #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodCollectLink))] pub async fn initiate_pm_collect_link_flow( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payment_methods::PaymentMethodCollectLinkRequest>, ) -> HttpResponse { let flow = Flow::PaymentMethodCollectLink; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::initiate_pm_collect_link(state, merchant_context, req) }, &auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))] pub async fn list_customer_payment_method_api( state: web::Data<AppState>, customer_id: web::Path<id_type::GlobalCustomerId>, req: HttpRequest, query_payload: web::Query<api_models::payment_methods::ListMethodsForPaymentMethodsRequest>, ) -> HttpResponse { let flow = Flow::CustomerPaymentMethodsList; let payload = query_payload.into_inner(); let customer_id = customer_id.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::list_saved_payment_methods_for_customer( state, merchant_context, customer_id.clone(), ) }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantCustomerRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all, fields(flow = ?Flow::GetPaymentMethodTokenData))] pub async fn get_payment_method_token_data( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodId>, json_payload: web::Json<api_models::payment_methods::GetTokenDataRequest>, ) -> HttpResponse { let flow = Flow::GetPaymentMethodTokenData; let payment_method_id = path.into_inner(); let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { payment_methods_routes::get_token_data_for_payment_method( state, auth.merchant_account, auth.key_store, auth.profile, req, payment_method_id.clone(), ) }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantCustomerRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all, fields(flow = ?Flow::TotalPaymentMethodCount))] pub async fn get_total_payment_method_count( state: web::Data<AppState>, req: HttpRequest, ) -> HttpResponse { let flow = Flow::TotalPaymentMethodCount; Box::pin(api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::get_total_saved_payment_methods_for_merchant( state, merchant_context, ) }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantCustomerRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// Generate a form link for collecting payment methods for a customer #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodCollectLink))] pub async fn render_pm_collect_link( state: web::Data<AppState>, req: HttpRequest, path: web::Path<(id_type::MerchantId, String)>, ) -> HttpResponse { let flow = Flow::PaymentMethodCollectLink; let (merchant_id, pm_collect_link_id) = path.into_inner(); let payload = payment_methods::PaymentMethodCollectLinkRenderRequest { merchant_id: merchant_id.clone(), pm_collect_link_id, }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::render_pm_collect_link(state, merchant_context, req) }, &auth::MerchantIdAuth(merchant_id), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsRetrieve))] pub async fn payment_method_retrieve_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::PaymentMethodsRetrieve; let payload = web::Json(PaymentMethodId { payment_method_id: path.into_inner(), }) .into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, pm, _| async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); cards::PmCards { state: &state, merchant_context: &merchant_context, } .retrieve_payment_method(pm) .await }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))] pub async fn payment_method_update_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, json_payload: web::Json<payment_methods::PaymentMethodUpdate>, ) -> HttpResponse { let flow = Flow::PaymentMethodsUpdate; let payment_method_id = path.into_inner(); let payload = json_payload.into_inner(); let api_auth = auth::ApiKeyAuth::default(); let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok((auth, _auth_flow)) => (auth, _auth_flow), Err(e) => return api::log_and_return_error_response(e), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); cards::update_customer_payment_method(state, merchant_context, req, &payment_method_id) }, &*auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsDelete))] pub async fn payment_method_delete_api( state: web::Data<AppState>, req: HttpRequest, payment_method_id: web::Path<(String,)>, ) -> HttpResponse { let flow = Flow::PaymentMethodsDelete; let pm = PaymentMethodId { payment_method_id: payment_method_id.into_inner().0, }; let api_auth = auth::ApiKeyAuth::default(); let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; Box::pin(api::server_wrap( flow, state, &req, pm, |state, auth: auth::AuthenticationData, req, _| async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); cards::PmCards { state: &state, merchant_context: &merchant_context, } .delete_payment_method(req) .await }, &*ephemeral_auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::ListCountriesCurrencies))] pub async fn list_countries_currencies_for_connector_payment_method( state: web::Data<AppState>, req: HttpRequest, query_payload: web::Query<payment_methods::ListCountriesCurrenciesRequest>, ) -> HttpResponse { let flow = Flow::ListCountriesCurrencies; let payload = query_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { cards::list_countries_currencies_for_connector_payment_method( state, req, auth.profile_id, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileConnectorWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::ProfileConnectorWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::ListCountriesCurrencies))] pub async fn list_countries_currencies_for_connector_payment_method( state: web::Data<AppState>, req: HttpRequest, query_payload: web::Query<payment_methods::ListCountriesCurrenciesRequest>, ) -> HttpResponse { let flow = Flow::ListCountriesCurrencies; let payload = query_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { cards::list_countries_currencies_for_connector_payment_method( state, req, Some(auth.profile.get_id().clone()), ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfileConnectorRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::ProfileConnectorRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::DefaultPaymentMethodsSet))] pub async fn default_payment_method_set_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<payment_methods::DefaultPaymentMethod>, ) -> HttpResponse { let flow = Flow::DefaultPaymentMethodsSet; let payload = path.into_inner(); let pc = payload.clone(); let customer_id = &pc.customer_id; let api_auth = auth::ApiKeyAuth::default(); let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, default_payment_method, _| async move { let merchant_id = auth.merchant_account.get_id(); cards::PmCards { state: &state, merchant_context: &domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account.clone(), auth.key_store), )), } .set_default_payment_method( merchant_id, customer_id, default_payment_method.payment_method_id, ) .await }, &*ephemeral_auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use api_models::payment_methods::PaymentMethodListRequest; use super::*; // #[test] // fn test_custom_list_deserialization() { // let dummy_data = "amount=120&recurring_enabled=true&installment_payment_enabled=true"; // let de_query: web::Query<PaymentMethodListRequest> = // web::Query::from_query(dummy_data).unwrap(); // let de_struct = de_query.into_inner(); // assert_eq!(de_struct.installment_payment_enabled, Some(true)) // } #[test] fn test_custom_list_deserialization_multi_amount() { let dummy_data = "amount=120&recurring_enabled=true&amount=1000"; let de_query: Result<web::Query<PaymentMethodListRequest>, _> = web::Query::from_query(dummy_data); assert!(de_query.is_err()) } } #[derive(Clone)] pub struct ParentPaymentMethodToken { key_for_token: String, } impl ParentPaymentMethodToken { pub fn create_key_for_token( (parent_pm_token, payment_method): (&String, api_models::enums::PaymentMethod), ) -> Self { Self { key_for_token: format!("pm_token_{parent_pm_token}_{payment_method}_hyperswitch"), } } #[cfg(feature = "v2")] pub fn return_key_for_token( (parent_pm_token, payment_method): (&String, api_models::enums::PaymentMethod), ) -> String { format!("pm_token_{parent_pm_token}_{payment_method}_hyperswitch") } pub async fn insert( &self, fulfillment_time: i64, token: PaymentTokenData, state: &SessionState, ) -> CustomResult<(), errors::ApiErrorResponse> { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; redis_conn .serialize_and_set_key_with_expiry( &self.key_for_token.as_str().into(), token, fulfillment_time, ) .await .change_context(errors::StorageError::KVError) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add token in redis")?; Ok(()) } pub fn should_delete_payment_method_token(&self, status: IntentStatus) -> bool { // RequiresMerchantAction: When the payment goes for merchant review incase of potential fraud allow payment_method_token to be stored until resolved ![ IntentStatus::RequiresCustomerAction, IntentStatus::RequiresMerchantAction, ] .contains(&status) } pub async fn delete(&self, state: &SessionState) -> CustomResult<(), errors::ApiErrorResponse> { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; match redis_conn .delete_key(&self.key_for_token.as_str().into()) .await { Ok(_) => Ok(()), Err(err) => { { logger::info!("Error while deleting redis key: {:?}", err) }; Ok(()) } } } } #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] #[instrument(skip_all, fields(flow = ?Flow::TokenizeCard))] pub async fn tokenize_card_api( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payment_methods::CardNetworkTokenizeRequest>, ) -> HttpResponse { let flow = Flow::TokenizeCard; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, _, req, _| async move { let merchant_id = req.merchant_id.clone(); let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account, key_store), )); let res = Box::pin(cards::tokenize_card_flow( &state, CardNetworkTokenizeRequest::foreign_from(req), &merchant_context, )) .await?; Ok(services::ApplicationResponse::Json(res)) }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] #[instrument(skip_all, fields(flow = ?Flow::TokenizeCardUsingPaymentMethodId))] pub async fn tokenize_card_using_pm_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, json_payload: web::Json<payment_methods::CardNetworkTokenizeRequest>, ) -> HttpResponse { let flow = Flow::TokenizeCardUsingPaymentMethodId; let pm_id = path.into_inner(); let mut payload = json_payload.into_inner(); if let payment_methods::TokenizeDataRequest::ExistingPaymentMethod(ref mut pm_data) = payload.data { pm_data.payment_method_id = pm_id; } else { return api::log_and_return_error_response(error_stack::report!( errors::ApiErrorResponse::InvalidDataValue { field_name: "card" } )); } Box::pin(api::server_wrap( flow, state, &req, payload, |state, _, req, _| async move { let merchant_id = req.merchant_id.clone(); let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account, key_store), )); let res = Box::pin(cards::tokenize_card_flow( &state, CardNetworkTokenizeRequest::foreign_from(req), &merchant_context, )) .await?; Ok(services::ApplicationResponse::Json(res)) }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] #[instrument(skip_all, fields(flow = ?Flow::TokenizeCardBatch))] pub async fn tokenize_card_batch_api( state: web::Data<AppState>, req: HttpRequest, MultipartForm(form): MultipartForm<tokenize::CardNetworkTokenizeForm>, ) -> HttpResponse { let flow = Flow::TokenizeCardBatch; let (merchant_id, records) = match tokenize::get_tokenize_card_form_records(form) { Ok(res) => res, Err(e) => return api::log_and_return_error_response(e.into()), }; Box::pin(api::server_wrap( flow, state, &req, records, |state, _, req, _| { let merchant_id = merchant_id.clone(); async move { let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account, key_store), )); Box::pin(tokenize::tokenize_cards(&state, req, &merchant_context)).await } }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionCreate))] pub async fn payment_methods_session_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_models::payment_methods::PaymentMethodSessionRequest>, ) -> HttpResponse { let flow = Flow::PaymentMethodSessionCreate; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, request, _| async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::payment_methods_session_create(state, merchant_context, request) .await }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionUpdate))] pub async fn payment_methods_session_update( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodSessionId>, json_payload: web::Json<api_models::payment_methods::PaymentMethodsSessionUpdateRequest>, ) -> HttpResponse { let flow = Flow::PaymentMethodSessionUpdate; let payment_method_session_id = path.into_inner(); let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let value = payment_method_session_id.clone(); async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::payment_methods_session_update( state, merchant_context, value.clone(), req, ) .await } }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionRetrieve))] pub async fn payment_methods_session_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodSessionId>, ) -> HttpResponse { let flow = Flow::PaymentMethodSessionRetrieve; let payment_method_session_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payment_method_session_id.clone(), |state, auth: auth::AuthenticationData, payment_method_session_id, _| async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::payment_methods_session_retrieve( state, merchant_context, payment_method_session_id, ) .await }, auth::api_or_client_auth( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::V2ClientAuth( common_utils::types::authentication::ResourceId::PaymentMethodSession( payment_method_session_id, ), ), req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))] pub async fn payment_method_session_list_payment_methods( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodSessionId>, ) -> HttpResponse { let flow = Flow::PaymentMethodsList; let payment_method_session_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payment_method_session_id.clone(), |state, auth: auth::AuthenticationData, payment_method_session_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::list_payment_methods_for_session( state, merchant_context, auth.profile, payment_method_session_id, ) }, &auth::V2ClientAuth( common_utils::types::authentication::ResourceId::PaymentMethodSession( payment_method_session_id, ), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize)] struct PaymentMethodsSessionGenericRequest<T: serde::Serialize> { payment_method_session_id: id_type::GlobalPaymentMethodSessionId, #[serde(flatten)] request: T, } #[cfg(feature = "v2")] impl<T: serde::Serialize> common_utils::events::ApiEventMetric for PaymentMethodsSessionGenericRequest<T> { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::PaymentMethodSession { payment_method_session_id: self.payment_method_session_id.clone(), }) } } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionConfirm))] pub async fn payment_method_session_confirm( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodSessionId>, json_payload: web::Json<api_models::payment_methods::PaymentMethodSessionConfirmRequest>, ) -> HttpResponse { let flow = Flow::PaymentMethodSessionConfirm; let payload = json_payload.into_inner(); let payment_method_session_id = path.into_inner(); let request = PaymentMethodsSessionGenericRequest { payment_method_session_id: payment_method_session_id.clone(), request: payload, }; Box::pin(api::server_wrap( flow, state, &req, request, |state, auth: auth::AuthenticationData, request, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::payment_methods_session_confirm( state, req_state, merchant_context, auth.profile, request.payment_method_session_id, request.request, ) }, &auth::V2ClientAuth( common_utils::types::authentication::ResourceId::PaymentMethodSession( payment_method_session_id, ), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionUpdateSavedPaymentMethod))] pub async fn payment_method_session_update_saved_payment_method( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodSessionId>, json_payload: web::Json< api_models::payment_methods::PaymentMethodSessionUpdateSavedPaymentMethod, >, ) -> HttpResponse { let flow = Flow::PaymentMethodSessionUpdateSavedPaymentMethod; let payload = json_payload.into_inner(); let payment_method_session_id = path.into_inner(); let request = PaymentMethodsSessionGenericRequest { payment_method_session_id: payment_method_session_id.clone(), request: payload, }; Box::pin(api::server_wrap( flow, state, &req, request, |state, auth: auth::AuthenticationData, request, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::payment_methods_session_update_payment_method( state, merchant_context, auth.profile, request.payment_method_session_id, request.request, ) }, &auth::V2ClientAuth( common_utils::types::authentication::ResourceId::PaymentMethodSession( payment_method_session_id, ), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionUpdateSavedPaymentMethod))] pub async fn payment_method_session_delete_saved_payment_method( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodSessionId>, json_payload: web::Json< api_models::payment_methods::PaymentMethodSessionDeleteSavedPaymentMethod, >, ) -> HttpResponse { let flow = Flow::PaymentMethodSessionDeleteSavedPaymentMethod; let payload = json_payload.into_inner(); let payment_method_session_id = path.into_inner(); let request = PaymentMethodsSessionGenericRequest { payment_method_session_id: payment_method_session_id.clone(), request: payload, }; Box::pin(api::server_wrap( flow, state, &req, request, |state, auth: auth::AuthenticationData, request, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::payment_methods_session_delete_payment_method( state, merchant_context, auth.profile, request.request.payment_method_id, request.payment_method_session_id, ) }, &auth::V2ClientAuth( common_utils::types::authentication::ResourceId::PaymentMethodSession( payment_method_session_id, ), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::NetworkTokenStatusCheck))] pub async fn network_token_status_check_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodId>, ) -> HttpResponse { let flow = Flow::NetworkTokenStatusCheck; let payment_method_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payment_method_id, |state, auth: auth::AuthenticationData, payment_method_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::check_network_token_status( state, merchant_context, payment_method_id, ) }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/payment_methods.rs
router::src::routes::payment_methods
11,590
true
// File: crates/router/src/routes/dummy_connector.rs // Module: router::src::routes::dummy_connector use actix_web::web; use router_env::{instrument, tracing}; use super::app; use crate::{ core::api_locking, services::{api, authentication as auth}, }; mod consts; mod core; mod errors; pub mod types; mod utils; #[cfg(all(feature = "dummy_connector", feature = "v1"))] #[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentCreate))] pub async fn dummy_connector_authorize_payment( state: web::Data<app::AppState>, req: actix_web::HttpRequest, path: web::Path<String>, ) -> impl actix_web::Responder { let flow = types::Flow::DummyPaymentAuthorize; let attempt_id = path.into_inner(); let payload = types::DummyConnectorPaymentConfirmRequest { attempt_id }; api::server_wrap( flow, state, &req, payload, |state, _: (), req, _| core::payment_authorize(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, ) .await } #[cfg(all(feature = "dummy_connector", feature = "v1"))] #[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentCreate))] pub async fn dummy_connector_complete_payment( state: web::Data<app::AppState>, req: actix_web::HttpRequest, path: web::Path<String>, json_payload: web::Query<types::DummyConnectorPaymentCompleteBody>, ) -> impl actix_web::Responder { let flow = types::Flow::DummyPaymentComplete; let attempt_id = path.into_inner(); let payload = types::DummyConnectorPaymentCompleteRequest { attempt_id, confirm: json_payload.confirm, }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, _: (), req, _| core::payment_complete(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "dummy_connector")] #[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentCreate))] pub async fn dummy_connector_payment( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<types::DummyConnectorPaymentRequest>, ) -> impl actix_web::Responder { let payload = json_payload.into_inner(); let flow = types::Flow::DummyPaymentCreate; Box::pin(api::server_wrap( flow, state, &req, payload, |state, _: (), req, _| core::payment(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "dummy_connector")] #[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentRetrieve))] pub async fn dummy_connector_payment_data( state: web::Data<app::AppState>, req: actix_web::HttpRequest, path: web::Path<String>, ) -> impl actix_web::Responder { let flow = types::Flow::DummyPaymentRetrieve; let payment_id = path.into_inner(); let payload = types::DummyConnectorPaymentRetrieveRequest { payment_id }; api::server_wrap( flow, state, &req, payload, |state, _: (), req, _| core::payment_data(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, ) .await } #[cfg(all(feature = "dummy_connector", feature = "v1"))] #[instrument(skip_all, fields(flow = ?types::Flow::DummyRefundCreate))] pub async fn dummy_connector_refund( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<types::DummyConnectorRefundRequest>, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl actix_web::Responder { let flow = types::Flow::DummyRefundCreate; let mut payload = json_payload.into_inner(); payload.payment_id = Some(path.into_inner()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, _: (), req, _| core::refund_payment(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "dummy_connector", feature = "v1"))] #[instrument(skip_all, fields(flow = ?types::Flow::DummyRefundRetrieve))] pub async fn dummy_connector_refund_data( state: web::Data<app::AppState>, req: actix_web::HttpRequest, path: web::Path<String>, ) -> impl actix_web::Responder { let flow = types::Flow::DummyRefundRetrieve; let refund_id = path.into_inner(); let payload = types::DummyConnectorRefundRetrieveRequest { refund_id }; api::server_wrap( flow, state, &req, payload, |state, _: (), req, _| core::refund_data(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, ) .await }
crates/router/src/routes/dummy_connector.rs
router::src::routes::dummy_connector
1,173
true
// File: crates/router/src/routes/hypersense.rs // Module: router::src::routes::hypersense use actix_web::{web, HttpRequest, HttpResponse}; use api_models::external_service_auth as external_service_auth_api; use router_env::Flow; use super::AppState; use crate::{ core::{api_locking, external_service_auth}, services::{ api, authentication::{self, ExternalServiceType}, }, }; pub async fn get_hypersense_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::HypersenseTokenRequest; Box::pin(api::server_wrap( flow, state, &req, (), |state, user, _, _| { external_service_auth::generate_external_token( state, user, ExternalServiceType::Hypersense, ) }, &authentication::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn signout_hypersense_token( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<external_service_auth_api::ExternalSignoutTokenRequest>, ) -> HttpResponse { let flow = Flow::HypersenseSignoutToken; Box::pin(api::server_wrap( flow, state.clone(), &http_req, json_payload.into_inner(), |state, _: (), json_payload, _| { external_service_auth::signout_external_token(state, json_payload) }, &authentication::NoAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn verify_hypersense_token( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<external_service_auth_api::ExternalVerifyTokenRequest>, ) -> HttpResponse { let flow = Flow::HypersenseVerifyToken; Box::pin(api::server_wrap( flow, state.clone(), &http_req, json_payload.into_inner(), |state, _: (), json_payload, _| { external_service_auth::verify_external_token( state, json_payload, ExternalServiceType::Hypersense, ) }, &authentication::NoAuth, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/hypersense.rs
router::src::routes::hypersense
514
true
// File: crates/router/src/routes/proxy.rs // Module: router::src::routes::proxy use actix_web::{web, Responder}; use router_env::{instrument, tracing, Flow}; use crate::{ self as app, core::{api_locking, proxy}, services::{api, authentication as auth}, types::domain, }; #[instrument(skip_all, fields(flow = ?Flow::Proxy))] pub async fn proxy( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Json<api_models::proxy::ProxyRequest>, ) -> impl Responder { let flow = Flow::Proxy; Box::pin(api::server_wrap( flow, state, &req, payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); proxy::proxy_core(state, merchant_context, req) }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/proxy.rs
router::src::routes::proxy
269
true
// File: crates/router/src/routes/refunds.rs // Module: router::src::routes::refunds use actix_web::{web, HttpRequest, HttpResponse}; use common_utils; use router_env::{instrument, tracing, Flow}; use super::app::AppState; #[cfg(feature = "v1")] use crate::core::refunds::*; #[cfg(feature = "v2")] use crate::core::refunds_v2::*; use crate::{ core::api_locking, services::{api, authentication as auth, authorization::permissions::Permission}, types::{api::refunds, domain}, }; #[cfg(feature = "v2")] /// A private module to hold internal types to be used in route handlers. /// This is because we will need to implement certain traits on these types which will have the resource id /// But the api payload will not contain the resource id /// So these types can hold the resource id along with actual api payload, on which api event and locking action traits can be implemented mod internal_payload_types { use super::*; // Serialize is implemented because of api events #[derive(Debug, serde::Serialize)] pub struct RefundsGenericRequestWithResourceId<T: serde::Serialize> { pub global_refund_id: common_utils::id_type::GlobalRefundId, pub payment_id: Option<common_utils::id_type::GlobalPaymentId>, #[serde(flatten)] pub payload: T, } impl<T: serde::Serialize> common_utils::events::ApiEventMetric for RefundsGenericRequestWithResourceId<T> { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { let refund_id = self.global_refund_id.clone(); let payment_id = self.payment_id.clone(); Some(common_utils::events::ApiEventsType::Refund { payment_id, refund_id, }) } } } /// Refunds - Create /// /// To create a refund against an already processed payment #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::RefundsCreate))] // #[post("")] pub async fn refunds_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<refunds::RefundRequest>, ) -> HttpResponse { let flow = Flow::RefundsCreate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); refund_create_core(state, merchant_context, auth.profile_id, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRefundWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::RefundsCreate))] // #[post("")] pub async fn refunds_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<refunds::RefundsCreateRequest>, ) -> HttpResponse { let flow = Flow::RefundsCreate; let global_refund_id = common_utils::id_type::GlobalRefundId::generate(&state.conf.cell_information.id); let payload = json_payload.into_inner(); let internal_refund_create_payload = internal_payload_types::RefundsGenericRequestWithResourceId { global_refund_id: global_refund_id.clone(), payment_id: Some(payload.payment_id.clone()), payload, }; let auth_type = if state.conf.merchant_id_auth.merchant_id_auth_enabled { &auth::MerchantIdAuth } else { auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfileRefundWrite, }, req.headers(), ) }; Box::pin(api::server_wrap( flow, state, &req, internal_refund_create_payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); refund_create_core( state, merchant_context, req.payload, global_refund_id.clone(), ) }, auth_type, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// Refunds - Retrieve (GET) /// /// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment #[instrument(skip_all, fields(flow))] // #[get("/{id}")] pub async fn refunds_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, query_params: web::Query<api_models::refunds::RefundsRetrieveBody>, ) -> HttpResponse { let refund_request = refunds::RefundsRetrieveRequest { refund_id: path.into_inner(), force_sync: query_params.force_sync, merchant_connector_details: None, }; let flow = match query_params.force_sync { Some(true) => Flow::RefundsRetrieveForceSync, _ => Flow::RefundsRetrieve, }; tracing::Span::current().record("flow", flow.to_string()); Box::pin(api::server_wrap( flow, state, &req, refund_request, |state, auth: auth::AuthenticationData, refund_request, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); refund_response_wrapper( state, merchant_context, auth.profile_id, refund_request, refund_retrieve_core_with_refund_id, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRefundRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow))] pub async fn refunds_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::GlobalRefundId>, query_params: web::Query<api_models::refunds::RefundsRetrieveBody>, ) -> HttpResponse { let refund_request = refunds::RefundsRetrieveRequest { refund_id: path.into_inner(), force_sync: query_params.force_sync, merchant_connector_details: None, }; let flow = match query_params.force_sync { Some(true) => Flow::RefundsRetrieveForceSync, _ => Flow::RefundsRetrieve, }; tracing::Span::current().record("flow", flow.to_string()); Box::pin(api::server_wrap( flow, state, &req, refund_request, |state, auth: auth::AuthenticationData, refund_request, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); refund_retrieve_core_with_refund_id( state, merchant_context, auth.profile, refund_request, ) }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfileRefundRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow))] pub async fn refunds_retrieve_with_gateway_creds( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::GlobalRefundId>, payload: web::Json<api_models::refunds::RefundsRetrievePayload>, ) -> HttpResponse { let flow = match payload.force_sync { Some(true) => Flow::RefundsRetrieveForceSync, _ => Flow::RefundsRetrieve, }; tracing::Span::current().record("flow", flow.to_string()); let refund_request = refunds::RefundsRetrieveRequest { refund_id: path.into_inner(), force_sync: payload.force_sync, merchant_connector_details: payload.merchant_connector_details.clone(), }; let auth_type = if state.conf.merchant_id_auth.merchant_id_auth_enabled { &auth::MerchantIdAuth } else { auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfileRefundRead, }, req.headers(), ) }; Box::pin(api::server_wrap( flow, state, &req, refund_request, |state, auth: auth::AuthenticationData, refund_request, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); refund_retrieve_core_with_refund_id( state, merchant_context, auth.profile, refund_request, ) }, auth_type, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// Refunds - Retrieve (POST) /// /// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment #[instrument(skip_all, fields(flow))] // #[post("/sync")] pub async fn refunds_retrieve_with_body( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<refunds::RefundsRetrieveRequest>, ) -> HttpResponse { let flow = match json_payload.force_sync { Some(true) => Flow::RefundsRetrieveForceSync, _ => Flow::RefundsRetrieve, }; tracing::Span::current().record("flow", flow.to_string()); Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); refund_response_wrapper( state, merchant_context, auth.profile_id, req, refund_retrieve_core_with_refund_id, ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// Refunds - Update /// /// To update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields #[instrument(skip_all, fields(flow = ?Flow::RefundsUpdate))] // #[post("/{id}")] pub async fn refunds_update( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<refunds::RefundUpdateRequest>, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::RefundsUpdate; let mut refund_update_req = json_payload.into_inner(); refund_update_req.refund_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, refund_update_req, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); refund_update_core(state, merchant_context, req) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::RefundsUpdate))] pub async fn refunds_metadata_update( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<refunds::RefundMetadataUpdateRequest>, path: web::Path<common_utils::id_type::GlobalRefundId>, ) -> HttpResponse { let flow = Flow::RefundsUpdate; let global_refund_id = path.into_inner(); let internal_payload = internal_payload_types::RefundsGenericRequestWithResourceId { global_refund_id: global_refund_id.clone(), payment_id: None, payload: json_payload.into_inner(), }; Box::pin(api::server_wrap( flow, state, &req, internal_payload, |state, auth: auth::AuthenticationData, req, _| { refund_metadata_update_core( state, auth.merchant_account, req.payload, global_refund_id.clone(), ) }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v1", feature = "olap"))] /// Refunds - List /// /// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided #[instrument(skip_all, fields(flow = ?Flow::RefundsList))] pub async fn refunds_list( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<api_models::refunds::RefundListRequest>, ) -> HttpResponse { let flow = Flow::RefundsList; Box::pin(api::server_wrap( flow, state, &req, payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); refund_list(state, merchant_context, None, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantRefundRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all, fields(flow = ?Flow::RefundsList))] pub async fn refunds_list( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<api_models::refunds::RefundListRequest>, ) -> HttpResponse { let flow = Flow::RefundsList; Box::pin(api::server_wrap( flow, state, &req, payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { refund_list(state, auth.merchant_account, auth.profile, req) }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantRefundRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v1", feature = "olap"))] /// Refunds - List at profile level /// /// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided #[instrument(skip_all, fields(flow = ?Flow::RefundsList))] pub async fn refunds_list_profile( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<api_models::refunds::RefundListRequest>, ) -> HttpResponse { let flow = Flow::RefundsList; Box::pin(api::server_wrap( flow, state, &req, payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); refund_list( state, merchant_context, auth.profile_id.map(|profile_id| vec![profile_id]), req, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRefundRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v1", feature = "olap"))] /// Refunds - Filter /// /// To list the refunds filters associated with list of connectors, currencies and payment statuses #[instrument(skip_all, fields(flow = ?Flow::RefundsList))] pub async fn refunds_filter_list( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<common_utils::types::TimeRange>, ) -> HttpResponse { let flow = Flow::RefundsList; Box::pin(api::server_wrap( flow, state, &req, payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); refund_filter_list(state, merchant_context, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantRefundRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v1", feature = "olap"))] /// Refunds - Filter V2 /// /// To list the refunds filters associated with list of connectors, currencies and payment statuses #[instrument(skip_all, fields(flow = ?Flow::RefundsFilters))] pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::RefundsFilters; Box::pin(api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); get_filters_for_refunds(state, merchant_context, None) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantRefundRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v1", feature = "olap"))] /// Refunds - Filter V2 at profile level /// /// To list the refunds filters associated with list of connectors, currencies and payment statuses #[instrument(skip_all, fields(flow = ?Flow::RefundsFilters))] pub async fn get_refunds_filters_profile( state: web::Data<AppState>, req: HttpRequest, ) -> HttpResponse { let flow = Flow::RefundsFilters; Box::pin(api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); get_filters_for_refunds( state, merchant_context, auth.profile_id.map(|profile_id| vec![profile_id]), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRefundRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all, fields(flow = ?Flow::RefundsAggregate))] pub async fn get_refunds_aggregates( state: web::Data<AppState>, req: HttpRequest, query_params: web::Query<common_utils::types::TimeRange>, ) -> HttpResponse { let flow = Flow::RefundsAggregate; let query_params = query_params.into_inner(); Box::pin(api::server_wrap( flow, state, &req, query_params, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); get_aggregates_for_refunds(state, merchant_context, None, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantRefundRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all, fields(flow = ?Flow::RefundsManualUpdate))] pub async fn refunds_manual_update( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<api_models::refunds::RefundManualUpdateRequest>, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::RefundsManualUpdate; let mut refund_manual_update_req = payload.into_inner(); refund_manual_update_req.refund_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, refund_manual_update_req, |state, _auth, req, _| refund_manual_update(state, req), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all, fields(flow = ?Flow::RefundsAggregate))] pub async fn get_refunds_aggregate_profile( state: web::Data<AppState>, req: HttpRequest, query_params: web::Query<common_utils::types::TimeRange>, ) -> HttpResponse { let flow = Flow::RefundsAggregate; let query_params = query_params.into_inner(); Box::pin(api::server_wrap( flow, state, &req, query_params, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); get_aggregates_for_refunds( state, merchant_context, auth.profile_id.map(|profile_id| vec![profile_id]), req, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRefundRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/refunds.rs
router::src::routes::refunds
5,264
true
// File: crates/router/src/routes/health.rs // Module: router::src::routes::health use actix_web::{web, HttpRequest}; use api_models::health_check::RouterHealthCheckResponse; use router_env::{instrument, logger, tracing, Flow}; use super::app; use crate::{ core::{api_locking, health_check::HealthCheckInterface}, errors::{self, RouterResponse}, routes::metrics, services::{api, authentication as auth}, }; /// . // #[logger::instrument(skip_all, name = "name1", level = "warn", fields( key1 = "val1" ))] #[instrument(skip_all, fields(flow = ?Flow::HealthCheck))] // #[actix_web::get("/health")] pub async fn health() -> impl actix_web::Responder { metrics::HEALTH_METRIC.add(1, &[]); logger::info!("Health was called"); actix_web::HttpResponse::Ok().body("health is good") } #[instrument(skip_all, fields(flow = ?Flow::DeepHealthCheck))] pub async fn deep_health_check( state: web::Data<app::AppState>, request: HttpRequest, ) -> impl actix_web::Responder { metrics::HEALTH_METRIC.add(1, &[]); let flow = Flow::DeepHealthCheck; Box::pin(api::server_wrap( flow, state, &request, (), |state, _: (), _, _| deep_health_check_func(state), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) .await } async fn deep_health_check_func( state: app::SessionState, ) -> RouterResponse<RouterHealthCheckResponse> { logger::info!("Deep health check was called"); logger::debug!("Database health check begin"); let db_status = state.health_check_db().await.map_err(|error| { let message = error.to_string(); error.change_context(errors::ApiErrorResponse::HealthCheckError { component: "Database", message, }) })?; logger::debug!("Database health check end"); logger::debug!("Redis health check begin"); let redis_status = state.health_check_redis().await.map_err(|error| { let message = error.to_string(); error.change_context(errors::ApiErrorResponse::HealthCheckError { component: "Redis", message, }) })?; logger::debug!("Redis health check end"); logger::debug!("Locker health check begin"); let locker_status = state.health_check_locker().await.map_err(|error| { let message = error.to_string(); error.change_context(errors::ApiErrorResponse::HealthCheckError { component: "Locker", message, }) })?; logger::debug!("Locker health check end"); logger::debug!("Analytics health check begin"); #[cfg(feature = "olap")] let analytics_status = state.health_check_analytics().await.map_err(|error| { let message = error.to_string(); error.change_context(errors::ApiErrorResponse::HealthCheckError { component: "Analytics", message, }) })?; logger::debug!("Analytics health check end"); logger::debug!("gRPC health check begin"); #[cfg(feature = "dynamic_routing")] let grpc_health_check = state.health_check_grpc().await.map_err(|error| { let message = error.to_string(); error.change_context(errors::ApiErrorResponse::HealthCheckError { component: "gRPC services", message, }) })?; logger::debug!("gRPC health check end"); logger::debug!("Decision Engine health check begin"); #[cfg(feature = "dynamic_routing")] let decision_engine_health_check = state .health_check_decision_engine() .await .map_err(|error| { let message = error.to_string(); error.change_context(errors::ApiErrorResponse::HealthCheckError { component: "Decision Engine service", message, }) })?; logger::debug!("Decision Engine health check end"); logger::debug!("Opensearch health check begin"); #[cfg(feature = "olap")] let opensearch_status = state.health_check_opensearch().await.map_err(|error| { let message = error.to_string(); error.change_context(errors::ApiErrorResponse::HealthCheckError { component: "Opensearch", message, }) })?; logger::debug!("Opensearch health check end"); logger::debug!("Outgoing Request health check begin"); let outgoing_check = state.health_check_outgoing().await.map_err(|error| { let message = error.to_string(); error.change_context(errors::ApiErrorResponse::HealthCheckError { component: "Outgoing Request", message, }) })?; logger::debug!("Outgoing Request health check end"); logger::debug!("Unified Connector Service health check begin"); let unified_connector_service_status = state .health_check_unified_connector_service() .await .map_err(|error| { let message = error.to_string(); error.change_context(errors::ApiErrorResponse::HealthCheckError { component: "Unified Connector Service", message, }) })?; logger::debug!("Unified Connector Service health check end"); let response = RouterHealthCheckResponse { database: db_status.into(), redis: redis_status.into(), vault: locker_status.into(), #[cfg(feature = "olap")] analytics: analytics_status.into(), #[cfg(feature = "olap")] opensearch: opensearch_status.into(), outgoing_request: outgoing_check.into(), #[cfg(feature = "dynamic_routing")] grpc_health_check, #[cfg(feature = "dynamic_routing")] decision_engine: decision_engine_health_check.into(), unified_connector_service: unified_connector_service_status.into(), }; Ok(api::ApplicationResponse::Json(response)) }
crates/router/src/routes/health.rs
router::src::routes::health
1,251
true
// File: crates/router/src/routes/payouts.rs // Module: router::src::routes::payouts use actix_web::{ body::{BoxBody, MessageBody}, web, HttpRequest, HttpResponse, Responder, }; use common_utils::id_type; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{api_locking, payouts::*}, services::{ api, authentication::{self as auth}, authorization::permissions::Permission, }, types::{api::payouts as payout_types, domain}, }; /// Payouts - Create #[instrument(skip_all, fields(flow = ?Flow::PayoutsCreate))] pub async fn payouts_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payout_types::PayoutCreateRequest>, ) -> HttpResponse { let flow = Flow::PayoutsCreate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payouts_create_core(state, merchant_context, req) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v1", feature = "payouts"))] /// Payouts - Retrieve #[instrument(skip_all, fields(flow = ?Flow::PayoutsRetrieve))] pub async fn payouts_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::PayoutId>, query_params: web::Query<payout_types::PayoutRetrieveBody>, ) -> HttpResponse { let payout_retrieve_request = payout_types::PayoutRetrieveRequest { payout_id: path.into_inner(), force_sync: query_params.force_sync.to_owned(), merchant_id: query_params.merchant_id.to_owned(), }; let flow = Flow::PayoutsRetrieve; Box::pin(api::server_wrap( flow, state, &req, payout_retrieve_request, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payouts_retrieve_core(state, merchant_context, auth.profile_id, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfilePayoutRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Payouts - Update #[instrument(skip_all, fields(flow = ?Flow::PayoutsUpdate))] pub async fn payouts_update( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::PayoutId>, json_payload: web::Json<payout_types::PayoutCreateRequest>, ) -> HttpResponse { let flow = Flow::PayoutsUpdate; let payout_id = path.into_inner(); let mut payout_update_payload = json_payload.into_inner(); payout_update_payload.payout_id = Some(payout_id); Box::pin(api::server_wrap( flow, state, &req, payout_update_payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payouts_update_core(state, merchant_context, req) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PayoutsConfirm))] pub async fn payouts_confirm( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payout_types::PayoutCreateRequest>, path: web::Path<id_type::PayoutId>, ) -> HttpResponse { let flow = Flow::PayoutsConfirm; let mut payload = json_payload.into_inner(); let payout_id = path.into_inner(); tracing::Span::current().record("payout_id", payout_id.get_string_repr()); payload.payout_id = Some(payout_id); payload.confirm = Some(true); let api_auth = auth::ApiKeyAuth::default(); let (auth_type, _auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok(auth) => auth, Err(e) => return api::log_and_return_error_response(e), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payouts_confirm_core(state, merchant_context, req) }, &*auth_type, api_locking::LockAction::NotApplicable, )) .await } /// Payouts - Cancel #[instrument(skip_all, fields(flow = ?Flow::PayoutsCancel))] pub async fn payouts_cancel( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::PayoutId>, ) -> HttpResponse { let flow = Flow::PayoutsCancel; let payload = payout_types::PayoutActionRequest { payout_id: path.into_inner(), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payouts_cancel_core(state, merchant_context, req) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } /// Payouts - Fulfill #[instrument(skip_all, fields(flow = ?Flow::PayoutsFulfill))] pub async fn payouts_fulfill( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::PayoutId>, ) -> HttpResponse { let flow = Flow::PayoutsFulfill; let payload = payout_types::PayoutActionRequest { payout_id: path.into_inner(), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payouts_fulfill_core(state, merchant_context, req) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } /// Payouts - List #[cfg(feature = "olap")] #[instrument(skip_all, fields(flow = ?Flow::PayoutsList))] pub async fn payouts_list( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Query<payout_types::PayoutListConstraints>, ) -> HttpResponse { let flow = Flow::PayoutsList; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payouts_list_core(state, merchant_context, None, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantPayoutRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Payouts - List Profile #[cfg(all(feature = "olap", feature = "payouts", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::PayoutsList))] pub async fn payouts_list_profile( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Query<payout_types::PayoutListConstraints>, ) -> HttpResponse { let flow = Flow::PayoutsList; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payouts_list_core( state, merchant_context, auth.profile_id.map(|profile_id| vec![profile_id]), req, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfilePayoutRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Payouts - Filtered list #[cfg(feature = "olap")] #[instrument(skip_all, fields(flow = ?Flow::PayoutsList))] pub async fn payouts_list_by_filter( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payout_types::PayoutListFilterConstraints>, ) -> HttpResponse { let flow = Flow::PayoutsList; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payouts_filtered_list_core(state, merchant_context, None, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantPayoutRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Payouts - Filtered list #[cfg(all(feature = "olap", feature = "payouts", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::PayoutsList))] pub async fn payouts_list_by_filter_profile( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payout_types::PayoutListFilterConstraints>, ) -> HttpResponse { let flow = Flow::PayoutsList; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payouts_filtered_list_core( state, merchant_context, auth.profile_id.map(|profile_id| vec![profile_id]), req, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfilePayoutRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Payouts - Available filters for Merchant #[cfg(feature = "olap")] #[instrument(skip_all, fields(flow = ?Flow::PayoutsFilter))] pub async fn payouts_list_available_filters_for_merchant( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<common_utils::types::TimeRange>, ) -> HttpResponse { let flow = Flow::PayoutsFilter; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payouts_list_available_filters_core(state, merchant_context, None, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantPayoutRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Payouts - Available filters for Profile #[cfg(all(feature = "olap", feature = "payouts", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::PayoutsFilter))] pub async fn payouts_list_available_filters_for_profile( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<common_utils::types::TimeRange>, ) -> HttpResponse { let flow = Flow::PayoutsFilter; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payouts_list_available_filters_core( state, merchant_context, auth.profile_id.map(|profile_id| vec![profile_id]), req, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfilePayoutRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PayoutsAccounts))] // #[get("/accounts")] pub async fn payouts_accounts() -> impl Responder { let _flow = Flow::PayoutsAccounts; http_response("accounts") } fn http_response<T: MessageBody + 'static>(response: T) -> HttpResponse<BoxBody> { HttpResponse::Ok().body(response) }
crates/router/src/routes/payouts.rs
router::src::routes::payouts
3,372
true
// File: crates/router/src/routes/fraud_check.rs // Module: router::src::routes::fraud_check use actix_web::{web, HttpRequest, HttpResponse}; use router_env::Flow; use crate::{ core::{api_locking, fraud_check as frm_core}, services::{self, api}, types::domain, AppState, }; #[cfg(feature = "v1")] pub async fn frm_fulfillment( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<frm_core::types::FrmFulfillmentRequest>, ) -> HttpResponse { let flow = Flow::FrmFulfillment; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, auth: services::authentication::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); frm_core::frm_fulfillment_core(state, merchant_context, req) }, &services::authentication::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/fraud_check.rs
router::src::routes::fraud_check
276
true
// File: crates/router/src/routes/lock_utils.rs // Module: router::src::routes::lock_utils use router_env::Flow; #[derive(Clone, Debug, strum::Display)] #[strum(serialize_all = "snake_case")] pub enum ApiIdentifier { Payments, Refunds, Webhooks, Organization, MerchantAccount, MerchantConnector, Configs, Customers, Ephemeral, Health, Mandates, PaymentMethods, PaymentMethodAuth, Payouts, Disputes, CardsInfo, Files, Cache, Profile, Verification, ApiKeys, PaymentLink, Routing, Subscription, Blocklist, Forex, RustLockerMigration, Gsm, Role, User, UserRole, ConnectorOnboarding, Recon, AiWorkflow, Poll, ApplePayCertificatesMigration, Relay, Documentation, CardNetworkTokenization, Hypersense, PaymentMethodSession, ProcessTracker, Authentication, Proxy, ProfileAcquirer, ThreeDsDecisionRule, GenericTokenization, RecoveryRecovery, } impl From<Flow> for ApiIdentifier { fn from(flow: Flow) -> Self { match flow { Flow::MerchantsAccountCreate | Flow::MerchantsAccountRetrieve | Flow::MerchantsAccountUpdate | Flow::MerchantsAccountDelete | Flow::MerchantTransferKey | Flow::MerchantAccountList | Flow::EnablePlatformAccount => Self::MerchantAccount, Flow::OrganizationCreate | Flow::OrganizationRetrieve | Flow::OrganizationUpdate => { Self::Organization } Flow::RoutingCreateConfig | Flow::RoutingLinkConfig | Flow::RoutingUnlinkConfig | Flow::RoutingRetrieveConfig | Flow::RoutingRetrieveActiveConfig | Flow::RoutingRetrieveDefaultConfig | Flow::RoutingRetrieveDictionary | Flow::RoutingUpdateConfig | Flow::RoutingUpdateDefaultConfig | Flow::RoutingDeleteConfig | Flow::DecisionManagerDeleteConfig | Flow::DecisionManagerRetrieveConfig | Flow::ToggleDynamicRouting | Flow::CreateDynamicRoutingConfig | Flow::UpdateDynamicRoutingConfigs | Flow::DecisionManagerUpsertConfig | Flow::RoutingEvaluateRule | Flow::DecisionEngineRuleMigration | Flow::VolumeSplitOnRoutingType | Flow::DecisionEngineDecideGatewayCall | Flow::DecisionEngineGatewayFeedbackCall => Self::Routing, Flow::CreateSubscription | Flow::ConfirmSubscription | Flow::CreateAndConfirmSubscription | Flow::GetSubscription | Flow::UpdateSubscription | Flow::GetSubscriptionEstimate | Flow::GetPlansForSubscription => Self::Subscription, Flow::RetrieveForexFlow => Self::Forex, Flow::AddToBlocklist => Self::Blocklist, Flow::DeleteFromBlocklist => Self::Blocklist, Flow::ListBlocklist => Self::Blocklist, Flow::ToggleBlocklistGuard => Self::Blocklist, Flow::MerchantConnectorsCreate | Flow::MerchantConnectorsRetrieve | Flow::MerchantConnectorsUpdate | Flow::MerchantConnectorsDelete | Flow::MerchantConnectorsList => Self::MerchantConnector, Flow::ConfigKeyCreate | Flow::ConfigKeyFetch | Flow::ConfigKeyUpdate | Flow::ConfigKeyDelete | Flow::CreateConfigKey => Self::Configs, Flow::CustomersCreate | Flow::CustomersRetrieve | Flow::CustomersUpdate | Flow::CustomersDelete | Flow::CustomersGetMandates | Flow::CustomersList | Flow::CustomersListWithConstraints => Self::Customers, Flow::EphemeralKeyCreate | Flow::EphemeralKeyDelete => Self::Ephemeral, Flow::DeepHealthCheck | Flow::HealthCheck => Self::Health, Flow::MandatesRetrieve | Flow::MandatesRevoke | Flow::MandatesList => Self::Mandates, Flow::PaymentMethodsCreate | Flow::PaymentMethodsMigrate | Flow::PaymentMethodsBatchUpdate | Flow::PaymentMethodsList | Flow::CustomerPaymentMethodsList | Flow::GetPaymentMethodTokenData | Flow::PaymentMethodsRetrieve | Flow::PaymentMethodsUpdate | Flow::PaymentMethodsDelete | Flow::NetworkTokenStatusCheck | Flow::PaymentMethodCollectLink | Flow::ValidatePaymentMethod | Flow::ListCountriesCurrencies | Flow::DefaultPaymentMethodsSet | Flow::PaymentMethodSave | Flow::TotalPaymentMethodCount => Self::PaymentMethods, Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth, Flow::PaymentsCreate | Flow::PaymentsRetrieve | Flow::PaymentsRetrieveForceSync | Flow::PaymentsUpdate | Flow::PaymentsConfirm | Flow::PaymentsCapture | Flow::PaymentsCancel | Flow::PaymentsCancelPostCapture | Flow::PaymentsApprove | Flow::PaymentsReject | Flow::PaymentsSessionToken | Flow::PaymentsStart | Flow::PaymentsList | Flow::PaymentsFilters | Flow::PaymentsAggregate | Flow::PaymentsRedirect | Flow::PaymentsIncrementalAuthorization | Flow::PaymentsExtendAuthorization | Flow::PaymentsExternalAuthentication | Flow::PaymentsAuthorize | Flow::GetExtendedCardInfo | Flow::PaymentsCompleteAuthorize | Flow::PaymentsManualUpdate | Flow::SessionUpdateTaxCalculation | Flow::PaymentsConfirmIntent | Flow::PaymentsCreateIntent | Flow::PaymentsGetIntent | Flow::GiftCardBalanceCheck | Flow::PaymentsPostSessionTokens | Flow::PaymentsUpdateMetadata | Flow::PaymentsUpdateIntent | Flow::PaymentsCreateAndConfirmIntent | Flow::PaymentStartRedirection | Flow::ProxyConfirmIntent | Flow::PaymentsRetrieveUsingMerchantReferenceId | Flow::PaymentAttemptsList | Flow::RecoveryPaymentsCreate | Flow::PaymentsSubmitEligibility => Self::Payments, Flow::PayoutsCreate | Flow::PayoutsRetrieve | Flow::PayoutsUpdate | Flow::PayoutsCancel | Flow::PayoutsFulfill | Flow::PayoutsList | Flow::PayoutsFilter | Flow::PayoutsAccounts | Flow::PayoutsConfirm | Flow::PayoutLinkInitiate => Self::Payouts, Flow::RefundsCreate | Flow::RefundsRetrieve | Flow::RefundsRetrieveForceSync | Flow::RefundsUpdate | Flow::RefundsList | Flow::RefundsFilters | Flow::RefundsAggregate | Flow::RefundsManualUpdate => Self::Refunds, Flow::Relay | Flow::RelayRetrieve => Self::Relay, Flow::FrmFulfillment | Flow::IncomingWebhookReceive | Flow::IncomingRelayWebhookReceive | Flow::WebhookEventInitialDeliveryAttemptList | Flow::WebhookEventDeliveryAttemptList | Flow::WebhookEventDeliveryRetry | Flow::RecoveryIncomingWebhookReceive | Flow::IncomingNetworkTokenWebhookReceive => Self::Webhooks, Flow::ApiKeyCreate | Flow::ApiKeyRetrieve | Flow::ApiKeyUpdate | Flow::ApiKeyRevoke | Flow::ApiKeyList => Self::ApiKeys, Flow::DisputesRetrieve | Flow::DisputesList | Flow::DisputesFilters | Flow::DisputesEvidenceSubmit | Flow::AttachDisputeEvidence | Flow::RetrieveDisputeEvidence | Flow::DisputesAggregate | Flow::DeleteDisputeEvidence => Self::Disputes, Flow::CardsInfo | Flow::CardsInfoCreate | Flow::CardsInfoUpdate | Flow::CardsInfoMigrate => Self::CardsInfo, Flow::CreateFile | Flow::DeleteFile | Flow::RetrieveFile => Self::Files, Flow::CacheInvalidate => Self::Cache, Flow::ProfileCreate | Flow::ProfileUpdate | Flow::ProfileRetrieve | Flow::ProfileDelete | Flow::ProfileList | Flow::ToggleExtendedCardInfo | Flow::ToggleConnectorAgnosticMit => Self::Profile, Flow::PaymentLinkRetrieve | Flow::PaymentLinkInitiate | Flow::PaymentSecureLinkInitiate | Flow::PaymentLinkList | Flow::PaymentLinkStatus => Self::PaymentLink, Flow::Verification => Self::Verification, Flow::RustLockerMigration => Self::RustLockerMigration, Flow::GsmRuleCreate | Flow::GsmRuleRetrieve | Flow::GsmRuleUpdate | Flow::GsmRuleDelete => Self::Gsm, Flow::ApplePayCertificatesMigration => Self::ApplePayCertificatesMigration, Flow::UserConnectAccount | Flow::UserSignUp | Flow::UserSignIn | Flow::Signout | Flow::ChangePassword | Flow::SetDashboardMetadata | Flow::GetMultipleDashboardMetadata | Flow::VerifyPaymentConnector | Flow::InternalUserSignup | Flow::TenantUserCreate | Flow::SwitchOrg | Flow::SwitchMerchantV2 | Flow::SwitchProfile | Flow::CreatePlatformAccount | Flow::UserOrgMerchantCreate | Flow::UserMerchantAccountCreate | Flow::GenerateSampleData | Flow::DeleteSampleData | Flow::GetUserDetails | Flow::GetUserRoleDetails | Flow::ForgotPassword | Flow::ResetPassword | Flow::RotatePassword | Flow::InviteMultipleUser | Flow::ReInviteUser | Flow::UserSignUpWithMerchantId | Flow::VerifyEmail | Flow::AcceptInviteFromEmail | Flow::VerifyEmailRequest | Flow::UpdateUserAccountDetails | Flow::TotpBegin | Flow::TotpReset | Flow::TotpVerify | Flow::TotpUpdate | Flow::RecoveryCodeVerify | Flow::RecoveryCodesGenerate | Flow::TerminateTwoFactorAuth | Flow::TwoFactorAuthStatus | Flow::CreateUserAuthenticationMethod | Flow::UpdateUserAuthenticationMethod | Flow::ListUserAuthenticationMethods | Flow::UserTransferKey | Flow::GetSsoAuthUrl | Flow::SignInWithSso | Flow::ListOrgForUser | Flow::ListMerchantsForUserInOrg | Flow::ListProfileForUserInOrgAndMerchant | Flow::ListInvitationsForUser | Flow::AuthSelect | Flow::GetThemeUsingLineage | Flow::GetThemeUsingThemeId | Flow::UploadFileToThemeStorage | Flow::CreateTheme | Flow::UpdateTheme | Flow::DeleteTheme | Flow::CreateUserTheme | Flow::UpdateUserTheme | Flow::DeleteUserTheme | Flow::GetUserThemeUsingThemeId | Flow::UploadFileToUserThemeStorage | Flow::GetUserThemeUsingLineage | Flow::ListAllThemesInLineage | Flow::CloneConnector => Self::User, Flow::GetDataFromHyperswitchAiFlow | Flow::ListAllChatInteractions => Self::AiWorkflow, Flow::ListRolesV2 | Flow::ListInvitableRolesAtEntityLevel | Flow::ListUpdatableRolesAtEntityLevel | Flow::GetRole | Flow::GetRoleV2 | Flow::GetRoleFromToken | Flow::GetRoleFromTokenV2 | Flow::GetParentGroupsInfoForRoleFromToken | Flow::UpdateUserRole | Flow::GetAuthorizationInfo | Flow::GetRolesInfo | Flow::GetParentGroupInfo | Flow::AcceptInvitationsV2 | Flow::AcceptInvitationsPreAuth | Flow::DeleteUserRole | Flow::CreateRole | Flow::CreateRoleV2 | Flow::UpdateRole | Flow::UserFromEmail | Flow::ListUsersInLineage => Self::UserRole, Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => { Self::ConnectorOnboarding } Flow::ReconMerchantUpdate | Flow::ReconTokenRequest | Flow::ReconServiceRequest | Flow::ReconVerifyToken => Self::Recon, Flow::RetrievePollStatus => Self::Poll, Flow::FeatureMatrix => Self::Documentation, Flow::TokenizeCard | Flow::TokenizeCardUsingPaymentMethodId | Flow::TokenizeCardBatch => Self::CardNetworkTokenization, Flow::HypersenseTokenRequest | Flow::HypersenseVerifyToken | Flow::HypersenseSignoutToken => Self::Hypersense, Flow::PaymentMethodSessionCreate | Flow::PaymentMethodSessionRetrieve | Flow::PaymentMethodSessionConfirm | Flow::PaymentMethodSessionUpdateSavedPaymentMethod | Flow::PaymentMethodSessionDeleteSavedPaymentMethod | Flow::PaymentMethodSessionUpdate => Self::PaymentMethodSession, Flow::RevenueRecoveryRetrieve | Flow::RevenueRecoveryResume => Self::ProcessTracker, Flow::AuthenticationCreate | Flow::AuthenticationEligibility | Flow::AuthenticationSync | Flow::AuthenticationSyncPostUpdate | Flow::AuthenticationAuthenticate => Self::Authentication, Flow::Proxy => Self::Proxy, Flow::ProfileAcquirerCreate | Flow::ProfileAcquirerUpdate => Self::ProfileAcquirer, Flow::ThreeDsDecisionRuleExecute => Self::ThreeDsDecisionRule, Flow::TokenizationCreate | Flow::TokenizationRetrieve | Flow::TokenizationDelete => { Self::GenericTokenization } Flow::RecoveryDataBackfill | Flow::RevenueRecoveryRedis => Self::RecoveryRecovery, } } }
crates/router/src/routes/lock_utils.rs
router::src::routes::lock_utils
3,153
true
// File: crates/router/src/routes/cards_info.rs // Module: router::src::routes::cards_info use actix_multipart::form::MultipartForm; use actix_web::{web, HttpRequest, HttpResponse, Responder}; use api_models::cards_info as cards_info_api_types; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{api_locking, cards_info}, services::{api, authentication as auth}, types::domain, }; #[cfg(feature = "v1")] /// Cards Info - Retrieve /// /// Retrieve the card information given the card bin #[utoipa::path( get, path = "/cards/{bin}", params(("bin" = String, Path, description = "The first 6 or 9 digits of card")), responses( (status = 200, description = "Card iin data found", body = CardInfoResponse), (status = 404, description = "Card iin data not found") ), operation_id = "Retrieve card information", security(("api_key" = []), ("publishable_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::CardsInfo))] pub async fn card_iin_info( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, payload: web::Query<api_models::cards_info::CardsInfoRequestParams>, ) -> impl Responder { let card_iin = path.into_inner(); let request_params = payload.into_inner(); let payload = api_models::cards_info::CardsInfoRequest { client_secret: request_params.client_secret, card_iin, }; let api_auth = auth::ApiKeyAuth::default(); let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok((auth, _auth_flow)) => (auth, _auth_flow), Err(e) => return api::log_and_return_error_response(e), }; Box::pin(api::server_wrap( Flow::CardsInfo, state, &req, payload, |state, auth, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); cards_info::retrieve_card_info(state, merchant_context, req) }, &*auth, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::CardsInfoCreate))] pub async fn create_cards_info( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<cards_info_api_types::CardInfoCreateRequest>, ) -> impl Responder { let payload = json_payload.into_inner(); let flow = Flow::CardsInfoCreate; Box::pin(api::server_wrap( flow, state.clone(), &req, payload, |state, _, payload, _| cards_info::create_card_info(state, payload), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::CardsInfoUpdate))] pub async fn update_cards_info( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<cards_info_api_types::CardInfoUpdateRequest>, ) -> impl Responder { let payload = json_payload.into_inner(); let flow = Flow::CardsInfoUpdate; Box::pin(api::server_wrap( flow, state.clone(), &req, payload, |state, _, payload, _| cards_info::update_card_info(state, payload), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] #[instrument(skip_all, fields(flow = ?Flow::CardsInfoMigrate))] pub async fn migrate_cards_info( state: web::Data<AppState>, req: HttpRequest, MultipartForm(form): MultipartForm<cards_info::CardsInfoUpdateForm>, ) -> HttpResponse { let flow = Flow::CardsInfoMigrate; let records = match cards_info::get_cards_bin_records(form) { Ok(records) => records, Err(e) => return api::log_and_return_error_response(e.into()), }; Box::pin(api::server_wrap( flow, state.clone(), &req, records, |state, _, payload, _| cards_info::migrate_cards_info(state, payload), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/cards_info.rs
router::src::routes::cards_info
1,039
true
// File: crates/router/src/routes/revenue_recovery_data_backfill.rs // Module: router::src::routes::revenue_recovery_data_backfill use actix_multipart::form::MultipartForm; use actix_web::{web, HttpRequest, HttpResponse}; use api_models::revenue_recovery_data_backfill::{ BackfillQuery, GetRedisDataQuery, RevenueRecoveryDataBackfillForm, UpdateTokenStatusRequest, }; use router_env::{instrument, tracing, Flow}; use crate::{ core::{api_locking, revenue_recovery_data_backfill}, routes::AppState, services::{api, authentication as auth}, types::{domain, storage}, }; #[instrument(skip_all, fields(flow = ?Flow::RecoveryDataBackfill))] pub async fn revenue_recovery_data_backfill( state: web::Data<AppState>, req: HttpRequest, query: web::Query<BackfillQuery>, MultipartForm(form): MultipartForm<RevenueRecoveryDataBackfillForm>, ) -> HttpResponse { let flow = Flow::RecoveryDataBackfill; // Parse cutoff_time from query parameter let cutoff_datetime = match query .cutoff_time .as_ref() .map(|time_str| { time::PrimitiveDateTime::parse( time_str, &time::format_description::well_known::Iso8601::DEFAULT, ) }) .transpose() { Ok(datetime) => datetime, Err(err) => { return HttpResponse::BadRequest().json(serde_json::json!({ "error": format!("Invalid datetime format: {}. Use ISO8601: 2024-01-15T10:30:00", err) })); } }; let records = match form.validate_and_get_records_with_errors() { Ok(records) => records, Err(e) => { return HttpResponse::BadRequest().json(serde_json::json!({ "error": e.to_string() })); } }; Box::pin(api::server_wrap( flow, state, &req, records, |state, _, records, _req| { revenue_recovery_data_backfill::revenue_recovery_data_backfill( state, records.records, cutoff_datetime, ) }, &auth::V2AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::RecoveryDataBackfill))] pub async fn update_revenue_recovery_additional_redis_data( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<UpdateTokenStatusRequest>, ) -> HttpResponse { let flow = Flow::RecoveryDataBackfill; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, _: (), request, _| { revenue_recovery_data_backfill::redis_update_additional_details_for_revenue_recovery( state, request, ) }, &auth::V2AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::RecoveryDataBackfill))] pub async fn revenue_recovery_data_backfill_status( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::RecoveryDataBackfill; let connector_customer_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, connector_customer_id, |state, _: (), id, _| { revenue_recovery_data_backfill::unlock_connector_customer_status(state, id) }, &auth::V2AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/revenue_recovery_data_backfill.rs
router::src::routes::revenue_recovery_data_backfill
833
true
// File: crates/router/src/routes/configs.rs // Module: router::src::routes::configs use actix_web::{web, HttpRequest, Responder}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{api_locking, configs}, services::{api, authentication as auth}, types::api as api_types, }; #[cfg(feature = "v1")] const ADMIN_API_AUTH: auth::AdminApiAuth = auth::AdminApiAuth; #[cfg(feature = "v2")] const ADMIN_API_AUTH: auth::V2AdminApiAuth = auth::V2AdminApiAuth; #[instrument(skip_all, fields(flow = ?Flow::CreateConfigKey))] pub async fn config_key_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_types::Config>, ) -> impl Responder { let flow = Flow::CreateConfigKey; let payload = json_payload.into_inner(); api::server_wrap( flow, state, &req, payload, |state, _, data, _| configs::set_config(state, data), &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, ) .await } #[instrument(skip_all, fields(flow = ?Flow::ConfigKeyFetch))] pub async fn config_key_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> impl Responder { let flow = Flow::ConfigKeyFetch; let key = path.into_inner(); api::server_wrap( flow, state, &req, &key, |state, _, key, _| configs::read_config(state, key), &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, ) .await } #[instrument(skip_all, fields(flow = ?Flow::ConfigKeyUpdate))] pub async fn config_key_update( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, json_payload: web::Json<api_types::ConfigUpdate>, ) -> impl Responder { let flow = Flow::ConfigKeyUpdate; let mut payload = json_payload.into_inner(); let key = path.into_inner(); payload.key = key; api::server_wrap( flow, state, &req, &payload, |state, _, payload, _| configs::update_config(state, payload), &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, ) .await } #[instrument(skip_all, fields(flow = ?Flow::ConfigKeyDelete))] pub async fn config_key_delete( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> impl Responder { let flow = Flow::ConfigKeyDelete; let key = path.into_inner(); api::server_wrap( flow, state, &req, key, |state, _, key, _| configs::config_delete(state, key), &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, ) .await }
crates/router/src/routes/configs.rs
router::src::routes::configs
686
true
// File: crates/router/src/routes/payout_link.rs // Module: router::src::routes::payout_link use actix_web::{web, Responder}; use api_models::payouts::PayoutLinkInitiateRequest; use router_env::Flow; use crate::{ core::{api_locking, payout_link::*}, services::{ api, authentication::{self as auth}, }, types::domain, AppState, }; #[cfg(feature = "v1")] pub async fn render_payout_link( state: web::Data<AppState>, req: actix_web::HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::PayoutId, )>, ) -> impl Responder { let flow = Flow::PayoutLinkInitiate; let (merchant_id, payout_id) = path.into_inner(); let payload = PayoutLinkInitiateRequest { merchant_id: merchant_id.clone(), payout_id, }; let headers = req.headers(); Box::pin(api::server_wrap( flow, state, &req, payload.clone(), |state, auth, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); initiate_payout_link(state, merchant_context, req, headers) }, &auth::MerchantIdAuth(merchant_id), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/payout_link.rs
router::src::routes::payout_link
334
true
// File: crates/router/src/routes/verification.rs // Module: router::src::routes::verification use actix_web::{web, HttpRequest, Responder}; use api_models::verifications; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{api_locking, verification}, services::{api, authentication as auth, authorization::permissions::Permission}, }; #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::Verification))] pub async fn apple_pay_merchant_registration( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<verifications::ApplepayMerchantVerificationRequest>, path: web::Path<common_utils::id_type::MerchantId>, ) -> impl Responder { let flow = Flow::Verification; let merchant_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, body, _| { verification::verify_merchant_creds_for_applepay( state.clone(), body, merchant_id.clone(), auth.profile_id, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileAccountWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all, fields(flow = ?Flow::Verification))] pub async fn apple_pay_merchant_registration( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<verifications::ApplepayMerchantVerificationRequest>, path: web::Path<common_utils::id_type::MerchantId>, ) -> impl Responder { let flow = Flow::Verification; let merchant_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, body, _| { verification::verify_merchant_creds_for_applepay( state.clone(), body, merchant_id.clone(), Some(auth.profile.get_id().clone()), ) }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfileAccountWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::Verification))] pub async fn retrieve_apple_pay_verified_domains( state: web::Data<AppState>, req: HttpRequest, params: web::Query<verifications::ApplepayGetVerifiedDomainsParam>, ) -> impl Responder { let flow = Flow::Verification; let merchant_id = &params.merchant_id; let mca_id = &params.merchant_connector_account_id; Box::pin(api::server_wrap( flow, state, &req, merchant_id.clone(), |state, _: auth::AuthenticationData, _, _| { verification::get_verified_apple_domains_with_mid_mca_id( state, merchant_id.to_owned(), mca_id.clone(), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantAccountRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/verification.rs
router::src::routes::verification
843
true
// File: crates/router/src/routes/payments.rs // Module: router::src::routes::payments use crate::{ core::api_locking::{self, GetLockingInput}, services::authorization::permissions::Permission, }; pub mod helpers; use actix_web::{web, Responder}; use error_stack::report; use hyperswitch_domain_models::payments::HeaderPayload; use masking::PeekInterface; use router_env::{env, instrument, logger, tracing, types, Flow}; use super::app::ReqState; #[cfg(feature = "v2")] use crate::core::gift_card; #[cfg(feature = "v2")] use crate::core::revenue_recovery::api as recovery; use crate::{ self as app, core::{ errors::{self, http_not_implemented}, payments::{self, PaymentRedirectFlow}, }, routes::lock_utils, services::{api, authentication as auth}, types::{ api::{ self as api_types, enums as api_enums, payments::{self as payment_types, PaymentIdTypeExt}, }, domain, transformers::ForeignTryFrom, }, }; #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCreate, payment_id))] pub async fn payments_create( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsRequest>, ) -> impl Responder { let flow = Flow::PaymentsCreate; let mut payload = json_payload.into_inner(); if let Err(err) = payload .validate() .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message }) { return api::log_and_return_error_response(err.into()); }; if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method { return http_not_implemented(); }; if let Err(err) = get_or_generate_payment_id(&mut payload) { return api::log_and_return_error_response(err); } let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; tracing::Span::current().record( "payment_id", payload .payment_id .as_ref() .map(|payment_id_type| payment_id_type.get_payment_intent_id()) .transpose() .unwrap_or_default() .as_ref() .map(|id| id.get_string_repr()) .unwrap_or_default(), ); let locking_action = payload.get_locking_input(flow.clone()); let auth_type = match env::which() { env::Env::Production => { &auth::InternalMerchantIdProfileIdAuth(auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, })) } _ => auth::auth_type( &auth::InternalMerchantIdProfileIdAuth(auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, })), &auth::InternalMerchantIdProfileIdAuth(auth::JWTAuth { permission: Permission::ProfilePaymentWrite, }), req.headers(), ), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); authorize_verify_select::<_>( payments::PaymentCreate, state, req_state, merchant_context, auth.profile_id, header_payload.clone(), req, api::AuthFlow::Client, ) }, auth_type, locking_action, )) .await } #[cfg(feature = "v2")] pub async fn recovery_payments_create( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::RecoveryPaymentsCreate>, ) -> impl Responder { let flow = Flow::RecoveryPaymentsCreate; let mut payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req.clone(), payload, |state, auth: auth::AuthenticationData, req_payload, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); recovery::custom_revenue_recovery_core( state.to_owned(), req_state, merchant_context, auth.profile, req_payload, ) }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCreateIntent, payment_id))] pub async fn payments_create_intent( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsCreateIntentRequest>, ) -> impl Responder { use hyperswitch_domain_models::payments::PaymentIntentData; let flow = Flow::PaymentsCreateIntent; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; let global_payment_id = common_utils::id_type::GlobalPaymentId::generate(&state.conf.cell_information.id); Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_intent_core::< api_types::PaymentCreateIntent, payment_types::PaymentsIntentResponse, _, _, PaymentIntentData<api_types::PaymentCreateIntent>, >( state, req_state, merchant_context, auth.profile, payments::operations::PaymentIntentCreate, req, global_payment_id.clone(), header_payload.clone(), ) }, match env::which() { env::Env::Production => &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, _ => auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfilePaymentWrite, }, req.headers(), ), }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsGetIntent, payment_id))] pub async fn payments_get_intent( state: web::Data<app::AppState>, req: actix_web::HttpRequest, path: web::Path<common_utils::id_type::GlobalPaymentId>, ) -> impl Responder { use api_models::payments::PaymentsGetIntentRequest; use hyperswitch_domain_models::payments::PaymentIntentData; let flow = Flow::PaymentsGetIntent; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; let payload = PaymentsGetIntentRequest { id: path.into_inner(), }; let global_payment_id = payload.id.clone(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_intent_core::< api_types::PaymentGetIntent, payment_types::PaymentsIntentResponse, _, _, PaymentIntentData<api_types::PaymentGetIntent>, >( state, req_state, merchant_context, auth.profile, payments::operations::PaymentGetIntent, req, global_payment_id.clone(), header_payload.clone(), ) }, auth::api_or_client_or_jwt_auth( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( global_payment_id.clone(), )), &auth::JWTAuth { permission: Permission::ProfileRevenueRecoveryRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentAttemptsList, payment_id,))] pub async fn list_payment_attempts( state: web::Data<app::AppState>, req: actix_web::HttpRequest, path: web::Path<common_utils::id_type::GlobalPaymentId>, ) -> impl Responder { let flow = Flow::PaymentAttemptsList; let payment_intent_id = path.into_inner(); let payload = api_models::payments::PaymentAttemptListRequest { payment_intent_id: payment_intent_id.clone(), }; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; Box::pin(api::server_wrap( flow, state, &req, payload.clone(), |session_state, auth, req_payload, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_list_attempts_using_payment_intent_id::< payments::operations::PaymentGetListAttempts, api_models::payments::PaymentAttemptListResponse, api_models::payments::PaymentAttemptListRequest, payments::operations::payment_attempt_list::PaymentGetListAttempts, hyperswitch_domain_models::payments::PaymentAttemptListData< payments::operations::PaymentGetListAttempts, >, >( session_state, req_state, merchant_context, auth.profile, payments::operations::PaymentGetListAttempts, payload.clone(), req_payload.payment_intent_id, header_payload.clone(), ) }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfilePaymentRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCreateAndConfirmIntent, payment_id))] pub async fn payments_create_and_confirm_intent( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsRequest>, ) -> impl Responder { let flow = Flow::PaymentsCreateAndConfirmIntent; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; let auth_type = if state.conf.merchant_id_auth.merchant_id_auth_enabled { &auth::MerchantIdAuth } else { match env::which() { env::Env::Production => &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, _ => auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfilePaymentWrite, }, req.headers(), ), } }; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, request, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_create_and_confirm_intent( state, req_state, merchant_context, auth.profile, request, header_payload.clone(), ) }, auth_type, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdateIntent, payment_id))] pub async fn payments_update_intent( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsUpdateIntentRequest>, path: web::Path<common_utils::id_type::GlobalPaymentId>, ) -> impl Responder { use hyperswitch_domain_models::payments::PaymentIntentData; let flow = Flow::PaymentsUpdateIntent; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { global_payment_id: path.into_inner(), payload: json_payload.into_inner(), }; let global_payment_id = internal_payload.global_payment_id.clone(); Box::pin(api::server_wrap( flow, state, &req, internal_payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account.clone(), auth.key_store.clone()), )); payments::payments_intent_core::< api_types::PaymentUpdateIntent, payment_types::PaymentsIntentResponse, _, _, PaymentIntentData<api_types::PaymentUpdateIntent>, >( state, req_state, merchant_context, auth.profile, payments::operations::PaymentUpdateIntent, req.payload, global_payment_id.clone(), header_payload.clone(), ) }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip(state, req), fields(flow = ?Flow::PaymentsStart, payment_id))] pub async fn payments_start( state: web::Data<app::AppState>, req: actix_web::HttpRequest, path: web::Path<( common_utils::id_type::PaymentId, common_utils::id_type::MerchantId, String, )>, ) -> impl Responder { let flow = Flow::PaymentsStart; let (payment_id, merchant_id, attempt_id) = path.into_inner(); let payload = payment_types::PaymentsStartRequest { payment_id: payment_id.clone(), merchant_id: merchant_id.clone(), attempt_id: attempt_id.clone(), }; let locking_action = payload.get_locking_input(flow.clone()); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::Authorize, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Authorize>, >( state, req_state, merchant_context, auth.profile_id, payments::operations::PaymentStart, req, api::AuthFlow::Client, payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), ) }, &auth::MerchantIdAuth(merchant_id), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip(state, req), fields(flow, payment_id))] pub async fn payments_retrieve( state: web::Data<app::AppState>, req: actix_web::HttpRequest, path: web::Path<common_utils::id_type::PaymentId>, json_payload: web::Query<payment_types::PaymentRetrieveBody>, ) -> impl Responder { let flow = match json_payload.force_sync { Some(true) => Flow::PaymentsRetrieveForceSync, _ => Flow::PaymentsRetrieve, }; let payment_id = path.into_inner(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); let payload = payment_types::PaymentsRetrieveRequest { resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id), merchant_id: json_payload.merchant_id.clone(), force_sync: json_payload.force_sync.unwrap_or(false), client_secret: json_payload.client_secret.clone(), expand_attempts: json_payload.expand_attempts, expand_captures: json_payload.expand_captures, all_keys_required: json_payload.all_keys_required, ..Default::default() }; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; tracing::Span::current().record("flow", flow.to_string()); let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }; let (auth_type, auth_flow) = match auth::check_internal_api_key_auth( req.headers(), &payload, api_auth, state.conf.internal_merchant_id_profile_id_auth.clone(), ) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::PSync, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::PSync>, >( state, req_state, merchant_context, auth.profile_id, payments::PaymentStatus, req, auth_flow, payments::CallConnectorAction::Trigger, None, header_payload.clone(), ) }, auth::auth_type( &*auth_type, &auth::JWTAuth { permission: Permission::ProfilePaymentRead, }, req.headers(), ), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip(state, req), fields(flow, payment_id))] pub async fn payments_retrieve_with_gateway_creds( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentRetrieveBodyWithCredentials>, ) -> impl Responder { let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }; let (auth_type, _auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; tracing::Span::current().record("payment_id", json_payload.payment_id.get_string_repr()); let payload = payment_types::PaymentsRetrieveRequest { resource_id: payment_types::PaymentIdType::PaymentIntentId(json_payload.payment_id.clone()), merchant_id: json_payload.merchant_id.clone(), force_sync: json_payload.force_sync.unwrap_or(false), merchant_connector_details: json_payload.merchant_connector_details.clone(), ..Default::default() }; let flow = match json_payload.force_sync { Some(true) => Flow::PaymentsRetrieveForceSync, _ => Flow::PaymentsRetrieve, }; tracing::Span::current().record("flow", flow.to_string()); let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::PSync, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::PSync>, >( state, req_state, merchant_context, auth.profile_id, payments::PaymentStatus, req, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), ) }, &*auth_type, locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdate, payment_id))] pub async fn payments_update( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsRequest>, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let flow = Flow::PaymentsUpdate; let mut payload = json_payload.into_inner(); if let Err(err) = payload .validate() .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message }) { return api::log_and_return_error_response(err.into()); }; if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method { return http_not_implemented(); }; let payment_id = path.into_inner(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id)); let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }; let (auth_type, auth_flow) = match auth::check_internal_api_key_auth_no_client_secret( req.headers(), api_auth, state.conf.internal_merchant_id_profile_id_auth.clone(), ) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); authorize_verify_select::<_>( payments::PaymentUpdate, state, req_state, merchant_context, auth.profile_id, HeaderPayload::default(), req, auth_flow, ) }, &*auth_type, locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsPostSessionTokens, payment_id))] pub async fn payments_post_session_tokens( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsPostSessionTokensRequest>, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let flow = Flow::PaymentsPostSessionTokens; let payment_id = path.into_inner(); let payload = payment_types::PaymentsPostSessionTokensRequest { payment_id, ..json_payload.into_inner() }; tracing::Span::current().record("payment_id", payload.payment_id.get_string_repr()); let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::PostSessionTokens, payment_types::PaymentsPostSessionTokensResponse, _, _, _, payments::PaymentData<api_types::PostSessionTokens>, >( state, req_state, merchant_context, auth.profile_id, payments::PaymentPostSessionTokens, req, api::AuthFlow::Client, payments::CallConnectorAction::Trigger, None, header_payload.clone(), ) }, &auth::PublishableKeyAuth, locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdateMetadata, payment_id))] pub async fn payments_update_metadata( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsUpdateMetadataRequest>, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let flow = Flow::PaymentsUpdateMetadata; let payment_id = path.into_inner(); let payload = payment_types::PaymentsUpdateMetadataRequest { payment_id, ..json_payload.into_inner() }; tracing::Span::current().record("payment_id", payload.payment_id.get_string_repr()); let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::UpdateMetadata, payment_types::PaymentsUpdateMetadataResponse, _, _, _, payments::PaymentData<api_types::UpdateMetadata>, >( state, req_state, merchant_context, auth.profile_id, payments::PaymentUpdateMetadata, req, api::AuthFlow::Client, payments::CallConnectorAction::Trigger, None, header_payload.clone(), ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm, payment_id))] pub async fn payments_confirm( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsRequest>, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let flow = Flow::PaymentsConfirm; let mut payload = json_payload.into_inner(); if let Err(err) = payload .validate() .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message }) { return api::log_and_return_error_response(err.into()); }; if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method { return http_not_implemented(); }; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; if let Err(err) = helpers::populate_browser_info(&req, &mut payload, &header_payload) { return api::log_and_return_error_response(err); } let payment_id = path.into_inner(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id)); payload.confirm = Some(true); let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }; let (auth_type, auth_flow) = match auth::check_internal_api_key_auth( req.headers(), &payload, api_auth, state.conf.internal_merchant_id_profile_id_auth.clone(), ) { Ok(auth) => auth, Err(e) => return api::log_and_return_error_response(e), }; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); authorize_verify_select::<_>( payments::PaymentConfirm, state, req_state, merchant_context, auth.profile_id, header_payload.clone(), req, auth_flow, ) }, &*auth_type, locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCapture, payment_id))] pub async fn payments_capture( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsCaptureRequest>, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let payment_id = path.into_inner(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); let flow = Flow::PaymentsCapture; let payload = payment_types::PaymentsCaptureRequest { payment_id, ..json_payload.into_inner() }; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, payload, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::Capture, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Capture>, >( state, req_state, merchant_context, auth.profile_id, payments::PaymentCapture, payload, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::SessionUpdateTaxCalculation, payment_id))] pub async fn payments_dynamic_tax_calculation( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsDynamicTaxCalculationRequest>, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let flow = Flow::SessionUpdateTaxCalculation; let payment_id = path.into_inner(); let payload = payment_types::PaymentsDynamicTaxCalculationRequest { payment_id, ..json_payload.into_inner() }; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(error) => { logger::error!( ?error, "Failed to get headers in payments_connector_session" ); HeaderPayload::default() } }; tracing::Span::current().record("payment_id", payload.payment_id.get_string_repr()); let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, payload, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::SdkSessionUpdate, payment_types::PaymentsDynamicTaxCalculationResponse, _, _, _, _, >( state, req_state, merchant_context, auth.profile_id, payments::PaymentSessionUpdate, payload, api::AuthFlow::Client, payments::CallConnectorAction::Trigger, None, header_payload.clone(), ) }, &auth::PublishableKeyAuth, locking_action, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsSessionToken, payment_id))] pub async fn payments_connector_session( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsSessionRequest>, path: web::Path<common_utils::id_type::GlobalPaymentId>, ) -> impl Responder { use hyperswitch_domain_models::payments::PaymentIntentData; let flow = Flow::PaymentsSessionToken; let global_payment_id = path.into_inner(); tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { global_payment_id: global_payment_id.clone(), payload: json_payload.into_inner(), }; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; let locking_action = internal_payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, internal_payload, |state, auth: auth::AuthenticationData, req, req_state| { let payment_id = req.global_payment_id; let request = req.payload; let operation = payments::operations::PaymentSessionIntent; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_session_core::< api_types::Session, payment_types::PaymentsSessionResponse, _, _, _, PaymentIntentData<api_types::Session>, >( state, req_state, merchant_context, auth.profile, operation, request, payment_id, payments::CallConnectorAction::Trigger, header_payload.clone(), ) }, &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( global_payment_id, )), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsSessionToken, payment_id))] pub async fn payments_connector_session( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsSessionRequest>, ) -> impl Responder { let flow = Flow::PaymentsSessionToken; let payload = json_payload.into_inner(); let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(error) => { logger::error!( ?error, "Failed to get headers in payments_connector_session" ); HeaderPayload::default() } }; tracing::Span::current().record("payment_id", payload.payment_id.get_string_repr()); let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, payload, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::Session, payment_types::PaymentsSessionResponse, _, _, _, payments::PaymentData<api_types::Session>, >( state, req_state, merchant_context, auth.profile_id, payments::PaymentSession, payload, api::AuthFlow::Client, payments::CallConnectorAction::Trigger, None, header_payload.clone(), ) }, &auth::HeaderAuth(auth::PublishableKeyAuth), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsRedirect, payment_id))] pub async fn payments_redirect_response( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: Option<web::Form<serde_json::Value>>, path: web::Path<( common_utils::id_type::PaymentId, common_utils::id_type::MerchantId, String, )>, ) -> impl Responder { let flow = Flow::PaymentsRedirect; let (payment_id, merchant_id, connector) = path.into_inner(); let param_string = req.query_string(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); let payload = payments::PaymentsRedirectResponseData { resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id), merchant_id: Some(merchant_id.clone()), force_sync: true, json_payload: json_payload.map(|payload| payload.0), param: Some(param_string.to_string()), connector: Some(connector), creds_identifier: None, }; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); <payments::PaymentRedirectSync as PaymentRedirectFlow>::handle_payments_redirect_response( &payments::PaymentRedirectSync {}, state, req_state, merchant_context, req, ) }, &auth::MerchantIdAuth(merchant_id), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsRedirect, payment_id))] pub async fn payments_redirect_response_with_creds_identifier( state: web::Data<app::AppState>, req: actix_web::HttpRequest, path: web::Path<( common_utils::id_type::PaymentId, common_utils::id_type::MerchantId, String, String, )>, ) -> impl Responder { let (payment_id, merchant_id, connector, creds_identifier) = path.into_inner(); let param_string = req.query_string(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); let payload = payments::PaymentsRedirectResponseData { resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id), merchant_id: Some(merchant_id.clone()), force_sync: true, json_payload: None, param: Some(param_string.to_string()), connector: Some(connector), creds_identifier: Some(creds_identifier), }; let flow = Flow::PaymentsRedirect; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); <payments::PaymentRedirectSync as PaymentRedirectFlow>::handle_payments_redirect_response( &payments::PaymentRedirectSync {}, state, req_state, merchant_context, req, ) }, &auth::MerchantIdAuth(merchant_id), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow =? Flow::PaymentsRedirect, payment_id))] pub async fn payments_complete_authorize_redirect( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: Option<web::Form<serde_json::Value>>, path: web::Path<( common_utils::id_type::PaymentId, common_utils::id_type::MerchantId, String, )>, ) -> impl Responder { let flow = Flow::PaymentsRedirect; let (payment_id, merchant_id, connector) = path.into_inner(); let param_string = req.query_string(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); let payload = payments::PaymentsRedirectResponseData { resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id), merchant_id: Some(merchant_id.clone()), param: Some(param_string.to_string()), json_payload: json_payload.map(|s| s.0), force_sync: false, connector: Some(connector), creds_identifier: None, }; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); <payments::PaymentRedirectCompleteAuthorize as PaymentRedirectFlow>::handle_payments_redirect_response( &payments::PaymentRedirectCompleteAuthorize {}, state, req_state, merchant_context, req, ) }, &auth::MerchantIdAuth(merchant_id), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow =? Flow::PaymentsRedirect, payment_id))] pub async fn payments_complete_authorize_redirect_with_creds_identifier( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: Option<web::Form<serde_json::Value>>, path: web::Path<( common_utils::id_type::PaymentId, common_utils::id_type::MerchantId, String, String, )>, ) -> impl Responder { let flow = Flow::PaymentsRedirect; let (payment_id, merchant_id, connector, creds_identifier) = path.into_inner(); let param_string = req.query_string(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); let payload = payments::PaymentsRedirectResponseData { resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id), merchant_id: Some(merchant_id.clone()), param: Some(param_string.to_string()), json_payload: json_payload.map(|s| s.0), force_sync: false, connector: Some(connector), creds_identifier: Some(creds_identifier), }; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); <payments::PaymentRedirectCompleteAuthorize as PaymentRedirectFlow>::handle_payments_redirect_response( &payments::PaymentRedirectCompleteAuthorize {}, state, req_state, merchant_context, req, ) }, &auth::MerchantIdAuth(merchant_id), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow =? Flow::PaymentsCompleteAuthorize, payment_id))] pub async fn payments_complete_authorize( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsCompleteAuthorizeRequest>, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let flow = Flow::PaymentsCompleteAuthorize; let mut payload = json_payload.into_inner(); let payment_id = path.into_inner(); payload.payment_id.clone_from(&payment_id); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); let payment_confirm_req = payment_types::PaymentsRequest { payment_id: Some(payment_types::PaymentIdType::PaymentIntentId( payment_id.clone(), )), shipping: payload.shipping.clone(), client_secret: Some(payload.client_secret.peek().clone()), threeds_method_comp_ind: payload.threeds_method_comp_ind.clone(), ..Default::default() }; let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }; let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payment_confirm_req, api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, _req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::CompleteAuthorize, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::CompleteAuthorize>, >( state.clone(), req_state, merchant_context, auth.profile_id, payments::operations::payment_complete_authorize::CompleteAuthorize, payment_confirm_req.clone(), auth_flow, payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), ) }, &*auth_type, locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCancel, payment_id))] pub async fn payments_cancel( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsCancelRequest>, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let flow = Flow::PaymentsCancel; let mut payload = json_payload.into_inner(); let payment_id = path.into_inner(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = payment_id; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::Void, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Void>, >( state, req_state, merchant_context, auth.profile_id, payments::PaymentCancel, req, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }), locking_action, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCancel, payment_id))] pub async fn payments_cancel( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsCancelRequest>, path: web::Path<common_utils::id_type::GlobalPaymentId>, ) -> impl Responder { let flow = Flow::PaymentsCancel; let global_payment_id = path.into_inner(); tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { global_payment_id: global_payment_id.clone(), payload: json_payload.into_inner(), }; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; let locking_action = internal_payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, internal_payload, |state, auth: auth::AuthenticationData, req, req_state| async { let payment_id = req.global_payment_id; let request = req.payload; let operation = payments::operations::payment_cancel_v2::PaymentsCancel; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(payments::payments_core::< hyperswitch_domain_models::router_flow_types::Void, api_models::payments::PaymentsCancelResponse, _, _, _, hyperswitch_domain_models::payments::PaymentCancelData< hyperswitch_domain_models::router_flow_types::Void, >, >( state, req_state, merchant_context, auth.profile, operation, request, payment_id, payments::CallConnectorAction::Trigger, header_payload.clone(), )) .await }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfilePaymentWrite, }, req.headers(), ), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCancelPostCapture, payment_id))] pub async fn payments_cancel_post_capture( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsCancelPostCaptureRequest>, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let flow = Flow::PaymentsCancelPostCapture; let mut payload = json_payload.into_inner(); let payment_id = path.into_inner(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = payment_id; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::PostCaptureVoid, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::PostCaptureVoid>, >( state, req_state, merchant_context, auth.profile_id, payments::PaymentCancelPostCapture, req, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }), locking_action, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PaymentsList))] #[cfg(all(feature = "olap", feature = "v1"))] pub async fn payments_list( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Query<payment_types::PaymentListConstraints>, ) -> impl Responder { let flow = Flow::PaymentsList; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::list_payments(state, merchant_context, None, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }), &auth::JWTAuth { permission: Permission::MerchantPaymentRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PaymentsList))] #[cfg(all(feature = "olap", feature = "v2"))] pub async fn payments_list( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Query<payment_types::PaymentListConstraints>, ) -> impl Responder { let flow = Flow::PaymentsList; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::list_payments(state, merchant_context, req) }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantPaymentRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PaymentsList))] #[cfg(all(feature = "olap", feature = "v1"))] pub async fn profile_payments_list( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Query<payment_types::PaymentListConstraints>, ) -> impl Responder { let flow = Flow::PaymentsList; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::list_payments( state, merchant_context, auth.profile_id.map(|profile_id| vec![profile_id]), req, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }), &auth::JWTAuth { permission: Permission::ProfilePaymentRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PaymentsList))] #[cfg(all(feature = "olap", feature = "v1"))] pub async fn payments_list_by_filter( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Json<payment_types::PaymentListFilterConstraints>, ) -> impl Responder { let flow = Flow::PaymentsList; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::apply_filters_on_payments(state, merchant_context, None, req) }, &auth::JWTAuth { permission: Permission::MerchantPaymentRead, }, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PaymentsList))] #[cfg(all(feature = "olap", feature = "v1"))] pub async fn profile_payments_list_by_filter( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Json<payment_types::PaymentListFilterConstraints>, ) -> impl Responder { let flow = Flow::PaymentsList; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::apply_filters_on_payments( state, merchant_context, auth.profile_id.map(|profile_id| vec![profile_id]), req, ) }, &auth::JWTAuth { permission: Permission::ProfilePaymentRead, }, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PaymentsList))] #[cfg(all(feature = "olap", feature = "v1"))] pub async fn get_filters_for_payments( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Json<common_utils::types::TimeRange>, ) -> impl Responder { let flow = Flow::PaymentsList; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::get_filters_for_payments(state, merchant_context, req) }, &auth::JWTAuth { permission: Permission::MerchantPaymentRead, }, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PaymentsFilters))] #[cfg(feature = "olap")] pub async fn get_payment_filters( state: web::Data<app::AppState>, req: actix_web::HttpRequest, ) -> impl Responder { let flow = Flow::PaymentsFilters; Box::pin(api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::get_payment_filters(state, merchant_context, None) }, &auth::JWTAuth { permission: Permission::MerchantPaymentRead, }, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PaymentsFilters))] #[cfg(all(feature = "olap", feature = "v2"))] pub async fn get_payment_filters_profile( state: web::Data<app::AppState>, req: actix_web::HttpRequest, ) -> impl Responder { let flow = Flow::PaymentsFilters; Box::pin(api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::get_payment_filters( state, merchant_context, Some(vec![auth.profile.get_id().clone()]), ) }, &auth::JWTAuth { permission: Permission::ProfilePaymentRead, }, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PaymentsFilters))] #[cfg(all(feature = "olap", feature = "v1"))] pub async fn get_payment_filters_profile( state: web::Data<app::AppState>, req: actix_web::HttpRequest, ) -> impl Responder { let flow = Flow::PaymentsFilters; Box::pin(api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::get_payment_filters( state, merchant_context, auth.profile_id.map(|profile_id| vec![profile_id]), ) }, &auth::JWTAuth { permission: Permission::ProfilePaymentRead, }, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PaymentsAggregate))] #[cfg(feature = "olap")] pub async fn get_payments_aggregates( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Query<common_utils::types::TimeRange>, ) -> impl Responder { let flow = Flow::PaymentsAggregate; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::get_aggregates_for_payments(state, merchant_context, None, req) }, &auth::JWTAuth { permission: Permission::MerchantPaymentRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "oltp", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::PaymentsApprove, payment_id))] pub async fn payments_approve( state: web::Data<app::AppState>, http_req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsApproveRequest>, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let mut payload = json_payload.into_inner(); let payment_id = path.into_inner(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = payment_id; let flow = Flow::PaymentsApprove; let fpayload = FPaymentsApproveRequest(&payload); let locking_action = fpayload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow.clone(), state, &http_req, payload.clone(), |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::Capture, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Capture>, >( state, req_state, merchant_context, auth.profile_id, payments::PaymentApprove, payment_types::PaymentsCaptureRequest { payment_id: req.payment_id, ..Default::default() }, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), ) }, match env::which() { env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }), _ => auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }), &auth::JWTAuth { permission: Permission::ProfilePaymentWrite, }, http_req.headers(), ), }, locking_action, )) .await } #[cfg(all(feature = "oltp", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::PaymentsReject, payment_id))] pub async fn payments_reject( state: web::Data<app::AppState>, http_req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsRejectRequest>, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let mut payload = json_payload.into_inner(); let payment_id = path.into_inner(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = payment_id; let flow = Flow::PaymentsReject; let fpayload = FPaymentsRejectRequest(&payload); let locking_action = fpayload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow.clone(), state, &http_req, payload.clone(), |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::Void, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Void>, >( state, req_state, merchant_context, auth.profile_id, payments::PaymentReject, payment_types::PaymentsCancelRequest { payment_id: req.payment_id, cancellation_reason: Some("Rejected by merchant".to_string()), ..Default::default() }, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), ) }, match env::which() { env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }), _ => auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }), &auth::JWTAuth { permission: Permission::ProfilePaymentWrite, }, http_req.headers(), ), }, locking_action, )) .await } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn authorize_verify_select<Op>( operation: Op, state: app::SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, header_payload: HeaderPayload, req: api_models::payments::PaymentsRequest, auth_flow: api::AuthFlow, ) -> errors::RouterResponse<api_models::payments::PaymentsResponse> where Op: Sync + Clone + std::fmt::Debug + payments::operations::Operation< api_types::Authorize, api_models::payments::PaymentsRequest, Data = payments::PaymentData<api_types::Authorize>, > + payments::operations::Operation< api_types::SetupMandate, api_models::payments::PaymentsRequest, Data = payments::PaymentData<api_types::SetupMandate>, >, { // TODO: Change for making it possible for the flow to be inferred internally or through validation layer // This is a temporary fix. // After analyzing the code structure, // the operation are flow agnostic, and the flow is only required in the post_update_tracker // Thus the flow can be generated just before calling the connector instead of explicitly passing it here. let is_recurring_details_type_nti_and_card_details = req .recurring_details .clone() .map(|recurring_details| { recurring_details.is_network_transaction_id_and_card_details_flow() }) .unwrap_or(false); if is_recurring_details_type_nti_and_card_details { // no list of eligible connectors will be passed in the confirm call logger::debug!("Authorize call for NTI and Card Details flow"); payments::proxy_for_payments_core::< api_types::Authorize, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Authorize>, >( state, req_state, merchant_context, profile_id, operation, req.clone(), auth_flow, payments::CallConnectorAction::Trigger, header_payload, req.all_keys_required, ) .await } else { let eligible_connectors = req.connector.clone(); match req.payment_type.unwrap_or_default() { api_models::enums::PaymentType::Normal | api_models::enums::PaymentType::RecurringMandate | api_models::enums::PaymentType::NewMandate => { payments::payments_core::< api_types::Authorize, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Authorize>, >( state, req_state, merchant_context, profile_id, operation, req, auth_flow, payments::CallConnectorAction::Trigger, eligible_connectors, header_payload, ) .await } api_models::enums::PaymentType::SetupMandate => { payments::payments_core::< api_types::SetupMandate, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::SetupMandate>, >( state, req_state, merchant_context, profile_id, operation, req, auth_flow, payments::CallConnectorAction::Trigger, eligible_connectors, header_payload, ) .await } } } } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsIncrementalAuthorization, payment_id))] pub async fn payments_incremental_authorization( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsIncrementalAuthorizationRequest>, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let flow = Flow::PaymentsIncrementalAuthorization; let mut payload = json_payload.into_inner(); let payment_id = path.into_inner(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = payment_id; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::IncrementalAuthorization, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::IncrementalAuthorization>, >( state, req_state, merchant_context, auth.profile_id, payments::PaymentIncrementalAuthorization, req, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsExtendAuthorization, payment_id))] pub async fn payments_extend_authorization( state: web::Data<app::AppState>, req: actix_web::HttpRequest, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let flow = Flow::PaymentsExtendAuthorization; let payment_id = path.into_inner(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); let payload = payment_types::PaymentsExtendAuthorizationRequest { payment_id }; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::ExtendAuthorization, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::ExtendAuthorization>, >( state, req_state, merchant_context, auth.profile_id, payments::PaymentExtendAuthorization, req, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsExternalAuthentication, payment_id))] pub async fn payments_external_authentication( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsExternalAuthenticationRequest>, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let flow = Flow::PaymentsExternalAuthentication; let mut payload = json_payload.into_inner(); let payment_id = path.into_inner(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = payment_id; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payment_external_authentication::< hyperswitch_domain_models::router_flow_types::Authenticate, >(state, merchant_context, req) }, &auth::HeaderAuth(auth::PublishableKeyAuth), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsAuthorize, payment_id))] pub async fn post_3ds_payments_authorize( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: Option<web::Form<serde_json::Value>>, path: web::Path<( common_utils::id_type::PaymentId, common_utils::id_type::MerchantId, String, )>, ) -> impl Responder { let flow = Flow::PaymentsAuthorize; let (payment_id, merchant_id, connector) = path.into_inner(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); let param_string = req.query_string(); let payload = payments::PaymentsRedirectResponseData { resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id), merchant_id: Some(merchant_id.clone()), force_sync: true, json_payload: json_payload.map(|payload| payload.0), param: Some(param_string.to_string()), connector: Some(connector), creds_identifier: None, }; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); <payments::PaymentAuthenticateCompleteAuthorize as PaymentRedirectFlow>::handle_payments_redirect_response( &payments::PaymentAuthenticateCompleteAuthorize {}, state, req_state, merchant_context, req, ) }, &auth::MerchantIdAuth(merchant_id), locking_action, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] pub async fn payments_manual_update( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsManualUpdateRequest>, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let flow = Flow::PaymentsManualUpdate; let mut payload = json_payload.into_inner(); let payment_id = path.into_inner(); let locking_action = payload.get_locking_input(flow.clone()); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); payload.payment_id = payment_id; Box::pin(api::server_wrap( flow, state, &req, payload, |state, _auth, req, _req_state| payments::payments_manual_update(state, req), &auth::AdminApiAuthWithMerchantIdFromHeader, locking_action, )) .await } #[cfg(feature = "v1")] /// Retrieve endpoint for merchant to fetch the encrypted customer payment method data #[instrument(skip_all, fields(flow = ?Flow::GetExtendedCardInfo, payment_id))] pub async fn retrieve_extended_card_info( state: web::Data<app::AppState>, req: actix_web::HttpRequest, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let flow = Flow::GetExtendedCardInfo; let payment_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payment_id, |state, auth: auth::AuthenticationData, payment_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::get_extended_card_info( state, merchant_context.get_merchant_account().get_id().to_owned(), payment_id, ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "oltp", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::PaymentsSubmitEligibility, payment_id))] pub async fn payments_submit_eligibility( state: web::Data<app::AppState>, http_req: actix_web::HttpRequest, json_payload: web::Json<payment_types::PaymentsEligibilityRequest>, path: web::Path<common_utils::id_type::PaymentId>, ) -> impl Responder { let flow = Flow::PaymentsSubmitEligibility; let payment_id = path.into_inner(); let mut payload = json_payload.into_inner(); payload.payment_id = payment_id.clone(); let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }; let (auth_type, _auth_flow) = match auth::check_client_secret_and_get_auth(http_req.headers(), &payload, api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; Box::pin(api::server_wrap( flow, state, &http_req, payment_id, |state, auth: auth::AuthenticationData, payment_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_submit_eligibility( state, merchant_context, payload.clone(), payment_id, ) }, &*auth_type, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub fn get_or_generate_payment_id( payload: &mut payment_types::PaymentsRequest, ) -> errors::RouterResult<()> { let given_payment_id = payload .payment_id .clone() .map(|payment_id| { payment_id .get_payment_intent_id() .map_err(|err| err.change_context(errors::ApiErrorResponse::PaymentNotFound)) }) .transpose()?; let payment_id = given_payment_id.unwrap_or(common_utils::id_type::PaymentId::default()); payload.is_payment_id_from_merchant = matches!( &payload.payment_id, Some(payment_types::PaymentIdType::PaymentIntentId(_)) ); payload.payment_id = Some(api_models::payments::PaymentIdType::PaymentIntentId( payment_id, )); Ok(()) } #[cfg(feature = "v1")] impl GetLockingInput for payment_types::PaymentsRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { match self.payment_id { Some(payment_types::PaymentIdType::PaymentIntentId(ref id)) => { let api_identifier = lock_utils::ApiIdentifier::from(flow); let intent_id_locking_input = api_locking::LockingInput { unique_locking_key: id.get_string_repr().to_owned(), api_identifier: api_identifier.clone(), override_lock_retries: None, }; if let Some(customer_id) = self .customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) { api_locking::LockAction::HoldMultiple { inputs: vec![ intent_id_locking_input, api_locking::LockingInput { unique_locking_key: customer_id.get_string_repr().to_owned(), api_identifier, override_lock_retries: None, }, ], } } else { api_locking::LockAction::Hold { input: intent_id_locking_input, } } } _ => api_locking::LockAction::NotApplicable, } } } #[cfg(feature = "v1")] impl GetLockingInput for payment_types::PaymentsStartRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } #[cfg(feature = "v1")] impl GetLockingInput for payment_types::PaymentsRetrieveRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { match self.resource_id { payment_types::PaymentIdType::PaymentIntentId(ref id) if self.force_sync => { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } _ => api_locking::LockAction::NotApplicable, } } } #[cfg(feature = "v1")] impl GetLockingInput for payment_types::PaymentsSessionRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } #[cfg(feature = "v2")] impl GetLockingInput for payment_types::PaymentsSessionRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, { api_locking::LockAction::NotApplicable } } #[cfg(feature = "v1")] impl GetLockingInput for payment_types::PaymentsDynamicTaxCalculationRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } #[cfg(feature = "v1")] impl GetLockingInput for payment_types::PaymentsPostSessionTokensRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } #[cfg(feature = "v1")] impl GetLockingInput for payment_types::PaymentsUpdateMetadataRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } #[cfg(feature = "v1")] impl GetLockingInput for payments::PaymentsRedirectResponseData { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { match self.resource_id { payment_types::PaymentIdType::PaymentIntentId(ref id) => { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } _ => api_locking::LockAction::NotApplicable, } } } #[cfg(feature = "v2")] impl GetLockingInput for payments::PaymentsRedirectResponseData { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } #[cfg(feature = "v1")] impl GetLockingInput for payment_types::PaymentsCompleteAuthorizeRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } #[cfg(feature = "v1")] impl GetLockingInput for payment_types::PaymentsCancelRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } #[cfg(feature = "v1")] impl GetLockingInput for payment_types::PaymentsCancelPostCaptureRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } #[cfg(feature = "v1")] impl GetLockingInput for payment_types::PaymentsExtendAuthorizationRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } #[cfg(feature = "v1")] impl GetLockingInput for payment_types::PaymentsCaptureRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } #[cfg(feature = "oltp")] struct FPaymentsApproveRequest<'a>(&'a payment_types::PaymentsApproveRequest); #[cfg(feature = "oltp")] impl GetLockingInput for FPaymentsApproveRequest<'_> { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.0.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } #[cfg(feature = "oltp")] struct FPaymentsRejectRequest<'a>(&'a payment_types::PaymentsRejectRequest); #[cfg(feature = "oltp")] impl GetLockingInput for FPaymentsRejectRequest<'_> { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.0.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } #[cfg(feature = "v1")] impl GetLockingInput for payment_types::PaymentsIncrementalAuthorizationRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } #[cfg(feature = "v1")] impl GetLockingInput for payment_types::PaymentsExternalAuthenticationRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } #[cfg(feature = "v1")] impl GetLockingInput for payment_types::PaymentsManualUpdateRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } #[instrument(skip_all, fields(flow = ?Flow::PaymentsAggregate))] #[cfg(all(feature = "olap", feature = "v1"))] pub async fn get_payments_aggregates_profile( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Query<common_utils::types::TimeRange>, ) -> impl Responder { let flow = Flow::PaymentsAggregate; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::get_aggregates_for_payments( state, merchant_context, auth.profile_id.map(|profile_id| vec![profile_id]), req, ) }, &auth::JWTAuth { permission: Permission::ProfilePaymentRead, }, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PaymentsAggregate))] #[cfg(all(feature = "olap", feature = "v2"))] pub async fn get_payments_aggregates_profile( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Query<common_utils::types::TimeRange>, ) -> impl Responder { let flow = Flow::PaymentsAggregate; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::get_aggregates_for_payments( state, merchant_context, Some(vec![auth.profile.get_id().clone()]), req, ) }, &auth::JWTAuth { permission: Permission::ProfilePaymentRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] /// A private module to hold internal types to be used in route handlers. /// This is because we will need to implement certain traits on these types which will have the resource id /// But the api payload will not contain the resource id /// So these types can hold the resource id along with actual api payload, on which api event and locking action traits can be implemented mod internal_payload_types { use super::*; // Serialize is implemented because of api events #[derive(Debug, serde::Serialize)] pub struct PaymentsGenericRequestWithResourceId<T: serde::Serialize> { pub global_payment_id: common_utils::id_type::GlobalPaymentId, #[serde(flatten)] pub payload: T, } impl<T: serde::Serialize> GetLockingInput for PaymentsGenericRequestWithResourceId<T> { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, lock_utils::ApiIdentifier: From<F>, { api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: self.global_payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::from(flow), override_lock_retries: None, }, } } } impl<T: serde::Serialize> common_utils::events::ApiEventMetric for PaymentsGenericRequestWithResourceId<T> { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Payment { payment_id: self.global_payment_id.clone(), }) } } } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentStartRedirection, payment_id))] pub async fn payments_start_redirection( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Query<api_models::payments::PaymentStartRedirectionParams>, path: web::Path<common_utils::id_type::GlobalPaymentId>, ) -> impl Responder { let flow = Flow::PaymentStartRedirection; let global_payment_id = path.into_inner(); tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); let publishable_key = &payload.publishable_key; let profile_id = &payload.profile_id; let payment_start_redirection_request = api_models::payments::PaymentStartRedirectionRequest { id: global_payment_id.clone(), }; let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { global_payment_id: global_payment_id.clone(), payload: payment_start_redirection_request.clone(), }; let locking_action = internal_payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payment_start_redirection_request.clone(), |state, auth: auth::AuthenticationData, _req, req_state| async { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payment_start_redirection( state, merchant_context, payment_start_redirection_request.clone(), ) .await }, &auth::PublishableKeyAndProfileIdAuth { publishable_key: publishable_key.clone(), profile_id: profile_id.clone(), }, locking_action, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirmIntent, payment_id))] pub async fn payment_confirm_intent( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<api_models::payments::PaymentsConfirmIntentRequest>, path: web::Path<common_utils::id_type::GlobalPaymentId>, ) -> impl Responder { use hyperswitch_domain_models::payments::PaymentConfirmData; let flow = Flow::PaymentsConfirmIntent; // TODO: Populate browser information into the payload // if let Err(err) = helpers::populate_ip_into_browser_info(&req, &mut payload) { // return api::log_and_return_error_response(err); // } let global_payment_id = path.into_inner(); tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { global_payment_id: global_payment_id.clone(), payload: json_payload.into_inner(), }; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; let locking_action = internal_payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, internal_payload, |state, auth: auth::AuthenticationData, req, req_state| async { let payment_id = req.global_payment_id; let request = req.payload; let operation = payments::operations::PaymentIntentConfirm; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(payments::payments_core::< api_types::Authorize, api_models::payments::PaymentsResponse, _, _, _, PaymentConfirmData<api_types::Authorize>, >( state, req_state, merchant_context, auth.profile, operation, request, payment_id, payments::CallConnectorAction::Trigger, header_payload.clone(), )) .await }, auth::api_or_client_auth( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( global_payment_id, )), req.headers(), ), locking_action, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::GiftCardBalanceCheck, payment_id))] pub async fn payment_check_gift_card_balance( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<api_models::payments::PaymentsGiftCardBalanceCheckRequest>, path: web::Path<common_utils::id_type::GlobalPaymentId>, ) -> impl Responder { let flow = Flow::GiftCardBalanceCheck; let global_payment_id = path.into_inner(); tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { global_payment_id: global_payment_id.clone(), payload: json_payload.into_inner(), }; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; Box::pin(api::server_wrap( flow, state, &req, internal_payload, |state, auth: auth::AuthenticationData, req, req_state| async { let payment_id = req.global_payment_id; let request = req.payload; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(gift_card::payments_check_gift_card_balance_core( state, merchant_context, auth.profile, req_state, request, header_payload.clone(), payment_id, )) .await }, auth::api_or_client_auth( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( global_payment_id, )), req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::ProxyConfirmIntent, payment_id))] pub async fn proxy_confirm_intent( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<api_models::payments::ProxyPaymentsRequest>, path: web::Path<common_utils::id_type::GlobalPaymentId>, ) -> impl Responder { use hyperswitch_domain_models::payments::PaymentConfirmData; let flow = Flow::ProxyConfirmIntent; // Extract the payment ID from the path let global_payment_id = path.into_inner(); tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); // Parse and validate headers let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; // Prepare the internal payload let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { global_payment_id, payload: json_payload.into_inner(), }; // Determine the locking action, if required let locking_action = internal_payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, internal_payload, |state, auth: auth::AuthenticationData, req, req_state| { let payment_id = req.global_payment_id; let request = req.payload; // Define the operation for proxy payments intent let operation = payments::operations::proxy_payments_intent::PaymentProxyIntent; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); // Call the core proxy logic Box::pin(payments::proxy_for_payments_core::< api_types::Authorize, api_models::payments::PaymentsResponse, _, _, _, PaymentConfirmData<api_types::Authorize>, >( state, req_state, merchant_context, auth.profile, operation, request, payment_id, payments::CallConnectorAction::Trigger, header_payload.clone(), None, )) }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, locking_action, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::ProxyConfirmIntent, payment_id))] pub async fn confirm_intent_with_external_vault_proxy( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: web::Json<api_models::payments::ExternalVaultProxyPaymentsRequest>, path: web::Path<common_utils::id_type::GlobalPaymentId>, ) -> impl Responder { use hyperswitch_domain_models::payments::PaymentConfirmData; let flow = Flow::ProxyConfirmIntent; // Extract the payment ID from the path let global_payment_id = path.into_inner(); tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); // Parse and validate headers let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; // Prepare the internal payload let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { global_payment_id: global_payment_id.clone(), payload: json_payload.into_inner(), }; // Determine the locking action, if required let locking_action = internal_payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, internal_payload, |state, auth: auth::AuthenticationData, req, req_state| { let payment_id = req.global_payment_id; let request = req.payload; // Define the operation for proxy payments intent let operation = payments::operations::external_vault_proxy_payment_intent::ExternalVaultProxyPaymentIntent; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); // Call the core proxy logic Box::pin(payments::external_vault_proxy_for_payments_core::< api_types::ExternalVaultProxy, api_models::payments::PaymentsResponse, _, _, _, PaymentConfirmData<api_types::ExternalVaultProxy>, >( state, req_state, merchant_context, auth.profile, operation, request, payment_id, payments::CallConnectorAction::Trigger, header_payload.clone(), None, )) }, auth::api_or_client_auth( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( global_payment_id, )), req.headers(), ), locking_action, )) .await } #[cfg(feature = "v2")] #[instrument(skip(state, req), fields(flow, payment_id))] pub async fn payment_status( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Query<api_models::payments::PaymentsStatusRequest>, path: web::Path<common_utils::id_type::GlobalPaymentId>, ) -> impl Responder { use hyperswitch_domain_models::payments::PaymentStatusData; let flow = match payload.force_sync { true => Flow::PaymentsRetrieveForceSync, false => Flow::PaymentsRetrieve, }; let global_payment_id = path.into_inner(); tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); let payload = payment_types::PaymentsRetrieveRequest { force_sync: payload.force_sync, expand_attempts: payload.expand_attempts, param: payload.param.clone(), return_raw_connector_response: payload.return_raw_connector_response, merchant_connector_details: None, }; let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { global_payment_id, payload, }; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; let locking_action = internal_payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, internal_payload, |state, auth: auth::AuthenticationData, req, req_state| async { let payment_id = req.global_payment_id; let request = req.payload; let operation = payments::operations::PaymentGet; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(payments::payments_core::< api_types::PSync, api_models::payments::PaymentsResponse, _, _, _, PaymentStatusData<api_types::PSync>, >( state, req_state, merchant_context, auth.profile, operation, request, payment_id, payments::CallConnectorAction::Trigger, header_payload.clone(), )) .await }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfilePaymentRead, }, req.headers(), ), locking_action, )) .await } #[cfg(feature = "v2")] #[instrument(skip(state, req), fields(flow, payment_id))] pub async fn payments_status_with_gateway_creds( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Json<api_models::payments::PaymentsRetrieveRequest>, path: web::Path<common_utils::id_type::GlobalPaymentId>, ) -> impl Responder { use hyperswitch_domain_models::payments::PaymentStatusData; let flow = match payload.force_sync { true => Flow::PaymentsRetrieveForceSync, false => Flow::PaymentsRetrieve, }; tracing::Span::current().record("flow", flow.to_string()); let global_payment_id = path.into_inner(); tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { global_payment_id, payload: payload.into_inner(), }; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; let locking_action = internal_payload.get_locking_input(flow.clone()); let auth_type = if state.conf.merchant_id_auth.merchant_id_auth_enabled { &auth::MerchantIdAuth } else { match env::which() { env::Env::Production => &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, _ => auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfilePaymentWrite, }, req.headers(), ), } }; Box::pin(api::server_wrap( flow, state, &req, internal_payload, |state, auth: auth::AuthenticationData, req, req_state| async { let payment_id = req.global_payment_id; let request = req.payload; let operation = payments::operations::PaymentGet; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(payments::payments_core::< api_types::PSync, api_models::payments::PaymentsResponse, _, _, _, PaymentStatusData<api_types::PSync>, >( state, req_state, merchant_context, auth.profile, operation, request, payment_id, payments::CallConnectorAction::Trigger, header_payload.clone(), )) .await }, auth_type, locking_action, )) .await } #[cfg(feature = "v2")] #[instrument(skip(state, req), fields(flow, payment_id))] pub async fn payment_get_intent_using_merchant_reference_id( state: web::Data<app::AppState>, req: actix_web::HttpRequest, path: web::Path<common_utils::id_type::PaymentReferenceId>, ) -> impl Responder { use crate::db::domain::merchant_context; let flow = Flow::PaymentsRetrieveUsingMerchantReferenceId; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; let merchant_reference_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, req_state| async { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(payments::payments_get_intent_using_merchant_reference( state, merchant_context, auth.profile, req_state, &merchant_reference_id, header_payload.clone(), )) .await }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsRedirect, payment_id))] pub async fn payments_finish_redirection( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: Option<web::Form<serde_json::Value>>, path: web::Path<( common_utils::id_type::GlobalPaymentId, String, common_utils::id_type::ProfileId, )>, ) -> impl Responder { let flow = Flow::PaymentsRedirect; let (payment_id, publishable_key, profile_id) = path.into_inner(); let param_string = req.query_string(); tracing::Span::current().record("payment_id", payment_id.get_string_repr()); let payload = payments::PaymentsRedirectResponseData { payment_id, json_payload: json_payload.map(|payload| payload.0), query_params: param_string.to_string(), }; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); <payments::PaymentRedirectSync as PaymentRedirectFlow>::handle_payments_redirect_response( &payments::PaymentRedirectSync {}, state, req_state, merchant_context, auth.profile, req, ) }, &auth::PublishableKeyAndProfileIdAuth { publishable_key: publishable_key.clone(), profile_id: profile_id.clone(), }, locking_action, )) .await } #[cfg(feature = "v2")] #[instrument(skip(state, req), fields(flow, payment_id))] pub async fn payments_capture( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Json<api_models::payments::PaymentsCaptureRequest>, path: web::Path<common_utils::id_type::GlobalPaymentId>, ) -> impl Responder { use hyperswitch_domain_models::payments::PaymentCaptureData; let flow = Flow::PaymentsCapture; let global_payment_id = path.into_inner(); tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { global_payment_id, payload: payload.into_inner(), }; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; let locking_action = internal_payload.get_locking_input(flow.clone()); Box::pin(api::server_wrap( flow, state, &req, internal_payload, |state, auth: auth::AuthenticationData, req, req_state| async { let payment_id = req.global_payment_id; let request = req.payload; let operation = payments::operations::payment_capture_v2::PaymentsCapture; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(payments::payments_core::< api_types::Capture, api_models::payments::PaymentsCaptureResponse, _, _, _, PaymentCaptureData<api_types::Capture>, >( state, req_state, merchant_context, auth.profile, operation, request, payment_id, payments::CallConnectorAction::Trigger, header_payload.clone(), )) .await }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfileAccountWrite, }, req.headers(), ), locking_action, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))] pub async fn list_payment_methods( state: web::Data<app::AppState>, req: actix_web::HttpRequest, path: web::Path<common_utils::id_type::GlobalPaymentId>, query_payload: web::Query<api_models::payments::ListMethodsForPaymentsRequest>, ) -> impl Responder { use crate::db::domain::merchant_context; let flow = Flow::PaymentMethodsList; let payload = query_payload.into_inner(); let global_payment_id = path.into_inner(); tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { global_payment_id: global_payment_id.clone(), payload, }; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; Box::pin(api::server_wrap( flow, state, &req, internal_payload, |state, auth, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payment_methods::list_payment_methods( state, merchant_context, auth.profile, req.global_payment_id, req.payload, &header_payload, ) }, &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( global_payment_id, )), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/payments.rs
router::src::routes::payments
26,881
true
// File: crates/router/src/routes/disputes.rs // Module: router::src::routes::disputes use actix_multipart::Multipart; use actix_web::{web, HttpRequest, HttpResponse}; use api_models::disputes as dispute_models; use router_env::{instrument, tracing, Flow}; use crate::{core::api_locking, services::authorization::permissions::Permission}; pub mod utils; use super::app::AppState; use crate::{ core::disputes, services::{api, authentication as auth}, types::{api::disputes as dispute_types, domain}, }; #[cfg(feature = "v1")] /// Disputes - Retrieve Dispute #[utoipa::path( get, path = "/disputes/{dispute_id}", params( ("dispute_id" = String, Path, description = "The identifier for dispute") ), responses( (status = 200, description = "The dispute was retrieved successfully", body = DisputeResponse), (status = 404, description = "Dispute does not exist in our records") ), tag = "Disputes", operation_id = "Retrieve a Dispute", security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::DisputesRetrieve))] pub async fn retrieve_dispute( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, json_payload: web::Query<dispute_models::DisputeRetrieveBody>, ) -> HttpResponse { let flow = Flow::DisputesRetrieve; let payload = dispute_models::DisputeRetrieveRequest { dispute_id: path.into_inner(), force_sync: json_payload.force_sync, }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); disputes::retrieve_dispute(state, merchant_context, auth.profile_id, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileDisputeRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::DisputesRetrieve))] pub async fn fetch_disputes( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, json_payload: web::Query<dispute_types::DisputeFetchQueryData>, ) -> HttpResponse { let flow = Flow::DisputesList; let connector_id = path.into_inner(); let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); disputes::connector_sync_disputes(state, merchant_context, connector_id.clone(), req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileDisputeRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Disputes - List Disputes #[utoipa::path( get, path = "/disputes/list", params( ("limit" = Option<i64>, Query, description = "The maximum number of Dispute Objects to include in the response"), ("dispute_status" = Option<DisputeStatus>, Query, description = "The status of dispute"), ("dispute_stage" = Option<DisputeStage>, Query, description = "The stage of dispute"), ("reason" = Option<String>, Query, description = "The reason for dispute"), ("connector" = Option<String>, Query, description = "The connector linked to dispute"), ("received_time" = Option<PrimitiveDateTime>, Query, description = "The time at which dispute is received"), ("received_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the dispute received time"), ("received_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the dispute received time"), ("received_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the dispute received time"), ("received_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the dispute received time"), ), responses( (status = 200, description = "The dispute list was retrieved successfully", body = Vec<DisputeResponse>), (status = 401, description = "Unauthorized request") ), tag = "Disputes", operation_id = "List Disputes", security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::DisputesList))] pub async fn retrieve_disputes_list( state: web::Data<AppState>, req: HttpRequest, query: web::Query<dispute_models::DisputeListGetConstraints>, ) -> HttpResponse { let flow = Flow::DisputesList; let payload = query.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); disputes::retrieve_disputes_list(state, merchant_context, None, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantDisputeRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// Disputes - List Disputes for The Given Business Profiles #[utoipa::path( get, path = "/disputes/profile/list", params( ("limit" = Option<i64>, Query, description = "The maximum number of Dispute Objects to include in the response"), ("dispute_status" = Option<DisputeStatus>, Query, description = "The status of dispute"), ("dispute_stage" = Option<DisputeStage>, Query, description = "The stage of dispute"), ("reason" = Option<String>, Query, description = "The reason for dispute"), ("connector" = Option<String>, Query, description = "The connector linked to dispute"), ("received_time" = Option<PrimitiveDateTime>, Query, description = "The time at which dispute is received"), ("received_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the dispute received time"), ("received_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the dispute received time"), ("received_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the dispute received time"), ("received_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the dispute received time"), ), responses( (status = 200, description = "The dispute list was retrieved successfully", body = Vec<DisputeResponse>), (status = 401, description = "Unauthorized request") ), tag = "Disputes", operation_id = "List Disputes for The given Business Profiles", security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::DisputesList))] pub async fn retrieve_disputes_list_profile( state: web::Data<AppState>, req: HttpRequest, payload: web::Query<dispute_models::DisputeListGetConstraints>, ) -> HttpResponse { let flow = Flow::DisputesList; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); disputes::retrieve_disputes_list( state, merchant_context, auth.profile_id.map(|profile_id| vec![profile_id]), req, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileDisputeRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// Disputes - Disputes Filters #[utoipa::path( get, path = "/disputes/filter", responses( (status = 200, description = "List of filters", body = DisputeListFilters), ), tag = "Disputes", operation_id = "List all filters for disputes", security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::DisputesFilters))] pub async fn get_disputes_filters(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::DisputesFilters; Box::pin(api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); disputes::get_filters_for_disputes(state, merchant_context, None) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantDisputeRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// Disputes - Disputes Filters Profile #[utoipa::path( get, path = "/disputes/profile/filter", responses( (status = 200, description = "List of filters", body = DisputeListFilters), ), tag = "Disputes", operation_id = "List all filters for disputes", security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::DisputesFilters))] pub async fn get_disputes_filters_profile( state: web::Data<AppState>, req: HttpRequest, ) -> HttpResponse { let flow = Flow::DisputesFilters; Box::pin(api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); disputes::get_filters_for_disputes( state, merchant_context, auth.profile_id.map(|profile_id| vec![profile_id]), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileDisputeRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// Disputes - Accept Dispute #[utoipa::path( get, path = "/disputes/accept/{dispute_id}", params( ("dispute_id" = String, Path, description = "The identifier for dispute") ), responses( (status = 200, description = "The dispute was accepted successfully", body = DisputeResponse), (status = 404, description = "Dispute does not exist in our records") ), tag = "Disputes", operation_id = "Accept a Dispute", security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::DisputesRetrieve))] pub async fn accept_dispute( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::DisputesRetrieve; let dispute_id = dispute_types::DisputeId { dispute_id: path.into_inner(), }; Box::pin(api::server_wrap( flow, state, &req, dispute_id, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); disputes::accept_dispute(state, merchant_context, auth.profile_id, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileDisputeWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// Disputes - Submit Dispute Evidence #[utoipa::path( post, path = "/disputes/evidence", request_body=AcceptDisputeRequestData, responses( (status = 200, description = "The dispute evidence submitted successfully", body = AcceptDisputeResponse), (status = 404, description = "Dispute does not exist in our records") ), tag = "Disputes", operation_id = "Submit Dispute Evidence", security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::DisputesEvidenceSubmit))] pub async fn submit_dispute_evidence( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<dispute_models::SubmitEvidenceRequest>, ) -> HttpResponse { let flow = Flow::DisputesEvidenceSubmit; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); disputes::submit_evidence(state, merchant_context, auth.profile_id, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileDisputeWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// Disputes - Attach Evidence to Dispute /// /// To attach an evidence file to dispute #[utoipa::path( put, path = "/disputes/evidence", request_body=MultipartRequestWithFile, responses( (status = 200, description = "Evidence attached to dispute", body = CreateFileResponse), (status = 400, description = "Bad Request") ), tag = "Disputes", operation_id = "Attach Evidence to Dispute", security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::AttachDisputeEvidence))] pub async fn attach_dispute_evidence( state: web::Data<AppState>, req: HttpRequest, payload: Multipart, ) -> HttpResponse { let flow = Flow::AttachDisputeEvidence; //Get attach_evidence_request from the multipart request let attach_evidence_request_result = utils::get_attach_evidence_request(payload).await; let attach_evidence_request = match attach_evidence_request_result { Ok(valid_request) => valid_request, Err(err) => return api::log_and_return_error_response(err), }; Box::pin(api::server_wrap( flow, state, &req, attach_evidence_request, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); disputes::attach_evidence(state, merchant_context, auth.profile_id, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileDisputeWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// Disputes - Retrieve Dispute #[utoipa::path( get, path = "/disputes/evidence/{dispute_id}", params( ("dispute_id" = String, Path, description = "The identifier for dispute") ), responses( (status = 200, description = "The dispute evidence was retrieved successfully", body = DisputeResponse), (status = 404, description = "Dispute does not exist in our records") ), tag = "Disputes", operation_id = "Retrieve a Dispute Evidence", security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::RetrieveDisputeEvidence))] pub async fn retrieve_dispute_evidence( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::RetrieveDisputeEvidence; let dispute_id = dispute_types::DisputeId { dispute_id: path.into_inner(), }; Box::pin(api::server_wrap( flow, state, &req, dispute_id, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); disputes::retrieve_dispute_evidence(state, merchant_context, auth.profile_id, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileDisputeRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Disputes - Delete Evidence attached to a Dispute /// /// To delete an evidence file attached to a dispute #[utoipa::path( put, path = "/disputes/evidence", request_body=DeleteEvidenceRequest, responses( (status = 200, description = "Evidence deleted from a dispute"), (status = 400, description = "Bad Request") ), tag = "Disputes", operation_id = "Delete Evidence attached to a Dispute", security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::DeleteDisputeEvidence))] pub async fn delete_dispute_evidence( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<dispute_models::DeleteEvidenceRequest>, ) -> HttpResponse { let flow = Flow::DeleteDisputeEvidence; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); disputes::delete_evidence(state, merchant_context, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileDisputeWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::DisputesAggregate))] pub async fn get_disputes_aggregate( state: web::Data<AppState>, req: HttpRequest, query_param: web::Query<common_utils::types::TimeRange>, ) -> HttpResponse { let flow = Flow::DisputesAggregate; let query_param = query_param.into_inner(); Box::pin(api::server_wrap( flow, state, &req, query_param, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); disputes::get_aggregates_for_disputes(state, merchant_context, None, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantDisputeRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::DisputesAggregate))] pub async fn get_disputes_aggregate_profile( state: web::Data<AppState>, req: HttpRequest, query_param: web::Query<common_utils::types::TimeRange>, ) -> HttpResponse { let flow = Flow::DisputesAggregate; let query_param = query_param.into_inner(); Box::pin(api::server_wrap( flow, state, &req, query_param, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); disputes::get_aggregates_for_disputes( state, merchant_context, auth.profile_id.map(|profile_id| vec![profile_id]), req, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileDisputeRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/disputes.rs
router::src::routes::disputes
5,126
true
// File: crates/router/src/routes/subscription.rs // Module: router::src::routes::subscription //! Analysis for usage of Subscription in Payment flows //! //! Functions that are used to perform the api level configuration and retrieval //! of various types under Subscriptions. use std::str::FromStr; use actix_web::{web, HttpRequest, HttpResponse, Responder}; use api_models::subscription as subscription_types; use error_stack::report; use hyperswitch_domain_models::errors; use router_env::{ tracing::{self, instrument}, Flow, }; use crate::{ core::api_locking, headers::X_PROFILE_ID, routes::AppState, services::{api as oss_api, authentication as auth, authorization::permissions::Permission}, types::domain, }; fn extract_profile_id(req: &HttpRequest) -> Result<common_utils::id_type::ProfileId, HttpResponse> { let header_value = req.headers().get(X_PROFILE_ID).ok_or_else(|| { HttpResponse::BadRequest().json( errors::api_error_response::ApiErrorResponse::MissingRequiredField { field_name: X_PROFILE_ID, }, ) })?; let profile_str = header_value.to_str().unwrap_or_default(); if profile_str.is_empty() { return Err(HttpResponse::BadRequest().json( errors::api_error_response::ApiErrorResponse::MissingRequiredField { field_name: X_PROFILE_ID, }, )); } common_utils::id_type::ProfileId::from_str(profile_str).map_err(|_| { HttpResponse::BadRequest().json( errors::api_error_response::ApiErrorResponse::InvalidDataValue { field_name: X_PROFILE_ID, }, ) }) } #[instrument(skip_all)] pub async fn create_subscription( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<subscription_types::CreateSubscriptionRequest>, ) -> impl Responder { let flow = Flow::CreateSubscription; let profile_id = match extract_profile_id(&req) { Ok(id) => id, Err(response) => return response, }; Box::pin(oss_api::server_wrap( flow, state, &req, json_payload.into_inner(), move |state, auth: auth::AuthenticationData, payload, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); subscriptions::create_subscription( state.into(), merchant_context, profile_id.clone(), payload.clone(), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileSubscriptionWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all)] pub async fn confirm_subscription( state: web::Data<AppState>, req: HttpRequest, subscription_id: web::Path<common_utils::id_type::SubscriptionId>, json_payload: web::Json<subscription_types::ConfirmSubscriptionRequest>, ) -> impl Responder { let flow = Flow::ConfirmSubscription; let subscription_id = subscription_id.into_inner(); let payload = json_payload.into_inner(); let profile_id = match extract_profile_id(&req) { Ok(id) => id, Err(response) => return response, }; let api_auth = auth::ApiKeyAuth::default(); let (auth_type, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok(auth) => auth, Err(err) => return oss_api::log_and_return_error_response(error_stack::report!(err)), }; Box::pin(oss_api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, payload, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); subscriptions::confirm_subscription( state.into(), merchant_context, profile_id.clone(), payload.clone(), subscription_id.clone(), ) }, auth::auth_type( &*auth_type, &auth::JWTAuth { permission: Permission::ProfileSubscriptionWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all)] pub async fn get_subscription_plans( state: web::Data<AppState>, req: HttpRequest, query: web::Query<subscription_types::GetPlansQuery>, ) -> impl Responder { let flow = Flow::GetPlansForSubscription; let api_auth = auth::ApiKeyAuth::default(); let payload = query.into_inner(); let profile_id = match extract_profile_id(&req) { Ok(profile_id) => profile_id, Err(response) => return response, }; let (auth_type, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok(auth) => auth, Err(err) => return oss_api::log_and_return_error_response(error_stack::report!(err)), }; Box::pin(oss_api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, query, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); subscriptions::get_subscription_plans( state.into(), merchant_context, profile_id.clone(), query, ) }, auth::auth_type( &*auth_type, &auth::JWTAuth { permission: Permission::ProfileSubscriptionRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Add support for get subscription by id #[instrument(skip_all)] pub async fn get_subscription( state: web::Data<AppState>, req: HttpRequest, subscription_id: web::Path<common_utils::id_type::SubscriptionId>, ) -> impl Responder { let flow = Flow::GetSubscription; let subscription_id = subscription_id.into_inner(); let profile_id = match extract_profile_id(&req) { Ok(id) => id, Err(response) => return response, }; Box::pin(oss_api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); subscriptions::get_subscription( state.into(), merchant_context, profile_id.clone(), subscription_id.clone(), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileSubscriptionRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all)] pub async fn create_and_confirm_subscription( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<subscription_types::CreateAndConfirmSubscriptionRequest>, ) -> impl Responder { let flow = Flow::CreateAndConfirmSubscription; let profile_id = match extract_profile_id(&req) { Ok(id) => id, Err(response) => return response, }; Box::pin(oss_api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, payload, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); subscriptions::create_and_confirm_subscription( state.into(), merchant_context, profile_id.clone(), payload.clone(), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileSubscriptionWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// add support for get subscription estimate #[instrument(skip_all)] pub async fn get_estimate( state: web::Data<AppState>, req: HttpRequest, query: web::Query<subscription_types::EstimateSubscriptionQuery>, ) -> impl Responder { let flow = Flow::GetSubscriptionEstimate; let profile_id = match extract_profile_id(&req) { Ok(id) => id, Err(response) => return response, }; let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, _auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) { Ok(auth) => auth, Err(err) => return oss_api::log_and_return_error_response(report!(err)), }; Box::pin(oss_api::server_wrap( flow, state, &req, query.into_inner(), |state, auth: auth::AuthenticationData, query, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); subscriptions::get_estimate(state.into(), merchant_context, profile_id.clone(), query) }, &*auth_type, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all)] pub async fn update_subscription( state: web::Data<AppState>, req: HttpRequest, subscription_id: web::Path<common_utils::id_type::SubscriptionId>, json_payload: web::Json<subscription_types::UpdateSubscriptionRequest>, ) -> impl Responder { let flow = Flow::UpdateSubscription; let subscription_id = subscription_id.into_inner(); let profile_id = match extract_profile_id(&req) { Ok(id) => id, Err(response) => return response, }; Box::pin(oss_api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, payload, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); subscriptions::update_subscription( state.into(), merchant_context, profile_id.clone(), subscription_id.clone(), payload.clone(), ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/subscription.rs
router::src::routes::subscription
2,386
true
// File: crates/router/src/routes/blocklist.rs // Module: router::src::routes::blocklist use actix_web::{web, HttpRequest, HttpResponse}; use api_models::blocklist as api_blocklist; use error_stack::report; use router_env::Flow; use crate::{ core::{api_locking, blocklist}, routes::AppState, services::{api, authentication as auth, authorization::permissions::Permission}, types::domain, }; #[utoipa::path( post, path = "/blocklist", request_body = BlocklistRequest, responses( (status = 200, description = "Fingerprint Blocked", body = BlocklistResponse), (status = 400, description = "Invalid Data") ), tag = "Blocklist", operation_id = "Block a Fingerprint", security(("api_key" = [])) )] pub async fn add_entry_to_blocklist( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_blocklist::AddToBlocklistRequest>, ) -> HttpResponse { let flow = Flow::AddToBlocklist; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, body, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); blocklist::add_entry_to_blocklist(state, merchant_context, body) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantAccountWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[utoipa::path( delete, path = "/blocklist", request_body = BlocklistRequest, responses( (status = 200, description = "Fingerprint Unblocked", body = BlocklistResponse), (status = 400, description = "Invalid Data") ), tag = "Blocklist", operation_id = "Unblock a Fingerprint", security(("api_key" = [])) )] pub async fn remove_entry_from_blocklist( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_blocklist::DeleteFromBlocklistRequest>, ) -> HttpResponse { let flow = Flow::DeleteFromBlocklist; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, body, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); blocklist::remove_entry_from_blocklist(state, merchant_context, body) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantAccountWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[utoipa::path( get, path = "/blocklist", params ( ("data_kind" = BlocklistDataKind, Query, description = "Kind of the fingerprint list requested"), ), responses( (status = 200, description = "Blocked Fingerprints", body = BlocklistResponse), (status = 400, description = "Invalid Data") ), tag = "Blocklist", operation_id = "List Blocked fingerprints of a particular kind", security(("api_key" = [])) )] pub async fn list_blocked_payment_methods( state: web::Data<AppState>, req: HttpRequest, query_payload: web::Query<api_blocklist::ListBlocklistQuery>, ) -> HttpResponse { let flow = Flow::ListBlocklist; let payload = query_payload.into_inner(); let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, query, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); blocklist::list_blocklist_entries(state, merchant_context, query) }, auth::auth_type( &*auth_type, &auth::JWTAuth { permission: Permission::MerchantAccountRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[utoipa::path( post, path = "/blocklist/toggle", params ( ("status" = bool, Query, description = "Boolean value to enable/disable blocklist"), ), responses( (status = 200, description = "Blocklist guard enabled/disabled", body = ToggleBlocklistResponse), (status = 400, description = "Invalid Data") ), tag = "Blocklist", operation_id = "Toggle blocklist guard for a particular merchant", security(("api_key" = [])) )] pub async fn toggle_blocklist_guard( state: web::Data<AppState>, req: HttpRequest, query_payload: web::Query<api_blocklist::ToggleBlocklistQuery>, ) -> HttpResponse { let flow = Flow::ListBlocklist; Box::pin(api::server_wrap( flow, state, &req, query_payload.into_inner(), |state, auth: auth::AuthenticationData, query, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); blocklist::toggle_blocklist_guard(state, merchant_context, query) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantAccountWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/blocklist.rs
router::src::routes::blocklist
1,461
true