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

pub fn get_client_secret_or_add_payment_method_for_migration(
    state: &state::PaymentMethodsState,
    req: pm_api::PaymentMethodCreate,
    merchant_context: &merchant_context::MerchantContext,
    migration_status: &mut migration::RecordMigrationStatusBuilder,
    controller: &dyn PaymentMethodsController,
) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse>


// Struct: SignUpRequest
// File: crates/api_models/src/user.rs
// Module: api_models
// Implementations: 0

pub struct SignUpRequest


// Struct: CeleroRefundResponse
// File: crates/hyperswitch_connectors/src/connectors/celero/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct CeleroRefundResponse


// Function: toggle_kv_for_all_merchants
// File: crates/router/src/core/admin.rs
// Module: router

pub fn toggle_kv_for_all_merchants(
    state: SessionState,
    enable: bool,
) -> RouterResponse<api_models::admin::ToggleAllKVResponse>


// Module Structure
// File: crates/analytics/src/lib.rs
// Module: analytics

// Public submodules:
pub mod active_payments;
pub mod api_event;
pub mod auth_events;
pub mod connector_events;
pub mod core;
pub mod disputes;
pub mod enums;
pub mod errors;
pub mod frm;
pub mod health_check;
pub mod metrics;
pub mod opensearch;
pub mod outgoing_webhook_event;
pub mod payment_intents;
pub mod payments;
// ... and 6 more

// Public exports:
pub use types::AnalyticsDomain;
pub use clickhouse::ClickhouseConfig;


// File: crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs
// Module: analytics

use std::collections::HashSet;

use api_models::analytics::{
    refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier},
    Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;

use super::RefundMetricRow;
use crate::{
    enums::AuthInfo,
    query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
    types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};

#[derive(Default)]
pub(crate) struct RefundCount {}

#[async_trait::async_trait]
impl<T> super::RefundMetric<T> for RefundCount
where
    T: AnalyticsDataSource + super::RefundMetricAnalytics,
    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: &[RefundDimensions],
        auth: &AuthInfo,
        filters: &RefundFilters,
        granularity: Option<Granularity>,
        time_range: &TimeRange,
        pool: &T,
    ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> {
        let mut query_builder: QueryBuilder<T> =
            QueryBuilder::new(AnalyticsCollection::RefundSessionized);

        for dim in dimensions.iter() {
            query_builder.add_select_column(dim).switch()?;
        }

        query_builder
            .add_select_column(Aggregate::Count {
                field: None,
                alias: Some("count"),
            })
            .switch()?;
        query_builder
            .add_select_column(Aggregate::Min {
                field: "created_at",
                alias: Some("start_bucket"),
            })
            .switch()?;
        query_builder
            .add_select_column(Aggregate::Max {
                field: "created_at",
                alias: Some("end_bucket"),
            })
            .switch()?;

        filters.set_filter_clause(&mut query_builder).switch()?;

        auth.set_filter_clause(&mut query_builder).switch()?;

        time_range
            .set_filter_clause(&mut query_builder)
            .attach_printable("Error filtering time range")
            .switch()?;

        for dim in dimensions.iter() {
            query_builder
                .add_group_by_clause(dim)
                .attach_printable("Error grouping by dimensions")
                .switch()?;
        }

        if let Some(granularity) = granularity {
            granularity
                .set_group_by_clause(&mut query_builder)
                .attach_printable("Error adding granularity")
                .switch()?;
        }

        query_builder
            .execute_query::<RefundMetricRow, _>(pool)
            .await
            .change_context(MetricsError::QueryBuildingError)?
            .change_context(MetricsError::QueryExecutionFailure)?
            .into_iter()
            .map(|i| {
                Ok((
                    RefundMetricsBucketIdentifier::new(
                        i.currency.as_ref().map(|i| i.0),
                        i.refund_status.as_ref().map(|i| i.0.to_string()),
                        i.connector.clone(),
                        i.refund_type.as_ref().map(|i| i.0.to_string()),
                        i.profile_id.clone(),
                        i.refund_reason.clone(),
                        i.refund_error_message.clone(),
                        TimeRange {
                            start_time: match (granularity, i.start_bucket) {
                                (Some(g), Some(st)) => g.clip_to_start(st)?,
                                _ => time_range.start_time,
                            },
                            end_time: granularity.as_ref().map_or_else(
                                || Ok(time_range.end_time),
                                |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
                            )?,
                        },
                    ),
                    i,
                ))
            })
            .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>()
            .change_context(MetricsError::PostProcessingFailure)
    }
}


// Struct: NetworkToken
// File: crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct NetworkToken


// Function: get_cookie_from_header
// File: crates/router/src/services/authentication.rs
// Module: router

pub fn get_cookie_from_header(headers: &HeaderMap) -> RouterResult<&str>


// Function: voucher_next_steps_check
// File: crates/router/src/core/payments/transformers.rs
// Module: router

pub fn voucher_next_steps_check(
    payment_attempt: storage::PaymentAttempt,
) -> RouterResult<Option<api_models::payments::VoucherNextStepData>>


// Function: insert
// File: crates/diesel_models/src/query/payment_method.rs
// Module: diesel_models

pub fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentMethod>


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

impl api::RefundSync for for Razorpay


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

impl api::ConnectorAccessToken for for Zen


// Struct: Deposited
// File: crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct Deposited


// Function: refund_retrieve
// File: crates/router/src/compatibility/stripe/refunds.rs
// Module: router

pub fn refund_retrieve(
    state: web::Data<routes::AppState>,
    req: HttpRequest,
    path: web::Path<String>,
) -> HttpResponse


// Implementation: impl GlobalPaymentMethodId
// File: crates/common_utils/src/id_type/global_id/payment_methods.rs
// Module: common_utils
// Methods: 3 total (3 public)

impl GlobalPaymentMethodId


// File: crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
// Module: router
// Public functions: 2

use common_utils::ext_traits::{OptionExt, ValueExt};
use error_stack::ResultExt;
use router_env::tracing::{self, instrument};

use crate::{
    core::{
        errors::RouterResult, fraud_check::frm_core_types::FrmFulfillmentRequest,
        payments::helpers, utils as core_utils,
    },
    errors,
    types::{
        domain,
        fraud_check::{FraudCheckFulfillmentData, FrmFulfillmentRouterData},
        storage, ConnectorAuthType, ErrorResponse, PaymentAddress, RouterData,
    },
    utils, SessionState,
};

#[cfg(feature = "v2")]
pub async fn construct_fulfillment_router_data<'a>(
    _state: &'a SessionState,
    _payment_intent: &'a storage::PaymentIntent,
    _payment_attempt: &storage::PaymentAttempt,
    _merchant_context: &domain::MerchantContext,
    _connector: String,
    _fulfillment_request: FrmFulfillmentRequest,
) -> RouterResult<FrmFulfillmentRouterData> {
    todo!()
}

