// Struct: VoltErrorList
// File: crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct VoltErrorList


// Struct: LoonioRedirectUrl
// File: crates/hyperswitch_connectors/src/connectors/loonio/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct LoonioRedirectUrl


// Struct: Address
// File: crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct Address


// Struct: PurchaseUnitItem
// File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct PurchaseUnitItem


// Struct: UpiCollectAdditionalData
// File: crates/api_models/src/payments/additional_info.rs
// Module: api_models
// Implementations: 0

pub struct UpiCollectAdditionalData


// Struct: PixInfo
// File: crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct PixInfo


// Function: get_request_extended_authorization_bool_if_connector_supports
// File: crates/hyperswitch_domain_models/src/payments.rs
// Module: hyperswitch_domain_models

pub fn get_request_extended_authorization_bool_if_connector_supports(
        &self,
        connector: common_enums::connector_enums::Connector,
        always_request_extended_authorization_optional: Option<AlwaysRequestExtendedAuthorization>,
        payment_method_optional: Option<common_enums::PaymentMethod>,
        payment_method_type_optional: Option<common_enums::PaymentMethodType>,
    ) -> Option<RequestExtendedAuthorizationBool>


// Struct: StripebillingPaymentsResponse
// File: crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct StripebillingPaymentsResponse


// Implementation: impl fmt::Debug for for DenseMap
// File: crates/hyperswitch_constraint_graph/src/dense_map.rs
// Module: hyperswitch_constraint_graph
// Methods: 1 total (0 public)

impl fmt::Debug for for DenseMap


// Implementation: impl api::ExternalVaultRetrieve for for Tokenex
// File: crates/hyperswitch_connectors/src/connectors/tokenex.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::ExternalVaultRetrieve for for Tokenex


// Implementation: impl api::ExternalVaultInsert for for Tokenex
// File: crates/hyperswitch_connectors/src/connectors/tokenex.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::ExternalVaultInsert for for Tokenex


// Implementation: impl MergedEnabledPaymentMethodTypes
// File: crates/router/src/core/payments/payment_methods.rs
// Module: router
// Methods: 1 total (0 public)

impl MergedEnabledPaymentMethodTypes


// Struct: CheckoutRequest
// File: crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct CheckoutRequest


// Function: check_token_status_with_tokenization_service
// File: crates/router/src/core/payment_methods/network_tokenization.rs
// Module: router

pub fn check_token_status_with_tokenization_service(
    _state: &routes::SessionState,
    _customer_id: &id_type::GlobalCustomerId,
    _network_token_requestor_reference_id: String,
    _tokenization_service: &settings::NetworkTokenizationService,
) -> CustomResult<(Option<Secret<String>>, Option<Secret<String>>), errors::NetworkTokenizationError>


// Struct: TesouroPaymentsResponse
// File: crates/hyperswitch_connectors/src/connectors/tesouro/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct TesouroPaymentsResponse


// Struct: DebitRoutingRequestData
// File: crates/api_models/src/open_router.rs
// Module: api_models
// Implementations: 0

pub struct DebitRoutingRequestData


// Function: combine
// File: crates/hyperswitch_constraint_graph/src/graph.rs
// Module: hyperswitch_constraint_graph

pub fn combine(g1: &Self, g2: &Self) -> Result<Self, GraphError<V>>


// Struct: PaymentMethodsSessionUpdateRequest
// File: crates/api_models/src/payment_methods.rs
// Module: api_models
// Implementations: 0

pub struct PaymentMethodsSessionUpdateRequest


// File: crates/router/src/workflows/refund_router.rs
// Module: router
// Public structs: 1

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(())
    }
}


// Function: profile_id
// File: crates/common_utils/src/types/user/theme.rs
// Module: common_utils

// Documentation: Get the profile_id from the lineage

pub fn profile_id(&self) -> Option<&id_type::ProfileId>


// Function: find_by_profile_id_connector_name
// File: crates/diesel_models/src/query/merchant_connector_account.rs
// Module: diesel_models

pub fn find_by_profile_id_connector_name(
        conn: &PgPooledConn,
        profile_id: &common_utils::id_type::ProfileId,
        connector_name: &str,
    ) -> StorageResult<Self>


// Function: transfer_user_key_store_keymanager
// File: crates/router/src/core/user.rs
// Module: router

pub fn transfer_user_key_store_keymanager(
    state: SessionState,
    req: user_api::UserKeyTransferRequest,
) -> UserResponse<user_api::UserTransferKeyResponse>


// Function: master_key
// File: crates/storage_impl/src/kv_router_store.rs
// Module: storage_impl

pub fn master_key(&self) -> &StrongSecret<Vec<u8>>


// Function: validate
// File: crates/analytics/src/opensearch.rs
// Module: analytics

pub fn validate(&self) -> Result<(), ApplicationError>


// Implementation: impl GetRequestIncrementalAuthorization for for PaymentsSyncData
// File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
// Module: hyperswitch_connectors
// Methods: 1 total (0 public)

impl GetRequestIncrementalAuthorization for for PaymentsSyncData


// File: crates/api_models/src/connector_enums.rs
// Module: api_models

pub use common_enums::connector_enums::Connector;


// Implementation: impl ContractBasedRoutingConfig
// File: crates/api_models/src/routing.rs
// Module: api_models
// Methods: 1 total (1 public)