#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn construct_fulfillment_router_data<'a>(
    state: &'a SessionState,
    payment_intent: &'a storage::PaymentIntent,
    payment_attempt: &storage::PaymentAttempt,
    merchant_context: &domain::MerchantContext,
    connector: String,
    fulfillment_request: FrmFulfillmentRequest,
) -> RouterResult<FrmFulfillmentRouterData> {
    let profile_id = payment_intent
        .profile_id
        .as_ref()
        .get_required_value("profile_id")
        .change_context(errors::ApiErrorResponse::InternalServerError)
        .attach_printable("profile_id is not set in payment_intent")?
        .clone();

    let connector_id = connector.clone();

    let merchant_connector_account = helpers::get_merchant_connector_account(
        state,
        merchant_context.get_merchant_account().get_id(),
        None,
        merchant_context.get_merchant_key_store(),
        &profile_id,
        &connector,
        None,
    )
    .await?;

    let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
    let auth_type: ConnectorAuthType = merchant_connector_account
        .get_connector_account_details()
        .parse_value("ConnectorAuthType")
        .change_context(errors::ApiErrorResponse::InternalServerError)?;
    let payment_method = utils::OptionExt::get_required_value(
        payment_attempt.payment_method,
        "payment_method_type",
    )?;
    let router_data = RouterData {
        flow: std::marker::PhantomData,
        merchant_id: merchant_context.get_merchant_account().get_id().clone(),
        tenant_id: state.tenant.tenant_id.clone(),
        connector,
        payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
        attempt_id: payment_attempt.attempt_id.clone(),
        status: payment_attempt.status,
        payment_method,
        connector_auth_type: auth_type,
        description: None,
        address: PaymentAddress::default(),
        auth_type: payment_attempt.authentication_type.unwrap_or_default(),
        connector_meta_data: merchant_connector_account.get_metadata(),
        connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
        amount_captured: payment_intent
            .amount_captured
            .map(|amt| amt.get_amount_as_i64()),
        minor_amount_captured: payment_intent.amount_captured,
        payment_method_status: None,
        request: FraudCheckFulfillmentData {
            amount: payment_attempt
                .net_amount
                .get_total_amount()
                .get_amount_as_i64(),
            order_details: payment_intent.order_details.clone(),
            fulfillment_req: fulfillment_request,
        },
        response: Err(ErrorResponse::default()),
        access_token: None,
        session_token: None,
        reference_id: None,
        payment_method_token: None,
        connector_customer: None,
        customer_id: None,
        recurring_mandate_payment_data: None,
        preprocessing_id: None,
        payment_method_balance: None,
        connector_request_reference_id: core_utils::get_connector_request_reference_id(
            &state.conf,
            merchant_context.get_merchant_account().get_id(),
            payment_intent,
            payment_attempt,
            &connector_id,
        )?,
        #[cfg(feature = "payouts")]
        payout_method_data: None,
        #[cfg(feature = "payouts")]
        quote_id: None,
        test_mode,
        connector_api_version: None,
        connector_http_status_code: None,
        external_latency: None,
        apple_pay_flow: None,
        frm_metadata: None,
        refund_id: None,
        dispute_id: None,
        connector_response: None,
        integrity_check: Ok(()),
        additional_merchant_data: None,
        header_payload: None,
        connector_mandate_request_reference_id: None,
        authentication_id: None,
        psd2_sca_exemption_type: None,
        raw_connector_response: None,
        is_payment_id_from_merchant: None,
        l2_l3_data: None,
        minor_amount_capturable: None,
    };
    Ok(router_data)
}


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

pub fn retrieve_payment_method_from_vault_internal(
    state: &routes::SessionState,
    merchant_context: &domain::MerchantContext,
    vault_id: &domain::VaultId,
    customer_id: &id_type::GlobalCustomerId,
) -> CustomResult<pm_types::VaultRetrieveResponse, errors::VaultError>


// Function: generate_digest_from_request
// File: crates/hyperswitch_connectors/src/connectors/nordea.rs
// Module: hyperswitch_connectors

pub fn generate_digest_from_request(&self, payload: &RequestContent) -> String


// Function: iso_4217
// File: crates/common_enums/src/enums.rs
// Module: common_enums

pub fn iso_4217(self) -> &'static str


// Function: update_customer_payment_method
// File: crates/router/src/core/payment_methods/cards.rs
// Module: router

pub fn update_customer_payment_method(
    state: routes::SessionState,
    merchant_context: domain::MerchantContext,
    req: api::PaymentMethodUpdate,
    payment_method_id: &str,
) -> errors::RouterResponse<api::PaymentMethodResponse>


// Struct: MandateCardDetails
// File: crates/api_models/src/mandates.rs
// Module: api_models
// Implementations: 0

pub struct MandateCardDetails


// Struct: ExternalAuthentication
// File: crates/router/src/core/unified_authentication_service/types.rs
// Module: router
// Implementations: 0

pub struct ExternalAuthentication


// Struct: ReconUpdateMerchantRequest
// File: crates/api_models/src/recon.rs
// Module: api_models
// Implementations: 0

pub struct ReconUpdateMerchantRequest


// Function: get_card_from_hs_locker
// File: crates/router/src/core/payment_methods/cards.rs
// Module: router

pub fn get_card_from_hs_locker<'a>(
    state: &'a routes::SessionState,
    customer_id: &id_type::CustomerId,
    merchant_id: &id_type::MerchantId,
    card_reference: &'a str,
    locker_choice: api_enums::LockerChoice,
) -> errors::CustomResult<Card, errors::VaultError>


// Function: new
// File: crates/hyperswitch_connectors/src/connectors/paytm.rs
// Module: hyperswitch_connectors

pub fn new() -> &'static Self


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

impl api::RefundSync for for Jpmorgan


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

// Public submodules:
pub mod api;
pub mod authentication;
pub mod connector_transformers;
pub mod domain;
pub mod fraud_check;
pub mod payment_methods;
pub mod pm_auth;
pub mod storage;
pub mod transformers;

// Public exports:
pub use api_models::{enums::Connector, mandates};
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
pub use common_utils::{pii, pii::Email, request::RequestContent, types::MinorUnit};
pub use hyperswitch_domain_models::router_data_v2::FrmFlowData;
pub use hyperswitch_domain_models::{
    payment_address::PaymentAddress,
    router_data::{
        AccessToken, AccessTokenAuthenticationResponse, AdditionalPaymentMethodConnectorResponse,
        ConnectorAuthType, ConnectorResponseData, ErrorResponse, GooglePayPaymentMethodDetails,
        GooglePayPredecryptDataInternal, L2L3Data, PaymentMethodBalance, PaymentMethodToken,
        RecurringMandatePaymentData, RouterData,
    },
    router_data_v2::{
        AccessTokenFlowData, AuthenticationTokenFlowData, DisputesFlowData,
        ExternalAuthenticationFlowData, FilesFlowData, MandateRevokeFlowData, PaymentFlowData,
        RefundFlowData, RouterDataV2, UasFlowData, WebhookSourceVerifyData,
    },
    router_request_types::{
        revenue_recovery::{
            BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest,
            InvoiceRecordBackRequest,
        },
        unified_authentication_service::{
            UasAuthenticationRequestData, UasAuthenticationResponseData,
            UasConfirmationRequestData, UasPostAuthenticationRequestData,
            UasPreAuthenticationRequestData,
        },
        AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData,
        AuthorizeSessionTokenData, BrowserInformation, ChargeRefunds, ChargeRefundsOptions,
        CompleteAuthorizeData, CompleteAuthorizeRedirectResponse, ConnectorCustomerData,
        CreateOrderRequestData, DefendDisputeRequestData, DestinationChargeRefund,
        DirectChargeRefund, DisputeSyncData, ExternalVaultProxyPaymentsData,
        FetchDisputesRequestData, MandateRevokeRequestData, MultipleCaptureRequestData,
        PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData,
        PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData,
        PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData,
        PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData,
        PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData,
        PaymentsUpdateMetadataData, RefundsData, ResponseId, RetrieveFileRequestData,
        SdkPaymentsSessionUpdateData, SetupMandateRequestData, SplitRefundsRequest,
        SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData, VaultRequestData,
        VerifyWebhookSourceRequestData,
    },
    router_response_types::{
        revenue_recovery::{
            BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse,
            InvoiceRecordBackResponse,
        },
        AcceptDisputeResponse, CaptureSyncResponse, DefendDisputeResponse, DisputeSyncResponse,
        FetchDisputesResponse, MandateReference, MandateRevokeResponseData, PaymentsResponseData,
        PreprocessingResponseId, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse,
        TaxCalculationResponseData, UploadFileResponse, VaultResponseData,
        VerifyWebhookSourceResponseData, VerifyWebhookStatus,
    },
};
pub use hyperswitch_domain_models::{
    router_data_v2::PayoutFlowData, router_request_types::PayoutsData,
    router_response_types::PayoutsResponseData,
};
pub use hyperswitch_interfaces::types::{
    PayoutCancelType, PayoutCreateType, PayoutEligibilityType, PayoutFulfillType, PayoutQuoteType,
    PayoutRecipientAccountType, PayoutRecipientType, PayoutSyncType,
};
pub use hyperswitch_interfaces::{
    disputes::DisputePayload,
    types::{
        AcceptDisputeType, ConnectorCustomerType, DefendDisputeType, FetchDisputesType,
        IncrementalAuthorizationType, MandateRevokeType, PaymentsAuthorizeType,
        PaymentsBalanceType, PaymentsCaptureType, PaymentsCompleteAuthorizeType, PaymentsInitType,
        PaymentsPostCaptureVoidType, PaymentsPostProcessingType, PaymentsPostSessionTokensType,
        PaymentsPreAuthorizeType, PaymentsPreProcessingType, PaymentsSessionType, PaymentsSyncType,
        PaymentsUpdateMetadataType, PaymentsVoidType, RefreshTokenType, RefundExecuteType,
        RefundSyncType, Response, RetrieveFileType, SdkSessionUpdateType, SetupMandateType,
        SubmitEvidenceType, TokenizationType, UploadFileType, VerifyWebhookSourceType,
    },
};
pub use crate::core::payments::CustomerDetails;


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