impl ContractBasedRoutingConfig


// Struct: CountAccumulator
// File: crates/analytics/src/auth_events/accumulator.rs
// Module: analytics
// Implementations: 1
// Traits: AuthEventMetricAccumulator

pub struct CountAccumulator


// Struct: BankOfAmericaConsumerAuthInformation
// File: crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct BankOfAmericaConsumerAuthInformation


    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(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::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());


// Function: build_pm_collect_link_status_html
// File: crates/router/src/services/api/generic_link_response.rs
// Module: router

pub fn build_pm_collect_link_status_html(
    link_data: &GenericLinkStatusData,
) -> CustomResult<String, errors::ApiErrorResponse>


// Struct: NuveiPaymentRequestData
// File: crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct NuveiPaymentRequestData


// Function: migrate_payment_methods
// File: crates/payment_methods/src/core/migration.rs
// Module: payment_methods

pub fn migrate_payment_methods(
    state: &state::PaymentMethodsState,
    payment_methods: Vec<pm_api::PaymentMethodRecord>,
    merchant_id: &common_utils::id_type::MerchantId,
    merchant_context: &merchant_context::MerchantContext,
    mca_ids: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
    controller: &dyn pm::PaymentMethodsController,
) -> PmMigrationResult<Vec<pm_api::PaymentMethodMigrationResponse>>


// Struct: MetricsResponse
// File: crates/api_models/src/analytics.rs
// Module: api_models
// Implementations: 0

pub struct MetricsResponse<T>


// Struct: TokenizationNew
// File: crates/hyperswitch_domain_models/src/tokenization.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct TokenizationNew


// Function: get_forex_rates
// File: crates/router/src/utils/currency.rs
// Module: router

pub fn get_forex_rates(
    state: &SessionState,
    data_expiration_delay: u32,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError>


// File: crates/router/src/configs.rs
// Module: router

use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret;

pub(crate) mod defaults;
pub mod secrets_transformers;
pub mod settings;
mod validations;

pub type Settings = settings::Settings<RawSecret>;


// Function: get_mandate
// File: crates/router/src/core/mandate.rs
// Module: router

pub fn get_mandate(
    state: SessionState,
    merchant_context: domain::MerchantContext,
    req: mandates::MandateId,
) -> RouterResponse<mandates::MandateResponse>


// Implementation: impl std::fmt::Display for for RoutingApproach
// File: crates/api_models/src/routing.rs
// Module: api_models
// Methods: 1 total (0 public)

impl std::fmt::Display for for RoutingApproach


// Implementation: impl api::PaymentSession for for Worldpayvantiv
// File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::PaymentSession for for Worldpayvantiv


// Function: get_payment_method_type
// File: crates/diesel_models/src/types.rs
// Module: diesel_models

pub fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethod>


// Function: mandate_procedure
// File: crates/router/src/core/mandate.rs
// Module: router

pub fn mandate_procedure<F, FData>(
    state: &SessionState,
    resp: &types::RouterData<F, FData, types::PaymentsResponseData>,
    customer_id: &Option<id_type::CustomerId>,
    pm_id: Option<String>,
    merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
    storage_scheme: MerchantStorageScheme,
    payment_id: &id_type::PaymentId,
) -> errors::RouterResult<Option<String>>
where
    FData: MandateBehaviour,


// File: crates/diesel_models/src/reverse_lookup.rs
// Module: diesel_models
// Public structs: 2

use diesel::{Identifiable, Insertable, Queryable, Selectable};

use crate::schema::reverse_lookup;

/// This reverse lookup table basically looks up id's and get result_id that you want. This is
/// useful for KV where you can't lookup without key
#[derive(
    Clone,
    Debug,
    serde::Serialize,
    serde::Deserialize,
    Identifiable,
    Queryable,
    Selectable,
    Eq,
    PartialEq,
)]
#[diesel(table_name = reverse_lookup, primary_key(lookup_id), check_for_backend(diesel::pg::Pg))]
pub struct ReverseLookup {
    /// Primary key. The key id.
    pub lookup_id: String,
    /// the `field` in KV database. Which is used to differentiate between two same keys
    pub sk_id: String,
    /// the value id. i.e the id you want to access KV table.
    pub pk_id: String,
    /// the source of insertion for reference
    pub source: String,
    pub updated_by: String,
}

#[derive(
    Clone,
    Debug,
    Insertable,
    router_derive::DebugAsDisplay,
    Eq,
    PartialEq,
    serde::Serialize,
    serde::Deserialize,
)]
#[diesel(table_name = reverse_lookup)]
pub struct ReverseLookupNew {
    pub lookup_id: String,
    pub pk_id: String,
    pub sk_id: String,
    pub source: String,
    pub updated_by: String,
}

impl From<ReverseLookupNew> for ReverseLookup {
    fn from(new: ReverseLookupNew) -> Self {
        Self {
            lookup_id: new.lookup_id,
            sk_id: new.sk_id,
            pk_id: new.pk_id,
            source: new.source,
            updated_by: new.updated_by,
        }
    }
}


// Implementation: impl api::PaymentSession for for Payload
// File: crates/hyperswitch_connectors/src/connectors/payload.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::PaymentSession for for Payload


// Function: disable_algorithm_id
// File: crates/api_models/src/routing.rs
// Module: api_models

pub fn disable_algorithm_id(&mut self, dynamic_routing_type: DynamicRoutingType)


// Implementation: impl api::ConnectorRedirectResponse for for Authorizedotnet
// File: crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs
// Module: hyperswitch_connectors
// Methods: 1 total (0 public)

impl api::ConnectorRedirectResponse for for Authorizedotnet


// Struct: BluesnapDisputeWebhookBody
// File: crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct BluesnapDisputeWebhookBody


// Struct: WellsfargoPaymentsResponse
// File: crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct WellsfargoPaymentsResponse


// Module Structure
// File: crates/common_enums/src/enums.rs
// Module: common_enums

// Public exports:
pub use accounts::{
    MerchantAccountRequestType, MerchantAccountType, MerchantProductType, OrganizationType,
};
pub use payments::ProductType;
pub use ui::*;
pub use super::connector_enums::RoutableConnectors;
pub use super::{
        DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus,
        DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind,
        DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus,
        DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency,
        DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage,
        DbDisputeStatus as DisputeStatus, DbFraudCheckStatus as FraudCheckStatus,
        DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus,
        DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode,
        DbPaymentType as PaymentType, DbProcessTrackerStatus as ProcessTrackerStatus,
        DbRefundStatus as RefundStatus,
        DbRequestIncrementalAuthorization as RequestIncrementalAuthorization,
        DbRoutingApproach as RoutingApproach, DbScaExemptionType as ScaExemptionType,
        DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState,
        DbTokenizationFlag as TokenizationFlag, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt,
    };


// Function: merchant_account_transfer_keys
// File: crates/router/src/routes/admin.rs
// Module: router

pub fn merchant_account_transfer_keys(
    state: web::Data<AppState>,
    req: HttpRequest,
    payload: web::Json<api_models::admin::MerchantKeyTransferRequest>,
) -> HttpResponse


// Implementation: impl api::PaymentSync for for Trustpayments
// File: crates/hyperswitch_connectors/src/connectors/trustpayments.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::PaymentSync for for Trustpayments


// Function: organization_retrieve
// File: crates/openapi/src/routes/organization.rs
// Module: openapi

pub fn organization_retrieve()


// Implementation: impl api::MandateSetup for for Bankofamerica
// File: crates/hyperswitch_connectors/src/connectors/bankofamerica.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::MandateSetup for for Bankofamerica


// Module Structure
// File: crates/router/src/types/api/admin.rs
// Module: router

// Public exports:
pub use api_models::admin;
pub use api_models::{
    admin::{
        MaskedHeaders, MerchantAccountCreate, MerchantAccountDeleteResponse,
        MerchantAccountResponse, MerchantAccountUpdate, MerchantConnectorCreate,
        MerchantConnectorDeleteResponse, MerchantConnectorDetails, MerchantConnectorDetailsWrap,
        MerchantConnectorId, MerchantConnectorResponse, MerchantDetails, MerchantId,
        PaymentMethodsEnabled, ProfileCreate, ProfileResponse, ProfileUpdate, ToggleAllKVRequest,
        ToggleAllKVResponse, ToggleKVRequest, ToggleKVResponse, WebhookDetails,
    },
    organization::{
        OrganizationCreateRequest, OrganizationId, OrganizationResponse, OrganizationUpdateRequest,
    },
};


// File: crates/router/src/workflows/api_key_expiry.rs
// Module: router
// Public structs: 1

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(())
    }
}


// Struct: AciWebhookAuthenticationDetails
// File: crates/hyperswitch_connectors/src/connectors/aci/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct AciWebhookAuthenticationDetails


// Struct: Health
// File: crates/router/src/bin/scheduler.rs
// Module: router
// Implementations: 1

pub struct Health


// File: crates/analytics/src/sdk_events/metrics.rs
// Module: analytics
// Public structs: 1

use std::collections::HashSet;

use api_models::analytics::{
    sdk_events::{
        SdkEventDimensions, SdkEventFilters, SdkEventMetrics, SdkEventMetricsBucketIdentifier,
    },
    Granularity, TimeRange,
};
use time::PrimitiveDateTime;

use crate::{
    query::{Aggregate, GroupByClause, ToSql, Window},
    types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, MetricsResult},
};

mod average_payment_time;
mod load_time;
mod payment_attempts;
mod payment_data_filled_count;
mod payment_method_selected_count;
mod payment_methods_call_count;
mod sdk_initiated_count;
mod sdk_rendered_count;

use average_payment_time::AveragePaymentTime;
use load_time::LoadTime;
use payment_attempts::PaymentAttempts;
use payment_data_filled_count::PaymentDataFilledCount;
use payment_method_selected_count::PaymentMethodSelectedCount;
use payment_methods_call_count::PaymentMethodsCallCount;
use sdk_initiated_count::SdkInitiatedCount;
use sdk_rendered_count::SdkRenderedCount;

#[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)]
pub struct SdkEventMetricRow {
    pub total: Option<bigdecimal::BigDecimal>,
    pub count: Option<i64>,
    pub time_bucket: Option<String>,
    pub payment_method: Option<String>,
    pub platform: Option<String>,
    pub browser_name: Option<String>,
    pub source: Option<String>,
    pub component: Option<String>,
    pub payment_experience: Option<String>,
}