use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
use masking::Secret;
use router::types::{self, api, storage::enums};
use test_utils::connector_auth;

use crate::utils::{self, ConnectorActions};

#[derive(Clone, Copy)]
struct BluecodeTest;
impl ConnectorActions for BluecodeTest {}
impl utils::Connector for BluecodeTest {
    fn get_data(&self) -> api::ConnectorData {
        use router::connector::Bluecode;
        utils::construct_connector_data_old(
            Box::new(Bluecode::new()),
            types::Connector::Plaid,
            api::GetToken::Connector,
            None,
        )
    }

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

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

static CONNECTOR: BluecodeTest = BluecodeTest {};

fn get_default_payment_info() -> Option<utils::PaymentInfo> {
    None
}

fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
    None
}

// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
    let response = CONNECTOR
        .authorize_payment(payment_method_details(), get_default_payment_info())
        .await
        .expect("Authorize payment response");
    assert_eq!(response.status, enums::AttemptStatus::Authorized);
}

// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
    let response = CONNECTOR
        .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
        .await
        .expect("Capture payment response");
    assert_eq!(response.status, enums::AttemptStatus::Charged);
}

// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
    let response = CONNECTOR
        .authorize_and_capture_payment(
            payment_method_details(),
            Some(types::PaymentsCaptureData {
                amount_to_capture: 50,
                ..utils::PaymentCaptureType::default().0
            }),
            get_default_payment_info(),
        )
        .await
        .expect("Capture payment response");
    assert_eq!(response.status, enums::AttemptStatus::Charged);
}

// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
    let authorize_response = CONNECTOR
        .authorize_payment(payment_method_details(), get_default_payment_info())
        .await
        .expect("Authorize payment response");
    let txn_id = utils::get_connector_transaction_id(authorize_response.response);
    let response = CONNECTOR
        .psync_retry_till_status_matches(
            enums::AttemptStatus::Authorized,
            Some(types::PaymentsSyncData {
                connector_transaction_id: types::ResponseId::ConnectorTransactionId(
                    txn_id.unwrap(),
                ),
                ..Default::default()
            }),
            get_default_payment_info(),
        )
        .await
        .expect("PSync response");
    assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}

// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
    let response = CONNECTOR
        .authorize_and_void_payment(
            payment_method_details(),
            Some(types::PaymentsCancelData {
                connector_transaction_id: String::from(""),
                cancellation_reason: Some("requested_by_customer".to_string()),
                ..Default::default()
            }),
            get_default_payment_info(),
        )
        .await
        .expect("Void payment response");
    assert_eq!(response.status, enums::AttemptStatus::Voided);
}

// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
    let response = CONNECTOR
        .capture_payment_and_refund(
            payment_method_details(),
            None,
            None,
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap().refund_status,
        enums::RefundStatus::Success,
    );
}

// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
    let response = CONNECTOR
        .capture_payment_and_refund(
            payment_method_details(),
            None,
            Some(types::RefundsData {
                refund_amount: 50,
                ..utils::PaymentRefundType::default().0
            }),
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap().refund_status,
        enums::RefundStatus::Success,
    );
}

// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
    let refund_response = CONNECTOR
        .capture_payment_and_refund(
            payment_method_details(),
            None,
            None,
            get_default_payment_info(),
        )
        .await
        .unwrap();
    let response = CONNECTOR
        .rsync_retry_till_status_matches(
            enums::RefundStatus::Success,
            refund_response.response.unwrap().connector_refund_id,
            None,
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap().refund_status,
        enums::RefundStatus::Success,
    );
}

// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
    let authorize_response = CONNECTOR
        .make_payment(payment_method_details(), get_default_payment_info())
        .await
        .unwrap();
    assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}

// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
    let authorize_response = CONNECTOR
        .make_payment(payment_method_details(), get_default_payment_info())
        .await
        .unwrap();
    assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
    let txn_id = utils::get_connector_transaction_id(authorize_response.response);
    assert_ne!(txn_id, None, "Empty connector transaction id");
    let response = CONNECTOR
        .psync_retry_till_status_matches(
            enums::AttemptStatus::Charged,
            Some(types::PaymentsSyncData {
                connector_transaction_id: types::ResponseId::ConnectorTransactionId(
                    txn_id.unwrap(),
                ),
                capture_method: Some(enums::CaptureMethod::Automatic),
                ..Default::default()
            }),
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(response.status, enums::AttemptStatus::Charged,);
}

// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
    let response = CONNECTOR
        .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap().refund_status,
        enums::RefundStatus::Success,
    );
}

// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
    let refund_response = CONNECTOR
        .make_payment_and_refund(
            payment_method_details(),
            Some(types::RefundsData {
                refund_amount: 50,
                ..utils::PaymentRefundType::default().0
            }),
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        refund_response.response.unwrap().refund_status,
        enums::RefundStatus::Success,
    );
}

// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
    CONNECTOR
        .make_payment_and_multiple_refund(
            payment_method_details(),
            Some(types::RefundsData {
                refund_amount: 50,
                ..utils::PaymentRefundType::default().0
            }),
            get_default_payment_info(),
        )
        .await;
}

// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
    let refund_response = CONNECTOR
        .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
        .await
        .unwrap();
    let response = CONNECTOR
        .rsync_retry_till_status_matches(
            enums::RefundStatus::Success,
            refund_response.response.unwrap().connector_refund_id,
            None,
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap().refund_status,
        enums::RefundStatus::Success,
    );
}

// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
    let response = CONNECTOR
        .make_payment(
            Some(types::PaymentsAuthorizeData {
                payment_method_data: PaymentMethodData::Card(Card {
                    card_cvc: Secret::new("12345".to_string()),
                    ..utils::CCardType::default().0
                }),
                ..utils::PaymentAuthorizeType::default().0
            }),
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap_err().message,
        "Your card's security code is invalid.".to_string(),
    );
}

// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
    let response = CONNECTOR
        .make_payment(
            Some(types::PaymentsAuthorizeData {
                payment_method_data: PaymentMethodData::Card(Card {
                    card_exp_month: Secret::new("20".to_string()),
                    ..utils::CCardType::default().0
                }),
                ..utils::PaymentAuthorizeType::default().0
            }),
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap_err().message,
        "Your card's expiration month is invalid.".to_string(),
    );
}

// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
    let response = CONNECTOR
        .make_payment(
            Some(types::PaymentsAuthorizeData {
                payment_method_data: PaymentMethodData::Card(Card {
                    card_exp_year: Secret::new("2000".to_string()),
                    ..utils::CCardType::default().0
                }),
                ..utils::PaymentAuthorizeType::default().0
            }),
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap_err().message,
        "Your card's expiration year is invalid.".to_string(),
    );
}

// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
    let authorize_response = CONNECTOR
        .make_payment(payment_method_details(), get_default_payment_info())
        .await
        .unwrap();
    assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
    let txn_id = utils::get_connector_transaction_id(authorize_response.response);
    assert_ne!(txn_id, None, "Empty connector transaction id");
    let void_response = CONNECTOR
        .void_payment(txn_id.unwrap(), None, get_default_payment_info())
        .await
        .unwrap();
    assert_eq!(
        void_response.response.unwrap_err().message,
        "You cannot cancel this PaymentIntent because it has a status of succeeded."
    );
}

// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
    let capture_response = CONNECTOR
        .capture_payment("123456789".to_string(), None, get_default_payment_info())
        .await
        .unwrap();
    assert_eq!(
        capture_response.response.unwrap_err().message,
        String::from("No such payment_intent: '123456789'")
    );
}

// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
    let response = CONNECTOR
        .make_payment_and_refund(
            payment_method_details(),
            Some(types::RefundsData {
                refund_amount: 150,
                ..utils::PaymentRefundType::default().0
            }),
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap_err().message,
        "Refund amount (₹1.50) is greater than charge amount (₹1.00)",
    );
}

// Connector dependent test cases goes here

// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests


// Implementation: impl TransactionType
// File: crates/common_enums/src/enums.rs
// Module: common_enums
// Methods: 1 total (1 public)

impl TransactionType


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

pub struct CheckoutRequest


// Function: get_encrypted_google_pay_payment_data_mandatory
// File: crates/common_types/src/payments.rs
// Module: common_types

// Documentation: Get the encrypted Google Pay payment data, returning an error if it does not exist

pub fn get_encrypted_google_pay_payment_data_mandatory(
        &self,
    ) -> Result<&GpayEcryptedTokenizationData, errors::ValidationError>


// Function: get_id
// File: crates/diesel_models/src/payment_method.rs
// Module: diesel_models

pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId


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

impl api::MandateSetup for for Nmi


// Function: get_card
// File: crates/hyperswitch_domain_models/src/vault.rs
// Module: hyperswitch_domain_models

pub fn get_card(&self) -> Option<&payment_methods::CardDetail>


// Function: from_predefined_roles
// File: crates/router/src/services/authorization/roles.rs
// Module: router

pub fn from_predefined_roles(role_id: &str) -> Option<Self>


// Function: generic_filter
// File: crates/diesel_models/src/query/generics.rs
// Module: diesel_models

pub fn generic_filter<T, P, O, R>(
    conn: &PgPooledConn,
    predicate: P,
    limit: Option<i64>,
    offset: Option<i64>,
    order: Option<O>,
) -> StorageResult<Vec<R>>
where
    T: HasTable<Table = T> + Table + BoxedDsl<'static, Pg> + GetPrimaryKey + 'static,
    IntoBoxed<'static, T, Pg>: FilterDsl<P, Output = IntoBoxed<'static, T, Pg>>
        + FilterDsl<IsNotNull<T::PK>, Output = IntoBoxed<'static, T, Pg>>
        + LimitDsl<Output = IntoBoxed<'static, T, Pg>>
        + OffsetDsl<Output = IntoBoxed<'static, T, Pg>>
        + OrderDsl<O, Output = IntoBoxed<'static, T, Pg>>
        + LoadQuery<'static, PgConnection, R>
        + QueryFragment<Pg>
        + Send,
    O: Expression,
    R: Send + 'static,


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

impl RoutingType


// Function: assertion
// File: crates/euclid/src/dssa/types.rs
// Module: euclid

pub fn assertion(value: &'a dir::DirValue, metadata: &'a Metadata) -> Self


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

impl common_utils::events::ApiEventMetric for for RoutingEvaluateRequest


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

pub struct AuthEventMetricsBucketValue


// Struct: StripeConnectRecipientCreateRequest
// File: crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct StripeConnectRecipientCreateRequest


impl
    ForeignFrom<
        &hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptFeatureMetadata,
    > for api_models::payments::PaymentAttemptFeatureMetadata
{
    fn foreign_from(
        feature_metadata: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptFeatureMetadata,
    ) -> Self {
        let revenue_recovery = feature_metadata.revenue_recovery.as_ref().map(|recovery| {
            api_models::payments::PaymentAttemptRevenueRecoveryData {
                attempt_triggered_by: recovery.attempt_triggered_by,
                charge_id: recovery.charge_id.clone(),
            }
        });
        Self { revenue_recovery }
    }
}

#[cfg(feature = "v2")]
impl ForeignFrom<&diesel_models::types::FeatureMetadata> for api_models::payments::FeatureMetadata {
    fn foreign_from(feature_metadata: &diesel_models::types::FeatureMetadata) -> Self {
        let revenue_recovery = feature_metadata
            .payment_revenue_recovery_metadata
            .as_ref()
            .map(|payment_revenue_recovery_metadata| {
                api_models::payments::PaymentRevenueRecoveryMetadata {
                    total_retry_count: payment_revenue_recovery_metadata.total_retry_count,
                    payment_connector_transmission: Some(
                        payment_revenue_recovery_metadata.payment_connector_transmission,
                    ),
                    connector: payment_revenue_recovery_metadata.connector,
                    billing_connector_id: payment_revenue_recovery_metadata
                        .billing_connector_id
                        .clone(),
                    active_attempt_payment_connector_id: payment_revenue_recovery_metadata
                        .active_attempt_payment_connector_id
                        .clone(),
                    payment_method_type: payment_revenue_recovery_metadata.payment_method_type,
                    payment_method_subtype: payment_revenue_recovery_metadata
                        .payment_method_subtype,
                    billing_connector_payment_details:
                        api_models::payments::BillingConnectorPaymentDetails::foreign_from(
                            &payment_revenue_recovery_metadata.billing_connector_payment_details,
                        ),
                    invoice_next_billing_time: payment_revenue_recovery_metadata
                        .invoice_next_billing_time,
                        billing_connector_payment_method_details:payment_revenue_recovery_metadata
                        .billing_connector_payment_method_details.as_ref().map(api_models::payments::BillingConnectorPaymentMethodDetails::foreign_from),
                    first_payment_attempt_network_advice_code: payment_revenue_recovery_metadata
                        .first_payment_attempt_network_advice_code
                        .clone(),
                    first_payment_attempt_network_decline_code: payment_revenue_recovery_metadata
                        .first_payment_attempt_network_decline_code
                        .clone(),
                    first_payment_attempt_pg_error_code: payment_revenue_recovery_metadata
                        .first_payment_attempt_pg_error_code
                        .clone(),
                    invoice_billing_started_at_time: payment_revenue_recovery_metadata
                        .invoice_billing_started_at_time,
                }
            });
        let apple_pay_details = feature_metadata
            .apple_pay_recurring_details
            .clone()
            .map(api_models::payments::ApplePayRecurringDetails::foreign_from);
        let redirect_res = feature_metadata
            .redirect_response
            .clone()
            .map(api_models::payments::RedirectResponse::foreign_from);
        Self {
            revenue_recovery,
            apple_pay_recurring_details: apple_pay_details,
            redirect_response: redirect_res,
            search_tags: feature_metadata.search_tags.clone(),
        }
    }
}

#[cfg(feature = "v2")]
impl ForeignFrom<hyperswitch_domain_models::payments::AmountDetails>
    for api_models::payments::AmountDetailsResponse
{
    fn foreign_from(amount_details: hyperswitch_domain_models::payments::AmountDetails) -> Self {
        Self {
            order_amount: amount_details.order_amount,
            currency: amount_details.currency,
            shipping_cost: amount_details.shipping_cost,
            order_tax_amount: amount_details.tax_details.and_then(|tax_details| {
                tax_details.default.map(|default| default.order_tax_amount)
            }),
            external_tax_calculation: amount_details.skip_external_tax_calculation,
            surcharge_calculation: amount_details.skip_surcharge_calculation,
            surcharge_amount: amount_details.surcharge_amount,
            tax_on_surcharge: amount_details.tax_on_surcharge,
        }
    }
}