pub trait SdkEventMetricAnalytics: LoadRow<SdkEventMetricRow> {}

#[async_trait::async_trait]
pub trait SdkEventMetric<T>
where
    T: AnalyticsDataSource + SdkEventMetricAnalytics,
{
    async fn load_metrics(
        &self,
        dimensions: &[SdkEventDimensions],
        publishable_key: &str,
        filters: &SdkEventFilters,
        granularity: Option<Granularity>,
        time_range: &TimeRange,
        pool: &T,
    ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>>;
}

#[async_trait::async_trait]
impl<T> SdkEventMetric<T> for SdkEventMetrics
where
    T: AnalyticsDataSource + SdkEventMetricAnalytics,
    PrimitiveDateTime: ToSql<T>,
    AnalyticsCollection: ToSql<T>,
    Granularity: GroupByClause<T>,
    Aggregate<&'static str>: ToSql<T>,
    Window<&'static str>: ToSql<T>,
{
    async fn load_metrics(
        &self,
        dimensions: &[SdkEventDimensions],
        publishable_key: &str,
        filters: &SdkEventFilters,
        granularity: Option<Granularity>,
        time_range: &TimeRange,
        pool: &T,
    ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> {
        match self {
            Self::PaymentAttempts => {
                PaymentAttempts
                    .load_metrics(
                        dimensions,
                        publishable_key,
                        filters,
                        granularity,
                        time_range,
                        pool,
                    )
                    .await
            }
            Self::PaymentMethodsCallCount => {
                PaymentMethodsCallCount
                    .load_metrics(
                        dimensions,
                        publishable_key,
                        filters,
                        granularity,
                        time_range,
                        pool,
                    )
                    .await
            }
            Self::SdkRenderedCount => {
                SdkRenderedCount
                    .load_metrics(
                        dimensions,
                        publishable_key,
                        filters,
                        granularity,
                        time_range,
                        pool,
                    )
                    .await
            }
            Self::SdkInitiatedCount => {
                SdkInitiatedCount
                    .load_metrics(
                        dimensions,
                        publishable_key,
                        filters,
                        granularity,
                        time_range,
                        pool,
                    )
                    .await
            }
            Self::PaymentMethodSelectedCount => {
                PaymentMethodSelectedCount
                    .load_metrics(
                        dimensions,
                        publishable_key,
                        filters,
                        granularity,
                        time_range,
                        pool,
                    )
                    .await
            }
            Self::PaymentDataFilledCount => {
                PaymentDataFilledCount
                    .load_metrics(
                        dimensions,
                        publishable_key,
                        filters,
                        granularity,
                        time_range,
                        pool,
                    )
                    .await
            }
            Self::AveragePaymentTime => {
                AveragePaymentTime
                    .load_metrics(
                        dimensions,
                        publishable_key,
                        filters,
                        granularity,
                        time_range,
                        pool,
                    )
                    .await
            }
            Self::LoadTime => {
                LoadTime
                    .load_metrics(
                        dimensions,
                        publishable_key,
                        filters,
                        granularity,
                        time_range,
                        pool,
                    )
                    .await
            }
        }
    }
}


// File: crates/router/tests/connectors/worldpay.rs
// Module: router

use futures::future::OptionFuture;
use router::types::{self, domain, storage::enums};
use serde_json::json;
use serial_test::serial;
use wiremock::{
    matchers::{body_json, method, path},
    Mock, ResponseTemplate,
};

use crate::{
    connector_auth,
    utils::{self, ConnectorActions, LocalMock, MockConfig},
};

struct Worldpay;

impl LocalMock for Worldpay {}
impl ConnectorActions for Worldpay {}
impl utils::Connector for Worldpay {
    fn get_data(&self) -> types::api::ConnectorData {
        use router::connector::Worldpay;
        utils::construct_connector_data_old(
            Box::new(Worldpay::new()),
            types::Connector::Worldpay,
            types::api::GetToken::Connector,
            None,
        )
    }

    fn get_auth_token(&self) -> types::ConnectorAuthType {
        utils::to_connector_auth_type(
            connector_auth::ConnectorAuthentication::new()
                .worldpay
                .expect("Missing connector authentication configuration")
                .into(),
        )
    }

    fn get_name(&self) -> String {
        "worldpay".to_string()
    }
}

#[actix_web::test]
#[serial]
async fn should_authorize_card_payment() {
    let conn = Worldpay {};
    let _mock = conn.start_server(get_mock_config()).await;
    let response = conn.authorize_payment(None, None).await.unwrap();
    assert_eq!(response.status, enums::AttemptStatus::Authorized);
    assert_eq!(
        utils::get_connector_transaction_id(response.response),
        Some("123456".to_string())
    );
}

#[actix_web::test]
#[serial]
async fn should_authorize_gpay_payment() {
    let conn = Worldpay {};
    let _mock = conn.start_server(get_mock_config()).await;
    let response = conn
        .authorize_payment(
            Some(types::PaymentsAuthorizeData {
                payment_method_data: domain::PaymentMethodData::Wallet(
                    domain::WalletData::GooglePay(domain::GooglePayWalletData {
                        pm_type: "CARD".to_string(),
                        description: "Visa1234567890".to_string(),
                        info: domain::GooglePayPaymentMethodInfo {
                            card_network: "VISA".to_string(),
                            card_details: "1234".to_string(),
                            assurance_details: None,
                        },
                        tokenization_data: common_types::payments::GpayTokenizationData::Encrypted(
                            common_types::payments::GpayEcryptedTokenizationData {
                                token_type: "worldpay".to_string(),
                                token: "someToken".to_string(),
                            },
                        ),
                    }),
                ),
                ..utils::PaymentAuthorizeType::default().0
            }),
            None,
        )
        .await
        .unwrap();
    assert_eq!(response.status, enums::AttemptStatus::Authorized);
    assert_eq!(
        utils::get_connector_transaction_id(response.response),
        Some("123456".to_string())
    );
}

#[actix_web::test]
#[serial]
async fn should_authorize_applepay_payment() {
    let conn = Worldpay {};
    let _mock = conn.start_server(get_mock_config()).await;
    let response = conn
        .authorize_payment(
            Some(types::PaymentsAuthorizeData {
                payment_method_data: domain::PaymentMethodData::Wallet(
                    domain::WalletData::ApplePay(domain::ApplePayWalletData {
                        payment_data: common_types::payments::ApplePayPaymentData::Encrypted(
                            "someData".to_string(),
                        ),
                        transaction_identifier: "someId".to_string(),
                        payment_method: domain::ApplepayPaymentMethod {
                            display_name: "someName".to_string(),
                            network: "visa".to_string(),
                            pm_type: "card".to_string(),
                        },
                    }),
                ),
                ..utils::PaymentAuthorizeType::default().0
            }),
            None,
        )
        .await
        .unwrap();
    assert_eq!(response.status, enums::AttemptStatus::Authorized);
    assert_eq!(
        utils::get_connector_transaction_id(response.response),
        Some("123456".to_string())
    );
}

#[actix_web::test]
#[serial]
async fn should_capture_already_authorized_payment() {
    let connector = Worldpay {};
    let _mock = connector.start_server(get_mock_config()).await;
    let authorize_response = connector.authorize_payment(None, None).await.unwrap();
    assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized);
    let txn_id = utils::get_connector_transaction_id(authorize_response.response);
    let response: OptionFuture<_> = txn_id
        .map(|transaction_id| async move {
            connector
                .capture_payment(transaction_id, None, None)
                .await
                .unwrap()
                .status
        })
        .into();
    assert_eq!(response.await, Some(enums::AttemptStatus::Charged));
}

#[actix_web::test]
#[serial]
async fn should_sync_payment() {
    let connector = Worldpay {};
    let _mock = connector.start_server(get_mock_config()).await;
    let response = connector
        .sync_payment(
            Some(types::PaymentsSyncData {
                connector_transaction_id: types::ResponseId::ConnectorTransactionId(
                    "112233".to_string(),
                ),
                ..Default::default()
            }),
            None,
        )
        .await
        .unwrap();
    assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}

#[actix_web::test]
#[serial]
async fn should_void_already_authorized_payment() {
    let connector = Worldpay {};
    let _mock = connector.start_server(get_mock_config()).await;
    let authorize_response = connector.authorize_payment(None, None).await.unwrap();
    assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized);
    let txn_id = utils::get_connector_transaction_id(authorize_response.response);
    let response: OptionFuture<_> = txn_id
        .map(|transaction_id| async move {
            connector
                .void_payment(transaction_id, None, None)
                .await
                .unwrap()
                .status
        })
        .into();
    assert_eq!(response.await, Some(enums::AttemptStatus::Voided));
}