#[cfg(feature = "v2")]
impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest>
    for diesel_models::PaymentLinkConfigRequestForPayments
{
    fn foreign_from(config: api_models::admin::PaymentLinkConfigRequest) -> Self {
        Self {
            theme: config.theme,
            logo: config.logo,
            seller_name: config.seller_name,
            sdk_layout: config.sdk_layout,
            display_sdk_only: config.display_sdk_only,
            enabled_saved_payment_method: config.enabled_saved_payment_method,
            hide_card_nickname_field: config.hide_card_nickname_field,
            show_card_form_by_default: config.show_card_form_by_default,
            details_layout: config.details_layout,
            transaction_details: config.transaction_details.map(|transaction_details| {
                transaction_details
                    .iter()
                    .map(|details| {
                        diesel_models::PaymentLinkTransactionDetails::foreign_from(details.clone())
                    })
                    .collect()
            }),
            background_image: config.background_image.map(|background_image| {
                diesel_models::business_profile::PaymentLinkBackgroundImageConfig::foreign_from(
                    background_image.clone(),
                )
            }),
            payment_button_text: config.payment_button_text,
            custom_message_for_card_terms: config.custom_message_for_card_terms,
            payment_button_colour: config.payment_button_colour,
            skip_status_screen: config.skip_status_screen,
            background_colour: config.background_colour,
            payment_button_text_colour: config.payment_button_text_colour,
            sdk_ui_rules: config.sdk_ui_rules,
            payment_link_ui_rules: config.payment_link_ui_rules,
            enable_button_only_on_form_ready: config.enable_button_only_on_form_ready,
            payment_form_header_text: config.payment_form_header_text,
            payment_form_label_type: config.payment_form_label_type,
            show_card_terms: config.show_card_terms,
            is_setup_mandate_flow: config.is_setup_mandate_flow,
            color_icon_card_cvc_error: config.color_icon_card_cvc_error,
        }
    }
}

#[cfg(feature = "v2")]
impl ForeignFrom<api_models::admin::PaymentLinkTransactionDetails>
    for diesel_models::PaymentLinkTransactionDetails
{
    fn foreign_from(from: api_models::admin::PaymentLinkTransactionDetails) -> Self {
        Self {
            key: from.key,
            value: from.value,
            ui_configuration: from
                .ui_configuration
                .map(diesel_models::TransactionDetailsUiConfiguration::foreign_from),
        }
    }
}

#[cfg(feature = "v2")]
impl ForeignFrom<api_models::admin::TransactionDetailsUiConfiguration>
    for diesel_models::TransactionDetailsUiConfiguration
{
    fn foreign_from(from: api_models::admin::TransactionDetailsUiConfiguration) -> Self {
        Self {
            position: from.position,
            is_key_bold: from.is_key_bold,
            is_value_bold: from.is_value_bold,
        }
    }
}

#[cfg(feature = "v2")]
impl ForeignFrom<diesel_models::PaymentLinkConfigRequestForPayments>
    for api_models::admin::PaymentLinkConfigRequest
{
    fn foreign_from(config: diesel_models::PaymentLinkConfigRequestForPayments) -> Self {
        Self {
            theme: config.theme,
            logo: config.logo,
            seller_name: config.seller_name,
            sdk_layout: config.sdk_layout,
            display_sdk_only: config.display_sdk_only,
            enabled_saved_payment_method: config.enabled_saved_payment_method,
            hide_card_nickname_field: config.hide_card_nickname_field,
            show_card_form_by_default: config.show_card_form_by_default,
            details_layout: config.details_layout,
            transaction_details: config.transaction_details.map(|transaction_details| {
                transaction_details
                    .iter()
                    .map(|details| {
                        api_models::admin::PaymentLinkTransactionDetails::foreign_from(
                            details.clone(),
                        )
                    })
                    .collect()
            }),
            background_image: config.background_image.map(|background_image| {
                api_models::admin::PaymentLinkBackgroundImageConfig::foreign_from(
                    background_image.clone(),
                )
            }),
            payment_button_text: config.payment_button_text,
            custom_message_for_card_terms: config.custom_message_for_card_terms,
            payment_button_colour: config.payment_button_colour,
            skip_status_screen: config.skip_status_screen,
            background_colour: config.background_colour,
            payment_button_text_colour: config.payment_button_text_colour,
            sdk_ui_rules: config.sdk_ui_rules,
            payment_link_ui_rules: config.payment_link_ui_rules,
            enable_button_only_on_form_ready: config.enable_button_only_on_form_ready,
            payment_form_header_text: config.payment_form_header_text,
            payment_form_label_type: config.payment_form_label_type,
            show_card_terms: config.show_card_terms,
            is_setup_mandate_flow: config.is_setup_mandate_flow,
            color_icon_card_cvc_error: config.color_icon_card_cvc_error,
        }
    }
}

#[cfg(feature = "v2")]
impl ForeignFrom<diesel_models::PaymentLinkTransactionDetails>
    for api_models::admin::PaymentLinkTransactionDetails
{
    fn foreign_from(from: diesel_models::PaymentLinkTransactionDetails) -> Self {
        Self {
            key: from.key,
            value: from.value,
            ui_configuration: from
                .ui_configuration
                .map(api_models::admin::TransactionDetailsUiConfiguration::foreign_from),
        }
    }
}

#[cfg(feature = "v2")]
impl ForeignFrom<diesel_models::TransactionDetailsUiConfiguration>
    for api_models::admin::TransactionDetailsUiConfiguration
{
    fn foreign_from(from: diesel_models::TransactionDetailsUiConfiguration) -> Self {
        Self {
            position: from.position,
            is_key_bold: from.is_key_bold,
            is_value_bold: from.is_value_bold,
        }
    }
}

impl ForeignFrom<DieselConnectorMandateReferenceId> for ConnectorMandateReferenceId {
    fn foreign_from(value: DieselConnectorMandateReferenceId) -> Self {
        Self::new(
            value.connector_mandate_id,
            value.payment_method_id,
            None,
            value.mandate_metadata,
            value.connector_mandate_request_reference_id,
        )
    }
}

impl ForeignFrom<ConnectorMandateReferenceId> for DieselConnectorMandateReferenceId {
    fn foreign_from(value: ConnectorMandateReferenceId) -> Self {
        Self {
            connector_mandate_id: value.get_connector_mandate_id(),
            payment_method_id: value.get_payment_method_id(),
            mandate_metadata: value.get_mandate_metadata(),
            connector_mandate_request_reference_id: value
                .get_connector_mandate_request_reference_id(),
        }
    }
}

impl ForeignFrom<DieselNetworkDetails> for NetworkDetails {
    fn foreign_from(value: DieselNetworkDetails) -> Self {
        Self {
            network_advice_code: value.network_advice_code,
        }
    }
}

impl ForeignFrom<NetworkDetails> for DieselNetworkDetails {
    fn foreign_from(value: NetworkDetails) -> Self {
        Self {
            network_advice_code: value.network_advice_code,
        }
    }
}

#[cfg(feature = "v2")]
impl ForeignFrom<diesel_models::ConnectorTokenDetails>
    for Option<api_models::payments::ConnectorTokenDetails>
{
    fn foreign_from(value: diesel_models::ConnectorTokenDetails) -> Self {
        let connector_token_request_reference_id =
            value.connector_token_request_reference_id.clone();
        value.connector_mandate_id.clone().map(|mandate_id| {
            api_models::payments::ConnectorTokenDetails {
                token: mandate_id,
                connector_token_request_reference_id,
            }
        })
    }
}