#[actix_web::test]
#[serial]
async fn should_fail_capture_for_invalid_payment() {
    let connector = Worldpay {};
    let _mock = connector.start_server(get_mock_config()).await;
    let authorize_response = connector.authorize_payment(None, None).await.unwrap();
    assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized);
    let response = connector
        .capture_payment("12345".to_string(), None, None)
        .await
        .unwrap();
    let err = response.response.unwrap_err();
    assert_eq!(
        err.message,
        "You must provide valid transaction id to capture payment".to_string()
    );
    assert_eq!(err.code, "invalid-id".to_string());
}

#[actix_web::test]
#[serial]
async fn should_refund_succeeded_payment() {
    let connector = Worldpay {};
    let _mock = connector.start_server(get_mock_config()).await;
    //make a successful payment
    let response = connector.make_payment(None, None).await.unwrap();

    //try refund for previous payment
    let transaction_id = utils::get_connector_transaction_id(response.response).unwrap();
    let response = connector
        .refund_payment(transaction_id, None, None)
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap().refund_status,
        enums::RefundStatus::Success,
    );
}

#[actix_web::test]
#[serial]
async fn should_sync_refund() {
    let connector = Worldpay {};
    let _mock = connector.start_server(get_mock_config()).await;
    let response = connector
        .sync_refund("654321".to_string(), None, None)
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap().refund_status,
        enums::RefundStatus::Success,
    );
}

fn get_mock_config() -> MockConfig {
    let authorized = json!({
        "outcome": "authorized",
        "_links": {
            "payments:cancel": {
                "href": "/payments/authorizations/cancellations/123456"
            },
            "payments:settle": {
                "href": "/payments/settlements/123456"
            },
            "payments:partialSettle": {
                "href": "/payments/settlements/partials/123456"
            },
            "payments:events": {
                "href": "/payments/events/123456"
            },
            "curies": [
                {
                    "name": "payments",
                    "href": "/rels/payments/{rel}",
                    "templated": true
                }
            ]
        }
    });
    let settled = json!({
        "_links": {
            "payments:refund": {
                "href": "/payments/settlements/refunds/full/654321"
            },
            "payments:partialRefund": {
                "href": "/payments/settlements/refunds/partials/654321"
            },
            "payments:events": {
                "href": "/payments/events/654321"
            },
            "curies": [
                {
                    "name": "payments",
                    "href": "/rels/payments/{rel}",
                    "templated": true
                }
            ]
        }
    });
    let error_resp = json!({
        "errorName": "invalid-id",
        "message": "You must provide valid transaction id to capture payment"
    });
    let partial_refund = json!({
        "_links": {
            "payments:events": {
                "href": "https://try.access.worldpay.com/payments/events/eyJrIjoiazNhYjYzMiJ9"
            },
            "curies": [{
                "name": "payments",
                "href": "https://try.access.worldpay.com/rels/payments/{rel}",
                "templated": true
            }]
        }
    });
    let partial_refund_req_body = json!({
        "value": {
            "amount": 100,
            "currency": "USD"
        },
        "reference": "123456"
    });
    let refunded = json!({
        "lastEvent": "refunded",
        "_links": {
            "payments:cancel": "/payments/authorizations/cancellations/654321",
            "payments:settle": "/payments/settlements/full/654321",
            "payments:partialSettle": "/payments/settlements/partials/654321",
            "curies": [
                {
                    "name": "payments",
                    "href": "/rels/payments/{rel}",
                    "templated": true
                }
            ]
        }
    });
    let sync_payment = json!({
        "lastEvent": "authorized",
        "_links": {
            "payments:events": "/payments/authorizations/events/654321",
            "payments:settle": "/payments/settlements/full/654321",
            "payments:partialSettle": "/payments/settlements/partials/654321",
            "curies": [
                {
                    "name": "payments",
                    "href": "/rels/payments/{rel}",
                    "templated": true
                }
            ]
        }
    });

    MockConfig {
        address: Some("127.0.0.1:9090".to_string()),
        mocks: vec![
            Mock::given(method("POST"))
                .and(path("/payments/authorizations".to_string()))
                .respond_with(ResponseTemplate::new(201).set_body_json(authorized)),
            Mock::given(method("POST"))
                .and(path("/payments/settlements/123456".to_string()))
                .respond_with(ResponseTemplate::new(202).set_body_json(settled)),
            Mock::given(method("GET"))
                .and(path("/payments/events/112233".to_string()))
                .respond_with(ResponseTemplate::new(200).set_body_json(sync_payment)),
            Mock::given(method("POST"))
                .and(path("/payments/settlements/12345".to_string()))
                .respond_with(ResponseTemplate::new(400).set_body_json(error_resp)),
            Mock::given(method("POST"))
                .and(path(
                    "/payments/settlements/refunds/partials/123456".to_string(),
                ))
                .and(body_json(partial_refund_req_body))
                .respond_with(ResponseTemplate::new(202).set_body_json(partial_refund)),
            Mock::given(method("GET"))
                .and(path("/payments/events/654321".to_string()))
                .respond_with(ResponseTemplate::new(200).set_body_json(refunded)),
        ],
    }
}


// Implementation: impl api::RefundSync for for Bambora
// File: crates/hyperswitch_connectors/src/connectors/bambora.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::RefundSync for for Bambora


// Struct: BamboraapacAuthType
// File: crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct BamboraapacAuthType


// Struct: MerchantAccountUpdateInternal
// File: crates/diesel_models/src/merchant_account.rs
// Module: diesel_models
// Implementations: 2

pub struct MerchantAccountUpdateInternal


// Struct: CustomerAcceptance
// File: crates/common_types/src/payments.rs
// Module: common_types
// Implementations: 2
// Traits: masking::SerializableSecret

pub struct CustomerAcceptance


// Implementation: impl api::PaymentToken for for Worldpayvantiv
// File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::PaymentToken for for Worldpayvantiv


// Struct: RouterHealthCheckResponse
// File: crates/api_models/src/health_check.rs
// Module: api_models
// Implementations: 1
// Traits: common_utils::events::ApiEventMetric

pub struct RouterHealthCheckResponse


// Implementation: impl ProphetpayCardContext
// File: crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs
// Module: hyperswitch_connectors
// Methods: 1 total (0 public)

impl ProphetpayCardContext


// Function: get_payout_method_data_from_temporary_locker
// File: crates/router/src/core/payment_methods/vault.rs
// Module: router

pub fn get_payout_method_data_from_temporary_locker(
        state: &routes::SessionState,
        lookup_key: &str,
        merchant_key_store: &domain::MerchantKeyStore,
    ) -> RouterResult<(Option<api::PayoutMethodData>, SupplementaryVaultData)>


// Implementation: impl Flexiti
// File: crates/hyperswitch_connectors/src/connectors/flexiti.rs
// Module: hyperswitch_connectors
// Methods: 1 total (1 public)

impl Flexiti