impl
    ForeignFrom<(
        Self,
        Option<&api_models::payments::AdditionalPaymentData>,
        Option<enums::PaymentMethod>,
    )> for Option<enums::PaymentMethodType>
{
    fn foreign_from(
        req: (
            Self,
            Option<&api_models::payments::AdditionalPaymentData>,
            Option<enums::PaymentMethod>,
        ),
    ) -> Self {
        let (payment_method_type, additional_pm_data, payment_method) = req;

        match (additional_pm_data, payment_method, payment_method_type) {
            (
                Some(api_models::payments::AdditionalPaymentData::Card(card_info)),
                Some(enums::PaymentMethod::Card),
                original_type,
            ) => {
                let bin_card_type = card_info.card_type.as_ref().and_then(|card_type_str| {
                    let normalized_type = card_type_str.trim().to_lowercase();
                    if normalized_type.is_empty() {
                        return None;
                    }
                    api_models::enums::PaymentMethodType::from_str(&normalized_type)
                        .map_err(|_| {
                            crate::logger::warn!("Invalid BIN card_type: '{}'", card_type_str);
                        })
                        .ok()
                });

                match (original_type, bin_card_type) {
                    // Override when there's a mismatch
                    (
                        Some(
                            original @ (enums::PaymentMethodType::Debit
                            | enums::PaymentMethodType::Credit),
                        ),
                        Some(bin_type),
                    ) if original != bin_type => {
                        crate::logger::info!("BIN lookup override: {} -> {}", original, bin_type);
                        bin_card_type
                    }
                    // Use BIN lookup if no original type exists
                    (None, Some(bin_type)) => {
                        crate::logger::info!(
                            "BIN lookup override: No original payment method type, using BIN result={}",
                            bin_type
                        );
                        Some(bin_type)
                    }
                    // Default
                    _ => original_type,
                }
            }
            // Skip BIN lookup for non-card payments
            _ => payment_method_type,
        }
    }
}

#[cfg(feature = "v1")]
impl From<pm_types::TokenResponse> for domain::NetworkTokenData {
    fn from(token_response: pm_types::TokenResponse) -> Self {
        Self {
            token_number: token_response.authentication_details.token,
            token_exp_month: token_response.token_details.exp_month,
            token_exp_year: token_response.token_details.exp_year,
            token_cryptogram: Some(token_response.authentication_details.cryptogram),
            card_issuer: None,
            card_network: Some(token_response.network),
            card_type: None,
            card_issuing_country: None,
            bank_code: None,
            nick_name: None,
            eci: None,
        }
    }
}
impl ForeignFrom<&hyperswitch_domain_models::router_data::ErrorResponse> for DieselNetworkDetails {
    fn foreign_from(err: &hyperswitch_domain_models::router_data::ErrorResponse) -> Self {
        Self {
            network_advice_code: err.network_advice_code.clone(),
        }
    }
}

impl ForeignFrom<common_types::three_ds_decision_rule_engine::ThreeDSDecision>
    for common_enums::AuthenticationType
{
    fn foreign_from(
        three_ds_decision: common_types::three_ds_decision_rule_engine::ThreeDSDecision,
    ) -> Self {
        match three_ds_decision {
            common_types::three_ds_decision_rule_engine::ThreeDSDecision::NoThreeDs => Self::NoThreeDs,
            common_types::three_ds_decision_rule_engine::ThreeDSDecision::ChallengeRequested
            | common_types::three_ds_decision_rule_engine::ThreeDSDecision::ChallengePreferred
            | common_types::three_ds_decision_rule_engine::ThreeDSDecision::ThreeDsExemptionRequestedTra
            | common_types::three_ds_decision_rule_engine::ThreeDSDecision::ThreeDsExemptionRequestedLowValue
            | common_types::three_ds_decision_rule_engine::ThreeDSDecision::IssuerThreeDsExemptionRequested => Self::ThreeDs,
        }
    }
}

impl ForeignFrom<common_types::three_ds_decision_rule_engine::ThreeDSDecision>
    for Option<common_enums::ScaExemptionType>
{
    fn foreign_from(
        three_ds_decision: common_types::three_ds_decision_rule_engine::ThreeDSDecision,
    ) -> Self {
        match three_ds_decision {
            common_types::three_ds_decision_rule_engine::ThreeDSDecision::ThreeDsExemptionRequestedTra => {
                Some(common_enums::ScaExemptionType::TransactionRiskAnalysis)
            }
            common_types::three_ds_decision_rule_engine::ThreeDSDecision::ThreeDsExemptionRequestedLowValue => {
                Some(common_enums::ScaExemptionType::LowValue)
            }
            common_types::three_ds_decision_rule_engine::ThreeDSDecision::NoThreeDs
            | common_types::three_ds_decision_rule_engine::ThreeDSDecision::ChallengeRequested
            | common_types::three_ds_decision_rule_engine::ThreeDSDecision::ChallengePreferred
            | common_types::three_ds_decision_rule_engine::ThreeDSDecision::IssuerThreeDsExemptionRequested => {
                None
            }
        }
    }
}


// Struct: PaytmRouterData
// File: crates/hyperswitch_connectors/src/connectors/paytm/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct PaytmRouterData<T>


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