// Function: get_disputes_aggregate_profile
// File: crates/router/src/routes/disputes.rs
// Module: router

pub fn get_disputes_aggregate_profile(
    state: web::Data<AppState>,
    req: HttpRequest,
    query_param: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse


// Implementation: impl api::PaymentCapture for for Boku
// File: crates/hyperswitch_connectors/src/connectors/boku.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::PaymentCapture for for Boku


// Function: get_refund_body
// File: crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs
// Module: hyperswitch_connectors

pub fn get_refund_body(
    req: &BamboraapacRouterData<&types::RefundExecuteRouterData>,
) -> Result<Vec<u8>, Error>


// Struct: TelemetryGuard
// File: crates/router_env/src/logger/setup.rs
// Module: router_env
// Implementations: 0

pub struct TelemetryGuard


// Implementation: impl ApiEventMetric for for ListBlocklistQuery
// File: crates/api_models/src/blocklist.rs
// Module: api_models
// Methods: 0 total (0 public)

impl ApiEventMetric for for ListBlocklistQuery


// Struct: PaymentMethodMetaData
// File: crates/api_models/src/three_ds_decision_rule.rs
// Module: api_models
// Implementations: 0

pub struct PaymentMethodMetaData


// File: crates/api_models/src/tokenization.rs
// Module: api_models
// Public structs: 4

use common_enums;
use common_utils::id_type;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::{schema, ToSchema};

#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct GenericTokenizationResponse {
    /// Unique identifier returned by the tokenization service
    #[schema(value_type = String, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")]
    pub id: id_type::GlobalTokenId,
    /// Created time of the tokenization id
    #[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")]
    pub created_at: PrimitiveDateTime,
    /// Status of the tokenization id created
    #[schema(value_type = String,example = "enabled")]
    pub flag: common_enums::TokenizationFlag,
}
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct GenericTokenizationRequest {
    /// Customer ID for which the tokenization is requested
    #[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")]
    pub customer_id: id_type::GlobalCustomerId,
    /// Request for tokenization which contains the data to be tokenized
    #[schema(value_type = Object,example = json!({ "city": "NY", "unit": "245" }))]
    pub token_request: masking::Secret<serde_json::Value>,
}

#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct DeleteTokenDataRequest {
    /// Customer ID for which the tokenization is requested
    #[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")]
    pub customer_id: id_type::GlobalCustomerId,
    /// Session ID associated with the tokenization request
    #[schema(value_type = String, example = "12345_pms_01926c58bc6e77c09e809964e72af8c8")]
    pub session_id: id_type::GlobalPaymentMethodSessionId,
}

#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct DeleteTokenDataResponse {
    /// Unique identifier returned by the tokenization service
    #[schema(value_type = String, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")]
    pub id: id_type::GlobalTokenId,
}


// Function: authentication_create
// File: crates/router/src/routes/authentication.rs
// Module: router

pub fn authentication_create(
    state: web::Data<app::AppState>,
    req: HttpRequest,
    json_payload: web::Json<AuthenticationCreateRequest>,
) -> impl Responder


// Implementation: impl common_utils::events::ApiEventMetric for for RelayRetrieveRequest
// File: crates/api_models/src/relay.rs
// Module: api_models
// Methods: 0 total (0 public)

impl common_utils::events::ApiEventMetric for for RelayRetrieveRequest


// Implementation: impl ConnectorValidation for for Zen
// File: crates/hyperswitch_connectors/src/connectors/zen.rs
// Module: hyperswitch_connectors
// Methods: 1 total (0 public)

impl ConnectorValidation for for Zen


// Function: collect
// File: crates/analytics/src/auth_events/accumulator.rs
// Module: analytics

pub fn collect(self) -> AuthEventMetricsBucketValue


// Function: get_refunds_filters_profile
// File: crates/router/src/routes/refunds.rs
// Module: router

pub fn get_refunds_filters_profile(
    state: web::Data<AppState>,
    req: HttpRequest,
) -> HttpResponse


// File: crates/hyperswitch_interfaces/src/crm.rs
// Module: hyperswitch_interfaces
// Public structs: 1

use common_enums::CountryAlpha2;
use common_utils::{
    errors::CustomResult,
    request::{Request, RequestContent},
};
use masking::Secret;

use super::types::Proxy;
use crate::errors::HttpClientError;

/// Crm Payload structure
#[derive(Clone, Debug, serde::Serialize, Default)]
pub struct CrmPayload {
    /// The legal name of the business.
    pub legal_business_name: Option<String>,

    /// A label or tag associated with the business.
    pub business_label: Option<String>,

    /// The location of the business, represented as a country code (ISO Alpha-2 format).
    pub business_location: Option<CountryAlpha2>,

    /// The display name of the business.
    pub display_name: Option<String>,

    /// The email address of the point of contact (POC) for the business.
    pub poc_email: Option<Secret<String>>,

    /// The type of business (e.g., LLC, Corporation, etc.).
    pub business_type: Option<String>,

    /// A unique identifier for the business.
    pub business_identifier: Option<String>,

    /// The website URL of the business.
    pub business_website: Option<String>,

    /// The name of the point of contact (POC) for the business.
    pub poc_name: Option<Secret<String>>,

    /// The contact number of the point of contact (POC) for the business.
    pub poc_contact: Option<Secret<String>>,

    /// Additional comments or notes about the business.
    pub comments: Option<String>,

    /// Indicates whether the Crm process for the business is completed.
    pub is_completed: bool,

    /// The name of the country where the business is located.
    pub business_country_name: Option<String>,
}

/// Trait defining the interface for encryption management
#[async_trait::async_trait]
pub trait CrmInterface: Send + Sync {
    /// Make body for the request
    async fn make_body(&self, details: CrmPayload) -> RequestContent;

    /// Encrypt the given input data
    async fn make_request(&self, body: RequestContent, origin_base_url: String) -> Request;

    /// Decrypt the given input data
    async fn send_request(
        &self,
        proxy: &Proxy,
        request: Request,
    ) -> CustomResult<reqwest::Response, HttpClientError>;
}


// Implementation: impl api::Refund for for Opayo
// File: crates/hyperswitch_connectors/src/connectors/opayo.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::Refund for for Opayo


// Function: get_recovery_codes
// File: crates/router/src/types/domain/user.rs
// Module: router

pub fn get_recovery_codes(&self) -> Option<Vec<Secret<String>>>


// Struct: FiservCancelRequest
// File: crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct FiservCancelRequest


// Function: find_by_user_email
// File: crates/diesel_models/src/query/user.rs
// Module: diesel_models

pub fn find_by_user_email(
        conn: &PgPooledConn,
        user_email: &pii::Email,
    ) -> StorageResult<Self>


// Implementation: impl api::ConnectorMandateRevoke for for Wellsfargo
// File: crates/hyperswitch_connectors/src/connectors/wellsfargo.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::ConnectorMandateRevoke for for Wellsfargo


// Struct: RiskifiedMetadata
// File: crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct RiskifiedMetadata


// Struct: PoRecipient
// File: crates/hyperswitch_domain_models/src/router_flow_types/payouts.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct PoRecipient


// Struct: Card
// File: crates/hyperswitch_connectors/src/connectors/globalpay/response.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct Card


// Implementation: impl StreamData
// File: crates/drainer/src/types.rs
// Module: drainer
// Methods: 1 total (1 public)

impl StreamData


// Struct: GetCard
// File: crates/router/src/core/payment_methods/transformers.rs
// Module: router
// Implementations: 0

pub struct GetCard<'a>


// Struct: DummyConnectorPaymentConfirmRequest
// File: crates/router/src/routes/dummy_connector/types.rs
// Module: router
// Implementations: 0

pub struct DummyConnectorPaymentConfirmRequest


// Function: list_initial_webhook_delivery_attempts
// File: crates/router/src/routes/webhook_events.rs
// Module: router

pub fn list_initial_webhook_delivery_attempts(
    state: web::Data<AppState>,
    req: HttpRequest,
    path: web::Path<common_utils::id_type::MerchantId>,
    json_payload: web::Json<EventListConstraints>,
) -> impl Responder


// Function: get_scope_name
// File: crates/router/src/services/authorization/permissions.rs
// Module: router

pub fn get_scope_name(scope: PermissionScope) -> &'static str


// Struct: TrustpayApplePayResponse
// File: crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct TrustpayApplePayResponse


// Implementation: impl api::RefundSync for for Barclaycard
// File: crates/hyperswitch_connectors/src/connectors/barclaycard.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::RefundSync for for Barclaycard


// Struct: ChargebackTransactionDetails
// File: crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct ChargebackTransactionDetails


// Function: payments_retrieve
// File: crates/router/src/routes/payments.rs
// Module: router

pub 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


// Implementation: impl std::fmt::Debug for for RedisStore
// File: crates/storage_impl/src/redis.rs
// Module: storage_impl
// Methods: 1 total (0 public)

impl std::fmt::Debug for for RedisStore


// Function: should_call_connector_create_customer
// File: crates/router/src/core/payments/customers.rs
// Module: router

pub fn should_call_connector_create_customer<'a>(
    connector: &api::ConnectorData,
    customer: &'a Option<domain::Customer>,
    payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
    connector_label: &str,
) -> (bool, Option<&'a str>)


// File: crates/hyperswitch_interfaces/src/configs.rs
// Module: hyperswitch_interfaces

pub use hyperswitch_domain_models::connector_endpoints::Connectors;


// Struct: RefundResponse
// File: crates/hyperswitch_connectors/src/connectors/phonepe/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct RefundResponse


// Struct: PaymentInfo
// File: crates/api_models/src/open_router.rs
// Module: api_models
// Implementations: 0

pub struct PaymentInfo


// Function: compare_password
// File: crates/router/src/types/domain/user.rs
// Module: router

pub fn compare_password(&self, candidate: &Secret<String>) -> UserResult<()>


// Function: server
// File: crates/router/src/routes/app.rs
// Module: router

pub fn server(state: AppState) -> Scope


// Implementation: impl ConfirmSubscriptionRequest
// File: crates/api_models/src/subscription.rs
// Module: api_models
// Methods: 2 total (2 public)

impl ConfirmSubscriptionRequest


// Struct: ProcessingInformation
// File: crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct ProcessingInformation


// Implementation: impl Eq for for StrongSecret
// File: crates/masking/src/strong_secret.rs
// Module: masking
// Methods: 0 total (0 public)

impl Eq for for StrongSecret