pub fn payments_dynamic_tax_calculation(
    state: web::Data<app::AppState>,
    req: actix_web::HttpRequest,
    json_payload: web::Json<payment_types::PaymentsDynamicTaxCalculationRequest>,
    path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder


// Struct: Paypal
// File: crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct Paypal


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

impl ConnectorValidation for for Dlocal


// Function: set_response_body
// File: crates/hyperswitch_interfaces/src/events/routing_api_logs.rs
// Module: hyperswitch_interfaces

// Documentation: fn set_response_body

pub fn set_response_body<T: Serialize>(&mut self, response: &T)


// Struct: FinixPaymentsResponse
// File: crates/hyperswitch_connectors/src/connectors/finix/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct FinixPaymentsResponse


// File: crates/api_models/src/webhooks.rs
// Module: api_models
// Public functions: 6
// Public structs: 3

use common_utils::custom_serde;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;

#[cfg(feature = "payouts")]
use crate::payouts;
use crate::{disputes, enums as api_enums, mandates, payments, refunds};

#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Copy)]
#[serde(rename_all = "snake_case")]
pub enum IncomingWebhookEvent {
    /// Authorization + Capture failure
    PaymentIntentFailure,
    /// Authorization + Capture success
    PaymentIntentSuccess,
    PaymentIntentProcessing,
    PaymentIntentPartiallyFunded,
    PaymentIntentCancelled,
    PaymentIntentCancelFailure,
    PaymentIntentAuthorizationSuccess,
    PaymentIntentAuthorizationFailure,
    PaymentIntentCaptureSuccess,
    PaymentIntentCaptureFailure,
    PaymentIntentExpired,
    PaymentActionRequired,
    EventNotSupported,
    SourceChargeable,
    SourceTransactionCreated,
    RefundFailure,
    RefundSuccess,
    DisputeOpened,
    DisputeExpired,
    DisputeAccepted,
    DisputeCancelled,
    DisputeChallenged,
    // dispute has been successfully challenged by the merchant
    DisputeWon,
    // dispute has been unsuccessfully challenged
    DisputeLost,
    MandateActive,
    MandateRevoked,
    EndpointVerification,
    ExternalAuthenticationARes,
    FrmApproved,
    FrmRejected,
    #[cfg(feature = "payouts")]
    PayoutSuccess,
    #[cfg(feature = "payouts")]
    PayoutFailure,
    #[cfg(feature = "payouts")]
    PayoutProcessing,
    #[cfg(feature = "payouts")]
    PayoutCancelled,
    #[cfg(feature = "payouts")]
    PayoutCreated,
    #[cfg(feature = "payouts")]
    PayoutExpired,
    #[cfg(feature = "payouts")]
    PayoutReversed,
    #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
    RecoveryPaymentFailure,
    #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
    RecoveryPaymentSuccess,
    #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
    RecoveryPaymentPending,
    #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
    RecoveryInvoiceCancel,
    SetupWebhook,
}

impl IncomingWebhookEvent {
    /// Convert UCS event type integer to IncomingWebhookEvent
    /// Maps from proto WebhookEventType enum values to IncomingWebhookEvent variants
    pub fn from_ucs_event_type(event_type: i32) -> Self {
        match event_type {
            0 => Self::EventNotSupported,
            // Payment intent events
            1 => Self::PaymentIntentFailure,
            2 => Self::PaymentIntentSuccess,
            3 => Self::PaymentIntentProcessing,
            4 => Self::PaymentIntentPartiallyFunded,
            5 => Self::PaymentIntentCancelled,
            6 => Self::PaymentIntentCancelFailure,
            7 => Self::PaymentIntentAuthorizationSuccess,
            8 => Self::PaymentIntentAuthorizationFailure,
            9 => Self::PaymentIntentCaptureSuccess,
            10 => Self::PaymentIntentCaptureFailure,
            11 => Self::PaymentIntentExpired,
            12 => Self::PaymentActionRequired,
            // Source events
            13 => Self::SourceChargeable,
            14 => Self::SourceTransactionCreated,
            // Refund events
            15 => Self::RefundFailure,
            16 => Self::RefundSuccess,
            // Dispute events
            17 => Self::DisputeOpened,
            18 => Self::DisputeExpired,
            19 => Self::DisputeAccepted,
            20 => Self::DisputeCancelled,
            21 => Self::DisputeChallenged,
            22 => Self::DisputeWon,
            23 => Self::DisputeLost,
            // Mandate events
            24 => Self::MandateActive,
            25 => Self::MandateRevoked,
            // Miscellaneous events
            26 => Self::EndpointVerification,
            27 => Self::ExternalAuthenticationARes,
            28 => Self::FrmApproved,
            29 => Self::FrmRejected,
            // Payout events
            #[cfg(feature = "payouts")]
            30 => Self::PayoutSuccess,
            #[cfg(feature = "payouts")]
            31 => Self::PayoutFailure,
            #[cfg(feature = "payouts")]
            32 => Self::PayoutProcessing,
            #[cfg(feature = "payouts")]
            33 => Self::PayoutCancelled,
            #[cfg(feature = "payouts")]
            34 => Self::PayoutCreated,
            #[cfg(feature = "payouts")]
            35 => Self::PayoutExpired,
            #[cfg(feature = "payouts")]
            36 => Self::PayoutReversed,
            _ => Self::EventNotSupported,
        }
    }
}

pub enum WebhookFlow {
    Payment,
    #[cfg(feature = "payouts")]
    Payout,
    Refund,
    Dispute,
    Subscription,
    ReturnResponse,
    BankTransfer,
    Mandate,
    ExternalAuthentication,
    FraudCheck,
    #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
    Recovery,
    Setup,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
/// This enum tells about the affect a webhook had on an object
pub enum WebhookResponseTracker {
    #[cfg(feature = "v1")]
    Payment {
        payment_id: common_utils::id_type::PaymentId,
        status: common_enums::IntentStatus,
    },
    #[cfg(feature = "v2")]
    Payment {
        payment_id: common_utils::id_type::GlobalPaymentId,
        status: common_enums::IntentStatus,
    },
    #[cfg(feature = "payouts")]
    Payout {
        payout_id: common_utils::id_type::PayoutId,
        status: common_enums::PayoutStatus,
    },
    #[cfg(feature = "v1")]
    Refund {
        payment_id: common_utils::id_type::PaymentId,
        refund_id: String,
        status: common_enums::RefundStatus,
    },
    #[cfg(feature = "v2")]
    Refund {
        payment_id: common_utils::id_type::GlobalPaymentId,
        refund_id: String,
        status: common_enums::RefundStatus,
    },
    #[cfg(feature = "v1")]
    Dispute {
        dispute_id: String,
        payment_id: common_utils::id_type::PaymentId,
        status: common_enums::DisputeStatus,
    },
    #[cfg(feature = "v2")]
    Dispute {
        dispute_id: String,
        payment_id: common_utils::id_type::GlobalPaymentId,
        status: common_enums::DisputeStatus,
    },
    Mandate {
        mandate_id: String,
        status: common_enums::MandateStatus,
    },
    #[cfg(feature = "v1")]
    PaymentMethod {
        payment_method_id: String,
        status: common_enums::PaymentMethodStatus,
    },
    NoEffect,
    Relay {
        relay_id: common_utils::id_type::RelayId,
        status: common_enums::RelayStatus,
    },
}

impl WebhookResponseTracker {
    #[cfg(feature = "v1")]
    pub fn get_payment_id(&self) -> Option<common_utils::id_type::PaymentId> {
        match self {
            Self::Payment { payment_id, .. }
            | Self::Refund { payment_id, .. }
            | Self::Dispute { payment_id, .. } => Some(payment_id.to_owned()),
            Self::NoEffect | Self::Mandate { .. } | Self::PaymentMethod { .. } => None,
            #[cfg(feature = "payouts")]
            Self::Payout { .. } => None,
            Self::Relay { .. } => None,
        }
    }

    #[cfg(feature = "v1")]
    pub fn get_payment_method_id(&self) -> Option<String> {
        match self {
            Self::PaymentMethod {
                payment_method_id, ..
            } => Some(payment_method_id.to_owned()),
            Self::Payment { .. }
            | Self::Refund { .. }
            | Self::Dispute { .. }
            | Self::NoEffect
            | Self::Mandate { .. }
            | Self::Relay { .. } => None,
            #[cfg(feature = "payouts")]
            Self::Payout { .. } => None,
        }
    }

    #[cfg(feature = "v2")]
    pub fn get_payment_id(&self) -> Option<common_utils::id_type::GlobalPaymentId> {
        match self {
            Self::Payment { payment_id, .. }
            | Self::Refund { payment_id, .. }
            | Self::Dispute { payment_id, .. } => Some(payment_id.to_owned()),
            Self::NoEffect | Self::Mandate { .. } => None,
            #[cfg(feature = "payouts")]
            Self::Payout { .. } => None,
            Self::Relay { .. } => None,
        }
    }
}

impl From<IncomingWebhookEvent> for WebhookFlow {
    fn from(evt: IncomingWebhookEvent) -> Self {
        match evt {
            IncomingWebhookEvent::PaymentIntentFailure
            | IncomingWebhookEvent::PaymentIntentSuccess
            | IncomingWebhookEvent::PaymentIntentProcessing
            | IncomingWebhookEvent::PaymentActionRequired
            | IncomingWebhookEvent::PaymentIntentPartiallyFunded
            | IncomingWebhookEvent::PaymentIntentCancelled
            | IncomingWebhookEvent::PaymentIntentCancelFailure
            | IncomingWebhookEvent::PaymentIntentAuthorizationSuccess
            | IncomingWebhookEvent::PaymentIntentAuthorizationFailure
            | IncomingWebhookEvent::PaymentIntentCaptureSuccess
            | IncomingWebhookEvent::PaymentIntentCaptureFailure
            | IncomingWebhookEvent::PaymentIntentExpired => Self::Payment,
            IncomingWebhookEvent::EventNotSupported => Self::ReturnResponse,
            IncomingWebhookEvent::RefundSuccess | IncomingWebhookEvent::RefundFailure => {
                Self::Refund
            }
            IncomingWebhookEvent::MandateActive | IncomingWebhookEvent::MandateRevoked => {
                Self::Mandate
            }
            IncomingWebhookEvent::DisputeOpened
            | IncomingWebhookEvent::DisputeAccepted
            | IncomingWebhookEvent::DisputeExpired
            | IncomingWebhookEvent::DisputeCancelled
            | IncomingWebhookEvent::DisputeChallenged
            | IncomingWebhookEvent::DisputeWon
            | IncomingWebhookEvent::DisputeLost => Self::Dispute,
            IncomingWebhookEvent::EndpointVerification => Self::ReturnResponse,
            IncomingWebhookEvent::SourceChargeable
            | IncomingWebhookEvent::SourceTransactionCreated => Self::BankTransfer,
            IncomingWebhookEvent::ExternalAuthenticationARes => Self::ExternalAuthentication,
            IncomingWebhookEvent::FrmApproved | IncomingWebhookEvent::FrmRejected => {
                Self::FraudCheck
            }
            #[cfg(feature = "payouts")]
            IncomingWebhookEvent::PayoutSuccess
            | IncomingWebhookEvent::PayoutFailure
            | IncomingWebhookEvent::PayoutProcessing
            | IncomingWebhookEvent::PayoutCancelled
            | IncomingWebhookEvent::PayoutCreated
            | IncomingWebhookEvent::PayoutExpired
            | IncomingWebhookEvent::PayoutReversed => Self::Payout,
            #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
            IncomingWebhookEvent::RecoveryInvoiceCancel
            | IncomingWebhookEvent::RecoveryPaymentFailure
            | IncomingWebhookEvent::RecoveryPaymentPending
            | IncomingWebhookEvent::RecoveryPaymentSuccess => Self::Recovery,
            IncomingWebhookEvent::SetupWebhook => Self::Setup,
        }
    }
}

pub type MerchantWebhookConfig = std::collections::HashSet<IncomingWebhookEvent>;

#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub enum RefundIdType {
    RefundId(String),
    ConnectorRefundId(String),
}

#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub enum MandateIdType {
    MandateId(String),
    ConnectorMandateId(String),
}

#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub enum AuthenticationIdType {
    AuthenticationId(common_utils::id_type::AuthenticationId),
    ConnectorAuthenticationId(String),
}

#[cfg(feature = "payouts")]
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub enum PayoutIdType {
    PayoutAttemptId(String),
    ConnectorPayoutId(String),
}

#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub enum ObjectReferenceId {
    PaymentId(payments::PaymentIdType),
    RefundId(RefundIdType),
    MandateId(MandateIdType),
    ExternalAuthenticationID(AuthenticationIdType),
    #[cfg(feature = "payouts")]
    PayoutId(PayoutIdType),
    #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
    InvoiceId(InvoiceIdType),
}

#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub enum InvoiceIdType {
    ConnectorInvoiceId(String),
}

#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
impl ObjectReferenceId {
    pub fn get_connector_transaction_id_as_string(
        self,
    ) -> Result<String, common_utils::errors::ValidationError> {
        match self {
            Self::PaymentId(
                payments::PaymentIdType::ConnectorTransactionId(id)
            ) => Ok(id),
            Self::PaymentId(_)=>Err(
                common_utils::errors::ValidationError::IncorrectValueProvided {
                    field_name: "ConnectorTransactionId variant of PaymentId is required but received otherr variant",
                },
            ),
            Self::RefundId(_) => Err(
                common_utils::errors::ValidationError::IncorrectValueProvided {
                    field_name: "PaymentId is required but received RefundId",
                },
            ),
            Self::MandateId(_) => Err(
                common_utils::errors::ValidationError::IncorrectValueProvided {
                    field_name: "PaymentId is required but received MandateId",
                },
            ),
            Self::ExternalAuthenticationID(_) => Err(
                common_utils::errors::ValidationError::IncorrectValueProvided {
                    field_name: "PaymentId is required but received ExternalAuthenticationID",
                },
            ),
            #[cfg(feature = "payouts")]
            Self::PayoutId(_) => Err(
                common_utils::errors::ValidationError::IncorrectValueProvided {
                    field_name: "PaymentId is required but received PayoutId",
                },
            ),
            Self::InvoiceId(_) => Err(
                common_utils::errors::ValidationError::IncorrectValueProvided {
                    field_name: "PaymentId is required but received InvoiceId",
                },
            )
        }
    }
}

pub struct IncomingWebhookDetails {
    pub object_reference_id: ObjectReferenceId,
    pub resource_object: Vec<u8>,
}

#[derive(Debug, Serialize, ToSchema)]
pub struct OutgoingWebhook {
    /// The merchant id of the merchant
    #[schema(value_type = String)]
    pub merchant_id: common_utils::id_type::MerchantId,

    /// The unique event id for each webhook
    pub event_id: String,

    /// The type of event this webhook corresponds to.
    #[schema(value_type = EventType)]
    pub event_type: api_enums::EventType,

    /// This is specific to the flow, for ex: it will be `PaymentsResponse` for payments flow
    pub content: OutgoingWebhookContent,

    /// The time at which webhook was sent
    #[serde(default, with = "custom_serde::iso8601")]
    pub timestamp: PrimitiveDateTime,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
#[serde(tag = "type", content = "object", rename_all = "snake_case")]
#[cfg(feature = "v1")]
pub enum OutgoingWebhookContent {
    #[schema(value_type = PaymentsResponse, title = "PaymentsResponse")]
    PaymentDetails(Box<payments::PaymentsResponse>),
    #[schema(value_type = RefundResponse, title = "RefundResponse")]
    RefundDetails(Box<refunds::RefundResponse>),
    #[schema(value_type = DisputeResponse, title = "DisputeResponse")]
    DisputeDetails(Box<disputes::DisputeResponse>),
    #[schema(value_type = MandateResponse, title = "MandateResponse")]
    MandateDetails(Box<mandates::MandateResponse>),
    #[cfg(feature = "payouts")]
    #[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")]
    PayoutDetails(Box<payouts::PayoutCreateResponse>),
}

#[derive(Debug, Clone, Serialize, ToSchema)]
#[serde(tag = "type", content = "object", rename_all = "snake_case")]
#[cfg(feature = "v2")]
pub enum OutgoingWebhookContent {
    #[schema(value_type = PaymentsResponse, title = "PaymentsResponse")]
    PaymentDetails(Box<payments::PaymentsResponse>),
    #[schema(value_type = RefundResponse, title = "RefundResponse")]
    RefundDetails(Box<refunds::RefundResponse>),
    #[schema(value_type = DisputeResponse, title = "DisputeResponse")]
    DisputeDetails(Box<disputes::DisputeResponse>),
    #[schema(value_type = MandateResponse, title = "MandateResponse")]
    MandateDetails(Box<mandates::MandateResponse>),
    #[cfg(feature = "payouts")]
    #[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")]
    PayoutDetails(Box<payouts::PayoutCreateResponse>),
}

#[derive(Debug, Clone, Serialize)]
pub struct ConnectorWebhookSecrets {
    pub secret: Vec<u8>,
    pub additional_secret: Option<masking::Secret<String>>,
}

#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl IncomingWebhookEvent {
    pub fn is_recovery_transaction_event(&self) -> bool {
        matches!(
            self,
            Self::RecoveryPaymentFailure
                | Self::RecoveryPaymentSuccess
                | Self::RecoveryPaymentPending
        )
    }
}


// File: crates/masking/src/strategy.rs
// Module: masking

use core::fmt;

/// Debugging trait which is specialized for handling secret values
pub trait Strategy<T> {
    /// Format information about the secret's type.
    fn fmt(value: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result;
}

/// Debug with type
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum WithType {}

impl<T> Strategy<T> for WithType {
    fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.write_str("*** ")?;
        fmt.write_str(std::any::type_name::<T>())?;
        fmt.write_str(" ***")
    }
}

/// Debug without type
pub enum WithoutType {}

impl<T> Strategy<T> for WithoutType {
    fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.write_str("*** ***")
    }
}


// Function: new
// File: crates/api_models/src/admin.rs
// Module: api_models

pub fn new(
        connector_label: String,
        merchant_connector_id: id_type::MerchantConnectorAccountId,
    ) -> Self


// Function: create_de_euclid_routing_algo
// File: crates/router/src/core/payments/routing/utils.rs
// Module: router

pub fn create_de_euclid_routing_algo(
    state: &SessionState,
    routing_request: &RoutingRule,
) -> RoutingResult<String>